content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Saving Pytorch model.state_dict() to s3 I am trying to save a trained Pytorch model to S3. However, the torch.save(model.state_dict(), file_name) seems to support only local files. How can the state dict be saved to an S3 file? I'm using Torch 0.4.0 A: As discussed by Soumith Chintala, Pytorch doesn't have custo...
Saving Pytorch model.state_dict() to s3
I am trying to save a trained Pytorch model to S3. However, the torch.save(model.state_dict(), file_name) seems to support only local files. How can the state dict be saved to an S3 file? I'm using Torch 0.4.0
[ "As discussed by Soumith Chintala, Pytorch doesn't have custom APIs to do this job. However you can use boto3 or Petastorm library to solve the problem.\nHere's a concrete example to write to an S3 object directly:\nimport boto3\n\n# Convert your existing model to JSON\nsaved_model = model.to_json()\n\n# Write JSON...
[ 3, 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0056144895_python_pytorch.txt
Q: Altair choropleth - Get geometry from transform_lookup I am trying to draw a choropleth map of municipalties in Denmark with color encoded as a sum of crimes in that municipalty. I have several entries for each municipalty since the data is over a time-period and types of crime and I have a single geometry entry f...
Altair choropleth - Get geometry from transform_lookup
I am trying to draw a choropleth map of municipalties in Denmark with color encoded as a sum of crimes in that municipalty. I have several entries for each municipalty since the data is over a time-period and types of crime and I have a single geometry entry for each municipalty. I want to perform a transform_lookup on...
[ "I think you're running into an issue similar to HConcat of mark_geoshape and mark_bar breaks depending of order (and the comments in the linked vega-lite issue). If you change the order of the data frames it will work.\nThere also seems to be some issue with the aggregation which I think is related to this issue h...
[ 1, 1 ]
[]
[]
[ "altair", "geopandas", "python", "vega_lite" ]
stackoverflow_0074151366_altair_geopandas_python_vega_lite.txt
Q: SyntaxError: unicodeescape I am trying to build a bot which gives a random answer from CSV file. Piece of code I have problem with: def get_data(lounaslista): with open('C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv', 'r') as f: r = csv.reader(f) data = [row for row in r] return data ...
SyntaxError: unicodeescape
I am trying to build a bot which gives a random answer from CSV file. Piece of code I have problem with: def get_data(lounaslista): with open('C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv', 'r') as f: r = csv.reader(f) data = [row for row in r] return data Error I'm getting: SyntaxError: ...
[ "Use double slash instead of simple slash in path.\ndef get_data(lounaslista):\n with open('C:\\\\Users\\\\p7l1n\\\\Desktop\\\\lounasbotti\\\\lounaslista.csv', 'r') as f:\n r = csv.reader(f)\n data = [row for row in r]\n return data\n\nExample with simple variable:\na = 'C:\\Users\\p7l1n\\Deskto...
[ 1, 1, 1 ]
[]
[]
[ "python", "python_unicode" ]
stackoverflow_0074207089_python_python_unicode.txt
Q: Fastest way to transform a continuous string of hex into base 10 in Python I have a 100M 3600 character length strings of hexadecimal digits that I want to split into blocks of three and then convert into base 10. Strictly speaking, I want to transform these into signed 4 byte numbers. DEADBEEF2022 -> (Split) DEA,...
Fastest way to transform a continuous string of hex into base 10 in Python
I have a 100M 3600 character length strings of hexadecimal digits that I want to split into blocks of three and then convert into base 10. Strictly speaking, I want to transform these into signed 4 byte numbers. DEADBEEF2022 -> (Split) DEA, DBE, EF2, 022 -> (Convert) 3562, 3518, 3862, 034 -> (Signed) 534, 578, 234, 03...
[ "\nAre there any ways I can improve the speed of this code?\n\nYou might try using functools.lru_cache decorator which will save and then use values for already seen input rather than computing it again following way\nimport functools\n@functools.lru_cache(4096)\ndef to_hex(a):\n number = int(a, 16)\n if num...
[ 2 ]
[]
[]
[ "optimization", "performance", "python" ]
stackoverflow_0074207045_optimization_performance_python.txt
Q: Reduce number of tiles of an image I have a list of images that I want to simplify by generating a tile list and indexing the image. Right now I'm testing with a single image and trying to find out a good alogorithm to compare the tiles. I might have to throw everything out and see if I can do something better. Ri...
Reduce number of tiles of an image
I have a list of images that I want to simplify by generating a tile list and indexing the image. Right now I'm testing with a single image and trying to find out a good alogorithm to compare the tiles. I might have to throw everything out and see if I can do something better. Right now I have this code: def tileize(im...
[ "You should not use __eq__, __hash__ and set like this since they are not designed for what you are looking for, i.e. approximate equality. One fondamental property of __eq__ and __hash__ is that if two objects are equal then their hash should be equal too. This invariant is not respected in your implementation.\n...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074205378_opencv_python.txt
Q: Recursive type annotations I'm trying to introduce static type annotations to my codebase where applicable. One case is when reading a JSON, the resulting object will be a dictionary keyed by strings, with values of one of the following types: bool str float int list dict However the list and dict above can cont...
Recursive type annotations
I'm trying to introduce static type annotations to my codebase where applicable. One case is when reading a JSON, the resulting object will be a dictionary keyed by strings, with values of one of the following types: bool str float int list dict However the list and dict above can contain that same sort of dictionary...
[ "As of mypy 0.990, mypy finally supports recursive type annotations, using the natural syntax:\nfrom typing import Union, Dict, List\n\nJSONVal = Union[None, bool, str, float, int, List['JSONVal'], Dict[str, 'JSONVal']]\n\nd: JSONVal = {'a': ['b']}\n\nmypy output:\nSuccess: no issues found in 1 source file\n\nBefor...
[ 11, 4 ]
[ "For more recent versions of mypy, this comment to the mentioned MyPy issue tracker suggests a partially working (but a bit convoluted) way of doing this using protocols, as long a using TypeVar is not required:\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom typing import TypeVar,...
[ -1 ]
[ "python", "python_3.x", "typing" ]
stackoverflow_0053638973_python_python_3.x_typing.txt
Q: How to load a BigQuery table from a file in GCS Bucket using Airflow? I am new to Airflow, and I am wondering, how do I load a file from a GCS Bucket to BigQuery? So far, I have managed to do BigQuery to GCS Bucket: bq_recent_questions_query = bigquery_operator.BigQueryOperator( task_id='bq_recent_questions_qu...
How to load a BigQuery table from a file in GCS Bucket using Airflow?
I am new to Airflow, and I am wondering, how do I load a file from a GCS Bucket to BigQuery? So far, I have managed to do BigQuery to GCS Bucket: bq_recent_questions_query = bigquery_operator.BigQueryOperator( task_id='bq_recent_questions_query', sql=""" SELECT owner_display_name, title, view_count FROM...
[ "For your requirement, you can use GCSToBigQueryOperator which is an operator in airflow to transfer files from Cloud Storage to BigQuery.For more information, check this link. You can try the below code.\ngcs_to_bq_operator.py\nimport os\nfrom airflow import DAG\nfrom airflow import models\nfrom airflow.providers...
[ 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "google_bigquery", "google_cloud_storage", "python" ]
stackoverflow_0074191180_airflow_directed_acyclic_graphs_google_bigquery_google_cloud_storage_python.txt
Q: Calculate the which percentile a value belongs to in a dataframe I have a dataframe with different categorical variables, year and expenditure. I would like to calculate the mean of the expenditure variable by group. Then I would like to calculate what percentile this mean corresponds to in the entire dataset of e...
Calculate the which percentile a value belongs to in a dataframe
I have a dataframe with different categorical variables, year and expenditure. I would like to calculate the mean of the expenditure variable by group. Then I would like to calculate what percentile this mean corresponds to in the entire dataset of expenditures. I would like to know this percentile value for the mean o...
[ "You should provide the expected output, but if I guess correctly you might want:\nfrom scipy import stats\n\nmeans['percentile'] = (means.groupby(['fkg','dkg', 'year'])\n .apply(lambda x: stats.percentileofscore(means['expenditure'], x)[0, 0])\n )\n\noutput:\n ...
[ 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0074207231_python_scipy.txt
Q: How to pass a list of fixtures to a test case in Pytest? I have a case where I need a list of fixtures (similar ones) inside a test case and perform same operation with those fixtures. For ex: def testcase(fixture1, fixture2, fixture3): # do some operation with fixture1 # do the same operation with fixture...
How to pass a list of fixtures to a test case in Pytest?
I have a case where I need a list of fixtures (similar ones) inside a test case and perform same operation with those fixtures. For ex: def testcase(fixture1, fixture2, fixture3): # do some operation with fixture1 # do the same operation with fixture2 # do the same operation with fixture3 The thing is I ha...
[ "I was able to achieve this by creating another fixture and returning the fixtures inside that fixture.\ndef fixture_that_returns_other_fixtures(fix1, fix2, fix3):\n return fix1, fix2, fix3\n\nand used fixture_that_returns_other_fixtures in all other tests wherever needed.\n", "From the pytest doc Here:\nimpor...
[ 1, 0 ]
[]
[]
[ "iterable", "pytest", "pytest_fixtures", "python", "python_3.x" ]
stackoverflow_0074203348_iterable_pytest_pytest_fixtures_python_python_3.x.txt
Q: Execute next() after the iteration in for loop in Python I have a dataclass reading data from some source. I made __iter__ and __next__ methods for this class, to be able to loop through it: def __iter__(self): # Return to the first entry, if it is not the current one if self._tree.GetReadEntry() != 0: ...
Execute next() after the iteration in for loop in Python
I have a dataclass reading data from some source. I made __iter__ and __next__ methods for this class, to be able to loop through it: def __iter__(self): # Return to the first entry, if it is not the current one if self._tree.GetReadEntry() != 0: self._tree.GetEntry(0) return self ## The next() me...
[ "A way to solve it is to change the class from iterator to iterable, as suggested in this topic. This way the first value that a for loop gets is the first entry from the data source. I am not aware of a way to do it with iterator.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074183440_python.txt
Q: install additional on azure for use with python webapp I am creating a webapp using Dash. I have created the requirements file to install the different python modules I need. One of the modules, Pyspice, works as interface to a program called ngspice. The question is how do I install ngspice on the azure app plan ...
install additional on azure for use with python webapp
I am creating a webapp using Dash. I have created the requirements file to install the different python modules I need. One of the modules, Pyspice, works as interface to a program called ngspice. The question is how do I install ngspice on the azure app plan I have. I can see the app plan is running Linux. But how do ...
[ "You can open an SSH session via azure portal, in your app service blade:\n\nAlso, you can open an SSH session in browser\nPaste the following URL into your browser and replace with your app name:\nhttps://<app-name>.scm.azurewebsites.net/webssh/host\n\nMore info: https://learn.microsoft.com/en-us/azure/app-servic...
[ 2 ]
[]
[]
[ "azure_web_app_service", "dependencies", "python" ]
stackoverflow_0074207143_azure_web_app_service_dependencies_python.txt
Q: How can i delete all my tweets using twitter api I'm trying to delete all the tweets/replies from my account, at first it worked, but it got to a point where he stopped deleting, and he can't receive the tweets anymore, giving the error: File "main.py", line 29, in fetch_tweets oldest = all_tweets[-1].id - 1 ...
How can i delete all my tweets using twitter api
I'm trying to delete all the tweets/replies from my account, at first it worked, but it got to a point where he stopped deleting, and he can't receive the tweets anymore, giving the error: File "main.py", line 29, in fetch_tweets oldest = all_tweets[-1].id - 1 IndexError: list index out of range and on my account...
[ "The API can only go back so far in retrieving older Tweets.\nAnother option would be to request your Twitter Archive, which would contain the Tweet IDs and content - you can then potentially use the API to delete Tweets by ID.\nNote that there are account and API rate limits that will restrict the speed at which y...
[ 1 ]
[]
[]
[ "api", "python", "tweepy", "twitter" ]
stackoverflow_0074207264_api_python_tweepy_twitter.txt
Q: unable to load whole data from mongodb atlas using python I have a python program to fetch data in a collection from mongodb atlas but i am able to view only 10 data using the below python code from pymongo import MongoClient from pprint import pprint client = MongoClient("mongodb+srv://####:#####@cluster0.0gdmi0s...
unable to load whole data from mongodb atlas using python
I have a python program to fetch data in a collection from mongodb atlas but i am able to view only 10 data using the below python code from pymongo import MongoClient from pprint import pprint client = MongoClient("mongodb+srv://####:#####@cluster0.0gdmi0s.mongodb.net/retryWrites=true&w=majority") db = client.test col...
[ "Might you have 10 users only..\nfrom pymongo import MongoClient\nfrom pprint import pprint\nclient = MongoClient(\"mongodb+srv://####:#####@cluster0.0gdmi0s.mongodb.net/retryWrites=true&w=majority\")\ndb = client.test\ncollection = db.user.find()\nfor i in collection:\n pprint(i)\n\n" ]
[ 1 ]
[]
[]
[ "mongodb", "mongodb_atlas", "python" ]
stackoverflow_0074206350_mongodb_mongodb_atlas_python.txt
Q: Fastapi app: empty array or TypeError: Boolean value of this clause is not defined So, Im doing simple todo-api app with fastapi and sqlmodel. Migrations went fine, but if I run my server, I dont see anything except empy array. I added some data in db file with DB Browser for SQLite, so it isn't empty. And when I ...
Fastapi app: empty array or TypeError: Boolean value of this clause is not defined
So, Im doing simple todo-api app with fastapi and sqlmodel. Migrations went fine, but if I run my server, I dont see anything except empy array. I added some data in db file with DB Browser for SQLite, so it isn't empty. And when I run my server and go to "/", I see only empty array and no data, and if I go to "/1/", I...
[ "From reading the Traceback, I'd say that whatever type statement.where(ToDo.id==id) returns, seems not to have a __bool__() Magic Method defined. So you can't check for \"truthy-ness\" in the if statement.\n", "So, the exception is that you're not actually executing the statement in select_todo before checking f...
[ 1, 1 ]
[]
[]
[ "backend", "fastapi", "python", "sqlmodel" ]
stackoverflow_0074206657_backend_fastapi_python_sqlmodel.txt
Q: cryptography.fernet.InvalidToken problem with cryptography Getting this error when trying to run this: File "Test Files.py", line 502, in decryptdefault decrypted = fernet.decrypt(d) File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 74, in decrypt timestamp, data = Fernet._get_unverified_token...
cryptography.fernet.InvalidToken problem with cryptography
Getting this error when trying to run this: File "Test Files.py", line 502, in decryptdefault decrypted = fernet.decrypt(d) File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 74, in decrypt timestamp, data = Fernet._get_unverified_token_data(token) File "/usr/lib/python3/dist-packages/cryptography...
[ "I have found out, through trial and error with the same project later down the line, that you need to turn your key into something like this key = b'niwaXsYbDiAxmLiqRiFbDa_8gHio15sNQ6ZO-sQ0nR4='\nThe main difference being the key is encoded in a utf-8 format and is now readable by Fernet and doesn't return that er...
[ 1 ]
[]
[]
[ "cryptography", "python" ]
stackoverflow_0071511610_cryptography_python.txt
Q: Updating Binary File on Github using Contents API After successfully updating a plain text file using the GitHub Repository Contents API, I tried to do the same thing with an Excel file. I understand that git isn't really designed to store binaries; however, this is what my client needs. Here are the relevant line...
Updating Binary File on Github using Contents API
After successfully updating a plain text file using the GitHub Repository Contents API, I tried to do the same thing with an Excel file. I understand that git isn't really designed to store binaries; however, this is what my client needs. Here are the relevant lines of Python code: # Get the XLSX file from the repo to ...
[ "Uploading a binary file is very much possible to GitHub. Both via git and via the GitHub API.\nThe following python snippet works as expected and uploads an excel file to a test repository at https://github.com/recycle-bin/github-playground/tree/main/hello . And I'm able to download the excel file as expected too....
[ 0 ]
[]
[]
[ "github_api", "python" ]
stackoverflow_0074091860_github_api_python.txt
Q: Create one stacked bar plot from one normalized dataframe column I'm struggling with creating a single stacked barplot from the dataframe below: sender_department Sales 0.441629 Operations 0.288440 Admin 0.244021 IT 0.013952 Engineering ...
Create one stacked bar plot from one normalized dataframe column
I'm struggling with creating a single stacked barplot from the dataframe below: sender_department Sales 0.441629 Operations 0.288440 Admin 0.244021 IT 0.013952 Engineering 0.007403 Marketing 0.004556 sender_department colu...
[ "I finally came up with this idea:\ndf.transpose()\n\nactive_senders.plot.barh(stacked=True)\n\nIs there a more pythonic way to do that?\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python", "seaborn", "visualization" ]
stackoverflow_0074206436_matplotlib_python_seaborn_visualization.txt
Q: How can this code for calculating a list of all dictionary values that occur only once be improved to less than quadratic complexity? Given a python dictionary. I've written a function that returns a list of keys whose values are unique in the given dictionary. Let's say that aDict = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4,...
How can this code for calculating a list of all dictionary values that occur only once be improved to less than quadratic complexity?
Given a python dictionary. I've written a function that returns a list of keys whose values are unique in the given dictionary. Let's say that aDict = {1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}. The function returns [1, 3, 8]. Keys that are mapped to 0 aren't returned because their share value with other key. The function w...
[ "You can do that in linear time like this\nfrom collections import defaultdict\n\ndef foo1(aDict):\n capture = defaultdict(lambda: 0)\n for i in aDict:\n capture[aDict[i]] += 1\n return [k for k in aDict if capture[aDict[k]] < 2]\n\nprint(foo1({1: 1, 3: 2, 6: 0, 7: 0, 8: 4, 10: 0}))\n\n", "One lin...
[ 3, 2, 1 ]
[]
[]
[ "dictionary", "python", "time_complexity" ]
stackoverflow_0074207428_dictionary_python_time_complexity.txt
Q: Python + UDP socket - can not recieve any data I want to recieve data by using UDP socket in Python. I send UDP data from my external HW every 1 second (connected with my PC via Ethernet cable). Also I can see data in the Wireshark: and also I can recieve data in Hercules: Also I can ping to my HW and get respon...
Python + UDP socket - can not recieve any data
I want to recieve data by using UDP socket in Python. I send UDP data from my external HW every 1 second (connected with my PC via Ethernet cable). Also I can see data in the Wireshark: and also I can recieve data in Hercules: Also I can ping to my HW and get response. What I have already tried import socket localIP...
[ "Disabling firewall is the solution - now it works!\n" ]
[ 1 ]
[]
[]
[ "ethernet", "python", "sockets", "udp" ]
stackoverflow_0074203913_ethernet_python_sockets_udp.txt
Q: How do i get this code to work? login/register program in python with dictionary and functions login_input = {"MEK1300":"Python"} username = {} user = input("To login enter Yes. If you want to register enter No: ") def login_info(): if user == "Yes": login_user() else: user == "No" regist...
How do i get this code to work? login/register program in python with dictionary and functions
login_input = {"MEK1300":"Python"} username = {} user = input("To login enter Yes. If you want to register enter No: ") def login_info(): if user == "Yes": login_user() else: user == "No" register_user() return user def register_user(): new_user = input("Enter a username: ") ...
[ "I think youre code is fine you need to call you first fucnction to begin the quiz with login_info()\nUpdated code:\nlogin_input = {\"MEK1300\":\"Python\"}\nusername = {}\nuser = input(\"To login enter Yes. If you want to register enter No: \") \n\ndef login_info():\n if user.upper() == \"YES\": #Convert YeS t...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074207235_python.txt
Q: Cannot install ggplot with anaconda I want to be able to use geom_smooth in ggplot. However, when I typed conda install ggplot, I get the error no packages found in current win-32 channels matching ggplot. Anyone know what is going on? A: Have you tried looking at www.binstar.org? Type in ggplot in the search ba...
Cannot install ggplot with anaconda
I want to be able to use geom_smooth in ggplot. However, when I typed conda install ggplot, I get the error no packages found in current win-32 channels matching ggplot. Anyone know what is going on?
[ "Have you tried looking at www.binstar.org? Type in ggplot in the search bar (I have already done so and it pops up with different options, one of which is a win32 channel. Since I have already looked at it this is what you should type into the command shell:\n conda install -c https://conda.binstar.org/bokeh gg...
[ 7, 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "anaconda", "python", "python_ggplot", "windows" ]
stackoverflow_0029312985_anaconda_python_python_ggplot_windows.txt
Q: Convert tuple to list and back I'm currently working on a map editor for a game in pygame, using tile maps. The level is built up out of blocks in the following structure (though much larger): level1 = ( (1,1,1,1,1,1) (1,0,0,0,0,1) (1,0,0,0,0,1) (1,0,0,0,0,1) (1,0,0,0,0...
Convert tuple to list and back
I'm currently working on a map editor for a game in pygame, using tile maps. The level is built up out of blocks in the following structure (though much larger): level1 = ( (1,1,1,1,1,1) (1,0,0,0,0,1) (1,0,0,0,0,1) (1,0,0,0,0,1) (1,0,0,0,0,1) (1,1,1,1,1,1)) where "...
[ "Convert tuple to list:\n>>> t = ('my', 'name', 'is', 'mr', 'tuple')\n>>> t\n('my', 'name', 'is', 'mr', 'tuple')\n>>> list(t)\n['my', 'name', 'is', 'mr', 'tuple']\n\nConvert list to tuple:\n>>> l = ['my', 'name', 'is', 'mr', 'list']\n>>> l\n['my', 'name', 'is', 'mr', 'list']\n>>> tuple(l)\n('my', 'name', 'is', 'mr'...
[ 364, 89, 27, 21, 20, 16, 5, 5, 2, 2, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0016296643_list_python_tuples.txt
Q: Is there a way to "transform" a CSV table into a simple nested if... else block in python? I'm fairly new to python and I'm looking forward to achieve the following: I have a table with several conditions as in the image below (maximum 5 conditions) along with various attributes. Each condition comes from a specif...
Is there a way to "transform" a CSV table into a simple nested if... else block in python?
I'm fairly new to python and I'm looking forward to achieve the following: I have a table with several conditions as in the image below (maximum 5 conditions) along with various attributes. Each condition comes from a specific set of values, for example Condition 1 has 2 possible values, Condition 2 has 4 possible valu...
[ "You can't really use \"If\"s and \"else\"s, since, if I understand your question correctly, you want to be able to read the conditions, attributes and values from a CSV file. Using \"If\"s and \"else\"s, you would only be able to check a fixed range of conditions and attributes defined in your code. What I would d...
[ 0 ]
[]
[]
[ "csv", "python", "python_3.x" ]
stackoverflow_0074204686_csv_python_python_3.x.txt
Q: SQLAlchemy DetachedInstanceError when Unit testing with Flask app.test_client My goal is to be able to test routes with the Flask app test_client using self.client.post(url, .... The problem that I'm running into is any time I make a request using it, I hit a DetachedInstanceError from SQLAlchemy, saying that eith...
SQLAlchemy DetachedInstanceError when Unit testing with Flask app.test_client
My goal is to be able to test routes with the Flask app test_client using self.client.post(url, .... The problem that I'm running into is any time I make a request using it, I hit a DetachedInstanceError from SQLAlchemy, saying that either refresh or lazy loading operations cannot occur. Here's my setup: class BaseTest...
[ "try something like this\nclass BaseTestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n self.postgresql = Postgresql()\n config = {\n 'FLASK_ENV': 'test',\n 'SQLALCHEMY_DATABASE_URI': self.postgresql.url()\n }\n with patch.dict('os.environ',...
[ 0 ]
[]
[]
[ "flask", "python", "python_unittest", "sqlalchemy" ]
stackoverflow_0056623301_flask_python_python_unittest_sqlalchemy.txt
Q: How to get correct Angle using python I am try to find the angle of line i know the coordinate points Start Point : 404, 119 Mid Point : 279, 214 End Point : 154, 310 import numpy as np def findangle(x1,y1,x2,y2,x3,y3): ria = np.arctan2(y2 - y1, x2 - x1) - np.arctan2(y3 - y1, x3 - x1) webangle = int(n...
How to get correct Angle using python
I am try to find the angle of line i know the coordinate points Start Point : 404, 119 Mid Point : 279, 214 End Point : 154, 310 import numpy as np def findangle(x1,y1,x2,y2,x3,y3): ria = np.arctan2(y2 - y1, x2 - x1) - np.arctan2(y3 - y1, x3 - x1) webangle = int(np.abs(ria * 180 / np.pi)) return webang...
[ "It's a simple math. The numpy.arctan2() returns a value in the range [-π, π]. So a difference of two values is in the range [-2π, 2π], and the absolute value of that is in the range [0, 2π]. You want an angle x in the range [0, π], and x is equivalent to (2π - x) in your context. So you can take x if x < π, and ta...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074206661_python.txt
Q: Sort tuple containing various data types in Python I'm faced with the following tuple containing several various datatypes: my_test_tuple = ( ["David", 3.14], [34, "Zak"], ["Colin", 54], [34, "Xerxes", True], ["Fred"] ) I need to sort it by the names alphabetically in descending order. The output should look the ...
Sort tuple containing various data types in Python
I'm faced with the following tuple containing several various datatypes: my_test_tuple = ( ["David", 3.14], [34, "Zak"], ["Colin", 54], [34, "Xerxes", True], ["Fred"] ) I need to sort it by the names alphabetically in descending order. The output should look the following: print(sort_tuple (my_test_tuple)) (['Colin', ...
[ "You can extract the names with list comprehension and then sort the original tuple/list based on the order of the new list you created:\nnames_tuple = [item[sub_item] for item in my_test_tuple for sub_item in item if type(sub_item) == str]\nsorted_list = tuple([x for _,x in sorted(zip(names_tuple, my_test_tuple))]...
[ 0, 0 ]
[]
[]
[ "python", "sorting", "tuples" ]
stackoverflow_0074205793_python_sorting_tuples.txt
Q: How to print the highest mAP in yolov7 from the training? When I train yolov7 using the following command !python train.py --data {dataset.location}/data.yaml --weights 'yolov7_training.pt' --device 0 --hyp "hyp.scratch.custom.yaml" Output: Epoch gpu_mem box obj cls total labels img_...
How to print the highest mAP in yolov7 from the training?
When I train yolov7 using the following command !python train.py --data {dataset.location}/data.yaml --weights 'yolov7_training.pt' --device 0 --hyp "hyp.scratch.custom.yaml" Output: Epoch gpu_mem box obj cls total labels img_size 100/299 10.5G 0.05475 0.02964 0 0.084...
[ "I set up wanb and added a Weave with the following line to get it\nruns.map((row) => row.history[\"metrics/mAP_0\\.5(B)\"].max)\n\n" ]
[ 0 ]
[]
[]
[ "computer_vision", "python", "yolo" ]
stackoverflow_0074142124_computer_vision_python_yolo.txt
Q: How to make a pyramid using recursion in python? I need to make a pyramid in python using recursion. Already made it, but I need help making it with recursion. def pyramid(n): for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("\r") pyramid(5) A: ...
How to make a pyramid using recursion in python?
I need to make a pyramid in python using recursion. Already made it, but I need help making it with recursion. def pyramid(n): for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("\r") pyramid(5)
[ "Recursion = the repeated application of a recursive procedure.\nCode:\ndef pyramid(n):\n if n==0:\n return\n else:\n pyramid(n-1)\n print(\"* \"*n)\n\nn = 10\npyramid(n)\n\nThis just repeats the function until n = 0.\n", "Matei's solution is reasonable, but since the original used a ne...
[ 5, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074207589_python_recursion.txt
Q: Compare two pandas dataframes and create column if condition is met Suppose I have these two dataframes: df1= ID index 087 4 087 5 087 6 df2= ID index 087 1 087 2 087 3 ... 087 10 087 11 087 12 ... And I would like to compare/join them based on the ID and index columns and the...
Compare two pandas dataframes and create column if condition is met
Suppose I have these two dataframes: df1= ID index 087 4 087 5 087 6 df2= ID index 087 1 087 2 087 3 ... 087 10 087 11 087 12 ... And I would like to compare/join them based on the ID and index columns and then create a 'pred' column in the rows that df1 also has. So that the resul...
[ "I would do it following way\nimport pandas as pd\ndf1 = pd.DataFrame({\"ID\":[87,87,87],\"index\":[4,5,6]})\ndf2 = pd.DataFrame({\"ID\":[87,87,87,87,87,87],\"index\":[1,2,3,10,11,12]})\ndf1[\"pred\"] = 1 # mark rows of df1\ndf = df1.merge(df2,\"outer\",[\"ID\",\"index\"])\ndf.pred = df.pred.fillna(0.0)\nprint(df)\...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074207598_dataframe_pandas_python.txt
Q: convert html file to BytesIO then pass as Flask variable I'm trying to convert a HTML file to BytesIO so that I don't need to write the file in the filesystem and get it from memory instead. I've read this about converting image to BytesIO however I can't apply it to HTML file. I'm using Flask as my framework. Wha...
convert html file to BytesIO then pass as Flask variable
I'm trying to convert a HTML file to BytesIO so that I don't need to write the file in the filesystem and get it from memory instead. I've read this about converting image to BytesIO however I can't apply it to HTML file. I'm using Flask as my framework. What i have tried: buffer = io.BytesIO() merged_df.to_html(buffe...
[ "First: using <img> to display HTML is totally wrong idea.\nTag <img> is only for images like PNG, JPG, etc.\nYou can get directly HTML using to_html() without filename\nhtml = merged_df.to_html(table_id='seasonality_table')\n\nand send this as HTML\nreturn render_template('summary_01.html', html_data=html)\n\nand ...
[ 1 ]
[]
[]
[ "bytesio", "pandas", "python" ]
stackoverflow_0074206728_bytesio_pandas_python.txt
Q: HTML form submission cuts off symbols after space in the values I have a Flask web app where I take entry from a form. It has two lists: <div class="form-row"> <div class="form-group col-md-6"> <label for="selected_domain" class="col-form-label">Select domain where service belongs</label> <select id="sel...
HTML form submission cuts off symbols after space in the values
I have a Flask web app where I take entry from a form. It has two lists: <div class="form-row"> <div class="form-group col-md-6"> <label for="selected_domain" class="col-form-label">Select domain where service belongs</label> <select id="selected_domain" name="selected_domain" class="form-control"> <opt...
[ "The answer was in comments - I just want to put it here so next person (as me - flask noob) could understand what's wrong. So you have tO chcnge in your template this part\n<option value={{x}}>{{x}}</option>\n\nto\n<option value=\"{{x}}\">\"{{x}}\"</option>\n\nThe cause of this problem is shown in “View Page Sourc...
[ 0 ]
[]
[]
[ "flask", "forms", "html", "python", "space" ]
stackoverflow_0059234854_flask_forms_html_python_space.txt
Q: How to plot with dtaidistance I tried an example using dtaidistance and dtw, but it did not plot the result. from dtaidistance import dtw from dtaidistance import dtw_visualisation as dtwvis import numpy as np s1 = np.array([0., 0, 1, 2, 1, 0, 1, 0, 0, 2, 1, 0, 0]) s2 = np.array([0., 1, 2, 3, 1, 0, 0, 0, 2, 1, 0, ...
How to plot with dtaidistance
I tried an example using dtaidistance and dtw, but it did not plot the result. from dtaidistance import dtw from dtaidistance import dtw_visualisation as dtwvis import numpy as np s1 = np.array([0., 0, 1, 2, 1, 0, 1, 0, 0, 2, 1, 0, 0]) s2 = np.array([0., 1, 2, 3, 1, 0, 0, 0, 2, 1, 0, 0, 0]) path = dtw.warping_path(s1, ...
[ "The picture in the example is not meant to be plotted within python but saved as .png to hard drive where the python code is stored.\n" ]
[ 0 ]
[]
[]
[ "dtw", "matplotlib", "plot", "python" ]
stackoverflow_0074207852_dtw_matplotlib_plot_python.txt
Q: How do I add a percentage field to a model in Django? I don't know how to go about it in My models.py so basically, i want to be able to input a number let's say 5 in the form field or from the admin panel and it renders in out as 5% I don't know if it's possible so what function do i use in my models.py did some ...
How do I add a percentage field to a model in Django?
I don't know how to go about it in My models.py so basically, i want to be able to input a number let's say 5 in the form field or from the admin panel and it renders in out as 5% I don't know if it's possible so what function do i use in my models.py did some research not helping help me out here. My models.py is like...
[ "Django by default not have any percentage field but you can archive those things like this\nmodels.py\nfrom django.db import models\n\n\nclass ProductModel(models.Model):\n name= models.CharField(max_length=100)\n og_price = models.IntegerField(null=True, blank=True)\n sell_price = models.IntegerField(nul...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074200538_django_django_models_python.txt
Q: Is there a solution to load html without asking me to store them in static folder? My index is loading well on browser, but when I click home page, there is nothing 404 error, is responding static/index.html, (when I click home page or any other such as contact, it is searching for html in static) why is it asking...
Is there a solution to load html without asking me to store them in static folder?
My index is loading well on browser, but when I click home page, there is nothing 404 error, is responding static/index.html, (when I click home page or any other such as contact, it is searching for html in static) why is it asking for index.html in static files and how can I rectify that?[ I stored my html files on t...
[ "if you create your index.html file on templates/index.html,then you can use this settings on your settings.py file:\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n # Add 'TEMPLATE_DIR' here\n 'DIRS': [os.path.join(BASE_DIR,\"templates\")],\n 'AP...
[ 0, 0 ]
[]
[]
[ "django", "html", "python", "web" ]
stackoverflow_0074207720_django_html_python_web.txt
Q: Merge xlsx files type error a was passed pandas tkinter python I'm looking for help to merge multiples xlsx files with pandas and tkinter. When I run the code I got this error : "TypeError: Can only merge Series or DataFrame objects, a <class 'str'> was passed" Thanks a lot for your help! My code is the following...
Merge xlsx files type error a was passed pandas tkinter python
I'm looking for help to merge multiples xlsx files with pandas and tkinter. When I run the code I got this error : "TypeError: Can only merge Series or DataFrame objects, a <class 'str'> was passed" Thanks a lot for your help! My code is the following: from tkinter import filedialog import pandas as pd window = Tk() w...
[ "The merge function takes two dataframes, left and right. You only provide one in the question. In the answer, we separate it with if/else since there is no second df to combine when we read the first file.\nfinal=pd.DataFrame() #all data will stored here.\nfirst=True # first file\nfor f in all_files:\n step1 =p...
[ 0 ]
[]
[]
[ "excel", "merge", "pandas", "python", "tkinter" ]
stackoverflow_0074206956_excel_merge_pandas_python_tkinter.txt
Q: Python - Problem returning True/False to class properties from class method I have a class as below which within the __init__ method I am trying to assign a True/False value to a class property using a class method. class Sensor: def __init__(self, json_data): self.sensor_eui = json_data['end_device_i...
Python - Problem returning True/False to class properties from class method
I have a class as below which within the __init__ method I am trying to assign a True/False value to a class property using a class method. class Sensor: def __init__(self, json_data): self.sensor_eui = json_data['end_device_ids']['dev_eui'] self.reading1 = json_data['uplink_message']['decoded_payl...
[ "The issue in your code is that instead of calling the function you assign it. In order to call the function you have to add the parenthesis.\nclass Sensor:\n\n def __init__(self, json_data):\n self.sensor_eui = json_data['end_device_ids']['dev_eui']\n self.reading1 = json_data['uplink_message']['d...
[ 1 ]
[]
[]
[ "class", "class_method", "python" ]
stackoverflow_0074207880_class_class_method_python.txt
Q: Python, in decorator with argument, how are arguments passed in def repeat(num_times): def decorator_repeat(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(num_times): func(*args, **kwargs) return wrapper return decorator...
Python, in decorator with argument, how are arguments passed in
def repeat(num_times): def decorator_repeat(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(num_times): func(*args, **kwargs) return wrapper return decorator_repeat @repeat(num_times=2) def say_whee(name): print(f...
[ "repeat is not the decorator; it's a decorator factory. The function it returns (decorator_repeat) is a closure over num_times, so num_times is available as a (nonlocal) variable to the closure it returns (wrapper). Without decorator syntax, you would write\ndef say_whee(name): \n print(f\"Hello {name}\")\n\...
[ 2, 0 ]
[]
[]
[ "arguments", "decorator", "functional_programming", "python", "scope" ]
stackoverflow_0074207480_arguments_decorator_functional_programming_python_scope.txt
Q: How do you read an XML file with extra text (i.e. namespaces) after the root tag using Python? XML (actually TCX) files produced by the routing site I use (plotaroute.com) produce a root tag line that is very long. I am not able to get Python to read this file. (My temporary workaround is to "manually" delete all ...
How do you read an XML file with extra text (i.e. namespaces) after the root tag using Python?
XML (actually TCX) files produced by the routing site I use (plotaroute.com) produce a root tag line that is very long. I am not able to get Python to read this file. (My temporary workaround is to "manually" delete all the extra text after the root tag before running my program.) If there's any text after "<TrainingCe...
[ "Here's a snipppet of the quick and dirty solution of adding {*} to findall/find:\ntrackpoints = dom.findall('{*}Courses/{*}Course/{*}Track/{*}Trackpoint')\n\ni=0\nfor t in trackpoints:\n lat = float(t.find('{*}Position/{*}LatitudeDegrees').text)\n long = float(t.find('{*}Position/{*}LongitudeDegrees').text)\...
[ 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0074200148_elementtree_python_xml.txt
Q: function to calculate best profit of array of stocks and time i'm writing function that gets an array of stock prices and calculates the best buy and sale profit. Each value in the array is the stock price and the index number is the hour of the price. how can keep indexes of the prices i want to buy and sell? def...
function to calculate best profit of array of stocks and time
i'm writing function that gets an array of stock prices and calculates the best buy and sale profit. Each value in the array is the stock price and the index number is the hour of the price. how can keep indexes of the prices i want to buy and sell? def inputValidation(price): isValidPrice = False # Validate in...
[ "I suggest that you save the price and its indexes in a list, then return it at the end:\ndef stockManagement(arr):\n maxProfitValue = 0\n currentMaxValue = 0\n \n # The list that will be returned at the end\n index_list = []\n\n minIndex = 0\n maxIndex = len(arr)\n for price in reversed(arr...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074207554_python.txt
Q: Pandas: how to append rows with for loop from existing value So i have this code: monthly['differences'] = monthly.GMV.diff() monthly['percentage'] = monthly.differences / (monthly.GMV - monthly.differences) *100 monthly which produce this dataframe: GMV differences percentage date 1 697...
Pandas: how to append rows with for loop from existing value
So i have this code: monthly['differences'] = monthly.GMV.diff() monthly['percentage'] = monthly.differences / (monthly.GMV - monthly.differences) *100 monthly which produce this dataframe: GMV differences percentage date 1 69793.30 NaN NaN 2 65159.60 -4633.70 -6.639176 3 ...
[ "You can loop in range 13..19 to calculate new rows from the previous ones:\ndef calc_new_val(old_row):\n new_row = pd.Series()\n new_row['GMV'] = old_row['GMV'] * (1 + old_row['percentage'] / 100)\n new_row['differences'] = new_row['GMV'] - old_row['GMV']\n new_row['percentage'] = new_row['differences'...
[ 1 ]
[]
[]
[ "append", "for_loop", "pandas", "python" ]
stackoverflow_0074206941_append_for_loop_pandas_python.txt
Q: Align numbers right for any input? I need to align numbers right for any input. However I can't seem to do it only for a specific input not for any input. I've also tried turning the list of strings into a list of nums using list comprehension and then do print("{:5d}".format(i)). I've also tried doing something l...
Align numbers right for any input?
I need to align numbers right for any input. However I can't seem to do it only for a specific input not for any input. I've also tried turning the list of strings into a list of nums using list comprehension and then do print("{:5d}".format(i)). I've also tried doing something like print("{:>len(i)}".format(i)) n = i...
[ "You can use a variable width specifier in string formatting:\nn = input().split()\n\nl = max(len(i) for i in n)\n\nm = sorted(n, key=int, reverse=True)\n\nfor i in m:\n print(\"{:>{:d}}\".format(i, l))\n\nWith an input of 1231231232131213 123123213213 12312321321 213123123, the output is:\n1231231232131213\n ...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074207872_python_python_3.x.txt
Q: Shouldn't display the row after specific length like after 10 characters I have a dataset which has some data. I don't want to display the row after 10 characters. I've written code like this. It is working when my data is not in array format. Like this. df = pd.DataFrame( {'column':['PYTHON R JAVA PYTHON', 'P...
Shouldn't display the row after specific length like after 10 characters
I have a dataset which has some data. I don't want to display the row after 10 characters. I've written code like this. It is working when my data is not in array format. Like this. df = pd.DataFrame( {'column':['PYTHON R JAVA PYTHON', 'PYTHON R JAVA PYTHON C DSS', 'Dss', 'Python R DSS', 'PYTHON'] }) but when ...
[ "The error is due to the first column value, which is a list, unlike the others which are strings.\nimport pandas as pd, numpy as np\nimport collections\nfrom collections import OrderedDict\ndf = pd.DataFrame( {'column':[['\"PYTHON R JAVA PYTHON\"'], 'PYTHON R JAVA PYTHON C DSS', 'Dss', 'Python R DSS', 'PYTHON'] })...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074206175_pandas_python.txt
Q: Assign one array column values to another array column in pandas dataframe I have a dataframe which contains array column and string column | string_col | array_col | |-------------|----------------------| | fruits | ['apple', 'banaana'] | | flowers | ['rose', 'sunflower']| | animals | ['l...
Assign one array column values to another array column in pandas dataframe
I have a dataframe which contains array column and string column | string_col | array_col | |-------------|----------------------| | fruits | ['apple', 'banaana'] | | flowers | ['rose', 'sunflower']| | animals | ['lion', 'tiger'] | I want to assign string_col elements to each element in ar...
[ "Use list comprehension for repeat strings by length of column:\ndf['new_col'] = [[a] * len(b) for a, b in zip(df['string_col'], df['array_col'])]\nprint (df)\n string_col array_col new_col\n0 fruits [apple, banaana] [fruits, fruits]\n1 flowers [rose, sunflower] [flowers, flowers...
[ 3 ]
[]
[]
[ "arrays", "dataframe", "pandas", "python", "string" ]
stackoverflow_0074208044_arrays_dataframe_pandas_python_string.txt
Q: Azure function not running on M1 Running import logging import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json()...
Azure function not running on M1
Running import logging import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: ...
[ "I kept running into problems with python on my M1 Mac until I went completely to Rosetta on the command line. For that, I did the following:\n\nUpdate Rosetta:\nIn a Terminal type:\n\nsoftwareupdate --install-rosetta\n\n\nIn Finder, type ⇧⌘G and go to /Applications/Utilities. Then duplicate Terminal:\n\n\n\nRename...
[ 1 ]
[]
[]
[ "apple_silicon", "azure_functions", "python" ]
stackoverflow_0074171275_apple_silicon_azure_functions_python.txt
Q: represent parent and child relation by dot(.) in python My input is: a = { "name": "a", "address": { "state": "b", "full": { "city": "c" } } } my expected output is: { "name": "a", "address.state": "b", "address.full.city": "c" } I have try many time bu...
represent parent and child relation by dot(.) in python
My input is: a = { "name": "a", "address": { "state": "b", "full": { "city": "c" } } } my expected output is: { "name": "a", "address.state": "b", "address.full.city": "c" } I have try many time but its very difficult.
[ "Using Recursion\ninput_dict = { \"name\": \"a\", \"address\": { \"state\": \"b\", \"full\": { \"city\": \"c\" } } }\ndef format_dict(input_dict, parent=None, res = {}):\n for k, v in input_dict.items():\n if isinstance(v, dict):\n if parent:\n format_dict(v, f\"{parent}.{k}\", r...
[ 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074207980_dictionary_python.txt
Q: Keras evaluate Accuracy w.r.t. a feature I have a dataset that consists of different features, like "gender". The task of the model is to determine if the annual income is above or below 50k. Let say I have a trained network that does the classification. Now I want to see how often the classifier makes false posit...
Keras evaluate Accuracy w.r.t. a feature
I have a dataset that consists of different features, like "gender". The task of the model is to determine if the annual income is above or below 50k. Let say I have a trained network that does the classification. Now I want to see how often the classifier makes false positive respectively false negative predictions by...
[ "The basic idea is as follows:\n1)Make a prediction with the Network.\n2)Set the predicted values as new column in your Dataset, you now have a new dataset data_new\nYour dataset now has two columns, one for the predicted and one for the true values. You can calculate the overall accuracy by boolean comparison (1 a...
[ 0 ]
[]
[]
[ "confusion_matrix", "keras", "python" ]
stackoverflow_0073691022_confusion_matrix_keras_python.txt
Q: Sending a normal message after a slash command is run Im trying to make my discord.py bot send a normal message after a user runs a certain slash command. Ive tried looking for others with this issue, but none of them are using nextcord. Im using nextcord, in a cog. Any help is appreciated. I tried things like int...
Sending a normal message after a slash command is run
Im trying to make my discord.py bot send a normal message after a user runs a certain slash command. Ive tried looking for others with this issue, but none of them are using nextcord. Im using nextcord, in a cog. Any help is appreciated. I tried things like interaction.send, interaction.send_message, self.bot.send_mess...
[ "Quick disclaimer: I am using discord.py, but this should work for nextcord too.\nIf you have an Interaction, you can get the channel from it and then use send to send a message in there.\nawait interaction.channel.send(\"whatever\")\n\nOr, you could also use followup to send messages with a Webhook:\nawait interac...
[ 1 ]
[]
[]
[ "discord", "nextcord", "python" ]
stackoverflow_0074201602_discord_nextcord_python.txt
Q: python pandas .apply func with multiple parameters just started my first independent project in python. i want to apply my own function to a data frame. the function should take two columns of said data frame as parameters: the function: ` def faustmann(profit, age): interest = 1.03 cost = 262 revenue ...
python pandas .apply func with multiple parameters
just started my first independent project in python. i want to apply my own function to a data frame. the function should take two columns of said data frame as parameters: the function: ` def faustmann(profit, age): interest = 1.03 cost = 262 revenue = (profit - ((cost * interest) ** age)) / ((interest ** ...
[ "can you try this:\npine_800[\"faustmann\"] = pine_800[['revenue','age']].apply(lambda x: faustmann(x['revenue'],x['age']),axis=1)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "function", "pandas", "python" ]
stackoverflow_0074207830_dataframe_function_pandas_python.txt
Q: Best way to output concurrent task results in shell on the go That is maybe a very basic question, and I can think of solutions, but I wondered if there is a more elegant one I don't know of (quick googling didn't bring anything useful). I wrote a script to communicate to a remote device. However, now that I have ...
Best way to output concurrent task results in shell on the go
That is maybe a very basic question, and I can think of solutions, but I wondered if there is a more elegant one I don't know of (quick googling didn't bring anything useful). I wrote a script to communicate to a remote device. However, now that I have more than one of that type, I thought I just make the communication...
[ "Since there was no good answer, I made my own solution, which is quite compact but efficient. I define a class that I call globally. Each thread populates it or updates a value based on its ID. The ID is meant to be the same list entry as taken for the thread. Here I made a simple example how to use it:\nclass col...
[ 0 ]
[]
[]
[ "concurrent.futures", "python", "shell" ]
stackoverflow_0074179438_concurrent.futures_python_shell.txt
Q: Python program to calculate maximum, minimum and average using built in function such as import Write a program that reads 6 temperatures (in the same format as before), and displays the maximum, minimum, and mean of the values. Hint: You should know there are built-in functions for max and min. If you hunt, you m...
Python program to calculate maximum, minimum and average using built in function such as import
Write a program that reads 6 temperatures (in the same format as before), and displays the maximum, minimum, and mean of the values. Hint: You should know there are built-in functions for max and min. If you hunt, you might also find one for the mean. I managed to do this program. ######################################...
[ "You don't need to import anything to compute minimum, maximum and average. You can use min(x) , max(x) and sum(x)/len(x) to compute these values from a list of numeric values.\nTo do so in your program, however, you have to store multiple inputs in a list of numeric values. You can do so by initiating an empty lis...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074207260_python.txt
Q: SyntaxError: invalid syntax | list comprehension on enumerated on list I am trying to run list comprehension on enumerated list but is gives syntax error. here is the code sample that I am trying to run. list1 = [1,2,3,4] print([(x,y) for x,y in enumerate(list1)]) Error: File "<ipython-input-18-dab77e038cc6>", li...
SyntaxError: invalid syntax | list comprehension on enumerated on list
I am trying to run list comprehension on enumerated list but is gives syntax error. here is the code sample that I am trying to run. list1 = [1,2,3,4] print([(x,y) for x,y in enumerate(list1)]) Error: File "<ipython-input-18-dab77e038cc6>", line 3 print([x,y for x,y in enumerate(list1)]) ^ SyntaxError...
[ "This works for me:\nlist1 = [1,2,3,4]\nz = [(x,y) for x,y in enumerate(list1)]\nprint(z)\n\nresult:\n[(0, 1), (1, 2), (2, 3), (3, 4)]\n\nAlso, removing the z and directly using print() also works.\n" ]
[ 0 ]
[]
[]
[ "enumeration", "list", "list_comprehension", "python" ]
stackoverflow_0074206689_enumeration_list_list_comprehension_python.txt
Q: Pandas to HDF5? How do I convert a big table in Pandas/Numpy to h5 format with the same structure? I used the next code, but received .h5 version with messy data data.to_hdf('data.h5',format = 'table', key='data') I attached the image with my data Or which data type can you recommend ? I received the next structu...
Pandas to HDF5?
How do I convert a big table in Pandas/Numpy to h5 format with the same structure? I used the next code, but received .h5 version with messy data data.to_hdf('data.h5',format = 'table', key='data') I attached the image with my data Or which data type can you recommend ? I received the next structure
[ "Setting format='table' writes the data as a PyTables Table. When you do this all the data will be in the 'table' dataset in group defined by key=. However, data of common data types will be grouped together in 1 'values_block_#' column/field (all ints, all floats, etc). To write them separately, you also need data...
[ 2 ]
[]
[]
[ "hdf5", "pandas", "python" ]
stackoverflow_0074196286_hdf5_pandas_python.txt
Q: Robust approach to plot data using for loop? My code working well, but the approach is very casual and time-consuming, therefore I am looking for robot approach to plot my data. Data: df=[ 0 1 2 3 0 168.090 7.079305 180.070 12.529506 1 166.410 15.354978 163.950 9.9834...
Robust approach to plot data using for loop?
My code working well, but the approach is very casual and time-consuming, therefore I am looking for robot approach to plot my data. Data: df=[ 0 1 2 3 0 168.090 7.079305 180.070 12.529506 1 166.410 15.354978 163.950 9.983409 2 187.730 9.258269 171.155 11.199766 3 ...
[ "Something like a simple for loop?\nimport pandas as pd\nfrom io import StringIO\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv(StringIO('''\n 0 1 2 3\n0 168.090 7.079305 180.070 12.529506\n1 166.410 15.354978 163.950 9.983409\n2 187.730 9.258269 171.155 11....
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074207887_python.txt
Q: Does python's subprocess.PIPE store all data sent to stdout into a buffer until it is read from and is there a way to stream? import subprocess from pathlib import Path def check_file_wc_count(path: Path, regex: str): try: zgrep = subprocess.run(['zgrep', regex, path], check=True, stdout=subprocess.PIPE) ...
Does python's subprocess.PIPE store all data sent to stdout into a buffer until it is read from and is there a way to stream?
import subprocess from pathlib import Path def check_file_wc_count(path: Path, regex: str): try: zgrep = subprocess.run(['zgrep', regex, path], check=True, stdout=subprocess.PIPE) except subprocess.CalledProcessError as e: return 0 output = subprocess.run(['wc', '-l'], input=zgrep.stdout, capture_output=...
[ "It does seem like using subprocess.PIPE the way I am in the posted example does save the stdout to an internal buffer. To avoid this, @chepner and @Omer Dagry solutions in the comments seem to work. I think using zgrep -c {regex} {path} is the most straight forward solution:\ndef check_num_quotes(path: Path, regex...
[ 0 ]
[]
[]
[ "linux", "pipe", "python", "subprocess" ]
stackoverflow_0074200217_linux_pipe_python_subprocess.txt
Q: Python shelve module type hints in PyCharm, "expected type xx, got Shelf[object] instead" I'm trying to understand why I'm getting IDE warnings about how I'm using the Python shelve module. All of the code here functions fine, I'm just getting IDE (PyCharm 2022.2.3 community edition) type warnings that I'd like t...
Python shelve module type hints in PyCharm, "expected type xx, got Shelf[object] instead"
I'm trying to understand why I'm getting IDE warnings about how I'm using the Python shelve module. All of the code here functions fine, I'm just getting IDE (PyCharm 2022.2.3 community edition) type warnings that I'd like to clean up. A super basic test that exemplifies the issue: import shelve s = shelve.open("test...
[ "The issue here is that shelve.open returns a shelve.Shelf instance (specifically a shelve.DbfilenameShelf). That is a MutableMapping subtype.\nA shelve.Shelf thus behaves essentially like a regular old dict, when it comes to type safety. Since the created Shelf can hold essentially any type of object, the inferred...
[ 0 ]
[]
[]
[ "pycharm", "python", "shelve", "type_hinting" ]
stackoverflow_0074196937_pycharm_python_shelve_type_hinting.txt
Q: YoutubeDL Can't get videos from YouTube playlist URL (Python. discord.py, youtube_dl) I am currently making a Discord music bot on Python with discord.py and youtube_dl frameworks. The issue I am having now is to play the playlists, now it only plays single YouTube videos. Here is a part of my test code written to...
YoutubeDL Can't get videos from YouTube playlist URL (Python. discord.py, youtube_dl)
I am currently making a Discord music bot on Python with discord.py and youtube_dl frameworks. The issue I am having now is to play the playlists, now it only plays single YouTube videos. Here is a part of my test code written to detect the problem: def search_yt(item): with YoutubeDL(YDL_OPTIONS) as ydl: t...
[ "Instead of using youtube-dl, you can use a better, more maintained version yt-dlp\nHere is the code:\nimport json\nimport yt_dlp\nURL = \"https://www.youtube.com/playlist?list=PL5CCDFBBE2143D7CB\"\nydl_opts = {}\nwith yt_dlp.YoutubeDL(ydl_opts) as ydl:\n info = ydl.extract_info(URL, download=False)\n\n # ℹ️ ...
[ 1 ]
[]
[]
[ "discord.py", "python", "youtube_dl" ]
stackoverflow_0074208097_discord.py_python_youtube_dl.txt
Q: Group every objects by year I had 3 objects [{u'criados': u'25/10/2022 00:50', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', u'id': 1, u'tipo': u'NAI', u'slug': u'Teste-1'}, {u'criados': u'25/10/2022 23:54', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/no...
Group every objects by year
I had 3 objects [{u'criados': u'25/10/2022 00:50', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', u'id': 1, u'tipo': u'NAI', u'slug': u'Teste-1'}, {u'criados': u'25/10/2022 23:54', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/Profile.pdf', u'id': 2...
[ "You can achieve the grouping like this (You can still use the output in django template)\nfrom datetime import datetime\n\nx = [\n {\n 'criados': '25/10/2022 00:50',\n 'arquivo': 'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf',\n 'id': 1,\n 'tipo': 'NAI',\n ...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074207473_django_python.txt
Q: Pandas won't skip empty line with index_col function I experience an issue when I am using pandas in python. I need to index my dataframe using country column. But there is an empty line after the column row which the csv file looks like this: 0 Televison, Physicians, and Life Expectancy 1 NaN, NaN, NaN, NaN, NaN,...
Pandas won't skip empty line with index_col function
I experience an issue when I am using pandas in python. I need to index my dataframe using country column. But there is an empty line after the column row which the csv file looks like this: 0 Televison, Physicians, and Life Expectancy 1 NaN, NaN, NaN, NaN, NaN, NaN 2 country, life expectancy, people/TV, people/physici...
[ "use skiprows=[0, 1, 3]\npd.read_clipboard(\n sep=',', skipinitialspace=True, skiprows=[0, 1, 3]\n)\n\n\n", "skip_blank_lines=True fixes this.\n(no need to manually pass line-numbers of blank lines)\n", "Create a new dataframe - cric_scores\ntest_scores = pd.DataFrame({'id' : [1, 2, '', 4, 5], \n'first_name'...
[ 1, 0, 0 ]
[]
[]
[ "blank_line", "indexing", "pandas", "python" ]
stackoverflow_0042462196_blank_line_indexing_pandas_python.txt
Q: CORS not working in Django but settings seem correct I am trying to make a POST call to Django from a React Native Web front end on different subdomains. I thought I had configured CORS correctly, but that does not seem to be the case. Here's what my Django settings.py looks like: CORS_ALLOW_CREDENTIALS = True CO...
CORS not working in Django but settings seem correct
I am trying to make a POST call to Django from a React Native Web front end on different subdomains. I thought I had configured CORS correctly, but that does not seem to be the case. Here's what my Django settings.py looks like: CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['*'] CORS_ALLOWED_ORIGINS = ['https:/...
[ "I had this issue before and I suggest to use:\nCORS_ORIGIN_ALLOW_ALL = True \n\nthat will allow all origins\nwith this config ofcourse:\nMIDDLEWARE = [\n ...\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n ...\n]\n\nINSTALLED_APPS = [\n ...\n 'corshe...
[ 5, 2, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "Are you sure that CORS_ALLOW_HEADERS allows you to set '*'?\nBased on here, it looks like it is designed to be extended rather than replaced:\nhttps://github.com/adamchainz/django-cors-headers/blob/2d22268ff59aa0b79820ea5b8983efd1e514ec4c/README.rst#cors_allow_headers\nThis test also led me to think that it is req...
[ -1, -1, -1 ]
[ "cors", "django", "django_cors_headers", "http", "python" ]
stackoverflow_0067327660_cors_django_django_cors_headers_http_python.txt
Q: ModuleNotFoundError: No module named 'bs4' I'm still super new to coding! Trying to learn from online tutorials, but I seem to be stuck on the first step! I think I installed bs4, but it's not showing up in python3, is it installed in the wrong place? robbie$ sudo -H pip install bs4 Requirement already satisfied: ...
ModuleNotFoundError: No module named 'bs4'
I'm still super new to coding! Trying to learn from online tutorials, but I seem to be stuck on the first step! I think I installed bs4, but it's not showing up in python3, is it installed in the wrong place? robbie$ sudo -H pip install bs4 Requirement already satisfied: bs4 in /Library/Python/2.7/site-packages Require...
[ "\nRequirement already satisfied: bs4 in /Library/Python/2.7/site-packages\nPython 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) \n\nYou have the module installed for Python 2.7, however you're using and trying to import it with Python 3.6.\nYou have to use pip3 like you use python3.\n", "If you are using pyth...
[ 18, 5, 3, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0043192173_beautifulsoup_python.txt
Q: Delete an artist from a figure I have a boxplot created with pandas (with all the lines saved in dict): tup = ....boxplot(column = [plot_it], by = 'C', ax = ax, return_type = 'both') How can I remove all the artists (lines added by the boxplot) from the figure,so that I can reuse those lines? I tried to copy.deep...
Delete an artist from a figure
I have a boxplot created with pandas (with all the lines saved in dict): tup = ....boxplot(column = [plot_it], by = 'C', ax = ax, return_type = 'both') How can I remove all the artists (lines added by the boxplot) from the figure,so that I can reuse those lines? I tried to copy.deepcopy() the lines and use the copies ...
[ "I solved the problem at least it does what I expcet it to do but it's quite nasty:\nfig, ax = plt.subplots()\ntup = self.stat.alls.boxplot(column = [plot_it], by = 'C', ax = ax, return_type = 'both')#,ax = ax\ndata = tup[0].lines['whiskers']\nline = data[0]\nxo = []\nxu = []\nyo = []\nyu = []\nx_med = []\ny_med = ...
[ 0 ]
[]
[]
[ "boxplot", "line", "pandas", "plot", "python" ]
stackoverflow_0073360220_boxplot_line_pandas_plot_python.txt
Q: ERROR: Could not build wheels for bcrypt which use PEP 517 and cannot be installed directly The interpreter configuration in pycharm became invalid for some reason so I created a new virtual environment for the project that I was working on, and installed the dependencies again. But I am having trouble in installi...
ERROR: Could not build wheels for bcrypt which use PEP 517 and cannot be installed directly
The interpreter configuration in pycharm became invalid for some reason so I created a new virtual environment for the project that I was working on, and installed the dependencies again. But I am having trouble in installing bcrypt again. Here's the complete error. The project was working fine with the previous interp...
[ "try using these commands:\npython -m pip install --upgrade pip\npython -m pip install --no-use-pep517 bcrypt\n\n", "What I did might work for you also:\n$ python -m pip install --no-use-pep517 bcrypt\n$ python -m pip install --upgrade pip\n\nand it worked.\n", "Fixing bcrypt to 3.2.2 (the latest version before...
[ 25, 1, 1, 0 ]
[ "try\npip install pep517\n\nPIP is very unreliable, it needs over 350 different packages under python, and the system as well\n", "I downloaded and installed\n\"microsoft visual c++ build tools\"\nhttps://go.microsoft.com/fwlink/?LinkId=691126\nand restarted the computer and worked for me.\n" ]
[ -1, -1 ]
[ "bcrypt", "pycharm", "python" ]
stackoverflow_0063509419_bcrypt_pycharm_python.txt
Q: Dictionary Values in Data Frames Attempting to insert a dictionary value into a separate column in a data frame, if the existing data frame column contains a dictionary's key. I have tried the code below, but get returning [] for value pairs: import pandas as pd import numpy as np df = pd.DataFrame({'key' : ["vs...
Dictionary Values in Data Frames
Attempting to insert a dictionary value into a separate column in a data frame, if the existing data frame column contains a dictionary's key. I have tried the code below, but get returning [] for value pairs: import pandas as pd import numpy as np df = pd.DataFrame({'key' : ["vs, vscode", "jupyter, jupyterlab", "pyt...
[ "Code:\ndef cascade_col(row_value):\n cvc_row = []\n for word in row_value.split(','): \n word =word.strip()\n if word in my_dict:\n cvc_row.append(my_dict[word])\n return ','.join(cvc_row)\n\nUsing lambda\ndf['Corresponding Value(s)'] = df['key'].apply(lambda row: ','.join([my_di...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python", "python_3.x" ]
stackoverflow_0074208133_dataframe_dictionary_pandas_python_python_3.x.txt
Q: How to add the column headers on every page on python-docx? I'm trying to print a Pandas data frame as .docx file on python. My problem is since the docx file will most of the time print more than 1 page, I want to have the column names of the data frame to be printed for every new page. Currently my code just pri...
How to add the column headers on every page on python-docx?
I'm trying to print a Pandas data frame as .docx file on python. My problem is since the docx file will most of the time print more than 1 page, I want to have the column names of the data frame to be printed for every new page. Currently my code just prints the whole data frame as is: # add the header rows. for j in r...
[ "what you're probably looking after is Repeat Header Rows functionality which can be find in here:\n\nsince python-docx doesn't have that functionality yet, you can add that flag by yourself. first you need to look for it in the ooxml schema http://www.datypic.com/sc/ooxml/e-w_tblHeader-1.html\nnote that rows that ...
[ 0 ]
[]
[]
[ "docx", "python", "python_docx" ]
stackoverflow_0074139113_docx_python_python_docx.txt
Q: My site is not displayed in the Google search list I just uploaded a site with Django on pythonanywhere and it was indexed by Google and it is displayed in the English search list, but it is not displayed in the Persian search list. This is my website link: https://peshgaman.pythonanywhere.com/ I registered my sit...
My site is not displayed in the Google search list
I just uploaded a site with Django on pythonanywhere and it was indexed by Google and it is displayed in the English search list, but it is not displayed in the Persian search list. This is my website link: https://peshgaman.pythonanywhere.com/ I registered my site in google search console and also created a sitemap fo...
[ "You can go ahead and type in your domain on the top bar in Google Search Console. There you will see if your site has been indexed and everything from the Google Database about the specific domain you requested. If not indexed you can request the crawler to crawl your site. Then your site is getting on the Google ...
[ 0 ]
[]
[]
[ "django", "indexing", "javascript", "python", "sitemap" ]
stackoverflow_0074208264_django_indexing_javascript_python_sitemap.txt
Q: skip_blank_lines is not working with pandas test_scores = pd.DataFrame({'id' : [1, 2, '', 4, 5], 'first_name' : ['Sachin', 'Dravid', '', 'Virat', 'Yuvraj'], 'scores' : [150, 210, '', 125, 75], 'state' : ['Mumbai', 'Karnataka','', 'Delhi', 'Punjab']}) test_scores.to_csv("test_scores.csv", sep = ',', header = True...
skip_blank_lines is not working with pandas
test_scores = pd.DataFrame({'id' : [1, 2, '', 4, 5], 'first_name' : ['Sachin', 'Dravid', '', 'Virat', 'Yuvraj'], 'scores' : [150, 210, '', 125, 75], 'state' : ['Mumbai', 'Karnataka','', 'Delhi', 'Punjab']}) test_scores.to_csv("test_scores.csv", sep = ',', header = True, index = False) skip = pd.read_csv(filepath_or_...
[ "Your line is not blank, it has all empty values. You need to use dropna:\nskip = (pd.read_csv(filepath_or_buffer='test_scores.csv', sep=',', header=0,\n skip_blank_lines=True, # not needed here\n )\n .dropna(how='all')\n )\n\noutput:\n id first_name scores ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074208522_pandas_python.txt
Q: Using anaconda environments with cygwin on windows Trying to set up environments with anaconda through the cygwin interface on Windows NT, and failing. Creating environments (conda create -n test_env) works fine. But activate test_env fails. I tried hacking it with: export PATH=/cygdrive/c/users/nick/anaconda3/e...
Using anaconda environments with cygwin on windows
Trying to set up environments with anaconda through the cygwin interface on Windows NT, and failing. Creating environments (conda create -n test_env) works fine. But activate test_env fails. I tried hacking it with: export PATH=/cygdrive/c/users/nick/anaconda3/envs/test:$PATH This fixes some behavior (which python p...
[ "After wrestling with the problem for quite some time, I think I've achieved a reasonable and workable method to integrate Anaconda's python (and associated environments) into Cygwin. Assuming you have both Cygwin and Anaconda working independently, to access all of the Anaconda tools from Cygwin, the following se...
[ 27, 11, 3, 1, 1 ]
[]
[]
[ "anaconda", "cygwin", "python", "windows" ]
stackoverflow_0036969824_anaconda_cygwin_python_windows.txt
Q: Not enough arguments for format string mysql error Can anyone help, I have no idea why it keeps returing the error ERROR: Not enough arguments for format string It's reading from a csv where the headers are named Property ID, Reference Number etc. The only difference is the addition of the _ in the table column...
Not enough arguments for format string mysql error
Can anyone help, I have no idea why it keeps returing the error ERROR: Not enough arguments for format string It's reading from a csv where the headers are named Property ID, Reference Number etc. The only difference is the addition of the _ in the table column names. Here is my script for reference: import csv impo...
[ "The error is happening because you have 37 columns that you are trying to insert data into, but 38 inputs that you are sending to the database i.e %s. Therefore you are telling the cursor to send a piece of data to the database but the cursor does not know where to insert the data into. You either forgot to includ...
[ 1, 1, 0 ]
[]
[]
[ "mysql", "pymysql", "python" ]
stackoverflow_0054947346_mysql_pymysql_python.txt
Q: How to add table title in python preferably with pandas I would like to add a table title in the out put. It's relatively easy to do this in r with flextable, you just have to use function set_caption(), is there a similar package in python with pandas dataframe (maybe PTable)? This is what I have right now, and ...
How to add table title in python preferably with pandas
I would like to add a table title in the out put. It's relatively easy to do this in r with flextable, you just have to use function set_caption(), is there a similar package in python with pandas dataframe (maybe PTable)? This is what I have right now, and this is what I would like to have Please help, thanks guys!
[ "Have you tried this doing this?\ndf.style.set_caption(\"Hello World\")\n\nSource: Pandas Styling\nEDIT:\nHere's an alternative way to present your table if you're okay with using matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nmy_frame = pd.DataFrame(data={'simulation1':[71,4.8,65,4.7],\n ...
[ 37, 17, 6, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0057958432_dataframe_pandas_python.txt
Q: Batch action with boto3 on GCS service I'm using boto3 for accessing Google Cloud Storage through S3 API. Most of the operations work well, but I can't perform any batch actions due to exception: botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the DeleteObjects operation: Invalid...
Batch action with boto3 on GCS service
I'm using boto3 for accessing Google Cloud Storage through S3 API. Most of the operations work well, but I can't perform any batch actions due to exception: botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the DeleteObjects operation: Invalid argument. Below I present source code whi...
[ "S3's multi-object delete API, which Google Cloud Storage does not support. Thus, it is not possible to do it this way for Google Cloud Storage - you will need to call delete_key () once per key.\n​\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "boto3", "google_cloud_storage", "python" ]
stackoverflow_0074206244_amazon_s3_boto3_google_cloud_storage_python.txt
Q: How to omit reporting files that have 100% coverage in Coverage.py Is there a setting I can put in the .coveragerc file under [report] to omit files that have 100% test coverage in my report? The closest thing I found was the exclude_lines option, but this only works for a regex pattern inside the code of your pr...
How to omit reporting files that have 100% coverage in Coverage.py
Is there a setting I can put in the .coveragerc file under [report] to omit files that have 100% test coverage in my report? The closest thing I found was the exclude_lines option, but this only works for a regex pattern inside the code of your project, not for the report itself.
[ "I don't believe so. Try submitting a Feature Request or writing such a feature and submitting a Pull Request.\nSee: http://nedbatchelder.com/code/coverage/config.html\n", "As of Coverage.py 4.3.2 is now a --skip-covered flag that can be passed to the pytest coverage report command.\nPytest can also be configured...
[ 1, 0 ]
[]
[]
[ "coverage.py", "python" ]
stackoverflow_0020543981_coverage.py_python.txt
Q: splitting dataframe into two subsets by boolean condition in one-liner is there a way we can use when we apply a condition on a df and get two return values: one fulfilling the condition and the second with remaining part? df_with_condition, df_without_condition = df.[some conditional actions] A: You could split...
splitting dataframe into two subsets by boolean condition in one-liner
is there a way we can use when we apply a condition on a df and get two return values: one fulfilling the condition and the second with remaining part? df_with_condition, df_without_condition = df.[some conditional actions]
[ "You could split the splitting command into two parts:\ndf_with_condition = df.[some conditional actions]\ndf_without_condition = df.[~(some conditional actions)]\n\n", "If the question is about performing the boolean splitting task in a single line, you can use a generator expression with groupby:\ndf_false, df_...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074208382_pandas_python.txt
Q: Why won't SymPy directly solve for the normalization of this wavefunction? Here is some minimal code demonstrating the problem. from sympy import * x = Symbol('x', real=True) t = Symbol('t', real=True) A = Symbol('A', real=True, positive=True) λ = Symbol('λ', real=True, positive=True) ω = Symbol('ω', real=True, p...
Why won't SymPy directly solve for the normalization of this wavefunction?
Here is some minimal code demonstrating the problem. from sympy import * x = Symbol('x', real=True) t = Symbol('t', real=True) A = Symbol('A', real=True, positive=True) λ = Symbol('λ', real=True, positive=True) ω = Symbol('ω', real=True, positive=True) # Define wavefunction psi_x_t = A * exp(-λ * Abs(x)) * exp(-I*ω*t...
[ "You are not getting a solution because you have declared assumptions on your variables and those assumptions are inconsistent with the solution. Let's try without those assumptions:\nIn [20]: from sympy import *\n ...: \n ...: x = Symbol('x')\n ...: t = Symbol('t')\n ...: A = Symbol('A')\n ...: λ = ...
[ 2, 1, 0 ]
[]
[]
[ "equation_solving", "python", "symbolic_math", "sympy" ]
stackoverflow_0074202605_equation_solving_python_symbolic_math_sympy.txt
Q: Return Parameters from a Recursive function in python sorry if this is a noob question, I wasn't able to find a solution online (maybe I just don't know what to search for). How do I return the "found" dictionary from this recursive function (I am only able to return the nth number) Note: simply returning found at...
Return Parameters from a Recursive function in python
sorry if this is a noob question, I wasn't able to find a solution online (maybe I just don't know what to search for). How do I return the "found" dictionary from this recursive function (I am only able to return the nth number) Note: simply returning found at the end does not work for multiple reasons # Nth Fibonacci...
[ "In both cases, you need to return found. But as your function returns dictionary, you need to access a needed value when you call it recursevly:\ndef nth_Rfib(n, found = {0:1, 1:1}):\n if n in found:\n return found\n else:\n found[n] = nth_Rfib(n-1, found)[n-1] + nth_Rfib(n-2, found)[n-2]\n ...
[ 3, 1 ]
[]
[]
[ "fibonacci", "python", "recursion" ]
stackoverflow_0074207857_fibonacci_python_recursion.txt
Q: Python PermissionError(13, 'Permission denied'))': /simple/pytest/ - cannot install packages I have an issue with installing packages on my WIN11. Until today, I used Python 2.7, which worked, but I upgraded to 3 because I want to use pytest. Now, however, I cannot install packages. My Python version 3.11.0 and pi...
Python PermissionError(13, 'Permission denied'))': /simple/pytest/ - cannot install packages
I have an issue with installing packages on my WIN11. Until today, I used Python 2.7, which worked, but I upgraded to 3 because I want to use pytest. Now, however, I cannot install packages. My Python version 3.11.0 and pip version is 22.3. Here is the screenshot of what I see: What I've tried: I reinstalled and rebo...
[ "I found the solution here: stackoverflow.com/questions/71999820/… this is a bug in python. 3.10.4, 30.10, 30.9, 30.8 is not working for me. Only python 3.7.4. I just downgraded to python 3.7.4 and now installing packages works well!\n" ]
[ 2 ]
[]
[]
[ "pip", "pytest", "python", "python_3.x" ]
stackoverflow_0074195056_pip_pytest_python_python_3.x.txt
Q: How to unwind a column in Pandas dataframe My dataframe is like: df = pd.DataFrame({'a':[1,2,3], 'b':["{'c':1}", "{'d':3}", "{'c':5, 'd':6}"]}) Expected output: a c d 0 1 1.0 NaN 1 2 NaN 3.0 2 3 5.0 6.0 Working solution would be df['b'].apply(pd.Series) but this is not working as the b column i...
How to unwind a column in Pandas dataframe
My dataframe is like: df = pd.DataFrame({'a':[1,2,3], 'b':["{'c':1}", "{'d':3}", "{'c':5, 'd':6}"]}) Expected output: a c d 0 1 1.0 NaN 1 2 NaN 3.0 2 3 5.0 6.0 Working solution would be df['b'].apply(pd.Series) but this is not working as the b column is string but not dict. I am not defining the col...
[ "Use ast.literal_eval for this and then as you already stated apply pd.Series with a join.\nimport pandas as pd\nimport ast\n\ndf = pd.DataFrame({'a':[1,2,3], 'b':[\"{'c':1}\", \"{'d':3}\", \"{'c':5, 'd':6}\"]})\n\n#convert strings to actual dictionaries\ndf['b'] = df['b'].apply(ast.literal_eval)\n\n#expand data to...
[ 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074208282_pandas_python.txt
Q: How to resolve CMake Error: Could not find a package configuration file provided by "boost_python3" I tried to install the lanelet2 library according to the github installation guide at https://github.com/fzi-forschungszentrum-informatik/Lanelet2. When I perform catkin build I get the following error: Errors <...
How to resolve CMake Error: Could not find a package configuration file provided by "boost_python3"
I tried to install the lanelet2 library according to the github installation guide at https://github.com/fzi-forschungszentrum-informatik/Lanelet2. When I perform catkin build I get the following error: Errors << lanelet2_python:cmake /home/student/catkin_ws/logs/lanelet2_python/build.cmake.000.log CMake Error at /...
[ "See neutrinoyu's comment at https://github.com/ethz-asl/kalibr/issues/368#issuecomment-651726289\n\n/kalibr/Schweizer-Messer/numpy_eigen/cmake/add_python_export_library.cmake:89\nchange\nlist(APPEND BOOST_COMPONENTS python3)\nto\nlist(APPEND BOOST_COMPONENTS python)\n\n\n" ]
[ 0 ]
[]
[]
[ "boost", "build", "cmake", "python" ]
stackoverflow_0069719159_boost_build_cmake_python.txt
Q: How to use duplicated, sort values, and pivot table to group the data w.r.t. cell value and keep the cell value that have occurred more than one time I want group the data from the table according to 'name' column values and keep the information where the 'name' column values have occurred more than one time in th...
How to use duplicated, sort values, and pivot table to group the data w.r.t. cell value and keep the cell value that have occurred more than one time
I want group the data from the table according to 'name' column values and keep the information where the 'name' column values have occurred more than one time in the table. The following code works fine for the given small data table. import pandas as pd data={'Name':['Danny','Damny','Monny','Quony','Dimny','Danny'], ...
[ "Everything except for the pivot logic is correct and should work for larger dataset as well.\nAnother approach would be calculate the count of names, filter by count > 1, and merge the names back to this table via left join.\nThis way is more explicit in filter by count > 1, and is more flexible to support filter ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074208560_pandas_python.txt
Q: Seaborn diverging palette: fix mid and end-points I am trying to visualise value negative and positive values with seaborn, where negative values become blue with increasing magnitute and positive values orange. In particular, I need 0 to be guaranteed to be white. My idea was to use: sns.diverging_palette(260, 30...
Seaborn diverging palette: fix mid and end-points
I am trying to visualise value negative and positive values with seaborn, where negative values become blue with increasing magnitute and positive values orange. In particular, I need 0 to be guaranteed to be white. My idea was to use: sns.diverging_palette(260, 30, s=100, center='light', as_cmap=True) but the manual ...
[ "A colormap just maps values in range [0., 1.] to the range of colors. In your example 0 maps to blue, 1 maps to orange and 0.5 the midpoint maps to white.\nSo the question is actually how the range of your values is mapped to [0., 1.]. If we use seaborn heatmap plot as an example then by default it maps minimum va...
[ 0 ]
[]
[]
[ "python", "seaborn" ]
stackoverflow_0074206551_python_seaborn.txt
Q: How do I correctly display pyLDAvis on Spyder or on a webpage? I'm trying to create an interactive pyLDAvis visualization for an LDA model I have built, and although I am able to create a static visualization, I am struggling with the following: Outputting a dynamic visual that interacts with the 'relevance metri...
How do I correctly display pyLDAvis on Spyder or on a webpage?
I'm trying to create an interactive pyLDAvis visualization for an LDA model I have built, and although I am able to create a static visualization, I am struggling with the following: Outputting a dynamic visual that interacts with the 'relevance metric' slider on the top right hand corner of the screen. The words per ...
[ "I am also trying to create an LDA vizualization and it works for me with my data. I just used your last 2 pieces of code (adding sort_topics=False) :\nvis_data = pyLDAvis.gensim_models.prepare(model, corpus, dictionary, sort_topics=False)\n\npyLDAvis.save_html(vis_data, 'path/doc_name.html')\n\nOnce you have saved...
[ 0 ]
[]
[]
[ "lda", "pyldavis", "python" ]
stackoverflow_0069011238_lda_pyldavis_python.txt
Q: "requirements.txt" not found when I try to build my python package I try to run python3 -m build to send a package on Pypi but i makes me this error: Traceback (most recent call last): File "C:\Users\vince\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python3...
"requirements.txt" not found when I try to build my python package
I try to run python3 -m build to send a package on Pypi but i makes me this error: Traceback (most recent call last): File "C:\Users\vince\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pep517\in_process\_in_process.py", line 363, in <module...
[ "it because requirements.txt is in another folder\nfor running your requiremnets.txt you need to go inside the folder\nin your case it is LRFutils foder\nso you need to go inside the LRFutils folder by doing\ncd LRFutils\n\nthen run\npip install -r requirements.txt\n\nhope it's work\n" ]
[ 1 ]
[]
[]
[ "build", "pypi", "python", "requirements.txt" ]
stackoverflow_0074208709_build_pypi_python_requirements.txt.txt
Q: Marshmallow How to Enforce a Required Field when Dumping? >>> class Foo(Schema): ... id = fields.Int(dump_only=True, required=True) ... name = fields.Str(required=True) ... >>> >>> Foo().dump({'asdf': 'abc'}) {} I would have thought that this would raise a ValidationError. Is there anyway to get a Marshma...
Marshmallow How to Enforce a Required Field when Dumping?
>>> class Foo(Schema): ... id = fields.Int(dump_only=True, required=True) ... name = fields.Str(required=True) ... >>> >>> Foo().dump({'asdf': 'abc'}) {} I would have thought that this would raise a ValidationError. Is there anyway to get a Marshmallow schema to enforce the required fields when calling dump ?
[ "Marshmallow only validates on load. It is a design choice.\nYou can use a pre_load method for this.\nI just realized this could also be achieved with a default callable raising a ValidationError.\nUntested code:\nclass Foo(Schema):\n id = fields.Int(dump_only=True, required=True, default=lambda: raise Validatio...
[ 0, 0 ]
[]
[]
[ "marshmallow", "python" ]
stackoverflow_0071225089_marshmallow_python.txt
Q: How to run multiple threads together in simpler code in Python? I'm trying to simplify the code of threads below: import threading def test1(): print("test1") def test2(): print('test2') thread1 = threading.Thread(target=test1) thread2 = threading.Thread(target=test2) thread1.start() thread2.start() thr...
How to run multiple threads together in simpler code in Python?
I'm trying to simplify the code of threads below: import threading def test1(): print("test1") def test2(): print('test2') thread1 = threading.Thread(target=test1) thread2 = threading.Thread(target=test2) thread1.start() thread2.start() thread1.join() thread2.join() So, I want to simplify this part of code ...
[ "just write it yourself ...\nclass Threads:\n def __init__(self,*functions):\n self._functions = functions\n self._threads = []\n\n def start(self):\n for func in self._functions:\n thread = threading.Thread(target=func)\n self._threads.append(thread)\n th...
[ 2, 0, 0 ]
[]
[]
[ "concurrency", "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074208679_concurrency_multithreading_python_python_3.x_python_multithreading.txt
Q: pandas pivot table on predefined values I am trying to count values for multiple columns including values that might not occur in the column. Given example data frame: foo = pd.DataFrame({'A':[False,False,True], 'B':[None, False, True], 'C': [None, None, None]}) my final result would look like: .value_counts() w...
pandas pivot table on predefined values
I am trying to count values for multiple columns including values that might not occur in the column. Given example data frame: foo = pd.DataFrame({'A':[False,False,True], 'B':[None, False, True], 'C': [None, None, None]}) my final result would look like: .value_counts() would not work here for me since it will miss ...
[ "You can melt and crosstab:\nbar = foo.melt(var_name='pivot_values').replace({None: 'None'})\n# for some reason, even using \"dropna=False\" in crosstab still removes None\n\nout = (pd.crosstab(bar['pivot_values'], bar['variable'], dropna=False)\n .reset_index().rename_axis(columns=None)\n )\n\nOutput:...
[ 2 ]
[]
[]
[ "pandas", "pivot_table", "python" ]
stackoverflow_0074208885_pandas_pivot_table_python.txt
Q: Get pymysql.connect cursor.execute() chunks in Python I Have this code: with DATAB.connect().execution_options(autocommit=True) as DB: with DB.begin(): DataContainer = [] for chunk in pd.read_sql_query("SELECT id, plat_id FROM plats WHERE date_request >= '{}';".format(Previous_Date), con=DB, ch...
Get pymysql.connect cursor.execute() chunks in Python
I Have this code: with DATAB.connect().execution_options(autocommit=True) as DB: with DB.begin(): DataContainer = [] for chunk in pd.read_sql_query("SELECT id, plat_id FROM plats WHERE date_request >= '{}';".format(Previous_Date), con=DB, chunksize=10000): DataContainer.append(chunk) ...
[ "You can paginate like this;\nquery = \"select * from table order by id limit %d offset %d\" % (chunksize, offset)\nresult_rows = cursor.execute(query)\n\nPut in a loop and increase offset by chunkSize every iteration.\n" ]
[ 0 ]
[]
[]
[ "chunks", "pandas", "pymysql", "python", "sql" ]
stackoverflow_0074208879_chunks_pandas_pymysql_python_sql.txt
Q: Installing old version of python packages I done a project 4-5 years before, currently i needed that project now, there i used specific python packages, for example, matplotlib==1.5.1 and scipy==0.19.0 is needed and more. To run that project now, I created a virtual env. with python version 3.5, but when installin...
Installing old version of python packages
I done a project 4-5 years before, currently i needed that project now, there i used specific python packages, for example, matplotlib==1.5.1 and scipy==0.19.0 is needed and more. To run that project now, I created a virtual env. with python version 3.5, but when installing those packages, I got Error:could not find a ...
[]
[]
[ "I Don't Know It will work or not but you can try this method too\nfirst create a requirements.txt file\nthen add you module with version like matplotlib==1.5.1 one by one\nthen run pip install -r requirements.txt\n" ]
[ -1 ]
[ "pip", "pypi", "python", "python_packaging" ]
stackoverflow_0074208932_pip_pypi_python_python_packaging.txt
Q: Is there a way to read multiple files from a list parallelly in multiple thread in PySpark? I have a list: dates that contains dates as its elements. All these dates are my file's partition columns. It is partitioned by created_date and created_hour. The columns created_date & created_hour won't be there in the da...
Is there a way to read multiple files from a list parallelly in multiple thread in PySpark?
I have a list: dates that contains dates as its elements. All these dates are my file's partition columns. It is partitioned by created_date and created_hour. The columns created_date & created_hour won't be there in the data as they are logical boundaries in the form of partitions. I am iterating the list and processi...
[ "If you read the folder instead of individual files:\nspark.read.orc('s3://some_path/')\n\nYou will get 2 additional columns in your DataFrame: created_date & created_hour.\nYou can then filter on these fields based on the array of dates you have, Spark will then read only the files under the appropriate folders.\n...
[ 0 ]
[]
[]
[ "apache_spark", "multithreading", "pyspark", "python", "python_3.x" ]
stackoverflow_0074207042_apache_spark_multithreading_pyspark_python_python_3.x.txt
Q: exact gurobi solver for chromatic number of coloring problem [error in the objective] I'm trying to solve the coloring problem by using gurobi in a lp setting. However, I do something wrong, but don't what exactly. `!pip install gurobipy' import networkx as nx import gurobipy as gp from gurobipy import * impor...
exact gurobi solver for chromatic number of coloring problem [error in the objective]
I'm trying to solve the coloring problem by using gurobi in a lp setting. However, I do something wrong, but don't what exactly. `!pip install gurobipy' import networkx as nx import gurobipy as gp from gurobipy import * import networkx as nx # create test graph n = 70 p = 0.6 G = nx.erdos_renyi_graph(n, p) nx.draw...
[ "already got the answer by adding an extra constraint for the graph coloring problem.\nfor u in range(n):\n for v in G[u]:\n if v > u:\n for j in range(k):\n m.addConstr(x[u][j] + x[v][j] <= y[j], name='ADJ_%d_%d_COL_%d')\n\n" ]
[ 0 ]
[]
[]
[ "graph_coloring", "graph_theory", "gurobi", "networkx", "python" ]
stackoverflow_0074196741_graph_coloring_graph_theory_gurobi_networkx_python.txt
Q: How read from a csv file and check with values in dictionary? The problem is to count the longest number of consecutive dna gene sequences in the seq.txt file and store it in a dictionary. The dictionary should store the corresponding key value pairs for the dna. For Example, AGAT:5. This means that AGAT occurred ...
How read from a csv file and check with values in dictionary?
The problem is to count the longest number of consecutive dna gene sequences in the seq.txt file and store it in a dictionary. The dictionary should store the corresponding key value pairs for the dna. For Example, AGAT:5. This means that AGAT occurred five consecutive times in the sample and was the maximum number of ...
[ "You have a subtle error in the dictionary you create with csvreader. The values are read as strings not ints. You can see this if you print rows:\nOrderedDict([('name', 'Albus'), ('AGATC', '15'), ('TTTTTTCT', '49'), ('AATG', '38'), ('TCTAG', '5'), ('GATA', '14'), ('TATC', '44'), ('GAAA', '14'), ('TCTG', '12')])\n\...
[ 1 ]
[]
[]
[ "cs50", "csv", "python" ]
stackoverflow_0074203287_cs50_csv_python.txt
Q: DateTimeField doesn't show in admin system How come my "date" field doesn't come up in the admin system? In my admin.py file i have from django.contrib import admin from glasses.players.models import * admin.site.register(Rating) and the Rating model has a field called "date" which looks like this date = models.D...
DateTimeField doesn't show in admin system
How come my "date" field doesn't come up in the admin system? In my admin.py file i have from django.contrib import admin from glasses.players.models import * admin.site.register(Rating) and the Rating model has a field called "date" which looks like this date = models.DateTimeField(editable=True, auto_now_add=True) ...
[ "If you really want to see date in the admin panel, you can add readonly_fields in admin.py:\nclass RatingAdmin(admin.ModelAdmin):\n readonly_fields = ('date',)\n\nadmin.site.register(Rating,RatingAdmin)\n\nAny field you specify will be added last after the editable fields. To control the order you can use the f...
[ 247, 68, 25, 19, 5, 5, 1, 0, 0, 0 ]
[]
[]
[ "admin", "django", "django_admin", "python" ]
stackoverflow_0006386172_admin_django_django_admin_python.txt
Q: is there an equivalent of R's nls in statsmodels? Does statsmodels support nonlinear regression to an arbitrary equation? (I know that there are some forms that are already built in, e.g. for logistic regression, but I am after something more flexible) In the solution https://stats.stackexchange.com/a/44249 to a q...
is there an equivalent of R's nls in statsmodels?
Does statsmodels support nonlinear regression to an arbitrary equation? (I know that there are some forms that are already built in, e.g. for logistic regression, but I am after something more flexible) In the solution https://stats.stackexchange.com/a/44249 to a question about non-linear regression, the code is in R ...
[ "consider scipy.optimize.curve_fit as desired R.nls-like function\n" ]
[ 0 ]
[]
[]
[ "python", "r", "statsmodels" ]
stackoverflow_0048505727_python_r_statsmodels.txt
Q: FastAPI: How to get JSON file from request & save it @router.get("/products", tags=["Product"], response_model=list[schemas.Product]) def get_all_product(db: Session = Depends(get_db)): return get_products(db) def get_products(db: Session): products = db.query(models.Product).all() return products Th...
FastAPI: How to get JSON file from request & save it
@router.get("/products", tags=["Product"], response_model=list[schemas.Product]) def get_all_product(db: Session = Depends(get_db)): return get_products(db) def get_products(db: Session): products = db.query(models.Product).all() return products The above works fine, when I go to localhost:5000/products I...
[ "To convert a list of SQLAlchemy objects to their Pydantic representations (which is what FastAPI does internally when you return them), you can use the utility function parse_obj_as from Pydantic.\nproducts = parse_obj_as(List[schemas.Product], get_products(db))\n\nproducts will now be a list of Pydantic Product o...
[ 0 ]
[]
[]
[ "fastapi", "json", "python" ]
stackoverflow_0074208157_fastapi_json_python.txt
Q: problem in Installing (python Library) face_recognition on windows 10/11 I am using python 3.9.9 pip 21.3.1 I am trying to install face_recognition so I installed CMake then when I tried to install dlib using command pip install dlib I got the following Collecting dlib Using cached dlib-19.22.1.tar.gz (7.4 MB) ...
problem in Installing (python Library) face_recognition on windows 10/11
I am using python 3.9.9 pip 21.3.1 I am trying to install face_recognition so I installed CMake then when I tried to install dlib using command pip install dlib I got the following Collecting dlib Using cached dlib-19.22.1.tar.gz (7.4 MB) Prep aring metadata (setup.py) ... done Building wheels for collecte...
[ "Fortunately, I solved the problem. These are the steps to download face_recognition Library:\n1- install python:\n\nin the command prompt write python and click Enter, this will open\nMicrosoft store for you, \"click download\" or \"install\" to download and\ninstall python. \"to check if it is downloaded or not t...
[ 1, 0 ]
[]
[]
[ "face_recognition", "pip", "python", "python_3.x" ]
stackoverflow_0070001837_face_recognition_pip_python_python_3.x.txt
Q: python: Dictionary counter items. How to optimize performance I need to keep track of occurrences of items in parsed files in a structure as follows: data= {'tomate': {'John': 2, 'mike': 2}, 'pasta': {'mike': 1}, 'wine': {'mike': 1, 'alex': 2}} the dictionary starts as empty one. data = {} and its is being popu...
python: Dictionary counter items. How to optimize performance
I need to keep track of occurrences of items in parsed files in a structure as follows: data= {'tomate': {'John': 2, 'mike': 2}, 'pasta': {'mike': 1}, 'wine': {'mike': 1, 'alex': 2}} the dictionary starts as empty one. data = {} and its is being populated with values when they are not there and adding up users +1 if...
[ "You can rewrite the function using if-else or using dict.setdefault and get rid of Exceptions:\ndef modify(data, key, client):\n data.setdefault(key, {}).setdefault(client, 0)\n data[key][client] += 1\n\n\ndata = {}\n\nmodify(data, \"tomate\", \"John\")\nmodify(data, \"tomate\", \"John\")\nmodify(data, \"tom...
[ 2, 2, 2, 0 ]
[]
[]
[ "counter", "dictionary", "python" ]
stackoverflow_0074204923_counter_dictionary_python.txt
Q: Is there anyway to specify templates and static folders(other than default) for Connexion app? I'm initializing app using connexion 2.4.0 library like this: connex_app = connexion.App(__name__, specification_dir='./') app = connex_app.app I need to specify the path to my static and templates directories somehow s...
Is there anyway to specify templates and static folders(other than default) for Connexion app?
I'm initializing app using connexion 2.4.0 library like this: connex_app = connexion.App(__name__, specification_dir='./') app = connex_app.app I need to specify the path to my static and templates directories somehow since they are not located in the root directory. In Flask I would use something like this app = Fl...
[ "Has an opening issue about this problem:\n\nhttps://github.com/zalando/connexion/issues/441\n\nAnd a opening pull request:\n\nhttps://github.com/zalando/connexion/pull/710\n\nBut the problem is not solved.\nYou can you this approach How to set static_url_path in Flask application just remember to use app.app to ac...
[ 0, 0, 0 ]
[]
[]
[ "connexion", "flask", "python" ]
stackoverflow_0060634212_connexion_flask_python.txt
Q: Opencv Why does the contour remain if the object has disappeared? I found a pre-written object detection program on the internet. I would like to use this to make a plastic bottle cap sensor on an assembly line that will tell me the size. Only when you move the cap out of the conveyor belt the coordinates taken fr...
Opencv Why does the contour remain if the object has disappeared?
I found a pre-written object detection program on the internet. I would like to use this to make a plastic bottle cap sensor on an assembly line that will tell me the size. Only when you move the cap out of the conveyor belt the coordinates taken from the contour stay there. Any ideas? import cv2 from object_detector i...
[ "Eran and Christoph are right. If no contour is found, the last position remains in the global x and y variables. Perhaps you want to increase the indent of the four lines that draw circle, lines and text so that it belongs to the for-loop above?\n....\n img = img[0:600, 60:700 ]\n\n contours = detector.detec...
[ 0 ]
[]
[]
[ "opencv", "python", "raspberry_pi" ]
stackoverflow_0074206273_opencv_python_raspberry_pi.txt
Q: Godaddy website cannot be scraped with Selenium Python I attempted to scrape the Godaddy website but was unsuccessful. When I conduct a search for a particular name, it comes up "We were unable to complete your search. Please try again." and a standard browser can use it just well (without selenium). Sorry if I've...
Godaddy website cannot be scraped with Selenium Python
I attempted to scrape the Godaddy website but was unsuccessful. When I conduct a search for a particular name, it comes up "We were unable to complete your search. Please try again." and a standard browser can use it just well (without selenium). Sorry if I've inconvenienced you with this query; this is my first time d...
[ "Looks like the search doesn't work for unauthenticated users. Try opening your url manually from the incognito mode (or just logout).\nIf you open this link as authenticated user you get the result of the search\n\nBut if you logout and then try to open this link you recieve \"We were unable to complete your searc...
[ 0 ]
[]
[]
[ "chrome_options", "python", "selenium_chromedriver", "selenium_webdriver", "webdriver" ]
stackoverflow_0074209115_chrome_options_python_selenium_chromedriver_selenium_webdriver_webdriver.txt
Q: Can I add multiple start points to a Schemdraw flowchart? I am making a process flow diagram as a flow chart in schemdraw. Here is the flow chart I have so far (it's not pretty but it is nowhere near done). Link to flow chart How can I make stream 1 AND stream 2 flow into manufacturing? Preferably, I'd like stream...
Can I add multiple start points to a Schemdraw flowchart?
I am making a process flow diagram as a flow chart in schemdraw. Here is the flow chart I have so far (it's not pretty but it is nowhere near done). Link to flow chart How can I make stream 1 AND stream 2 flow into manufacturing? Preferably, I'd like stream 1 to the left of manufacturing and stream 2 above it. I've att...
[ "I figured it out:\nYou can use .reverse() to reverse an arrow. So, the code would look like this:\nimport schemdraw\nfrom schemdraw import flow\n\nwith schemdraw.Drawing() as d:\n d.config(fontsize=10)\n d += (str1 := flow.Start().anchor('W').label('Stream 1'))\n d += flow.Arrow().right().at(str1.E)\n ...
[ 0 ]
[]
[]
[ "flowchart", "python", "schemdraw" ]
stackoverflow_0074046881_flowchart_python_schemdraw.txt
Q: TypeError: This COM object can not automate the makepy process - please run makepy manually for this object What this kind of error? Traceback error C:\Users\DELL\PycharmProjects\MyNew\venv\Scripts\python.exe C:/Users/DELL/PycharmProjects/MyNew/agaaaaain.py Traceback (most recent call last): File "C:\Users\DELL...
TypeError: This COM object can not automate the makepy process - please run makepy manually for this object
What this kind of error? Traceback error C:\Users\DELL\PycharmProjects\MyNew\venv\Scripts\python.exe C:/Users/DELL/PycharmProjects/MyNew/agaaaaain.py Traceback (most recent call last): File "C:\Users\DELL\PycharmProjects\MyNew\venv\lib\site- packages\win32com\client\gencache.py", line 530, in EnsureDispatch ti ...
[ "Encountered the same issue and resolve it by closing all running Excel applications.\n", "Issue also can arise if running the line excel = win32.gencache.EnsureDispatch('Excel.Application') more then once in your instance (AKA. a For loop).\n", "In my case, I was using events over different threads and I forgo...
[ 11, 0, 0, -2 ]
[ "I had the same problem...was fixed in my case by adding those 2 lines:\nworkbook.Close(SaveChanges=True)\nxl.Quit()\n\n" ]
[ -1 ]
[ "csv", "pandas", "python", "xlsm" ]
stackoverflow_0057030278_csv_pandas_python_xlsm.txt
Q: Deserialize MessagePack data in Python generated in .NET with struct I have a program which serialises a large amount of data (450 data points) in .NET using MessagePack with a Struct. I can deserialise the data in Python but I can not obtain the key structure in Python. .NET byte[] statusBytes = Decompress(compre...
Deserialize MessagePack data in Python generated in .NET with struct
I have a program which serialises a large amount of data (450 data points) in .NET using MessagePack with a Struct. I can deserialise the data in Python but I can not obtain the key structure in Python. .NET byte[] statusBytes = Decompress(compressedData); StatusT statusObject = new StatusT(); using (var ms = new Mem...
[ "Solution\nUse CLI pythonnet library:\nfrom pythonnet import load\nload('netfx')\nimport clr\nclr.AddReference(<path_to_dll>) # for both MsgPack and <my_dotNET_library>\n\nfrom MsgPack.Serialization import MessagePackSerializer\nfrom System.IO import MemoryStream\nfrom <my_dotNET_library> import StatusT\n\nserializ...
[ 0 ]
[]
[]
[ "c#", "msgpack", "python", "serialization" ]
stackoverflow_0074067800_c#_msgpack_python_serialization.txt