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: Display JSON data on a page as a expandable/collapsible list I need help with with displaying JSON data on a page like expandable/collapsible list. Here is a valid JSON I`ve made converting from XML with Python: JSON Data And to display it I`m usig this: <!DOCTYPE HTML> <head> <title>JSON Tree View</title> ...
Display JSON data on a page as a expandable/collapsible list
I need help with with displaying JSON data on a page like expandable/collapsible list. Here is a valid JSON I`ve made converting from XML with Python: JSON Data And to display it I`m usig this: <!DOCTYPE HTML> <head> <title>JSON Tree View</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jq...
[ "a good-looking, compact, collapsible tree view\npgrabovets' json-view is amazingly clean and well designed.\nCheck out the demo\n", "If you can consider using JS libraries , consider using JSON Formatter or Render JSON.\nBoth these libraries offer configuration options like themes, maximum depth and sorting.\nTo...
[ 13, 9, 3, 0 ]
[]
[]
[ "javascript", "json", "list", "python", "tree" ]
stackoverflow_0032549518_javascript_json_list_python_tree.txt
Q: How to merge multiple columns in Pandas with a single series? I have a dataframe (t) of codes for patients surgeries. On any hospital admission they can have 5 surgeries or combination of surgeries, - the index on the left column is the indiviudal patient. I want to add the text description for all 5 surgeries to ...
How to merge multiple columns in Pandas with a single series?
I have a dataframe (t) of codes for patients surgeries. On any hospital admission they can have 5 surgeries or combination of surgeries, - the index on the left column is the indiviudal patient. I want to add the text description for all 5 surgeries to indivisual new columns. | OPERTN_01 | OPERTN_02 | OPERTN_0...
[ "I think a dictionary-based replace method is what you're after. Does the following achieve your desired result?\ncode_map = {i[1]: i[2] for i in opcs_short.to_records()}\n\nfor col in t.columns:\n t[col + \" Description\"] = t[col].replace(code_map)\n\n" ]
[ 2 ]
[]
[]
[ "merge", "pandas", "python" ]
stackoverflow_0074588410_merge_pandas_python.txt
Q: Does `await` in Python yield to the event loop? I was wondering what exactly happens when we await a coroutine in async Python code, for example: await send_message(string) (1) send_message is added to the event loop, and the calling coroutine gives up control to the event loop, or (2) We jump directly into send_...
Does `await` in Python yield to the event loop?
I was wondering what exactly happens when we await a coroutine in async Python code, for example: await send_message(string) (1) send_message is added to the event loop, and the calling coroutine gives up control to the event loop, or (2) We jump directly into send_message Most explanations I read point to (1), as the...
[ "Disclaimer: Open to correction (particularly as to details and correct terminology) since I arrived here looking for the answer to this myself. Nevertheless, the research below points to a pretty decisive \"main point\" conclusion:\nCorrect OP answer: No, await (per se) does not yield to the event loop, yield yiel...
[ 38, 0 ]
[]
[]
[ "async_await", "asynchronous", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0059586879_async_await_asynchronous_python_python_3.x_python_asyncio.txt
Q: Python freezes on smtplib.SMTP("smtp.gmail.com", 587) I am attempting to create a script that send an email, using Gmail. However, my code freezes when the line below is ran: smtplib.SMTP("smtp.gmail.com", 587) It is before my username and password are entered, so it is nothing to do with my Gmail account. Why is...
Python freezes on smtplib.SMTP("smtp.gmail.com", 587)
I am attempting to create a script that send an email, using Gmail. However, my code freezes when the line below is ran: smtplib.SMTP("smtp.gmail.com", 587) It is before my username and password are entered, so it is nothing to do with my Gmail account. Why is this happening? I am using Python 3.6.3 The full code is b...
[ "It is most likely a firewall or similar issue. On the machine having the issue, try running this on the command line:\nping smtp.gmail.com\n\nAssuming that works, then try:\ntelnet smtp.gmail.com 587\n\nI'm assuming a Linux machine with this command. You'll need to adapt for others. If that connects, type ehlo lis...
[ 6, 4, 3, 0 ]
[]
[]
[ "python", "smtplib" ]
stackoverflow_0050624003_python_smtplib.txt
Q: How to match complete words for acronym using regex? I want to only get complete words from acronyms with ( ) around them. For example, there is a sentence 'Lung cancer screening (LCS) reduces NSCLC mortality'; ->I want to get 'Lung cancer screening' as a result. How can I do it with regex? original question: I w...
How to match complete words for acronym using regex?
I want to only get complete words from acronyms with ( ) around them. For example, there is a sentence 'Lung cancer screening (LCS) reduces NSCLC mortality'; ->I want to get 'Lung cancer screening' as a result. How can I do it with regex? original question: I want to remove repeated upper alphabets : "HIV acquired imm...
[ "Assuming you want to target 2 or more capital letters, I would use re.sub here:\ninp = \"Lung cancer screening (LCS) reduces NSCLC mortality\"\noutput = re.sub(r'\\s*(?:\\([A-Z]+\\)|[A-Z]{2,})\\s*', ' ', inp).strip()\nprint(output) # Lung cancer screening reduces mortality\n\n", "import re\ns = 'HIV acquired im...
[ 0, 0 ]
[]
[]
[ "alphabet", "python", "regex" ]
stackoverflow_0074588659_alphabet_python_regex.txt
Q: Using json_normalize function to create a relational data model? I have a nested Python dictionary that I want to convert into a relational model. I am struggling to parse the dictionary into two related tables: a "workspace" table and a "datasets" table - joined by the key workspace_id simplified_dict ={ "wo...
Using json_normalize function to create a relational data model?
I have a nested Python dictionary that I want to convert into a relational model. I am struggling to parse the dictionary into two related tables: a "workspace" table and a "datasets" table - joined by the key workspace_id simplified_dict ={ "workspaces":[ { "workspace_id":"d507422c", "work...
[ "workspace_df = pd.json_normalize(data=simplified_dict, record_path=[\"workspaces\"]).drop(columns=\"datasets\")\nprint(workspace_df)\n\ndatasets_df = pd.json_normalize(data=simplified_dict[\"workspaces\"], meta=[\"workspace_id\"], record_path=[\"datasets\"])\nprint(datasets_df)\n\nAlternative:\ndatasets_df = pd.js...
[ 2 ]
[]
[]
[ "dictionary", "json_normalize", "jsonparser", "pandas", "python" ]
stackoverflow_0074588672_dictionary_json_normalize_jsonparser_pandas_python.txt
Q: flask-migrate / alembic: How to add a postgresql identity column to an existing table? I’m trying to create a migration to add a new identity column to an existing table. The table should eventually become the new primary key of that table. class Action(db.Model): id = db.Column(db.Integer(), db.Identity(), pr...
flask-migrate / alembic: How to add a postgresql identity column to an existing table?
I’m trying to create a migration to add a new identity column to an existing table. The table should eventually become the new primary key of that table. class Action(db.Model): id = db.Column(db.Integer(), db.Identity(), primary_key=True) # new primary key uuid = db.Column(sqlalchemy_utils.UUIDType, index=Tru...
[ "It seems it was as simple as adding sa.Identity():\ndef upgrade():\n \"\"\"Upgrade from previous version.\"\"\"\n op.add_column(\"actions\", sa.Column(\"id\", sa.Integer(), sa.Identity(), nullable=False))\n\n" ]
[ 0 ]
[]
[]
[ "alembic", "flask_migrate", "postgresql", "python" ]
stackoverflow_0074588719_alembic_flask_migrate_postgresql_python.txt
Q: Remove rows in pandas dataframe after a certain value at max index I have a pandas dataframe with rate look like below: import numpy as np import pandas as pd num = np.repeat(12, 3) num1 = np.repeat(11, 3) num2 = np.repeat(7, 2) num3 = np.repeat(10, 2) num4 = np.repeat(7, 3) num5 = np.repeat(9, 5) num6 = np.repea...
Remove rows in pandas dataframe after a certain value at max index
I have a pandas dataframe with rate look like below: import numpy as np import pandas as pd num = np.repeat(12, 3) num1 = np.repeat(11, 3) num2 = np.repeat(7, 2) num3 = np.repeat(10, 2) num4 = np.repeat(7, 3) num5 = np.repeat(9, 5) num6 = np.repeat(3, 4) num7 = np.repeat(7, 4) df = pd.DataFrame(columns= ['rate']) df[...
[ "Here is one way to do it using Pandas shift method:\n# Setup\nmax_indices = df[(df[\"rate\"] != df[\"rate\"].shift(-1)) & (df[\"rate\"].isin([7, 9]))].index\nindex = df.index.to_list()\nnew_index = []\nstart = 0\n\n# Build new index\nfor idx in max_indices:\n new_index = new_index + index[start: idx + 1]\n s...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074553929_dataframe_pandas_python.txt
Q: How can we get weekly and monthly returns based on daily stock closing prices? All my data is in a dataframe My dataframe originally looks like this. index ticker Adj Close Date 2022-01-03 0 AXP 166.056259 2022-01-04 1 AXP 171.387100 2022-01-05 2 ...
How can we get weekly and monthly returns based on daily stock closing prices? All my data is in a dataframe
My dataframe originally looks like this. index ticker Adj Close Date 2022-01-03 0 AXP 166.056259 2022-01-04 1 AXP 171.387100 2022-01-05 2 AXP 169.560791 2022-01-06 3 AXP 171.114563 2022-01-07 4 AXP 172.579315 Or, if I reset the ...
[ "You can extract the month and the week as separate columns as below, and then you can use groupby with aggregates first and last which will allow you to compute the gain for the whole week (in case you hold the stock)\nimport random\nimport pandas as pd\n\nvalue = random.sample(range(1, 80), 79)\nbegin_date = '201...
[ 1 ]
[]
[]
[ "dataframe", "python", "python_3.x" ]
stackoverflow_0074587121_dataframe_python_python_3.x.txt
Q: Creating and updating data from API answerI to Django REST project (MySQ)? I have a Django REST project. I have a models User, Store and Warehouse. And I have a module with marketplace parser, that gets data from marketplace API. In this module there is a class Market and a method "get_warehouses_list". This metho...
Creating and updating data from API answerI to Django REST project (MySQ)?
I have a Django REST project. I have a models User, Store and Warehouse. And I have a module with marketplace parser, that gets data from marketplace API. In this module there is a class Market and a method "get_warehouses_list". This method returns a JSON with a STORE's warehouse list. Examle answer: { "result": [ { "...
[ "The 400 Error might be caused by a number of reasons. Do you have any logging information you can provide? Either from the Python logs or using the browser developer tools?\nIn your own code you are returning a 400 code if the variable data is empty. Are you sure you are not hitting this validation?\nIf nothing tu...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074588744_django_django_rest_framework_python.txt
Q: Set specific tick lablels while deleting preexisting labels on an axis I need to set a specific tick label on a certain tick position, while deleting preexisting labels. Specifically, The labels on the x axis are dates for the value of a stock, and I want to delete those and set one for each month instead. Date ...
Set specific tick lablels while deleting preexisting labels on an axis
I need to set a specific tick label on a certain tick position, while deleting preexisting labels. Specifically, The labels on the x axis are dates for the value of a stock, and I want to delete those and set one for each month instead. Date Open High Low Close/Price Volume 6/24/2019 86.78 87.11 86.06 ...
[ "How about something like this?\nimport pandas as pd\nimport datetime\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\n\n\ndf = pd.DataFrame({'Date': {0: '6/24/2019', 1: '6/25/2019', 2: '6/26/2019', 3: '6/27/2019', 4: '6/28/2019', 5: '7/1/2019', 6: '7/2/2019', 7: '7/3/2019'}, 'Open': {0: 86.78, ...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074587661_matplotlib_pandas_python.txt
Q: requests.Session() creating different session every time. How to reuse it? I am trying to initialize a requests.Session, to keep a connection with a webpage. However, I read that each time the session class is called, a new session is created. How is it possible to keep the connection alive? Because with my curren...
requests.Session() creating different session every time. How to reuse it?
I am trying to initialize a requests.Session, to keep a connection with a webpage. However, I read that each time the session class is called, a new session is created. How is it possible to keep the connection alive? Because with my current code, it's giving me the webpage content after I call the login method (that's...
[ "The whole point of requests.Session is to persist ephemeral constants (like cookies) between requests. In your code you initialize a new session object, when you initialize a LoginLogout object.\nYou do that here:\nif switch_parameter == \"login\": \n login_var = LoginLogout()\n...\n\nAnd you do that her...
[ 1 ]
[]
[]
[ "python", "request", "session_cookies" ]
stackoverflow_0074588769_python_request_session_cookies.txt
Q: How to get temperature measure given location and time values in a dataframe? I have a pandas dataframe consisting of geo-locations and a time in the past. location_time = pd.read_csv(r'geo_time.csv') print (geo_time) > +---------+---------+---------+-------------------+ | latitude|longitude| altitude| ...
How to get temperature measure given location and time values in a dataframe?
I have a pandas dataframe consisting of geo-locations and a time in the past. location_time = pd.read_csv(r'geo_time.csv') print (geo_time) > +---------+---------+---------+-------------------+ | latitude|longitude| altitude| start| +---------+---------+---------+-------------------+ | 48.2393| ...
[ "With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"latitude\": [48.2393, 35.5426, 49.2466],\n \"longitude\": [11.5713, 139.5975, -123.2214],\n \"altitude\": [520, 5, 5],\n \"start\": [\"2020-03-12 13:00:00\", \"2020-07-31 18:00:00\", \"2020-06-23 11:0...
[ 1 ]
[]
[]
[ "dataframe", "meteostat", "pandas", "python", "weather" ]
stackoverflow_0074549899_dataframe_meteostat_pandas_python_weather.txt
Q: How to achieve this dynamic alloction in Pyspark I have a dataframe store_df :- store ID Div 637 4000000970 Pac 637 4000000435 Pac 637 4000055542 Pac 637 4000042206 Pac 637 4000014114 Pac I have another dataframe final_list :- Div ID Rank Category Pac 4000000970 1 A Pac 4000000432 2 A Pac 4000000405 3 A...
How to achieve this dynamic alloction in Pyspark
I have a dataframe store_df :- store ID Div 637 4000000970 Pac 637 4000000435 Pac 637 4000055542 Pac 637 4000042206 Pac 637 4000014114 Pac I have another dataframe final_list :- Div ID Rank Category Pac 4000000970 1 A Pac 4000000432 2 A Pac 4000000405 3 A Pac 4000042431 4 A Pac 22000...
[ "from pyspark.sql import SparkSession,Row\nfrom pyspark.sql.functions import mean, min, max,count,row_number,lit,udf,col\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import IntegerType\nfrom pyspark.sql.window import Window\n\n# creating the session\nspark = SparkSession.builder.getOrCreate()\n \...
[ 0 ]
[]
[]
[ "azure_databricks", "pyspark", "python" ]
stackoverflow_0074570168_azure_databricks_pyspark_python.txt
Q: I added a proxy to Selenium and now the page won't open [Python] My bot successfully worked on my local network. But by adding proxies as if lost connection to the network... Here's my code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support impor...
I added a proxy to Selenium and now the page won't open [Python]
My bot successfully worked on my local network. But by adding proxies as if lost connection to the network... Here's my code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import B...
[ "Try to change port\nExample: 4444 to 12345 / 55555\n" ]
[ 0 ]
[]
[]
[ "proxy", "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0074206758_proxy_python_python_3.x_selenium_selenium_webdriver.txt
Q: Python Binance Futures - problem creating Take Profit Limit order -> (APIError(code=-2021): Order would immediately trigger.) Trying to write a basic Binance trading bot in python. Keep getting "APIError(code=-2021): Order would immediately trigger" even though it makes no sense when placing a limit order. At the ...
Python Binance Futures - problem creating Take Profit Limit order -> (APIError(code=-2021): Order would immediately trigger.)
Trying to write a basic Binance trading bot in python. Keep getting "APIError(code=-2021): Order would immediately trigger" even though it makes no sense when placing a limit order. At the time of writing this the ETH/BUSD exchange is rate is at about 1210. I printed out my current price (1210.00) and target price (121...
[ "Answering my own question because I figured it out.\nAshamed to admit it but I realized the take profit / stop loss orders are additional separate orders you can send AFTER your first limit/market... order. This means you have to send 2 separate orders to Bianance. If we take a look at my example:\nFirst I send a ...
[ 0 ]
[]
[]
[ "binance", "cryptocurrency", "python", "trading" ]
stackoverflow_0074584665_binance_cryptocurrency_python_trading.txt
Q: Running Python code in parallel from Rust with rust-cpython I'm trying to speed up a data pipeline using Rust. The pipeline contains bits of Python code that I don't want to modify, so I'm trying to run them as-is from Rust using rust-cpython and multiple threads. However, the performance is not what I expected, ...
Running Python code in parallel from Rust with rust-cpython
I'm trying to speed up a data pipeline using Rust. The pipeline contains bits of Python code that I don't want to modify, so I'm trying to run them as-is from Rust using rust-cpython and multiple threads. However, the performance is not what I expected, it's actually the same as running the python code bits sequential...
[ "The CPython implementation of Python does not allow executing Python bytecode in multiple threads at the same time. As you note yourself, the global interpreter lock (GIL) prevents this.\nWe don't have any information on what exactly your Python code is doing, so I'll give a few general hints how you could improve...
[ 2, 0 ]
[]
[]
[ "cpython", "python", "rust" ]
stackoverflow_0060148992_cpython_python_rust.txt
Q: Is there any way to solve "string index out of range" My problem is to count words having alphabet 'a' at second position in a string Eg : banana in a bag o/p banana bag for i in re: if i[1]== 'a': print(i) It was showing index out of range error due to word "a" in a sentence I want output without err...
Is there any way to solve "string index out of range"
My problem is to count words having alphabet 'a' at second position in a string Eg : banana in a bag o/p banana bag for i in re: if i[1]== 'a': print(i) It was showing index out of range error due to word "a" in a sentence I want output without error can anyone solve it?
[ "I think this is what you wanted If i am clear..!\nPlease let me know.!!\nCode:-\nstring=\"banana in a bag\"\nresult=\"\"\nfor word in string.split():\n try: \n if word[1]==\"a\":\n result+=word+\" \"\n except IndexError:\n continue\nprint(result)\n\nOutput:-\nbanana bag\n\n", "we c...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074588792_python.txt
Q: Mysql connector cannot be installed When I try to install MySQL python connector, it installs but at the last step it shows that the directory doesn't have those privileges. What do I do? I try it every alternate day. It should be installed. A: Run the Setup as Administrator
Mysql connector cannot be installed
When I try to install MySQL python connector, it installs but at the last step it shows that the directory doesn't have those privileges. What do I do? I try it every alternate day. It should be installed.
[ "Run the Setup as Administrator\n" ]
[ 0 ]
[]
[]
[ "mysql_connector_python", "python" ]
stackoverflow_0074587927_mysql_connector_python_python.txt
Q: Making an advent calendar on Python I'm trying to create a python script that prints a different statement on every day of December leading up to Christmas. Below is what I've tried so far as a test but it doesn't work :/ from datetime import date today = date.today() nov_27 = 2022-11-27 nov_28 = 2022-11-28 if ...
Making an advent calendar on Python
I'm trying to create a python script that prints a different statement on every day of December leading up to Christmas. Below is what I've tried so far as a test but it doesn't work :/ from datetime import date today = date.today() nov_27 = 2022-11-27 nov_28 = 2022-11-28 if today == nov_27: print("words") elif ...
[ "Observe that\nnov_27 = 2022-11-27\nprint(nov_27)\n\ngives output\n1984\n\nas 2022-11-27 is treated as arithmetic by python, use datetime.date to create date object instance which you can compare with today e.g.\nfrom datetime import date\ntoday = date.today()\nnov_27 = date(2022,11,27)\nnov_28 = date(2022,11,28)\n...
[ 0, 0 ]
[]
[]
[ "datetime", "if_statement", "python" ]
stackoverflow_0074588927_datetime_if_statement_python.txt
Q: My program crashes after i hold the w key to move the turtle for too long in the turtle library The code is as follows: import turtle width = 400 length = 300 wn = turtle.Screen() wn.bgcolor("black") wn.title("x") drawer = turtle.Turtle() drawer.speed(3) drawer.begin_fill() drawer.color("blue", "yellow") def d...
My program crashes after i hold the w key to move the turtle for too long in the turtle library
The code is as follows: import turtle width = 400 length = 300 wn = turtle.Screen() wn.bgcolor("black") wn.title("x") drawer = turtle.Turtle() drawer.speed(3) drawer.begin_fill() drawer.color("blue", "yellow") def drawern(): drawer.seth(90) drawer.fd(1) def drawerw(): drawer.seth(180) drawer.fd(1) ...
[ "I believe the stack overflow error is due to repeated assigning of angle to the stack. To prevent this, you can introduce a debounce. We will name our debounce as move.\nA debounce, in simple terms, is fail-safe to prevent an event for triggering again and again while keeping the rest of the code running.\nDefine ...
[ 0 ]
[]
[]
[ "python", "turtle_graphics" ]
stackoverflow_0074588827_python_turtle_graphics.txt
Q: pandas insert new column based on two column header value I want to add new column to see exam differences in a percentage value. import pandas as pd exam_1 = { 'Name': ['Jonn', 'Tomas', 'Fran', 'Olga', 'Veronika', 'Stephan'], 'Mat': [85, 75, 50, 93, 88, 90], 'Science': [96, 97, 99, 87, 90, 88], 'Reading'...
pandas insert new column based on two column header value
I want to add new column to see exam differences in a percentage value. import pandas as pd exam_1 = { 'Name': ['Jonn', 'Tomas', 'Fran', 'Olga', 'Veronika', 'Stephan'], 'Mat': [85, 75, 50, 93, 88, 90], 'Science': [96, 97, 99, 87, 90, 88], 'Reading': [80, 60, 72, 86, 84, 77], 'Wiritng': [78, 82, 88, 78, 86, 8...
[ "You can start by making a list with every column having the suffixe _2 and then use pandas.DataFrame.insert with pandas.Index.get_loc on a list comprehension to insert the result columns where they should.\nTry this :\nedge_cols= cmp.columns.str.extractall(\"(\\w+_2)\")[0].tolist()\n\n[cmp.insert(cmp.columns.get_l...
[ 1, 0 ]
[]
[]
[ "merge", "pandas", "python", "sorting" ]
stackoverflow_0074588293_merge_pandas_python_sorting.txt
Q: How to fix PyQt6-tools installation error? I want to create my small GUI app with PyQt6. I've installed PyQt6, but I also have to install PyQt6-tools. So, when I tried to get it, I got this error: C:\Users\egorl>pip install pyqt6-tools Collecting pyqt6-tools Using cached pyqt6_tools-6.1.0.3.2-py3-none-any.whl (2...
How to fix PyQt6-tools installation error?
I want to create my small GUI app with PyQt6. I've installed PyQt6, but I also have to install PyQt6-tools. So, when I tried to get it, I got this error: C:\Users\egorl>pip install pyqt6-tools Collecting pyqt6-tools Using cached pyqt6_tools-6.1.0.3.2-py3-none-any.whl (29 kB) Using cached pyqt6_tools-6.0.3.3.2-py3-n...
[ "Had the same errors with python 3.10, but didnt want to give up and revert to older version 3.9\nInstalled the designer seperately from https://build-system.fman.io/qt-designer-download\nIts a small and quick install.\n", "As suggested by eyllanesc, using python3.9 worked out for me.\n<PathToPython3.9>\\python.e...
[ 2, 1, 0 ]
[]
[]
[ "pip", "pyqt", "pyqt6", "python" ]
stackoverflow_0069870103_pip_pyqt_pyqt6_python.txt
Q: How to delete an instantiated object Python? I am relatively new to object oriented programming and I cannot figure out how to delete an instantiated object in Python. if self.hit_paddle(pos) == True or self.hit_paddle2(pos) == True: bar = bar + 1 if bar == 1: global barbox1 barbox1 = barfill(canvas) ...
How to delete an instantiated object Python?
I am relatively new to object oriented programming and I cannot figure out how to delete an instantiated object in Python. if self.hit_paddle(pos) == True or self.hit_paddle2(pos) == True: bar = bar + 1 if bar == 1: global barbox1 barbox1 = barfill(canvas) barbox1.canvas.move(barbox1.id, 253, 367) if ba...
[ "object.__del__(self) is called when the instance is about to be destroyed.\n>>> class Test:\n... def __del__(self):\n... print \"deleted\"\n... \n>>> test = Test()\n>>> del test\ndeleted\n\nObject is not deleted unless all of its references are removed(As quoted by ethan)\nAlso, From Python official do...
[ 66, 26, 0 ]
[]
[]
[ "object", "python", "variables" ]
stackoverflow_0021514631_object_python_variables.txt
Q: How to create a repeating loop in python with sympy, without changing one variable in the loop so basically I have encountered a problem where I have made my loop, but since one of the variables is defined before the actual assignment, the code stops working. the code. Another thing is that I'm working in Spyder, ...
How to create a repeating loop in python with sympy, without changing one variable in the loop
so basically I have encountered a problem where I have made my loop, but since one of the variables is defined before the actual assignment, the code stops working. the code. Another thing is that I'm working in Spyder, and I don't know why, but if I try to code so that the program collect variables initially (which is...
[ "So, here is, in text form, your code (sorry, plagiarism argument is not valid around here)\nq = sympy.Function('q')\nq = sympy.diff(f)\n\ndef main():\n a = sympy.Function('a')\n a = sympy.diff(q)\n j = sympy.function\n j = 1+(1/sympy.factorial(count))*q\n r = sympy.Function('r')\n r = j+(1/sympy....
[ 0 ]
[]
[]
[ "python", "spyder", "sympy" ]
stackoverflow_0074586228_python_spyder_sympy.txt
Q: Pandas numerci column concider as string if NaN is inside I am starting to learn Python and I have an issue with pandas data frame. In R even if numeric columns have NaN values R manages to define the correct type of data in each column. In Pandas this does not seem to be the case: data = { "calories": ["NA", 380,...
Pandas numerci column concider as string if NaN is inside
I am starting to learn Python and I have an issue with pandas data frame. In R even if numeric columns have NaN values R manages to define the correct type of data in each column. In Pandas this does not seem to be the case: data = { "calories": ["NA", 380, 390], "duration": [50, 40, 45] } df = pd.DataFrame(data) df.d...
[ "\"NA\" is a string, use np.nan or float('nan'):\ndata = {\n\"calories\": [float('nan'), 380, 390],\n\"duration\": [50, 40, 45]\n}\n\ndf = pd.DataFrame(data)\nprint(df.dtypes)\n\ncalories float64\nduration int64\ndtype: object\n\nOr:\nimport numpy as np\ndata = {\n\"calories\": [np.nan, 380, 390],\n\"durati...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074589088_pandas_python.txt
Q: entering int or float using input() I need to enter different values to input(), sometimes integer sometime float. My code is number1 = input() number2 = input() Formula = (number1 + 20) * (10 + number2) I know that input() returns a string which is why I need to convert the numbers to float or int. But how can I...
entering int or float using input()
I need to enter different values to input(), sometimes integer sometime float. My code is number1 = input() number2 = input() Formula = (number1 + 20) * (10 + number2) I know that input() returns a string which is why I need to convert the numbers to float or int. But how can I enter a float or integer without using n...
[ "If your inputs are \"sometimes\" ints and \"sometimes\" floats then just wrap each input in a float(). You could make something more complex, but why would you?\n", "You could check for the presence of a decimal point in your string to decide if you want to coerce it into a float or an int.\nnumber = input()\n\n...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0071789343_python.txt
Q: Lauch default editor (like 'webbrowser' module) Is there a simple way to lauch the systems default editor from a Python command-line tool, like the webbrowser module? A: Under windows you can simply "execute" the file and the default action will be taken: os.system('c:/tmp/sample.txt') For this example a defaul...
Lauch default editor (like 'webbrowser' module)
Is there a simple way to lauch the systems default editor from a Python command-line tool, like the webbrowser module?
[ "Under windows you can simply \"execute\" the file and the default action will be taken: \nos.system('c:/tmp/sample.txt')\nFor this example a default editor will spawn. Under UNIX there is an environment variable called EDITOR, so you need to use something like: \nos.system('%s %s' % (os.getenv('EDITOR'), filename)...
[ 18, 4, 3, 2, 0 ]
[]
[]
[ "command_line", "editor", "python" ]
stackoverflow_0001442841_command_line_editor_python.txt
Q: How to call a function in a Django template? I have a function on my views.py file that connects to a mail server and then appends to my Django model the email addresses of the recipients. The script works good. In Django, I'm displaying the model with a table, and I'd like to include a button that says Get Emails...
How to call a function in a Django template?
I have a function on my views.py file that connects to a mail server and then appends to my Django model the email addresses of the recipients. The script works good. In Django, I'm displaying the model with a table, and I'd like to include a button that says Get Emails and runs this function and it then reloads the pa...
[ "Django does not use app-specific urls.py files by default. You must include them in your main urls.py, for example:\nfrom django.urls import include, path\n\nurlpatterns = [\n path('marketing/', SubscriberListView.as_view(), name='marketing'),\n path('myapp/', include('myapp.urls')),\n ...\n]\n\nAssuming ...
[ 1, 0 ]
[]
[]
[ "django", "function", "python", "templates" ]
stackoverflow_0074588972_django_function_python_templates.txt
Q: why after TfidfVectorizer i have X has 24 features, but PassiveAggressiveClassifier is expecting 113905 features as input I'm trying to use TfidfVectorizer on array with one example and use it for model prediction, but after TfidfVectorizer i get: <1x24 sparse matrix of type '<class 'numpy.float64'>' with 24 s...
why after TfidfVectorizer i have X has 24 features, but PassiveAggressiveClassifier is expecting 113905 features as input
I'm trying to use TfidfVectorizer on array with one example and use it for model prediction, but after TfidfVectorizer i get: <1x24 sparse matrix of type '<class 'numpy.float64'>' with 24 stored elements in Compressed Sparse Row format> insted of: 2x113905 like my x_test or x_train, thats what i did: labels=df.Lab...
[ "I found a solution in this stack problem was that I made new vocabulary and my new \"test example\" have had only few characters like that:\nSo i reruned this karnels:\n#DataFlair - Initialize a TfidfVectorizer\ntfidf_vectorizer=TfidfVectorizer(stop_words=my_stopwords_list,smooth_idf=False)\n#DataFlair - Fit and t...
[ 0 ]
[]
[]
[ "python", "tf_idf", "tfidfvectorizer", "vectorization" ]
stackoverflow_0074553178_python_tf_idf_tfidfvectorizer_vectorization.txt
Q: How to edit/delete slash command message after its buttons have been interacted with (discord py disnake api wrapper) here's a mega simple coin flip example i made for this question is there any way to -edit the original slash command message with the result of the coin flip to get rid of the buttons -delete the o...
How to edit/delete slash command message after its buttons have been interacted with (discord py disnake api wrapper)
here's a mega simple coin flip example i made for this question is there any way to -edit the original slash command message with the result of the coin flip to get rid of the buttons -delete the original slash command message class CoinFlipButtons(disnake.ui.View): def __init__(self): super().__init__(timeo...
[ "to edit:\nawait inter.response.edit_message()\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord_buttons", "disnake", "python" ]
stackoverflow_0074577232_discord_discord_buttons_disnake_python.txt
Q: Using rdflib with anzograph I am using the community edition of anzograph. I have no problem using the sparql http protocol, however when I try to use the graph store protocol via rdflib I get a result I don't understand. I am running the docker image from the anzo website and have mapped ports -p 80:8080 443:84...
Using rdflib with anzograph
I am using the community edition of anzograph. I have no problem using the sparql http protocol, however when I try to use the graph store protocol via rdflib I get a result I don't understand. I am running the docker image from the anzo website and have mapped ports -p 80:8080 443:8443 7070:7070. Here is the snippet...
[ "Solved! In spite of what the documentation says, using /sparql (rather than /rdf-graph-store) together with the graph store port of 7070 works. So the correct snippet is:\nimport rdflib\nimport rdflib.plugins.stores.sparqlstore as store\n\nstore = store.SPARQLStore(\"http://192.168.1.104:7070/sparql\")\ngraph = ...
[ 0 ]
[]
[]
[ "anzograph", "graph_databases", "python", "rdflib" ]
stackoverflow_0074588464_anzograph_graph_databases_python_rdflib.txt
Q: How to make a dataframe from a list of tuples, where tuples are the values? I have a time series dataset on which I am running the auto arima model. The dataset has multiple columns that are independent of each other, so basically it's like multiple auto arima analysis. The code I currently have loops through all ...
How to make a dataframe from a list of tuples, where tuples are the values?
I have a time series dataset on which I am running the auto arima model. The dataset has multiple columns that are independent of each other, so basically it's like multiple auto arima analysis. The code I currently have loops through all the columns in the dataframe and stores the order values of p,d,q for each column...
[ "Let's say that:\n\ndf has three columns: \"Col1\", \"Col2\", \"Col3\"\nand autoarima_results == [(1, 1, 0), (2, 1, 1), (1, 1, 1)]\n\nThen, here is one way to do it:\nnew_df = (\n pd.DataFrame(autoarima_results, index=cols)\n .pipe(lambda df_: df_.assign(pdq_values=df_.apply(lambda x: tuple(x), axis=1)))[\n ...
[ 0, 0 ]
[]
[]
[ "arima", "dataframe", "pandas", "python", "tuples" ]
stackoverflow_0074548631_arima_dataframe_pandas_python_tuples.txt
Q: How to update text in pysimplegui I'm very new to python so I'm just experimenting with new GUIs and other things. I was wondering if you could open up a window using pysimplegui and have a piece of text which says "0", and when you click a button the text changes to the previous number +1. For E.G: at first the t...
How to update text in pysimplegui
I'm very new to python so I'm just experimenting with new GUIs and other things. I was wondering if you could open up a window using pysimplegui and have a piece of text which says "0", and when you click a button the text changes to the previous number +1. For E.G: at first the text says "0", but when you click a butt...
[ "Should call method window[element_key].update(value=new_value) to update the element window[element_key] with new value new_value.\nNew layout and new window are not required.\nimport PySimpleGUI as sg\n\nnum = 0\n\nlayout = [\n [sg.Text(num, key='xxx')],\n [sg.Button(\"hi\")],\n]\n\nwindow = sg.Window(\"the...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074578705_python.txt
Q: how to count the number of specific lines between time intervals I have a dataset that contains two columns: time and source and I want to count 192.168.1.128 between each second I have this: Time Source 2022-11-27 09:19:27 192.168.1.128 2022-11-27 09:19:27 152.199.19.161 20...
how to count the number of specific lines between time intervals
I have a dataset that contains two columns: time and source and I want to count 192.168.1.128 between each second I have this: Time Source 2022-11-27 09:19:27 192.168.1.128 2022-11-27 09:19:27 152.199.19.161 2022-11-27 09:19:27 192.168.1.128 2022-11-27 09:19:27 192.168.1...
[ "You could use:\ndf['Source'].eq('192.168.1.128').groupby(df['Time']).count().reset_index()\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074589226_dataframe_pandas_python.txt
Q: How to create abstract properties in python abstract classes In the following code, I create a base abstract class Base. I want all the classes that inherit from Base to provide the name property, so I made this property an @abstractmethod. Then I created a subclass of Base, called Base_1, which is meant to supply...
How to create abstract properties in python abstract classes
In the following code, I create a base abstract class Base. I want all the classes that inherit from Base to provide the name property, so I made this property an @abstractmethod. Then I created a subclass of Base, called Base_1, which is meant to supply some functionality, but still remain abstract. There is no name p...
[ "Since Python 3.3 a bug was fixed meaning the property() decorator is now correctly identified as abstract when applied to an abstract method.\nNote: Order matters, you have to use @property above @abstractmethod\nPython 3.3+: (python docs):\nfrom abc import ABC, abstractmethod\n\nclass C(ABC):\n @property\n ...
[ 255, 57, 10, 5, 3, 0, 0 ]
[]
[]
[ "abstract_class", "decorator", "properties", "python" ]
stackoverflow_0005960337_abstract_class_decorator_properties_python.txt
Q: How to get p-value and pearson's r for a list of columns in Pandas? I'm trying to make a multiindexed table (a matrix) of correlation coefficients and p-values. I'd prefer to use the scipy.stats tests. x = pd.DataFrame( list( zip( [1,2,3,4,5,6], [5, 7, 8, 4, 2, 8], [13, 16, 12, 11, 9, 10] ...
How to get p-value and pearson's r for a list of columns in Pandas?
I'm trying to make a multiindexed table (a matrix) of correlation coefficients and p-values. I'd prefer to use the scipy.stats tests. x = pd.DataFrame( list( zip( [1,2,3,4,5,6], [5, 7, 8, 4, 2, 8], [13, 16, 12, 11, 9, 10] ) ), columns= ['a', 'b', 'c'] ...
[ "Here is one way to do it using scipy pearsonr and Pandas corr methods:\nimport pandas as pd\nfrom scipy.stats import pearsonr\n\ndef pearsonr_pval(x, y):\n return pearsonr(x, y)[1]\n\n\ndf = (\n pd.concat(\n [\n x.corr(method=\"pearson\").reset_index().assign(value=\"r\"),\n x.co...
[ 1 ]
[]
[]
[ "correlation", "pandas", "python", "scipy" ]
stackoverflow_0074537135_correlation_pandas_python_scipy.txt
Q: Why this replace(), re.sub() or strip() do not work with this string? I'm using BeautifulSoup to get a result from a webpage. I've transformed the data object to string and I'm not being able to trim it. I've got the following string: text = '\n\n\n This product is not available.\n \n' I've tried three...
Why this replace(), re.sub() or strip() do not work with this string?
I'm using BeautifulSoup to get a result from a webpage. I've transformed the data object to string and I'm not being able to trim it. I've got the following string: text = '\n\n\n This product is not available.\n \n' I've tried three options to start removing the newline character: string=text.replace('\n'...
[ "Just use .getText(strip=True).\nHere's how:\nimport requests\nfrom bs4 import BeautifulSoup\n\nresp = requests.get('https://soysuper.com/p/granola-con-avena-y-frutos-rojos-kellogg-s-special-k-320-g-320-g', headers={'User-Agent':'Chrome/44.0.2403.157','Accept-Language': 'es-ES, es;q=0.5'})\nsoup = BeautifulSoup(res...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "replace", "strip", "trim" ]
stackoverflow_0074589213_beautifulsoup_python_replace_strip_trim.txt
Q: Why am i getting this error when i am trying to install pygame through cmd and pip? Microsoft Windows [Version 10.0.19044.2251] (c) Microsoft Corporation. All rights reserved. C:\Users\User>py -3.10 -m pip install pygame Collecting pygame Using cached pygame-2.1.2.tar.gz (10.1 MB) Preparing metadata (setup.py...
Why am i getting this error when i am trying to install pygame through cmd and pip?
Microsoft Windows [Version 10.0.19044.2251] (c) Microsoft Corporation. All rights reserved. C:\Users\User>py -3.10 -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 r...
[]
[]
[ "just run this command its installs the pygame command on windows\npip install pygame\n\n" ]
[ -1 ]
[ "pygame", "python", "windows" ]
stackoverflow_0074589224_pygame_python_windows.txt
Q: can't install ta-lib on amazon sagemaker I can't manage to install TA-LIB on amazon sage maker; the error is very weird: Making install in src /bin/sh: line 17: cd: src: Not a directory make: *** [install-recursive] Error 1 bash-4.2$ ./configure checking for a BSD-compatible install... /usr/bin/install -c check...
can't install ta-lib on amazon sagemaker
I can't manage to install TA-LIB on amazon sage maker; the error is very weird: Making install in src /bin/sh: line 17: cd: src: Not a directory make: *** [install-recursive] Error 1 bash-4.2$ ./configure checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes c...
[ "As was discussed at TA-Lib's python wrapper project's issue pages one may install ta-lib to the folder that's allowed for writing with current user permissions:\nmkdir ~/ta-lib-bin\n./configure --prefix=~/ta-lib-bin\nmake\nmake install\n\nAnd then instruct the wrapper to search for TA-Lib headers and binaries in t...
[ 1, 0 ]
[]
[]
[ "amazon", "python", "ta_lib" ]
stackoverflow_0070448069_amazon_python_ta_lib.txt
Q: Convert string into datetime.time object Given the string in this format "HH:MM", for example "03:55", that represents 3 hours and 55 minutes. I want to convert it to datetime.time object for easier manipulation. What would be the easiest way to do that? A: Use datetime.datetime.strptime() and call .time() on th...
Convert string into datetime.time object
Given the string in this format "HH:MM", for example "03:55", that represents 3 hours and 55 minutes. I want to convert it to datetime.time object for easier manipulation. What would be the easiest way to do that?
[ "Use datetime.datetime.strptime() and call .time() on the result:\n>>> datetime.datetime.strptime('03:55', '%H:%M').time()\ndatetime.time(3, 55)\n\nThe first argument to .strptime() is the string to parse, the second is the expected format.\n", ">>> datetime.time(*map(int, '03:55'.split(':')))\ndatetime.time(3, 5...
[ 152, 17, 2, 0 ]
[]
[]
[ "python", "python_datetime", "time" ]
stackoverflow_0014295673_python_python_datetime_time.txt
Q: 'int' does not uspport indexing I am trying to make a loop for a string that contains 16 numbers, idea is to multiply *2 all the pair digits, but while doing that, I get an error of a string. I tried several ways but not succeeding. cardNumber = input("Enter a 16-digit card number:") cardNumber = int(cardNumber.re...
'int' does not uspport indexing
I am trying to make a loop for a string that contains 16 numbers, idea is to multiply *2 all the pair digits, but while doing that, I get an error of a string. I tried several ways but not succeeding. cardNumber = input("Enter a 16-digit card number:") cardNumber = int(cardNumber.replace(" ","")) #cardNumber = str(card...
[ "You convert cardnumber to an integer, e.g. 4137894711755904. Integers do not have a \"digit position\", thus cardNumber[i] cannot work. This indexing works on strings, but not on number types.\nYou could convert the string to a list of integers, e.g.\ncard_number= input(\"Enter a 16-digit card number:\")\ndigits =...
[ 1, 1 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0074589198_integer_python_string.txt
Q: MicroPython on Wemos D1 esp8266:- TypeError: can't convert Pin to int Code: from machine import Pin from machine import ADC from time import sleep_ms x = ADC(Pin(4, Pin.IN)) y = ADC(Pin(5, Pin.IN)) x.atten(ADC.ATTN_11DB) y.atten(ADC.ATTN_11DB) while True: x_val = x.read() y_val = y.read() print('Curr...
MicroPython on Wemos D1 esp8266:- TypeError: can't convert Pin to int
Code: from machine import Pin from machine import ADC from time import sleep_ms x = ADC(Pin(4, Pin.IN)) y = ADC(Pin(5, Pin.IN)) x.atten(ADC.ATTN_11DB) y.atten(ADC.ATTN_11DB) while True: x_val = x.read() y_val = y.read() print('Current position:{},{}'.format(x_val,y_val)) sleep_ms(300) Error: Tracebac...
[ "The TypeError means you are using an object (a variable) of a different type then expected. The error tells you that, in this case, on line 5, an int is expected, but a Pin was used in your code.\nLine 5 of your code is:\nx = ADC(Pin(4, Pin.IN))\n\nand it contains a Pin indeed.\nLooking into the documentation of t...
[ 2 ]
[]
[]
[ "esp8266", "micropython", "python", "typeerror" ]
stackoverflow_0074589133_esp8266_micropython_python_typeerror.txt
Q: How i understanding AD9833 SPI communication using Python with my raspberry? Hi i had an issue to discuss, and i dont realy understand to send data with SPI with Python I want to send data with my Raspberry Pi 4 ver.b using Python to send data to my module named AD9833 DDS. So i found code in internet, writed in ...
How i understanding AD9833 SPI communication using Python with my raspberry?
Hi i had an issue to discuss, and i dont realy understand to send data with SPI with Python I want to send data with my Raspberry Pi 4 ver.b using Python to send data to my module named AD9833 DDS. So i found code in internet, writed in Python (sor. https://ez.analog.com/dds/f/q-a/28431/ad9833-programming-in-raspberry...
[ "This problem can be split into a number of sub tasks.\n\nValues to send\nSequence values sent in\nHow values sent over SPI\n\nAs SamMaster pointed out there is an application note from Analog Devices that shows the sequence of values to send to set the frequency to 400 Hz\nhttps://www.analog.com/media/en/technical...
[ 0 ]
[]
[]
[ "interface", "python", "raspberry_pi", "spidev" ]
stackoverflow_0074545102_interface_python_raspberry_pi_spidev.txt
Q: Morse Code Translator - Calling a function within an if statement using Python `I'm trying to write code that starts with a question asking the user if they want to encode or decode to/from morse. Based on their response (1 or 2), it runs through an if statement, and will call the required function(s). It will tak...
Morse Code Translator - Calling a function within an if statement using Python
`I'm trying to write code that starts with a question asking the user if they want to encode or decode to/from morse. Based on their response (1 or 2), it runs through an if statement, and will call the required function(s). It will take a user's input via user_input() and either return it in morse code, or return it i...
[ "The function decode_morse() is defined twice: one with a parameter, and one without. Try to change the names of the functions.\n", "I managed to figure it out - I needed to print the results of the decode_morse() function and remove 'return results.lower()' as this stopped the print from executing. The correct c...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074588893_python_python_3.x.txt
Q: I have problem adding String with Interger I tried everything I could but somehow it still doesnt work can anyone help? A: Properly write number_one as below: on line one, it should look like this: number_one = int(input("Type number ")) Your print statements are having wrong concatenation, you can't add a str...
I have problem adding String with Interger
I tried everything I could but somehow it still doesnt work can anyone help?
[ "Properly write number_one as below:\non line one, it should look like this:\nnumber_one = int(input(\"Type number \"))\n\nYour print statements are having wrong concatenation, you can't add a str to an int so I recommend using f-string or changing the first + in all the print statements to ,. For example:\nprint(...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074589331_python.txt
Q: How to get class name in python playwright? How to get a Class name using playwright and pyton? I tried that but without success. It could also be the color that is contained in the css page.locator('xpath=//*[@id="__next"]/div[1]/div/div[2]/div[1]/div[1]/div/div[1]').Class() A: Try this: page.locator('xpath=//*...
How to get class name in python playwright?
How to get a Class name using playwright and pyton? I tried that but without success. It could also be the color that is contained in the css page.locator('xpath=//*[@id="__next"]/div[1]/div/div[2]/div[1]/div[1]/div/div[1]').Class()
[ "Try this:\npage.locator('xpath=//*[@id=\"__next\"]/div[1]/div/div[2]/div[1]/div[1]/div/div[1]').get_attribute(\"class\")\n\nWith method get_attribute you can get any attribute from your html element.\n" ]
[ 0 ]
[]
[]
[ "playwright_python", "python", "web_scraping" ]
stackoverflow_0074586465_playwright_python_python_web_scraping.txt
Q: Convert string to hexadecimal with python How to change a string to hexadecimal with Python? For example I would like to do string "a2" -> 0xa2 And through this, I want to satisfy the following formula 0x12 ^ 0xa2 = 0xb0 A: There are 2 methods to get hexadecimal value of string: Method 1 str = '0xa2' convert_str...
Convert string to hexadecimal with python
How to change a string to hexadecimal with Python? For example I would like to do string "a2" -> 0xa2 And through this, I want to satisfy the following formula 0x12 ^ 0xa2 = 0xb0
[ "There are 2 methods to get hexadecimal value of string:\nMethod 1\nstr = '0xa2'\nconvert_str = int(str, base=16)\nhex_value = hex(convert_str)\n\nMethod 2\nfrom ast import literal_eval\nstr = '0xa2'\nconvert_str = literal_eval(str)\nhex_value = hex(convert_str)\n\nOutput:\n0xa2\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074589254_python.txt
Q: What is a floating number and its purpose in terms of theory I am just learning python and making a calculator and the tutorial says float instead of int. what is a floating number Why not just use int A: A float is a number with numbers after decimal points, for example 12.56 . It can also be called a real. An ...
What is a floating number and its purpose in terms of theory
I am just learning python and making a calculator and the tutorial says float instead of int. what is a floating number Why not just use int
[ "A float is a number with numbers after decimal points, for example 12.56 . It can also be called a real.\nAn integer is a whole number eg 12.\nIf you use an integer in a calculator, then you wouldn't be able to calculate with anything other than whole numbers.\nfor example using int is fine if you do 12 + 12. Howe...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074589392_python.txt
Q: Selenium WebDriver Unable to Find ChromeDriver Recently I've been trying to do some webscraping, however I am utterly unable to run Selenium's webdriver. I am trying to run this basic boilerplate code: import pandas as pd import requests from bs4 import BeautifulSoup from selenium import webdriver import time web...
Selenium WebDriver Unable to Find ChromeDriver
Recently I've been trying to do some webscraping, however I am utterly unable to run Selenium's webdriver. I am trying to run this basic boilerplate code: import pandas as pd import requests from bs4 import BeautifulSoup from selenium import webdriver import time web = webdriver.Chrome(service_args=["--verbose", "--lo...
[ "You can try the other option of importing the Chromedriver through webdriver_manager like this:\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nservice = ChromeService(executable_path=ChromeDriverManager().install())\ndriver = webdriver.Chrome(service=service)\n\n", "Have you install the libraries, ...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074589046_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How to prevent unwanted Matplotlib y-axis minor tick labels in log log plot (and keep x-axis minor ticks) In Matplotlib, a log-log plot generates unwanted y-axis tick labels for the minor ticks. I tried this code, which specifies the (major) y-axis ticks to be [1,1.2,1.4,1.6] and expecting that any y-axis minor ti...
How to prevent unwanted Matplotlib y-axis minor tick labels in log log plot (and keep x-axis minor ticks)
In Matplotlib, a log-log plot generates unwanted y-axis tick labels for the minor ticks. I tried this code, which specifies the (major) y-axis ticks to be [1,1.2,1.4,1.6] and expecting that any y-axis minor ticks will have no labels. # imports import numpy as np from matplotlib import pyplot as plt # data x = np.linsp...
[ "To disable the minor ticks of a log plot in matplotlib, we can use minorticks_off() method.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074589426_matplotlib_python.txt
Q: How to get percentage difference between two columns of different DataFrames? There are 2 DataFrames with coin pairs and float prices. Need to make new DataFrame with coin pairs and the price difference as a percentage. First DataFrame in txt Second DataFrame in txt I tried this function, it didn't work def get_di...
How to get percentage difference between two columns of different DataFrames?
There are 2 DataFrames with coin pairs and float prices. Need to make new DataFrame with coin pairs and the price difference as a percentage. First DataFrame in txt Second DataFrame in txt I tried this function, it didn't work def get_diff(): for i in df2['askPrice']: for x in df3['Low price']: ...
[ "Let's put the desired calcultaions in a new list then transform it into a column within df3\ndiff = [((y-x)/x)*100 for (y, x) in zip(df2['askPrice'],df3['Low price'])] \n\ndf3['diff'] = diff\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074589377_dataframe_pandas_python.txt
Q: requests_html render (async) not working on AWS Lambda Read-only file system I have a Python script that scrapes data from a webpage. It works on my local but not on AWS Lambda because it only allows writes new file to /tmp directory. I tried to go through request_html render API and it seems like it's not possibl...
requests_html render (async) not working on AWS Lambda Read-only file system
I have a Python script that scrapes data from a webpage. It works on my local but not on AWS Lambda because it only allows writes new file to /tmp directory. I tried to go through request_html render API and it seems like it's not possible to change the file location. It default take current working directory by defaul...
[ "How's set an environment variable below from lambda web UI?\nPYPPETEER_HOME=/tmp/\n\nIt may change working directory of pyppeteer (a module running inside request_html).\nmaybe, it's a related question: Pyppeteer fails to download headless chrome when running on AWS Lambda\n" ]
[ 0 ]
[]
[]
[ "aws_lambda", "python", "python_requests_html" ]
stackoverflow_0074011801_aws_lambda_python_python_requests_html.txt
Q: Why format string throws error on list but not tuple Why does passing a list to the following format method fail, but passing the same list, coerced to a tuple run without errors? From my test, the tuple is not (multiply) inheriting from Python's atomic numeric types (I assume not complex either) so overall I'm co...
Why format string throws error on list but not tuple
Why does passing a list to the following format method fail, but passing the same list, coerced to a tuple run without errors? From my test, the tuple is not (multiply) inheriting from Python's atomic numeric types (I assume not complex either) so overall I'm confused by what the interpreter is telling me, and why it c...
[ "This is just how format % values works; as documented in the manual:\n\nIf format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).\n\n(See: ...
[ 2 ]
[]
[]
[ "python", "string", "tuples" ]
stackoverflow_0074589435_python_string_tuples.txt
Q: Convert python script which runs a bash script to executable file with Pyinstaller I want to convert a python script which runs a local bash script to executable file with Pyinstaller. My project structure is as following: Project/ |-- bash_script/ | |-- script.sh |-- main.py The main.py contains a line which r...
Convert python script which runs a bash script to executable file with Pyinstaller
I want to convert a python script which runs a local bash script to executable file with Pyinstaller. My project structure is as following: Project/ |-- bash_script/ | |-- script.sh |-- main.py The main.py contains a line which runs the script locally: output = subprocess.check_output('./bash_script/script.sh', shel...
[ "In your main.py:\nimport subprocess\nimport os\n\nscript = os.path.join(os.path.dirname(__file__),'bash_script','script.sh')\noutput = subprocess.check_output(script, shell=True).decode()\nprint(output)\n\nThen run:\npyinstaller -F --add-data ./bash_script/script.sh:./bash_script main.py\n\nAnd bobs your uncle!\np...
[ 1 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0074588616_pyinstaller_python.txt
Q: zsh: command not found: django-admin when starting a django project I use Ubuntu 15.10 and zsh (don't know if it can help) So I try to install django: pip install django Downloading/unpacking django Downloading Django-1.9.5-py2.py3-none-any.whl (6.6MB): 6.6MB downloaded Installing collected packages: django Succ...
zsh: command not found: django-admin when starting a django project
I use Ubuntu 15.10 and zsh (don't know if it can help) So I try to install django: pip install django Downloading/unpacking django Downloading Django-1.9.5-py2.py3-none-any.whl (6.6MB): 6.6MB downloaded Installing collected packages: django Successfully installed django Cleaning up... Everything works fine. When I d...
[ "I found an alternative solution.\nWith find / -name django-admin I found django-admin in myHome/.local/bin/django-admin.\nSo instead of django-admin startproject mysite I use the full path myHome/.local/bin/django-admin startproject mysite\nthanks to @Evert, this is why I got the problem.\nhis comment:\nThis is li...
[ 9, 6, 4, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "pip", "python", "ubuntu_15.10" ]
stackoverflow_0036446599_django_pip_python_ubuntu_15.10.txt
Q: Compute the greatest common divisor and least common multiple of two integers I need to write a Python program in which the user enters two numbers and receives the LCM and HCF of those numbers. I tried it, and my LCM was correct, but my HCF was not, so could anyone assist me in locating the HCF? Thank you! num1 =...
Compute the greatest common divisor and least common multiple of two integers
I need to write a Python program in which the user enters two numbers and receives the LCM and HCF of those numbers. I tried it, and my LCM was correct, but my HCF was not, so could anyone assist me in locating the HCF? Thank you! num1 = int(input('Enter your first number: ')) num2 = int(input('Enter your second number...
[ "You can use Euclidian algorithm if you want to find greatest common divisor or in your terms highest common factor (HCF): here is the link to the article in FreeCodeCamp.org\nHere is the code you can use for python for your case:\n\"\"\" \nfinding HCF\n\"\"\"\n\ndef hcfLoop(x : int, y : int) -> int:\n \"\"\" ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074589299_python.txt
Q: Python Selenium using loop to check keywords keywords = ['no stock','out of stock','not available'] n = 0 while True: n+=1 print(f'now check {n} times') for keyword in keywords: if keyword in driver.page_source: print(f'found {keyword}, refresh after 30 seconds') time....
Python Selenium using loop to check keywords
keywords = ['no stock','out of stock','not available'] n = 0 while True: n+=1 print(f'now check {n} times') for keyword in keywords: if keyword in driver.page_source: print(f'found {keyword}, refresh after 30 seconds') time.sleep(30) driver.get(url) else...
[ "Maybe is this the logic you are looking for?\nkeywords = ['no stock','out of stock','not available']\n\nn = 0\nwhile True:\n n+=1\n print(f'now check {n} times')\n keywords_found = 0\n for keyword in keywords:\n if keyword in driver.page_source:\n keywords_found += 1\n prin...
[ 0 ]
[]
[]
[ "loops", "python", "selenium" ]
stackoverflow_0074589110_loops_python_selenium.txt
Q: Subtracting more than 2 numbers in Python I am little bit new to the programming. I am learning Python, version 3.6. print("1.+ \n2.-\n3.*\n4./") choice = int(input()) if choice == 1: sum = 0 print("How many numbers you want to sum?") numb = int(input()) for i in range(numb): a = int(input(...
Subtracting more than 2 numbers in Python
I am little bit new to the programming. I am learning Python, version 3.6. print("1.+ \n2.-\n3.*\n4./") choice = int(input()) if choice == 1: sum = 0 print("How many numbers you want to sum?") numb = int(input()) for i in range(numb): a = int(input(str(i+1)+". number ")) sum+=a print...
[ "You can do the exact same thing you're already doing. Python has -=, *=, and /= operators that work the same way as the += you're already using.\n", "You can also use the *args or *kargs in order to subtract more than two numbers. If you define *args keyword in a function then it will help you to take as many va...
[ 2, 1, 0 ]
[]
[]
[ "calculator", "python" ]
stackoverflow_0048816636_calculator_python.txt
Q: Create an integer timestamp that corresponds to a Pandas Timestamp's timezone Suppose we have a dataset with a UNIX timestamp in milliseconds: data = [ { "unix_ts": 1669291200000, "val": 10 }, { "unix_ts": 1669291260000, "val": 25 } ] Which we convert to a Pandas datafram...
Create an integer timestamp that corresponds to a Pandas Timestamp's timezone
Suppose we have a dataset with a UNIX timestamp in milliseconds: data = [ { "unix_ts": 1669291200000, "val": 10 }, { "unix_ts": 1669291260000, "val": 25 } ] Which we convert to a Pandas dataframe with a Pandas timestamp (datetime) set to US/Eastern: df = pd.DataFrame(data) df[...
[ "Here's a way to implement this by localizing to None, as I've described in the comments.\nimport pandas as pd\n\ndf = pd.DataFrame({\"unix_ts\": [1651363200000, 1669291260000],\n \"val\": [10, 25]})\n\ndf[\"ET\"] = pd.to_datetime(df[\"unix_ts\"], unit='ms', utc=True).dt.tz_convert(\"America/New_Y...
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python", "unix_timestamp" ]
stackoverflow_0074576268_dataframe_datetime_pandas_python_unix_timestamp.txt
Q: Selenium web scraping project I am new to using selenium. I previously wrote a scrapper using Beautiful Soup and it was working fine until I ran into "accept cookie". enter image description here I attempted to use Selenium to click on the "X" button, and then I wanted to pass the page_source to Beautifulsoup to r...
Selenium web scraping project
I am new to using selenium. I previously wrote a scrapper using Beautiful Soup and it was working fine until I ran into "accept cookie". enter image description here I attempted to use Selenium to click on the "X" button, and then I wanted to pass the page_source to Beautifulsoup to reuse my previous script. But my sou...
[ "\nBut my soup is still showing the page with the \"accept cookie\", resulting in none of the class to be able to be found\n\nBut the listings should show up even without closing cookies notice, and the part of your code to close the cookies notice looks fine anyway (maybe refreshing brings it back....?)\n\nYou mig...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074588641_beautifulsoup_python_selenium_web_scraping.txt
Q: TimeoutError: [WinError 10060] A connection attempt failed : Except block doesn't execute either In my program i have a try and except block like so try: if exitCritera(ceLiveprc,peLiveprc,ceEntry,peEntry): closeAllOpenAndPendingTrades(cTok,pTok,ceEntry,peEntry) except(TimeoutError) as e: print("Ti...
TimeoutError: [WinError 10060] A connection attempt failed : Except block doesn't execute either
In my program i have a try and except block like so try: if exitCritera(ceLiveprc,peLiveprc,ceEntry,peEntry): closeAllOpenAndPendingTrades(cTok,pTok,ceEntry,peEntry) except(TimeoutError) as e: print("Timeout error occured re-trying...:{}".format(datetime.now())) time.sleep(1) if exitCritera(ceLi...
[ "[WinError 10060] is a Windows Socket Error. Try catching it as an OSError, that worked for me in a very similar case.\nChange your code to the following:\ntry:\n if exitCritera(ceLiveprc,peLiveprc,ceEntry,peEntry):\n closeAllOpenAndPendingTrades(cTok,pTok,ceEntry,peEntry)\nexcept OSError as e:\n print...
[ 1 ]
[]
[]
[ "python", "python_requests", "timeoutexception" ]
stackoverflow_0072267807_python_python_requests_timeoutexception.txt
Q: splitting a text by a capital letter after a small letter, without loosing the small letter I have the following type of strings: "CanadaUnited States", "GermanyEnglandSpain" I want to split them into the countries' names, i.e.: ['Canada', 'United States'] ['Germany', 'England', 'Spain'] I have tried using the fol...
splitting a text by a capital letter after a small letter, without loosing the small letter
I have the following type of strings: "CanadaUnited States", "GermanyEnglandSpain" I want to split them into the countries' names, i.e.: ['Canada', 'United States'] ['Germany', 'England', 'Spain'] I have tried using the following regex: text = "GermanyEnglandSpain" re.split('[a-z](?=[A-Z])', text) and I'm getting: ['G...
[ "I would use re.findall here with a regex find all approach:\ninp = \"CanadaUnited States\"\ncountries = re.findall(r'[A-Z][a-z]+(?: [A-Z][a-z]+)*', inp)\nprint(countries) # ['Canada', 'United States']\n\nThe regex pattern used here says to match:\n\n[A-Z][a-z]+ match a leading uppercase word of a country name\n(?...
[ 2, 2, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0074589171_python_regex_string.txt
Q: What is the Python equivalent of Matlab's tic and toc functions? What is the Python equivalent of Matlab's tic and toc functions? A: Apart from timeit which ThiefMaster mentioned, a simple way to do it is just (after importing time): t = time.time() # do stuff elapsed = time.time() - t I have a helper class I l...
What is the Python equivalent of Matlab's tic and toc functions?
What is the Python equivalent of Matlab's tic and toc functions?
[ "Apart from timeit which ThiefMaster mentioned, a simple way to do it is just (after importing time):\nt = time.time()\n# do stuff\nelapsed = time.time() - t\n\nI have a helper class I like to use:\nclass Timer(object):\n def __init__(self, name=None):\n self.name = name\n\n def __enter__(self):\n ...
[ 224, 50, 23, 18, 14, 8, 5, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "matlab", "python", "timing" ]
stackoverflow_0005849800_matlab_python_timing.txt
Q: How i can calulate the sum from a csv file in python? Hy guys i have one problem with the python. I just start to learn and my teacher has give me the task with the python. So the problre is how i can calulate the sum from a column in csv file in pyhon. Here is my tries : import pandas as pd df = pd.read_csv('1.c...
How i can calulate the sum from a csv file in python?
Hy guys i have one problem with the python. I just start to learn and my teacher has give me the task with the python. So the problre is how i can calulate the sum from a column in csv file in pyhon. Here is my tries : import pandas as pd df = pd.read_csv('1.csv') dfsum=sum(df) print(dfsum) My termial is compley for...
[ "\nSo I dont know if your csv file contains only negative number or it's juste the way you present it, but what i can say is that you can try this it gonna work eitherway :\ndf = pd.read_csv(\"1.csv\", names=[\"my_column\"])\ndfsum = df[\"my_column\"].sum()\n\nassuming you have all negative numbers the result is : ...
[ 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074589475_csv_python.txt
Q: webscraping returns not full info learning webscraping at the moment and decided to scrap telegram's web version so i choosed one of the chats (favorite one with yourself) and sent few voices there. My task is - i want to exract all voices lenght when i inspect page there is a div container <div class="audio-time"...
webscraping returns not full info
learning webscraping at the moment and decided to scrap telegram's web version so i choosed one of the chats (favorite one with yourself) and sent few voices there. My task is - i want to exract all voices lenght when i inspect page there is a div container <div class="audio-time">0:00</div> telegramURL = 'https://web....
[ "The problem is not the parser, it's beautiful soup itself. Last time I've used it can only do static scraping which means it only returns the html to traverse the DOM and if it had any scripts in it wouldn't load.\nStatic scraping ignores JavaScript.\nYou have to switch to Selenium with a chrome webdriver. It has ...
[ 0 ]
[]
[]
[ "python", "telegram", "web_scraping" ]
stackoverflow_0074589410_python_telegram_web_scraping.txt
Q: i cant count the full list bot discord python I'm trying to count the entire embed list but it always shows me the same number... should appear 1 2 3 4 ... I don't know how to solve this problem this is the code @bot.command() async def habbo(ctx): response = requests.get("https://images.habbo.com/habbo-web-l...
i cant count the full list bot discord python
I'm trying to count the entire embed list but it always shows me the same number... should appear 1 2 3 4 ... I don't know how to solve this problem this is the code @bot.command() async def habbo(ctx): response = requests.get("https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json") ...
[ "This should work. I just removed the .join() function and created the appending with a loop instead.\n@bot.command()\nasync def habbo(ctx):\n response = requests.get(\"https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json\")\n data = response.json()\n \n count = 0\n co...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074589140_python.txt
Q: Could not find function xmlCheckVersion in library libxml2 while executing pip install uspto-opendata-python I have conda xml2 installed. However, when I execute pip install uspto-opendata-python, I get the following message could not find function xmlCheckVersion in library libxml2. is libxml2 installed? I noti...
Could not find function xmlCheckVersion in library libxml2 while executing pip install uspto-opendata-python
I have conda xml2 installed. However, when I execute pip install uspto-opendata-python, I get the following message could not find function xmlCheckVersion in library libxml2. is libxml2 installed? I noticed a similar question here - Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? - ...
[ "I encountered the same error. You must download the file from\nArchived: Unofficial Windows Binaries for Python Extension Packages, then install it like this on Windows:\npip install C:\\Users\\USER\\Downloads\\lxml-4.9.0-cp311-cp311-win_amd64.whl\n" ]
[ 0 ]
[]
[]
[ "libxml2", "python" ]
stackoverflow_0072550326_libxml2_python.txt
Q: python, itertools: 'list' object is not callable I'm trying to run this function but I got the error: TypeError: 'list' object is not callable import itertools def get_all_pair_combinations(list): return list(itertools.combinations(list, 2)) pair_indexes = get_all_pair_combinations(list(range(len(feature...
python, itertools: 'list' object is not callable
I'm trying to run this function but I got the error: TypeError: 'list' object is not callable import itertools def get_all_pair_combinations(list): return list(itertools.combinations(list, 2)) pair_indexes = get_all_pair_combinations(list(range(len(features_vectors[0])))) the features_vectors[0] that is call...
[]
[]
[ "you can't pass list to a function, read about map function!\n" ]
[ -3 ]
[ "pandas", "python", "python_itertools" ]
stackoverflow_0074589578_pandas_python_python_itertools.txt
Q: How to transform a Pandas Dataframe with irregular coordinates into a xarray Dataset I'm working with a pandas Dataframe on python, but in order to plot as a map my data I have to transform it into a xarray Dataset, since the library I'm using to plot (salem) works best for this class. The problem I'm having is th...
How to transform a Pandas Dataframe with irregular coordinates into a xarray Dataset
I'm working with a pandas Dataframe on python, but in order to plot as a map my data I have to transform it into a xarray Dataset, since the library I'm using to plot (salem) works best for this class. The problem I'm having is that the grid of my data isn't regular so I can't seem to be able to create the Dataset. My ...
[ "If you really require a rectangularly gridded dataset you need to resample your data into a regular grid... (rasterio, pyresample etc. provide useful functionalities for that). However if you just want to plot the data, this is not necessary!\nNot sure about salem (never used it so far), but I've tried my best to...
[ 1 ]
[]
[]
[ "dataset", "pandas", "python", "python_xarray" ]
stackoverflow_0074561493_dataset_pandas_python_python_xarray.txt
Q: "Exception has occurred: TclError unknown option" I am making memory match on pyhton but I keep getting this error: "Exception has occurred: TclError unknown option" Here's the code. Any ideas? import random import time from tkinter import * from PIL import Image, ImageTk from turtle import * def show_symbol(x, y...
"Exception has occurred: TclError unknown option"
I am making memory match on pyhton but I keep getting this error: "Exception has occurred: TclError unknown option" Here's the code. Any ideas? import random import time from tkinter import * from PIL import Image, ImageTk from turtle import * def show_symbol(x, y): global first global previousX, previousY ...
[ "Your line:\nbutton = Button(command=lambda x=x, y=y: show_symbol(x, y), window_height=3 window_width=3)\n\nhas multiple related problems; the options window_height and window_width are simply unknown to the widget, as the error message says. Did you mean height and width, respectively?\n" ]
[ 1 ]
[]
[]
[ "python", "tcl", "tkinter" ]
stackoverflow_0074585943_python_tcl_tkinter.txt
Q: re.sub(".*", ", "(replacement)", "text") doubles replacement on Python 3.7 On Python 3.7 (tested on Windows 64 bits), the replacement of a string using the RegEx .* gives the input string repeated twice! On Python 3.7.2: >>> import re >>> re.sub(".*", "(replacement)", "sample text") '(replacement)(replacement)' O...
re.sub(".*", ", "(replacement)", "text") doubles replacement on Python 3.7
On Python 3.7 (tested on Windows 64 bits), the replacement of a string using the RegEx .* gives the input string repeated twice! On Python 3.7.2: >>> import re >>> re.sub(".*", "(replacement)", "sample text") '(replacement)(replacement)' On Python 3.6.4: >>> import re >>> re.sub(".*", "(replacement)", "sample text") '...
[ "This is not a bug, but a bug fix in Python 3.7 from the commit fbb490fd2f38bd817d99c20c05121ad0168a38ee.\nIn regex, a non-zero-width match moves the pointer position to the end of the match, so that the next assertion, zero-width or not, can continue to match from the position following the match. So in your examp...
[ 20, 0 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0054713570_python_python_re.txt
Q: What's pylint's TypeVar name specification? Pylint gives a warning whenever something like this happens: import typing SEQ_FR = typing.TypeVar("SEQ_FR") #^^^^^ gets underlined with the warning The warning is like this: Type variable name "SEQ_FR" doesn't conform to predefined naming style. pylint(invalid-name) I...
What's pylint's TypeVar name specification?
Pylint gives a warning whenever something like this happens: import typing SEQ_FR = typing.TypeVar("SEQ_FR") #^^^^^ gets underlined with the warning The warning is like this: Type variable name "SEQ_FR" doesn't conform to predefined naming style. pylint(invalid-name) I tried searching through Pylint's documentations ...
[ "You can find the rule used in the Pylint messages documentation; this error is named invalid-name, so the specific documentation can be found on the invalid-name / C0103 page, which has a TypeVar rule in the Predefined Naming Patterns section:\n\nName type: typevar\nGood Names: T, _CallableT, _T_co, AnyStr, Device...
[ 9 ]
[]
[]
[ "pylint", "python", "vscode_python" ]
stackoverflow_0074589610_pylint_python_vscode_python.txt
Q: error while working with fbprophet model using cutoffs I am facing an issue while trying to work with fbprophet cross_valisation using cutoffs tying to see the results for the last 7 months. My data is ranging from 2017-01-01 to 2022-07-01 df_cv2 = cross_validation(model=m, cutoffs=cutoffs, horizon='30 days') Valu...
error while working with fbprophet model using cutoffs
I am facing an issue while trying to work with fbprophet cross_valisation using cutoffs tying to see the results for the last 7 months. My data is ranging from 2017-01-01 to 2022-07-01 df_cv2 = cross_validation(model=m, cutoffs=cutoffs, horizon='30 days') ValueError Traceback (most recent...
[ "I faced the same problem and I coped with it efficiently setting horizon = '31 days' (i.e., the maximum number that could elapse between two months).\nThis is due to how index_predicted (used here: yhat = m.predict(df[index_predicted][columns])), is set: index_predicted = (df['ds'] > cutoff) & (df['ds'] <= cutoff ...
[ 0 ]
[]
[]
[ "facebook_prophet", "forecasting", "pandas", "python", "time_series" ]
stackoverflow_0073656137_facebook_prophet_forecasting_pandas_python_time_series.txt
Q: Resize image by 50% using the least amount of lines I have the following code that resizes the image by a number hardcoded I would like it to resize using the following formula - image_size / 2 f = r'C:\Users\elazar\bucket\PHOTO' for file in os.listdir(f): f_img = f+"/"+file img = Image.open(f_img).resize(...
Resize image by 50% using the least amount of lines
I have the following code that resizes the image by a number hardcoded I would like it to resize using the following formula - image_size / 2 f = r'C:\Users\elazar\bucket\PHOTO' for file in os.listdir(f): f_img = f+"/"+file img = Image.open(f_img).resize((540,540)).save(f_img) Is it possible to shorten this co...
[ "\".size\" gives the width and height of a picture as a tuple. You can replace the code below with your 4th line.\nImage.open(f_img).resize((int(Image.open(f_img).size[0] / 2), int(Image.open(f_img).size[1] / 2))).save(f_img)\n\nHowever, this one line code is much more inefficient than the code below. It opens the ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074589508_python.txt
Q: Cannot catch requests.exceptions.ConnectionError with try except It feels like I am slowly losing my sanity. I am unable to catch a connection error in a REST-API request. I read at least 20 similar questions on stackoverflow, tried every possible except statement I could think of and simplified the code as much a...
Cannot catch requests.exceptions.ConnectionError with try except
It feels like I am slowly losing my sanity. I am unable to catch a connection error in a REST-API request. I read at least 20 similar questions on stackoverflow, tried every possible except statement I could think of and simplified the code as much as I could to rule out certain other libraries. I am using Python 3.7 a...
[ "Okay, I could figure it out myself. Kind of.\nA huge problem was that the traceback doesn't point to the line of my code where the exception is raised. I still don't know why that is and if this should be considered a bug in requests or not. But in any case: requests raises a ConnectionError in adapters.py but the...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_requests", "try_except" ]
stackoverflow_0074253820_python_python_3.x_python_requests_try_except.txt
Q: Temporarily change cursor using Python I am writing a script that intercepts a touchpad output and send to the windows after some processing. So there is no GUI involved. I want to change the cursor temporarily when certain cursor behavior occurs. I have searched the web to the best of my abilities and found very ...
Temporarily change cursor using Python
I am writing a script that intercepts a touchpad output and send to the windows after some processing. So there is no GUI involved. I want to change the cursor temporarily when certain cursor behavior occurs. I have searched the web to the best of my abilities and found very few posts that talked about using win32api.S...
[ "Using the code below the cursor is changed system-wide though I have to restored to the arrow cursor below quitting the program. If there are other better ways I would appreciate your response.\nfrom ctypes import *\nimport win32con\n\nSetSystemCursor = windll.user32.SetSystemCursor #reference to function\nSetSyst...
[ 1, 0 ]
[]
[]
[ "cursor", "python", "winapi" ]
stackoverflow_0007921307_cursor_python_winapi.txt
Q: Space de-limited results, errors when Concatenating 2 columns the code I'm running gives results that are space de-liminated. This creates a problem with my sector column which gives a result of Communication Services. It creates 1 column for Communication and another column for Services where I need 1 column sayi...
Space de-limited results, errors when Concatenating 2 columns
the code I'm running gives results that are space de-liminated. This creates a problem with my sector column which gives a result of Communication Services. It creates 1 column for Communication and another column for Services where I need 1 column saying Communication Services. I have tried to concatentate the 2 colum...
[ "Let us reformulate the get_stats function to return dictionary instead string. This way you can avoid the unnecessary step to split the strings to create a dataframe\ndef get_stats(ticker):\n info = yf.Tickers(ticker).tickers[ticker].info\n cols = ['currentPrice', 'marketCap', 'sector']\n return {'ticker'...
[ 1 ]
[]
[]
[ "concatenation", "pandas", "python" ]
stackoverflow_0074589387_concatenation_pandas_python.txt
Q: train, test, validation splits in tfds.load so I am asked to implement the split function parameter: 80% train, 10% validation, and 10% test. And I do not understand how to do it here. Please help. Thanks. def plot_example(x_raw, y_raw): fig, axes = plt.subplots(3, 3) i = 0 for i in range(3): for j in ra...
train, test, validation splits in tfds.load
so I am asked to implement the split function parameter: 80% train, 10% validation, and 10% test. And I do not understand how to do it here. Please help. Thanks. def plot_example(x_raw, y_raw): fig, axes = plt.subplots(3, 3) i = 0 for i in range(3): for j in range(3): imgplot = axes[i,j].imshow(x_raw[i*...
[ "The tfds.load has the argument of split. You can use this argument to load the dataset in your desired format. If you want 80% train, 10% val, 10% test, you can simply do\ntfds.load(\n colorectal_histology,\n split=[\"train[20%:]\", \"train[0%:10%]\", \"train[10%:20%\"],\n as_supervised=True, \n with_i...
[ 0 ]
[]
[]
[ "machine_learning", "python", "scikit_learn", "sklearn_pandas" ]
stackoverflow_0074587287_machine_learning_python_scikit_learn_sklearn_pandas.txt
Q: How to use .env files and environment variables with Python and macOS So I am connecting to an RPC cloud-node and trying to get the latest block from the Ethereum blockchain, along with all the block details and have written some code in python using web3.py. I have the code ready and according to the official doc...
How to use .env files and environment variables with Python and macOS
So I am connecting to an RPC cloud-node and trying to get the latest block from the Ethereum blockchain, along with all the block details and have written some code in python using web3.py. I have the code ready and according to the official doc https://web3py.readthedocs.io/en/v5/troubleshooting.html, I am able to set...
[ "The easiest way to have environment variables on macOS is to use Bash shell environment files and source command. Virtualenv does this internally when you run the command source venv/bin/activate.\nNote that there is no standard on .env file format.\nCreate an env file mac.env with the content:\nexport USERNAME=xy...
[ 0 ]
[]
[]
[ "environment_variables", "ethereum", "python", "virtual_environment", "web3py" ]
stackoverflow_0074567136_environment_variables_ethereum_python_virtual_environment_web3py.txt
Q: How to make a variable based on the content of another variable I have a CSV with info in it, the start of it is the profile name and I want to store the row as a variable name thats the profile name value like so: def GetShipping(): file = "profiles.csv" with open(file) as f: heading =...
How to make a variable based on the content of another variable
I have a CSV with info in it, the start of it is the profile name and I want to store the row as a variable name thats the profile name value like so: def GetShipping(): file = "profiles.csv" with open(file) as f: heading = next(f) reader = csv.reader(f) for row in re...
[ "It's hard to understand your question.\nBut, below code will give you some idea.\nimport csv\nfrom typing import Tuple, Dict\n\n\ndef GetShipping():\n file = \"profiles.csv\"\n with open(file) as f:\n heading = next(f)\n reader = csv.reader(f)\n\n profile_map: Dict[str, Tuple[str, str, s...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074589586_csv_python.txt
Q: How to include xml prolog to xml files using python 3? I want to include the XML prolog in my XML file... I tried the following - ET.tostring(root, encoding='utf8', method='xml') But it works only while printing and not for writing to file. I have a small code where I am changing an attribute and modifying the X...
How to include xml prolog to xml files using python 3?
I want to include the XML prolog in my XML file... I tried the following - ET.tostring(root, encoding='utf8', method='xml') But it works only while printing and not for writing to file. I have a small code where I am changing an attribute and modifying the XML file. But I want to add the XML prolog also. Any idea how...
[ "In order to add prolog to XML you need to pass additional parameter (xml_declaration) to tree.write() method as follows:\ntree.write('xyz.xml', xml_declaration=True)\n\nThe last but one code line is redundant, so our method should take one more parameter:\ntree.write('xyz.xml', encoding='UTF-8', xml_declaration=Tr...
[ 1, 0 ]
[]
[]
[ "elementtree", "lxml", "python", "python_3.x", "xml" ]
stackoverflow_0061949852_elementtree_lxml_python_python_3.x_xml.txt
Q: Python .toml and .cfg nonsense? I am having a hard time configure proper cfg and toml files.... I just want to understand these, I am coming from a Java background, and nothing clear from my researches. Why namespaces are so bad ? Simple python project would take the first folder / package as a name... if I call ...
Python .toml and .cfg nonsense?
I am having a hard time configure proper cfg and toml files.... I just want to understand these, I am coming from a Java background, and nothing clear from my researches. Why namespaces are so bad ? Simple python project would take the first folder / package as a name... if I call it SQLAlchemy it will override the re...
[ "\nWhy namespaces are so bad ?\n\nPackage namespacing is a community decision with advantages and drawbacks. The python community has largely fallen on the side of not doing it, in part for social reasons and in part for technological reasons: the language historically did not support \"namespace packages\" and the...
[ 0 ]
[]
[]
[ "cfg", "package", "python", "toml" ]
stackoverflow_0074589685_cfg_package_python_toml.txt
Q: Problem with Python code to send data from Mac to Arduino thanks in advance for any help on this. I am writing some code to send data from a Mac to an Arduino board so that I can program a flash memory device. I have a Python program which negotiates a link to the arduino board and then should send 256 byte chunks...
Problem with Python code to send data from Mac to Arduino
thanks in advance for any help on this. I am writing some code to send data from a Mac to an Arduino board so that I can program a flash memory device. I have a Python program which negotiates a link to the arduino board and then should send 256 byte chunks of data read from a file to the arduino. Code running on the A...
[ "I worked on this some more to fix some checksum-related bugs and the following code works:\n import serial, time, sys\n\ntry:\n dataFile = open(sys.argv[1], \"rb\")\nexcept IOError:\n sys.exit(\"file cannot be opened\") \narduino = serial.Serial('/dev/cu.usbmodem2101', 115200, timeout=1)\ntime.sleep(1) #...
[ 0 ]
[]
[]
[ "bytestream", "pyserial", "python", "serial_port" ]
stackoverflow_0074577735_bytestream_pyserial_python_serial_port.txt
Q: How to print out variable name instead of value? If I have a list of variables and each variable is assigned to an equation, how can I print the variable itself from the list not the result of the equation For example: x = 1 + 1 y = 2 + 2 z = 3 + 3 list = [x, y, z] print(list[0]) print(list[1]) print(list[2]) S...
How to print out variable name instead of value?
If I have a list of variables and each variable is assigned to an equation, how can I print the variable itself from the list not the result of the equation For example: x = 1 + 1 y = 2 + 2 z = 3 + 3 list = [x, y, z] print(list[0]) print(list[1]) print(list[2]) Should print out: x y z Instead of: 2 4 6
[ "print() giving you a values of list[0], or list[1] or list[2]\nYou gave them values 2,4,6 at the start of your app\nx = 1 + 1\ny = 2 + 2\nz = 3 + 3\n\nif you want to get x,y,z try this:\nx = \"x\"\ny = \"y\"\nz = \"z\"\n\n", "in that case, you will need to change your list to a string, otherwise it will think th...
[ 1, 0, 0, 0 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0074589346_debugging_python.txt
Q: python function questiton about listed many object Calculus exam results are announced and your result is above the announced average. You want to have an idea about the letter grade you will get, and to do this you ask everyone you know about their exam results. You want to calculate the median of the results, wh...
python function questiton about listed many object
Calculus exam results are announced and your result is above the announced average. You want to have an idea about the letter grade you will get, and to do this you ask everyone you know about their exam results. You want to calculate the median of the results, which will give you some more idea about the distribution ...
[ "You can test with doc test.\ndef find_median(lists):\n \"\"\"\n >>> find_median([1])\n 1\n >>> find_median([3,1])\n 3\n >>> find_median([1,2,3])\n 2\n >>> find_median([1,6,3,5])\n 5\n >>> find_median([5,3,5])\n 5\n \"\"\"\n copied = lists[:]\n copied.sort()\n length = l...
[ 0, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074589728_function_list_python.txt
Q: Find how many times a string appears within elements of a list in Python? If I have a list of strings such as this: names = ["Alice", "Bob", "Charlie", "Darren"] How would I find how many of these strings contain the letter 'a'? I tried using the count function names.count("a") But this only output the amount of...
Find how many times a string appears within elements of a list in Python?
If I have a list of strings such as this: names = ["Alice", "Bob", "Charlie", "Darren"] How would I find how many of these strings contain the letter 'a'? I tried using the count function names.count("a") But this only output the amount of elements that were 'a' rather than contained 'a'.
[ "A list comprehension can be used to determine the no. of elements with letter 'a' in them.\nprint(len([x for x in names if 'a' in x]))\n\nO/P: 2\n", "We can use a loop:\nnames = [\"Alice\", \"Bob\", \"Charlie\", \"Darren\"]\n\ncount=0\n\nfor i in range(len(names)):\n if 'a' in list(names[i]):\n count+=...
[ 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074589773_list_python.txt
Q: Set a module's class method as an attribute of that module from outside that module The objective: I have a package with submodules that I would like to be accessible in the most straightforward way possible. The submodules contain classes to take advantage of the class structure, but don't need to be initialized ...
Set a module's class method as an attribute of that module from outside that module
The objective: I have a package with submodules that I would like to be accessible in the most straightforward way possible. The submodules contain classes to take advantage of the class structure, but don't need to be initialized (as they contain static and class methods). So, ideally, I would like to access them as f...
[ "I just checked it on my machine.\nCreated a package myPackage with a module subModule that has a function someMethod.\nI run a python shell with working directory in the same directory that the myPackage is in, and to get these 3 import statements to work:\nfrom myPackage.subModule import someMethod\n\nfrom myPack...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074547307_python_python_3.x.txt
Q: Python Async Limit Concurrent coroutines per second My use case is the following : I’m using python 3.8 I have an async function analyse_doc that is a wrapper for a http request to a web service. I have approx 1000 docs to analyse as fast as possible. The service allows for 15 transaction per second (and not 15 co...
Python Async Limit Concurrent coroutines per second
My use case is the following : I’m using python 3.8 I have an async function analyse_doc that is a wrapper for a http request to a web service. I have approx 1000 docs to analyse as fast as possible. The service allows for 15 transaction per second (and not 15 concurrent request at any second). So first sec I can send ...
[ "You could try adding another sleep tasks into the mix to drive the request generation. Something like this\nimport asyncio\nimport random\n\nONE_SECOND = 1\nCONCURRENT_TASK_LIMIT = 2\nTASKS_TO_CREATE = 10\n\nloop = asyncio.new_event_loop()\n\nwork_todo = []\nwork_in_progress = []\n\n# just creates arbitrary work ...
[ 1 ]
[]
[]
[ "asynchronous", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074585677_asynchronous_python_python_3.x_python_asyncio.txt
Q: How do I cross time series in pandas? Let's say I've got a dataframe with an integer index: pd.DataFrame([[4,5],[7,8],[9,10]],columns=['a','b']) a b 0 4 5 1 7 8 2 9 10 I'd like to create a matrix of ratios for each of a cross b, for each index, so I get a series of matrices of the form: a/a a/b...
How do I cross time series in pandas?
Let's say I've got a dataframe with an integer index: pd.DataFrame([[4,5],[7,8],[9,10]],columns=['a','b']) a b 0 4 5 1 7 8 2 9 10 I'd like to create a matrix of ratios for each of a cross b, for each index, so I get a series of matrices of the form: a/a a/b b/a b/b for each index. Ultimately, I'll ...
[ "Easy way:\npd.DataFrame({f'{x}/{y}': df[x] / df[y] for x in df for y in df})\n\nSlightly complicated way (might be faster if you have large number of columns):\na = df.values[None].T / df.values\npd.DataFrame(np.hstack(a), columns=(f'{x}/{y}' for x in df for y in df))\n\nResult\n a/a a/b b/a b/b\n0 1....
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074589778_pandas_python.txt
Q: Method that acts like a static method AND a regular method I was wondering if there is a way for a class to define a method that behaves like a static method (can be called without an instance variable) and a regular method (can be called with an instance variable). Im making an RSA module that would help me solve...
Method that acts like a static method AND a regular method
I was wondering if there is a way for a class to define a method that behaves like a static method (can be called without an instance variable) and a regular method (can be called with an instance variable). Im making an RSA module that would help me solve RSA problems, the initialization goes like this: class RSA: ...
[ "In python, you use modules for that kind of stuff, not classes:\nin rsa.py\ndef fermat_factorization(n):\n \"\"\"Ordinary function\"\"\"\n\nclass RSA:\n def fermat_factorization(self):\n \"\"\"Method\"\"\"\n return fermat_factorization(self.n)\n\nsomewhere else:\n import rsa\n\n x = rsa.fermat_f...
[ 2 ]
[]
[]
[ "oop", "python", "python_3.x" ]
stackoverflow_0074589462_oop_python_python_3.x.txt
Q: Insertion sort python algorithm: Why do we subtract 1 from i? Here is the code: list_a = [3,2,5,7,4,1] def insertion_sort(list_a): indexing_length = range(1,len(list_a)) for i in indexing_length: value_to_sort = list_a[i] while list_a[i-1] > value_to_sort and i>0: list_a[i], list_a[i-1] = list...
Insertion sort python algorithm: Why do we subtract 1 from i?
Here is the code: list_a = [3,2,5,7,4,1] def insertion_sort(list_a): indexing_length = range(1,len(list_a)) for i in indexing_length: value_to_sort = list_a[i] while list_a[i-1] > value_to_sort and i>0: list_a[i], list_a[i-1] = list_a[i-1], list_a[i] i = i - 1 return list_a I understa...
[ "Hi and welcome to SO,\nrange(a, b) in python is equivalent to [a, b[ in mathematics with a and b two floating numbers and a < b\nAnd range(b) is equivalent to [0, b[ in mathematics.\n", "in insertion sort, you select each value and go back ward to place in the corresponding place where it is smaller than right p...
[ 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "insertion_sort", "python" ]
stackoverflow_0074589512_algorithm_insertion_sort_python.txt
Q: django - DecimalField max_digits, decimal_places explained So I'm just starting out with Django and using it to store forex prices which are represented as 1.21242, 1.20641, etc... model.py from django.db import models # Create your models here. class ForexPrice(models.Model): openPrice = models.DecimalField(...
django - DecimalField max_digits, decimal_places explained
So I'm just starting out with Django and using it to store forex prices which are represented as 1.21242, 1.20641, etc... model.py from django.db import models # Create your models here. class ForexPrice(models.Model): openPrice = models.DecimalField(max_digits=6, decimal_places=6) highPrice = models.DecimalFi...
[ "max_digits must be equal, or higher than decimal_places.\nIf you were to have 123456.654321 you'd have to define max_digits=12, decimal_places=6.\nmax_digits is INCLUDING decimal_places.\n", "\"max_digits\" represents the number of digits all of your numbers.\n\"decimal_places\" represents the number of digits t...
[ 19, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0067307399_django_django_models_python.txt
Q: What exactly happens when you create an alias of the Exception class? try: 0/0 except Exception as e: print(e) The above code prints division by zero as one would expect. But if we try to print without creating the alias: try: 0/0 except Exception: print(Exception) It simply prints <class 'Except...
What exactly happens when you create an alias of the Exception class?
try: 0/0 except Exception as e: print(e) The above code prints division by zero as one would expect. But if we try to print without creating the alias: try: 0/0 except Exception: print(Exception) It simply prints <class 'Exception'>. What is happening here? The as keyword is used to create an "alias"....
[ "The documentation of Python states this:\n\nThe except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define str() to print all the arguments without ex...
[ 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0074589925_exception_python.txt
Q: Changing layout and adding titles to JSON file with python I'm trying to extract data from two different api endpoints and create a JSON file with said data. I wish to have titles for each object to distinguish the different data. My code is below: import requests import json headers = { 'accept-language': 'e...
Changing layout and adding titles to JSON file with python
I'm trying to extract data from two different api endpoints and create a JSON file with said data. I wish to have titles for each object to distinguish the different data. My code is below: import requests import json headers = { 'accept-language': 'en-US,en;q=0.9', 'origin': 'https://www.nasdaq.com/', 're...
[ "Just create a dictionary and place the two values in it before dumping it as JSON.\nSolution\nimport requests\nimport json\n\nheaders = {\n 'accept-language': 'en-US,en;q=0.9',\n 'origin': 'https://www.nasdaq.com/',\n 'referer': 'https://www.nasdaq.com/',\n 'accept': 'application/json, text/plain, */*'...
[ 1 ]
[]
[]
[ "api", "json", "python" ]
stackoverflow_0074589989_api_json_python.txt
Q: Path hunting with Z3 solver I am modeling below problem in Z3. The aim is to find the path for Agent to reach the coin avoiding obstacles. Initial_grid =[['T' 'T' 'T' 'T' 'T' 'T' 'T'] ['T' ' ' ' ' ' ' ' ' ' ' 'T'] ['T' ' ' 'A' 'O' ' ' 'O' 'T'] ['T' 'O' ' ' ' ' ' ' ' ' 'T']...
Path hunting with Z3 solver
I am modeling below problem in Z3. The aim is to find the path for Agent to reach the coin avoiding obstacles. Initial_grid =[['T' 'T' 'T' 'T' 'T' 'T' 'T'] ['T' ' ' ' ' ' ' ' ' ' ' 'T'] ['T' ' ' 'A' 'O' ' ' 'O' 'T'] ['T' 'O' ' ' ' ' ' ' ' ' 'T'] ['T' ' ' ' ' 'O' '...
[ "One way to think about these sorts of search problems is a two pronged approach:\n\nCan I find a path with 1 move? If not, try with 2 moves, 3 moves, etc. till you hit an upper bound and you decide to stop trying.\n\nInstead of \"searching,\" imagine a path is given to you; how would you check that it's a good pat...
[ 1, 0 ]
[]
[]
[ "python", "z3", "z3py" ]
stackoverflow_0074582355_python_z3_z3py.txt
Q: How to format dictionary.items , so that it will return 2 marks after comma? I have a excel sheet and I extract some values from the sheet. But some numbers extracted from the file sheet looks like: 3767.3999999999996 and it has to be: 3767,39. So just two decimals after comma. I Tried with this function: import ...
How to format dictionary.items , so that it will return 2 marks after comma?
I have a excel sheet and I extract some values from the sheet. But some numbers extracted from the file sheet looks like: 3767.3999999999996 and it has to be: 3767,39. So just two decimals after comma. I Tried with this function: import openpyxl def load_excel_file(self, file_name): excelWorkbook = openpyxl.l...
[ "The issue is at \"{:.2%}\".format(fruit_sums.items()), but even if it had worked, you would have tried to iterate key, values on a string, that is absolutly not the way\nYou need to apply the formatting logic only the value only\nreturn \"\\n\".join(f\"{a} {b:.2f}\" for a, b in fruit_sums.items())\n\n" ]
[ 1 ]
[]
[]
[ "format", "python" ]
stackoverflow_0074590144_format_python.txt
Q: Using a class-based test as a fixture I am using this class which creates my login test: import pytest from pages.loginPage import LoginPage from utils import utilis as utils @pytest.mark.usefixtures("test_setup") class TestLogin(): def test_login(self): driver=self.driver driver.get(utils.UR...
Using a class-based test as a fixture
I am using this class which creates my login test: import pytest from pages.loginPage import LoginPage from utils import utilis as utils @pytest.mark.usefixtures("test_setup") class TestLogin(): def test_login(self): driver=self.driver driver.get(utils.URL) login =LoginPage(driver) ...
[ "Fixtures can be methods defined in a class, but then they are not available outside of the class. As the pytest documentation on fixtures states:\n\nFixture availability is determined from the perspective of the test. A fixture is only available for tests to request if they are in the scope that fixture is defined...
[ 1 ]
[]
[]
[ "pytest", "python", "testing" ]
stackoverflow_0074590160_pytest_python_testing.txt
Q: Finding the outlier points from matplotlib : boxplot I am plotting a non-normal distribution using boxplot and interested in finding out about outliers using boxplot function of matplotlib. Besides the plot I am interested in finding out the value of points in my code which are shown as outliers in the boxplot. I...
Finding the outlier points from matplotlib : boxplot
I am plotting a non-normal distribution using boxplot and interested in finding out about outliers using boxplot function of matplotlib. Besides the plot I am interested in finding out the value of points in my code which are shown as outliers in the boxplot. Is there any way I can extract these values for use in my d...
[ "Do you means those points above and below the two black lines?\nfrom pylab import *\nspread= rand(50) * 100\ncenter = ones(25) * 50\nflier_high = rand(10) * 100 + 100\nflier_low = rand(10) * -100\ndata =concatenate((spread, center, flier_high, flier_low), 0)\nr = boxplot(data)\n\n\nStore the return dict from boxpl...
[ 21, 1 ]
[]
[]
[ "matplotlib", "outliers", "python" ]
stackoverflow_0010238357_matplotlib_outliers_python.txt
Q: How to make my python code less clumsy? (dealing with if/elif statements and pandas) I wrote a function that generates a table after feeding it a list. It is part of a web scraping script I'm working on. The function works (not the best but good enough for its purpose) but is there a better way to achieve better/s...
How to make my python code less clumsy? (dealing with if/elif statements and pandas)
I wrote a function that generates a table after feeding it a list. It is part of a web scraping script I'm working on. The function works (not the best but good enough for its purpose) but is there a better way to achieve better/similar/same result? For example, here's a list I would want to turn into a table: listings...
[ "We can use list comprehensions and zip statement:\ndef MakeTable(listings):\n\n hour_idx = [i for i, item in enumerate(listings) if re.search(r\"([0-9,]*\\s[0-9]*\\s(Minute|Hour)\\sago|[0-9,]*\\sNow)\", item)]\n \n ls = [listings[3:hour_idx[0]+1]]\n \n ls_2 = [x[y[i]+1:y[i+1]+1] for (x, y, i) in zip...
[ 4, 1 ]
[]
[]
[ "if_statement", "pandas", "python" ]
stackoverflow_0074589824_if_statement_pandas_python.txt