QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,297,775
16,467,154
How to properly figure out all possible "long entries" made based on the OHLC data and upper bound and lower bound price series? Pandas related
<p>Say you have a Pandas <code>df</code> that contains the OHLC (short for the Open, High, Low, Close) prices of a particular financial asset.</p> <p>Also, you have two other Pandas dataframes to consider, one of them called <code>upper_bound</code> that contains a series of prices which are above the close price, and the other called <code>lower_bound</code> that contains a series of prices which are below the close price.</p> <p>All the necessary data can be found <a href="https://github.com/noahverner1995/Data-Dump-Folder/blob/main/StackOverFlowQuestions/All_possible_long_entrries_problem.py" rel="nofollow noreferrer">here</a>.</p> <p>All of these Pandas dataframes share the same index, and this is how it would look like once plotted everything in a single candlestick chart (<em>The <strong>pink trend</strong> represents the</em> <code>upper_bound</code><em>, while the <strong>white trend</strong> represents the</em> <code>lower_bound</code>):</p> <p><a href="https://i.sstatic.net/MR418.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MR418.png" alt="APT/USDT chart" /></a></p> <p>You need to:</p> <ol> <li>Find out the index value at which the low price from the <code>df</code> is lower or equal to the lower bound value.</li> <li>Find out the next index value at which the high price from the <code>df</code> is greater or equal to the upper bound value.</li> <li>Estimate the percentage change from the first index value of the lower bound to the second index value of the upper bound.</li> <li>Append that percentage change, that first index value, and that second index value to another dataframe called <code>possible_long_entries</code></li> <li>Repeat this process until there's no more data to analyze</li> </ol> <h1>My (possibly bad) approach</h1> <p>I wrote the following Python code in order to solve this problem:</p> <pre><code># Find all the possible long entries that could have been made considering the information above possible_long_entries = pd.DataFrame(columns=['Actual Percentage Change', 'Start Index', 'End Index']) i=0 while i &lt; (len(df)-1): if df['Low Price'][i] &lt;= lower_bound[i]: lower_index = i j = i + 1 while j &lt; (len(df)-1): if df['High Price'][j] &gt;= upper_bound[j]: upper_index = j percentage_change = (upper_bound.iat[upper_index] - lower_bound.iat[lower_index]) / lower_bound.iat[lower_index] * 100 possible_long_entries = possible_long_entries.append({'Actual Percentage Change':percentage_change,'Start Index': lower_index, 'End Index':upper_index},ignore_index=True) i = j + 1 print(i) break else: j += 1 else: i += 1 </code></pre> <p>The problem with this code is the fact that it <em>kinda</em> enters in an infinite loop when <code>i</code> equals to <strong>407</strong>, not sure why. After I manually stopped the execution, I checked out the <code>possible_long_entries</code> and these were data that it managed to extract:</p> <pre><code>final_dict = {'Actual Percentage Change': {0: 3.694220620875114, 1: 2.4230128905797654, 2: 2.1254433367789014, 3: 2.9138599524587625, 4: 3.177040784650736, 5: 1.0867515559002843, 6: 0.08567173253550972, 7: 0.19999498819328332, 8: 3.069342080456284, 9: 1.467935498997383, 10: -0.6867540630203672, 11: 2.019389675661748, 12: 3.1057216745256353, 13: 1.758775161828502}, 'Start Index': {0: 17.0, 1: 50.0, 2: 89.0, 3: 106.0, 4: 113.0, 5: 132.0, 6: 169.0, 7: 193.0, 8: 237.0, 9: 271.0, 10: 285.0, 11: 345.0, 12: 374.0, 13: 401.0}, 'End Index': {0: 38.0, 1: 62.0, 2: 101.0, 3: 109.0, 4: 118.0, 5: 146.0, 6: 185.0, 7: 206.0, 8: 251.0, 9: 281.0, 10: 322.0, 11: 361.0, 12: 396.0, 13: 406.0}} possible_long_entries = pd.DataFrame(final_dict) </code></pre> <p>May I get some help here please?</p>
<python><pandas><dataframe><data-science><back-testing>
2023-01-31 13:17:50
1
875
NoahVerner
75,297,701
13,023,224
Remove and replace multiple commas in string
<p>I have this dataset</p> <pre><code>df = pd.DataFrame({'name':{0: 'John,Smith', 1: 'Peter,Blue', 2:'Larry,One,Stacy,Orange' , 3:'Joe,Good' , 4:'Pete,High,Anne,Green'}}) </code></pre> <p>yielding:</p> <pre><code>name 0 John,Smith 1 Peter,Blue 2 Larry,One,Stacy,Orange 3 Joe,Good 4 Pete,High,Anne,Green </code></pre> <p>I would like to:</p> <ul> <li>remove commas (replace them by one space)</li> <li>wherever I have 2 persons in one cell, insert the &quot;&amp;&quot;symbol after the first person family name and before the second person name.</li> </ul> <p>Desired output:</p> <pre><code>name 0 John Smith 1 Peter Blue 2 Larry One &amp; Stacy Orange 3 Joe Good 4 Pete High &amp; Anne Green </code></pre> <p>Tried this code below, but it simply removes commas. I could not find how to insert the &quot;&amp;&quot;symbol in the same code.</p> <pre><code>df['name']= df['name'].str.replace(r',', '', regex=True) </code></pre> <p>Disclaimer : all names in this table are fictitious. No identification with actual persons (living or deceased)is intended or should be inferred.</p>
<python><pandas><replace>
2023-01-31 13:11:34
4
571
josepmaria
75,297,565
4,783,029
How to disable iPython Notebook's (ipynb) cell output line wrapping in VSCode?
<p>I use PySpark in VSCode <code>ipynb</code> documents. The text lines in the cells <strong>output</strong> are wrapped and it is not possible to understand them correctly.</p> <p><a href="https://i.sstatic.net/Z0pz2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Z0pz2.png" alt="enter image description here" /></a></p> <p>For code cell <kbd>Alt</kbd>+<kbd>Z</kbd> keybinding toggles between wrapped and non-wrapped modes but it does not work for code output.</p> <p>In Jupyter Notebooks (in the browser) this trick works: <a href="https://stackoverflow.com/a/63476260/4783029">https://stackoverflow.com/a/63476260/4783029</a> But in VSCode it does not.</p> <p><strong>Question:</strong><br /> How to get unwrapped output in VSCode cell <strong>output</strong>?<br /> Is there any option or keybinding?</p>
<python><visual-studio-code><jupyter-notebook>
2023-01-31 13:01:10
0
5,750
GegznaV
75,297,555
9,281,109
Is there anyway to use kubernetes pods with a shared resource NFS to save chunks of files as they come?
<p>I have encountered in this issue for some days and I cannot get along with it with this configuration. So basically the issue is to open a request stream with octet-stream and as I get the file write it down to a file in filesystem, this works perfectly locally and hosted on Debian Linux servers, but there are some issues hosting it in Kubernetes where I have only one pod (I don't have other pods so that load balancer can cause issues) when I start creating and appending the bytes to file that file keeps the size 0 at all times sometimes it does upload at the end sometimes not, but it's like it is keeping everything in the memory or something since when I pause the file and resume again the server finds the size of the file is 0 and starts again. There are other issues with this too, like uploading more than one file that are related to each other depending on the business logic.</p> <p>This is some small function that I initialize the empty files</p> <pre><code>def _initialize_file(uid: str) -&gt; None: if not os.path.exists(nfs_path_that_is_shared): os.makedirs(nfs_path_that_is_shared) open(os.path.join(nfs_path_that_is_shared, f&quot;{uid}&quot;), &quot;a&quot;).close() </code></pre> <p>This patch function accepts the file completes everything</p> <pre><code>@router.patch(&quot;/{uuid}&quot;, status_code=status.HTTP_204_NO_CONTENT) async def upload_chunk( response: Response, uuid: str, content_type: str = Header(None), content_length: int = Header(None), upload_offset: int = Header(None), _: bytes | None = Depends(_get_request_chunk), ) -&gt; Response: return await _get_and_save_the_file( response, uuid, content_type, content_length, upload_offset, ) </code></pre> <p>and here is this method that is not working as expected in kubernetes deployments</p> <pre><code>async def _get_request_chunk( request: Request, uuid: str = Path(...), post_request: bool = False, ) -&gt; bool | None: log.info(&quot;Reading metadata&quot;) meta = _read_metadata(uuid) if not meta or not _file_exists(uuid): log.info(&quot;Metadata not found&quot;) return False path = f&quot;{nfs_path_that_is_shared}/{uuid}&quot; with open(path, &quot;ab&quot;) as f: log.info(&quot;Getting chunks&quot;) async for chunk in request.stream(): if post_request and chunk is None or len(chunk) == 0: log.info(&quot;Chunk is empty&quot;) return None log.info(&quot;Checking chunk size&quot;) if _get_file_length(uuid) + len(chunk) &gt; MAX_SIZE: log.info(&quot;Throwing HTTP_ENTITY_TO_LARGE&quot;) raise HTTP_ENTITY_TO_LARGE log.info(&quot;Writing chunk&quot;) f.write(chunk) log.info(&quot;Modifying metadata&quot;) meta.offset += len(chunk) meta.upload_chunk_size = len(chunk) meta.upload_part += 1 log.info(&quot;Writing metadata&quot;) _write_metadata(meta) log.info(&quot;Metadata written&quot;) return True </code></pre> <p>I am planning to add Redis as a solution since all our infrastructure if I cannot find a solution for this...</p> <p>Any help is much appreciated!</p> <p>I tried adding NFS that is shared between namespaces and pods, but that was the same issue it wrote the file sometimes usually until everything is uploaded it doesn't write the bytes to the file where in contrast locally it writes bytes as it receives.</p> <p>Edit: <strong>I did also implemented aiofiles async non blocking but it did not work.</strong></p>
<python><kubernetes><fastapi><nfs>
2023-01-31 13:00:05
0
2,372
Edi
75,297,516
2,141,427
Python function to extract specific values from complex JSON logs data
<p>I am trying to write a Python function (for use in a Google Cloud Function) that extracts specific values from JSON logs data. Ordinarily, I do this using the standard method of sorting through keys:</p> <pre><code>my_data['key1'], etc. </code></pre> <p>This JSON data, however is quite different, since it appears to have the data I need as lists inside of dictionaries. Here is a sample of the logs data:</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-js lang-js prettyprint-override"><code>{ "insertId": "-mgv16adfcja", "logName": "projects/my_project/logs/cloudaudit.googleapis.com%2Factivity", "protoPayload": { "@type": "type.googleapis.com/google.cloud.audit.AuditLog", "authenticationInfo": { "principalEmail": "email@email.com" }, "authorizationInfo": [{ "granted": true, "permission": "resourcemanager.projects.setIamPolicy", "resource": "projects/my_project", "resourceAttributes": { "name": "projects/my_project", "service": "cloudresourcemanager.googleapis.com", "type": "cloudresourcemanager.googleapis.com/Project" } }, { "granted": true, "permission": "resourcemanager.projects.setIamPolicy", "resource": "projects/my_project", "resourceAttributes": { "name": "projects/my_project", "service": "cloudresourcemanager.googleapis.com", "type": "cloudresourcemanager.googleapis.com/Project" } } ], "methodName": "SetIamPolicy", "request": { "@type": "type.SetIamPolicyRequest", "policy": { "bindings": [{ "members": [ "serviceAccount:my-test- sa @my_project.iam.gserviceaccount.com " ], "role": "projects/my_project/roles/PubBuckets" }, { "members": [ "serviceAccount:my-test-sa- 2 @my_project.iam.gserviceaccount.com " ], "role": "roles/owner" }, { "members": [ "serviceAccount:my-test-sa-3@my_project.iam.gserviceaccount.com", "serviceAccount:my-test-sa-4@my_project.iam.gserviceaccount.com" ] }</code></pre> </div> </div> </p> <p>My goal with this data is to extract the &quot;role&quot;:&quot;roles/editor&quot; and the associated &quot;members.&quot; So in this case, I would like to extract service accounts my-test-sa-3, 4, and 5, and print them.</p> <p>When the JSON enters my cloud function I do the following:</p> <pre><code>pubsub_message = base64.b64decode(event['data']).decode('utf-8') msg = json.loads(pubsub_message) print(msg) </code></pre> <p>And I can get to other data that I need, e.g., project id-</p> <pre><code>proj_id = msg['resource']['labels']['project_id'] </code></pre> <p>But I cannot get into the lists within the dictionaries effectively. The deepest I can currently get is to the 'bindings' key.</p> <p>I have additionally tried restructuring and flattening output as a list:</p> <pre class="lang-py prettyprint-override"><code> policy_request =credentials.projects().getIamPolicy(resource=proj_id, body={}) policy_response = policy_request.execute() my_bindings = policy_response['bindings'] flat_list = [] for element in my_bindings: if type(element) is list: for item in element: flat_list.append(item) else: flat_list.append(element) print('Here is flat_list: ', flat_list) I then use an if statement to search the list, which returns nothing. I can't use indices, because the output will change consistently, so I need a solution that can extract the values by a key, value approach if at all possible. Expected Output: Role: roles/editor Members: sa-1@gcloud.com sa2@gcloud.com sa3@gcloud.com and so on Appreciate any help. </code></pre>
<python><json><data-structures><google-cloud-functions>
2023-01-31 12:57:21
0
333
Jman
75,297,454
4,534,466
MLFlow - Experiment tracking - No such file or directory
<p>I want to run experiment tracking on my jupyter notebooks, I've installed mlflow and have set it up as such:</p> <pre><code>Path(&quot;mlruns&quot;).mkdir(parents=True, exist_ok=True) mlflow.set_tracking_uri(&quot;file:mlruns&quot;) client = mlflow.MlflowClient() experiment_id = client.create_experiment( EXPERIMENT_NAME, tags={ &quot;author&quot;: &quot;me&quot;, } ) experiment = client.get_experiment(experiment_id) </code></pre> <p>Now I want to track it, so I create a plot and run as follows:</p> <pre><code>with mlflow.start_run( experiment_id=experiment_id, run_name=&quot;foobar&quot;, description=&quot;Lorem Ipsum dolor sit amet&quot; ) as run: mlflow.log_figure(fig, &quot;figure_name.png&quot;) </code></pre> <p>but doing so gives me the following error:</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'mlruns\\&lt;experiment_id&gt;\\&lt;run_id&gt;\\tags\\mlflow.source.name' </code></pre> <p>What am I doing wrong? How can I set it up to track this image?</p>
<python><mlflow>
2023-01-31 12:52:17
0
1,530
João Areias
75,297,426
5,190,087
How to handle the callback with MagicMock
<pre><code>import unittest from mock import Mock, MagicMock import time wait = False def pushback_callback(self, res): print(&quot;Received callback&quot;) wait = True def pushback_fcn(callback): print(&quot;pushback_fcn&quot;) def execute(): pushback_fcn(pushback_callback) while wait == False: time.sleep(5) print(&quot;done&quot;) #********* Test code ************# pushback_fcn = MagicMock() execute() </code></pre> <p>As test code never call the callback, wait value is False always hence the test code wait forever. Is there any way we can get the function pointer form MagicMock?</p>
<python><python-mock><magicmock>
2023-01-31 12:49:29
1
1,598
Swapnil
75,297,406
222,529
How to make pytest select tests having markers with arguments
<p><a href="https://docs.pytest.org/en/7.2.x/example/markers.html#passing-a-callable-to-custom-markers" rel="nofollow noreferrer">According to the official documentation</a>, it is possible to mark tests with custom markers that have positional or keyword arguments. For instance:</p> <pre class="lang-py prettyprint-override"><code>@pytest.mark.my_marker.with_args('this') def test_marker_this(): pass @pytest.mark.my_marker.with_args('that') def test_marker_that(): pass </code></pre> <p>From the command line, how do I select the test(s) where <code>my_marker</code> has the argument <code>this</code>?</p> <p>The only approach I could think of (<code>pytest -m 'my_marker == &quot;this&quot;'</code>) does not work.</p> <p>How can I do an &quot;inverse selection&quot;, i.e. selecting all tests that are <em>not</em> marked with &quot;that&quot;?</p> <p>And finally, what if the argument is not a string - maybe a bool or an int?</p>
<python><pytest>
2023-01-31 12:48:11
1
3,215
Jir
75,297,385
15,537,675
Read large json file - update?
<p>I'm having a large json file which I'm struggling to read and work with in python. It seems I can for instance run <code>json.loads()</code> but then it crashes after a while.</p> <p>There are two questions which are basically the same thing:</p> <p><a href="https://stackoverflow.com/questions/10382253/reading-rather-large-json-files">Reading rather large JSON files</a></p> <p><a href="https://stackoverflow.com/questions/2400643/is-there-a-memory-efficient-and-fast-way-to-load-big-json-files">Is there a memory efficient and fast way to load big JSON files?</a></p> <p>But these questions are from 2010 and 2012, so I was wondering if there's a newer/better/faster way to do things?</p> <p>My file is on the format:</p> <pre><code>import json f = open('../Data/response.json') data = json.load(f) dict_keys(['item', 'version']) # Path to data : data['item'] </code></pre> <p>Thanks.</p>
<python><json>
2023-01-31 12:47:02
1
472
OLGJ
75,297,220
16,591,917
Why does objective function for some iteration shows as NaN
<p>I have a Gekko model and is currently experimenting with different objective functions. Most of the objective functions is built with <code>.COST</code> and <code>.DCOST</code> constructs on <code>CV</code> and <code>MV</code> variables augmented by some additional <code>Maximize</code> and <code>Minimize</code> statements. However, what happens is that some permutations of these seem to cause the Objective function value for some iterations to become NaN, as shown in the attached picture. I not sure if that means that the Obj function when calculated for some values result division by zero, inf or otherwise undefined. I will appreciate some pointers as to how to overcome this.</p> <p><a href="https://i.sstatic.net/zA9kA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zA9kA.png" alt="enter image description here" /></a></p>
<python><gekko>
2023-01-31 12:33:57
1
319
JacquesStrydom
75,297,212
3,593,246
Find all tags containing a string in BeautifulSoup
<p>In BeautifulSoup, I can use <code>find_all(string='example')</code> to find all NavigableStrings that match against a string or regex.</p> <p>Is there a way to do this using <code>get_text()</code> instead of <code>string</code>, so that the search matches a string even if it spans across multiple nodes? i.e. I'd want to do something like: <code>find_all(get_text()='Python BeautifulSoup')</code>, which would match against the entire inner string content.</p> <p>For example, take this snippet:</p> <pre><code>&lt;body&gt; &lt;div&gt; Python &lt;br&gt; BeautifulSoup &lt;/div&gt; &lt;/body&gt; </code></pre> <p>If I wanted to find 'Python Beautiful Soup' and have it return both the <code>body</code> and <code>div</code> tags, how could I accomplish this?</p>
<python><html><parsing><web-scraping><beautifulsoup>
2023-01-31 12:33:29
2
362
jayp
75,297,205
20,185,574
Compute Bernoulli numbers with Python recursive program
<p>I'm trying to solve a problem about Bernoulli numbers using Python. The aim is to output the numerator and the denominator of the $n$-th Bernoulli number. I use the conventions and the generic formula given in <a href="https://projectlovelace.net/problems/ada-lovelaces-note-g/" rel="nofollow noreferrer">this source</a>.</p> <p>Here is my code. I use the auxiliary function <code>aux_bernoulli</code> to compute Bernoulli numbers using recursivity.</p> <pre class="lang-py prettyprint-override"><code>from fractions import Fraction from math import factorial def aux_bernoulli(n): if n == 0: return 1 elif n == 1: # convention return -0.5 elif (n-1)%2==0: # B(n)=0 when n is odd return 0 else: somme = 0 for k in range(n): somme += (factorial(n)/(factorial(n+1-k)*factorial(k))) * aux_bernoulli(k) return -somme def bernoulli(n): ber = aux_bernoulli(n) print(ber) # for debugging purposes numerator, denominator = Fraction(ber).numerator, Fraction(ber).denominator return numerator, denominator </code></pre> <p>This code is giving me <strong>wrong values that are very close to the right ones</strong> and I can't understand figure out why. Here are some examples:</p> <pre><code>bernoulli(4) bernoulli(6) bernoulli(8) </code></pre> <p>Output:</p> <pre><code>-0.03333333333333338 (-600479950316067, 18014398509481984) 0.023809523809524058 (214457125112883, 9007199254740992) -0.033333333333335075 (-1200959900632195, 36028797018963968) </code></pre> <p>Correct values according to <a href="https://codegolf.stackexchange.com/questions/65382/bernoulli-numbers">this source</a>:</p> <pre><code>-0.033333 (-1, 30) 0.0280952 (1/42) -0.033333 (-1, 30) </code></pre> <p>Does anyone know what's wrong with my approach?</p>
<python><recursion><math><fractions><python-fractions>
2023-01-31 12:33:03
1
461
Barbara Gendron
75,297,138
12,297,666
Why predict works without fit the model in Keras
<p>Check the following code:</p> <pre><code>import numpy as np import keras from keras.models import Sequential from keras.layers import Conv1D, MaxPooling1D, Flatten from sklearn.model_selection import train_test_split # Data X = np.random.rand(1000, 100, 1) y = np.random.randint(0, 2, (1000, 1)) # Splitting into train and test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Conv1D model = Sequential() model.add(Conv1D(32, kernel_size=3, activation='relu', input_shape=(100, 1))) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) # Predict before fitting the model cnn_features_train = model.predict(X_train) cnn_features_test = model.predict(X_test) </code></pre> <p>Why this runs without throwing an error? The weights are not yet stabilished by the <code>.fit</code> method, how can it predict something?</p> <p>If i try to do the same thing (predict before fitting the model) using <code>Sklearn</code> i get the expected error, for example:</p> <pre><code>from sklearn.ensemble import RandomForestClassifier # Data X = np.random.rand(1000, 100, 1) y = np.random.randint(0, 2, (1000, 1)) # Splitting into train and test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Random Forest rf = RandomForestClassifier() rf.predict(X_test) </code></pre> <p>The error:</p> <pre><code> sklearn.exceptions.NotFittedError: This RandomForestClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator. </code></pre>
<python><keras>
2023-01-31 12:28:00
1
679
Murilo
75,297,062
821,780
pytest requests to fastapi in a separate process
<p>I am trying to have working tests for an API written with FastAPI.</p> <p>I start the service in a separate process, run the tests with requests to the service, and check if the results are as expected.</p> <p>I have extracted the key parts into a minimal working example, in the PD.</p> <p>Running the MWE with the main file works fine. The tests fail, though.</p> <ul> <li>Why do the tests fail?</li> <li>How should we test APIs?</li> </ul> <p>PD: the code is <a href="https://gist.github.com/trylks/1c924e244635551ea7e1a5385b4d25e6" rel="nofollow noreferrer">in a GIST</a>, but now also here:</p> <h2>README.md</h2> <pre class="lang-markdown prettyprint-override"><code># Minimal example to ask in StackOverflow Pytest does not allow to start a process with a service and tests requests to it, at least not in the most straightforward way IMHO. I may be missing something, or I may be doing something wrong. Hence, I share this short code in a gist, to ask. ## How to run it The dependencies are: `fastapi pytest requests uvicorn`. You may install them with your package / environment manager of choice, or use `pipenv install` with the provided `Pipfile`. To run the code in the environment (e.g. `pipenv shell`), run: `python3 mwe.py`. You should see everything is `OK`. To run the test, run in the environment: `pytest`. This does not work for me, the request times out. </code></pre> <h2>mwe.py</h2> <pre class="lang-python prettyprint-override"><code>import fastapi, multiprocessing, requests, time, uvicorn app = fastapi.FastAPI() @app.get('/ok') def ok(): return 'OK' class service: def __enter__(self): def run_service(): uvicorn.run('mwe:app', host='0.0.0.0', port=8000, reload=True) self.service = multiprocessing.Process(target=run_service) self.service.start() time.sleep(10) def __exit__(self, *args): self.service.terminate() def main(): with service(): return requests.get('http://127.0.0.1:8000/ok').ok if __name__ == '__main__': print('🆖🆗'[main()]) </code></pre> <h2>Pipfile</h2> <pre class="lang-ini prettyprint-override"><code>[[source]] url = &quot;https://pypi.org/simple&quot; verify_ssl = true name = &quot;pypi&quot; [packages] pytest = &quot;*&quot; fastapi = &quot;*&quot; requests = &quot;*&quot; uvicorn = &quot;*&quot; [requires] python_version = &quot;3.10&quot; python_full_version = &quot;3.10.6&quot; </code></pre> <h2>test_mwe.py</h2> <pre class="lang-python prettyprint-override"><code>from mwe import main def test_main(): assert main() </code></pre>
<python><multiprocessing><pytest><fastapi>
2023-01-31 12:21:59
1
1,498
Trylks
75,296,710
3,099,733
Is it possible to limit YAML bool value literal in python?
<p>I am using YAML to describe some configuration that will be read by a Python tool using <code>ruamel</code>. The problem is I need to use string literal ON a lot and in YAML ON without quote will be treated as bool value <code>true</code>. I have to quote those 'ON' carefully or else the tool will throw unexpected result.</p> <p>Is it possible to tell <code>ruamel</code> to only treat <code>true</code> and <code>false</code> as bool, and for other keywords like ON, Yes, just treat them as string literal to reduce the chance of making mistake? For this use case I don't think I have to stick to the YAML specification as there is little chance that the configuration file will be processed by others.</p>
<python><yaml><pyyaml><ruamel.yaml>
2023-01-31 11:50:06
1
1,959
link89
75,296,495
13,490,682
Sum the values ​of a column with Python
<p>I'm new to python, I would like to read a column of values ​​from a csv file and add them together, but only those to the left of the &quot;,&quot; My csv File:</p> <pre><code>Name Code Angel 19;90 Eduardo 20;21 Miguel 30;45 </code></pre> <p>I would like to be able to sum only the numbers to the left of the &quot;Code&quot; column, so that my output is &quot;19+20+30 = 69&quot;. I tried deleting the &quot;;&quot; and converting the string to int but sums but joins the numbers together and I have this output:</p> <pre><code>Your final sum is : 1990 +2021 +3045 = 7056 </code></pre>
<python><pandas><dataframe>
2023-01-31 11:32:33
4
393
Jacket
75,296,469
13,184,183
Is there a way to get version of production model in mlflow?
<p>I use <code>mlflow 1.23.1</code> and when trying to load model via <code>models:/model_name/Production</code> I receive error described <a href="https://github.com/mlflow/mlflow/issues/5171#issuecomment-1027234578" rel="nofollow noreferrer">here</a> with <code>405</code> code <code>Method not allowed</code>. Setting versions of <code>mlflow</code> and <code>python</code> the same on client and server didn't help. However, loading model with <code>models:/model_name/version</code> works fine. So I wonder if there is a way to deduce which version Production stage has?</p>
<python><mlflow>
2023-01-31 11:30:09
1
956
Nourless
75,296,422
11,964,058
Adding new key value to dictionary in a for loop
<p>I have a hugging face dataset in format</p> <pre><code> test = [{'doc':document1, 'id':id1},{'doc':document2, 'id':id2}.......] </code></pre> <p>I'm trying to generate summaries for the dataset and append them to the doc. The code below takes one dict from test and computes lex rank summary. This is stored in summary variable as a list (each list item is a summary). I want each summary to be appended to a new key called summary for each dict in dataset.</p> <pre><code>for i in test: segments = get_segmented_text(i['doc']) expected_length = round(len(segments) / median_compression_ratio) most_central_indices = compute_lexrank_sentences(model, segments, device, expected_length) summary = [segments[idx] for idx in sorted(most_central_indices)] i['summary'] = '\n'.join(summary) </code></pre> <p>This code supposed to add another key value with summaries but it doesn't add anything neither gives any error.</p> <p>Here is expected output:</p> <pre><code>test = [{'doc':document1, 'id':id1, 'summary': summary1},{'doc':document2, 'id':id2, 'summary':summary2}.......] </code></pre> <p>Thanks in advance</p> <p><strong>Edit:</strong> I approached this problem by converting the huggingface dataset to dataframe and slight changes in code (code below). It works fine this way. But still I would like to know how to do this on huggingface dataset.</p> <pre><code> for i, row in df.iterrows(): segments = get_segmented_text(row['doc']) expected_length = round(len(segments) / median_compression_ratio) most_central_indices = compute_lexrank_sentences(model, segments, device, expected_length) summary = [segments[idx] for idx in sorted(most_central_indices)] df.at[i, 'summary'] = '\n'.join(bert_summary) </code></pre>
<python><dictionary><for-loop>
2023-01-31 11:25:26
1
493
Praveen Bushipaka
75,296,322
17,176,270
How can I retrieve relative document in MongoDB?
<p>I'm using Flask with Jinja2 template engine and MongoDB via pymongo. This are my documents from two collections (phone and factory):</p> <pre><code>phone = db.get_collection(&quot;phone&quot;) { &quot;_id&quot;: ObjectId(&quot;63d8d39206c9f93e68d27206&quot;), &quot;brand&quot;: &quot;Apple&quot;, &quot;model&quot;: &quot;iPhone XR&quot;, &quot;year&quot;: NumberInt(&quot;2016&quot;), &quot;image&quot;: &quot;https://apple-mania.com.ua/media/catalog/product/cache/e026f651b05122a6916299262b60c47d/a/p/apple-iphone-xr-yellow_1.png&quot;, &quot;CPU&quot;: { &quot;manufacturer&quot;: &quot;A12 Bionic&quot;, &quot;cores&quot;: NumberInt(&quot;10&quot;) }, &quot;misc&quot;: [ &quot;Bluetooth 5.0&quot;, &quot;NFC&quot;, &quot;GPS&quot; ], &quot;factory_id&quot;: ObjectId(&quot;63d8d42b7a4d7a7e825ef956&quot;) } factory = db.get_collection(&quot;factory&quot;) { &quot;_id&quot;: ObjectId(&quot;63d8d42b7a4d7a7e825ef956&quot;), &quot;name&quot;: &quot;Foxconn&quot;, &quot;stock&quot;: NumberInt(&quot;1000&quot;) } </code></pre> <p>In my python code to retrieve the data I do:</p> <pre><code>models = list( phone.find({&quot;brand&quot;: brand}, projection={&quot;model&quot;: True, &quot;image&quot;: True, &quot;factory_id&quot;: True}) ) </code></pre> <p>How can I retrieve relative factory document by <code>factory_id</code> and have it as an embedded document in a <code>models</code> list?</p>
<python><mongodb><pymongo>
2023-01-31 11:16:56
1
780
Vitalii Mytenko
75,296,240
5,654,564
Define timeout when tox is installing requirements
<p>I have a gitlab ci pipeline which basically do some stuff on the enviornment ( install python and other packages) then it simply run <code>tox</code> in order to run some tests.</p> <pre><code>stages: - check before_script: # here you can run any commands before the pipelines start - apt-get -qq update &amp;&amp; apt-get -qq install -y python3.9 - apt-get install -y libpq-dev &amp;&amp; apt-get install -y python3.9-dev - apt-get install -y build-essential &amp;&amp; apt-get install -y gcc &amp;&amp; apt-get install -y postgresql - apt-get install -y postgresql-contrib &amp;&amp; apt-get install -y ffmpeg libsm6 libxext6 - apt-get install -y git - pip install tox check: stage: check image: gitlab.*****.com:****/***** environment: prod services: - name: docker:19.03.8-dind #20.10.7 alias: docker only: - master script: - | echo &quot; machine gitlab.*****.com login gitlab-ci-token password $CI_JOB_TOKEN &quot; &gt; ~/.netrc - tox </code></pre> <p>This is my <code>tox.ini</code>:</p> <pre><code>[tox] envlist = {python3.9} [testenv] passenv = * setenv = AIRFLOW_HOME = /airflow_home deps= pytest -r{toxinidir}/requirements.txt commands= pytest </code></pre> <p>The problem is that when <code>tox</code> is building the env and installing the packages specified in the <code>requirements.txt</code> it returns a <code>ReadTimeOutError</code>.</p> <p>I've tried to delete <code>tox</code> and simply run a <code>pip install -r requiremenets --default-timeout=200</code> and it worked.<br> So the problem seems to be a timeout. I'd like to define a <code>timeout</code> but i don't want to discard tox.</p> <p>How can i do it?</p>
<python><gitlab><tox>
2023-01-31 11:10:03
2
2,507
Marco Fumagalli
75,295,957
15,034,606
why does Fuzzywuzzy python script take forever to generate results?
<p>To give an idea, I have an excel file(.xlsx format) within which I am working with 2 sheets at a time.</p> <p>I am interested in 'entity name' from sheet a and 'name' from sheet b.</p> <p>Sheet b has 'name' column written 7times.</p> <p>my sheet a looks like this.</p> <pre><code>Isin Entity Name DE0005545503 1&amp;1 AG US68243Q1067 1-800-Flowers.Com Inc US68269G1076 1Life Healthcare Inc US3369011032 1st Source Corp </code></pre> <p>while my sheet b looks like this</p> <pre><code>name company_id name company_id name company_id name company_id name company_id name company_id name LIVERPOOL PARTNERS MICROCAP GROWTH FUND MANAGER PTY LTD 586056 FERRARI NADIA 1000741 DORSET COMMUNITY RADIO LTD 1250023 Hunan Guangtongsheng Communication Service Co., Ltd. 1500335 Steffes Prüf- und Messtechnik GmbH, 1550006 CHL SRL 2000320 Qu Star, Inc. BISCUIT AVENUE PTY LTD 586474 D AMBROSIO MARIA 1000382 LUCKY WORLD PRODUCTIONS LIMITED 1250024 Zhuzhou Wanlian Telecommunication Co., Ltd. 1500354 e42 II GmbH 1550510 EGGTRONIC SPA 2000023 Molly Shaheen, L.L.C. CL MAY1212 PTY LTD 586475 TORIJA ZANE LUCIA LUCIA 1000389 FYLDE COAST MEDIA LTD 1250034 Zhongyi Tietong Co., Ltd. Yanling Xiayang Broadband TV Service Center 1500376 Valorem Capital UG (haftungsbeschränkt) 1550539 MARACAIBA INVEST SRL 2000139 Truptisudhir Pharmacy Inc </code></pre> <p>alternatively you can find the sheet b here:<a href="https://i.sstatic.net/tBZnE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tBZnE.png" alt="enter image description here" /></a></p> <p>Here's my code</p> <pre><code>import pandas as pd from fuzzywuzzy import fuzz filename = 'C:/Users/Downloads/SUniverse.xlsx' dataframe1 = pd.read_excel(filename, sheet_name='A') dataframe2 = pd.read_excel(filename, sheet_name='B') # print(dataframe1.head()) # print(dataframe2.head()) # Clean customers lists A_cleaned = [df1 for df1 in dataframe1[&quot;Entity Name&quot;] if not(pd.isnull(df1))] B_cleaned = [df2 for df2 in dataframe2[&quot;name&quot;].unique() if not(pd.isnull(df2))] print(A_cleaned) print(B_cleaned) # Perform fuzzy string matching tuples_list = [max([(fuzz.token_set_ratio(i,j),j) for j in B_cleaned]) for i in A_cleaned] print(tuples_list) # Unpack list of tuples into two lists similarity_score, fuzzy_match = map(list,zip(*tuples_list)) # Create pandas DataFrame df = pd.DataFrame({&quot;I_Entity_Name&quot;:A_cleaned, &quot;I_Name&quot;: fuzzy_match, &quot;similarity score&quot;:similarity_score}) df.to_excel(&quot;C:/Users/Downloads/fuz-match-output.xlsx&quot;, sheet_name=&quot;Fuzzy String Matching&quot;, index=False) print('done!') </code></pre> <p>The code takes forever to generate results. It has been over 20hours and the script is still running. My excel input file is going over 50mbs in size(just wanna say that it contains millions of records).</p> <p>How do I ensure that my script runs at a faster pace and generates the result? I want the output to be this:</p> <pre><code>Entity Name Name fuzzy score apple APPLE 100 . . . </code></pre>
<python><excel><pandas><dataframe><fuzzywuzzy>
2023-01-31 10:44:23
0
521
technophile_3
75,295,935
5,343,362
Improve text reading from image
<p>I am trying to read movie credits from a movie. To make a MVP I started with a picture:<a href="https://i.sstatic.net/eR2ls.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eR2ls.jpg" alt="enter image description here" /></a></p> <p>I use this code:</p> <pre><code>print(pytesseract.image_to_string(cv2.imread('frames/frame_144889.jpg'))) </code></pre> <p>I tried different psm but it return an ugly text.</p> <pre><code>one Swimmer Decay Nurse Aer a ig coy Coy cor ag Or Rr Sa Ae Red cod Reng OED Ty Ryan Stunt Double UST er ey a er Pm JESSICA NAPIER ALEX MALONE Ey DAMIEN STROUTHOS JESSE ROWLES DARIUS WILLIAMS beamed Aya GEORGE HOUVARDAS Sih ata ARS Vara BES liv4 MIKE DUNCAN Pe OV TN Ia Ale Tate SUV (aa: ae SU aa AIDEN GILLETT MARK DUNCAN. </code></pre> <p>I tried with other picture with bigger resolution with better result but I which to be able to enable non HD movie.</p> <p>What could I do to improve the precision of the reading ?</p> <p>Regards Quentin</p>
<python><ocr><tesseract>
2023-01-31 10:41:58
1
301
Quentin M
75,295,899
5,868,293
How to add indicator column that lists all values of another column in pandas
<p>I have the following pandas dataframe:</p> <pre><code>import pandas as pd pd.DataFrame({'id': [1,1,1,1,2,2,2], 'col': ['a','b','c','c','a','b','d']}) id col 0 1 a 1 1 b 2 1 c 3 1 c 4 2 a 5 2 b 6 2 d </code></pre> <p>I would like to add a new column, which would contain the list of unique values of <code>col</code> by <code>id</code></p> <p>The end dataframe would look like this:</p> <pre><code>pd.DataFrame({'id': [1,1,1,1,2,2,2], 'col': ['a','b','c','c','a','b','d'], 'col2': [['a','b','c'],['a','b','c'],['a','b','c'],['a','b','c'], ['a','b','d'],['a','b','d'],['a','b','d']]}) id col col2 0 1 a [a, b, c] 1 1 b [a, b, c] 2 1 c [a, b, c] 3 1 c [a, b, c] 4 2 a [a, b, d] 5 2 b [a, b, d] 6 2 d [a, b, d] </code></pre> <p>How could I do that ?</p>
<python><pandas>
2023-01-31 10:39:15
2
4,512
quant
75,295,856
9,038,295
Pre-commit install-hooks does not work (SSLError)
<p>I use conda Python environments. Whenever I try to run <code>pre-commit install-hooks</code>, I get the error</p> <pre><code> Could not fetch URL https://pypi.org/simple/ruamel-yaml/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded w ith url: /simple/ruamel-yaml/ (Caused by SSLError(&quot;Can't connect to HTTPS URL because the SSL module is not available.&quot;)) - skipping ... WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. </code></pre> <p>However, <code>pip</code> works just fine when I use it.</p> <p>I already tried <code>pre-commit clean</code>, uninstalling <code>pre-commit</code> and reinstalling it (either with <code>conda</code> or <code>pip</code>), updating <code>pip</code>, switching off the VPN, and also any other solution I could find on Google. Nothing seems to work. Could you please help me?</p> <p>The <code>.pre-commit-config.yaml</code> looks like this:</p> <pre><code>repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: - id: check-yaml - id: check-added-large-files - repo: https://github.com/psf/black rev: stable hooks: - id: black language_version: python3.8 - repo: https://github.com/pycqa/isort rev: 5.10.1 hooks: - id: isort name: isort (python) </code></pre>
<python><ssl><pre-commit-hook><pre-commit><pre-commit.com>
2023-01-31 10:35:14
2
501
karu
75,295,827
1,870,969
Find tuples in a list of tuples, with consecutive values and turn them into bigger tuples
<p>I have a list of tuples, each having two elements. Example:</p> <pre><code>my_tuples = [('black', 'grey'), ('red', 'orange'), ('blue', 'purple'), ('orange', 'yellow'), ('grey', 'white'), ('yellow', 'cream')] </code></pre> <p>I am looking for an efficient way to find all the tuples whose first values are identical to second value of another one, make a triple of them, and continue adding values in this manner until all such chains are found. In this example, it should give the following list back:</p> <pre><code>my_tuples_processed = [('black', 'grey', 'white'), ('blue', 'purple'), ('red', 'orange', 'yellow', 'cream')] </code></pre> <p>Any help on this would be appreciated.</p>
<python><list><sorting><tuples>
2023-01-31 10:33:14
2
997
Vahid S. Bokharaie
75,295,687
7,318,120
How can I Export Pandas DataFrame to Google Sheets (specific cell) using Python?
<ul> <li>I can read data and write data to a google sheet.</li> <li>I can also write a pandas dataframe to a google sheet <code>cell(1,1)</code>.</li> </ul> <p>I am now trying to write the same dataframe to a specific cell (like <code>cell(20,20)</code>) on a sheet.</p> <p>resources:</p> <ul> <li><p>this link is close, but only refers to the sheet and does not specify the cell: <a href="https://stackoverflow.com/questions/62917910/how-can-i-export-pandas-dataframe-to-google-sheets-using-python">How can I Export Pandas DataFrame to Google Sheets using Python?</a></p> </li> <li><p>the docs are here, but the example seems to only refer to a sheet (so the result is again <code>cell(1,1)</code>): <a href="https://docs.gspread.org/en/latest/user-guide.html#using-gspread-with-pandas" rel="nofollow noreferrer">https://docs.gspread.org/en/latest/user-guide.html#using-gspread-with-pandas</a></p> </li> </ul> <p>what i have tried:</p> <ul> <li>i have tried to modify the <code>update_cell</code> command with a dataframe.</li> </ul> <pre class="lang-py prettyprint-override"><code># this works sh.sheet1.update_cell(20,20,'hello world') # but this fails # example dataframe d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) # write to a specific cell sh.sheet1.update_cell(20,20,df) </code></pre> <p>So my question is, <strong>how can i specify the cell that the pandas Dataframe is written to ?</strong></p>
<python><pandas><dataframe><google-sheets><google-sheets-api>
2023-01-31 10:21:29
1
6,075
darren
75,295,639
19,580,067
Split the text between the start and end words from a long String using Regex Python
<p>Extracted a threaded email body using pywin32 and I need to extract the signature part alone from the body. I tried to split the text using the signature start as starting word and the next email From as the Ending word. For ex: 'With Regards' will be the starting word and 'Von' will be the ending word.</p> <p>Body of the email:</p> <pre><code>Dear Sir, Your Order is ready and tested. It will be shipped shortly. Let me know once you receive it. With Regards, dcabv, vce technologies vce.com cont:+00440044 From: abc@gsn.com To:csd@scb.com Sub: product Dear Sir, Can I get the update of my order? With Regards, abc cont:+46346466 Von: csd@scb.com Gesendet:abc@gsn.com Sub: Order Placed Dear Sir, your order has placed. you will receive it shortly. With Regards, dcabv, vce technologies vce.com cont:+00440044 </code></pre> <p>Another Text:</p> <pre><code>a = &quot;&quot;&quot; Best regards, i.V. Cap. Mars Wel Chief Superintendent ========================== P E N T H O L E Sahrts-HC Elba 379 D- 259 Ham Tel: +58 58 58585-584 Mobile: +91 758 858 5875 Fax: +47 47 85885-855 Sitz: Ham, HA 5772 Von: Korayae Vinay &lt;Korayae.Vinay@robo.com&gt; Gesendet: Donnes, 19. Januar 2014 12:16 An: Wel, Mars &lt;wel.s@dolo.de&gt; Betreff: RE: Prod Order Dear Donnes; Good day A few minutes before ı placed the order. If you need any assistance we are happy to help with that. Best Regards Korayae Vinay Managing Director &quot;&quot;&quot; </code></pre> <p>Any suggestions?</p> <p>The code I tried is below:</p> <pre><code>re.findall('(?:(?:With best regards,|Best Regards,)\s*.*(?:Von:|From:))', body, flags = re.IGNORECASE|re.DOTALL|re.MULTILINE) Note: body is the body of the extracted email. </code></pre> <p>The Output I received:</p> <pre><code>With Regards, dcabv, vce technologies vce.com cont:+00440044 From: abc@gsn.com To:csd@scb.com Sub: product Dear Sir, Can I get the update of my order? With Regards, abc cont:+46346466 Von: </code></pre> <p>But I want the output to be splitted into two as 1st output will be from 'With Regards' of 1st email til 'From'.</p> <p>2nd output will be from 'With Regards' of 2nd email til 'Von'.</p>
<python><regex><regex-lookarounds>
2023-01-31 10:17:54
1
359
Pravin
75,295,398
9,962,007
How to find which python package(s) require(s) certain dependency?
<p>Ideally using a one-liner, without the need for a dedicated script (e.g. looping and grepping over <code>pipdeptree -p</code> output with many packages). Ideally using standard tools (unless the extra package required is actively maintained).</p> <p>Importantly, the package (said dependency) is not installed, so its reverse dependencies cannot be established using <code>pipdeptree -r -p</code>.</p> <hr /> <p>This was motivated (but is off-topic here) by <code>&quot;UserWarning: You do not have a working installation of the service_identity module: 'No module named service_identity'.&quot;</code></p>
<python><pip><dependencies><conda>
2023-01-31 09:57:29
0
7,211
mirekphd
75,295,311
7,132,596
Pandas qcut with infinite values
<p>I would like to have bins with infinite values on the left and right. This worked in older pandas versions (at least 1.1.5) but not in 1.5.</p> <pre><code>pd.qcut([1,2,3,4,5,-np.inf, np.inf], q=3, duplicates=&quot;drop&quot;) </code></pre> <p>results in <code>ValueError: missing values must be missing in the same location both left and right sides</code>.</p> <p>When omitting the <code>duplicates</code> keyword the following error occurs:</p> <pre><code>ValueError: Bin edges must be unique: array([nan, 2., 4., nan]). You can drop duplicate edges by setting the 'duplicates' kwarg </code></pre> <p>My workaround is to replace <code>np.inf</code> with with really high numbers such as <code>1e9</code>, but this is not as nice as using np-inf. Is this a bug or intended that <code>np.inf</code> is treated as <code>nan</code>?</p>
<python><pandas><numpy>
2023-01-31 09:49:24
0
956
Hans Bambel
75,295,294
6,256,859
Django - Can not join 2 models
<p><strong>Problem:</strong> Joining 2 models in Django.</p> <p><strong>Error</strong>: Error during template rendering. Direct assignment to the reverse side of a many-to-many set is prohibited. Use entity_id.set() instead.</p> <p>I have read through all the threads on SO. Tried all the suggested solutions, read the Django documentation and think I just must be fundamentally misunderstanding something. Any help would be much appreciated.</p> <p>I have 2 models. <em>Entity</em> and <em>File</em>.</p> <p>An <em>Entity</em> can have multiples <em>Files</em> but each <em>File</em> only has 1 <em>Entity</em>.</p> <p>The primary keys of each table are just auto incrementing integers. Therefore I want to join column <strong>entity_id</strong> from <em>File</em> with <strong>entity_id</strong> from <em>Entity</em>. According to the documentation I have set <strong>entity_id</strong> in <em>File</em> as a ForeignKey. And I have set <strong>entity_id</strong> as unique in <em>Entity</em></p> <pre><code>class Entity(models.Model): pk_entity = models.AutoField(primary_key=True) entity_id = models.IntegerField(blank=True, null=True, unique=True) name = models.CharField(blank=True, null=True) class Meta: managed = False db_table = 'entities' class File(models.Model): pk_file = models.AutoField(primary_key=True) filename = models.CharField(blank=True, null=True) entity_id = models.ForeignKey(Entity, on_delete= models.CASCADE, to_field='entity_id') </code></pre> <p>The view is just trying to render this. I have tried using .all() rather than select_related() but no data renders.</p> <pre><code>class TestListView(ListView): queryset = File.objects.select_related() template_name = &quot;operations/files/test_list.html&quot; </code></pre> <p>And this is the html:</p> <pre><code>{% extends &quot;base.html&quot; %} {% block content %} &lt;div&gt; &lt;div&gt; &lt;ul&gt; {% for x in object_list %} &lt;li&gt; {{x}} &lt;/li&gt; {% empty %} &lt;p&gt;Empty&lt;/p&gt; {% endfor %} &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; {% endblock %} </code></pre>
<python><django><django-models><django-rest-framework><django-views>
2023-01-31 09:47:33
1
1,080
Andy
75,295,132
13,983,136
How to place specific constraints on the parameters of a Pydantic model?
<p>How can I place specific constraints on the parameters of a Pydantic model? In particular, I would like:</p> <ul> <li><code>start_date</code> must be at least <code>&quot;2019-01-01&quot;</code></li> <li><code>end_date</code> must be greater than <code>start_date</code></li> <li><code>code</code> must be one and only one of the values ​​in the set</li> <li><code>cluster</code> must be one and only one of the values ​​in the set</li> </ul> <p>The code I'm using is as follows:</p> <pre><code>from fastapi import FastAPI from pydantic import BaseModel from typing import Set import uvicorn app = FastAPI() class Query(BaseModel): start_date: str end_date: str code: Set[str] = { &quot;A1&quot;, &quot;A2&quot;, &quot;A3&quot;, &quot;A4&quot;, &quot;X1&quot;, &quot;X2&quot;, &quot;X3&quot;, &quot;X4&quot;, &quot;X5&quot;, &quot;Y1&quot;, &quot;Y2&quot;, &quot;Y3&quot; } cluster: Set[str] = {&quot;C1&quot;, &quot;C2&quot;, &quot;C3&quot;} @app.post(&quot;/&quot;) async def read_table(query: Query): return {&quot;msg&quot;: query} if __name__ == &quot;__main__&quot;: uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000) </code></pre>
<python><fastapi><pydantic>
2023-01-31 09:35:26
2
787
LJG
75,295,115
7,657,180
Remove corrupt exif warnings with tiff images
<p>I am trying to fix the corrupt exif warnings from tiff images and here's a code I am using</p> <pre><code>from PIL import Image def remove_exif(image_name): image = Image.open(image_name) if not image.getexif(): return print('removing EXIF from', image_name, '...') data = list(image.getdata()) image_without_exif = Image.new(image.mode, image.size) image_without_exif.putdata(data) image_without_exif.save(image_name) remove_exif('ggg.tiff') print('Done') </code></pre> <p>The code is working and removed the exif but I got one page only while the tiff before the exif remove was of two pages. Is it possible to keep all the pages of the tiff image?</p>
<python><python-imaging-library>
2023-01-31 09:33:47
0
9,608
YasserKhalil
75,295,032
9,758,017
Set steps on y-axis with matplotlib
<p>Currently I have the problem that I do not get the steps on the <strong>y-axis</strong> (score) changed. My representation currently looks like this:</p> <p><a href="https://i.sstatic.net/c4yNt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c4yNt.png" alt="enter image description here" /></a></p> <p>However, since only whole numbers are possible in my evaluation, these 0.5 steps are rather meaningless in my representation. I would like to change these steps from 0.5 to 1.0. So that I get the steps <code>[0, 1, 2, 3, ...]</code> instead of <code>[0.0, 0.5, 1.0, 1.5, 2.0, ...]</code>.</p> <p>My code broken down to the most necessary and simplified looks like this:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt # some calculations x = np.arange(len(something)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, test1_means, width, label='Test 1') rects2 = ax.bar(x + width/2, test2_means, width, label='Test 2') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Scores') ax.set_title('Something to check') ax.set_xticks(x, something) ax.legend() ax.bar_label(rects1, padding=3) ax.bar_label(rects2, padding=3) fig.tight_layout() plt.show() </code></pre> <p>In addition, after research, I tried setting the variable <code>ax.set_yticks</code> or adjusting the <code>fig</code>. Unfortunately, these attempts did not work.</p> <p>What am I doing wrong or is this a default setting of matplotlib at this point?</p> <hr /> <p><strong>Edit after comment:</strong></p> <p>My calculations are prepared on the basis of Excel data. Here is a reproducible code snippet with the current values how the code might look like in the final effect:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt stories = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;] test1_means = [2, 3, 2, 3, 1] test2_means = [0, 1, 0, 0, 0] x = np.arange(len(stories)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, test1_means, width, label='Test 1') rects2 = ax.bar(x + width/2, test2_means, width, label='Test 2') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Scores') ax.set_title('Something') ax.set_xticks(x, stories) ax.legend() ax.bar_label(rects1, padding=3) ax.bar_label(rects2, padding=3) fig.tight_layout() plt.show() </code></pre>
<python><matplotlib>
2023-01-31 09:26:49
2
1,778
41 72 6c
75,294,999
10,413,428
Path from list of path parts with pathlib
<p>I want to generate a path based on a list inside the configuration toml. I have chosen a list to be able to support different operating systems.</p> <p>For example the following list is stored inside my configuration.toml:</p> <pre class="lang-ini prettyprint-override"><code>temporary_storage_folder = [&quot;~&quot;, &quot;temp&quot;, &quot;machine_name&quot;] </code></pre> <p>This should then be converted into a Path object.</p> <p>The trivial constructor seems not to exists, so:</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path Path([&quot;~&quot;, &quot;temp&quot;, &quot;mesomics&quot;]) </code></pre> <p>does not work.</p> <p>I came up with the following solution</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path config_list = [&quot;~&quot;, &quot;temp&quot;, &quot;machine_name&quot;] # is actually parsed from the toml path_list = [Path(x) for x in config_list] path_obj = Path(*path_list) </code></pre> <p>but I'm not sure if this is best practice or the pythonic way of achieving my goal. I'm also open to suggestions on how to otherwise save a general path in a config.</p>
<python><python-3.x><pathlib><toml>
2023-01-31 09:23:38
1
405
sebwr
75,294,852
11,710,304
String manipulation in polars
<p>I have a record in polars which has no header so far. This header should refer to the first row of the record. Before I instantiate this row as header, I want to manipulate the entries.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl # Creating a dictionary with the data data = { &quot;Column_1&quot;: [&quot;ID&quot;, 4, 4, 4, 4], &quot;Column_2&quot;: [&quot;LocalValue&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;], &quot;Column_3&quot;: [&quot;Data\nField&quot;, &quot;Q&quot;, &quot;R&quot;, &quot;S&quot;, &quot;T&quot;], &quot;Column_4&quot;: [None, None, None, None, None], &quot;Column_5&quot;: [&quot;Global Value&quot;, &quot;G&quot;, &quot;H&quot;, &quot;I&quot;, &quot;J&quot;], } # Creating the dataframe table = pl.DataFrame(data, strict=False) print(table) </code></pre> <pre><code>shape: (5, 5) ┌──────────┬────────────┬──────────┬──────────┬──────────────┐ │ Column_1 ┆ Column_2 ┆ Column_3 ┆ Column_4 ┆ Column_5 │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ null ┆ str │ ╞══════════╪════════════╪══════════╪══════════╪══════════════╡ │ ID ┆ LocalValue ┆ Data ┆ null ┆ Global Value │ │ ┆ ┆ Field ┆ ┆ │ │ 4 ┆ B ┆ Q ┆ null ┆ G │ │ 4 ┆ C ┆ R ┆ null ┆ H │ │ 4 ┆ D ┆ S ┆ null ┆ I │ │ 4 ┆ E ┆ T ┆ null ┆ J │ └──────────┴────────────┴──────────┴──────────┴──────────────┘ </code></pre> <p>First, I want to replace line breaks and spaces between words with an underscore. Furthermore I want to fill Camel Cases with an underscore (e.g. TestTest -&gt; Test_Test). Finally, all entries should be lowercase. For this I wrote the following function:</p> <pre class="lang-py prettyprint-override"><code>def clean_dataframe_columns(df): header = list(df.head(1).transpose().to_series()) cleaned_headers = [] for entry in header: if entry: entry = ( entry.replace(&quot;\n&quot;, &quot;_&quot;) .replace(&quot;(?&lt;=[a-z])(?=[A-Z])&quot;, &quot;_&quot;) .replace(&quot;\s&quot;, &quot;_&quot;) .to_lowercase() ) else: entry = &quot;no_column&quot; cleaned_headers.append(entry) df.columns = cleaned_headers return df </code></pre> <p>Unfortunately I have the following error. What am I doing wrong?</p> <pre><code># AttributeError: 'int' object has no attribute 'replace' </code></pre> <p>The goal should be this dataframe:</p> <pre><code>shape: (4, 5) ┌─────┬─────────────┬────────────┬───────────┬──────────────┐ │ id ┆ local_value ┆ data_field ┆ no_column ┆ global_value │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ f64 ┆ str │ ╞═════╪═════════════╪════════════╪═══════════╪══════════════╡ │ 4 ┆ B ┆ Q ┆ null ┆ G │ │ 4 ┆ C ┆ R ┆ null ┆ H │ │ 4 ┆ D ┆ S ┆ null ┆ I │ │ 4 ┆ E ┆ T ┆ null ┆ J │ └─────┴─────────────┴────────────┴───────────┴──────────────┘ </code></pre>
<python><string><dataframe><python-polars>
2023-01-31 09:11:32
2
437
Horseman
75,294,739
10,488,923
Rocket UniData/UniVerse: ODBC Unable to allocate sufficient memory
<p>Whenever I tried using <code>pyodbc</code> to connect to a Rocket UniData/UniVerse data I kept running into the error:</p> <pre><code>pyodbc.Error: ('00000', '[00000] [Rocket U2][U2ODBC][0302810]Unable to allocate sufficient memory! (0) (SQLDriverConnect); [00000] [Rocket U2][U2ODBC][0400182]Connection not open. (0)') </code></pre> <p>My code looks as follows:</p> <pre><code>import pyodbc conStr = 'Driver={U2 64-Bit ODBC};Database=myDb;Server=localhost;UID=user;PWD=password' conn = pyodbc.connect(conStr) cursor = conn.cursor() </code></pre>
<python><odbc><pyodbc><universe><unidata>
2023-01-31 09:01:16
1
989
Kagiso Marvin Molekwa
75,294,735
10,829,044
Sort column names using wildcard using pandas
<p>I have a big dataframe with more than 100 columns. I am sharing a miniature version of my real dataframe below</p> <pre><code>ID rev_Q1 rev_Q5 rev_Q4 rev_Q3 rev_Q2 tx_Q3 tx_Q5 tx_Q2 tx_Q1 tx_Q4 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 </code></pre> <p>I would like to do the below</p> <p>a) sort the column names based on Quarters (ex:Q1,Q2,Q3,Q4,Q5..Q100..Q1000) for each column pattern</p> <p>b) By column pattern, I mean the keyword that is before underscore which is <code>rev</code> and <code>tx</code>.</p> <p>So, I tried the below but it doesn't work and it also shifts the <code>ID</code> column to the back</p> <pre><code>df = df.reindex(sorted(df.columns), axis=1) </code></pre> <p>I expect my output to be like as below. In real time, there are more than 100 columns with more than 30 patterns like <code>rev</code>, <code>tx</code> etc. I want my <code>ID</code> column to be in the first position as shown below.</p> <pre><code>ID rev_Q1 rev_Q2 rev_Q3 rev_Q4 rev_Q5 tx_Q1 tx_Q2 tx_Q3 tx_Q4 tx_Q5 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 </code></pre>
<python><pandas><string><list><dataframe>
2023-01-31 09:01:08
3
7,793
The Great
75,294,711
9,879,869
What would be the best way to return the result of asynchronous task to Django views?
<p>I am building a Djano app that processes image in a Celery task. A post inside the view method handles the input and triggers the task. Inside the task, I create a model instance based on the processed image. In the same view, I wanted to return a response of the de-serialization of the model instance. What is the best way to throw this response? Should a frontend expect this on another url? How can I signal my app that the model instance is ready to be served?</p> <pre><code># models.py class Image(models.Model): name = models.CharField(max_length=50, blank=True) ... # tasks.py @shared_task def long_running_function(user, data): image = Image.objects.create() ... return image # ? # views.py class RequestImage(APIView): def post(self, request): ... image = celery_task_example.delay( request.user.id, request.data ) # if image is ready serializer = ImageSerializer(image) return Response(serializer.data) </code></pre>
<python><django><asynchronous><django-rest-framework><celery>
2023-01-31 08:58:37
0
1,572
Nikko
75,294,710
7,657,180
Count pages on tiff raises TypeError: int() argument must be a string
<p>I am working on some images with tiff extension and I have a step that I should count the pages of each tiff image Here's my try till now</p> <pre><code>from pathlib import Path from PIL import Image import os def count_pages(img): i = 0 while True: try: img.seek(i) except EOFError: break i += 1 return i BASE_DIR = Path.cwd() IDs_DIR = BASE_DIR / 'FLDR' sPath = os.path.join(IDs_DIR, 'ggg.tiff') im = Image.open(sPath) print(count_pages(im)) </code></pre> <p>But with some of the tiff (not all of them), I encountered an error like that</p> <pre><code>site-packages\PIL\TiffImagePlugin.py:845: UserWarning: Corrupt EXIF data. Expecting to read 2 bytes but only got 0. warnings.warn(str(msg)) Traceback (most recent call last): File &quot;Demo.py&quot;, line 19, in &lt;module&gt; print(count_pages(im)) File &quot;Demo.py&quot;, line 9, in count_pages img.seek(i) File &quot;C:\Users\Future\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\TiffImagePlugin.py&quot;, line 1101, in seek self._seek(frame) File &quot;C:\Users\Future\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\TiffImagePlugin.py&quot;, line 1142, in _seek self._setup() File &quot;C:\Users\Future\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\TiffImagePlugin.py&quot;, line 1333, in _setup xsize = int(self.tag_v2.get(IMAGEWIDTH)) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' </code></pre>
<python><python-imaging-library>
2023-01-31 08:58:35
1
9,608
YasserKhalil
75,294,667
5,641,924
Flatten a column with nested dictionary in pandas
<p>I fetch data from MySQL database. The fetched data has a column with nested lists and dictionaries. This json is similar to the stored data in my database:</p> <pre><code>my_dict = {'id': [1, 2, 3], 'b': [{'100': [{'p': 10, 'max': 20, 'min': 15}, {'p': 20, 'max': 30, 'min': 20}] }, {'101': [{'p': 100, 'max': 200, 'min': 150}], '102': [{'p': 105, 'max': 205, 'min': 155}, {'p': 102, 'max': 202, 'min': 152}]}, {'103': [{'p': 210, 'max': 2110, 'min': 1115}]}]} </code></pre> <p>and in code, I have <code>df</code> only:</p> <pre><code>df = pd.DataFrame(my_dict) df id b 0 1 {'100': [{'p': 10, 'max': 20, 'min': 15}, {'p': 20, 'max': 30, 'min': 20}]} 1 2 {'101': [{'p': 100, 'max': 200, 'min': 150}], '102': [{'p': 105, 'max': 205, 'min': 155}, {'p': 102, 'max': 202, 'min': 152}]} 2 3 {'103': [{'p': 210, 'max': 2110, 'min': 1115}]} </code></pre> <p>Now, I want to flat the column <code>b</code> like the following:</p> <pre><code>df id key p max min 0 1 100 10 20 15 1 1 100 20 30 20 2 2 101 100 200 150 3 2 102 105 205 155 4 2 102 102 202 152 5 3 103 210 2120 1115 </code></pre> <p>I read about the <code>explode</code> and <code>pd.json_normalize</code>. But they did not help. What is the most efficient solution for this problem?</p>
<python><pandas>
2023-01-31 08:53:30
2
642
Mohammadreza Riahi
75,294,639
12,769,783
Onnxruntime: inference with CUDNN on GPU only working if pytorch imported first
<p>I am trying to perform inference with the onnxruntime-gpu. Therefore, I installed CUDA, CUDNN and onnxruntime-gpu on my system, and checked that my GPU was compatible (versions listed below).</p> <p>When I attempt to start an inference session, I receive the following warning:</p> <pre class="lang-bash prettyprint-override"><code>&gt;&gt;&gt; import onnxruntime as rt &gt;&gt;&gt; rt.get_available_providers() ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] &gt;&gt;&gt; rt.InferenceSession(&quot;[ PATH TO MODEL .onnx]&quot;, providers= ['CUDAExecutionProvider']) 2023-01-31 09:07:03.289984495 [W:onnxruntime:Default, onnxruntime_pybind_state.cc:578 CreateExecutionProviderInstance] Failed to create CUDAExecutionProvider. Please reference https://onnxruntime.ai/docs/reference/execution-providers/CUDA-ExecutionProvider.html#requirements to ensure all dependencies are met. &lt;onnxruntime.capi.onnxruntime_inference_collection.InferenceSession object at 0x7f740b4af100&gt; </code></pre> <p>However, <a href="https://stackoverflow.com/questions/75267445/why-does-onnxruntime-fail-to-create-cudaexecutionprovider-in-linuxubuntu-20/75267493#75267493">if I import torch first</a>, inference runs on my GPU, and I see my python program listed under nvidia-smi as soon as I start the inference session:</p> <pre class="lang-bash prettyprint-override"><code>$ python Python 3.8.16 (default, Dec 7 2022, 01:12:06) [GCC 11.3.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import torch &gt;&gt;&gt; import onnxruntime as rt &gt;&gt;&gt; sess = rt.InferenceSession(&quot;PATH TO MODEL . onnx&quot;, providers=['CUDAExecutionProvider']) &gt;&gt;&gt; </code></pre> <p>Does anyone know why this is the case? The import order is important; if I import torch after importing the onnxruntime, I receive the same warning as if I hadn't imported torch.</p> <p>I checked the <code>__init__</code> of the torch package, and tracked down the helpful lines of code to loading <code>libtorch_global_deps.so</code>:</p> <pre class="lang-py prettyprint-override"><code> import ctypes lib_path = '[ path to my .venv38]/lib/python3.8/site-packages/torch/lib/libtorch_global_deps.so' ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL) </code></pre> <pre class="lang-bash prettyprint-override"><code>$ python Python 3.8.16 (default, Dec 7 2022, 01:12:06) [GCC 11.3.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import ctypes &gt;&gt;&gt; lib_path = '[ path to my .venv38]/lib/python3.8/site-packages/torch/lib/libtorch_global_deps.so' &gt;&gt;&gt; ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL) &gt;&gt;&gt; import onnxruntime as rt &gt;&gt;&gt; sess = rt.InferenceSession(&quot;PATH TO MODEL . onnx&quot;, providers=['CUDAExecutionProvider']) &gt;&gt;&gt; </code></pre> <p>also does the trick.</p> <h3>Installed versions</h3> <ul> <li>NVIDIA-SMI 510.108.03</li> <li>Driver Version: 510.108.03</li> <li>CUDA Version: 11.6</li> <li>CuDNN Version: cudnn-11.4-linux-x64-v8.2.4.15</li> <li>onnx==1.12.0</li> <li>onnxruntime-gpu==1.13.1</li> <li>torch==1.12.1+cu116</li> <li>torchvision==0.13.1+cu116</li> <li>Python version 3.8</li> <li>Ubuntu 22.04 5.19.3-051903-generic</li> </ul> <p>Python packages installed in a virtual environemnt.</p>
<python><pytorch><onnxruntime>
2023-01-31 08:50:24
0
1,596
mutableVoid
75,294,630
7,800,760
Python: best way to check for list of URLs
<p>I have a file defining a list of RSS feeds:</p> <pre><code>RSS_FEEDS = [ &quot;https://www.fanpage.it/feed/&quot;, &quot;https://www.ilfattoquotidiano.it/feed/&quot;, &quot;https://forbes.it/feed/&quot;, &quot;https://formiche.net/feed/&quot;, ] </code></pre> <p>I wrote the following test:</p> <pre><code>import requests from feeds import RSS_FEEDS for rssfeed in RSS_FEEDS: response = requests.get(rssfeed) assert response.status_code == 200 </code></pre> <p>Are there more efficient (download less stuff) ways?</p> <p>How would you handle a slow response vs a dead link?</p> <p>The above would just tell me if the URL is fetchable, but how could I assess if it's a valid RSS stream?</p>
<python><unit-testing><rss>
2023-01-31 08:49:24
2
1,231
Robert Alexander
75,294,337
5,159,404
how to align matplotlib graphs
<p>I am plotting two different graphs with matplotlib. The two plots are separate and must be kept that way since I am saving them onto file and have different uses for them.</p> <p>As it can be seen on the picture below they are misaligned because the ylabels on the top graph are occupying more space than the one on the bottom. Is there a way to fix the width occupied by the labels? I have tried:</p> <pre class="lang-py prettyprint-override"><code>ax.set_ylabel('Y Axis Label', labelpad=50) </code></pre> <p>But it didn't do much</p> <p>Importantly, I cannot change the label format (scientific or other).</p> <p><a href="https://i.sstatic.net/fODWQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fODWQ.png" alt="enter image description here" /></a></p> <p>the whole function that produces the single graph follows:</p> <pre class="lang-py prettyprint-override"><code>def prepare_plot(inputDataFrame : pd.DataFrame(), median_columns : list(str()), upper_lower_quantiles : int, labels : list(str())) : &quot;&quot;&quot; inputDataFrame: dataframe with values median_columns: names of the columns to be used for median values upper_lower_quantiles: Delta (1, 2 or 3) compared to the median, if invalid input will default to 1 labels: labels to be set &quot;&quot;&quot; if upper_lower_quantiles not in [1,2,3] : upper_lower_quantiles = 1 flike = io.BytesIO() df = inputDataFrame x = df.index fig, ax = plt.subplots() fig.set_size_inches(15, 5) colors = ['g','r','b'] for median, label, color in zip(median_columns,labels, colors): lower = median[:-1] + f'{3 - upper_lower_quantiles}' upper = median[:-1] + f'{3 + upper_lower_quantiles}' try: ax.plot(x, df[median], label=label, color=color) ax.fill_between(x, df[lower], #Lower Bound df[upper], #Upper Bound color=color, alpha=.1 ) except: print(f'Error on Key ({median}), label ({label}), color ({color})') print(f'Not graphing the line') ax.grid() lgd = ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5), fontsize=10) fig.savefig(flike, bbox_extra_artists=(lgd,), bbox_inches='tight') b64 = base64.b64encode(flike.getvalue()).decode() #Saving in a format that is embeddable in different other platforms return b64 </code></pre>
<python><matplotlib>
2023-01-31 08:20:38
0
1,002
Wing
75,294,118
10,731,820
How to pass parameters from one Pass state to another?
<p>How to pass parameters from one Pass state to another? <code>aws_stepfunctions.JsonPath.string_at</code> is working fine when invoking lambda function (insude <code>aws_stepfunctions.TaskInput.from_object</code>) but it is not working with Pass state (inside <code>aws_stepfunctions.Result.from_object</code></p> <p>I have:</p> <pre><code>initial_pass = aws_stepfunctions.Pass( self, &quot;initial_pass&quot;, result=aws_stepfunctions.Result.from_object( { &quot;iterator&quot;: {&quot;count&quot;: 5, &quot;index&quot;: 0, &quot;step&quot;: 1, &quot;continue&quot;: True}, &quot;globals&quot;: { &quot;start_datetime&quot;: &quot;2023-01-01&quot;, &quot;end_datetime&quot;: &quot;&quot;, &quot;upload_start_datetime&quot;: &quot;&quot;, &quot;upload_end_datetime&quot;: &quot;&quot;, &quot;device_details&quot;: {}, }, } ) ) second_pass = aws_stepfunctions.Pass( self, &quot;second_pass&quot;, result=aws_stepfunctions.Result.from_object( { &quot;iterator&quot;: {&quot;count&quot;: 5, &quot;index&quot;: 0, &quot;step&quot;: 1, &quot;continue&quot;: True}, &quot;globals&quot;: aws_stepfunctions.JsonPath.string_at(&quot;$.globals&quot;), } ), ) </code></pre> <p>I am getting this as output:</p> <pre><code>{ &quot;iterator&quot;: { &quot;count&quot;: 5, &quot;index&quot;: 0, &quot;step&quot;: 1, &quot;continue&quot;: true }, &quot;globals&quot;: &quot;$.globals&quot; } </code></pre>
<python><amazon-web-services><aws-cdk>
2023-01-31 07:54:51
2
853
psowa001
75,293,876
3,247,006
How to reduce more `SELECT` queries which are already reduced by "prefetch_related()" to iterate 3 or more models?
<p>I have <code>Country</code>, <code>State</code> and <code>City</code> models which are chained by foreign keys as shown below:</p> <pre class="lang-py prettyprint-override"><code>class Country(models.Model): name = models.CharField(max_length=20) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=20) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=20) </code></pre> <p>Then, I iterate <code>Country</code> and <code>State</code> models with <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related" rel="nofollow noreferrer">prefetch_related()</a> as shown below:</p> <pre class="lang-py prettyprint-override"><code>for country_obj in Country.objects.prefetch_related(&quot;state_set&quot;).all(): for state_obj in country_obj.state_set.all(): print(country_obj, state_obj) </code></pre> <p>Then, 2 <code>SELECT</code> queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see <a href="https://stackoverflow.com/questions/722221/how-to-log-postgresql-queries#answer-75031321">my answer</a> explaining how to enable and disable the query logs on PostgreSQL:</p> <p><a href="https://i.sstatic.net/8zR77.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8zR77.png" alt="enter image description here" /></a></p> <p>Next, I iterate <code>Country</code>, <code>State</code> and <code>City</code> models with prefetch_related() as shown below:</p> <pre class="lang-py prettyprint-override"><code>for country_obj in Country.objects.prefetch_related(&quot;state_set__city_set&quot;).all(): for state_obj in country_obj.state_set.all(): for city_obj in state_obj.city_set.all(): print(country_obj, state_obj, city_obj) </code></pre> <p>Then, 3 <code>SELECT</code> queries are run as shown below:</p> <p><a href="https://i.sstatic.net/6nP8A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6nP8A.png" alt="enter image description here" /></a></p> <p>Now, how can I reduce 3 <code>SELECT</code> queries to 2 <code>SELECT</code> queries or less for the example just above iterating <code>Country</code>, <code>State</code> and <code>City</code> models with <code>prefetch_related()</code>?</p>
<python><django><postgresql><django-models><django-prefetch-related>
2023-01-31 07:28:40
1
42,516
Super Kai - Kazuya Ito
75,293,854
6,494,707
How to convert the radius from meter to pixel?
<p>I have a camera with these specs:</p> <ul> <li>full resolution 1280x1024</li> <li>pixel size 0.0048mm</li> <li>focal length 8 mm</li> </ul> <p>I need to detect a ball in this image. It is 4 meters away and its radius is 0.0373 meter.</p> <p>How to convert the radius to from meter to pixel in this case?</p> <p>the reason is that I need to use <a href="https://docs.opencv.org/3.4/d3/de5/tutorial_js_houghcircles.html" rel="nofollow noreferrer">cv2.HoughCircles()</a> and need to have the value for this function.</p>
<python><opencv><image-processing><geometry><camera-calibration>
2023-01-31 07:26:25
1
2,236
S.EB
75,293,732
8,034,918
How to resolve ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor
<p>I am trying to get the embedding for a siamese network written in keras and I keep having the issue below. Does anyone know how to solve this issue?</p> <p>Here is the network:</p> <pre><code>input = layers.Input((40, 1)) x = layers.Conv1D(8, 64, activation=&quot;relu&quot;, padding='same', kernel_regularizer=regularizers.L1L2(l1=1e-5, l2=1e-4),)(input) x = layers.Conv1D(8, 128, activation=&quot;relu&quot;, padding='same', kernel_regularizer=regularizers.L1L2(l1=1e-5, l2=1e-4),)(x) x = layers.AveragePooling1D(pool_size= 2, padding='same')(x) x = layers.Flatten()(x) x = layers.Dense(100, activation=&quot;relu&quot;)(x) embedding_network = keras.Model(input, x) input_1 = layers.Input((40, 1)) input_2 = layers.Input((40, 1)) cnn_1 = embedding_network(input_1) cnn_2 = embedding_network(input_2) merge_layer_1 = layers.Lambda(euclidean_distance)([cnn_1, cnn_2]) output_layer = layers.Dense(1, activation=&quot;sigmoid&quot;)(merge_layer_1) siamese = keras.Model(inputs=[input_1, input_2], outputs=output_layer) </code></pre> <p>Here is the what it is done to get the embedding:</p> <pre><code>get_layer_output = tf.keras.backend.function([siamese.layers[0].input],[siamese.layers[-2].output]) </code></pre> <p>Here is the error:</p> <pre><code>ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(None, 40, 1), dtype=tf.float32, name='input_3'), name='input_3', description=&quot;created by layer 'input_3'&quot;) at layer &quot;model&quot;. The following previous layers were accessed without issue: ['model'] </code></pre>
<python><tensorflow><keras>
2023-01-31 07:12:03
1
439
user8034918
75,293,644
2,989,330
GUnicorn: Queue not working after re-starting worker
<h2>Problem Statement</h2> <p>After booting the GUnicorn worker processes, I want the worker processes still be able to receive data from another process. Currently, I'm trying to use <code>multiprocessing.Queue</code> to achieve this. Specifically, I start a data management process before forking the workers and use two queues to connect it with the workers. One queue is for the workers to request data from the data management process, the other to receive the data. In the <code>post_fork</code> hook, a worker sends out a request to the request queue and receives a response on the response queue, and only then proceeds to serving the application.</p> <p>This works fine at first. However, when I manually terminate the workers and gunicorn restarts it, it will get stuck in the <code>post_fork</code> method and never receive a response from the data management process.</p> <h2>Minimal Example</h2> <p>The following code shows a minimal example (<code>config.py</code>):</p> <pre><code>import logging import os import multiprocessing logging.basicConfig(level=logging.INFO) bind = &quot;localhost:8080&quot; workers = 1 def s(req_q: multiprocessing.Queue, resp_q: multiprocessing.Queue): while True: logging.info(&quot;Waiting for messages&quot;) other_pid = req_q.get() logging.info(&quot;Got a message from %d&quot;, other_pid) resp_q.put(os.getpid()) m = multiprocessing.Manager() q1 = m.Queue() q2 = m.Queue() proc = multiprocessing.Process(target=s, args=(q1, q2), daemon=True) proc.start() def post_fork(server, worker): logging.info(&quot;Sending request&quot;) q1.put(os.getpid()) logging.info(&quot;Request sent&quot;) other_pid = q2.get() logging.info(&quot;Got response from %d&quot;, other_pid) </code></pre> <p>My application module (<code>app.py</code>) is:</p> <pre><code>from flask import Flask app = Flask(__name__) </code></pre> <p>And I start the server via</p> <pre><code>$ gunicorn -c config.py app:app INFO:root:Waiting for messages [2023-01-31 14:20:46 +0800] [24553] [INFO] Starting gunicorn 20.1.0 [2023-01-31 14:20:46 +0800] [24553] [INFO] Listening at: http://127.0.0.1:8080 (24553) [2023-01-31 14:20:46 +0800] [24553] [INFO] Using worker: sync [2023-01-31 14:20:46 +0800] [24580] [INFO] Booting worker with pid: 24580 INFO:root:Sending request INFO:root:Request sent INFO:root:Got a message from 24580 INFO:root:Waiting for messages INFO:root:Got response from 24574 </code></pre> <p>The log shows that the messages were successfully exchanged. Now, we'll stop the worker process and let gunicorn restart it:</p> <pre><code>$ kill 24580 [2023-01-31 14:22:40 +0800] [24580] [INFO] Worker exiting (pid: 24580) Error in atexit._run_exitfuncs: Traceback (most recent call last): File &quot;/usr/lib/python3.6/multiprocessing/util.py&quot;, line 319, in _exit_function p.join() File &quot;/usr/lib/python3.6/multiprocessing/process.py&quot;, line 122, in join assert self._parent_pid == os.getpid(), 'can only join a child process' AssertionError: can only join a child process [2023-01-31 14:22:40 +0800] [24553] [WARNING] Worker with pid 24574 was terminated due to signal 15 [2023-01-31 14:22:40 +0800] [29497] [INFO] Booting worker with pid: 29497 INFO:root:Sending request INFO:root:Request sent </code></pre> <h2>Question</h2> <p>Why doesn't <code>s</code> receive the message from the worker after re-starting?</p> <p>Besides, why am I getting this 'can only join a child process' error thrown? Does it has something to do with the problem?</p> <h2>Environment</h2> <ul> <li>Python: 3.8.0</li> <li>GUnicorn: 20.1.0</li> <li>OS: Ubuntu 18.04</li> </ul> <h2>Related Questions</h2> <p>In <a href="https://stackoverflow.com/questions/46657799/multiprocessing-queue-cant-get-data-after-gunicorn-worker-timeout">this question</a>, a similar problem is presented, and the solution was to use &quot;<em>multiprocessing.manager.queue</em>&quot;. However, this didn't solved the issue in my case.</p> <h2>Side Note</h2> <p>I already considered the following alternative designs:</p> <ul> <li>Use HTTP/gRPC/... to share the data: The data that I need to share isn't serializable</li> <li>Use <code>threading.Thread</code> instead of <code>multiprocessing.Process</code> for the data management process: The data management process initializes an object that will throw an error when it is forked, so I cannot initialize this object within the GUnicorn master process.</li> </ul>
<python><multiprocessing><queue><python-multiprocessing><gunicorn>
2023-01-31 07:01:35
1
3,203
Green 绿色
75,293,413
1,173,495
importlib.metadata error on pre-commit tool
<p>I have installed pre-commit 3.0.1 via asdf. When I try to run pre-commit -v throwing the following error</p> <pre><code>Traceback (most recent call last): File &quot;/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/python&quot;, line 47, in &lt;module&gt; raise SystemExit(main()) File &quot;/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/python&quot;, line 34, in main runpy.run_module(args.m, run_name='__main__', alter_sys=True) File &quot;/Users/san/.pyenv/versions/3.7.9/lib/python3.7/runpy.py&quot;, line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File &quot;/Users/san/.pyenv/versions/3.7.9/lib/python3.7/runpy.py&quot;, line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File &quot;/Users/san/.pyenv/versions/3.7.9/lib/python3.7/runpy.py&quot;, line 85, in _run_code exec(code, run_globals) File &quot;/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/wheels/pre_commit-3.0.1-py2.py3-none-any.whl/pre_commit/__main__.py&quot;, line 3, in &lt;module&gt; File &quot;/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/wheels/pre_commit-3.0.1-py2.py3-none-any.whl/pre_commit/main.py&quot;, line 9, in &lt;module&gt; File &quot;/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/wheels/pre_commit-3.0.1-py2.py3-none-any.whl/pre_commit/constants.py&quot;, line 3, in &lt;module&gt; ModuleNotFoundError: No module named 'importlib.metadata' </code></pre> <p>Python version: <strong>3.7.9</strong></p> <p>asdf version: <strong>v0.11.1</strong></p>
<python><pre-commit><pre-commit.com><asdf>
2023-01-31 06:32:04
4
10,189
SANN3
75,293,337
1,670,830
How to print the value of a variable in the stack trace
<p>I want to print in the stack trace the value of a variable.</p> <p>Indeed, when executing my program, I have an error and I would like to know the value of a variable.</p> <p>I don't have access to the console.</p> <hr /> <p>code:</p> <pre><code>os.chdir(directoryName) </code></pre> <p>Error:</p> <blockquote> <p>os.chdir(directoryName) FileNotFoundError: [Errno 2] No such file or directory: '' »</p> </blockquote>
<python>
2023-01-31 06:21:13
2
3,563
Colas
75,293,289
14,808,637
Adjacency matrix using numpy
<p>I need to generate the following adjacency matrices:</p> <p><strong>No of Nodes = 3</strong></p> <pre><code> A B C AB AC BC A 0 1 1 0 0 1 B 1 0 1 0 1 0 C 1 1 0 1 0 0 AB 0 0 1 0 0 0 AC 0 1 0 0 0 0 BC 1 0 0 0 0 0 </code></pre> <p>To generate an adjacency matrix for 3 nodes, I can use the code available <a href="https://stackoverflow.com/questions/75285357/graph-edges-intialization-between-nodes-using-numpy">here</a>, which is</p> <pre><code>out = np.block([ [1 - np.eye(3), np.eye(3) ], [ np.eye(3), np.zeros((3, 3))] ]).astype(int) </code></pre> <p>But it cannot use for different number of nodes, for example if we have 5 nodes then:</p> <p><strong>No of Nodes = 5</strong></p> <pre><code> A B C D E AB AC AD AE BC BD BE CD CE DE A 0 1 1 1 1 0 0 0 0 1 1 1 1 1 1 B 1 0 1 1 1 0 1 1 1 0 0 0 1 1 1 C 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 D 1 1 1 0 1 1 1 0 1 1 0 1 0 1 0 E 1 1 1 1 0 1 1 1 0 1 1 0 1 0 0 AB 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 AC 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 AD 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 AE 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 BC 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 BD 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 BE 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 CD 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 CE 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 DE 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>Is there any simple and easiest way to implement these adjacency matrices?</p>
<python><numpy><adjacency-matrix>
2023-01-31 06:13:28
1
774
Ahmad
75,293,254
6,660,638
How to remove space in cluster in python diagrams
<p>I am generating cluster with the below code</p> <pre class="lang-py prettyprint-override"><code>from diagrams import Diagram, Cluster, Node with Diagram('./output/output', show=False, outformat='svg') as d: with Cluster('cluster'): n1 = Node('A', height = '0.5', width = '5', labelloc = &quot;c&quot;, fillcolor = 'purple', fontcolor = 'white', style = 'filled') n2 = Node('B', height = '0.5', width = '5', labelloc = &quot;c&quot;, fillcolor = 'purple', fontcolor = 'white', style = 'filled') n3 = Node('C', height='0.5', width='5', labelloc=&quot;c&quot;, fillcolor='purple', fontcolor='white', style='filled') n4 = Node('D', height='0.5', width='5', labelloc=&quot;c&quot;, fillcolor='purple', fontcolor='white', style='filled') </code></pre> <p>The generated diagram <a href="https://i.sstatic.net/SmQyz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SmQyz.png" alt="enter image description here" /></a></p> <p>As you can see there is lot of space between Node(A), Node(B), Node(C) etc. Does anyone know how to remove this?</p>
<python><graphviz><diagram>
2023-01-31 06:07:07
1
9,097
Epsi95
75,293,239
2,218,321
Python3 error No module named 'attrs' when running Scrapy in Ubuntu terminal
<p>I am new to Python. I installed Scrapy on ubuntu linux. When I run <code>Scrapy shell</code> I get this error</p> <pre><code> File &quot;/home/user/.local/lib/python3.10/site-packages/scrapy/downloadermiddlewares/retry.py&quot;, line 25, in &lt;module&gt; from twisted.web.client import ResponseFailed File &quot;/home/user/.local/lib/python3.10/site-packages/twisted/web/client.py&quot;, line 24, in &lt;module&gt; from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS File &quot;/home/user/.local/lib/python3.10/site-packages/twisted/internet/endpoints.py&quot;, line 63, in &lt;module&gt; from twisted.python.systemd import ListenFDs File &quot;/home/user/.local/lib/python3.10/site-packages/twisted/python/systemd.py&quot;, line 18, in &lt;module&gt; from attrs import Factory, define ModuleNotFoundError: No module named 'attrs' </code></pre> <p>I also already ran the commands</p> <pre><code>python3.10 -m pip install attrs pip install attrs </code></pre> <p>with the result</p> <blockquote> <p>Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: attrs in /usr/lib/python3/dist-packages (21.2.0)</p> </blockquote>
<python><python-3.x><scrapy>
2023-01-31 06:05:14
3
2,189
M a m a D
75,293,146
2,543,424
Unable to import definitions from submodule package
<p>I have a project that uses a git submodule to import a python package from a private repository, which is then installed via pip. The structure is something like this:</p> <pre><code>my_project _submodules prvt_pkg prvt_pkg lib __init__.py types.py __init__.py prvt_pkg.py setup.py requirements.txt app.py </code></pre> <p>(not sure if this makes a difference, but <code>setup.py</code> looks like this:</p> <pre class="lang-py prettyprint-override"><code>import setuptools from setuptools import find_packages with open(&quot;readme.md&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as fh: long_description = fh.read() setuptools.setup( name='prvt_pkg', version='0.0.1', author='...', author_email='...', description='...', long_description=long_description, long_description_content_type=&quot;text/markdown&quot;, url='...', project_urls={ &quot;Bug Tracker&quot;: &quot;...&quot; }, packages=find_packages(), install_requires=[], ) </code></pre> <p>I am able to import the main class from <code>prvt_pkg.py</code> like</p> <pre class="lang-py prettyprint-override"><code>from prvt_pkg.prvt_pkg import my_prvt_class </code></pre> <p>however, I would also like to import the pydantic types defined in <code>_submodules/prvt_pkg/prvt_pkg/lib/types.py</code> like</p> <pre class="lang-py prettyprint-override"><code>from prvt_pkg.lib.types import MyType </code></pre> <p>but PyCharm is telling me that won't work</p> <p>All of the <code>__init__.py</code> files are empty.</p> <p>Is there a way that I can achieve this? Thanks in advance</p>
<python><python-3.x>
2023-01-31 05:50:54
1
1,301
e-e
75,293,106
4,897,973
Shared code library between Docker containers
<p>I've seen a related question from 2017 <a href="https://stackoverflow.com/questions/46135315/cp-vs-rsync-vs-something-faster">here</a> and the linked GitHub discussion from 2014 <a href="https://github.com/moby/moby/issues/1676" rel="nofollow noreferrer">here</a>, but this behavior really doesn't make sense to me and I'd like to know if there is any good workaround for it.</p> <p>Currently, I'm working on a project which has a single git repository as the root directory and multiple subdirectories which each contain a service I'm running in separate docker containers. This has worked well up until now since there was not any shared code between these services, however, as projects evolve requirements change and I've created a small code library which I'd like to share between two services. This library is not big enough to warrent something like a git submodule, but it's not small enough that I would want to have to make all updates twice if the code were duplicated.</p> <p>ex. In the project root, I have two directories <code>Foo</code> and <code>Bar</code> which will both contain a support library <code>FooBar</code>. The directory structure I would like is then something like this:</p> <pre><code>&lt;root&gt; | +- Foo | | | +- FooBar | | | +- Dockerfile | +- Bar | | | +- FooBar | | | +- Dockerfile </code></pre> <p>where <code>FooBar</code> contains the same source files in both instances. My instinctive solution here is to simply create a symlink, ex. <code>Foo/FooBar</code> is a link to <code>../Bar/FooBar</code> where the source reside. As per the linked question/discussion, this is not supported. The reasoning given in the GitHub discussion does make sense, if the symlink could point anywhere on the host system, I can imagine many bad outcomes would be possible, but in my specific instance, these two services will never be deployed separately and the symlink simply points to another docker image's source. If I setup the symlinks as I want, the Dockerfile COPY command seems to just copy the link as-is, so it becomes a dead link in the destination image. I would prefer it follow the symlink and copy the file itself.</p> <p>I'm not an expert on the workings of docker, and while I've read some of the documentation, it's totally possible that I missed an easy solution to this problem. Is there any way for me to setup this directory structure so that there is only a single master copy of the shared code which can be referenced from both of my services? These specific services are developed in Python and the <code>FooBar</code> library is a python module if that makes any difference.</p>
<python><docker><web-services><dockerfile>
2023-01-31 05:44:31
1
1,228
beeselmane
75,293,068
10,829,044
pandas split string and extract upto n index position
<p>I have my input data like as below stored in a dataframe column</p> <pre><code>active_days_revenue active_days_rate total_revenue gap_days_rate </code></pre> <p>I would like to do the below</p> <p>a) split the string using <code>_</code> delimiter</p> <p>b) extract <code>n</code> elements from the delimiter</p> <p>So, I tried the below</p> <pre><code>df['text'].split('_')[:1] # but this doesn't work df['text'].split('_')[0] # this works but returns only the 1st element </code></pre> <p>I expect my output like below. Instead of just getting items based on <code>0 index position</code>, I would like to get from <code>0 to 1st index position</code></p> <pre><code>active_days active_days total_revenue gap_days </code></pre>
<python><pandas><string><list><dataframe>
2023-01-31 05:38:50
1
7,793
The Great
75,293,047
11,235,205
Pytorch: Is there a way to implement layer-wise learning rate decay when using a Scheduler?
<p>I want to implement the layer-wise learning rate decay while still using a Scheduler. Specifically, what I currently have is:</p> <pre class="lang-py prettyprint-override"><code>model = Model() optim = optim.Adam(lr=0.1) scheduler = optim.lr_scheduler.OneCycleLR(optim, max_lr=0.1) </code></pre> <p>Then, the learning rate is increased to <code>0.1</code> in the first 30% of the epochs and gradually decays over time. I want to further add this with layer-wise Learning rate decay.</p> <p><a href="https://kozodoi.me/python/deep%20learning/pytorch/tutorial/2022/03/29/discriminative-lr.html" rel="nofollow noreferrer">This tutorial</a> is something that I want to implement, but it uses a <strong>fixed LR</strong> instead of changing LR like when used with a Scheduler. What I want is at every step, the model still uses the LR it gets from the optimizer, but then <em>every layer's LR is also decayed by a factor</em>. It goes like:</p> <pre class="lang-py prettyprint-override"><code>for i in range(steps): lr = scheduler.get_last_lr() for idx, layer in enumerate(model.layers()): layer['lr'] = lr * 0.9 ** (idx+1) output = model(input) ... </code></pre> <p>However, when using this, do I have to pass the <code>model.parameters()</code> to the optimizer again? How will the LR be computed in this scenario? Is there a better way to do this?</p> <p>Also I am looking for a way to do that for very large models where listing all layers and specifying LRs for each of them is a bit exhaustive.</p>
<python><pytorch>
2023-01-31 05:35:04
1
2,779
Long Luu
75,292,769
3,099,733
cloudpickle: unexpectly import my local module when it is not necessary
<p>In file ai2_kit/domain.py</p> <pre class="lang-py prettyprint-override"><code>def fun(ctx): def in_add(a, b): print (a+b) ctx.executor.run_python_fn(in_add)(1, 2) # this pass ctx.executor.run_python_fn(out_add)(1, 2) # this failed, the error is: ModuleNotFoundError: No module named 'ai2_kit' def out_add(a, b): print(a+b) </code></pre> <p>the method <code>run_python_fn</code> is defined in ai2_kit/executor.py , the basic idea is use <code>python -c</code> to execute a python script on remote machine.</p> <pre class="lang-py prettyprint-override"><code> def run_python_script(self, script: str): return self.connector.run('python -c {}'.format(shlex.quote(script))) def run_python_fn(self, fn: T, python_cmd=None) -&gt; T: def remote_fn(*args, **kwargs): dumped_fn = base64.b64encode(cloudpickle.dumps(lambda: fn(*args, **kwargs), protocol=pickle.DEFAULT_PROTOCOL)) script = '''import base64,pickle; pickle.loads(base64.b64decode({}))()'''.format(repr(dumped_fn)) self.run_python_script(script=script, python_cmd=python_cmd) </code></pre> <p>I have no idea why it will import <code>ai2_kit</code> when use a function outside of current function, the method <code>out_add</code> doesn't have any external dependencies. Is there any method to workaround this problem? Thank you! Both local and remote python is v3.9.</p>
<python><pickle><cloudpickle>
2023-01-31 04:40:01
1
1,959
link89
75,292,737
7,415,134
why these 2 sorting is opposite in order
<p>I am implementing bubble sort in Python and used range for indexing the array:</p> <pre><code>&quot;&quot;&quot; program to implement bubble sort &quot;&quot;&quot; a = [9,1,5,3,7,4,2,6,8] for i in range(len(a)): for j in range(i+1, len(a)): if a[i] &gt; a[j]: a[i], a[j] = a[j], a[i] print(a) </code></pre> <p>I got the array sorted in increasing order but when I used enumerate instead of range,</p> <pre><code>&quot;&quot;&quot; program to implement bubble sort &quot;&quot;&quot; a = [9,1,5,3,7,4,2,6,8] for i, x in enumerate(a): for j, y in enumerate(a): if a[i] &gt; a[j]: a[i], a[j] = a[j], a[i] print(a) </code></pre> <p>I got the array sorted in decreasing order</p> <p>Why it happened,is there something I am missing?</p>
<python><sorting><range><bubble-sort><enumerate>
2023-01-31 04:31:26
2
379
Sid
75,292,736
4,893,753
Adding packages to memgraph transformation
<p>I am writing a memgraph transformation in python.</p> <p>When I import modules such as &quot;requests&quot; or &quot;networkx&quot;, the transformation works as expected.</p> <p>I have avro data w/ schema registry, so I need to deserialize it. I followed the memgraph example here: <a href="https://memgraph.com/docs/memgraph/2.3.0/import-data/kafka/avro#deserialization" rel="nofollow noreferrer">https://memgraph.com/docs/memgraph/2.3.0/import-data/kafka/avro#deserialization</a></p> <p>When I save the transformation with those imports, I receive the error:</p> <pre><code>[Error] Unable to load module &quot;/memgraph/internal_modules/test_try_plz.py&quot;; Traceback (most recent call last): File &quot;/memgraph/internal_modules/test_try_plz.py&quot;, line 4, in &lt;module&gt; from confluent_kafka.schema_registry import SchemaRegistryClient ModuleNotFoundError: No module named 'confluent_kafka' . For more details, visit https://memgr.ph/modules. </code></pre> <p>How can I update my transform or memgraph instance to include the confluent_kafka module?</p> <p>The link provided in the answer did not provide any leads, at least to me.</p>
<python><avro><confluent-schema-registry><memgraphdb>
2023-01-31 04:31:22
1
911
Avocado
75,292,657
787,463
Is there a data serialisation language (or program/editor) without repeating property names?
<p>So I'm working on a program (one for my own amusement, as often is the case). Still nowhere near as good as I'd like to be <strong><em>snip long story</em></strong> anyways I'm trying for my first time to use an external configuration file rather than have variables littered throughout the source (Python, so not hard to change, just need your good friend Ctrl+F).</p> <p>Been looking at JSON mostly, but for objects which have more than one value (so I can't just use a key: value pair) I need to write the field names for each entry, which gets annoying. Some demo data (i.e. not a configuration file):</p> <pre class="lang-json prettyprint-override"><code>{ &quot;people&quot;: [ {&quot;first&quot;: &quot;John&quot;, &quot;second&quot;: &quot;Smith&quot;, &quot;age&quot;: 34}, {&quot;first&quot;: &quot;Jane&quot;, &quot;second&quot;: &quot;Doe&quot;, &quot;age&quot;: 40}, {&quot;first&quot;: &quot;Fred&quot;, &quot;second&quot;: &quot;Blogs&quot;, &quot;age&quot;: 56} ] } </code></pre> <p>Gets really annoying as I add more people. I know it's for readability, but it adds to my workload.</p> <p>Also looked at YAML, but still the same basic problem:</p> <pre class="lang-yaml prettyprint-override"><code>--- people: - first: John second: Smith age: 34 - first: Jane second: Doe age: 40 - first: Fred second: Blogs age: 56 </code></pre> <p>The easiest solution I can think of is just to have the values in an array without names and assign them in the program by iterating through the array, but that defeats the purpose of readability. (n.b. just code just written off the top of my head so hopefully it's the right code)</p> <p><em>people.json:</em></p> <pre class="lang-json prettyprint-override"><code>{ &quot;people&quot;: [ [&quot;John&quot;, &quot;Smith&quot;, 34], [&quot;Jane&quot;, &quot;Doe&quot;, 40], [&quot;Fred&quot;, &quot;Blogs&quot;, 56] ] } </code></pre> <p><em>peoples.py:</em></p> <pre class="lang-python prettyprint-override"><code>import json class person: def __init__(self, first, second, age): self.first = first self.second = second self.age = age people_file = open(&quot;people.json&quot;, &quot;r&quot;) people_data = json.load(people_file) all_people = list() for each_person in people_data[&quot;people&quot;]: new_person = person(each_person[0], each_person[1], each_person[2]) all_people.append(new_person) </code></pre> <p>I think how GFM does tables would work great, but I'm not aware of any languages which support it (I know this could be prettier if I lined it up).</p> <pre class="lang-markdown prettyprint-override"><code>|first|second|age| |-----|------|---| |John|Smith|34| |Jane|Doe|40| |Fred|Blogs|56| </code></pre> <p>Umm... I hope people can make a question out of all that. Is there something I'm missing, a language (or maybe an editor or something) where I don't need to repeat myself so much? I know &quot;easy&quot; would probably by a CSV file (although I might run afoul of having to escape several special characters, as I said 3 miles above in my opening paragraph, this is a config file, but people are an easier example), but that defeats the purpose of having all my settings in one place.</p>
<python><json><serialization><yaml>
2023-01-31 04:16:36
1
325
Slashee the Cow
75,292,494
15,379,556
How to write and call wrapper without decorator in python
<p>I'd like to write wrapper function for various functions.</p> <p>How can I write the wrapper function and call it?</p> <ul> <li>Without decorator</li> </ul> <p>This is my expectation but doesn't work.</p> <pre><code>import external_library # example def wrapper(func): return func() def test1(a,b): print(a,b) def test2(a,b,c,d): print(a,b,c,d) wrapper(test1(1,2)) # a,b wrapper(test2(1,2,3,4)) # 1,2,3,4 wrapper(external_library.some_api()) # working like direct call </code></pre> <p>I got an error</p> <pre><code>'NoneType' object is not callable </code></pre>
<python>
2023-01-31 03:43:54
2
327
HG K
75,292,431
4,688,190
Python function with excessive number of variables
<p>Very general question: I am attempting to write a fairly complext Python script.</p> <pre><code>#Part A: 100 lines of python code #Part B: 500 lines of python code #Part C: 100 lines of python code </code></pre> <p>Assume that I want &quot;Part B&quot; taken out of the picture for readability and debugging purposes, because I know that it is running well and I want to focus on the other parts of the code.</p> <p>I would define a function like this:</p> <pre><code>def part_b(): #500 lines of python code #Part A: 100 lines of python code part_b() #Part C: 100 lines of python code </code></pre> <p>The problem with this approach in my case is that there are more than twenty variables that need to be sent to &quot;Part C&quot;. The following looks like bad practice.</p> <pre><code>def part_b(): global var1 global var2 global var3... </code></pre> <p>I am aware that I could return an object with more than twenty attibutes, but that would increase complexity and decrease readability.</p> <p>In other words, is there a pythonic way of saying &quot;execute this block of code, but move it away from the code that I am currently focusing on&quot;. This is for a Selenium automation project.</p>
<python>
2023-01-31 03:27:35
1
678
Ned Hulton
75,292,400
1,572,146
SQLalchemy with column names starting and ending with underscores
<p>Set <code>RDBMS_URI</code> env var to a connection string like <code>postgresql://username:password@host/database</code>, then on Python 3.9 with PostgreSQL 15 and SQLalchemy 1.14 run:</p> <pre><code>from os import environ from sqlalchemy import Boolean, Column, Identity, Integer from sqlalchemy import create_engine from sqlalchemy.orm import declarative_base Base = declarative_base() class Tbl(Base): __tablename__ = 'Tbl' __has_error__ = Column(Boolean) id = Column(Integer, primary_key=True, server_default=Identity()) engine = create_engine(environ[&quot;RDBMS_URI&quot;]) Base.metadata.create_all(engine) </code></pre> <p>Checking the database:</p> <pre class="lang-bash prettyprint-override"><code>=&gt; \d &quot;Tbl&quot; Table &quot;public.Tbl&quot; Column | Type | Collation | Nullable | Default --------+---------+-----------+----------+---------------------------------- id | integer | | not null | generated by default as identity Indexes: &quot;Tbl_pkey&quot; PRIMARY KEY, btree (id) </code></pre> <p>How do I force the column names with double underscore to work?</p>
<python><sqlalchemy>
2023-01-31 03:21:20
1
1,930
Samuel Marks
75,292,326
1,070,833
how to add custom format to QMovie in python
<p>I have a simple widget that uses QMovie to display animated gif on a QLabel. This works really well. I would like to implement my own format and add it to supported formats in QMovie (all in python). Is it possible?</p> <p>QMovies <code>supportedFormats()</code> returns two supported formats:</p> <p><code>[PySide2.QtCore.QByteArray(b'gif'), PySide2.QtCore.QByteArray(b'webp')]</code></p> <p>What is the way to extend it?</p> <p>I can simply subclass QLabel and make it work with my custom format but if feels like extending QMovie supported formats is the &quot;correct&quot; way of handling the problem. I cannot find any examples or even docs about it online.</p>
<python><qt><pyqt><pyside>
2023-01-31 03:06:17
0
1,109
pawel
75,292,270
5,805,389
Poetry cannot handle sources which redirect after setting cert
<p>I have a pypi server, TLS server cert signed by self signed CA.</p> <p>I added it as a source (default, secondary = false) to my <code>toml</code> file using</p> <p><code>poetry source add mypypiserver https://server.url/</code></p> <p>I added the CA cert using</p> <p><code>poetry config certificates.mypypiserver.cert /path/to/ca.crt</code></p> <p>When attempting to add external packages from pypi, such as <code>matplotlib</code>, even if I specify the source as pypi, I get an <code>SSLError</code>.</p> <p><code>poetry add --source pypi matplotlib</code></p> <p>Verbose logging tells me it tries to access <code>/python-dateutil/</code> which results in a <code>303</code> redirect to <code>https://pypi.org/simple/python-dateutil/</code>.</p> <p>Errors:</p> <p><code>[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)</code></p> <p><code>HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/python-dateutil/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))</code></p> <p>I suspect this is because the certificate of <code>pypi.org</code> does not match the self signed CA certificate.</p> <p>How can this be resolved?</p>
<python><ssl><python-poetry><http-status-code-303><pypiserver>
2023-01-31 02:53:54
0
805
Shuri2060
75,292,083
1,326,945
reportlab.pdfgen generating corrupted PDF
<p>I have a Django Python 3.6.5 view that's intended to write and export a report to PDF using reportlab.pdfgen. I can get the PDF file to generate when the view is called, but the .pdf file that's generated is corrupted. I'm following reportlab's documentation as best as I can tell, is there an issue with how I'm creating and writing the PDF?</p> <pre><code>from datetime import datetime from django.http import FileResponse from io import BytesIO from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from django.conf import settings from django.core.files.storage import get_storage_class from django.http import HttpResponse from django.shortcuts import redirect from app.models import Organization from app.models import Question, Report # add a footer to the PDF def add_pdf_footer(pdf): date_str = datetime.now().strftime(&quot;%Y-%m-%d&quot;) pdf.saveState() width, height = letter pdf.setFont(&quot;Helvetica&quot;, 9) text = f&quot;Exported on {date_str}&quot; pdf.drawRightString(width - 50, 700, text) pdf.restoreState() def export_report_pdf(request, report_id): org = Organization.objects.get(id=request.session[&quot;org&quot;]) try: report = Report.objects.get(id=report_id, org=org) # build file response = HttpResponse(content_type='application/pdf') filename = f&quot;{org.name}_{report.report_type.standard}_report_{report.year}_export_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf&quot; response[&quot;Content-Disposition&quot;] = f&quot;attachment; filename={filename}&quot; buffer = BytesIO() sections = report.get_sections() headers = [&quot;standard&quot;, &quot;topic&quot;, &quot;code&quot;, &quot;question&quot;, &quot;value&quot;, &quot;units&quot;, &quot;note&quot;] if len(sections) &gt; 1: headers = [&quot;standard&quot;, &quot;topic&quot;, &quot;section&quot;, &quot;code&quot;, &quot;question&quot;, &quot;value&quot;, &quot;units&quot;, &quot;note&quot;] answers = report.get_or_create_answers(request.user) answers_to_export = [] for answer in answers: question = answer.question if question.dependency is not None: dependency = question.dependency dep_answer = list(filter(lambda x: x.question == dependency, answers))[0] if question.is_dependency_resolved(dep_answer): answers_to_export.append(answer) else: answers_to_export.append(answer) pdf = canvas.Canvas(buffer, pagesize=letter) pdf.setFont(&quot;Helvetica&quot;, 15) pdf.drawString(100,800, &quot;{org.name} - {report.year} {report.report_type.standard} - {report.report_type.name} Report&quot;) pdf.setFont(&quot;Helvetica&quot;, 12) y = 750 for header in headers: pdf.drawString(100, y, header) y -= 25 for answer in answers_to_export: qtype = answer.question.question_type if qtype == Question.QUESTION_TYPE_MULTISELECT: value = &quot;, &quot;.join([ans.value for ans in answer.values_selected.all()]) elif qtype == Question.QUESTION_TYPE_SELECT: value = answer.value_selected.value if answer.value_selected else &quot;&quot; elif qtype == Question.QUESTION_TYPE_DATE: value = answer.value_date.strftime(&quot;%Y-%m-%d&quot;) else: value = answer.value if len(sections) &gt; 1: pdf.drawString(180, y, answer.question.section) pdf.drawString(260, y, answer.question.code) if answer.question.text: pdf.drawString(340, y, answer.question.text) if value: pdf.drawString(420, y, value) if answer.question.units: pdf.drawString(500, y, answer.question.units) if answer.note: pdf.drawString(580, y, answer.note) y -= 30 else: pdf.drawString(260, y, answer.question.code) if answer.question.text: pdf.drawString(340, y, answer.question.text) if value: pdf.drawString(420, y, value) if answer.question.units: pdf.drawString(500, y, answer.question.units) if answer.note: pdf.drawString(580, y, answer.note) y -= 30 # set PDF export footer add_pdf_footer(pdf) pdf.save() # return file return response except: log.error(traceback.print_exc()) return redirect(&quot;admin-report&quot;) </code></pre>
<python><python-3.x><pdf-generation><reportlab>
2023-01-31 02:15:50
0
1,585
Chris B.
75,291,919
5,942,100
Positive and negative value sum separately in Pandas
<p>Find and sum all negative values Find and sum all positive values</p> <p><strong>DATA</strong></p> <pre><code>ID value A -1 B -5 AA 1 TT 3 UV 4 QA 50 WQ -40 QC 10 </code></pre> <p><strong>DESIRED</strong></p> <pre><code>positive 68 negative -46 </code></pre> <p><strong>DOING</strong></p> <pre><code>df.groupby(df['value'].agg([('value' , lambda x : x[x &lt; 0].sum()) , ('positive' , lambda x : x[x &gt; 0].sum())]) </code></pre> <p>Any suggestion is appreciated</p>
<python><pandas><numpy>
2023-01-31 01:45:56
1
4,428
Lynn
75,291,891
4,573,162
Python Unit Test to Assert Type Annotation of Object
<p>In Python versions &lt;3.11 where the <code>assert_type</code> (<a href="https://docs.python.org/3/library/typing.html#typing.assert_type" rel="nofollow noreferrer">source</a>) isn't available, how does one assert a type annotation via the <code>unittest</code> <code>TestCase</code> class? Example of the problem:</p> <pre><code>from typing import List from unittest import TestCase def dummy() -&gt; List[str]: return [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;] class TestDummy(TestCase): def test_dummy(self): self.assertEqual( List[str], type(dummy()) ) </code></pre> <p>The test fails with the following output:</p> <pre><code>&lt;class 'list'&gt; != typing.List[str] Expected :typing.List[str] Actual :&lt;class 'list'&gt; &lt;Click to see difference&gt; Traceback (most recent call last): File &quot;C:\Users\z\dev\mercata\scratch\mock_testing.py&quot;, line 12, in test_dummy self.assertEqual( AssertionError: typing.List[str] != &lt;class 'list'&gt; </code></pre> <p>The approach I currently use is as follows:</p> <pre><code>data = dummy() self.assertTrue( type(data) == list ) self.assertTrue(all([ type(d) == str for d in data ])) </code></pre> <p>This <em>works</em> but requires iterating the entirety of the object which is unwieldy with larger datasets. Is there a more efficient approach for Python versions &lt;3.11 (not requiring a third-party package)?</p>
<python><python-3.x><unit-testing><python-typing>
2023-01-31 01:40:58
2
4,628
alphazwest
75,291,569
14,890,683
Python Plotly Scatterplot Highlight Group on Click
<p>Is there a way to highlight all points with attribute on click?</p> <p>I am working within a Streamlit framework, so Dash solutions won't work.</p> <p>Similar to this post: <a href="https://stackoverflow.com/questions/52532428/highlight-all-values-from-a-group-on-hover?noredirect=1&amp;lq=1">Highlight all values from a group on hover</a></p> <p>In the below, example, I'm looking to highlight all items from the same <code>group</code> after clicking.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import plotly.express as px df = pd.DataFrame(dict( x=[4, 5, 1, 3, 2, 2], y=[3, 1, 7, 9, 8, 3], group=[0, 0, 0, 1, 1, 1], value=[1, 2, 3, 4, 5, 6], hover=['s1', 's2', 's3', 's4', 's5', 's6'] )) fig = px.scatter( df, y='y', x='x', color='group', hover_name='hover', ) fig.show() </code></pre>
<python><plotly><visualization><scatter-plot><streamlit>
2023-01-31 00:25:21
0
345
Oliver
75,291,413
11,333,172
Checking topological equivalence in shapely
<h1>Problem</h1> <p>I am using shapely 2.0.0. I have a bunch of polygons in shapely as <code>shapely.Polygon</code> and I would like to check if any of the polygons is a rectangle. This can be done by checking if a polygon's minimum rotated rectangle is <strong>topologically equivalent</strong> to itself. I have tried the following approaches (please refer to below codes):</p> <ol> <li><p>Testing if the minimum rotated rectangle is topologically equivalent to the original polygon using <code>shapely.equals</code>. However, this method fails due to floating point errors and apparently there is no way for me to use <code>shapely.equals</code> with tolerances based on the <a href="https://shapely.readthedocs.io/en/stable/reference/shapely.equals.html?highlight=equals#shapely.equals" rel="nofollow noreferrer">documentation</a>.</p> </li> <li><p>Testing if the minimum rotated rectangle is structurally equivalent to the original polygon using <code>shapely.equals_exact</code>.<a href="https://shapely.readthedocs.io/en/stable/reference/shapely.equals_exact.html#shapely.equals_exact" rel="nofollow noreferrer"> The problem is this requires the polygon's coordinates to be equal (within specified tolerance) and in the same order</a>, which in this case the minimum rotated rectangle have different order of coordinates than the original polygon which causes problems. Moreover, in general polygons may have different number of coordinates on the exterior and still have topological equvalences.</p> </li> <li><p>My current inplementation thus check if the area of minimum rotated rectangles vs the original polygon is in certain tolerance. The problem is this is not really checking the topological equvalence and may fail for some cases.</p> </li> </ol> <p>This thus raised me a question that I would like to have your suggestions: <strong>With the consideration of floating point operations, What is the best way to check the topological equvalence of polygons in shapely?</strong> Any help and suggestions will be greatly appreciated.</p> <h1>Minimal Reproducible Example</h1> <pre><code>from shapely import minimum_rotated_rectangle, Polygon from shapely.plotting import plot_polygon import matplotlib.pyplot as plt box1 = Polygon([(0,0),(0.5,0),(0.5,0.8),(0.2,0.8),(0,0.8),(0,0)]) box2 = minimum_rotated_rectangle(box1) </code></pre> <pre><code>plot_polygon(box1) plt.show() </code></pre> <p><a href="https://i.sstatic.net/SM20n.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SM20n.png" alt="enter image description here" /></a></p> <pre><code>plot_polygon(box2) plt.show() </code></pre> <p><a href="https://i.sstatic.net/SbgIv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SbgIv.png" alt="enter image description here" /></a></p> <h2>1st approach (fails because of floating point error):</h2> <pre><code>&gt;&gt;&gt;box1.equals(box2) False &gt;&gt;&gt;box1.area 0.4 &gt;&gt;&gt;box2.area 0.4000000000000001 </code></pre> <h2>2nd approach (fails because of exterior points mismatch):</h2> <pre><code>&gt;&gt;&gt;box1.equals_exact(box2,tolerance = 1e-3) False &gt;&gt;&gt;box1.boundary LINESTRING (0 0, 0.5 0, 0.5 0.8, 0.2 0.8, 0 0.8, 0 0) &gt;&gt;&gt;box2.boundary LINESTRING (0 0, 0.5 0, 0.5 0.8000000000000002, 0 0.8000000000000002, 0 0) </code></pre> <h2>Current approach</h2> <pre><code>&gt;&gt;&gt;import math &gt;&gt;&gt;math.isclose(box1.area,box2.area,rel_tol=1e-9) True </code></pre>
<python><shapely>
2023-01-30 23:56:24
0
620
adrianop01
75,291,327
11,370,582
Upload multiple Excel workbooks and concatanate - dcc.Upload, Plotly Dash
<p>I'm developing a interactive dashboard using Plotly Dash, which takes an Excel workbook as an input, formats the data into a pandas dataframe and displays as a bar graph.</p> <p>It works well with a single workbook but when I add a variable to allow for multiple works to be loaded and concatenated into one long dataframe and visualized I am running into a persistence issue. Where the data is kept after the browser is refreshed, even though <code>storage_type</code> is set to <code>memory</code> per the documentation.</p> <pre><code>app = dash.Dash(__name__, external_stylesheets=external_stylesheets) dfmeans = [] app.layout = html.Div([ # this code section taken from Dash docs https://dash.plotly.com/dash-core-components/upload dcc.Store(id='stored-data', storage_type='memory'), dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, # Allow multiple files to be uploaded multiple=True </code></pre> <p>I suspect this is because I have declared the list variable <code>df_means =[]</code> outside of the main function but that's the only place I have been able to get it to work. When I place it inside the <code>parse_contents()</code> function the data is replaced each time I add a new workbook.</p> <p>Has anyone out there successfully implemented the Dash Upload component <code>dcc.Upload</code> taking multiple workbooks/excel files as an input? The documentation out there on uploading more that one file is really sparse from what I can find. Full code here -</p> <pre><code>import base64 import datetime import io import re import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import dash_table import plotly.express as px import pandas as pd from read_workbook import * import pdb suppress_callback_exceptions=True external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) dfmeans = [] app.layout = html.Div([ # this code section taken from Dash docs https://dash.plotly.com/dash-core-components/upload dcc.Store(id='stored-data', storage_type='memory'), dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, # Allow multiple files to be uploaded multiple=True ), html.Div(id='output-div'), html.Div(id='output-datatable'), ]) def parse_contents(contents, filename, date): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: workbook_xl = pd.ExcelFile(io.BytesIO(decoded)) # print(workbook_xl) #aggregates all months data into a single data frame def get_all_months(workbook_xl): months = ['July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June'] xl_file = pd.ExcelFile(workbook_xl) months_data = [] for month in months: months_data.append(get_month_dataframe(xl_file, month)) print(months_data) return pd.concat(months_data) #run get all months function and produce behavior dataframe df = get_all_months(workbook_xl) #convert episode values to float and aggregate mean per shift df['value'] = df['value'].astype(float) dfmean = df.groupby(['Date', 'variable'],sort=False,)['value'].mean().round(2).reset_index() dfmeans.append(dfmean) dfmean = pd.concat(dfmeans) except Exception as e: print(e) return html.Div([ 'There was an error processing this file.' ]) return html.Div([ html.H5(filename), # html.H6(datetime.datetime.fromtimestamp(date)), dash_table.DataTable( data=dfmean.to_dict('records'), columns=[{'name': i, 'id': i} for i in dfmean.columns], page_size=15 ), dcc.Store(id='stored-data', data=dfmean.to_dict('records')), html.Hr(), # horizontal line # For debugging, display the raw contents provided by the web browser html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ]) @app.callback(Output('output-datatable', 'children'), Input('upload-data', 'contents'), State('upload-data', 'filename'), State('upload-data', 'last_modified')) def update_output(list_of_contents, list_of_names, list_of_dates): if list_of_contents is not None: children = [ parse_contents(c, n, d) for c, n, d in zip(list_of_contents, list_of_names, list_of_dates)] return children @app.callback(Output('output-div', 'children'), Input('stored-data','data')) def make_graphs(data): df_agg = pd.DataFrame(data) # df_agg['Date'] = pd.to_datetime(df_agg['Date']) if df_agg.empty: print(&quot;Dataframe epmty&quot;) else: bar_fig = px.bar(df_agg, x=df_agg['Date'], y=df_agg['value'], color = 'variable',barmode='group') return dcc.Graph(figure=bar_fig) if __name__ == '__main__': app.run_server(debug=True) </code></pre>
<python><pandas><flask><plotly><plotly-dash>
2023-01-30 23:37:35
1
904
John Conor
75,291,306
6,202,327
Using sfepy to solve a simple 2D differential euqation
<p>I am trying to learn sfepy. To that effect I want to solve the differential equation</p> <p><a href="https://i.sstatic.net/DQNfN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DQNfN.png" alt="enter image description here" /></a></p> <p>On a triangle domain (2D).</p> <p>There';s 2 things I don't understand from reading the <a href="https://sfepy.org/doc-devel/tutorial.html#tutorial-interactive-source" rel="nofollow noreferrer">docs</a>.</p> <ol> <li><p>How do I specify a single triangle mesh? The code seems to assume you already have the mesh file but it does not provide a link to it so I don;t know hwo to cosntruct my data.</p> </li> <li><p>I am having a ahrd time learning how to map the equation onto sfepy's syntax. i.e. I don;t really know how to specify the problem using the library even after followignt he tutorial.</p> </li> </ol>
<python><math><numerical-methods><differential-equations><finite-element-analysis>
2023-01-30 23:34:57
1
9,951
Makogan
75,291,295
4,047,084
Dynamodb GSI containing boolean
<p>I have a dynamodb table of events that have specified start and end times. These events can be happening in realtime, in which case, the end timestamp is not yet written.</p> <p>I have setup a global secondary index with the sort key being the binary field, <code>active</code>. When I try and update a record to set this to true, I get the error:</p> <pre><code>Expected: B Actual: BOOL </code></pre> <p>The python code for this is:</p> <pre><code>table.update_item( Key={ 'fingerprint': item['fingerprint'], 'startedtimestamp': item['startedtimestamp'] }, UpdateExpression=&quot;SET #active :active, resolvedtimestamp :resolvedtimestamp&quot;, ExpressionAttributeNames : { '#active' : 'active', '#resolvedtimestamp' : 'resolvedtimestamp' }, ExpressionAttributeValues={ ':active': False, ':resolvedtimestamp': resolvedtimestamp}, ) </code></pre> <p>I have also been reading elsewhere about using a sparse index instead. In this case though, if the index was just the <code>resolvedtimestamp</code>, would it be possible to query for the active records (e.g. <code>resolvedtimestamp</code> is not set)? Otherwise, what other optimizations can I do to the table and indices to be able to query for active records?</p>
<python><amazon-dynamodb><database-administration>
2023-01-30 23:32:11
2
1,864
Stuart Buckingham
75,291,090
2,057,516
Why don't I get a full traceback from a saved exception - and how do I get and save the full trace?
<p>I have a user submitted data validation interface for a scientific site in django, and I want the user to be able to submit files of scientific data that will aid them in resolving simple problems with their data before they're allowed to make a formal submission (to reduce workload on the curators who actually load the data into our database).</p> <p>The validation interface re-uses the loading code, which is good for code re-use. It has a &quot;validate mode&quot; that doesn't change the database. Everything is in an atomic transaction block and it gets rolled back in any case when it runs in validate mode.</p> <p>I'm in the middle of a refactor to alleviate a problem. The problem is that the user has to submit the files multiple times, each time, getting the next error. So I've been refining the code to be able to &quot;buffer&quot; the exceptions in an array and only really stop if any error makes further processing impossible. So far, it's working great.</p> <p>Since unexpected errors are expected in this interface (because the data is complex and lab users are continually finding new ways to screw up the data), I am catching and buffering any exception and intend to write custom exception classes for each case as I encounter them.</p> <p>The problem is that when I'm adding new features and encounter a new error, the tracebacks in the buffered exceptions aren't being fully preserved, which makes it annoying to debug - even when I change the code to raise and immediately catch the exception so I can add it to the buffer with the traceback. For example, in my debugging, I may get an exception from a large block of code, and I can't tell what line it is coming from.</p> <p>I have worked around this problem by saving the traceback as a string inside the buffered exception object, which just feels wrong. I had to play around in the shell to get it to work. Here is my simple test case to demonstrate what's happening. It's reproducible for me, but apparently not for others who try this toy example - and I don't know why:</p> <pre><code>import traceback class teste(Exception): &quot;&quot;&quot;This is an exception class I'm going to raise to represent some unanticipated exception - for which I will want a traceback.&quot;&quot;&quot; pass def buf(exc, args): &quot;&quot;&quot;This represents my method I call to buffer an exception, but for this example, I just return the exception and keep it in main in a variable. The actual method in my code appends to a data member array in the loader object.&quot;&quot;&quot; try: raise exc(*args) except Exception as e: # This is a sanity check that prints the trace that I will want to get from the buffered exception object later print(&quot;STACK:&quot;) traceback.print_stack() # This is my workaround where I save the trace as a string in the exception object e.past_tb = &quot;&quot;.join(traceback.format_stack()) return e </code></pre> <p>The above example raises the exception inside <code>buf</code>. (My original code supports both raising the exception for the first time and buffering an already raised and caught exception. In both cases, I wasn't getting a saved full traceback, so I'm only providing the one example case (where I raise it inside the <code>buf</code> method).</p> <p>And here's what I see when I use the above code in the shell. This first call shows my sanity check - the whole stack, which is what I want to be able to access later:</p> <pre><code>In [5]: es = buf(teste, [&quot;This is a test&quot;]) STACK: File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/manage.py&quot;, line 22, in &lt;module&gt; main() File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/manage.py&quot;, line 18, in main execute_from_command_line(sys.argv) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/__init__.py&quot;, line 419, in execute_from_command_line utility.execute() File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/__init__.py&quot;, line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/base.py&quot;, line 354, in run_from_argv self.execute(*args, **cmd_options) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/base.py&quot;, line 398, in execute output = self.handle(*args, **options) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/commands/shell.py&quot;, line 100, in handle return getattr(self, shell)(options) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/commands/shell.py&quot;, line 36, in ipython start_ipython(argv=[]) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/__init__.py&quot;, line 126, in start_ipython return launch_new_instance(argv=argv, **kwargs) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/traitlets/config/application.py&quot;, line 846, in launch_instance app.start() File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/terminal/ipapp.py&quot;, line 356, in start self.shell.mainloop() File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/terminal/interactiveshell.py&quot;, line 566, in mainloop self.interact() File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/terminal/interactiveshell.py&quot;, line 557, in interact self.run_cell(code, store_history=True) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py&quot;, line 2914, in run_cell result = self._run_cell( File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py&quot;, line 2960, in _run_cell return runner(coro) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/core/async_helpers.py&quot;, line 78, in _pseudo_sync_runner coro.send(None) File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py&quot;, line 3185, in run_cell_async has_raised = await self.run_ast_nodes(code_ast.body, cell_name, File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py&quot;, line 3377, in run_ast_nodes if (await self.run_code(code, result, async_=asy)): File &quot;/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py&quot;, line 3457, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File &quot;&lt;ipython-input-5-92f4a0db918d&gt;&quot;, line 1, in &lt;module&gt; es = buf(teste, [&quot;This is a test&quot;]) File &quot;&lt;ipython-input-2-86e515dc1ec1&gt;&quot;, line 6, in buf traceback.print_stack() </code></pre> <p>But this is what I see when I want to see the original traceback from the <code>es</code> object (i.e. the buffered exception) later. It only has the last item from the traceback. This is exactly what I see in the original source code - a single item for the line of code inside the buffer method:</p> <pre><code>In [8]: traceback.print_exception(type(es), es, es.__traceback__) Traceback (most recent call last): File &quot;&lt;ipython-input-2-86e515dc1ec1&gt;&quot;, line 3, in buf raise exc(*args) teste: This is a test </code></pre> <p>My workaround suffices for now, but I'd like to have a proper traceback object.</p> <p>I debugged the issue by re-cloning our repo in a second directory to make sure I hadn't messed up my sandbox. I guess I should try this on another computer too - my office mac. But can anyone point me in the right direction to debug this issue? What could be the cause for losing the full traceback?</p>
<python><django>
2023-01-30 23:05:19
1
1,225
hepcat72
75,291,059
688,208
What is the reason for list.__str__ using __repr__ of its elements?
<p>What is the reason for <code>list.__str__</code> using <code>__repr__</code> of its elements?</p> <p>Example:</p> <pre class="lang-python prettyprint-override"><code>class Unit: def __str__(self): return &quot;unit&quot; def __repr__(self): return f&quot;&lt;unit id={id(self)}&gt;&quot; &gt;&gt;&gt; str(Unit()) 'unit' &gt;&gt;&gt; str([Unit()]) '[&lt;unit id=1491139133008&gt;]' </code></pre>
<python><python-3.x>
2023-01-30 23:00:00
2
493
Number47
75,291,026
5,860,483
Django rest framework unsupported media type with image upload
<p>this is my first time trying to upload image to django rest framework, i am using svelte for my front end and using the fetch api for requests.</p> <p>i am have an error that i cannot solve. all requests containing images return an unsupported media type error.</p> <p><strong>Back End</strong></p> <p>i have added these line to my settings.py</p> <pre><code># Actual directory user files go to MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'mediafiles') # URL used to access the media MEDIA_URL = '/media/' </code></pre> <p>my simplified views.py</p> <pre><code>@api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) @parser_classes([FormParser, MultiPartParser]) def products(request): if request.method == 'POST' and isPermitted(request.user, 'allow_edit_inventory'): serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk if serializer.is_valid(): serializer.save() return Response({'message': &quot;product added&quot;}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>my urls.py</p> <pre><code>from django.contrib import admin from django.urls import path, include from rest_framework.authtoken import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(&quot;API.urls&quot;)) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <p>and finally my models.py</p> <pre><code>def product_images_upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class Product(models.Model): name = models.CharField(max_length=200) image_url = models.ImageField(upload_to=product_images_upload_to, blank=True, null=True) </code></pre> <p><strong>Front End</strong></p> <p>my file upload component in svelte, the exported image variable is what get used in the request in the following code.</p> <pre><code> export let avatar, fileinput, image; const onFileSelected = (e) =&gt; { image = e.target.files[0]; let reader = new FileReader(); reader.readAsDataURL(image); reader.onload = (e) =&gt; { avatar = e.target.result; }; }; </code></pre> <p>request</p> <pre><code>export const addProduct = async (product) =&gt; { const fd = new FormData(); fd.append(&quot;name&quot;, product.name); fd.append(&quot;image_url&quot;, product.image_url); const response = await fetch(`${URL}/products`, { method: &quot;POST&quot;, headers: { &quot;Content-Type&quot;: `multipart/form-data boundary=${fd._boundary}`, Authorization: `token ${localStorage.getItem(&quot;auth&quot;)}` }, body: JSON.stringify(product), }) return response } </code></pre>
<python><django><django-rest-framework><fetch><svelte>
2023-01-30 22:55:11
1
330
Omar Alhussani
75,291,018
19,321,677
How to create %lift from pandas dataframe comparing several variants to control group?
<p>my df looks like this:</p> <pre><code>segment group purchase_amount A control 2601 A variant1 2608 A variant2 2586 B control 2441 B variant1 2712 B variant2 2710 </code></pre> <p>I would like a table where WITHIN segments, I can compare all variants with the respective control. Something like this:</p> <pre><code>segment %lift purchase_amount A variant1 (2608-2601)/2601 A variant2 (2586-2601)/2601 B variant1 (2712-2441)/2441 B variant2 (2710-2441)/2441 </code></pre> <p>How can I do this with pandas?</p>
<python><pandas>
2023-01-30 22:54:34
2
365
titutubs
75,290,914
18,476,381
Convert sql join data into list of dictionaries on certain same key
<p>From a sql stored proc that performs a join on two tables I get the data below.</p> <pre class="lang-py prettyprint-override"><code>[ {&quot;service_order_number&quot;: &quot;ABC&quot;, &quot;vendor_id&quot;: 0, &quot;recipient_id&quot;: 0, &quot;item_id&quot;: 0, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;}, {&quot;service_order_number&quot;: &quot;ABC&quot;, &quot;vendor_id&quot;: 0, &quot;recipient_id&quot;: 0, &quot;item_id&quot;: 1, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;}, {&quot;service_order_number&quot;: &quot;DEF&quot;, &quot;vendor_id&quot;: 0, &quot;recipient_id&quot;: 0, &quot;item_id&quot;: 2, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;}, {&quot;service_order_number&quot;: &quot;DEF&quot;, &quot;vendor_id&quot;: 0, &quot;recipient_id&quot;: 0, &quot;item_id&quot;: 3, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;} ] </code></pre> <p>What would be the best way to convert this data into the below format? Is it possible on the python side? Or is there something other than a join I can perform to get data back in this format?</p> <pre class="lang-py prettyprint-override"><code>[{ &quot;service_order_number&quot;: &quot;ABC&quot;, &quot;vendor_id&quot;: 0, &quot;recipient_id&quot;: 0, items: [ { &quot;item_id&quot;: 0, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;, }, { &quot;item_id&quot;: 1, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;, } ] }, {&quot;service_order_number&quot;: &quot;DEF&quot; &quot;vendor_id&quot;: 0, &quot;recipient_id&quot;: 0, items: [ { &quot;item_id&quot;: 2, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;, }, { &quot;item_id&quot;: 3, &quot;part_number&quot;: &quot;string&quot;, &quot;part_description&quot;: &quot;string&quot;, } ] }] </code></pre>
<python><sql><list><dictionary>
2023-01-30 22:41:00
2
609
Masterstack8080
75,290,880
1,130,785
How do I aggregate array elements column-wise in pyspark?
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> </tr> </thead> <tbody> <tr> <td>[1,2,3,4]</td> <td>[0,1,0,3]</td> </tr> <tr> <td>[5,6,7,8]</td> <td>[0,3,4,8]</td> </tr> </tbody> </table> </div> <p><code>desired result:</code></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> </tr> </thead> <tbody> <tr> <td>[6,8,10,12]</td> <td>[0,4,4,11]</td> </tr> </tbody> </table> </div> <p>In snowflake's snowpark this is relatively straight forward using <a href="https://docs.snowflake.com/ko/developer-guide/snowpark/reference/python/api/snowflake.snowpark.functions.array_construct.html" rel="nofollow noreferrer">array_construct</a>. Apache Spark has a similar <a href="https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.array.html" rel="nofollow noreferrer">array</a> function but there is a major difference.</p> <p>In snowpark, I can do <code>array_construct(count('*'), sum(col('x')), sum(col('y'), count(col('y')))</code> but apache spark seems to count <code>array()</code> as an aggregation and complains that I can't have an aggregation inside of an aggregation.</p> <p><code>pyspark.sql.utils.AnalysisException: It is not allowed to use an aggregate function in the argument of another aggregate function. Please use the inner aggregate function in a sub-query.;</code></p> <p>I'm trying to write a piece of code that can handle both snowpark and apache spark but this <code>array_construct</code> vs <code>array</code> is proving trickier than anticipated. Next up is to explore doing a groupby &amp; collect_list but wondering how others have solved this?</p>
<python><arrays><apache-spark><pyspark><snowflake-cloud-data-platform>
2023-01-30 22:35:52
2
2,027
whisperstream
75,290,789
6,524,326
Efficient pythonic way to compute the difference between the max and min elements of each tuple in a large list of tuples
<p>Using the following code, I am trying to calculate the difference between the max and min elements of each tuple in a large list of tuples and store the results in a list. However, the code runs for long time and then OS kills it because it consumes huge amount of RAM. The large list is generated by choosing <code>n</code> numbers from a list, basically all possible ways as shown in the snippet below. I think the issue lies exactly there: itertools.combinations, which tries to store a massive list in memory.</p> <p>I need the sum of the diffs arising from each combination actually, that's why I thought first I would get the diffs in a list and then call sum.</p> <pre><code>import itertools n = 40 lst = [639, 744, 947, 856, 102, 639, 916, 665, 766, 679, 679, 484, 658, 559, 564, 3, 384, 763, 236, 404, 566, 347, 866, 285, 107, 577, 989, 715, 84, 280, 153, 76, 24, 453, 284, 126, 92, 200, 792, 858, 231, 823, 695, 889, 382, 611, 244, 119, 726, 480] result = [max(x)-min(x) for x in itertools.combinations(lst, n)] </code></pre> <p>It will be a great learning experience for me if someone provides a hint about tackling this issue.</p>
<python><algorithm>
2023-01-30 22:22:59
3
828
Wasim Aftab
75,290,788
1,867,985
numpy in a virtual environment: DLL load failure on attempted parallelization
<p>I'm doing some scientific computation in python, and recently switched away from Anaconda since it doesn't yet support python 3.10 (which has some new features I'd like to use). I am now running on python version <code>3.10.9</code>. I have a pipenv virtual environment set up for this, and in it I've got numpy version <code>1.23.5</code> installed. (Trying to upgrade to a newer version fails with a bunch of errors -- if upgrading numpy ends up being necessary I'll need to open a new question to ask about how to get that working.)</p> <p>Everything initially seems to be working fine, until I try to run a parallelized numpy computation. At that point, I get the error <code>DLL load failed while importing _multiarray_umath: The specified module could not be found.</code> Here's the associated traceback:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\charles\.virtualenvs\pipenv-WB8juvy1\lib\site-packages\numpy\core\__init__.py&quot;, line 23, in &lt;module&gt; from . import multiarray File &quot;C:\Users\charles\.virtualenvs\pipenv-WB8juvy1\lib\site-packages\numpy\core\multiarray.py&quot;, line 10, in &lt;module&gt; from . import overrides File &quot;C:\Users\charles\.virtualenvs\pipenv-WB8juvy1\lib\site-packages\numpy\core\overrides.py&quot;, line 6, in &lt;module&gt; from numpy.core._multiarray_umath import ( ImportError: DLL load failed while importing _multiarray_umath: The specified module could not be found. </code></pre> <p>I can import numpy just fine, and I can use various functions from numpy without issue as well. I only get problems when I specifically want to do some parallelized computations. At that point my console gets flooded with this error (as far as I can tell, it's printing nearly exactly the same thing over and over, presumably once for every worker that it tried to launch).</p> <p>The following text is also included in the error message:</p> <pre><code>IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.10 from &quot;C:\Users\charles\.virtualenvs\pipenv-WB8juvy1\Scripts\python.exe&quot; * The NumPy version is: &quot;1.24.1&quot; and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. </code></pre> <p>While this looks pretty promising, I've read through the documentation on that page and nothing seems to be addressing the particular issue I'm running into here.</p> <p>Additional details about my setup: The virtual environment was set up with pipenv, using the <code>--site-packages</code> flag (as I don't seem to be able to properly install PyQt5 in the virtual environment, so I'm just sourcing it from the system). I've got numpy installed in both my system's <code>site-packages</code> - that is version <code>1.24.1</code> (which checks out with the error messages) - and in the virtual environment's site packages (I didn't explicitly install it there, it was installed as a dependency; the virtual version is <code>1.23.5</code>). Uninstalling numpy from the system site packages does not fix the issue.</p> <p>I've also tried completely deleting the virtual environment and reinstalling it from the pipfile, but that also doesn't fix the issue. The version of numpy which is installed in the virtual environment does indeed have a DLL in its <code>.lib</code> folder, so it's not just missing. As far as I can tell there's nothing weird about my path; just in case I tried manually adding the <code>.lib</code> folders where the DLLs live to the path. I added both the virtual and system site packages to the path, and tried sourcing them in various different orders, to no avail.</p> <p>I'm kinda at the end of my ability to troubleshoot this at this point, hence this request for help. In the meantime I'm resorting to doing all of my computations serially, but (as you might imagine) this is very slow and not very sustainable for the long term. If nobody can help me fix this, I'm going to have to just go back to Anaconda and give up on features from the newer python versions until they support them. (Or maybe I can try working without a virtual environment, but I've messed up systems pretty badly that way before and I'm kind of loathe to take that approach).</p>
<python><numpy><dll><virtualenv><pipenv>
2023-01-30 22:22:56
0
325
realityChemist
75,290,706
21,046,803
How to copy Stackoverflow example Dataframe into a pandas Dataframe for reproduction
<p>Is there an systematic approach do import copied dataframes from Stackoverflow Questions into your programm? I often see Dataframes similar like the example below. But i usually have to put in some <code>&quot;:&quot;</code> or some other formatting to turn it into a proper pandas Dataframe via <code>pd.read_cvs</code>.</p> <p><em>So my questions are:</em></p> <ul> <li>Am i missing something here or is everyone else also just trying out 2-3 things per copied Dataframe until its &quot;clean&quot;?</li> <li>The other way around. Is there a recommended format to copy your example Dataframe into a Stackoverflow question?</li> </ul> <pre><code> Name id other list 0 bren {00005, 0002,0003} abc [[1000, A, 90],[9000, S, 28],[5000, T, 48]] 1 frenn {00006,0001} gf [3000, B, 80], [7000, R, 98] 2 kylie {00007} jgj [600, C, 55] 3 juke {00009} gg [5000, D, 88] </code></pre> <p>Usually i create a dummyfile and copy/paste the provided Dataframe from Stackoverflow. In the dummyfile i replace the whitespaces with &quot;:&quot;. Finally i use:</p> <pre><code>import pandas as pd df=pd.read_cvs(&quot;dummyfile&quot;, sep=&quot;:&quot;) </code></pre> <p>Otherwise i get Problems like shown below</p> <pre><code>print(df.columns) #output &quot; list&quot; </code></pre> <pre><code> Name ... list 0 ben {00005, 0002,0003} abc [[1000, A, 90],[9000, S, ... 48]] 1 alex {00006,0001} gf [3000, B, 80], [7000, R, ... None 2 linn {00007} jgj [600, C, 55] NaN None ... None 3 luke {00009} gg [5000, D, 88] NaN None ... None </code></pre> <p>I expect a clean dataframe.</p>
<python><pandas><dataframe><csv>
2023-01-30 22:12:04
1
1,539
tetris programming
75,290,680
14,293,020
How to gather arrays of different sizes in the same array with Numpy?
<p><strong>Context:</strong> I have 3 arrays. <code>A</code> that is <em>3x3</em>, <code>B</code> that is <em>5x2</em>, and <code>C</code> that is a <em>3D</em> array.</p> <p><strong>Question:</strong> Is there a way to stack arrays of different sizes along the 1st dimension of a 3D array, with Numpy ?</p> <p><strong>Example:</strong> if <code>A</code> and <code>B</code> are stacked in <code>C</code> along its first dimension, and I want to access <code>A</code>, I would type <code>C[0]</code>.</p> <p><strong>Problem:</strong> I know I can use Xarray for that, but I wanted to know if there was a Numpy way to do it. So far, I have been artificially extending the arrays with NaNs to match their sizes (see code below).</p> <p><strong>Code:</strong></p> <pre><code># Generate the arrays A = np.random.rand(3,3) B = np.random.rand(5,2) C = np.zeros((2,5,3)) # Resize the arrays to fit C AR = np.full([C.shape[1], C.shape[2]], np.nan) # Generate an array full of NaNs that fits C AR[:A.shape[0],:A.shape[1]] = A # Input the previous array in the resized one BR = np.full([C.shape[1], C.shape[2]], np.nan) # Generate an array full of NaNs that fits C BR[:B.shape[0],:B.shape[1]] = B # Input the previous array in the resized one # Stack the resized arrays in C C[0] = AR C[1] = BR </code></pre>
<python><arrays><numpy>
2023-01-30 22:08:42
1
721
Nihilum
75,290,517
18,476,381
pymsql (1054, "Unknown column 'None' in 'call statement'")
<p>I am trying to call stored procedure with pymsql but it looks like I am getting an error when one of the param is passed in as None. My stored proc is able to handle cases of Null but ofcourse not None. I was under the impression that pymysql automatically converts None to Null. Below is the code I am using.</p> <pre><code>_exec_statement = 'call kp_get_purchase_order(None,10,0)' self.cursor.execute(_exec_statement) return self.cursor.fetchall() </code></pre> <blockquote> <p>Error: pymysql.err.OperationalError: (1054, &quot;Unknown column 'None' in 'call statement'&quot;)</p> </blockquote> <p>Is there a way to convert None to Null to pass into the cursor?</p>
<python><sql><pymysql>
2023-01-30 21:48:30
1
609
Masterstack8080
75,290,501
9,663,207
Is it possible to use SQLAlchemy where the models are defined in different files?
<p>I'm using SQLAlchemy for the first time and trying to define my models / schema. My only experience with ORM prior to this was with Rails and <a href="https://guides.rubyonrails.org/active_record_basics.html" rel="nofollow noreferrer">ActiveRecord</a>.</p> <p>Anyway, following SQLAlchemy's ORM Quick Start, this is the basic example they use (I have removed a few lines which are not relevant to my question):</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import ForeignKey from sqlalchemy import String from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship class Base(DeclarativeBase): pass class User(Base): __tablename__ = &quot;user_account&quot; id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(30)) addresses: Mapped[list[&quot;Address&quot;]] = relationship( back_populates=&quot;user&quot;, cascade=&quot;all, delete-orphan&quot; ) class Address(Base): __tablename__ = &quot;address&quot; id: Mapped[int] = mapped_column(primary_key=True) email_address: Mapped[str] user_id: Mapped[int] = mapped_column(ForeignKey(&quot;user_account.id&quot;)) user: Mapped[&quot;User&quot;] = relationship(back_populates=&quot;addresses&quot;) </code></pre> <p>My question is: is it possible to create two models in separate files (<code>user.py</code> and <code>address.py</code>), defining each model in its own file, and then import them and run a command like the following in order to instantiate the database:</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import create_engine engine = create_engine(&quot;sqlite://&quot;, echo=True) Base.metadata.create_all(engine) </code></pre>
<python><database><sqlalchemy><orm>
2023-01-30 21:46:34
3
724
g_t_m
75,290,351
6,843,153
Get Slack channel ID with python slack sdk
<p>I'm writing a Slack bot that requires updating already posted messages, so I implemented this code using Slack python SDK:</p> <pre><code>def update_message(self, message_text, ts): response = self.client.chat_update(channel=self.channel, ts=ts, text=message_text) return response </code></pre> <p>The problem is that I only have the channel name, and the method <code>chat_update()</code> requires the channel ID.</p> <p>How can I know the channel ID if I know the channel name?</p>
<python><slack><slack-api>
2023-01-30 21:28:02
3
5,505
HuLu ViCa
75,290,271
7,056,539
pyproject.toml listing an editable package as a dependency for an editable package
<p>Using setuptools, is it possible to list another editable package as a dependency for an editable package?</p> <p>I'm trying to develop a collection of packages in order to use them across different production services, one of these packages (<code>my_pkg_1</code>) depends on a subset of my package collection (<code>my_pkg_2</code>, <code>my_pkg_x</code>, ...), so far, I've managed to put together this <code>pyproject.toml</code>:</p> <pre class="lang-ini prettyprint-override"><code>[build-system] requires = [&quot;setuptools&quot;] build-backend = &quot;setuptools.build_meta&quot; [project] name = &quot;my_pkg_1&quot; version = &quot;0.0.1&quot; dependencies = [ &quot;my_pkg_2 @ file:///somewhere/in/mysystem/my_pkg_2&quot; ] </code></pre> <p>which <em>does</em> work when/for installing <code>my_pkg_1</code> in editable mode, and it does install <code>my_pkg_2</code> but not in editable mode. this is what I see when I <code>pip list</code>:</p> <pre class="lang-bash prettyprint-override"><code>Package Version Editable project location --------------- ------- ------------------------- my_pkg_2 0.0.1 my_pkg_1 0.0.1 /somewhere/in/mysystem/my_pkg_1 </code></pre> <p>Is what I'm trying to do even possible? if so, how?</p>
<python><pip><setuptools><pyproject.toml>
2023-01-30 21:19:05
2
419
Nasa
75,290,101
3,357,935
Could Match.start(0) ever return -1 in Python?
<p>I recently came across a code block using Python's <a href="https://docs.python.org/3.11/library/re.html#" rel="nofollow noreferrer"><code>re</code> library</a> that had a confusing sanity check.</p> <pre><code>import re def someFunctionName(pattern, string): for match in re.finditer(pattern, string): match_offset = match.start(0) if match_offset == -1: raise IndexError(&quot;Capture group offset was -1.&quot;) </code></pre> <p>The <a href="https://docs.python.org/3.11/library/re.html#re.Match.start" rel="nofollow noreferrer">documentation for <code>Match.start([group])</code></a> says it will return <code>-1</code> if the specified group exists but did not contribute to the match. The documentation also says that a group of zero will refer to the entire matched substring. I can't think of any scenario where a match could exist without a matched substring, making the <code>-1</code> check seem unnecessary.</p> <p>Is there any scenario in which <code>Match.start(0)</code> could possibly return <code>-1</code>?</p>
<python><regex><python-re>
2023-01-30 21:01:30
0
27,724
Stevoisiak
75,289,851
2,594,812
Why does calling future.exception() in a done callback change the traceback
<p>I noticed that error messages in <a href="https://github.com/hadron/carthage" rel="nofollow noreferrer">Carthage</a> were sometimes getting truncated. That code is quite complex, so I worked on reproducing things in simpler form and found:</p> <ul> <li>If I attach a done callback to a coroutine that calls the <code>result</code> method</li> <li>I also await the coroutine elsewhere</li> <li>the coroutine raises a exception</li> </ul> <p>Then the traceback that eventually gets printed only includes the await call but not the portion of the traceback in the coroutine. However in the done callback never calls <code>result</code> I get the full traceback.</p> <pre class="lang-py prettyprint-override"><code>import asyncio async def my_traceback_gets_mangled(): def bar(): raise TypeError('I wish I had a traceback that let me find this bogus raise') await asyncio.sleep(1) bar() def done_cb(fut): try: fut.result() except: pass async def main(): fut = asyncio.ensure_future(my_traceback_gets_mangled()) fut.add_done_callback(done_cb) await fut asyncio.run(main()) </code></pre> <p>If I run that, I see:</p> <pre><code>Traceback (most recent call last): File &quot;/tmp/foo.py&quot;, line 18, in &lt;module&gt; asyncio.run(main()) File &quot;/usr/lib/python3.10/asyncio/runners.py&quot;, line 44, in run return loop.run_until_complete(main) File &quot;/usr/lib/python3.10/asyncio/base_events.py&quot;, line 649, in run_until_complete return future.result() File &quot;/tmp/foo.py&quot;, line 16, in main await fut TypeError: I wish I had a traceback that let me find this bogus raise </code></pre> <p>But if I remove the call to <code>fut.result</code>, then the traceback includes the call to bar and actually shows where the <code>TypeError</code> gets raised. Interestingly in pypy (rather than cpython), I get the behavior I expect, namely that I get the full traceback.</p>
<python><python-asyncio>
2023-01-30 20:35:14
0
6,539
Sam Hartman
75,290,757
24,894
Why is running 2 processes on 2 cores slower than on a single core?
<p>I would expect some overhead from context switching when running two processes on the same CPU core. What I didn't expect is so much overhead when running two processes on two separate CPU cores.</p> <p>Here is my Python program to do some counting:</p> <pre class="lang-python prettyprint-override"><code>import time start = time.time() j = 0 for i in range(0, 80000000): j += i elapsed = time.time() - start print(&quot;\nElapsed: %f&quot; % elapsed) </code></pre> <p>By itself this program completes in about 7 seconds. If I run this program twice simultaneously on the same CPU core:</p> <pre><code>$ taskset --cpu-list 0 time python3 cpu-bound.py &amp; taskset --cpu-list 0 time python3 cpu-bound.py &amp; Elapsed: 15.553317 7.77user 0.01system 0:15.59elapsed 49%CPU (0avgtext+0avgdata 8924maxresident)k 0inputs+0outputs (0major+942minor)pagefaults 0swaps Elapsed: 15.840124 8.10user 0.00system 0:15.90elapsed 50%CPU (0avgtext+0avgdata 9060maxresident)k 0inputs+0outputs (0major+946minor)pagefaults 0swaps </code></pre> <p>I get 14-15 seconds, which is expected as they run on the same CPU, so one has to be paused for the other one to run, etc. However, running the two processes on different CPU cores:</p> <pre><code>$ taskset --cpu-list 0 time python3 cpu-bound.py &amp; taskset --cpu-list 1 time python3 cpu-bound.py &amp; Elapsed: 17.081092 17.10user 0.00system 0:17.12elapsed 99%CPU (0avgtext+0avgdata 8848maxresident)k 0inputs+0outputs (0major+943minor)pagefaults 0swaps Elapsed: 17.094898 17.10user 0.00system 0:17.14elapsed 99%CPU (0avgtext+0avgdata 8948maxresident)k 0inputs+0outputs (0major+944minor)pagefaults 0swaps </code></pre> <p>I would expect each process to report a time that's close to the original 7 seconds, because the processes are running in parallel and on separate cores.</p> <p>However, I'm seeing 15-17 seconds execution on each process.</p> <p>Could anyone please shed some light on this behavior? Thank you!</p> <p><strong>Update</strong>: I'll describe the environments I tried to run this in below.</p> <p>First I ran this in a Docker container on an M1 Mac which has 4 cores. CPU 0 and 1 are the first and second core respectively. I then ran again on a t3.medium VM on AWS which has 2 vCPUs and observed similar results.</p> <p><strong>Update</strong>: I also got similar results in PHP, as well a php-fpm static pool with 1 worker (to run sequentially), with 2 workers with CPU affinity (to run in parallel on a single core) and with 2 workers without affinity (parallel on two cores). I observed the similar behavior -- running in parallel on separate cores is nowhere near as fast as an original single run.</p> <p>I then decided to try a similar program in C and the results were very different and very much in line with what I expected in the first place:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; int main() { time_t t; double elapsed; int i, j = 0; t = time(NULL); for (i = 0; i &lt;= 2000000000; i++) { j += i; } t = time(NULL) - t; elapsed = ((double) t); printf(&quot;Elapsed: %f\n&quot;, elapsed); return 0; } </code></pre> <p>A single run was about 6 seconds (time_t is rounded to seconds):</p> <pre><code>$ ./a.out Elapsed: 6.000000 </code></pre> <p>Two runs on a single CPU core yielded:</p> <pre><code>$ taskset --cpu-list 0 ./a.out &amp; taskset --cpu-list 0 ./a.out &amp; Elapsed: 12.00 Elapsed: 12.00 </code></pre> <p>Two runs on separate CPU cores gave:</p> <pre><code>$ taskset --cpu-list 0 ./a.out &amp; taskset --cpu-list 1 ./a.out &amp; Elapsed: 6.00 Elapsed: 6.00 </code></pre> <p>This behavior is more in line with what I expected in the first place, but why is it so drastically different for Python and PHP?</p>
<php><python><cpu-usage>
2023-01-30 20:18:25
1
32,751
kovshenin
75,289,619
1,825,360
problem.getSolutions() of constraint library yielding no solutions
<p>I'm trying to solve a small constraint problem using the &quot;constraint&quot; library in Python. The code is as follows but the solutions is empty. I was expecting a solution for Km * wt_Km (1 *42). Can somebody help in solving this? Thanks</p> <pre><code>from constraint import * wt_Nd = 1 wt_Qd = 1 wt_Km = 42 wt_Ka = 14 wt_Mx = 16 problem = Problem() problem.addVariable('Nd', range(1)) problem.addVariable('Qd', range(2)) problem.addVariable('Ka', range(2)) problem.addVariable('Km', range(2)) problem.addVariable('Mx', range(1)) value_diff = 42 problem.addConstraint(lambda Nd,Qd,Km,Ka,Mx: value_diff == Nd * wt_Nd + Qd * wt_Qd + Km * wt_Km + Ka * wt_Ka + Mx * wt_Mx , ('Nd','Qd','Km', 'Ka', 'Mx') ) solutions = problem.getSolutions() print(solutions) </code></pre>
<python><constraint-programming>
2023-01-30 20:10:30
1
469
The August
75,289,579
7,177,478
Leetcode 393: UTF-8 Validation (Python)
<p>problem:</p> <blockquote> <p>Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p> <p>A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:</p> <p>For a 1-byte character, the first bit is a 0, followed by its Unicode code. For an n-bytes character, the first n bits are all one's, the n</p> <ul> <li><p>1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10. This is how the UTF-8 encoding would work:</p> <p>Number of Bytes | UTF-8 Octet Sequence<br /> | (binary)<br /> --------------------+-----------------------------------------<br /> 1 | 0xxxxxxx<br /> 2 | 110xxxxx 10xxxxxx<br /> 3 | 1110xxxx 10xxxxxx 10xxxxxx<br /> 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx<br /> denotes a bit in the binary form of a byte that may be either 0 or 1.</p> </li> </ul> </blockquote> <p>I was trying to figure out this question. And one of the testcase is [250,145,145,145,145]. My code would return True, but the answer is False. My question is how is [250,145,145,145,145] a false?</p> <p>250: 11111010<br /> 145: 10010001</p> <p>Here is my code:</p> <pre><code>class Solution: def validUtf8(self, data: List[int]) -&gt; bool: def bitfield(n, length=8): digits = bin(n)[2:] rtn = ['0' for i in range(8)] start = length - len(digits) for i in range(len(digits)): rtn[start] = digits[i] start += 1 return rtn def check_byte_num(num: List[int]): if num[0] == '0': return 1 cnt = 0 for i in range(len(num)): if num[i] == '1': cnt += 1 else: return cnt return cnt def check_follow_char(num: List[int]): if num[0] == '1' and num[1] == '0': return True else: return False idx = 0 while idx &lt; len(data): char_bit = bitfield(data[idx]) if idx == len(data) - 1 and char_bit[0] != '0': return False char_num = check_byte_num(char_bit) char_num -= 1 idx += 1 while char_num &gt; 0: if idx &gt;= len(data): return False if not check_follow_char(bitfield(data[idx])): return False idx += 1 char_num -= 1 return True </code></pre>
<python><list><bit>
2023-01-30 20:05:24
0
420
Ian
75,289,517
353,337
Python string plus extra data, mutability
<p>I'm looking for a Python class that behaves exactly like <code>str</code> execpt that</p> <ul> <li>it should be mutable, i.e., its content modifyable in-place, and</li> <li>it should carry some extra data.</li> </ul> <p>This</p> <pre class="lang-py prettyprint-override"><code>class MyString(str): def __init__(self, string): super().__init__() self._foo = &quot;more data&quot; a = MyString(&quot;123&quot;) print(a) print(isinstance(a, str)) </code></pre> <pre><code>123 True more data </code></pre> <p>works for the extra-data part, but I'm not sure if I can modify <code>&quot;123&quot;</code>.</p> <p>Any hints?</p>
<python><string>
2023-01-30 19:59:52
2
59,565
Nico Schlömer
75,289,350
4,826,074
Keep only outer edges of object in an image
<p>I have a number of grayscale images as the left one below. I only want to keep the outer edges of the object in the image using python, preferably OpenCV. I have tried OpenCV erosion and then get the right image below. However, as seen in the image there is still brighter areas inside of the object. I want to remove those and only keep the outer edge. What would be an efficient way to achieve this? Simple thresholding will not work, because the bright &quot;stripes&quot; inside the object may sometimes be brighter than the edges. Edge detection will detect edges also inside the &quot;main&quot; edges.</p> <p>The right image - &quot;eroded_areas&quot; is achieved by the following code:</p> <pre><code> im = cv2.imread(im_path, cv2.IMREAD_GRAYSCALE) im_eroded = copy.deepcopy(im) kernel_size=3 kernel = np.ones((kernel_size, kernel_size), np.uint8) im_eroded = cv2.erode(im_eroded, kernel, iterations=1) eroded_areas = im - im_eroded plt.imshow(eroded_areas) </code></pre> <p><a href="https://i.sstatic.net/4lz6E.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4lz6E.png" alt="enter image description here" /></a></p>
<python><opencv>
2023-01-30 19:41:48
2
380
Johan hvn
75,289,188
8,119,069
Trying to make a scrollable table with tkinter
<p>I'm trying to make a scrollable <strong>grid</strong> table. I had a look at some answers and it seems the way is to make a <strong>Frame</strong>, then put a <strong>Canvas</strong> and a <strong>Scrollbar</strong> next to eachother and apply some commands for scrolling. I have this code here, but I can't figure out what is wrong with this.</p> <pre><code>import tkinter as tk class Test: def __init__(self): self.root = tk.Tk() table_and_scrollbar_frame = tk.Frame(self.root) table_frame = tk.Canvas(table_and_scrollbar_frame) table_frame.grid(row=0, column=0) self.table_headers = [&quot;header_1&quot;, &quot;header_2&quot;, &quot;header_3&quot;, &quot;header_4&quot;] for test_row in range(0,100): for header_to_create in self.table_headers: current_entry = tk.Entry(table_frame, width=25, justify='center') current_entry.insert(0, header_to_create + &quot; &quot; + str(test_row)) current_entry.configure(state='disabled', disabledforeground='blue') current_entry.grid(row=test_row, column=self.table_headers.index(header_to_create)) table_scrollbar = tk.Scrollbar(table_and_scrollbar_frame, orient='vertical', command=table_frame.yview) table_scrollbar.grid(row=0, column=1, sticky='ns') table_frame.configure(yscrollcommand=table_scrollbar.set) table_frame.config(scrollregion=table_frame.bbox(&quot;all&quot;)) table_and_scrollbar_frame.pack() return if __name__ == '__main__': program = Test() program.root.mainloop() </code></pre> <p>I'm not sure what is wrong/missing here?</p>
<python><python-3.x><tkinter><tkinter-canvas>
2023-01-30 19:25:03
1
501
DoctorEvil
75,289,181
15,341,457
Join rows and concatenate attribute values in a csv file with pandas
<p>I have a csv file structured like this:</p> <p><a href="https://i.sstatic.net/qhA56.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qhA56.png" alt="enter image description here" /></a></p> <p>As you can see, many lines are repeated (they represent the same entity) with the attribute 'category' being the only difference between each other. I would like to join those rows and include all the categories in a single value.</p> <p>For example the attribute 'category' for Walmart should be: &quot;Retail, Dowjones, SuperMarketChains&quot;.</p> <p>Edit:</p> <p>I would like the output table to be structured like this:</p> <p><a href="https://i.sstatic.net/6t0HO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6t0HO.png" alt="enter image description here" /></a></p> <p>Edit 2:</p> <p>What worked for me was:</p> <pre><code>df4.groupby([&quot;ID azienda&quot;,&quot;Name&quot;,&quot;Company code&quot;, &quot;Marketcap&quot;, &quot;Share price&quot;, &quot;Earnings&quot;, &quot;Revenue&quot;, &quot;Shares&quot;, &quot;Employees&quot;] )['Category'].agg(list).reset_index() </code></pre>
<python><pandas><csv><join><row>
2023-01-30 19:24:09
2
332
Rodolfo
75,289,130
4,718,335
Flatten nested Pydantic model
<pre class="lang-py prettyprint-override"><code>from typing import Union from pydantic import BaseModel, Field class Category(BaseModel): name: str = Field(alias=&quot;name&quot;) class OrderItems(BaseModel): name: str = Field(alias=&quot;name&quot;) category: Category = Field(alias=&quot;category&quot;) unit: Union[str, None] = Field(alias=&quot;unit&quot;) quantity: int = Field(alias=&quot;quantity&quot;) </code></pre> <p>When instantiated like this:</p> <pre class="lang-py prettyprint-override"><code>OrderItems(**{'name': 'Test','category':{'name': 'Test Cat'}, 'unit': 'kg', 'quantity': 10}) </code></pre> <p>It returns data like this:</p> <pre class="lang-py prettyprint-override"><code>OrderItems(name='Test', category=Category(name='Test Cat'), unit='kg', quantity=10) </code></pre> <p>But I want the output like this:</p> <pre class="lang-py prettyprint-override"><code>OrderItems(name='Test', category='Test Cat', unit='kg', quantity=10) </code></pre> <p>How can I achieve this?</p>
<python><fastapi><pydantic>
2023-01-30 19:18:16
5
1,864
Russell
75,289,020
5,278,205
Remove duplicate numbers separated by a symbol in a string using Hive's REGEXP_REPLACE
<p>I have a spark dataframe with a string column that includes numbers separated by <code>;</code>, for example: <code>862;1595;17;862;49;862;19;100;17;49</code>, I would like to remove the duplicated numbers, leaving the following: <code>862;1595;17;49;19;100</code></p> <p>As far as patterns go I have tried</p> <ol> <li><code>&quot;\\b(\\d+(?:\\.\\d+)?) ([^;]+); (?=.*\\b\\1 \\2\\b)</code></li> <li><code>(?&lt;=\b\1:.*)\b(\w+):?</code></li> <li><code>\\b(+)\\b(?=.*?\\b\1\\b)</code></li> <li><code>(\b[^,]+)(?=.*, *\1(?:,|$)), *</code></li> </ol> <p>But nothing has yielded what I need thus far.</p>
<python><regex><pyspark><hive><sparklyr>
2023-01-30 19:07:09
1
5,213
Cyrus Mohammadian
75,288,973
6,387,095
Pandas - compare day and month only against a datetime?
<p>I want to compare a <code>timestamp</code> datatype <code>datetime64[ns]</code> with a <code>datetime.date</code> I only want a comparison based on <code>day and month</code></p> <p>df</p> <pre><code> timestamp last_price 0 2023-01-22 14:15:06.033314 100.0 1 2023-01-25 14:15:06.213591 101.0 2 2023-01-30 14:15:06.313554 102.0 3 2023-03-31 14:15:07.018540 103.0 cu_date = datetime.datetime.now().date() cu_year = cu_date.year check_end_date = datetime.datetime.strptime(f'{cu_year}-11-05', '%Y-%m-%d').date() check_start_date = datetime.datetime.strptime(f'{cu_year}-03-12', '%Y-%m-%d').date() # this is incorrect as the day can be greater than check_start_date while the month might be less. daylight_off_df = df.loc[((df.timestamp.dt.month &gt;= check_end_date.month) &amp; (df.timestamp.dt.day &gt;= check_end_date.day)) | ((df.timestamp.dt.month &lt;= check_start_date.month) &amp; (df.timestamp.dt.day &lt;= check_start_date.day))] daylight_on_df = df.loc[((df.timestamp.dt.month &lt;= check_end_date.month) &amp; (df.timestamp.dt.day &lt;= check_end_date.day)) &amp; ((df.timestamp.dt.month &gt;= check_start_date.month) &amp; (df.timestamp.dt.day &gt;= check_start_date.day))] </code></pre> <p>I am trying to think up of the logic to do this, but failing.</p> <p>Expected output:</p> <p>daylight_off_df</p> <pre><code> timestamp last_price 0 2023-01-22 14:15:06.033314 100.0 1 2023-01-25 14:15:06.213591 101.0 2 2023-01-30 14:15:06.313554 102.0 </code></pre> <p>daylight_on_df</p> <pre><code> timestamp last_price 3 2023-03-31 14:15:07.018540 103.0 </code></pre> <p>In summation separate the dataframe as per day and month comparison while ignoring the year.</p>
<python><pandas><datetime>
2023-01-30 19:02:22
2
4,075
Sid