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: I am new to regular expression can someone help me convert this to regular expression using Python? A valid number is defined by the following rules: can have any number of digits, but it can have only digits and a decimal point and possibly a leading sign. the decimal point is optional, but if it appears in the...
I am new to regular expression can someone help me convert this to regular expression using Python?
A valid number is defined by the following rules: can have any number of digits, but it can have only digits and a decimal point and possibly a leading sign. the decimal point is optional, but if it appears in the number, there must be only one, and it must have digits on its left and its right. There should be whit...
[ "Put + after the digits to allow more than one.\nMake the decimal point and digits after it optional by putting them in a group followed by ?.\nThe whitespace after the number should be a lookahead. Otherwise, you won't be able to find two consecutive numbers, since re.findall() won't return overlapping matches. Bu...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074270537_python.txt
Q: Airflow DAG next run is stuck in past Next airflow DAG run with '00 14 * * 1,2,3,4,5' schedule interval is scheduled for 2022-10-31, 14:00:00, which was 5 hours ago. Is it possible to skip the unexecuted run without actually running the DAG? I also tried: Triggering the DAG manually. Changing the schedule interval...
Airflow DAG next run is stuck in past
Next airflow DAG run with '00 14 * * 1,2,3,4,5' schedule interval is scheduled for 2022-10-31, 14:00:00, which was 5 hours ago. Is it possible to skip the unexecuted run without actually running the DAG? I also tried: Triggering the DAG manually. Changing the schedule interval to now and running the DAG creates 3 day o...
[ "Take a look at data intervals.\nWhen you create a dag with a start_date=datetime(2022, 10, 31) and a schedule_interval='00 14 * * 1,2,3,4,5' this creates a data interval of 2022/10/31 to 2022/11/01 @ 14:00.\nDags always run at the end of their data interval. Airflow was designed as an orchestrator for ETL data pro...
[ 1 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074268897_airflow_python.txt
Q: pop index out of range error in Python when modifying a copy of lists and dictionaries while iterating through the original dictionary I have two Python lists. One list, called area = [1500, 500, 1500, 2000, 2500, 2000], stores the areas of homes. Another list, called price = [30000, 10000, 20000, 40000, 50000, 45...
pop index out of range error in Python when modifying a copy of lists and dictionaries while iterating through the original dictionary
I have two Python lists. One list, called area = [1500, 500, 1500, 2000, 2500, 2000], stores the areas of homes. Another list, called price = [30000, 10000, 20000, 40000, 50000, 45000], stores the corresponding prices of these homes. I created a dictionary called priceDict, whose keys are the unique areas of homes and ...
[ "newPriceDict[houseArea].pop(i) modifies housePrice. newPriceDict is a shallow copy of priceDict, so the values in the dictionary are the same as the values in PriceDict.\nUse copy.deepcopy() to make a deep copy.\nfrom copy import deepcopy\nfrom statistics import mean, stdev\n\narea = [1200, 1200, 1200, 2000]\npric...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074270611_python.txt
Q: fetching value between an anchor tag with bs4 or regex is there a way to get the value between the anchor tags? so in this case 'Bjelica, Nemanja' using beautiful soup? <a href="/wiki/Nemanja_Bjelica" title="Nemanja Bjelica">Bjelica, Nemanja</a> I tried to do it like this name = k.find('a')['title'] but i want ...
fetching value between an anchor tag with bs4 or regex
is there a way to get the value between the anchor tags? so in this case 'Bjelica, Nemanja' using beautiful soup? <a href="/wiki/Nemanja_Bjelica" title="Nemanja Bjelica">Bjelica, Nemanja</a> I tried to do it like this name = k.find('a')['title'] but i want to get the name between the anchor tags. Any hints?
[ "It's called the text content of a tag. As one of commenter mentioned, you can use .text, but I personally prefer .get_text() [which actually gets called to generate .text anyway] because it lets you add separators for keeping texts from multiple inline elements getting smushed together. You can check out the docum...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074270556_beautifulsoup_python.txt
Q: how to create docker-build n Docker file after pushed from dockerhub(Error response from daemon: unexpected error reading Dockerfile) am new to docker I am unable to run the docker code which is pulled from docker hub 1.Windows 10 pro, 64bit 2.able to run hello-world 3.C:\Program Files\Docker\Docker\Dockerfile>doc...
how to create docker-build n Docker file after pushed from dockerhub(Error response from daemon: unexpected error reading Dockerfile)
am new to docker I am unable to run the docker code which is pulled from docker hub 1.Windows 10 pro, 64bit 2.able to run hello-world 3.C:\Program Files\Docker\Docker\Dockerfile>docker version Client: Docker Engine - Community Version: 19.03.5 API version: 1.40 Go version: go1.12.12 Git commi...
[ "You can already see the problem at step 3. You created Dockerfile as a directory. It is a file. Delete the directory and make sure you have a file called Dockerfile in the directory where you run docker build. Make sure that Dockerfile is correctly edited.\n", "If you have a dockerfile located somewhere in a fi...
[ 0, 0, 0 ]
[]
[]
[ "docker", "docker_build", "dockerfile", "dockerhub", "python" ]
stackoverflow_0060163077_docker_docker_build_dockerfile_dockerhub_python.txt
Q: How to remove def and incorporate the function into the code? I am trying to remove def function since we are not allowed to use that, but I don't know how to. def is_one_away(first: str, other: str) -> bool: # check lengths if len(first) != len(other): return False error_count = 0 ...
How to remove def and incorporate the function into the code?
I am trying to remove def function since we are not allowed to use that, but I don't know how to. def is_one_away(first: str, other: str) -> bool: # check lengths if len(first) != len(other): return False error_count = 0 for i in range(len(first)): if first[i] != other[i]: ...
[ "Change the returned value to the value you're assigning to similarity.\nUse break to end the loop instead of return.\nif len(x) != len(y):\n similarity = False\nelse:\n for i in range(len(x)):\n if x[i] != y[i]:\n similarity = False\n else:\n similarity = True\n\nThere's no need f...
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074270730_function_python.txt
Q: How to split index into multi-index with non-delimiter pandas I have this data frame: index 0 idxaa1cx1 some_text idxbb2cx2 some_text idxcc3cx3 some_text I want to split the index into a multi index like so: idx_1 idx_2 0 idxa a1cx1 some_text idxb b2cx2 s...
How to split index into multi-index with non-delimiter pandas
I have this data frame: index 0 idxaa1cx1 some_text idxbb2cx2 some_text idxcc3cx3 some_text I want to split the index into a multi index like so: idx_1 idx_2 0 idxa a1cx1 some_text idxb b2cx2 some_text idxc c3cx3 some_text I've tried this: df.ind...
[ "You can use pd.MultiIndex.from_arrays:\ndf.index = pd.MultiIndex.from_arrays([df.index.str[:4], df.index.str[-5:]])\ndf.rename_axis((\"idx_1\", \"idx_2\"))\n\n\n", "The minimalist approach\ndf.index = [df.index.str[:4], df.index.str[-5:]]\ndf\n\n 0\nindex index \nidxa a1cx1 some_t...
[ 6, 4, 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0043503831_dataframe_pandas_python.txt
Q: Prevent Generation of Log File with Python logging I have a simple script that I run as an exe file on Windows. However, when I am developing the script, I run it from the command line and use the logging module to output debug info to a log file. I would like to turn off the generation of the log file for my prod...
Prevent Generation of Log File with Python logging
I have a simple script that I run as an exe file on Windows. However, when I am developing the script, I run it from the command line and use the logging module to output debug info to a log file. I would like to turn off the generation of the log file for my production code. How would I go about doing that? This is th...
[ "If you don't mind the generation of an empty log file for production, you can simply increase the threshold of logging to a level above logging.DEBUG, such as logging.INFO, so that messages logged with logging.debug won't get output to the log file:\nlogging.basicConfig(filename='file.log', # creates an empty file...
[ 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0074270683_logging_python.txt
Q: Capturing 0-n occurrences of a regex group I'm parsing output from textfiles that could change depending on when script is executed. I want to capture one or more lines of ip address, advertised address, and age. When I run my script it only captures the first or last match depending on where I place the metachara...
Capturing 0-n occurrences of a regex group
I'm parsing output from textfiles that could change depending on when script is executed. I want to capture one or more lines of ip address, advertised address, and age. When I run my script it only captures the first or last match depending on where I place the metacharacters, however I want all the ip lines to be cap...
[ "well I found one way of doing this\nregex = (\nr\"[\\S+\\- ]* +Link States ?[\\(Area \\S+\\)]*\\n\"\nr\"\\n*\"\nr\"(Link ID +ADV Router +Age) +Seq# +[\\S+ ]*\"\nr\"\\n*\"\nr\"(?:([\\d+\\.]+ +[\\d+\\.]+ +[\\d+]+)?) *\\S+ *\\S+ *\\S*\\n*\"\nr\"(?:([\\d+\\.]+ +[\\d+\\.]+ +[\\d+]+)? +\\S+ +\\S+ *[\\d+]*\\n)?\"\nr\"(?:...
[ 0 ]
[]
[]
[ "python", "regex_group" ]
stackoverflow_0074260768_python_regex_group.txt
Q: Expand Dataframe with Lists in the columns In Python, how do I expand this dataframe... sect_id sector func_list func_id 0 AAA ['A', 'B'] [1,2] 1 BBB ['C', 'D'] [3,4] To this format? sect_id sector func_list func_id 0 AAA A 1 0 AAA B 2 1 BBB C 3 1 BBB D 4 Thanks for your advice. A: Try: from ast import...
Expand Dataframe with Lists in the columns
In Python, how do I expand this dataframe... sect_id sector func_list func_id 0 AAA ['A', 'B'] [1,2] 1 BBB ['C', 'D'] [3,4] To this format? sect_id sector func_list func_id 0 AAA A 1 0 AAA B 2 1 BBB C 3 1 BBB D 4 Thanks for your advice.
[ "Try:\nfrom ast import literal_eval\n\n# apply ast.literal_eval if necessary:\ndf[\"func_list\"] = df[\"func_list\"].apply(literal_eval)\ndf[\"func_id\"] = df[\"func_id\"].apply(literal_eval)\n\nprint(df.explode([\"func_list\", \"func_id\"]))\n\nPrints:\n sect_id sector func_list func_id\n0 0 AAA ...
[ 1, 1, 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074270609_dataframe_list_pandas_python.txt
Q: how to sum each array in 3d array i have some array ` arr_values = [[71, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 78]], [[70, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 79]], ...
how to sum each array in 3d array
i have some array ` arr_values = [[71, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 78]], [[70, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 79]], [[70, 70, 80, 80, 50, 90, 100, 85, 75]...
[ "If you want to return a list of sums, do it by creating an empty list and then appending each sum iteratively.\narraySums = []\nfor subArray in arr_values:\n arrays = []\n for array in subArray:\n curSum = 0\n for elem in array:\n curSum += elem\n arrays.append([curSum])\n ...
[ 0 ]
[]
[]
[ "arrays", "list", "loops", "python" ]
stackoverflow_0074270774_arrays_list_loops_python.txt
Q: Trying to upgrade python on my kali, and I keep getting this error: E: The package python3-virtualenv needs to reinstalled, but I can't find an archive for it.
Trying to upgrade python on my kali, and I keep getting this error:
E: The package python3-virtualenv needs to reinstalled, but I can't find an archive for it.
[]
[]
[ "Have you tried installing python env?\nTry this\n\nsudo apt-get install python3-venv\nor this\nsudo apt-get install python{version}-venv\n\nOne more thing there is no need to upgrade you can directly install new version along with previous versions.\nTry this command to install new version\n\nsudo apt install pyth...
[ -1 ]
[ "kali_linux", "linux", "python" ]
stackoverflow_0074270735_kali_linux_linux_python.txt
Q: Python text adventure: How to make it so that when the player types specific keywords (in no particular order) certain text is displayed? I'm writing a text adventure (also known as interactive story or choose your own adventure) using python. The idea is to make it so that players can type in whatever they want t...
Python text adventure: How to make it so that when the player types specific keywords (in no particular order) certain text is displayed?
I'm writing a text adventure (also known as interactive story or choose your own adventure) using python. The idea is to make it so that players can type in whatever they want themselves to do in game (ex "punch window") into the console and then the console will display a response to that action ("the glass shatters b...
[ "Regarding your first question, here's a simple script that seems to do the kind of thing you're trying to do.\nreqs = [\n['throw', 'toss'],\n['rock','stone'],\n['smash','break','shatter'],\n['glass','window']]\n\nplayer_input = \"glass throw stone break\"\n\nif all(any(s in player_input for s in syns) for syns in ...
[ 0 ]
[]
[]
[ "console", "game_development", "python", "python_3.x" ]
stackoverflow_0074270696_console_game_development_python_python_3.x.txt
Q: Using client.run() and client.close() in a loop gives "session is closed" on the second run Warning: complete discord.py noob here (and Python in general). I'm trying to make a Discord bot that would warn me when an product is available, so I have a main .py file that runs a loop with selenium firefox that checks ...
Using client.run() and client.close() in a loop gives "session is closed" on the second run
Warning: complete discord.py noob here (and Python in general). I'm trying to make a Discord bot that would warn me when an product is available, so I have a main .py file that runs a loop with selenium firefox that checks the availability, and that part runs well. Inside that loop, when the product is available, I am...
[ "Can I ask what the purpose of your bot is? Im confused as to why you have this: await client.close What is the purpose in closing your bot's connection to discord after going through what I presume is a command? If you can let me know about that I think I'll be much more able to help. Also, may I suggest using the...
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python", "selenium" ]
stackoverflow_0074269823_bots_discord_discord.py_python_selenium.txt
Q: How to set up proxy for pandas read_html? I have a python script that utilizes pd.read_html to DataFrame data contain on a webpage. The script also loops different dates into the url so that I can read multiple days of data. I know the syntax of my script is correct but when I run it at a corporation with a proxy,...
How to set up proxy for pandas read_html?
I have a python script that utilizes pd.read_html to DataFrame data contain on a webpage. The script also loops different dates into the url so that I can read multiple days of data. I know the syntax of my script is correct but when I run it at a corporation with a proxy, it fails. This is the specific URL and the lin...
[ "You must use\nrequest.get\n\nComplete your code with:\ndf = pd.read_html(StringIO(r))\n", "I had the same problem before today. Now I have saved it.\nYou can get the html by using 'request' and then read it by using 'pandas.read_html'\nI don't know how to type in code type here.\nHere is the methods:\nimport req...
[ 0, 0 ]
[]
[]
[ "html", "http_proxy", "pandas", "python" ]
stackoverflow_0059365452_html_http_proxy_pandas_python.txt
Q: How to access to Django ORM DB in pytest? I am writing a smoke test for a POST request to API Django using pytest. With a Post request, I write the value to the DB and check that it appears. The data from POST request appears in the database, but the test fails due to the error below. import requests from datetime...
How to access to Django ORM DB in pytest?
I am writing a smoke test for a POST request to API Django using pytest. With a Post request, I write the value to the DB and check that it appears. The data from POST request appears in the database, but the test fails due to the error below. import requests from datetime import datetime from json_import.models import...
[ "Hi how are you? What is the response from your response api when you submit the post? The answer is 200? or 201? or something else?\nIt's created ?\nAnother thing, try changing BASE_URL to the resource name, you can do it with python manage.py show_urls but this is an extension https://pypi.org/project/django-show...
[ 0 ]
[]
[]
[ "django", "orm", "pytest", "python" ]
stackoverflow_0074265073_django_orm_pytest_python.txt
Q: usage of ''self'' and ''cls'' in python I understand from the question Difference between 'cls' and 'self' in Python classes? that 'cls' is used in class methods while 'self' is used in instance methods. However, I use 'self' in class methods but it is still working fine. For example, class Test: @classmethod...
usage of ''self'' and ''cls'' in python
I understand from the question Difference between 'cls' and 'self' in Python classes? that 'cls' is used in class methods while 'self' is used in instance methods. However, I use 'self' in class methods but it is still working fine. For example, class Test: @classmethod def hello(self, name): print ('hello '...
[ "You can use any name you want. But as per the naming standard defined within PEP8(Style Guide for Python Code), it's better to name self for the first argument to instance methods and cls for the first argument to class methods.\n\nFunction and Method Arguments\nAlways use self for the first argument to instance m...
[ 2 ]
[]
[]
[ "class", "class_method", "python" ]
stackoverflow_0074270886_class_class_method_python.txt
Q: Trying to access widget from other class tkinter When I am trying to reference in a different class in a function I get a error saying their is not attribute between the widget I am referencing and the class. Here is the code displaying the referencing: class Window(tk.Tk): def __init__(self): super()....
Trying to access widget from other class tkinter
When I am trying to reference in a different class in a function I get a error saying their is not attribute between the widget I am referencing and the class. Here is the code displaying the referencing: class Window(tk.Tk): def __init__(self): super().__init__() self.init_csv() def init_csv(...
[ "You have to create an instance of the LeftFrame class before you can use it or the widgets inside. This isn't something unique to tkinter, it's a fundamental aspect of using classes.\nUsually the solution looks something like this:\nclass Window(tk.Tk):\n def __init__(self):\n super().__init__()\n ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074270364_python_tkinter.txt
Q: vscode-python extension - "python.envFile"/"envFile" parameters doesn't work I'm trying to configure a FastAPI based Python project to consume an .env (enviroment variables) file from an alternate location. I've tried every possible configuration so that VSCode (vscode-python extension) loads the .env file from a ...
vscode-python extension - "python.envFile"/"envFile" parameters doesn't work
I'm trying to configure a FastAPI based Python project to consume an .env (enviroment variables) file from an alternate location. I've tried every possible configuration so that VSCode (vscode-python extension) loads the .env file from a specific location. Nothing works. I believe this is a bug of the vscode-python ext...
[ "Use python-dotenv packages.\n\nInstall python-dotenv using pip install python-dotenv command in terminal\n\n\nFile structure\npyenv\n├─ .env\n└─ Test.py\n\n\nSample code\nfrom dotenv import load_dotenv\nimport os\nload_dotenv()\nprint(os.environ.get(\"envvar\"))\n\n\nOperation result\n\n\n\nNote: If the env file n...
[ 1 ]
[]
[]
[ "environment_variables", "python", "visual_studio_code" ]
stackoverflow_0074268323_environment_variables_python_visual_studio_code.txt
Q: Big query not converting the time but just changing the time zone Step # 1 -- In my big query table, I created (in SQL) and saved a field (create_time) in Pacific time (America/Los_Angeles) and it appears like this -> 2022-05-31T06:07:46.044000 . update: This create time field is created from a UTC time field in b...
Big query not converting the time but just changing the time zone
Step # 1 -- In my big query table, I created (in SQL) and saved a field (create_time) in Pacific time (America/Los_Angeles) and it appears like this -> 2022-05-31T06:07:46.044000 . update: This create time field is created from a UTC time field in big query table. I am just doing the following to create the create_time...
[ "I Solved the issue by explicitly stating the time zone when reading the BQ data in my python job in step #2 . Used -> timestamp(create_time, 'America/Los_Angeles')\n" ]
[ 1 ]
[]
[]
[ "datetime", "google_bigquery", "python" ]
stackoverflow_0074230394_datetime_google_bigquery_python.txt
Q: Pandas - Get column value counts as new columns in dataframe I have a pandas dataframe that looks like this: Type Status typeA New typeA Working typeA Working typeA Closed typeA Closed typeA Closed typeB New typeB Working typeC Closed typeC Closed typeC Closed I'd like to group the dataframe by the 'T...
Pandas - Get column value counts as new columns in dataframe
I have a pandas dataframe that looks like this: Type Status typeA New typeA Working typeA Working typeA Closed typeA Closed typeA Closed typeB New typeB Working typeC Closed typeC Closed typeC Closed I'd like to group the dataframe by the 'Type' field and get the count of each status as ...
[ "Try as follows:\n\nUse pd.crosstab to reach the first stage of your desired output.\nFor the second stage, I am assuming that the list you mention indeed contains all possible values. If so, we can apply df.reindex to axis=1 to add the missing possibilities as columns.\nAs mentioned by BeRT2me in the comments, we ...
[ 1, 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074269212_pandas_python.txt
Q: Error in Plotly choropleth graph when binning values I am trying to create a choropleth graph with usa counties and color by range. I'm creating bins of my values with qcut and i get the following error: TypeError: object of type 'builtin_function_or_method' has no len() Although when i use the len() function i ge...
Error in Plotly choropleth graph when binning values
I am trying to create a choropleth graph with usa counties and color by range. I'm creating bins of my values with qcut and i get the following error: TypeError: object of type 'builtin_function_or_method' has no len() Although when i use the len() function i get a result len(pd.qcut(us_counties.ec_county, q=10).astype...
[ "Since a string cannot be used to specify a color, set the class value obtained by the binning process. Specify a discrete color map for it. I applied your code based on the example in the reference since you didn't present any concrete data. Classify the unemployment rate into 10 classes and use the resulting clas...
[ 1 ]
[]
[]
[ "jupyter", "plotly", "python" ]
stackoverflow_0074265108_jupyter_plotly_python.txt
Q: Plotly Dash, center multiple cards within dbc.Row How can I center the cards below? I have passed justify='center' & align='center' It does not make a diffrence and aligned to the left? code below import dash from dash import html import dash_bootstrap_components as dbc app = dash.Dash(__name__, external_stylesh...
Plotly Dash, center multiple cards within dbc.Row
How can I center the cards below? I have passed justify='center' & align='center' It does not make a diffrence and aligned to the left? code below import dash from dash import html import dash_bootstrap_components as dbc app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) server = app.server """Ch...
[ "I see that problem comes from style={'width': '25rem'}.\nSo you just need to delete it and then it worked.\n\n*Note: I changed className=\"mb-4\" to className=\"p-4\"\n" ]
[ 1 ]
[]
[]
[ "plotly_dash", "python", "python_3.x" ]
stackoverflow_0074268689_plotly_dash_python_python_3.x.txt
Q: Need Probability function in Python I’m currently learning a couple of programming languages, but I need to make something like a function that works as the following: Imagine you’ve a bag where you know you’ve 5 blue balls, 2 yellow balls, 1 pink ball. And you want to take one ball out of the bag and check it’s c...
Need Probability function in Python
I’m currently learning a couple of programming languages, but I need to make something like a function that works as the following: Imagine you’ve a bag where you know you’ve 5 blue balls, 2 yellow balls, 1 pink ball. And you want to take one ball out of the bag and check it’s color. So the ideia is that the array shou...
[ "Example using random.choices\nimport random\n\na = [\"blue\", \"yellow\", \"pink\"]\n\nprint(random.choices(a, weights=[5/8, 2/8, 1/8]))\n\n", "You can try this and can modify any number of drawings you may need\nfrom random import choices\n\ncolors = ['Blue', 'Yellow', 'Pink'] # All color choices\nprob_dist = [...
[ 0, 0 ]
[]
[]
[ "function", "probability", "python" ]
stackoverflow_0074270892_function_probability_python.txt
Q: my line 34 code in python has an error and I don't know what is the problem? print("FIRST COME FIRST SERVE SCHEDULLING") n= int(input("Please enter number of jobs : ")) d = dict() for i in range(n): key = "P"+str(i+1) a = int(input("Please enter arrival time of jobs"+str(i+1)+": ")) b = int(input("Pl...
my line 34 code in python has an error and I don't know what is the problem?
print("FIRST COME FIRST SERVE SCHEDULLING") n= int(input("Please enter number of jobs : ")) d = dict() for i in range(n): key = "P"+str(i+1) a = int(input("Please enter arrival time of jobs"+str(i+1)+": ")) b = int(input("Please enter burst time of jobs"+str(i+1)+": ")) l = [] l.append(a) l.ap...
[ "The problem is at line 35, because you're trying to iterate ATT and it doesn't exist, change it to TAT and after that refactor the line 37 otherwise you'll get the error: TypeError: can only concatenate list (not \"int\") to list.\nThis should work:\navg_ATT = 0\nfor i in TAT:\n avg_ATT +=i\navg_ATT = (TAT.appe...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074271005_python.txt
Q: Pandas: how to set column values to np.NaN if they don't match a list of strings I have a dataframe df that looks like this: import pandas as pd import numpy as np df = pd.DataFrame({ 'name': ['foo','bar', '', 'blue', '', 'buzz', np.NaN ,'red', ''], 'key': [1, 2, 3, 4, 5, 6, 7, 8, 9] }) df color key 0 fo...
Pandas: how to set column values to np.NaN if they don't match a list of strings
I have a dataframe df that looks like this: import pandas as pd import numpy as np df = pd.DataFrame({ 'name': ['foo','bar', '', 'blue', '', 'buzz', np.NaN ,'red', ''], 'key': [1, 2, 3, 4, 5, 6, 7, 8, 9] }) df color key 0 foo 1 1 bar 2 2 3 3 blue 4 4 5 5 buzz 6 6 ...
[ "You can use df.loc to access a group of rows and columns by label(s) or a boolean array.\n>>> import pandas as pd\n>>> import numpy as np\n>>>\n>>> df = pd.DataFrame({\n... 'name': ['foo','bar', '', 'blue', '', 'buzz', np.NaN ,'red', ''],\n... 'key': [1, 2, 3, 4, 5, 6, 7, 8, 9]\n... })\n>>> df\n name key\n0 f...
[ 1 ]
[]
[]
[ "nan", "numpy", "pandas", "python" ]
stackoverflow_0074271089_nan_numpy_pandas_python.txt
Q: How can I click "onclick" elements using selenium and Python? I have been trying to click an element that has an onclick event to download a file. HTML code. Interface. Form interface I have tried the following ways to click on purpose to download the file but it shows the following errors. driver.find_element(By...
How can I click "onclick" elements using selenium and Python?
I have been trying to click an element that has an onclick event to download a file. HTML code. Interface. Form interface I have tried the following ways to click on purpose to download the file but it shows the following errors. driver.find_element(By.ID, "frmForma1:btnConsultar").click() NoSuchElementException: Mess...
[ "You can try to add sleep function after you load url\ntime.sleep(3) \n\n" ]
[ 0 ]
[]
[]
[ "onclick", "python", "selenium" ]
stackoverflow_0074270960_onclick_python_selenium.txt
Q: how to convert csv file into a list and write csv file I have a csv file with some lines(couple row of text), and I am trying to make a list from the csv file and write a csv file with a "Text" header. I am trying like this import csv crimefile = open('file_1.csv', 'r') reader = csv.reader(crimefile) allRows = [r...
how to convert csv file into a list and write csv file
I have a csv file with some lines(couple row of text), and I am trying to make a list from the csv file and write a csv file with a "Text" header. I am trying like this import csv crimefile = open('file_1.csv', 'r') reader = csv.reader(crimefile) allRows = [row for row in reader] print(allRows) It's output like that:...
[ "It looks like you want the text to be split by commas and new lines, but all in one list.\nallRows = []\nwith open('file_1.csv', 'r') as crimefile:\n for line in crimefile:\n allRows += line.strip().split(',')\nprint(allRows)\n\n" ]
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074270581_csv_python.txt
Q: Python Change Master/Application Volume How do I change it? I'm looking for something like: SetMasterVolume(0.5) SetAppVolume('FooBar',0.5) I tried using ctypes.windll.winmm, but I can't find much documentation on how to use it. Thanks in advance. A: I'd hope after 5 years this is no longer a problem for you, b...
Python Change Master/Application Volume
How do I change it? I'm looking for something like: SetMasterVolume(0.5) SetAppVolume('FooBar',0.5) I tried using ctypes.windll.winmm, but I can't find much documentation on how to use it. Thanks in advance.
[ "I'd hope after 5 years this is no longer a problem for you, but I've just had to do the same thing. It's possible using the PyCaw library. \nSimple proof of concept, based on PyCaw's examples\nfrom __future__ import print_function\nfrom pycaw.pycaw import AudioUtilities, ISimpleAudioVolume\n\n\ndef main():\n se...
[ 40, 10, 3, 3, 2, 1, 0, 0, 0 ]
[ "First import subprocess\n import subprocess\nThen to get the master volume\ndef get_master_volume(self):\n proc = subprocess.Popen('/usr/bin/amixer sget Master', shell=True, stdout=subprocess.PIPE)\n amixer_stdout = proc.communicate()[0].split('\\n')[4]\n proc.wait()\n\n find_start = amixer_stdout.f...
[ -1 ]
[ "audio", "python", "volume", "windows" ]
stackoverflow_0020828752_audio_python_volume_windows.txt
Q: How to loop through each row within a dataframe that contains a string, and match such string to each item in a list? Dear Stackoverflow community- I have a dataframe df, that has a row 'name' which contains different names in it: print(df) name tom jerry steven Zeo Then I have a list with names in it: print(lis...
How to loop through each row within a dataframe that contains a string, and match such string to each item in a list?
Dear Stackoverflow community- I have a dataframe df, that has a row 'name' which contains different names in it: print(df) name tom jerry steven Zeo Then I have a list with names in it: print(list) ['tom', 'zeo'] How do I create a new column in df, df['matched'], that will return the matched value from the list to ...
[ "We can try using str.extract here with a regex alternation:\nnames = [\"tom\", \"zeo\", ...]\nregex = r'^(' + r'|'.join(names) + r')$'\ndf[\"matched\"] = df[\"name\"].str.extract(regex)\n\nOutput:\n name matched\n0 tom tom\n1 jerry NaN\n2 steven NaN\n3 Zeo zeo\n\n" ]
[ 0 ]
[]
[]
[ "matching", "python", "string" ]
stackoverflow_0074271091_matching_python_string.txt
Q: What is the difference between pandas agg and apply function? I can't figure out the difference between Pandas .aggregate and .apply functions. Take the following as an example: I load a dataset, do a groupby, define a simple function, and either user .agg or .apply. As you may see, the printing statement within m...
What is the difference between pandas agg and apply function?
I can't figure out the difference between Pandas .aggregate and .apply functions. Take the following as an example: I load a dataset, do a groupby, define a simple function, and either user .agg or .apply. As you may see, the printing statement within my function results in the same output after using .agg and .apply. ...
[ "apply applies the function to each group (your Species). Your function returns 1, so you end up with 1 value for each of 3 groups.\nagg aggregates each column (feature) for each group, so you end up with one value per column per group.\nDo read the groupby docs, they're quite helpful. There are also a bunch of tut...
[ 59, 36, 3, 0, 0, 0 ]
[]
[]
[ "pandas", "pandas_groupby", "python" ]
stackoverflow_0021828398_pandas_pandas_groupby_python.txt
Q: Why C++ implementation using std::unordered_map is much slower than equivalent Python implementation using dictionary? For this I am using the coordinate transformation (x,y)-> 1000*x+y for efficiency. It's not very important to understand what the code is doing, but it for this problem: https://oeis.org/A337663 T...
Why C++ implementation using std::unordered_map is much slower than equivalent Python implementation using dictionary?
For this I am using the coordinate transformation (x,y)-> 1000*x+y for efficiency. It's not very important to understand what the code is doing, but it for this problem: https://oeis.org/A337663 This simply adds ones to the board and then removes them as a metric for performance: ################## #1###1###1###1###1# ...
[ "Most of the execution time should be spent in cache misses, allocations and in the overheads of the container implementations (ie. low-level details). This is why enabling optimizations should have a small impact (if not even negligible). The compiler cannot easily optimize hash-table containers. The gap between C...
[ 3 ]
[]
[]
[ "c++", "performance", "python" ]
stackoverflow_0074269252_c++_performance_python.txt
Q: Python- Reading From Text File to Graph I am trying to read from the file and then create a graph. So far all sources I found show how to read from file that already has numbers separated. The one I am trying to read has string and numbers together but I only wish to read the numbers and store them in a list and t...
Python- Reading From Text File to Graph
I am trying to read from the file and then create a graph. So far all sources I found show how to read from file that already has numbers separated. The one I am trying to read has string and numbers together but I only wish to read the numbers and store them in a list and then graph it. Here is what I got so far: The ...
[ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndf = pd.read_csv(sep=':\\s|,\\s', names=['idn', 'Salesman ID', 'brand', 'Kia sold', 'timestamp'])\n\nfig = sns.scatterplot(data=df, x='Salesman ID', y='Kia sold', marker='o', color='g')\nfig.set_title('Sales Numbers')\nplt.show()\n\nOut...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074268033_python.txt
Q: Python Max retries exceeded with url while using request I was working on urls using request library. so I can check that if the URL is working or not using get method. The Script works fine for the rest of URLs but for one url it took a lot of time and then this error occur: requests.exceptions.ConnectionError: H...
Python Max retries exceeded with url while using request
I was working on urls using request library. so I can check that if the URL is working or not using get method. The Script works fine for the rest of URLs but for one url it took a lot of time and then this error occur: requests.exceptions.ConnectionError: HTTPConnectionPool(host='macromedia.com', port=80): Max retries...
[ "Are you actually experiencing a Timeout exception now or still an exception of class requests.exceptions.ConnectionError ? (if the latter this would explain why your current exception handling code isn't working).\nYou should be catch both ConnectionError and Timeout exceptions along with a generic catch all.\nFor...
[ 1 ]
[]
[]
[ "python", "python_3.x", "request" ]
stackoverflow_0074271139_python_python_3.x_request.txt
Q: How to transfers files with Google Workspace Admin SDK (python) I am trying to write a program that transfers users drive and docs files from one user to another. It looks like I can do it using this documentation Documentation. I created the data transfer object, which looks like this: datatransfer = { 'k...
How to transfers files with Google Workspace Admin SDK (python)
I am trying to write a program that transfers users drive and docs files from one user to another. It looks like I can do it using this documentation Documentation. I created the data transfer object, which looks like this: datatransfer = { 'kind': 'admin#datatransfer#DataTransfer', 'oldOwnerUserId': 's...
[ "I finally got this to work. If anyone else is struggling with this and stumbles on this, \"applicationId\" is a number, not a string. Also, the error message is misleading - there is no nested field called \"resource.\" This is what worked for me:\ndatatransfer = {\n \"newOwnerUserId\": \"SomeNumber\",\n ...
[ 0 ]
[]
[]
[ "google_admin_sdk", "google_cloud_data_transfer", "python" ]
stackoverflow_0074270126_google_admin_sdk_google_cloud_data_transfer_python.txt
Q: I want to do a 2X3 transposition in python but can't matrix = [['*','*','*'], ['*','*','*']] t_matrix = [['*','*'], ['*','*'], ['*','*']] print(list(zip(*matrix))) [('*', '*'), ('*', '*'), ('*', '*')] The above is what happens. I want the matrix to look like t_matrix, but it does...
I want to do a 2X3 transposition in python but can't
matrix = [['*','*','*'], ['*','*','*']] t_matrix = [['*','*'], ['*','*'], ['*','*']] print(list(zip(*matrix))) [('*', '*'), ('*', '*'), ('*', '*')] The above is what happens. I want the matrix to look like t_matrix, but it doesn't. How can I do the transposition?
[ "Just use a list comprehension to map each tuple to a list.\nprint([[a, b] for a, b in zip(*matrix)])\n\nMore generally:\nprint([list(x) for x in zip(*matrix)])\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074271221_python.txt
Q: Best way to do operations in np.matrix with conditions on the indexes I am looking for the best way to perform operations in numpy matrices that depend on conditions on the indices. The matrix I am working on is a symmetric square matrix, in particular it is a weighted adjacency matrix. At the moment I have three ...
Best way to do operations in np.matrix with conditions on the indexes
I am looking for the best way to perform operations in numpy matrices that depend on conditions on the indices. The matrix I am working on is a symmetric square matrix, in particular it is a weighted adjacency matrix. At the moment I have three nested loops, which is computationally expensive. The code below records ho...
[ "You were on the right track with einsum. You can use the function with any arrays you want in a single call, meaning that the subtraction can be temporarily stored as a new array and used in einsum. You need to be careful though to somehow account for the fact that einsum goes through all indices, so your constrai...
[ 0 ]
[]
[]
[ "loops", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074270451_loops_numpy_numpy_ndarray_python.txt
Q: How to show dictionary data in table format in terminal I am trying to solve the simple usecase where I need to show data in terminal in tabular style not needed fancy table but somehow that emits like table. here is my code. score = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}} players...
How to show dictionary data in table format in terminal
I am trying to solve the simple usecase where I need to show data in terminal in tabular style not needed fancy table but somehow that emits like table. here is my code. score = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}} players_name = ["jack","joe"] for each_rounds in range(0,2): pri...
[ "You're iterating players and rounds together, but what you need to do is iterate players and then rounds for each player. It's probably easier to generate a list of scores for each player and then print that:\nscore = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}}\nplayers = list(score['r...
[ 2 ]
[]
[]
[ "dictionary", "for_loop", "python" ]
stackoverflow_0074271109_dictionary_for_loop_python.txt
Q: Robot Framework having trouble evaluating expression with a colon in it I currently have a conditional statement with two variables in Robot Framework that have a colon(:) in the string. The evaluation fails every time. Both variables are strings and the same evaluation will work just fine in Python (':00'==':00')...
Robot Framework having trouble evaluating expression with a colon in it
I currently have a conditional statement with two variables in Robot Framework that have a colon(:) in the string. The evaluation fails every time. Both variables are strings and the same evaluation will work just fine in Python (':00'==':00'). I've tried an escape char \:00, I've also tried with just one zero :0. *** ...
[ "The condition needs to be valid python. In your case, after the variables are substituted the expression becomes if :00==:00 which is invalid python.\nYou have a couple options. The first is to surround your data with quotes:\nIF \"${string_one}\"==\"${string_two}\"\n\nThe above guarantees a string compariso...
[ 0 ]
[]
[]
[ "python", "robotframework" ]
stackoverflow_0072051563_python_robotframework.txt
Q: How to solve a congruence system in python? for the problem Ax ≡ B (MOD C) I did this, and it was okay: def congru(a,b,c): for i in range(0,c): if ((a*i - b)%c)== 0 : print(i) Now I have to solve a system of equations, where A = ( 5x + 7y) and A= (6x + 2y), and B= 4 and B = 12 , respectively...
How to solve a congruence system in python?
for the problem Ax ≡ B (MOD C) I did this, and it was okay: def congru(a,b,c): for i in range(0,c): if ((a*i - b)%c)== 0 : print(i) Now I have to solve a system of equations, where A = ( 5x + 7y) and A= (6x + 2y), and B= 4 and B = 12 , respectively, and C is 26. In other words: ( 5x + 7y)≡ 4 (m...
[ "For the aX ≡ b (mod m) linear congruence, here is a more powerful Python solution, based on Euler's theorem, which will work well even for very large numbers:\ndef linear_congruence(a, b, m):\n if b == 0:\n return 0\n\n if a < 0:\n a = -a\n b = -b\n\n b %= m\n while a > m:\n ...
[ 2, 1, 0, 0 ]
[ "To solve linear congruence system, You should use Chinese theorem of reminders.\nI wrote full code using python and AppJar (AppJar is for grafics).\nAnd You can download it from my github profile: github profile, full code there\nThere You can find all the functions I used.\nIt is very simple and I am sure You wil...
[ -1 ]
[ "algorithm", "discrete_mathematics", "math", "python" ]
stackoverflow_0048252234_algorithm_discrete_mathematics_math_python.txt
Q: Filter out index from 2-D numpy array Say I have a 2-D numpy array, A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] # Shape: (3, 4) and I have another 1-D array, B = [0, 2, 1] # Shape: (3,) I want to extract an element from the index of A's ith row corresponding to B's ith element. Meaning, if we consider the 3...
Filter out index from 2-D numpy array
Say I have a 2-D numpy array, A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] # Shape: (3, 4) and I have another 1-D array, B = [0, 2, 1] # Shape: (3,) I want to extract an element from the index of A's ith row corresponding to B's ith element. Meaning, if we consider the 3nd element in B, output will be 2nd element...
[ "Simple enough with advanced indexing\nC = A[np.arange(B.size), B]\n\nwhich, for your example, yields [0, 6, 9] which is the correct result as @MichaelDelgado points out.\n", "If your B array is the position along the second axis which you'd like for each element in the first axis, just provide a corresponding se...
[ 3, 1, 1 ]
[]
[]
[ "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074271193_numpy_numpy_ndarray_python.txt
Q: beautifulsoup - obtaining the tag and it's parent from the text inside? Using beautifulsoup it is possible to do the following: for heading in soup.find_all('h1'): print(heading.text) Top Rated Movies However, is there a method to extract the tags themselves, given the text? A way of working backwards from th...
beautifulsoup - obtaining the tag and it's parent from the text inside?
Using beautifulsoup it is possible to do the following: for heading in soup.find_all('h1'): print(heading.text) Top Rated Movies However, is there a method to extract the tags themselves, given the text? A way of working backwards from the above example, something like: soup.find_tag('Top Rated Movies') h1
[ "There are quite a few ways.\nIf you know the exact text, you can use text or string argument like\ntags = soup.find_all(True, string=\"Top Rated Movies\")\n\nfor more ways to use the string argument, like when you only know part of the text, you can check out the relevant section of the documentation.\n\nAlso, for...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074270903_beautifulsoup_python_web_scraping.txt
Q: Django: how to create custom "base" model In almost all my tables (= classes of models.Model) I have three DateTimeField: creation validity start validity end Is there a way to have a "base" model class where I declare those fields, and make all my other model extend this one? I couldn't find a valuable answer o...
Django: how to create custom "base" model
In almost all my tables (= classes of models.Model) I have three DateTimeField: creation validity start validity end Is there a way to have a "base" model class where I declare those fields, and make all my other model extend this one? I couldn't find a valuable answer on the Web.
[ "You need to create an abstract base class having these common fields and then inherit this base class in your models.\nStep-1: Create a new Abstract Base Class\nWe first create an abstract base class called BaseModel. This BaseModel class contains the 3 model fields creation_date, valididity_start_date and validit...
[ 56, 10, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0031647490_django_django_models_python.txt
Q: How do I return the email from the element in webdriver? I want to scrape the email from this website https://www.tripadvisor.co.uk/Restaurant_Review-g186389-d14025284-Reviews-The_Queen_s_Head-Dorking_Surrey_England.html I did this email = driver.execute_script("return document.querySelector(`a[href^='...
How do I return the email from the element in webdriver?
I want to scrape the email from this website https://www.tripadvisor.co.uk/Restaurant_Review-g186389-d14025284-Reviews-The_Queen_s_Head-Dorking_Surrey_England.html I did this email = driver.execute_script("return document.querySelector(`a[href^='mailto:']`)") and I got back the following <selenium.webdriv...
[ "return the href:\nreturn document.querySelector(`a[href^='mailto:']`).href\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "python", "selenium" ]
stackoverflow_0074270717_javascript_python_selenium.txt
Q: Pandas csv write not understanding empty space inside double quotes I'm currently trying to read a csv file, add/delete/rename some columns using Pandas dataframe, and then write it back to the same file. However, a few of the files I'm using contain records which look like this: Column 1,Column 2,Column 3,Column ...
Pandas csv write not understanding empty space inside double quotes
I'm currently trying to read a csv file, add/delete/rename some columns using Pandas dataframe, and then write it back to the same file. However, a few of the files I'm using contain records which look like this: Column 1,Column 2,Column 3,Column 4 123," ",ABCD,"This, that, and this" I was able to successfully get Pan...
[ "It's still a valid CSV without the quotes around the space. A field only needs to be quoted if it contains the separator (comma).\nYou don't need skipinitalspace=True on the read. That's only needed if the CSV looks like A, B, C, D instead of A,B,C,D.\nThe quotechar parameter isn't needed either as \" is the defau...
[ 0, 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074270904_csv_pandas_python.txt
Q: How to recreate a deleted table with Django Migrations? There are two models Groups and Students and only one table for Groups of them, the Students table was deleted. How to make Django recreate the deleted table? If I do makemigrations it prints "No changes detected". On admin page when I click on the Students t...
How to recreate a deleted table with Django Migrations?
There are two models Groups and Students and only one table for Groups of them, the Students table was deleted. How to make Django recreate the deleted table? If I do makemigrations it prints "No changes detected". On admin page when I click on the Students table it throws an exception: relation "students_students" doe...
[ "In django 1.7 you can try:\n1. Delete your migrations folder\n\n2. In the database: DELETE FROM django_migrations WHERE app = 'app_name'.\n You could alternatively just truncate this table.\n\n3. python manage.py makemigrations\n\n4. python manage.py migrate --fake\n\nIf you are working in django 1.9.5 this is t...
[ 82, 17, 16, 14, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "django_migrations", "django_models", "postgresql", "python" ]
stackoverflow_0033259477_django_django_migrations_django_models_postgresql_python.txt
Q: Django-viewflow query all assigned to user tasks How to query django-viewflow for all tasks assigned to user? Probably viewflow.managers.TaskQuerySet inbox() is right place. But how to invoke it? Alternatively how to query users task from viewflow.models.Process object? A: You could just use Task.objects.filter(...
Django-viewflow query all assigned to user tasks
How to query django-viewflow for all tasks assigned to user? Probably viewflow.managers.TaskQuerySet inbox() is right place. But how to invoke it? Alternatively how to query users task from viewflow.models.Process object?
[ "You could just use\nTask.objects.filter(process=..., owner=self.request.user, status=STATUS.ASSIGNED)\n\n", "Heve done it like below finaly\nclass CoopOnboardingProcess(Process):\n user = models.ForeignKey(CustomUser, on_delete=models.RESTRICT, blank=True, null=True)\n text = models.CharField(max_length=15...
[ 1, 0 ]
[]
[]
[ "bpmn", "business_process_management", "django", "django_viewflow", "python" ]
stackoverflow_0074194033_bpmn_business_process_management_django_django_viewflow_python.txt
Q: How do we extract JSON data from Binance using Pandas in python, to get account equity? I am trying to calculate my account equity in BTC (I am just running the testnet at the moment) from Binance using the official python library. The response is a JSON format giving the name of the asset, the free and the locked...
How do we extract JSON data from Binance using Pandas in python, to get account equity?
I am trying to calculate my account equity in BTC (I am just running the testnet at the moment) from Binance using the official python library. The response is a JSON format giving the name of the asset, the free and the locked balances. I can store this as a .txt file, or a csv. I need to somehow extract the informat...
[ "Client.account() looks like:\n{\n \"makerCommission\": 15,\n \"takerCommission\": 15,\n \"buyerCommission\": 0,\n \"sellerCommission\": 0,\n \"canTrade\": true,\n \"canWithdraw\": true,\n \"canDeposit\": true,\n \"brokered\": false,\n \"updateTime\": 123456789,\n \"accountType\": \"SPOT\",\n \"balances\...
[ 0 ]
[]
[]
[ "binance_api_client", "dataframe", "pandas", "python" ]
stackoverflow_0074271198_binance_api_client_dataframe_pandas_python.txt
Q: Creating a new series for a Pandas data frame with boolean values but a non boolean index I've been trying to add a new series to my DataFrame using the .loc method as shown below EM['Starting'] = EM.loc[(['Program_Start_Date']==Trimester_Start_Date)] However I am receiving the below error and have not been able ...
Creating a new series for a Pandas data frame with boolean values but a non boolean index
I've been trying to add a new series to my DataFrame using the .loc method as shown below EM['Starting'] = EM.loc[(['Program_Start_Date']==Trimester_Start_Date)] However I am receiving the below error and have not been able to figure out how to fix it KeyError: 'False: boolean label can not be used without a boolean i...
[ "So, you're trying to use .loc() with a condition, so it's returning True or False. And that doesn't work with .loc() unless the index is also True/False.\nWhat I think you might be trying to do is filter the dataframe, which would look something like:\nfilter = [x==y for x,y in zip(EM.Program_Start_Date, EM.Trimes...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074271184_dataframe_pandas_python.txt
Q: Pyspark merge 2 Array of Maps into 1 column with missing keys I have the following dataset test_table = spark.createDataFrame( [ ("US", "CA", "S", "2022-10-01",100, 10, 1), ("US", "CA", "M", "2022-10-01",100, 15, 5), ("US", "CA", "L", "2022-10-01",100, 20, 10), ("US", "CA", "S",...
Pyspark merge 2 Array of Maps into 1 column with missing keys
I have the following dataset test_table = spark.createDataFrame( [ ("US", "CA", "S", "2022-10-01",100, 10, 1), ("US", "CA", "M", "2022-10-01",100, 15, 5), ("US", "CA", "L", "2022-10-01",100, 20, 10), ("US", "CA", "S", "2022-10-01",200, 10, 1), ("US", "CA", "M", "2022-10-01",2...
[ "Give this all the correct decorators and such, and it'll do what you're looking for...\ndef merge_payloads(latest_payload, prev_payload):\n return dict(y for x in [*prev_payload, *latest_payload] for y in x.items())\n\nlatest = [{'100': {'cumulative_ttl_sold': 37, 'cumulative_ttl_returned': 17}}]\nprev = [{'100...
[ 1 ]
[]
[]
[ "apache_spark", "pyspark", "python", "sql" ]
stackoverflow_0074271398_apache_spark_pyspark_python_sql.txt
Q: AttributeError: module 'tensorflow.python.training.experimental.mixed_precision' has no attribute '_register_wrapper_optimizer_cls' I am using Keras to implement a neural network. But when I use model = Sequential(), I get the following error: AttributeError Traceback (most recent call l...
AttributeError: module 'tensorflow.python.training.experimental.mixed_precision' has no attribute '_register_wrapper_optimizer_cls'
I am using Keras to implement a neural network. But when I use model = Sequential(), I get the following error: AttributeError Traceback (most recent call last) <ipython-input-31-fa9fd3b0e211> in <module> 8 9 # Create the model ---> 10 model = Sequential() 11 model.add(Dropo...
[ "This problem maybe occurs in the keras package version.\nBecause the installed tensorflow version does not match the keras version. Just uninstall keras and reinstall your own tensorflow corresponding version.\npip3 uninstall keras\npip3 install keras --upgrade\n\nIn summary, you need to match the correct environm...
[ 14, 10, 7, 6, 1, 0 ]
[]
[]
[ "deep_learning", "keras", "python", "python_3.x", "tensorflow2.0" ]
stackoverflow_0066178738_deep_learning_keras_python_python_3.x_tensorflow2.0.txt
Q: How to restore optimizer by tf.train.Checkpoint? I want to restore the optimizer's state, so I did the following: # create optimizer optimizer = tf.keras.optimizers.Adam(0.1) # save ckpt_dir = 'logs\\ckpts\\ckpt_0' optm_ckpt = tf.train.Checkpoint(optimizer=optimizer) optm_ckpt.save(os.path.join(ckpt_dir, 'adam', ...
How to restore optimizer by tf.train.Checkpoint?
I want to restore the optimizer's state, so I did the following: # create optimizer optimizer = tf.keras.optimizers.Adam(0.1) # save ckpt_dir = 'logs\\ckpts\\ckpt_0' optm_ckpt = tf.train.Checkpoint(optimizer=optimizer) optm_ckpt.save(os.path.join(ckpt_dir, 'adam', 'adam_ckpt')) # restore and check optm_ckpt.restore(o...
[ "while creating checkpoints you can pass the optimizer argument for saving the optimizer status\ncheckpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)\n\nThen you can restore optimizer status while restoring those checkpoints.For more details please refer to this documentation. Thank You.\n" ]
[ 0 ]
[]
[]
[ "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0067236765_python_tensorflow_tensorflow2.0.txt
Q: Removing trailing whitespace for a tic tac toe board in python I am trying to resolve the error as highlighted in the picture below. I am able to print a tic-tac-toe board but the trailing whitespace affects the test case. I am not better yet at using strings to represent a list of numbers. The desired output is e...
Removing trailing whitespace for a tic tac toe board in python
I am trying to resolve the error as highlighted in the picture below. I am able to print a tic-tac-toe board but the trailing whitespace affects the test case. I am not better yet at using strings to represent a list of numbers. The desired output is embedded in the image below: def printBoard(plane):#function to prin...
[ "I believe you are looking to right justify the numbers while also enforcing 3 characters of width so your printed board retains its formatting. To do this, you can eliminate the caret character from your print statements, which will allow the printed values to right justify. The caret signifies that you are center...
[ 1, 0 ]
[]
[]
[ "python", "removing_whitespace", "trailing_whitespace" ]
stackoverflow_0074271155_python_removing_whitespace_trailing_whitespace.txt
Q: Adding a stacked plot as a subplot in python Please I need help with a plot. I am making a 3x3 dimension figure containing 7 subplots. I want two(2) of the subplots (ax6 and ax7) to be stacked plots. Does anyone have an idea how I can make this work? I used the code below to make the grid. fig = plt.figure() fig.s...
Adding a stacked plot as a subplot in python
Please I need help with a plot. I am making a 3x3 dimension figure containing 7 subplots. I want two(2) of the subplots (ax6 and ax7) to be stacked plots. Does anyone have an idea how I can make this work? I used the code below to make the grid. fig = plt.figure() fig.set_figheight(8) fig.set_figwidth(10) gs = gridspec...
[ "Please look at the comments in the code:\nimport matplotlib.pyplot as plt \nfrom matplotlib import gridspec\nimport numpy as np\n\nfig = plt.figure(figsize=(10, 8))\ng = gridspec.GridSpec(3, 3)\n\nax1 = plt.subplot(g[0, 0])\nax2 = plt.subplot(g[0, 1])\nax3 = plt.subplot(g[0, 2])\nax4 = plt.subplot(g[1, 0])\nax5 = ...
[ 1 ]
[]
[]
[ "matplotlib", "python", "subplot" ]
stackoverflow_0074257369_matplotlib_python_subplot.txt
Q: How can I modify the values in a pyspark dataframe based on the previous row's values? I have a pyspark dataframe which contains duplicates of certain column values, like this: showing deptDF +--------+----+------------+----------+--------+-----------+ |quantity|cost|participants|activity |category|id | +...
How can I modify the values in a pyspark dataframe based on the previous row's values?
I have a pyspark dataframe which contains duplicates of certain column values, like this: showing deptDF +--------+----+------------+----------+--------+-----------+ |quantity|cost|participants|activity |category|id | +--------+----+------------+----------+--------+-----------+ |4 |10 |2 |skii...
[ "I don't think you have to use any iteration in this case, just a window function can achieve your goal:\ndf = spark.createDataFrame(\n [\n (4, 10, 1, 1),\n (4, 10, 1, 2)\n ],\n schema=['a', 'b', 'c', 'participants']\n)\n\ndf.show(10, False)\n+---+---+---+------------+\n|a |b |c |participa...
[ 1 ]
[]
[]
[ "dataframe", "duplicates", "pyspark", "python" ]
stackoverflow_0074265757_dataframe_duplicates_pyspark_python.txt
Q: Pandas drop duplicates and keep first entry when fulfilling multi column condition I have a DataFrame on the following format. id | value | more columns 1 '' 1 '' 1 '' 1.1 "some text" 1.1 "xxx" 1.2 "xxx" 2 '' 2.1 '' 2.1.1 ...
Pandas drop duplicates and keep first entry when fulfilling multi column condition
I have a DataFrame on the following format. id | value | more columns 1 '' 1 '' 1 '' 1.1 "some text" 1.1 "xxx" 1.2 "xxx" 2 '' 2.1 '' 2.1.1 "xxx" 1 '' 3 '' 3 '' 3.1 "hi" I want to drop ...
[ "df = pd.DataFrame({'id': ['1', '1', '1', '1.1', '1.1', '1.2', '2', '2.1', '2.1.1', '1', '3', '3', '3.1'],\n 'value': ['', '', '', 'some text', 'xxx', 'xxx', '', '', 'xxx', '', '', '', 'hi']})\n\n\ndef fun(x):\n if x.value.eq('').all():\n return x.drop_duplicates('value')\n else:\n ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074271360_pandas_python.txt
Q: Change plotly express "color" variable with button I would like to create a plotly plot where I can change the value of the plotly express color argument via a button. I am using plotly.express.scatter for this. For example, the initial plot shown is px.scatter(df, "sepal_length", "sepal_width", color="species"). ...
Change plotly express "color" variable with button
I would like to create a plotly plot where I can change the value of the plotly express color argument via a button. I am using plotly.express.scatter for this. For example, the initial plot shown is px.scatter(df, "sepal_length", "sepal_width", color="species"). Changing from "species" to "petal length" in a dropdown ...
[ "For color='species', three graphs are internally created for each categorical variable. And color='petal_length' consists of a single graph data. So, it is possible to handle this by setting the drop-down to show/hide the graph. The actual code reuses the data created by express.scatter. The data for each graph wi...
[ 1 ]
[]
[]
[ "pandas", "plot", "plotly", "plotly_express", "python" ]
stackoverflow_0074264697_pandas_plot_plotly_plotly_express_python.txt
Q: Python Multiple inheritance doesn't seem to be "depth first". Or am i missing something obvious class B: def f(self): return "p" class C1(B): #no definition of f pass class C2(B): def f(self): return "c2" class G(C1,C2): pass g = G() print("I would expect this value to be 'p'....
Python Multiple inheritance doesn't seem to be "depth first". Or am i missing something obvious
class B: def f(self): return "p" class C1(B): #no definition of f pass class C2(B): def f(self): return "c2" class G(C1,C2): pass g = G() print("I would expect this value to be 'p'. But it prints 'c2'",g.f()) According to python documentation: https://docs.python.org/3/tutorial/...
[ "\"That is definitely not happening.\" Sure it is.\nConsider this:\nclass A:\n def f(self):\n return \"a\"\n\n\nclass B:\n def f(self):\n return \"b\"\n\n\nclass C1(B):\n # no definition of f\n pass\n\n\nclass C2(B):\n def f(self):\n return \"c2\"\n\n\nclass G(C1, C2):\n pass\...
[ 0 ]
[]
[]
[ "multiple_inheritance", "oop", "python" ]
stackoverflow_0074271582_multiple_inheritance_oop_python.txt
Q: Plot a graph for the data types of a DataFrame I want to visualize the data types of my dataset as a part of exploratory data analysis and I have this data. In [1]: df_planet = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], 'radius': [2439.7, 6051.8, 6378.1], ...
Plot a graph for the data types of a DataFrame
I want to visualize the data types of my dataset as a part of exploratory data analysis and I have this data. In [1]: df_planet = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], 'radius': [2439.7, 6051.8, 6378.1], 'planet': ['Mercury', 'Venus', 'Earth']}) In...
[ "You need to count the data types.\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf_planet = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],\n 'radius': [2439.7, 6051.8, 6378.1],\n 'planet': ['Mercury', 'Venus', 'Earth']})\n\n\nplt.pie(df_planet.dtypes....
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "visualization" ]
stackoverflow_0074271565_matplotlib_pandas_python_visualization.txt
Q: Pandas change of state (decomposition) I'm trying to find a method of calculate the change of status. Status: C>B>A This is the dataset: ID Start 1007 A 1007 A 1007 B 1008 B 1008 A 1008 C 1008 B 1009 A 1009 A What I would like to do is calculate the number of changes per person. ID Increase Same Decrea...
Pandas change of state (decomposition)
I'm trying to find a method of calculate the change of status. Status: C>B>A This is the dataset: ID Start 1007 A 1007 A 1007 B 1008 B 1008 A 1008 C 1008 B 1009 A 1009 A What I would like to do is calculate the number of changes per person. ID Increase Same Decrease 1007 1 1 0 1008...
[ "import pandas as pd\n\n '''\n df = pd.DataFrame({\n 'ID' : [1007, 1007, 1007, 1008, 1008, 1008, 1008, 1009, 1009],\n 'Start' : ['A', 'A', 'B', 'B', 'A', 'C', 'B', 'A', 'A']\n })\n '''\n\n\ndef foo(df):\n\n ID_num = len(pd.unique(df['ID']))\n\n df_goal = pd.DataFrame({\n 'ID': pd.uniq...
[ 0 ]
[]
[]
[ "pandas", "python", "status" ]
stackoverflow_0074271162_pandas_python_status.txt
Q: Convert array of elements to multiple columns How I can convert a array (in a column) with a set of elements in a JSON dataset to multiple columns with python, spark or pandas? The data is structured in this form: root |-- items: array (nullable = true) | |-- element: struct (containsNull = true) | | |...
Convert array of elements to multiple columns
How I can convert a array (in a column) with a set of elements in a JSON dataset to multiple columns with python, spark or pandas? The data is structured in this form: root |-- items: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- id: string (nullable = true) | | |-- idAc...
[ "an array of structs can be exploded into columns using the inline sql function.\nhere's an example of how it works.\ndata_sdf = spark.createDataFrame([([(1234, 2345, 3456), (4321, 5432, 6543)],)], \n 'items array<struct<id: int, id_acc: int, foo: int>>'\n ...
[ 1, 0 ]
[]
[]
[ "apache_spark", "databricks", "pandas", "pyspark", "python" ]
stackoverflow_0074269558_apache_spark_databricks_pandas_pyspark_python.txt
Q: from app import db // No module named 'flask' maybe it looks strange, but I really don't understand what's wrong with this app. I started learning Flask and in the beggining of my path I received this error. Thanks in advance for helping! And if u can suggest pls what other databases I can use with Flask >>> from...
from app import db // No module named 'flask'
maybe it looks strange, but I really don't understand what's wrong with this app. I started learning Flask and in the beggining of my path I received this error. Thanks in advance for helping! And if u can suggest pls what other databases I can use with Flask >>> from app import db Traceback (most recent call last):...
[ "I see the screenshot you might do this in Python Console?if in Python Console,it is a pure python environment, not include your app package,you need finish the code, and use python app.py to run it.\n" ]
[ 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0074271413_python_virtualenv.txt
Q: Matplotlib and TKinter - Is there a way to have a graph update dynamically with button presses? I am attempting to follow a tutorial that uses TKinter and Matplotlib to produce graphs on a frame of a tkinter app. A problem that I have run in to is that the graph is not reloaded when I press the button. The command...
Matplotlib and TKinter - Is there a way to have a graph update dynamically with button presses?
I am attempting to follow a tutorial that uses TKinter and Matplotlib to produce graphs on a frame of a tkinter app. A problem that I have run in to is that the graph is not reloaded when I press the button. The command starts as soon as the program starts and does not run again upon being pressed. Below is the code th...
[ "Put all of the logic for plotting the matplotlib figure into a separate method and call it whenever the button is pressed for the graph frame/page. This means you will need a separate method for that specific button as well because it will need to call the graphing logic method when fired. The example below does...
[ 0 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0074270504_matplotlib_python_tkinter.txt
Q: Pipenv: Command Not Found I'm new to Python development and attempting to use pipenv. I ran the command pip install pipenv, which ran successfully: ... Successfully built pipenv pathlib shutilwhich pythonz-bd virtualenv-clone Installing collected packages: virtualenv, pathlib, shutilwhich, backports.shutil-get-ter...
Pipenv: Command Not Found
I'm new to Python development and attempting to use pipenv. I ran the command pip install pipenv, which ran successfully: ... Successfully built pipenv pathlib shutilwhich pythonz-bd virtualenv-clone Installing collected packages: virtualenv, pathlib, shutilwhich, backports.shutil-get-terminal-size, pythonz-bd, virtual...
[ "This fixed it for me:\nsudo -H pip install -U pipenv\n\n", "That happens because you are not installing it globally (system wide). For it to be available in your path you need to install it using sudo, like this:\n$ sudo pip install pipenv\n\n", "If you've done a user installation, you'll need to add the right...
[ 245, 207, 111, 42, 29, 15, 8, 5, 5, 5, 5, 4, 4, 4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ "For me, what worked on Windows was running Command Prompt as administrator and then installing pipenv globally: python -m pip install pipenv.\n" ]
[ -1 ]
[ "pip", "pipenv", "python", "python_3.x" ]
stackoverflow_0046391721_pip_pipenv_python_python_3.x.txt
Q: Can't compare naive and aware datetime.now() <= challenge.datetime_end I am trying to compare the current date and time with dates and times specified in models using comparison operators: if challenge.datetime_start <= datetime.now() <= challenge.datetime_end: The script errors out with: TypeError: can't compar...
Can't compare naive and aware datetime.now() <= challenge.datetime_end
I am trying to compare the current date and time with dates and times specified in models using comparison operators: if challenge.datetime_start <= datetime.now() <= challenge.datetime_end: The script errors out with: TypeError: can't compare offset-naive and offset-aware datetimes The models look like this: class ...
[ "By default, the datetime object is naive in Python, so you need to make both of them either naive or aware datetime objects. This can be done using:\nimport datetime\nimport pytz\n\nutc=pytz.UTC\n\nchallenge.datetime_start = utc.localize(challenge.datetime_start) \nchallenge.datetime_end = utc.localize(challenge.d...
[ 264, 157, 114, 46, 8, 3, 2, 1, 0, 0 ]
[ "Just:\ndt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'\ndt = datetime.datetime.strptime(dt,format)\n\nSo do this:\nstart_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')\nstart_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')\n\nend_time = challenge...
[ -1 ]
[ "comparison", "datetime", "django", "python" ]
stackoverflow_0015307623_comparison_datetime_django_python.txt
Q: Custom color highlighting for Pylance in VS Code: defined variables in white, undefined variables in red I am using Pylance in VS Code (Dark Theme), writing Python 3.9. When semantic highlighting is enabled, well defined variables are colored in cyan and when I use a variable that is not defined (and will yield er...
Custom color highlighting for Pylance in VS Code: defined variables in white, undefined variables in red
I am using Pylance in VS Code (Dark Theme), writing Python 3.9. When semantic highlighting is enabled, well defined variables are colored in cyan and when I use a variable that is not defined (and will yield error when running the code) it is colored in white. I want to change this such that a well defined variable wil...
[ "The following configuration may be useful to you\n// settings.json file\n{\n \"editor.tokenColorCustomizations\":{\n \"[Default Dark+]\": {\n \"textMateRules\": [\n {\n \"scope\": \"meta.function-call.arguments.python, source.python\",\n \"s...
[ 1 ]
[]
[]
[ "pylance", "python", "visual_studio_code" ]
stackoverflow_0074265477_pylance_python_visual_studio_code.txt
Q: replacing values in a data frame from a dictionary with multiple keys I have not seen any posts about this on here. I have a data frame with some data that i would like to replace the values with the values found in a dictionary. This could simply be done with .replace but I want to keep this dynamic and reference...
replacing values in a data frame from a dictionary with multiple keys
I have not seen any posts about this on here. I have a data frame with some data that i would like to replace the values with the values found in a dictionary. This could simply be done with .replace but I want to keep this dynamic and reference the df column names using a paired dictionary map. import pandas as pd da...
[ "I'd keep the replace_dict keys the same as the column names.\ndef map_from_dict(data: pd.DataFrame, cols: list, mapping: dict) -> pd.DataFrame:\n return pd.DataFrame([data[x].map(mapping.get(x)) for x in cols]).transpose()\n\n\ndf = pd.DataFrame({\n \"letters\": [\"Alphabet\"],\n \"states\": [\"Indiana\"]...
[ 1, 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074270887_dataframe_dictionary_pandas_python.txt
Q: How to print the content of the last saved text file in a folder using Python I want to print the content of the last saved text file in a folder using Python. I wrote the below code. It is printing out only the path of the file but not the content. folder_path = r'C:\Users\Siciid\Desktop\restaurant\bill' ...
How to print the content of the last saved text file in a folder using Python
I want to print the content of the last saved text file in a folder using Python. I wrote the below code. It is printing out only the path of the file but not the content. folder_path = r'C:\Users\Siciid\Desktop\restaurant\bill' file_type = r'\*txt' files = glob.glob(folder_path + file_type) max_file = ...
[ "You can do that using the following code. Just replace the line where you open and write a file with these two lines:\nwith open(max_file, \"r\") as f, open(filename, 'w') as f2:\n f2.write(f.read())\n\nThe max_file variable contains a file name, not the contents of the file, so writing it to the temp file and ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074271556_python.txt
Q: Remotely accesssing RTSP url with Python & OpenCV I am able to view the camera on the local area network with the following python code, not a problem. However when the same code is run from a remote site, it breaks with empty frames. VLC player can view this network address over the remote connection just fine. H...
Remotely accesssing RTSP url with Python & OpenCV
I am able to view the camera on the local area network with the following python code, not a problem. However when the same code is run from a remote site, it breaks with empty frames. VLC player can view this network address over the remote connection just fine. Here is the code: import os import cv2 os.environ["OP...
[ "Here is a way to access rstp cam stream from a remote LAN with opencv. Doing so requires two basic computers, in my case rpi3s, one in each LAN.\nCheck both the rpis for IP forwarding being enabled:\nsysctl net.ipv4.ip_forward\n\nIf the value is '0' then: edit /etc/sysctl.conf. Search for a line containing the ent...
[ 1 ]
[]
[]
[ "ffmpeg", "opencv", "python", "rtsp" ]
stackoverflow_0074253332_ffmpeg_opencv_python_rtsp.txt
Q: How to create lists given a number without writing everything line by line? Say there is a variable that finds a number of objects, and empty lists have to be created for each object. For example: objectNum = 4 a = [ ] b = [ ] c = [ ] d = [ ] Or with any other number, and those lists have to be named by alphabet....
How to create lists given a number without writing everything line by line?
Say there is a variable that finds a number of objects, and empty lists have to be created for each object. For example: objectNum = 4 a = [ ] b = [ ] c = [ ] d = [ ] Or with any other number, and those lists have to be named by alphabet. How can this be done? I tried using globals() function, but that was applicable ...
[ "When you want a variable number of variables that you don't know in advance, one usually uses a dictionary instead of adding them dynamically to the module namespace as a variable. If you didn't know you were going to add, say, \"t\", how would you know to use it later?\nIn your example, you want lower case letter...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074271690_python.txt
Q: how to get aligned output of two list? la=["ngsir","raise","kajggf","kajggsdda","kajgg","kajggkjabfkafku","kajgg","asakfaflg","as","sfowih","akjfglff"] lb=["raise","kajggf","kajggkjabfkafku","cvsk","kajgg","asakfaflg","as","sfowih","akjfglff","kajggsdda","kajgg"] print("team A:\t\t\t team B:") for i in range(11): ...
how to get aligned output of two list?
la=["ngsir","raise","kajggf","kajggsdda","kajgg","kajggkjabfkafku","kajgg","asakfaflg","as","sfowih","akjfglff"] lb=["raise","kajggf","kajggkjabfkafku","cvsk","kajgg","asakfaflg","as","sfowih","akjfglff","kajggsdda","kajgg"] print("team A:\t\t\t team B:") for i in range(11): print(la[i]+"\t\t\t"+lb[i]) i was expecting ...
[ "I believe that the below solution achieves what you are looking for.\nla=[\"ngsir\",\"raise\",\"kajggf\",\"kajggsdda\",\"kajgg\",\"kajggkjabfkafku\",\"kajgg\",\"asakfaflg\",\"as\",\"sfowih\",\"akjfglff\"]\n\nlb=[\"raise\",\"kajggf\",\"kajggkjabfkafku\",\"cvsk\",\"kajgg\",\"asakfaflg\",\"as\",\"sfowih\",\"akjfglff\...
[ 2, 1, 1, 0 ]
[]
[]
[ "alignment", "list", "python" ]
stackoverflow_0074271681_alignment_list_python.txt
Q: How to upload file to supabase storage with python api? I am working with a project which needs to use python to store the png file into supabase storage. But I do not know how to do that. Can anyone please help me? I actually got a bucket in my storage. But when i use fllowing code to print buckets, it will just ...
How to upload file to supabase storage with python api?
I am working with a project which needs to use python to store the png file into supabase storage. But I do not know how to do that. Can anyone please help me? I actually got a bucket in my storage. But when i use fllowing code to print buckets, it will just give me "[]". url = storage_url key = get_settings().supabase...
[ "Supabase-py maintainer here. Thanks for the question! Supabase Storage makes use of Row Level Security(RLS) policies under the hood and will only show buckets that the client can view. If there are no buckets that a client can view it will return an empty list.\nCould you check your Supabase Dashboard settings and...
[ 1 ]
[]
[]
[ "python", "supabase_py" ]
stackoverflow_0074270778_python_supabase_py.txt
Q: Selenium unable to locate element event though element does exists i want to get the location this store from google maps but selenium is unable to locate it. why is that? store google maps link: https://www.google.com/maps/place/Blaze+Pizza/@24.5014283,54.387503,17z/data=!3m1!4b1!4m5!3m4!1s0x3e5e676982d20b17:0xe2...
Selenium unable to locate element event though element does exists
i want to get the location this store from google maps but selenium is unable to locate it. why is that? store google maps link: https://www.google.com/maps/place/Blaze+Pizza/@24.5014283,54.387503,17z/data=!3m1!4b1!4m5!3m4!1s0x3e5e676982d20b17:0xe2c5b69e67e4c85d!8m2!3d24.5014283!4d54.3896917 by code segment: location =...
[ "First friend, it is not right to look for the xpath this way. Copying your code and correcting it would be like this (Locating Elements - Documentation\nlocation = driver.find_element(By.XPATH,'//*[@id=\"QA0Szd\"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[9]/div[3]/button/div[1]/div[2]/div[1]').text\n\nIn addit...
[ 1, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074251910_python_selenium_selenium_chromedriver_web_scraping.txt
Q: Parsing boolean values with argparse I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: my_program --my_boolean_flag False However, the following test code does not do what I would like: import argparse parser = argparse.ArgumentParser(descr...
Parsing boolean values with argparse
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: my_program --my_boolean_flag False However, the following test code does not do what I would like: import argparse parser = argparse.ArgumentParser(description="My parser") parser.add_argument("-...
[ "I think a more canonical way to do this is via:\ncommand --feature\n\nand\ncommand --no-feature\n\nargparse supports this version nicely:\nPython 3.9+:\nparser.add_argument('--feature', action=argparse.BooleanOptionalAction)\n\nPython < 3.9:\nparser.add_argument('--feature', action='store_true')\nparser.add_argume...
[ 1315, 473, 360, 117, 81, 40, 30, 29, 19, 15, 13, 12, 12, 9, 6, 4, 3, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "argparse", "boolean", "command_line_arguments", "python" ]
stackoverflow_0015008758_argparse_boolean_command_line_arguments_python.txt
Q: Save List of Lists in a file I want to know if there is a simple way to save list of lists in a file to import it later again like the same list of lists. No matter the size of it. List_lists=[["a",1,2,3,4],["b",1,2,3,4],["c",1,2,3,4],.....] Also i want to know is there is a way to throw a list with the first ele...
Save List of Lists in a file
I want to know if there is a simple way to save list of lists in a file to import it later again like the same list of lists. No matter the size of it. List_lists=[["a",1,2,3,4],["b",1,2,3,4],["c",1,2,3,4],.....] Also i want to know is there is a way to throw a list with the first element in each list (in this case "a...
[ "You can save the list into a CSV file using the numpy module in python. Please see sample code below.\ncode:\nimport numpy as np\n\nList_lists=[[\"a\",1,2,3,4],[\"b\",1,2,3,4],[\"c\",1,2,3,4]]\n\n# using the savetxt \n# from the numpy module\nnp.savetxt(\"list.csv\", List_lists, delimiter =\", \", fmt ='% s')\n\no...
[ 0 ]
[ "You could use the zip() function, which joins lists together in their corresponding order.\nl1 = ['a', 1, 2, 3, 4]\nl2 = ['b', 1, 2, 3, 4]\nl3 = ['c', 1, 2, 3, 4]\n\n# To access them through a for loop:\nfor a, b, c in zip(l1, l2, l3):\n # Do something\n\nNote that using nested lists are fine as well.\n" ]
[ -1 ]
[ "file", "list", "python", "save" ]
stackoverflow_0074271865_file_list_python_save.txt
Q: How to iterate, move items to a dictionary and keep state in a list using values from a second list as conditions? I have two lists. The first list is the authors' list. The second list has two types of objects, authors and text. Text is split into words. The structure of the second list is that there is an author...
How to iterate, move items to a dictionary and keep state in a list using values from a second list as conditions?
I have two lists. The first list is the authors' list. The second list has two types of objects, authors and text. Text is split into words. The structure of the second list is that there is an author first and several words which together make his speech. In the second list there are several authors with their speeche...
[ "Checking if an element of authors_and_words is in authors is easy enough: use the in keyword.\nNow, iterate over each element of authors_and_words, and if it is an author, that is your dictionary key. Whenever you find a new author, create a dictionary that will store their lines, and append this dictionary to the...
[ 1, 0 ]
[]
[]
[ "algorithm", "loops", "python" ]
stackoverflow_0074266816_algorithm_loops_python.txt
Q: Python list - call function with different values def check(val, list=[]): list.append(val) return list list1=check("a") list2=check("b",[]) list3=check("c") If I run list1 and check the output it shows ["a"] But, If I run list1, list2 and list3 in one cell and check for list1 it shows ['a','c'], can so...
Python list - call function with different values
def check(val, list=[]): list.append(val) return list list1=check("a") list2=check("b",[]) list3=check("c") If I run list1 and check the output it shows ["a"] But, If I run list1, list2 and list3 in one cell and check for list1 it shows ['a','c'], can someone please explain why is it so?
[ "This is the right way to do this:\ndef check(val, values=None):\n if values is None:\n values = []\n values.append(val)\n return values\n\n\nlist1 = check(\"a\")\nlist2 = check(\"b\", [])\nlist3 = check(\"c\")\n\nDefault argument values should not be mutable. You can find a good explanation here,\n...
[ 2 ]
[ "It seems that list1 and list3 share same object.\nYou can try this:\ndef check(val, list=[]):\n list.append(val)\n print(hex(id(list)))\n return list\n\nlist1=check(\"a\")\nlist2=check(\"b\")\nlist3=check(\"c\")\n\nprint(list1)\nprint(list2)\nprint(list3)\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074272010_python.txt
Q: How to Find the number of rows and columns in QGridlayout in PyQt5? How to find the number of rows and columns in QGridlayout ?, In my code, I have Buttons arranged in QGridLayout. Now I need to find out the total number of columns and the total number of rows. from PyQt5.QtWidgets import * from PyQt5.QtCore impo...
How to Find the number of rows and columns in QGridlayout in PyQt5?
How to find the number of rows and columns in QGridlayout ?, In my code, I have Buttons arranged in QGridLayout. Now I need to find out the total number of columns and the total number of rows. from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Widget(QWidget): def __init__(self): super().__in...
[ "For basic usage, rowCount() and columnCount() will suffice, as already said in other answers.\nBe aware, though, that the above will only be reliable for the following conditions:\n\nlayout items (widgets, nested layouts, spacers) are always added continuously: for instance, grid layout allows adding an item at ro...
[ 3, 2, 1 ]
[]
[]
[ "pyqt", "pyqt5", "python" ]
stackoverflow_0074270987_pyqt_pyqt5_python.txt
Q: Best way to replace multiple characters in a string? I need to replace some characters as follows: & ➔ \&, # ➔ \#, ... I coded as follows, but I guess there should be some better way. Any hints? strs = strs.replace('&', '\&') strs = strs.replace('#', '\#') ... A: Replacing two characters I timed all the methods ...
Best way to replace multiple characters in a string?
I need to replace some characters as follows: & ➔ \&, # ➔ \#, ... I coded as follows, but I guess there should be some better way. Any hints? strs = strs.replace('&', '\&') strs = strs.replace('#', '\#') ...
[ "Replacing two characters\nI timed all the methods in the current answers along with one extra.\nWith an input string of abc&def#ghi and replacing & -> \\& and # -> \\#, the fastest way was to chain together the replacements like this: text.replace('&', '\\&').replace('#', '\\#').\nTimings for each function:\n\na) ...
[ 690, 80, 72, 44, 18, 18, 8, 5, 3, 3, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "replace", "string" ]
stackoverflow_0003411771_python_replace_string.txt
Q: Python: weighted percentile for each row of array I would like to calculate the weighted median of each row of a pandas dataframe. I found this nice function (https://stackoverflow.com/a/29677616/10588967), but I don't seem to be able to pass a 2d array. def weighted_quantile(values, quantiles, sample_weight=None,...
Python: weighted percentile for each row of array
I would like to calculate the weighted median of each row of a pandas dataframe. I found this nice function (https://stackoverflow.com/a/29677616/10588967), but I don't seem to be able to pass a 2d array. def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False): """ Very close ...
[ " np.cumsum(sample_weight)\n\nreturn a 1D list. So you would like to reshape it to (10,5,5) using\nnp.cumsum(sample_weight).reshape(10,5,5)\n\n", "Try my code in the handy repo\nhttps://github.com/syrte/handy/blob/773a1500a9e10dd28eb0704fded94d6105a84374/stats.py#L239\nI copy the docstring here, so you see what ...
[ 0, 0 ]
[]
[]
[ "numpy", "pandas", "percentile", "python", "weighted" ]
stackoverflow_0053095153_numpy_pandas_percentile_python_weighted.txt
Q: I want to validate my array json data having value as 'None' i want to validate my json array. also want to validate if array field comes as 'None' then it should be validated also, if array field is not 'None' then it will validate all the fields as required. from jsonschema import validate data ={"coffee": {"re...
I want to validate my array json data having value as 'None'
i want to validate my json array. also want to validate if array field comes as 'None' then it should be validated also, if array field is not 'None' then it will validate all the fields as required. from jsonschema import validate data ={"coffee": {"region": [{"id": 1,"name": "John Doe"},{"id": 2,"name": "Don Joeh"}]...
[ "I just rearranged the schema in your code and it validates both sample data. Let me know if it works for you.\nschema = {\"type\": \"object\",\n \"required\": [\"coffee\", \"brewing\"],\n \"additionalProperties\": False,\n \"properties\": {\n \"coffee\": {\"type\": \"object\", \"required\":...
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074271821_json_python.txt
Q: moviepy mp4 to mp3 converter I am trying to use python to convert files from mp4 to mp3. After some research most places recommend moviepy. I used the command pip install moviepy and it seemed to go off without a hitch. I go to VS Code and enter what a youtube video told me to enter (I know its not recommended to ...
moviepy mp4 to mp3 converter
I am trying to use python to convert files from mp4 to mp3. After some research most places recommend moviepy. I used the command pip install moviepy and it seemed to go off without a hitch. I go to VS Code and enter what a youtube video told me to enter (I know its not recommended to do that, I just wanted to see if i...
[ "try to use this code which is i got\nimport moviepy.editor\nimport os\nos.environ[\"IMAGEIO_FFMPEG_EXE\"] = \"/usr/bin/ffmpeg\"\nmp4_file = \"file_name.mp4\"\n\nmp3_file = \"file_name.mp3\"\n# Replace the parameter with the location of the video\n\nvideo = moviepy.editor.VideoFileClip(\"mp4_file\")\naudio = video....
[ 0 ]
[]
[]
[ "ffmpeg", "moviepy", "python", "python_3.x" ]
stackoverflow_0074270073_ffmpeg_moviepy_python_python_3.x.txt
Q: Alembic drops and creates foreign key constraints (autogenerate) when the table has different schema than the referenced columns I am trying to use the autogenerate feature from alembic to update the schema of a MSSQL database. class Table1(Base): __tablename__ = "table1" __table_args__ = ( Primary...
Alembic drops and creates foreign key constraints (autogenerate) when the table has different schema than the referenced columns
I am trying to use the autogenerate feature from alembic to update the schema of a MSSQL database. class Table1(Base): __tablename__ = "table1" __table_args__ = ( PrimaryKeyConstraint("ID", name="PK_Table1"), ) ID = Column(Integer, nullable=False) class Table2(Base): __tablename__ = "table...
[ "I'm also facing this issue. And no luck finding the answer. For now i just edit the alembic generated code and do the db upgrade. But it's very annoying repeated thing especially when the tables grow up.\n" ]
[ 0 ]
[]
[]
[ "alembic", "foreign_keys", "python", "sqlalchemy" ]
stackoverflow_0072941066_alembic_foreign_keys_python_sqlalchemy.txt
Q: How do I turn an SQLite table into a SpatiaLite table? I've got a Pandas table in an SQLite database with 40 odd columns all of which might need to be interrogated in QGIS. The table contains XY data and a previous Python code captured the EPSG code needed to create the points. How do I transform my Pandas or SQLi...
How do I turn an SQLite table into a SpatiaLite table?
I've got a Pandas table in an SQLite database with 40 odd columns all of which might need to be interrogated in QGIS. The table contains XY data and a previous Python code captured the EPSG code needed to create the points. How do I transform my Pandas or SQLite table into a SpatiaLite table? spatialite_path = 'C:\Prog...
[ "Finally I guess'n'checked my way into using this tidbit at the end of the code:\ncur.execute('SELECT RecoverGeometryColumn(\"table_with_XY\", \"geometry\", (?), \"POINT\", \"XY\")', (EPSG_Code,))\n\nFull code:\n#This only has to happen once per computer (i think) so feel free to skip these 2 lines\nspatialite_path...
[ 0 ]
[]
[]
[ "pandas", "python", "qgis", "spatialite", "sqlite" ]
stackoverflow_0074272165_pandas_python_qgis_spatialite_sqlite.txt
Q: Python type error: 'numpy.ndarray' object is not callable--how to fix? This is my code. When I run it, I get an issue with the python error: 'numpy.ndarray' object is not callable. I think that the issue is because I call V_function_prime in the functions for find_k, find_w, but I don't know how else to do this i...
Python type error: 'numpy.ndarray' object is not callable--how to fix?
This is my code. When I run it, I get an issue with the python error: 'numpy.ndarray' object is not callable. I think that the issue is because I call V_function_prime in the functions for find_k, find_w, but I don't know how else to do this import numpy as np import copy as cp import scipy as sp from scipy import op...
[ "#takes in value w and current guess of v_prime and returns optimal capital choice (k)\ndef find_k(k, w, v_function_prime):\n foc = (1-phi)*u_prime(w - (1-phi)*k) - beta*v_function_prime(production(k) - R*phi*k)(production_prime(k)-R*phi) ## Two times repeated function call\n return foc\n\n\nCheck above block...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074272097_numpy_python.txt
Q: Joining data frames one after the other with no matching columns - Python pandas I have two dataframes like: A B 1 2 3 4 5 6 df2: C D 7 8 9 10 2 3 4 5 I wish to combine these dataframes one after the other like the following: A B C D 1 2 3 4 5 6 7 8 9 10 2 3 4 5 I have tried using concat ...
Joining data frames one after the other with no matching columns - Python pandas
I have two dataframes like: A B 1 2 3 4 5 6 df2: C D 7 8 9 10 2 3 4 5 I wish to combine these dataframes one after the other like the following: A B C D 1 2 3 4 5 6 7 8 9 10 2 3 4 5 I have tried using concat and join but it doesnt give me this desired output. Thanks
[ "import pandas as pd\nimport numpy as np\n\n\ndf1 = pd.DataFrame({\n 'A' : [1, 3, 5],\n 'B' : [2, 4, 6]\n})\n\ndf2 = pd.DataFrame({\n 'C' : [7, 9, 2, 4],\n 'D' : [8, 10, 3, 5]\n})\n\n\ndef foo(df1, df2):\n df_1 = df1.copy()\n df_2 = df2.copy()\n df1[df_2.columns] = np.nan\n df2[df_1.columns]...
[ 0, 0 ]
[]
[]
[ "concatenation", "dataframe", "pandas", "python" ]
stackoverflow_0074271648_concatenation_dataframe_pandas_python.txt
Q: error when install pygame using -m pip install pygame from cmd C:\Windows\System32>python -m pip install pygame Collecting pygame Using cached pygame-2.1.2.tar.gz (10.1 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ ...
error when install pygame using -m pip install pygame from cmd
C:\Windows\System32>python -m pip install pygame Collecting pygame Using cached pygame-2.1.2.tar.gz (10.1 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [77 lines of output] .... note: This error ori...
[ "You need to install/update setuptools:\npip install --upgrade setuptools\n\nIt will most probably fix your issue.\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074272051_pygame_python.txt
Q: How to return output as 'int' instead of 'numpy.int64'? I am new to Python and I have troubles understanding the difference between 'int' and 'numpy.int64'. Below is the question: I would need to complete the function explore_data to return a tuple, t, with the following elements. t[0] - tuple - the shape of df t[...
How to return output as 'int' instead of 'numpy.int64'?
I am new to Python and I have troubles understanding the difference between 'int' and 'numpy.int64'. Below is the question: I would need to complete the function explore_data to return a tuple, t, with the following elements. t[0] - tuple - the shape of df t[1] - pd.DataFrame - the first five rows of df t[2] - dict - m...
[ "You can convert your keys and values of the dictionary while assigning them like this\nimport pandas as pd, numpy as np\ndef explore_data(df):\n res = list()\n res.append(df.shape) \n res.append(df.head())\n gb = df.groupby('year').size()\n gb = gb.to_frame().reset_index().rename(columns = {0: 'Numb...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074271854_python.txt
Q: CUDA 11.8 and Pytorch with RTX 3060 (Not working GPU as compute engine) I'm trying to use my GPU as compute engine with Pytorch. I have all the drivers (522.25) with CUDA 11.8 installed in my local machine, but Pytorch can't recognize my GPU. I'll attach images from my noteebok cells and my CMD with NVIDIA-SMI com...
CUDA 11.8 and Pytorch with RTX 3060 (Not working GPU as compute engine)
I'm trying to use my GPU as compute engine with Pytorch. I have all the drivers (522.25) with CUDA 11.8 installed in my local machine, but Pytorch can't recognize my GPU. I'll attach images from my noteebok cells and my CMD with NVIDIA-SMI command. I will appreciate any kind of help or info regarding this issue. I in...
[]
[]
[ "Lastest pytorch is supported at cuda version 11.6 ...\nYou can check it this link below\nhttps://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel_22-02.html\n" ]
[ -2 ]
[ "cuda", "python", "pytorch" ]
stackoverflow_0074269680_cuda_python_pytorch.txt
Q: django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace I am trying to create a Log in and Registration for a Django Rest Framework but I keep getting django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace not sure what is the reason for getting this error and how to fix it...
django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace
I am trying to create a Log in and Registration for a Django Rest Framework but I keep getting django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace not sure what is the reason for getting this error and how to fix it? Here is the serializers.py: class UserSerializer(serializers.ModelSerializer): ...
[ "Make sure that you defined the app_name=\"user\" just above the url patterns in urls.py to be the registered namespace.\nurls.py:\napp_name='user'\n\nurlpatterns=[\n #...\n #...\n path('get-details/', UserDetailAPI.as_view()),\n path('register/', RegisterUserAPIView.as_view()),\n #...\n #...\n]\n...
[ 2, 1 ]
[]
[]
[ "django", "django_rest_framework", "django_urls", "django_views", "python" ]
stackoverflow_0074271324_django_django_rest_framework_django_urls_django_views_python.txt
Q: add select options to an existing selection field odoo 15 im trying to add more options to an existing selection field (em_y) depending on what's selected from another selection field (em_x) . here is my code from odoo import models,fields,api class HrEmployee(models.Model): _inherit=['hr.employee'] em_x ...
add select options to an existing selection field odoo 15
im trying to add more options to an existing selection field (em_y) depending on what's selected from another selection field (em_x) . here is my code from odoo import models,fields,api class HrEmployee(models.Model): _inherit=['hr.employee'] em_x = fields.Selection(selection=[('x A','x A'),('x B','x B')],stri...
[ "It isn't possible with \"Selection\" field. You must use \"Many2one\" field and in onchange method return domain.\nclass HrEmployee(models.Model):\n _inherit=['hr.employee']\n\n em_x = fields.Many2one('em.x',string='X')\n em_y = fields.Many2one('em.x',string='Y',domain=[('id','=',0)])\n\n@api.onchange('em_x')\n...
[ 0 ]
[]
[]
[ "odoo", "odoo_14", "odoo_15", "python", "xml" ]
stackoverflow_0074265732_odoo_odoo_14_odoo_15_python_xml.txt
Q: Get max value from nested dictionary return both keys if equal I have following dictionary { "match_1":{ "home_team":2, "away_team":1 }, "match_2":{ "home_team":1, "away_team":2 }, "match_3":{ "home_team":1, "away_team":4} } I want to sum home...
Get max value from nested dictionary return both keys if equal
I have following dictionary { "match_1":{ "home_team":2, "away_team":1 }, "match_2":{ "home_team":1, "away_team":2 }, "match_3":{ "home_team":1, "away_team":4} } I want to sum home team and away team goals and find which team won in aggregate if b...
[ "Try the below approach\ntable = {\n \"match_1\":{\n \"home_team\":2,\n \"away_team\":1\n },\n \"match_2\":{\n \"home_team\":1,\n \"away_team\":2\n },\n \"match_3\":{\n \"home_team\":1,\n \"away_team\":4}\n\n\n}\nscore = {}\nfor match in table.keys():\n ...
[ 1, 1, 1, 1 ]
[]
[]
[ "dictionary", "max", "python" ]
stackoverflow_0074272210_dictionary_max_python.txt
Q: Expand dict to dataframe with one value of key is list I am new to python and try to figure out this one, can't find this anywhere please help! I have a dictionary like the following: dict1 = {'id':1, 'col': 'b', 'item': [{'num': 111, 'value': 222},{'num': 333, 'value': 444}]} I know how to expand first list in 'i...
Expand dict to dataframe with one value of key is list
I am new to python and try to figure out this one, can't find this anywhere please help! I have a dictionary like the following: dict1 = {'id':1, 'col': 'b', 'item': [{'num': 111, 'value': 222},{'num': 333, 'value': 444}]} I know how to expand first list in 'item' to dataframe into one row, my code are as follow: df = ...
[ "In fact, the solution is to iterate on the item list and append each time the same row with id, col and the new num and value\ndf = pd.DataFrame()\ndf = df.append({'id':1, 'col': 'b', 'item': [{'num': 111, 'value': 222},{'num': 333, 'value': 444}]}, ignore_index=True)\nitem_detail = df.loc[0, 'item']\nfor item in ...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "list", "python" ]
stackoverflow_0074270265_dataframe_dictionary_list_python.txt
Q: Making a random int just be itself once in loop So.. im working on this loop: stuff_so_far = [intl_pt] for i in range(0, num_pts - 1): rdm = random.randint(0, len(points_in_code) - 1) a = (stuff_so_far[i][0] + points_in_code[rdm][0]) // 2 b = (stuff_so_far[i][1] + points_in_code[rdm][1]) // 2 stuf...
Making a random int just be itself once in loop
So.. im working on this loop: stuff_so_far = [intl_pt] for i in range(0, num_pts - 1): rdm = random.randint(0, len(points_in_code) - 1) a = (stuff_so_far[i][0] + points_in_code[rdm][0]) // 2 b = (stuff_so_far[i][1] + points_in_code[rdm][1]) // 2 stuff_so_far.append((a, b)) Basically what i want to ach...
[ "You can use random.sample:\nimport random\n\npoints_in_code = [11, 4, 13, 18, 7, 12] # Just a example\nnum_pts = 4\n\nindexes = random.sample(range(len(points_in_code)), num_pts - 1)\nfor rdm, i in zip(indexes, range(0, num_pts - 1)):\n pass # rdm will be a random unique index\n # i will increase 1 each iter...
[ 1, 0, 0 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0074272259_for_loop_loops_python.txt
Q: How to debug sporadic freezing of PyQt5 application after exiting? I'm developing PyQt5 application of medium complexity. It has various widgets (both native and third-party) and Qthreads. It woks fine most of the time, but once in about 5 times the application hangs in the background after I exit it. Here is how ...
How to debug sporadic freezing of PyQt5 application after exiting?
I'm developing PyQt5 application of medium complexity. It has various widgets (both native and third-party) and Qthreads. It woks fine most of the time, but once in about 5 times the application hangs in the background after I exit it. Here is how I define closeEvent: def closeEvent(self, event): qApp.quit() And I...
[ "This kind of bugs are hard to isolate. It looks like my particular bug emerges as a result of combination of several widgets of the app and it's hard to even provide a minimal working example that reproduces the error. Not to mention the error only happens once in a few runs.\nIt looks like I've found the main cul...
[ 0 ]
[]
[]
[ "debugging", "multithreading", "pyqt", "python" ]
stackoverflow_0074262502_debugging_multithreading_pyqt_python.txt
Q: For Loop Comparing Values Through Inequalities and Appending it to a new list a = [1,4,7,5,9,3,5] b = [3,7,6,5,4,9,7] c = [] for i in range(len(a)-1): if a[i] < b[i]: c.append(b[i]) I have the simple code above. Since len(a) = 7. The for loop should run 7-1 =6 times. I want to check is a[i] i...
For Loop Comparing Values Through Inequalities and Appending it to a new list
a = [1,4,7,5,9,3,5] b = [3,7,6,5,4,9,7] c = [] for i in range(len(a)-1): if a[i] < b[i]: c.append(b[i]) I have the simple code above. Since len(a) = 7. The for loop should run 7-1 =6 times. I want to check is a[i] is less than b[i]. If this is true, then it should print the b[i] value in the new l...
[ "I am not entirely sure what you are trying to achieve but as far as I can tell your code is doing what you are saying. The reason you are not getting any output is because you are not printing the resulting list (try add print(c) to the end of your code.\nIf instead you are trying to make a new list that contains ...
[ 1, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0074272363_list_loops_python.txt
Q: How to effectively iterate by many foreignkey objects with Django ORM? Let's say that I have model like: class User(AbstractUser): ... seller = models.ForeignKey(Seller, related_name="user", on_delete=models.SET_NULL, null=True) ... And I trying to get seller email address using this code: from app.models ...
How to effectively iterate by many foreignkey objects with Django ORM?
Let's say that I have model like: class User(AbstractUser): ... seller = models.ForeignKey(Seller, related_name="user", on_delete=models.SET_NULL, null=True) ... And I trying to get seller email address using this code: from app.models import User from django_print_sql import print_sql with print_sql(count_onl...
[ "Looks like select_related is working for this case:\nfrom app.models import User\nfrom django_print_sql import print_sql\n\nwith print_sql(count_only=False):\n users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related('seller').only('seller__email').exclude(seller__email__exact='')\n fo...
[ 0, 0 ]
[]
[]
[ "django", "django_orm", "python", "sql" ]
stackoverflow_0074271140_django_django_orm_python_sql.txt
Q: How to make simple filtration with django-filter I faced with a problem. I have a simple drf project with car-entrance permits application. views.py ` class PermitViewSet(ModelViewSet): queryset = Permit.objects.filter() serializer_class = PermitSerializer filter_backends = [DjangoFilterBackend] fi...
How to make simple filtration with django-filter
I faced with a problem. I have a simple drf project with car-entrance permits application. views.py ` class PermitViewSet(ModelViewSet): queryset = Permit.objects.filter() serializer_class = PermitSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['car_number'] serializers.py ` class P...
[ "You specify the fields with the filterset_fields attribute [drf-doc], not the filter_fields attribute:\nclass PermitViewSet(ModelViewSet):\n queryset = Permit.objects.all()\n serializer_class = PermitSerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ['car_number']\n", "First o...
[ 3, 0 ]
[]
[]
[ "django", "django_filters", "django_rest_framework", "python" ]
stackoverflow_0074269328_django_django_filters_django_rest_framework_python.txt
Q: Pytorch loss is nan I'm trying to write my first neural network with pytorch. Unfortunately, I encounter a problem when I want to get the loss. The following error message: RuntimeError: Function 'LogSoftmaxBackward0' returned nan values in its 0th output. So I tried debugging and found something strange. The inp...
Pytorch loss is nan
I'm trying to write my first neural network with pytorch. Unfortunately, I encounter a problem when I want to get the loss. The following error message: RuntimeError: Function 'LogSoftmaxBackward0' returned nan values in its 0th output. So I tried debugging and found something strange. The input has no nans and infs a...
[ "Sorry, my reputation is not enough for me to comment directly. This may be caused by the exploding gradient due to the excessive learning rate. It is recommended that you reduce the learning rate or use weight_decay.\n", "If it is an error in the 0th output, that means your weights are still not fully updates so...
[ 2, 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0071503683_python_pytorch.txt
Q: How to get a thread name in Python? I'm trying to get the thread name test_thread with threading.current_thread().name between t.start() and t.join() as shown below: import threading def test(): print("test") # Thread name t = threading.Thread(target=test, n...
How to get a thread name in Python?
I'm trying to get the thread name test_thread with threading.current_thread().name between t.start() and t.join() as shown below: import threading def test(): print("test") # Thread name t = threading.Thread(target=test, name="test_thread") t.start() print(thread...
[ "You need to use threading.current_thread().name in test() as shown below:\nimport threading\n\ndef test():\n print(\"test\")\n print(threading.current_thread().name) # Here\n \nt = threading.Thread(target=test, name=\"test_thread\")\nt.start() ...
[ 0 ]
[]
[]
[ "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074272554_multithreading_python_python_3.x_python_multithreading.txt