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: How to #include in Xcode #include <Python.h> the error of this code is 'Python.h' file not found. I've installed python by brew, the results show below. And the path of python already written in to $PATH MacBook-Pro test % python --version Python 3.10.8 MacBook-Pro test % brew search python ==> Formulae app-engine-python python-tk@3.11 boost-python3 python-tk@3.9 bpython python-typing-extensions gst-python python-yq ipython python@3.10 ✔ libpython-tabulate python@3.11 micropython python@3.7 ptpython python@3.8 python-build python@3.9 python-gdbm@3.11 reorder-python-imports python-launcher wxpython python-lsp-server pythran python-markdown jython python-tabulate cython python-tk@3.10 ==> Casks awips-python mysql-connector-python If you meant "python" specifically: It was migrated from homebrew/cask to homebrew/core. MacBook-Pro test % echo $PATH /usr/local/opt/python@3.10/libexec/bin:/Users/fanxuezhou/opt/anaconda3/bin:/Users/fanxuezhou/opt/anaconda3/condabin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin If someone can tell me how to use Python.h in Xcode, or how can I compile the code by command line? MacBook-Pro test % gcc main.cpp -o test main.cpp:9:10: fatal error: 'Python.h' file not found #include <Python.h> ^~~~~~~~~~ 1 error generated. The error message of Xcode A: I've fixed this problem by using g++, g++ main.cpp -o test -I /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/include/ -L /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib -l python3.10
How to #include in Xcode
#include <Python.h> the error of this code is 'Python.h' file not found. I've installed python by brew, the results show below. And the path of python already written in to $PATH MacBook-Pro test % python --version Python 3.10.8 MacBook-Pro test % brew search python ==> Formulae app-engine-python python-tk@3.11 boost-python3 python-tk@3.9 bpython python-typing-extensions gst-python python-yq ipython python@3.10 ✔ libpython-tabulate python@3.11 micropython python@3.7 ptpython python@3.8 python-build python@3.9 python-gdbm@3.11 reorder-python-imports python-launcher wxpython python-lsp-server pythran python-markdown jython python-tabulate cython python-tk@3.10 ==> Casks awips-python mysql-connector-python If you meant "python" specifically: It was migrated from homebrew/cask to homebrew/core. MacBook-Pro test % echo $PATH /usr/local/opt/python@3.10/libexec/bin:/Users/fanxuezhou/opt/anaconda3/bin:/Users/fanxuezhou/opt/anaconda3/condabin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin If someone can tell me how to use Python.h in Xcode, or how can I compile the code by command line? MacBook-Pro test % gcc main.cpp -o test main.cpp:9:10: fatal error: 'Python.h' file not found #include <Python.h> ^~~~~~~~~~ 1 error generated. The error message of Xcode
[ "I've fixed this problem by using g++,\ng++ main.cpp -o test -I /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/include/ -L /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib -l python3.10\n\n" ]
[ 0 ]
[]
[]
[ "c++", "python", "python_3.x", "xcode" ]
stackoverflow_0074458612_c++_python_python_3.x_xcode.txt
Q: Python, Streamlit AgGrid add new row to AgGrid Table I am trying to add a new row to an AgGrid Table using streamlit and python At this point, I just want to add 1 or more new rows to the table generated by the AgGrid by pressing the "add row" button. After pressing the "add row" button I generate a second table with the new row mistakenly, so I get 2 data-tables instead of updating the main table. The initial data df = get_data() is been gathered from a SQL query. I want to add a new row and (for now) save it into a CSV file or at least get the updated DF with the new row added as an output and graph it My current code import streamlit as st from metrics.get_metrics import get_data from metrics.config import PATH_SAMPLES filename: str = 'updated_sample.csv' save_path = PATH_SAMPLES.joinpath(filename) def generate_agrid(data: pd.DataFrame): gb = GridOptionsBuilder.from_dataframe(data) gb.configure_default_column(editable=True) # Make columns editable gb.configure_pagination(paginationAutoPageSize=True) # Add pagination gb.configure_side_bar() # Add a sidebar gb.configure_selection('multiple', use_checkbox=True, groupSelectsChildren="Group checkbox select children") # Enable multi-row selection gridOptions = gb.build() grid_response = AgGrid( data, gridOptions=gridOptions, data_return_mode=DataReturnMode.AS_INPUT, update_on='MANUAL', # <- Should it let me update before returning? fit_columns_on_grid_load=False, theme=AgGridTheme.STREAMLIT, # Add theme color to the table enable_enterprise_modules=True, height=350, width='100%', reload_data=True ) data = grid_response['data'] selected = grid_response['selected_rows'] df = pd.DataFrame(selected) # Pass the selected rows to a new dataframe df return grid_response def onAddRow(grid_table): df = pd.DataFrame(grid_table['data']) column_fillers = { column: (False if df.dtypes[column] == "BooleanDtype" else 0 if df.dtypes[column] == "dtype('float64')" else '' if df.dtypes[column] == "string[python]" else datetime.datetime.utcnow() if df.dtypes[column] == "dtype('<M8[ns]')" else '') for column in df.columns } data = [column_fillers] df_empty = pd.DataFrame(data, columns=df.columns) df = pd.concat([df, df_empty], axis=0, ignore_index=True) grid_table = generate_agrid(df) return grid_table # First data gather df = get_data() if __name__ == '__main__': # Start graphing grid_table = generate_agrid(df) # add row st.sidebar.button("Add row", on_click=onAddRow, args=[grid_table]) A: Here is a sample minimal code. import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode def generate_agrid(df): gb = GridOptionsBuilder.from_dataframe(df) gb.configure_selection(selection_mode="multiple", use_checkbox=True) gridoptions = gb.build() grid_response = AgGrid( df, height=200, gridOptions=gridoptions, update_mode=GridUpdateMode.MANUAL ) selected = grid_response['selected_rows'] # Show the selected row. if selected: st.write('selected') st.dataframe(selected) return grid_response def add_row(grid_table): df = pd.DataFrame(grid_table['data']) new_row = [['', 100]] df_empty = pd.DataFrame(new_row, columns=df.columns) df = pd.concat([df, df_empty], axis=0, ignore_index=True) # Save new df to sample.csv. df.to_csv('sample.csv', index=False) def get_data(): """Reads sample.csv and return a dataframe.""" return pd.read_csv('sample.csv') if __name__ == '__main__': df = get_data() grid_response = generate_agrid(df) st.sidebar.button("Add row", on_click=add_row, args=[grid_response]) Initial output Output after pressing add row sample.csv team,points Lakers,120 Celtics,130
Python, Streamlit AgGrid add new row to AgGrid Table
I am trying to add a new row to an AgGrid Table using streamlit and python At this point, I just want to add 1 or more new rows to the table generated by the AgGrid by pressing the "add row" button. After pressing the "add row" button I generate a second table with the new row mistakenly, so I get 2 data-tables instead of updating the main table. The initial data df = get_data() is been gathered from a SQL query. I want to add a new row and (for now) save it into a CSV file or at least get the updated DF with the new row added as an output and graph it My current code import streamlit as st from metrics.get_metrics import get_data from metrics.config import PATH_SAMPLES filename: str = 'updated_sample.csv' save_path = PATH_SAMPLES.joinpath(filename) def generate_agrid(data: pd.DataFrame): gb = GridOptionsBuilder.from_dataframe(data) gb.configure_default_column(editable=True) # Make columns editable gb.configure_pagination(paginationAutoPageSize=True) # Add pagination gb.configure_side_bar() # Add a sidebar gb.configure_selection('multiple', use_checkbox=True, groupSelectsChildren="Group checkbox select children") # Enable multi-row selection gridOptions = gb.build() grid_response = AgGrid( data, gridOptions=gridOptions, data_return_mode=DataReturnMode.AS_INPUT, update_on='MANUAL', # <- Should it let me update before returning? fit_columns_on_grid_load=False, theme=AgGridTheme.STREAMLIT, # Add theme color to the table enable_enterprise_modules=True, height=350, width='100%', reload_data=True ) data = grid_response['data'] selected = grid_response['selected_rows'] df = pd.DataFrame(selected) # Pass the selected rows to a new dataframe df return grid_response def onAddRow(grid_table): df = pd.DataFrame(grid_table['data']) column_fillers = { column: (False if df.dtypes[column] == "BooleanDtype" else 0 if df.dtypes[column] == "dtype('float64')" else '' if df.dtypes[column] == "string[python]" else datetime.datetime.utcnow() if df.dtypes[column] == "dtype('<M8[ns]')" else '') for column in df.columns } data = [column_fillers] df_empty = pd.DataFrame(data, columns=df.columns) df = pd.concat([df, df_empty], axis=0, ignore_index=True) grid_table = generate_agrid(df) return grid_table # First data gather df = get_data() if __name__ == '__main__': # Start graphing grid_table = generate_agrid(df) # add row st.sidebar.button("Add row", on_click=onAddRow, args=[grid_table])
[ "Here is a sample minimal code.\nimport streamlit as st\nimport pandas as pd\nfrom st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode\n\n\ndef generate_agrid(df):\n gb = GridOptionsBuilder.from_dataframe(df)\n gb.configure_selection(selection_mode=\"multiple\", use_checkbox=True)\n gridoptions = gb.build()\n\n grid_response = AgGrid(\n df,\n height=200,\n gridOptions=gridoptions,\n update_mode=GridUpdateMode.MANUAL\n )\n selected = grid_response['selected_rows']\n\n # Show the selected row.\n if selected:\n st.write('selected')\n st.dataframe(selected)\n\n return grid_response\n\n\ndef add_row(grid_table):\n df = pd.DataFrame(grid_table['data'])\n\n new_row = [['', 100]]\n df_empty = pd.DataFrame(new_row, columns=df.columns)\n df = pd.concat([df, df_empty], axis=0, ignore_index=True)\n\n # Save new df to sample.csv.\n df.to_csv('sample.csv', index=False)\n\n\ndef get_data():\n \"\"\"Reads sample.csv and return a dataframe.\"\"\"\n return pd.read_csv('sample.csv')\n\n\nif __name__ == '__main__':\n df = get_data()\n grid_response = generate_agrid(df)\n\n st.sidebar.button(\"Add row\", on_click=add_row, args=[grid_response])\n\n\nInitial output\n\nOutput after pressing add row\n\nsample.csv\nteam,points\nLakers,120\nCeltics,130\n\n" ]
[ 1 ]
[]
[]
[ "graph", "pandas", "python", "streamlit" ]
stackoverflow_0074449270_graph_pandas_python_streamlit.txt
Q: How to append only the numbers in a row to a variable using float and an if statement in a for loop Given a data set with the goal of graphing the data these issues arise: The header is an entry in the list, Some of the entries are blank (data missing), Even the numbers are in the form of strings income=[] fertility=[] for row in csv: income.append(row[2]) fertility.append(row[3]) print(income) print(fertility) I am trying to modify the above for loop that appends only the numerical values of the row using the float function coded below. def isNumeric(s): try: s = float(s) return True except: return False Below is my attempt, that is not appending the numerical values of the rows only giving me blank sets for income and fertility. income=[] fertility=[] for row in csv: if isNumeric(row[2])=='True' and isNumeric(row[3])=='True': float(row[2]) float(row[3]) income.append(float(row[2])) fertility.append(float(row[3])) print(income) print(fertility) A: You can do this more simply by just doing both float conversions in a single try/except: income = [] fertility = [] for row in csv: try: i, f = float(row[2]), float(row[3]) income.append(i) fertility.append(f) except ValueError: pass If either float() call raises ValueError, nothing will be appended, and the loop will just continue on to the next row. A: Samwise's response is a good one - it's simple and it is very pythonic - it tries to change the strings into floats and if that fails, it doesn't update the lists. If you want your code to work, though, you can try it with these corrections: income=[] fertility=[] for row in csv: if isNumeric(row[2]) and isNumeric(row[3]): income.append(float(row[2])) fertility.append(float(row[3])) print(income) print(fertility)
How to append only the numbers in a row to a variable using float and an if statement in a for loop
Given a data set with the goal of graphing the data these issues arise: The header is an entry in the list, Some of the entries are blank (data missing), Even the numbers are in the form of strings income=[] fertility=[] for row in csv: income.append(row[2]) fertility.append(row[3]) print(income) print(fertility) I am trying to modify the above for loop that appends only the numerical values of the row using the float function coded below. def isNumeric(s): try: s = float(s) return True except: return False Below is my attempt, that is not appending the numerical values of the rows only giving me blank sets for income and fertility. income=[] fertility=[] for row in csv: if isNumeric(row[2])=='True' and isNumeric(row[3])=='True': float(row[2]) float(row[3]) income.append(float(row[2])) fertility.append(float(row[3])) print(income) print(fertility)
[ "You can do this more simply by just doing both float conversions in a single try/except:\nincome = []\nfertility = []\nfor row in csv:\n try:\n i, f = float(row[2]), float(row[3])\n income.append(i)\n fertility.append(f)\n except ValueError:\n pass\n\nIf either float() call raises ValueError, nothing will be appended, and the loop will just continue on to the next row.\n", "Samwise's response is a good one - it's simple and it is very pythonic - it tries to change the strings into floats and if that fails, it doesn't update the lists.\nIf you want your code to work, though, you can try it with these corrections:\nincome=[]\nfertility=[]\nfor row in csv:\n if isNumeric(row[2]) and isNumeric(row[3]):\n income.append(float(row[2]))\n fertility.append(float(row[3]))\n\nprint(income)\nprint(fertility)\n\n" ]
[ 1, 0 ]
[]
[]
[ "for_loop", "if_statement", "python" ]
stackoverflow_0074484028_for_loop_if_statement_python.txt
Q: Run kafka consumer without while loop using python I am using Confluentinc Kafka with Python & multi-threading. In this I have N worker threads running in parallel, whenever a thread completes its work it poll the message from kafka on demand. This whole job is done using the while loop. By using the while loop my main thread gets blocked & there is no other operation can be performed. Below is the sample of my code: import concurrent.futures with concurrent.futures.ThreadPoolExecutor(5) as executor: while True: counter = 0 for future in futures: is_running = future.running() if is_running: counter += 1 avail_slots = 5 - counter if avail_slots > 0: for message in get_poll_message(avail_slots): future = executor.submit( message_thread_executor, message=message ) futures.append(future) elif avail_slots == 0: time.sleep(10) def get_poll_message(avail_slots) raw_messages = kafka_consumer.poll(max_records=avail_slots) msgs = [] for topic_partition, message in raw_messages.items(): for msg in message: msgs.append(msg) return msgs I am looking if there is any other way to do that in Python instead of using the while loop? I want to remove the while loop so that my main thread does not get block. A: You could use supervisor Python library to run 5 processes in parallel with one consumer. That would simplify your code and offer you better process management. Otherwise, your while loop should be in the Thread body with a callback for the records it had polled, not in the main loop, iterating over each future, and only passing one message at a time to an executor.
Run kafka consumer without while loop using python
I am using Confluentinc Kafka with Python & multi-threading. In this I have N worker threads running in parallel, whenever a thread completes its work it poll the message from kafka on demand. This whole job is done using the while loop. By using the while loop my main thread gets blocked & there is no other operation can be performed. Below is the sample of my code: import concurrent.futures with concurrent.futures.ThreadPoolExecutor(5) as executor: while True: counter = 0 for future in futures: is_running = future.running() if is_running: counter += 1 avail_slots = 5 - counter if avail_slots > 0: for message in get_poll_message(avail_slots): future = executor.submit( message_thread_executor, message=message ) futures.append(future) elif avail_slots == 0: time.sleep(10) def get_poll_message(avail_slots) raw_messages = kafka_consumer.poll(max_records=avail_slots) msgs = [] for topic_partition, message in raw_messages.items(): for msg in message: msgs.append(msg) return msgs I am looking if there is any other way to do that in Python instead of using the while loop? I want to remove the while loop so that my main thread does not get block.
[ "You could use supervisor Python library to run 5 processes in parallel with one consumer. That would simplify your code and offer you better process management.\nOtherwise, your while loop should be in the Thread body with a callback for the records it had polled, not in the main loop, iterating over each future, and only passing one message at a time to an executor.\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "python", "while_loop" ]
stackoverflow_0074455299_apache_kafka_confluent_kafka_python_python_while_loop.txt
Q: How can you merge two data frames on a column that both data frames have if the column d types are not the same? I have two dataframes with a column called "US Postal State Code" and I am trying to merge them together on that column into a new dataframe. The problem is that the column has an object dtype in the first dataframe and a int64 dtype in the second dataframe. I tried to change the column with the object dtype to int64 using Enterprise3['US Postal State Code']=Enterprise3['US Postal State Code'].astype(int) however I got an error that states ValueError: invalid literal for int() with base 10: 'AL' Is there another way to change the dtypes so that they match and can be merged? A: You'll have to convert one of the columns to the others datatype with a custom function: def convert_postal(p): if p == "AL": return 35045 elif p = "OtherCodes": return other_codes_numerical_code Enterprise3["US Postal State Code"] = Enterprise3["US Postal State Code"].map(convert_postal) A: Use the dtype attribute on your dataframe to see what kinds of datatypes you have. Afterwards coerce them into the proper datatype. Your calculation does not work since some of your values have the foreign datatype.
How can you merge two data frames on a column that both data frames have if the column d types are not the same?
I have two dataframes with a column called "US Postal State Code" and I am trying to merge them together on that column into a new dataframe. The problem is that the column has an object dtype in the first dataframe and a int64 dtype in the second dataframe. I tried to change the column with the object dtype to int64 using Enterprise3['US Postal State Code']=Enterprise3['US Postal State Code'].astype(int) however I got an error that states ValueError: invalid literal for int() with base 10: 'AL' Is there another way to change the dtypes so that they match and can be merged?
[ "You'll have to convert one of the columns to the others datatype with a custom function:\ndef convert_postal(p):\n if p == \"AL\":\n return 35045\n elif p = \"OtherCodes\":\n return other_codes_numerical_code\n\nEnterprise3[\"US Postal State Code\"] = Enterprise3[\"US Postal State Code\"].map(convert_postal)\n\n", "Use the dtype attribute on your dataframe to see what kinds of datatypes you have. Afterwards coerce them into the proper datatype. Your calculation does not work since some of your values have the foreign datatype.\n" ]
[ 0, 0 ]
[]
[]
[ "computer_science", "data_science", "python" ]
stackoverflow_0074484066_computer_science_data_science_python.txt
Q: How to create a single DataFrame column from two separate arrays being pulled through a loop I want to create a DataFrame that prints precipitation type for multiple cities based on certain criteria. I have multiple variables that I would like to run through a single loop. For example, if temperature > 32 and precipitation amount > 0 then return "Rain". I use an API to pull current forecast data, so my actual TMP and precip arrays are different daily. https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html on this page is what I am essentially trying to reproduce, except with more than just one condition so I can include more precipitation types. TMP = [17, 16, 16, 15, 14, 14, 13, 13, 14, 16, 17, 19, 21, 23, 24, 25, 25, 24, 23, 22, 21, 21, 23, 23] precip = [0.0, 0.0, 0.0, 0.0, 0.017, 0.017, 0.017, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.020, 0.025, 0.035, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.017, 0.02] weather_df2 = pd.DataFrame({'A': [TMP], 'B': [precip]}) def rain_condition(n): for n in range(TMP.size): if TMP[n] > 32 and precip[n] < 0.001: return "Dry" elif TMP[n] < 32 and precip[n] > 0.25: return "Icing" return "Rain" def make_pretty(styler): styler.set_caption("Weather Conditions") styler.format(rain_condition) styler.background_gradient(axis=None,cmap="YlGnBu", vmin=0.001,vmax=5) return styler s = weather_df2.style.pipe(make_pretty) s This creates two columns taking TMP and precip separately, I want weather_df2 to have one column. It works if I just use TMP, but I need an if and condition. A: Is this what you're looking for? import pandas as pd def rain_condition(tmp, _precip): """ Calculate the rain condition based on the temperature and precipitation. Parameters ---------- tmp : list Temperatures. _precip : list Precipitation values. Returns ------- pd.DataFrame A DataFrame with rain conditions. """ result = [] for n in range(min([len(tmp), len(_precip)])): if tmp[n] > 32 and _precip[n] < 0.001: result.append("Dry") elif tmp[n] < 32 and _precip[n] > 0.25: result.append("Icing") result.append("Rain") return pd.DataFrame({'Weather': result}) def background_highlight(v): """ Highlight the background in a different color depending on the value. Parameters ---------- v : Any The value to be highlighted. Returns ------- str | None The CSS property to apply. """ if v == 'Rain': return 'color:white;background-color:#53789E' return 'background-color:#DBF1FD' if v == 'Icing' else None def make_pretty(styler, hide_columns: bool = True): """Format a DataFrame with a Styler. Parameters ---------- styler : pd.Styler | pd.DataFrame | pd.Series The Styler, or DataFrame to format. hide_columns : bool, default True Whether to hide the column names. Returns ------- pd.Styler The formatted Styler. """ if isinstance(styler, pd.Series): styler = styler.to_frame() if isinstance(styler, pd.DataFrame): return make_pretty(styler.style) if hide_columns: styler.hide_columns() styler.set_caption("<h2>Weather Conditions</h2>") styler.background_gradient(axis=None, cmap="YlGnBu", vmin=0.001, vmax=5) return styler.applymap(background_highlight) TMP = [17, 16, 16, 33, 14, 14, 13, 13, 14, 16, 17, 19, 21, 23, 24, 25, 25, 24, 23, 22, 21, 21, 23, 23] precip = [0.0, 0.0, 0.0, 0.0, 0.017, 0.017, 0.017, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.020, 0.26, 0.035, 0.32, 0.017,0.017, 0.017] s = rain_condition(TMP, precip).pipe(make_pretty) s Output: Notes Instead of creating the dataframe weather_df2, prior to calling the rain_condition function, I've modified it to instead generate the dataframe that will then be styled later on. I've modified the function make_pretty so that it converts pandas.Series or pandas.DataFrame objects to pandas.Styler, in order to make it more robust.
How to create a single DataFrame column from two separate arrays being pulled through a loop
I want to create a DataFrame that prints precipitation type for multiple cities based on certain criteria. I have multiple variables that I would like to run through a single loop. For example, if temperature > 32 and precipitation amount > 0 then return "Rain". I use an API to pull current forecast data, so my actual TMP and precip arrays are different daily. https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html on this page is what I am essentially trying to reproduce, except with more than just one condition so I can include more precipitation types. TMP = [17, 16, 16, 15, 14, 14, 13, 13, 14, 16, 17, 19, 21, 23, 24, 25, 25, 24, 23, 22, 21, 21, 23, 23] precip = [0.0, 0.0, 0.0, 0.0, 0.017, 0.017, 0.017, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.020, 0.025, 0.035, 0.017, 0.017,0.017, 0.017, 0.017, 0.017, 0.017, 0.02] weather_df2 = pd.DataFrame({'A': [TMP], 'B': [precip]}) def rain_condition(n): for n in range(TMP.size): if TMP[n] > 32 and precip[n] < 0.001: return "Dry" elif TMP[n] < 32 and precip[n] > 0.25: return "Icing" return "Rain" def make_pretty(styler): styler.set_caption("Weather Conditions") styler.format(rain_condition) styler.background_gradient(axis=None,cmap="YlGnBu", vmin=0.001,vmax=5) return styler s = weather_df2.style.pipe(make_pretty) s This creates two columns taking TMP and precip separately, I want weather_df2 to have one column. It works if I just use TMP, but I need an if and condition.
[ "Is this what you're looking for?\n\nimport pandas as pd\n\n\ndef rain_condition(tmp, _precip):\n \"\"\"\n Calculate the rain condition based on the temperature and precipitation.\n \n Parameters\n ----------\n tmp : list\n Temperatures.\n _precip : list\n Precipitation values.\n\n Returns\n -------\n pd.DataFrame\n A DataFrame with rain conditions.\n \"\"\"\n result = []\n for n in range(min([len(tmp), len(_precip)])):\n if tmp[n] > 32 and _precip[n] < 0.001:\n result.append(\"Dry\")\n elif tmp[n] < 32 and _precip[n] > 0.25: \n result.append(\"Icing\")\n result.append(\"Rain\")\n return pd.DataFrame({'Weather': result})\n\n\ndef background_highlight(v):\n \"\"\"\n Highlight the background in a different color depending on the value.\n\n Parameters\n ----------\n v : Any\n The value to be highlighted.\n\n Returns\n -------\n str | None\n The CSS property to apply.\n \"\"\"\n if v == 'Rain':\n return 'color:white;background-color:#53789E'\n return 'background-color:#DBF1FD' if v == 'Icing' else None\n\n\ndef make_pretty(styler, hide_columns: bool = True):\n \"\"\"Format a DataFrame with a Styler.\n\n Parameters\n ----------\n styler : pd.Styler | pd.DataFrame | pd.Series\n The Styler, or DataFrame to format.\n hide_columns : bool, default True\n Whether to hide the column names.\n\n Returns\n -------\n pd.Styler\n The formatted Styler.\n \"\"\"\n if isinstance(styler, pd.Series):\n styler = styler.to_frame()\n if isinstance(styler, pd.DataFrame):\n return make_pretty(styler.style)\n if hide_columns:\n styler.hide_columns()\n styler.set_caption(\"<h2>Weather Conditions</h2>\")\n styler.background_gradient(axis=None, cmap=\"YlGnBu\", vmin=0.001, vmax=5)\n return styler.applymap(background_highlight)\n\n\nTMP = [17, 16, 16, 33, 14, 14, 13, 13, 14, 16, 17, 19, 21, 23, 24, 25, 25, 24, 23, 22, 21, 21, 23, 23]\nprecip = [0.0, 0.0, 0.0, 0.0, 0.017, 0.017, 0.017, 0.017, 0.017,0.017, 0.017,\n 0.017, 0.017, 0.020, 0.26, 0.035, 0.32, 0.017,0.017, 0.017]\n\ns = rain_condition(TMP, precip).pipe(make_pretty)\ns\n\n\nOutput:\n\nNotes\n\nInstead of creating the dataframe weather_df2, prior to calling the rain_condition function, I've modified it to instead generate the dataframe that will then be styled later on.\nI've modified the function make_pretty so that it converts pandas.Series or pandas.DataFrame objects to pandas.Styler, in order to make it more robust.\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074480950_pandas_python.txt
Q: How does QuantLib forwardRate function work? I'm looking to find the expected interest rates for some period in the future based on the term structure of government bonds in python. I'm trying to use this code as a base: http://gouthamanbalaraman.com/blog/quantlib-term-structure-bootstrap-yield-curve.html I was hoping that this is what the forwardRate() function would do. But if I call: yieldcurve.forwardRate(d, d+ ql.Period("1Y"), day_count, compounding, freq).rate() The resulting rate is unreasonably high - above the rates anytime in that one year period. An I misunderstanding what forwardRate is supposed to do / doing something wrong here / is there another way to get this value easily? A: Based on that code it sounds like you're looking to calculate the 1Y forward rate for a particular date d. The forwardRate() method you mentioned should do just that, but check that the daycount and compounding are consistent with your yield curve definition since those can cause forward rates to look odd. Otherwise if the yield curve is upward sloping, it shouldn't be surprising that some forward rates are higher than any of the spot or par rates. That's just a consequence of the term structure.
How does QuantLib forwardRate function work?
I'm looking to find the expected interest rates for some period in the future based on the term structure of government bonds in python. I'm trying to use this code as a base: http://gouthamanbalaraman.com/blog/quantlib-term-structure-bootstrap-yield-curve.html I was hoping that this is what the forwardRate() function would do. But if I call: yieldcurve.forwardRate(d, d+ ql.Period("1Y"), day_count, compounding, freq).rate() The resulting rate is unreasonably high - above the rates anytime in that one year period. An I misunderstanding what forwardRate is supposed to do / doing something wrong here / is there another way to get this value easily?
[ "Based on that code it sounds like you're looking to calculate the 1Y forward rate for a particular date d. The forwardRate() method you mentioned should do just that, but check that the daycount and compounding are consistent with your yield curve definition since those can cause forward rates to look odd.\nOtherwise if the yield curve is upward sloping, it shouldn't be surprising that some forward rates are higher than any of the spot or par rates. That's just a consequence of the term structure.\n" ]
[ 1 ]
[]
[]
[ "python", "quantlib" ]
stackoverflow_0074437250_python_quantlib.txt
Q: plotly.py layout images - hover events In plotly python, is it possible to trigger a hover event for images in your plot? I have a plot with a layout image. I would like to detect if the user hovers the mouse over the image. example plot with image: fig = go.Figure() fig.add_trace( go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]) ) fig.add_layout_image( dict( source="https://images.plot.ly/language-icons/api-home/python-logo.png", xref="x", yref="y", x=0, y=3, sizex=2, sizey=2, sizing="stretch", opacity=0.5, layer="below") ) fig.show() References: • I've found hover events for plotly.js: https://plotly.com/javascript/hover-events/ • I see a hover example here: https://plotly.com/python/v3/cars-exploration/ but it does not work the way I intend, but perhaps it can be? scatter = fig.data[0] def hover_fn(trace, points, state): ind = points.point_inds[0] details.value = cars_df.iloc[ind].to_frame().to_html() scatter.on_hover(hover_fn) For instance, can I call something like: def hover_fn(): print("hello world") my_image = fig.data[layout_image] my_image.on_hover(hover_fn) A: I'm going to start out with code and explanation; at the end of this answer, I've added all of the code again in one chunk. As far as I know, as long as it's a layout object, there is no simple method of instituting hover content. If you would like hover content, then instead of a layout object, make it a trace. There is one major difference between images in the layout and images in a trace. In a trace, you have to encode the image to base64. When it's in the layout, Plotly does it for you. (Why?? GREAT QUESTION!!! I can tell you it's the same in other programming languages.) The first step: encode the image for the trace. import plotly.graph_objects as go import base64 from io import BytesIO from urllib.request import urlopen # read url url = urlopen("https://images.plot.ly/language-icons/api-home/python-logo.png") pref = "data:image/png;base64," # prefix for Javascript # transcribe binary bytes into base64 UTF-8 aimg = pref + base64.b64encode((BytesIO(url.read())).getvalue()).decode('utf8') When you add images as a trace, it automatically flips the y-axis. So, to prevent issues with the other trace, I have annotated a second y-axis. fig = go.Figure().set_subplots(specs = [[{"secondary_y": True}]]) The traces. By the way, the order in which you code them is the order they are layered. So if you want the image on the bottom, add that trace first. fig.add_trace( go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]), secondary_y = False ) # size of image 100 x 100 with dx & dy at .03, reduce size to 3% of original fig.add_trace(go.Image(source = aimg, x0 = 0, y0 = 0, dx = .03, dy = .03, opacity = .5, hoverinfo = "all", zsmooth = 'fast', name = "Python symbol"), secondary_y = True) So that the image isn't skewed and the different axes are all aligned, I've added specifications for the axes to square it all up. I also hid the labels for the second y-axis. fig.update_xaxes(range = [-.5, 3.5], constrain = "domain") fig.update_yaxes(scaleanchor = "x", scaleratio = 1, secondary_y = False, range = [-.5, 3.5]) fig.update_yaxes(title = "", secondary_y = True, scaleratio = 1, scaleanchor = "x", showticklabels = False, range = [3.5, -.5]) All the code altogether: import plotly.graph_objects as go import base64 from io import BytesIO from urllib.request import urlopen # read url url = urlopen("https://images.plot.ly/language-icons/api-home/python-logo.png") pref = "data:image/png;base64," # prefix for Javascript # transcribe binary bytes into base64 UTF-8 aimg = pref + base64.b64encode((BytesIO(url.read())).getvalue()).decode('utf8') fig = go.Figure().set_subplots(specs = [[{"secondary_y": True}]]) fig.add_trace( go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]), secondary_y = False ) fig.add_trace(go.Image(source = aimg, x0 = 0, y0 = 0, dx = .03, dy = .03, opacity = .5, hoverinfo = "all", zsmooth = 'fast', name = "Python symbol"), secondary_y = True) fig.update_xaxes(range = [-.5, 3.5], constrain = "domain") fig.update_yaxes(scaleanchor = "x", scaleratio = 1, secondary_y = False, range = [-.5, 3.5]) fig.update_yaxes(title = "", secondary_y = True, scaleratio = 1, scaleanchor = "x", showticklabels = False, range = [3.5, -.5]) fig.show()
plotly.py layout images - hover events
In plotly python, is it possible to trigger a hover event for images in your plot? I have a plot with a layout image. I would like to detect if the user hovers the mouse over the image. example plot with image: fig = go.Figure() fig.add_trace( go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]) ) fig.add_layout_image( dict( source="https://images.plot.ly/language-icons/api-home/python-logo.png", xref="x", yref="y", x=0, y=3, sizex=2, sizey=2, sizing="stretch", opacity=0.5, layer="below") ) fig.show() References: • I've found hover events for plotly.js: https://plotly.com/javascript/hover-events/ • I see a hover example here: https://plotly.com/python/v3/cars-exploration/ but it does not work the way I intend, but perhaps it can be? scatter = fig.data[0] def hover_fn(trace, points, state): ind = points.point_inds[0] details.value = cars_df.iloc[ind].to_frame().to_html() scatter.on_hover(hover_fn) For instance, can I call something like: def hover_fn(): print("hello world") my_image = fig.data[layout_image] my_image.on_hover(hover_fn)
[ "I'm going to start out with code and explanation; at the end of this answer, I've added all of the code again in one chunk.\nAs far as I know, as long as it's a layout object, there is no simple method of instituting hover content. If you would like hover content, then instead of a layout object, make it a trace.\nThere is one major difference between images in the layout and images in a trace. In a trace, you have to encode the image to base64. When it's in the layout, Plotly does it for you. (Why?? GREAT QUESTION!!! I can tell you it's the same in other programming languages.)\nThe first step: encode the image for the trace.\nimport plotly.graph_objects as go\nimport base64\nfrom io import BytesIO\nfrom urllib.request import urlopen\n\n# read url\nurl = urlopen(\"https://images.plot.ly/language-icons/api-home/python-logo.png\")\npref = \"data:image/png;base64,\" # prefix for Javascript\n# transcribe binary bytes into base64 UTF-8\naimg = pref + base64.b64encode((BytesIO(url.read())).getvalue()).decode('utf8')\n\nWhen you add images as a trace, it automatically flips the y-axis. So, to prevent issues with the other trace, I have annotated a second y-axis.\nfig = go.Figure().set_subplots(specs = [[{\"secondary_y\": True}]])\n\nThe traces. By the way, the order in which you code them is the order they are layered. So if you want the image on the bottom, add that trace first.\nfig.add_trace(\n go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]),\n secondary_y = False\n)\n# size of image 100 x 100 with dx & dy at .03, reduce size to 3% of original\nfig.add_trace(go.Image(source = aimg, x0 = 0, y0 = 0, dx = .03, dy = .03,\n opacity = .5, hoverinfo = \"all\", zsmooth = 'fast',\n name = \"Python symbol\"),\n secondary_y = True)\n\nSo that the image isn't skewed and the different axes are all aligned, I've added specifications for the axes to square it all up. I also hid the labels for the second y-axis.\nfig.update_xaxes(range = [-.5, 3.5], constrain = \"domain\")\nfig.update_yaxes(scaleanchor = \"x\", scaleratio = 1, \n secondary_y = False, range = [-.5, 3.5])\nfig.update_yaxes(title = \"\", secondary_y = True, scaleratio = 1, scaleanchor = \"x\", \n showticklabels = False, range = [3.5, -.5])\n\n\n\n\nAll the code altogether:\nimport plotly.graph_objects as go\nimport base64\nfrom io import BytesIO\nfrom urllib.request import urlopen\n\n# read url\nurl = urlopen(\"https://images.plot.ly/language-icons/api-home/python-logo.png\")\npref = \"data:image/png;base64,\" # prefix for Javascript\n# transcribe binary bytes into base64 UTF-8\naimg = pref + base64.b64encode((BytesIO(url.read())).getvalue()).decode('utf8')\n\nfig = go.Figure().set_subplots(specs = [[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1]),\n secondary_y = False\n)\n\nfig.add_trace(go.Image(source = aimg, x0 = 0, y0 = 0, dx = .03, dy = .03,\n opacity = .5, hoverinfo = \"all\", zsmooth = 'fast',\n name = \"Python symbol\"),\n secondary_y = True)\n\n\nfig.update_xaxes(range = [-.5, 3.5], constrain = \"domain\")\nfig.update_yaxes(scaleanchor = \"x\", scaleratio = 1, \n secondary_y = False, range = [-.5, 3.5])\nfig.update_yaxes(title = \"\", secondary_y = True, scaleratio = 1, scaleanchor = \"x\", \n showticklabels = False, range = [3.5, -.5])\n\nfig.show()\n\n" ]
[ 0 ]
[]
[]
[ "hover", "image", "javascript", "plotly", "python" ]
stackoverflow_0074479798_hover_image_javascript_plotly_python.txt
Q: Multiplying a multi index dataframe with single index dataframe I have a dataframe "A" which is multi indexed shown below LL SK Di Co Bracket yr_wk 1 121 2 2 4 3 122 3 6 5 4 123 3 2 6 2 124 2 5 5 3 125 3 5 6 3 2 121 4 7 1 6 122 1 5 1 7 123 3 9 6 4 124 5 1 5 6 125 8 7 7 2 Another dataframe "B" which is single index Factor yr_wk 121 0.98 122 1.045 123 0.92 124 0.99 125 0.95 I am trying to multiple the factor column of dataframe B with columns of A, grouped by the yr_wk column. Below is the resultant dataframe which I am trying to calculate LL SK Di Co Bracket yr_wk 1 121 2*0.98 2*0.98 4*0.98 3*0.98 122 3*1.045 6*1.045 5*1.045 4*1.045 123 3*0.92 2*0.92 6*0.92 2*0.92 124 2*0.99 5*0.99 5*0.99 3*0.99 125 3*0.95 5*0.95 6*0.95 3*0.95 2 121 4*0.98 7*0.98 1*0.98 6*0.98 122 1*1.045 5*1.045 1*1.045 7*1.045 123 3*0.92 9*0.92 6*0.92 4*0.92 124 5*0.99 1*0.99 5*0.99 6*0.99 125 8*0.95 7*0.95 7*0.95 2*0.95 Below is what I tried but it is not working because I am messing up the index C= A.multiply(B) A: import pandas as pd df = pd.DataFrame({'yr_wk': [121, 122,123], 'LL': [2, 3, 3], 'SK':[2,6,2]}) df2 = pd.DataFrame({'yr_wk': [121, 122,123], 'Factor': [0.98, 1.045, 0.92]}) df = df.merge(df2, on = 'yr_wk') for key in ['LL', 'SK']: df[key] = df[key] * df['Factor'] df = df.drop('Factor', axis=1) df A: try this: factor = dfA.merge( dfB, how='left', left_on=dfA.index.get_level_values(1), right_index=True)['Factor'] result = dfA.mul(factor, axis=0) print(result) >>> LL SK Di Co Bracket yr_wk 1 121 1.960 1.960 3.920 2.940 122 3.135 6.270 5.225 4.180 123 2.760 1.840 5.520 1.840 124 1.980 4.950 4.950 2.970 125 2.850 4.750 5.700 2.850 2 121 3.920 6.860 0.980 5.880 122 1.045 5.225 1.045 7.315 123 2.760 8.280 5.520 3.680 124 4.950 0.990 4.950 5.940 125 7.600 6.650 6.650 1.900 A: First use broad casting df_A.unstack(0).mul(df_B['Factor'], axis=0).stack() LL SK Di Co yr_wk Bracket 121 1 1.96 1.96 3.92 2.94 2 3.92 6.86 0.98 5.88 122 1 3.13 6.27 5.22 4.18 2 1.04 5.22 1.04 7.31 123 1 2.76 1.84 5.52 1.84 2 2.76 8.28 5.52 3.68 124 1 1.98 4.95 4.95 2.97 2 4.95 0.99 4.95 5.94 125 1 2.85 4.75 5.70 2.85 2 7.60 6.65 6.65 1.90 Second swaplevel and sort_index to make desired output (include First Code) df_A.unstack(0).mul(df_B['Factor'], axis=0).stack().swaplevel(0, 1).sort_index() output: LL SK Di Co Bracket yr_wk 1 121 1.96 1.96 3.92 2.94 122 3.13 6.27 5.22 4.18 123 2.76 1.84 5.52 1.84 124 1.98 4.95 4.95 2.97 125 2.85 4.75 5.70 2.85 2 121 3.92 6.86 0.98 5.88 122 1.04 5.22 1.04 7.31 123 2.76 8.28 5.52 3.68 124 4.95 0.99 4.95 5.94 125 7.60 6.65 6.65 1.90
Multiplying a multi index dataframe with single index dataframe
I have a dataframe "A" which is multi indexed shown below LL SK Di Co Bracket yr_wk 1 121 2 2 4 3 122 3 6 5 4 123 3 2 6 2 124 2 5 5 3 125 3 5 6 3 2 121 4 7 1 6 122 1 5 1 7 123 3 9 6 4 124 5 1 5 6 125 8 7 7 2 Another dataframe "B" which is single index Factor yr_wk 121 0.98 122 1.045 123 0.92 124 0.99 125 0.95 I am trying to multiple the factor column of dataframe B with columns of A, grouped by the yr_wk column. Below is the resultant dataframe which I am trying to calculate LL SK Di Co Bracket yr_wk 1 121 2*0.98 2*0.98 4*0.98 3*0.98 122 3*1.045 6*1.045 5*1.045 4*1.045 123 3*0.92 2*0.92 6*0.92 2*0.92 124 2*0.99 5*0.99 5*0.99 3*0.99 125 3*0.95 5*0.95 6*0.95 3*0.95 2 121 4*0.98 7*0.98 1*0.98 6*0.98 122 1*1.045 5*1.045 1*1.045 7*1.045 123 3*0.92 9*0.92 6*0.92 4*0.92 124 5*0.99 1*0.99 5*0.99 6*0.99 125 8*0.95 7*0.95 7*0.95 2*0.95 Below is what I tried but it is not working because I am messing up the index C= A.multiply(B)
[ "import pandas as pd\ndf = pd.DataFrame({'yr_wk': [121, 122,123], 'LL': [2, 3, 3], 'SK':[2,6,2]})\ndf2 = pd.DataFrame({'yr_wk': [121, 122,123], 'Factor': [0.98, 1.045, 0.92]})\ndf = df.merge(df2, on = 'yr_wk')\nfor key in ['LL', 'SK']:\n df[key] = df[key] * df['Factor']\ndf = df.drop('Factor', axis=1)\ndf\n\n", "try this:\nfactor = dfA.merge(\n dfB, \n how='left', \n left_on=dfA.index.get_level_values(1), \n right_index=True)['Factor']\n\nresult = dfA.mul(factor, axis=0)\nprint(result)\n>>>\n LL SK Di Co\nBracket yr_wk \n1 121 1.960 1.960 3.920 2.940\n 122 3.135 6.270 5.225 4.180\n 123 2.760 1.840 5.520 1.840\n 124 1.980 4.950 4.950 2.970\n 125 2.850 4.750 5.700 2.850\n2 121 3.920 6.860 0.980 5.880\n 122 1.045 5.225 1.045 7.315\n 123 2.760 8.280 5.520 3.680\n 124 4.950 0.990 4.950 5.940\n 125 7.600 6.650 6.650 1.900\n\n", "First\nuse broad casting\ndf_A.unstack(0).mul(df_B['Factor'], axis=0).stack()\n\n LL SK Di Co\nyr_wk Bracket \n121 1 1.96 1.96 3.92 2.94\n 2 3.92 6.86 0.98 5.88\n122 1 3.13 6.27 5.22 4.18\n 2 1.04 5.22 1.04 7.31\n123 1 2.76 1.84 5.52 1.84\n 2 2.76 8.28 5.52 3.68\n124 1 1.98 4.95 4.95 2.97\n 2 4.95 0.99 4.95 5.94\n125 1 2.85 4.75 5.70 2.85\n 2 7.60 6.65 6.65 1.90\n\n\nSecond\nswaplevel and sort_index to make desired output (include First Code)\ndf_A.unstack(0).mul(df_B['Factor'], axis=0).stack().swaplevel(0, 1).sort_index()\n\noutput:\n LL SK Di Co\nBracket yr_wk \n1 121 1.96 1.96 3.92 2.94\n 122 3.13 6.27 5.22 4.18\n 123 2.76 1.84 5.52 1.84\n 124 1.98 4.95 4.95 2.97\n 125 2.85 4.75 5.70 2.85\n2 121 3.92 6.86 0.98 5.88\n 122 1.04 5.22 1.04 7.31\n 123 2.76 8.28 5.52 3.68\n 124 4.95 0.99 4.95 5.94\n 125 7.60 6.65 6.65 1.90\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "multi_index", "pandas", "python" ]
stackoverflow_0074484077_multi_index_pandas_python.txt
Q: How to Configure Poetry Environments in Pycharm With Windows + WSL2? TL;DR: can't configure a Python Interpreter on PyCharm (Windows) using an existing Poetry environment in WSL. When trying to set the Poetry environment path under Add Python Interpreter > Poetry Environment > Existing Environment, the needed Python executable simply does not show. What am I doing wrong? ==================================================== Details: I'm using PyCharm Pro 2021.3 on Windows 11, with Python running on WSL2 (Ubuntu 20.04). I am trying to add a python interpreter for an existing Poetry environment I created on WSL2, and it just does not seem to work. PyCharm's current support of Poetry is via adopting this plugin. From what I could gather from the plugin's official documentation, in order to define an interpreter with an existing Poetry environment, I go to Python Interpreter > Add > Poetry Environment, choose Existing environment, and put in the path to that specific environment: In order to find the path to that environment, I run "poetry env info", which gives a path in the following pattern: \\wsl$\Ubuntu-20.04\home\$USER$\.cache\pypoetry\virtualenvs\my-pretty-project-<some-hash>-py3.8\ When running which python in the environment, I see the python executable is at: \\wsl$\Ubuntu-20.04\home\$USER$\.cache\pypoetry\virtualenvs\my-pretty-project-<some-hash>-py3.8\bin\python However - when I browse to that location in PyCharm, the Python file simple does not show. The bin directory appears as empty - as also described in this question. However - and similarly to what described in said question - if I try to redefine the default interpreter path for WSL to be the path to that Poetry environment, the Python executable is there and kicking: (The solution described in the aforementioned question, sadly, does not work for my problem, as I am already using the patch to the Poetry environment). What can I do to make this work? A: Let me get this straight: You want PyCharm for Windows to execute Python binaries in WSL? That cannot happen. Binaries in WSL are "ELF" binaries which Windows cannot execute (outside WSL). If the virtualenv was created by poetry from within WSL, it will contain ELF Python binaries. And that is why PyCharm for Windows won't ever pick it up. Because ultimately PyCharm for Windows relies on Windows to execute the binaries, as long as you don't choose the WSL option. Explicitly selecting the "WSL" option indicates to PyCharm that for this particular virtualenv you want PyCharm to invoke the binaries using WSL. The solution is either to re-create the virtualenv in Windows, or just use the "WSL" option but you have to manage the poetry manually via WSL shell.
How to Configure Poetry Environments in Pycharm With Windows + WSL2?
TL;DR: can't configure a Python Interpreter on PyCharm (Windows) using an existing Poetry environment in WSL. When trying to set the Poetry environment path under Add Python Interpreter > Poetry Environment > Existing Environment, the needed Python executable simply does not show. What am I doing wrong? ==================================================== Details: I'm using PyCharm Pro 2021.3 on Windows 11, with Python running on WSL2 (Ubuntu 20.04). I am trying to add a python interpreter for an existing Poetry environment I created on WSL2, and it just does not seem to work. PyCharm's current support of Poetry is via adopting this plugin. From what I could gather from the plugin's official documentation, in order to define an interpreter with an existing Poetry environment, I go to Python Interpreter > Add > Poetry Environment, choose Existing environment, and put in the path to that specific environment: In order to find the path to that environment, I run "poetry env info", which gives a path in the following pattern: \\wsl$\Ubuntu-20.04\home\$USER$\.cache\pypoetry\virtualenvs\my-pretty-project-<some-hash>-py3.8\ When running which python in the environment, I see the python executable is at: \\wsl$\Ubuntu-20.04\home\$USER$\.cache\pypoetry\virtualenvs\my-pretty-project-<some-hash>-py3.8\bin\python However - when I browse to that location in PyCharm, the Python file simple does not show. The bin directory appears as empty - as also described in this question. However - and similarly to what described in said question - if I try to redefine the default interpreter path for WSL to be the path to that Poetry environment, the Python executable is there and kicking: (The solution described in the aforementioned question, sadly, does not work for my problem, as I am already using the patch to the Poetry environment). What can I do to make this work?
[ "Let me get this straight: You want PyCharm for Windows to execute Python binaries in WSL?\nThat cannot happen.\nBinaries in WSL are \"ELF\" binaries which Windows cannot execute (outside WSL). If the virtualenv was created by poetry from within WSL, it will contain ELF Python binaries. And that is why PyCharm for Windows won't ever pick it up. Because ultimately PyCharm for Windows relies on Windows to execute the binaries, as long as you don't choose the WSL option.\nExplicitly selecting the \"WSL\" option indicates to PyCharm that for this particular virtualenv you want PyCharm to invoke the binaries using WSL.\nThe solution is either to re-create the virtualenv in Windows, or just use the \"WSL\" option but you have to manage the poetry manually via WSL shell.\n" ]
[ 0 ]
[]
[]
[ "pycharm", "python", "python_poetry", "ubuntu_20.04", "wsl_2" ]
stackoverflow_0070205270_pycharm_python_python_poetry_ubuntu_20.04_wsl_2.txt
Q: How can I read a function's signature including default argument values? Given a function object, how can I get its signature? For example, for: def my_method(first, second, third='something'): pass I would like to get "my_method(first, second, third='something')". A: import inspect def foo(a, b, x='blah'): pass print(inspect.signature(foo)) # (a, b, x='blah') Python 3.5+ recommends inspect.signature(). A: Arguably the easiest way to find the signature for a function would be help(function): >>> def function(arg1, arg2="foo", *args, **kwargs): pass >>> help(function) Help on function function in module __main__: function(arg1, arg2='foo', *args, **kwargs) Also, in Python 3 a method was added to the inspect module called signature, which is designed to represent the signature of a callable object and its return annotation: >>> from inspect import signature >>> def foo(a, *, b:int, **kwargs): ... pass >>> sig = signature(foo) >>> str(sig) '(a, *, b:int, **kwargs)' >>> str(sig.parameters['b']) 'b:int' >>> sig.parameters['b'].annotation <class 'int'> A: #! /usr/bin/env python import inspect from collections import namedtuple DefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value') def _get_default_arg(args, defaults, arg_index): """ Method that determines if an argument has default value or not, and if yes what is the default value for the argument :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg'] :param defaults: array of default values, eg: (42, 'something') :param arg_index: index of the argument in the argument array for which, this function checks if a default value exists or not. And if default value exists it would return the default value. Example argument: 1 :return: Tuple of whether there is a default or not, and if yes the default value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42) """ if not defaults: return DefaultArgSpec(False, None) args_with_no_defaults = len(args) - len(defaults) if arg_index < args_with_no_defaults: return DefaultArgSpec(False, None) else: value = defaults[arg_index - args_with_no_defaults] if (type(value) is str): value = '"%s"' % value return DefaultArgSpec(True, value) def get_method_sig(method): """ Given a function, it returns a string that pretty much looks how the function signature would be written in python. :param method: a python method :return: A string similar describing the pythong method signature. eg: "my_method(first_argArg, second_arg=42, third_arg='something')" """ # The return value of ArgSpec is a bit weird, as the list of arguments and # list of defaults are returned in separate array. # eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'], # varargs=None, keywords=None, defaults=(42, 'something')) argspec = inspect.getargspec(method) arg_index=0 args = [] # Use the args and defaults array returned by argspec and find out # which arguments has default for arg in argspec.args: default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index) if default_arg.has_default: args.append("%s=%s" % (arg, default_arg.default_value)) else: args.append(arg) arg_index += 1 return "%s(%s)" % (method.__name__, ", ".join(args)) if __name__ == '__main__': def my_method(first_arg, second_arg=42, third_arg='something'): pass print get_method_sig(my_method) # my_method(first_argArg, second_arg=42, third_arg="something") A: Try calling help on an object to find out about it. >>> foo = [1, 2, 3] >>> help(foo.append) Help on built-in function append: append(...) L.append(object) -- append object to end A: Maybe a bit late to the party, but if you also want to keep the order of the arguments and their defaults, then you can use the Abstract Syntax Tree module (ast). Here's a proof of concept (beware the code to sort the arguments and match them to their defaults can definitely be improved/made more clear): import ast for class_ in [c for c in module.body if isinstance(c, ast.ClassDef)]: for method in [m for m in class_.body if isinstance(m, ast.FunctionDef)]: args = [] if method.args.args: [args.append([a.col_offset, a.id]) for a in method.args.args] if method.args.defaults: [args.append([a.col_offset, '=' + a.id]) for a in method.args.defaults] sorted_args = sorted(args) for i, p in enumerate(sorted_args): if p[1].startswith('='): sorted_args[i-1][1] += p[1] sorted_args = [k[1] for k in sorted_args if not k[1].startswith('=')] if method.args.vararg: sorted_args.append('*' + method.args.vararg) if method.args.kwarg: sorted_args.append('**' + method.args.kwarg) signature = '(' + ', '.join(sorted_args) + ')' print method.name + signature A: Use %pdef in the command line (IPython), it will print only the signature. e.g. %pdef np.loadtxt np.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes') A: If all you're trying to do is print the function then use pydoc. import pydoc def foo(arg1, arg2, *args, **kwargs): '''Some foo fn''' pass >>> print pydoc.render_doc(foo).splitlines()[2] foo(arg1, arg2, *args, **kwargs) If you're trying to actually analyze the function signature then use argspec of the inspection module. I had to do that when validating a user's hook script function into a general framework. A: Example code: import inspect from collections import OrderedDict def get_signature(fn): params = inspect.signature(fn).parameters args = [] kwargs = OrderedDict() for p in params.values(): if p.default is p.empty: args.append(p.name) else: kwargs[p.name] = p.default return args, kwargs def test_sig(): def fn(a, b, c, d=3, e="abc"): pass assert get_signature(fn) == ( ["a", "b", "c"], OrderedDict([("d", 3), ("e", "abc")]) ) A: Another late entry. My point isn't to, again, print the sig, or display help. It is to programmatically introspect function parameters (when I got to this question I was looking to check Django view functions by looking at functions with request as a first parameter name). The key is the Signature.parameters attribute, which is actually not that complicated (note that inspect._empty is akin to None in concept). import inspect from typing import Any, cast def check_signature(func : "Callable") -> None: funcname = func.__name__ try: # class inspect.Signature(parameters=None, *, return_annotation=Signature.empty) # see https://docs.python.org/3/library/inspect.html#inspect.Signature sig = inspect.signature(func) except (ValueError,) as e: print(f"\n\n`{funcname}` has no signature") return print(f"\n\n`{funcname}{sig}` parameters:") for position, (name,param) in enumerate(sig.parameters.items()): # class inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty) # see https://docs.python.org/3/library/inspect.html#inspect.Parameter print(f" {position} {name:30.30} kind={param.kind.description.replace(' ','_')} / default={param.default if param.default is not inspect._empty else ''} / annotation={param.annotation if param.annotation is not inspect._empty else ''}") class Foo: def bar(self, zoom : int =2): pass for func in [Any, check_signature, print, Foo.bar, Foo().bar, isinstance, issubclass, cast]: check_signature(func) output: `Any(*args, **kwds)` parameters: 0 args kind=variadic_positional / default= / annotation= 1 kwds kind=variadic_keyword / default= / annotation= `check_signature(func: 'Callable') -> None` parameters: 0 func kind=positional_or_keyword / default= / annotation=Callable `print` has no signature `bar(self, zoom: int = 2)` parameters: 0 self kind=positional_or_keyword / default= / annotation= 1 zoom kind=positional_or_keyword / default=2 / annotation=<class 'int'> `bar(zoom: int = 2)` parameters: 0 zoom kind=positional_or_keyword / default=2 / annotation=<class 'int'> `isinstance(obj, class_or_tuple, /)` parameters: 0 obj kind=positional-only / default= / annotation= 1 class_or_tuple kind=positional-only / default= / annotation= `issubclass(cls, class_or_tuple, /)` parameters: 0 cls kind=positional-only / default= / annotation= 1 class_or_tuple kind=positional-only / default= / annotation= `cast(typ, val)` parameters: 0 typ kind=positional_or_keyword / default= / annotation= 1 val kind=positional_or_keyword / default= / annotation= In the OP's case you'd just check for param.default is not inspect._empty. I'd opt for returning a dict[str, Any] of those. To make things a bit easier on myself, I went and added a pydantic wrapper to the whole thing: class FuncSignature(BaseModel): class Config: arbitrary_types_allowed = True funcname: str sig : inspect.Signature by_pos : dict[int,inspect.Parameter] by_name: dict[str,inspect.Parameter] undefined = inspect._empty def get_signature(func : "Callable") -> FuncSignature: """return signature for a function""" funcname = func.__name__ sig = inspect.signature(func) by_name, by_pos = {},{} for position, (name,param) in enumerate(sig.parameters.items()): by_name[name] = param by_pos[position] = param return FuncSignature(funcname=funcname, sig=sig,by_name=by_name,by_pos=by_pos) which allowed me to def myview(request, rdbname): pass res = check_signature(myview) print(res.by_pos[0].name == "request") # True
How can I read a function's signature including default argument values?
Given a function object, how can I get its signature? For example, for: def my_method(first, second, third='something'): pass I would like to get "my_method(first, second, third='something')".
[ "import inspect\n\ndef foo(a, b, x='blah'):\n pass\n\nprint(inspect.signature(foo))\n# (a, b, x='blah')\n\nPython 3.5+ recommends inspect.signature().\n", "Arguably the easiest way to find the signature for a function would be help(function):\n>>> def function(arg1, arg2=\"foo\", *args, **kwargs): pass\n>>> help(function)\nHelp on function function in module __main__:\n\nfunction(arg1, arg2='foo', *args, **kwargs)\n\nAlso, in Python 3 a method was added to the inspect module called signature, which is designed to represent the signature of a callable object and its return annotation:\n>>> from inspect import signature\n>>> def foo(a, *, b:int, **kwargs):\n... pass\n\n>>> sig = signature(foo)\n\n>>> str(sig)\n'(a, *, b:int, **kwargs)'\n\n>>> str(sig.parameters['b'])\n'b:int'\n\n>>> sig.parameters['b'].annotation\n<class 'int'>\n\n", "#! /usr/bin/env python\n\nimport inspect\nfrom collections import namedtuple\n\nDefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value')\n\ndef _get_default_arg(args, defaults, arg_index):\n \"\"\" Method that determines if an argument has default value or not,\n and if yes what is the default value for the argument\n\n :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']\n :param defaults: array of default values, eg: (42, 'something')\n :param arg_index: index of the argument in the argument array for which,\n this function checks if a default value exists or not. And if default value\n exists it would return the default value. Example argument: 1\n :return: Tuple of whether there is a default or not, and if yes the default\n value, eg: for index 2 i.e. for \"second_arg\" this function returns (True, 42)\n \"\"\"\n if not defaults:\n return DefaultArgSpec(False, None)\n\n args_with_no_defaults = len(args) - len(defaults)\n\n if arg_index < args_with_no_defaults:\n return DefaultArgSpec(False, None)\n else:\n value = defaults[arg_index - args_with_no_defaults]\n if (type(value) is str):\n value = '\"%s\"' % value\n return DefaultArgSpec(True, value)\n\ndef get_method_sig(method):\n \"\"\" Given a function, it returns a string that pretty much looks how the\n function signature would be written in python.\n\n :param method: a python method\n :return: A string similar describing the pythong method signature.\n eg: \"my_method(first_argArg, second_arg=42, third_arg='something')\"\n \"\"\"\n\n # The return value of ArgSpec is a bit weird, as the list of arguments and\n # list of defaults are returned in separate array.\n # eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],\n # varargs=None, keywords=None, defaults=(42, 'something'))\n argspec = inspect.getargspec(method)\n arg_index=0\n args = []\n\n # Use the args and defaults array returned by argspec and find out\n # which arguments has default\n for arg in argspec.args:\n default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)\n if default_arg.has_default:\n args.append(\"%s=%s\" % (arg, default_arg.default_value))\n else:\n args.append(arg)\n arg_index += 1\n return \"%s(%s)\" % (method.__name__, \", \".join(args))\n\n\nif __name__ == '__main__':\n def my_method(first_arg, second_arg=42, third_arg='something'):\n pass\n\n print get_method_sig(my_method)\n # my_method(first_argArg, second_arg=42, third_arg=\"something\")\n\n", "Try calling help on an object to find out about it.\n>>> foo = [1, 2, 3]\n>>> help(foo.append)\nHelp on built-in function append:\n\nappend(...)\n L.append(object) -- append object to end\n\n", "Maybe a bit late to the party, but if you also want to keep the order of the arguments and their defaults, then you can use the Abstract Syntax Tree module (ast).\nHere's a proof of concept (beware the code to sort the arguments and match them to their defaults can definitely be improved/made more clear):\nimport ast\n\nfor class_ in [c for c in module.body if isinstance(c, ast.ClassDef)]:\n for method in [m for m in class_.body if isinstance(m, ast.FunctionDef)]:\n args = []\n if method.args.args:\n [args.append([a.col_offset, a.id]) for a in method.args.args]\n if method.args.defaults:\n [args.append([a.col_offset, '=' + a.id]) for a in method.args.defaults]\n sorted_args = sorted(args)\n for i, p in enumerate(sorted_args):\n if p[1].startswith('='):\n sorted_args[i-1][1] += p[1]\n sorted_args = [k[1] for k in sorted_args if not k[1].startswith('=')]\n\n if method.args.vararg:\n sorted_args.append('*' + method.args.vararg)\n if method.args.kwarg:\n sorted_args.append('**' + method.args.kwarg)\n\n signature = '(' + ', '.join(sorted_args) + ')'\n\n print method.name + signature\n\n", "Use %pdef in the command line (IPython), it will print only the signature.\ne.g. %pdef np.loadtxt\n np.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes')\n\n", "If all you're trying to do is print the function then use pydoc.\nimport pydoc \n\ndef foo(arg1, arg2, *args, **kwargs): \n '''Some foo fn''' \n pass \n\n>>> print pydoc.render_doc(foo).splitlines()[2]\nfoo(arg1, arg2, *args, **kwargs)\n\nIf you're trying to actually analyze the function signature then use argspec of the inspection module. I had to do that when validating a user's hook script function into a general framework.\n", "Example code:\nimport inspect\nfrom collections import OrderedDict\n\n\ndef get_signature(fn):\n params = inspect.signature(fn).parameters\n args = []\n kwargs = OrderedDict()\n for p in params.values():\n if p.default is p.empty:\n args.append(p.name)\n else:\n kwargs[p.name] = p.default\n return args, kwargs\n\n\ndef test_sig():\n def fn(a, b, c, d=3, e=\"abc\"):\n pass\n\n assert get_signature(fn) == (\n [\"a\", \"b\", \"c\"], OrderedDict([(\"d\", 3), (\"e\", \"abc\")])\n )\n\n", "Another late entry. My point isn't to, again, print the sig, or display help. It is to programmatically introspect function parameters (when I got to this question I was looking to check Django view functions by looking at functions with request as a first parameter name).\nThe key is the Signature.parameters attribute, which is actually not that complicated (note that inspect._empty is akin to None in concept).\nimport inspect\nfrom typing import Any, cast\n\ndef check_signature(func : \"Callable\") -> None:\n funcname = func.__name__\n try:\n # class inspect.Signature(parameters=None, *, return_annotation=Signature.empty)\n # see https://docs.python.org/3/library/inspect.html#inspect.Signature\n sig = inspect.signature(func)\n except (ValueError,) as e: \n print(f\"\\n\\n`{funcname}` has no signature\")\n return\n \n print(f\"\\n\\n`{funcname}{sig}` parameters:\")\n for position, (name,param) in enumerate(sig.parameters.items()):\n # class inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)\n # see https://docs.python.org/3/library/inspect.html#inspect.Parameter\n print(f\" {position} {name:30.30} kind={param.kind.description.replace(' ','_')} / default={param.default if param.default is not inspect._empty else ''} / annotation={param.annotation if param.annotation is not inspect._empty else ''}\")\n\nclass Foo:\n def bar(self, zoom : int =2):\n pass\n\nfor func in [Any, check_signature, print, Foo.bar, Foo().bar, isinstance, issubclass, cast]:\n check_signature(func)\n\n\noutput:\n\n\n`Any(*args, **kwds)` parameters:\n 0 args kind=variadic_positional / default= / annotation=\n 1 kwds kind=variadic_keyword / default= / annotation=\n\n\n`check_signature(func: 'Callable') -> None` parameters:\n 0 func kind=positional_or_keyword / default= / annotation=Callable\n\n\n`print` has no signature\n\n\n`bar(self, zoom: int = 2)` parameters:\n 0 self kind=positional_or_keyword / default= / annotation=\n 1 zoom kind=positional_or_keyword / default=2 / annotation=<class 'int'>\n\n\n`bar(zoom: int = 2)` parameters:\n 0 zoom kind=positional_or_keyword / default=2 / annotation=<class 'int'>\n\n\n`isinstance(obj, class_or_tuple, /)` parameters:\n 0 obj kind=positional-only / default= / annotation=\n 1 class_or_tuple kind=positional-only / default= / annotation=\n\n\n`issubclass(cls, class_or_tuple, /)` parameters:\n 0 cls kind=positional-only / default= / annotation=\n 1 class_or_tuple kind=positional-only / default= / annotation=\n\n\n`cast(typ, val)` parameters:\n 0 typ kind=positional_or_keyword / default= / annotation=\n 1 val kind=positional_or_keyword / default= / annotation=\n\n\nIn the OP's case you'd just check for param.default is not inspect._empty. I'd opt for returning a dict[str, Any] of those.\nTo make things a bit easier on myself, I went and added a pydantic wrapper to the whole thing:\nclass FuncSignature(BaseModel):\n\n class Config:\n arbitrary_types_allowed = True\n\n funcname: str\n sig : inspect.Signature\n by_pos : dict[int,inspect.Parameter]\n by_name: dict[str,inspect.Parameter]\n\n undefined = inspect._empty\n\ndef get_signature(func : \"Callable\") -> FuncSignature:\n \"\"\"return signature for a function\"\"\"\n funcname = func.__name__\n sig = inspect.signature(func)\n by_name, by_pos = {},{}\n\n for position, (name,param) in enumerate(sig.parameters.items()):\n by_name[name] = param\n by_pos[position] = param\n\n return FuncSignature(funcname=funcname, sig=sig,by_name=by_name,by_pos=by_pos)\n\nwhich allowed me to\ndef myview(request, rdbname):\n pass\n\nres = check_signature(myview)\nprint(res.by_pos[0].name == \"request\") # True\n\n" ]
[ 237, 58, 15, 10, 8, 7, 6, 6, 0 ]
[]
[]
[ "arguments", "inspect", "python" ]
stackoverflow_0002677185_arguments_inspect_python.txt
Q: Video written through OpenCV on Raspberry Pi not running I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code import cv2 cap = cv2.VideoCapture(0) fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'') out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480)) while True: ret, frame = cap.read() cv2.imshow('frame', frame) out.write(frame) if cv2.waitKey(1) & 0xFF== ord('q'): break cap.release() cv2.destroyAllWindows() The video file is created but I am not able to run that file. I also tried with different formats like 'XVID','MJPG','H264' but faced the same issue. My opencv version is 4.3.038 A: There are two issues, I would like to address: Issue #1: DIVX should be declared as: fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') Issue #2: You have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480) frame = cv2.resize(frame, (640, 480)) But if you use it with DIVX you will have a warning: OpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v' Instead of DIVX use mp4v for creating .mp4 videos. Code: import cv2 cap = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') out = cv2.VideoWriter('output.mp4', fourcc, 25, (640, 480), isColor=True) while True: ret, frame = cap.read() frame = cv2.resize(frame, (640, 480)) cv2.imshow('frame', frame) out.write(frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() out.release() cv2.destroyAllWindows() A: You can try this code. Works for me import cv2 cap = cv2.VideoCapture(0) video_speed = 15 #This frame rate works well on my case video_name = 'output.avi' writer = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc('M','J','P','G'),video_speed, (640,480)) while True: ret , frame = cap.read() if ret == True: writer.writer(frame) cv2.imshow('Frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break else: break cap.release() writer.release() cv2.destroyAllWindows()
Video written through OpenCV on Raspberry Pi not running
I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code import cv2 cap = cv2.VideoCapture(0) fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'') out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480)) while True: ret, frame = cap.read() cv2.imshow('frame', frame) out.write(frame) if cv2.waitKey(1) & 0xFF== ord('q'): break cap.release() cv2.destroyAllWindows() The video file is created but I am not able to run that file. I also tried with different formats like 'XVID','MJPG','H264' but faced the same issue. My opencv version is 4.3.038
[ "There are two issues, I would like to address:\n\nIssue #1: DIVX should be declared as:\n\n\n\n\nfourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')\n\n\nIssue #2:\n\n\n\n\nYou have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480)\n\n\nframe = cv2.resize(frame, (640, 480))\n\n\n\nBut if you use it with DIVX you will have a warning:\nOpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)'\nOpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'\n\nInstead of DIVX use mp4v for creating .mp4 videos.\nCode:\n\nimport cv2\ncap = cv2.VideoCapture(0)\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\nout = cv2.VideoWriter('output.mp4', fourcc, 25, (640, 480), isColor=True)\nwhile True:\n ret, frame = cap.read()\n frame = cv2.resize(frame, (640, 480))\n cv2.imshow('frame', frame)\n out.write(frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n\n", "You can try this code. Works for me\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\nvideo_speed = 15 #This frame rate works well on my case\nvideo_name = 'output.avi'\nwriter = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc('M','J','P','G'),video_speed, (640,480))\n\nwhile True:\n ret , frame = cap.read()\n if ret == True:\n writer.writer(frame)\n cv2.imshow('Frame', frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n else:\n break\n\ncap.release()\nwriter.release()\ncv2.destroyAllWindows()\n\n" ]
[ 2, 0 ]
[]
[]
[ "live_streaming", "opencv", "python", "raspberry_pi4" ]
stackoverflow_0063873746_live_streaming_opencv_python_raspberry_pi4.txt
Q: Filter rows with consecutive numbers I have some data. I want to remain with rows when an ID has 4 consecutive numbers. For example, if ID 1 has rows 100, 101, 102, 103, 105, the "105" should be excluded. Data: ID X 0 1 100 1 1 101 2 1 102 3 1 103 4 1 105 5 2 100 6 2 102 7 2 103 8 2 104 9 3 100 10 3 101 11 3 102 12 3 103 13 3 106 14 3 107 15 3 108 16 3 109 17 3 110 18 3 112 19 4 100 20 4 102 21 4 103 22 4 104 23 4 105 24 4 107 Expected results: ID X 0 1 100 1 1 101 2 1 102 3 1 103 4 3 100 5 3 101 6 3 102 7 3 103 8 3 106 9 3 107 10 3 108 11 3 109 12 3 110 13 4 102 14 4 103 15 4 104 16 4 105 A: You can identify the consecutive values, then filter the groups by size with groupby.filter: # group consecutive X g = df['X'].diff().gt(1).cumsum() # no need to group here, we'll group later # filter groups out = df.groupby(['ID', g]).filter(lambda g: len(g)>=4)#.reset_index(drop=True) output: ID X 0 1 100 1 1 101 2 1 102 3 1 103 9 3 100 10 3 101 11 3 102 12 3 103 13 3 106 14 3 107 15 3 108 16 3 109 17 3 110 20 4 102 21 4 103 22 4 104 23 4 105 A: Another method: out = df.groupby(df.groupby('ID')['X'].diff().ne(1).cumsum()).filter(lambda x: len(x) >= 4) print(out) # Output ID X 0 1 100 1 1 101 2 1 102 3 1 103 9 3 100 10 3 101 11 3 102 12 3 103 13 3 106 14 3 107 15 3 108 16 3 109 17 3 110 20 4 102 21 4 103 22 4 104 23 4 105 A: def function1(dd:pd.DataFrame): return dd.assign(rk=(dd.assign(col1=(dd.X.diff()>1).cumsum()).groupby('col1').transform('size'))) df1.groupby('ID').apply(function1).loc[lambda x:x.rk>3,:'X'] ID X 0 1 100 1 1 101 2 1 102 3 1 103 9 3 100 10 3 101 11 3 102 12 3 103 13 3 106 14 3 107 15 3 108 16 3 109 17 3 110 20 4 102 21 4 103 22 4 104 23 4 105
Filter rows with consecutive numbers
I have some data. I want to remain with rows when an ID has 4 consecutive numbers. For example, if ID 1 has rows 100, 101, 102, 103, 105, the "105" should be excluded. Data: ID X 0 1 100 1 1 101 2 1 102 3 1 103 4 1 105 5 2 100 6 2 102 7 2 103 8 2 104 9 3 100 10 3 101 11 3 102 12 3 103 13 3 106 14 3 107 15 3 108 16 3 109 17 3 110 18 3 112 19 4 100 20 4 102 21 4 103 22 4 104 23 4 105 24 4 107 Expected results: ID X 0 1 100 1 1 101 2 1 102 3 1 103 4 3 100 5 3 101 6 3 102 7 3 103 8 3 106 9 3 107 10 3 108 11 3 109 12 3 110 13 4 102 14 4 103 15 4 104 16 4 105
[ "You can identify the consecutive values, then filter the groups by size with groupby.filter:\n# group consecutive X\ng = df['X'].diff().gt(1).cumsum() # no need to group here, we'll group later\n\n# filter groups\nout = df.groupby(['ID', g]).filter(lambda g: len(g)>=4)#.reset_index(drop=True)\n\noutput:\n ID X\n0 1 100\n1 1 101\n2 1 102\n3 1 103\n9 3 100\n10 3 101\n11 3 102\n12 3 103\n13 3 106\n14 3 107\n15 3 108\n16 3 109\n17 3 110\n20 4 102\n21 4 103\n22 4 104\n23 4 105\n\n", "Another method:\nout = df.groupby(df.groupby('ID')['X'].diff().ne(1).cumsum()).filter(lambda x: len(x) >= 4)\nprint(out)\n\n# Output\n ID X\n0 1 100\n1 1 101\n2 1 102\n3 1 103\n9 3 100\n10 3 101\n11 3 102\n12 3 103\n13 3 106\n14 3 107\n15 3 108\n16 3 109\n17 3 110\n20 4 102\n21 4 103\n22 4 104\n23 4 105\n\n", "def function1(dd:pd.DataFrame):\n return dd.assign(rk=(dd.assign(col1=(dd.X.diff()>1).cumsum()).groupby('col1').transform('size')))\ndf1.groupby('ID').apply(function1).loc[lambda x:x.rk>3,:'X']\n\n\n ID X\n0 1 100\n1 1 101\n2 1 102\n3 1 103\n9 3 100\n10 3 101\n11 3 102\n12 3 103\n13 3 106\n14 3 107\n15 3 108\n16 3 109\n17 3 110\n20 4 102\n21 4 103\n22 4 104\n23 4 105\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0073072372_pandas_python.txt
Q: How do I elegantly rename Pandas value counts output? I want to call df['item'].value_counts() and, with minimal manipulation, end up with a dataframe with columns item and count. I can do something like this: df['item'].value_counts().reset_index().rename(columns={"item":"count", "index": "item"}) ... which is fine but I'm like 95% sure there is a cleaner way to do this by passing a variable to reset_index or something similar A: Let us try with groupby df.groupby('item')['item'].count().reset_index(name='count') A: Using set_axis is very slightly cleaner. df['item'].value_counts().reset_index().set_axis(['item','count'], axis=1) A: Using groupby, value_counts, and to_frame import pandas as pd # 1.5.1 df = pd.DataFrame({"item": list("aaabbbbbbccc")}) counts = df.groupby("item").value_counts().to_frame("count").reset_index() print(counts) item count 0 a 3 1 b 6 2 c 3 using value_counts and to_frame counts = df["item"].value_counts().to_frame("count").reset_index(names="item") print(counts) item count 0 a 3 1 b 6 2 c 3 References to_frame df.reset_index calls for parameter names vs name in pd.Series.reset_index
How do I elegantly rename Pandas value counts output?
I want to call df['item'].value_counts() and, with minimal manipulation, end up with a dataframe with columns item and count. I can do something like this: df['item'].value_counts().reset_index().rename(columns={"item":"count", "index": "item"}) ... which is fine but I'm like 95% sure there is a cleaner way to do this by passing a variable to reset_index or something similar
[ "Let us try with groupby\ndf.groupby('item')['item'].count().reset_index(name='count')\n\n", "Using set_axis is very slightly cleaner.\ndf['item'].value_counts().reset_index().set_axis(['item','count'], axis=1)\n\n", "Using groupby, value_counts, and to_frame\nimport pandas as pd # 1.5.1\n\n\ndf = pd.DataFrame({\"item\": list(\"aaabbbbbbccc\")})\n\ncounts = df.groupby(\"item\").value_counts().to_frame(\"count\").reset_index()\n\nprint(counts)\n\n item count\n0 a 3\n1 b 6\n2 c 3\n\nusing value_counts and to_frame\ncounts = df[\"item\"].value_counts().to_frame(\"count\").reset_index(names=\"item\")\n\nprint(counts)\n\n item count\n0 a 3\n1 b 6\n2 c 3\n\nReferences\nto_frame\ndf.reset_index calls for parameter names vs name in pd.Series.reset_index\n" ]
[ 2, 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074484322_pandas_python.txt
Q: Prediction for horse racing scikit learn - multiple rows per race Goal I want to train a model with Scikit-learn that predicts the outcome of horse races. I have a CSV file that includes multiple features like position, age, weight, horse_name, race_id etc. Problem In my original CSV file each horse is represented in one row. With positions from 1-8 each race consists of 8 rows. When I train my model however, the model looks at each row as an individual event (race) and therefore does not perform well. Approach I tried to solve this issue and created a new CSV file in which each row represents one race and the features go from position1, age1, weight1, horse_name1, race_id1 to position8, age8, weight8, horse_name8, race_id8 (see below). However, using a Multioutput in this case my model does not train at all but notices that age1, weight1 are the columns of the winner and does get 100 percent accuracy. Ideas I wonder if there is a way to solve this issue. Maybe it is possible to use the original file but somehow tell the model that the rows with the same race_id have to be treated as one event. I could think of using groupby(race_id) but I was not able to feed the new groups into the model. Also you might use a bag for each race like when doing predictions for text data. I am actually stuck here so any suggestions are much appreciated :) ORIGINAL DF position horse age weight race_id 1 name1 3y 900 1 2 name2 4y 800 1 3 name3 5y 760 1 ... ... ... ... ... 8 name8 7y 980 1 1 name9 4y 880 2 ... ... ... ... ... 8 name16 5y 770 2 NEW DF position1 horse1 weight1 race_id1 ... position8 horse8 weight8 race_id8 1 name1 900 1 8 name8 980 1 1 name9 880 2 8 name16 770 2 A: if I correctly understand your problem you want to convert your old dataframe to new dataframe and feed that to your model. you can use this code: import pandas as pd import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) df = pd.DataFrame({'position': [1, 2, 3, 4], 'horse': ['name1', 'name2', 'name3', 'name8'], 'age': ['4y', '4y', '5y', '7y'], 'weight': [800, 978, 76, 565], 'race_id': [1, 1, 2, 2]}) groupby_race = df.groupby(['race_id']) arr = [] for name, group in groupby_race: r = np.concatenate([row.values for index, row in group.iterrows()]) arr.append(r) new_df = pd.DataFrame(data=arr, columns = ['position1', 'horse1', 'age1', 'weight1', 'race_id1', 'position2', 'horse2', 'age2', 'weight2', 'race_id2']) A: I think what is doable here is to create a logistic regression using the sklearn library which allows us to predict the chances of winning for each horse. I imagine it to be quite difficult to incorporate the fact of who the horse is racing against in each run. So here is what I would do: Assign a column to your data frame for whether the horse won or not Split into train and test data Implement sklearn.LogisticRegression Fit LogisticRegression Report score It might be advisable to check what features of your dataset are important so a principal component analysis would be helpful to reduce the dimension of your predictor space. In addition, the logistic regression assumes that our predictors are independent of each other and so you might need to do some exploratory analysis first to see whether there is some collinearity in your dataset. Documentation for the Logistic Regression: (https://scikitlearn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) Would love to try it out myself if you would want to share your dataset!
Prediction for horse racing scikit learn - multiple rows per race
Goal I want to train a model with Scikit-learn that predicts the outcome of horse races. I have a CSV file that includes multiple features like position, age, weight, horse_name, race_id etc. Problem In my original CSV file each horse is represented in one row. With positions from 1-8 each race consists of 8 rows. When I train my model however, the model looks at each row as an individual event (race) and therefore does not perform well. Approach I tried to solve this issue and created a new CSV file in which each row represents one race and the features go from position1, age1, weight1, horse_name1, race_id1 to position8, age8, weight8, horse_name8, race_id8 (see below). However, using a Multioutput in this case my model does not train at all but notices that age1, weight1 are the columns of the winner and does get 100 percent accuracy. Ideas I wonder if there is a way to solve this issue. Maybe it is possible to use the original file but somehow tell the model that the rows with the same race_id have to be treated as one event. I could think of using groupby(race_id) but I was not able to feed the new groups into the model. Also you might use a bag for each race like when doing predictions for text data. I am actually stuck here so any suggestions are much appreciated :) ORIGINAL DF position horse age weight race_id 1 name1 3y 900 1 2 name2 4y 800 1 3 name3 5y 760 1 ... ... ... ... ... 8 name8 7y 980 1 1 name9 4y 880 2 ... ... ... ... ... 8 name16 5y 770 2 NEW DF position1 horse1 weight1 race_id1 ... position8 horse8 weight8 race_id8 1 name1 900 1 8 name8 980 1 1 name9 880 2 8 name16 770 2
[ "if I correctly understand your problem you want to convert your old dataframe to new dataframe and feed that to your model.\n you can use this code:\nimport pandas as pd\nimport numpy as np\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\ndf = pd.DataFrame({'position': [1, 2, 3, 4],\n 'horse': ['name1', 'name2', 'name3', 'name8'],\n 'age': ['4y', '4y', '5y', '7y'],\n 'weight': [800, 978, 76, 565],\n 'race_id': [1, 1, 2, 2]})\n\ngroupby_race = df.groupby(['race_id'])\narr = []\nfor name, group in groupby_race:\n r = np.concatenate([row.values for index, row in group.iterrows()])\n arr.append(r)\nnew_df = pd.DataFrame(data=arr, columns = ['position1', 'horse1', 'age1', 'weight1', 'race_id1',\n 'position2', 'horse2', 'age2', 'weight2', 'race_id2'])\n\n", "I think what is doable here is to create a logistic regression using the sklearn library which allows us to predict the chances of winning for each horse. I imagine it to be quite difficult to incorporate the fact of who the horse is racing against in each run. So here is what I would do:\n\nAssign a column to your data frame for whether the horse won or not\n\nSplit into train and test data\n\nImplement sklearn.LogisticRegression\n\nFit LogisticRegression\n\nReport score\n\n\nIt might be advisable to check what features of your dataset are important so a principal component analysis would be helpful to reduce the dimension of your predictor space. In addition, the logistic regression assumes that our predictors are independent of each other and so you might need to do some exploratory analysis first to see whether there is some collinearity in your dataset.\nDocumentation for the Logistic Regression: (https://scikitlearn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html)\nWould love to try it out myself if you would want to share your dataset!\n" ]
[ 1, 0 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0061385916_python_scikit_learn.txt
Q: matplotlib make axis ticks label for dates bold I want to have bold labels on my axis, so I can use the plot for publication. I also need to have the label of the lines in the legend plotted in bold. So far I can set the axis labels and the legend to the size and weight I want. I can also set the size of the axis labels to the size I want, however I am failing with the weight. Here is an example code: # plotting libs from pylab import * from matplotlib import rc if __name__=='__main__': tmpData = np.random.random( 100 ) # activate latex text rendering rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') #create figure f = figure(figsize=(10,10)) ax = gca() plot(np.arange(100), tmpData, label=r'\textbf{Line 1}', linewidth=2) ylabel(r'\textbf{Y-AXIS}', fontsize=20) xlabel(r'\textbf{X-AXIS}', fontsize=20) fontsize = 20 fontweight = 'bold' fontproperties = {'family':'sans-serif','sans-serif':['Helvetica'],'weight' : fontweight, 'size' : fontsize} ax.set_xticklabels(ax.get_xticks(), fontproperties) ax.set_yticklabels(ax.get_yticks(), fontproperties) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) legend() show() sys.exit() And this is what I get: Any idea what I am missing or doing wrong in order to get the axis ticks label in bold? EDIT I have updated my code using toms response. However I now have another problem, as I need to use datetime on the x-axis, this has not the same effect as on the normal y-axis (sorry for not putting this in in the original question, but I did not think it would change things): # plotting libs from pylab import * from matplotlib import rc, rcParams import matplotlib.dates as dates # datetime import datetime if __name__=='__main__': tmpData = np.random.random( 100 ) base = datetime.datetime(2000, 1, 1) arr = np.array([base + datetime.timedelta(days=i) for i in xrange(100)]) # activate latex text rendering rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath'] #create figure f = figure(figsize=(10,10)) ax = gca() plot(np.arange(100), tmpData, label=r'\textbf{Line 1}', linewidth=2) ylabel(r'\textbf{Y-AXIS}', fontsize=20) xlabel(r'\textbf{X-AXIS}', fontsize=20) ax.xaxis.set_tick_params(labelsize=20) ax.yaxis.set_tick_params(labelsize=20) ax.xaxis.set_major_formatter(dates.DateFormatter('%m/%Y')) ax.xaxis.set_major_locator(dates.MonthLocator(interval=1)) legend() Now my result looks like this: It seems to be that the changes doe not affect the display or rather the weight of the x-axis ticks labels. A: I think the problem is because the ticks are made in LaTeX math-mode, so the font properties don't apply. You can get around this by adding the correct commands to the LaTeX preamble, using rcParams. Specifcally, you need to use \boldmath to get the correct weight, and \usepackage{sfmath} to get sans-serif font. Also, you can use set_tick_params to set the font size of the tick labels. Here's some code that does what you want: import numpy as np from matplotlib import rc,rcParams from pylab import * tmpData = np.random.random( 100 ) # activate latex text rendering rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath'] #create figure f = figure(figsize=(10,10)) ax = gca() plot(np.arange(100), tmpData, label=r'\textbf{Line 1}', linewidth=2) ylabel(r'\textbf{Y-AXIS}', fontsize=20) xlabel(r'\textbf{X-AXIS}', fontsize=20) ax.xaxis.set_tick_params(labelsize=20) ax.yaxis.set_tick_params(labelsize=20) legend() A: Use plt.xticks(x, weight = 'bold') A: labels = axes.get_xticklabels() + axes.get_yticklabels() [label.set_fontweight('bold') for label in labels] A: If you want to make the axis labels bold automatically (i.e. without having to add \textbf every time), you could do the following from matplotlib.axes import Axes from matplotlib import pyplot as plt plt.rcParams['text.usetex'] = True def get_new_func(axis_name): # returns a modified version of the Axes.set_xlabel (or y) methods orig_func = getattr(Axes, f'set_{axis_name}label') def add_bold(self, *args, **kwargs): new_args = list(args) new_args[0] = fr"\textbf{{{new_args[0]}}}" # modify the argument return orig_func(self, *new_args, **kwargs) return add_bold for x in ['x', 'y']: setattr(Axes, f'set_{x}label', get_new_func(x)) # modify the methods of the Axis class x = np.linspace(0, 2 * 3.14, 20) y = np.sin(x) ax = plt.gca() ax.plot(x, y) ax.set_xlabel("Theta") ax.set_ylabel("Amp") plt.show() This makes use of the fact that the Axis.set_xlabel and Axis.set_ylabel methods are attributes (in this case function objects) that can be modified by the user. The modification is done in add_bold, which simply calls the original function object but with a modified argument. orig_func and add_bold are defined inside of get_new_func in order to correctly preserve the reference to the original method (i.e. i'm forming a closure). A: this is another example for you import matplotlib.pyplot as plt places = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] literacy_rate = [100, 98, 90, 85, 75, 50, 30, 45, 65, 70] female_literacy = [95, 100, 50, 60, 85, 80, 75, 99, 70, 30] plt.xlabel("Places") plt.ylabel("Percentage") plt.plot(places, literacy_rate, color='blue', linewidth=6, label="Literacy rate") plt.plot(places, female_literacy, color='fuchsia', linewidth=4, label="Female Literacy rate") plt.legend(loc='lower left', ncol=1) and the youtput will be like this:
matplotlib make axis ticks label for dates bold
I want to have bold labels on my axis, so I can use the plot for publication. I also need to have the label of the lines in the legend plotted in bold. So far I can set the axis labels and the legend to the size and weight I want. I can also set the size of the axis labels to the size I want, however I am failing with the weight. Here is an example code: # plotting libs from pylab import * from matplotlib import rc if __name__=='__main__': tmpData = np.random.random( 100 ) # activate latex text rendering rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') #create figure f = figure(figsize=(10,10)) ax = gca() plot(np.arange(100), tmpData, label=r'\textbf{Line 1}', linewidth=2) ylabel(r'\textbf{Y-AXIS}', fontsize=20) xlabel(r'\textbf{X-AXIS}', fontsize=20) fontsize = 20 fontweight = 'bold' fontproperties = {'family':'sans-serif','sans-serif':['Helvetica'],'weight' : fontweight, 'size' : fontsize} ax.set_xticklabels(ax.get_xticks(), fontproperties) ax.set_yticklabels(ax.get_yticks(), fontproperties) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) legend() show() sys.exit() And this is what I get: Any idea what I am missing or doing wrong in order to get the axis ticks label in bold? EDIT I have updated my code using toms response. However I now have another problem, as I need to use datetime on the x-axis, this has not the same effect as on the normal y-axis (sorry for not putting this in in the original question, but I did not think it would change things): # plotting libs from pylab import * from matplotlib import rc, rcParams import matplotlib.dates as dates # datetime import datetime if __name__=='__main__': tmpData = np.random.random( 100 ) base = datetime.datetime(2000, 1, 1) arr = np.array([base + datetime.timedelta(days=i) for i in xrange(100)]) # activate latex text rendering rc('text', usetex=True) rc('axes', linewidth=2) rc('font', weight='bold') rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath'] #create figure f = figure(figsize=(10,10)) ax = gca() plot(np.arange(100), tmpData, label=r'\textbf{Line 1}', linewidth=2) ylabel(r'\textbf{Y-AXIS}', fontsize=20) xlabel(r'\textbf{X-AXIS}', fontsize=20) ax.xaxis.set_tick_params(labelsize=20) ax.yaxis.set_tick_params(labelsize=20) ax.xaxis.set_major_formatter(dates.DateFormatter('%m/%Y')) ax.xaxis.set_major_locator(dates.MonthLocator(interval=1)) legend() Now my result looks like this: It seems to be that the changes doe not affect the display or rather the weight of the x-axis ticks labels.
[ "I think the problem is because the ticks are made in LaTeX math-mode, so the font properties don't apply.\nYou can get around this by adding the correct commands to the LaTeX preamble, using rcParams. Specifcally, you need to use \\boldmath to get the correct weight, and \\usepackage{sfmath} to get sans-serif font.\nAlso, you can use set_tick_params to set the font size of the tick labels.\nHere's some code that does what you want:\nimport numpy as np\nfrom matplotlib import rc,rcParams\nfrom pylab import *\n\ntmpData = np.random.random( 100 )\n\n\n# activate latex text rendering\nrc('text', usetex=True)\nrc('axes', linewidth=2)\nrc('font', weight='bold')\nrcParams['text.latex.preamble'] = [r'\\usepackage{sfmath} \\boldmath']\n\n#create figure\nf = figure(figsize=(10,10))\n\nax = gca()\n\nplot(np.arange(100), tmpData, label=r'\\textbf{Line 1}', linewidth=2)\n\nylabel(r'\\textbf{Y-AXIS}', fontsize=20)\nxlabel(r'\\textbf{X-AXIS}', fontsize=20)\n\nax.xaxis.set_tick_params(labelsize=20)\nax.yaxis.set_tick_params(labelsize=20)\n\nlegend()\n\n", "Use\nplt.xticks(x, weight = 'bold')\n\n", "labels = axes.get_xticklabels() + axes.get_yticklabels()\n [label.set_fontweight('bold') for label in labels]\n\n", "If you want to make the axis labels bold automatically (i.e. without having to add \\textbf every time), you could do the following\nfrom matplotlib.axes import Axes\nfrom matplotlib import pyplot as plt\nplt.rcParams['text.usetex'] = True\n\ndef get_new_func(axis_name): # returns a modified version of the Axes.set_xlabel (or y) methods\n orig_func = getattr(Axes, f'set_{axis_name}label')\n\n def add_bold(self, *args, **kwargs):\n new_args = list(args)\n new_args[0] = fr\"\\textbf{{{new_args[0]}}}\" # modify the argument\n return orig_func(self, *new_args, **kwargs)\n\n return add_bold\n\nfor x in ['x', 'y']: \n setattr(Axes, f'set_{x}label', get_new_func(x)) # modify the methods of the Axis class\n\n\nx = np.linspace(0, 2 * 3.14, 20)\ny = np.sin(x)\nax = plt.gca()\n\nax.plot(x, y)\nax.set_xlabel(\"Theta\")\nax.set_ylabel(\"Amp\")\n\nplt.show()\n\nThis makes use of the fact that the Axis.set_xlabel and Axis.set_ylabel methods are attributes (in this case function objects) that can be modified by the user. The modification is done in add_bold, which simply calls the original function object but with a modified argument. orig_func and add_bold are defined inside of get_new_func in order to correctly preserve the reference to the original method (i.e. i'm forming a closure).\n", "this is another example for you\nimport matplotlib.pyplot as plt\n \nplaces = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"]\nliteracy_rate = [100, 98, 90, 85, 75, 50, 30, 45, 65, 70]\nfemale_literacy = [95, 100, 50, 60, 85, 80, 75, 99, 70, 30]\n \nplt.xlabel(\"Places\")\nplt.ylabel(\"Percentage\")\n \nplt.plot(places, literacy_rate, color='blue',\n linewidth=6, label=\"Literacy rate\")\n \nplt.plot(places, female_literacy, color='fuchsia',\n linewidth=4, label=\"Female Literacy rate\")\n \nplt.legend(loc='lower left', ncol=1)\n\nand the youtput will be like this:\n\n" ]
[ 18, 15, 8, 0, 0 ]
[]
[]
[ "matplotlib", "python", "tex" ]
stackoverflow_0029766827_matplotlib_python_tex.txt
Q: PyShell and IPython are showing an extra indentation that is not there I just started using tmux along with slime, PyShell and IPython and I have ran into the following problem. I am trying to run the following code: names = ['a', 'b', 'c'] nc = { name : 0 for name in names} count = 1 for name in names: nc[name] += count count += 1 print(nc) and when I normally run the file in terminal using python3 file.py, it correctly returns {'a': 1, 'b': 2, 'c': 3}. However, when running this with slime, it is saying that there is an unexpected indent and the error message is showing that the following is being inputted: names = ['a', 'b', 'c'] nc = { name : 0 for name in names} count = 1 for name in names: nc[name] += count count += 1 print However, this is not what I am inputting. Here is a to show this. Where is the problem coming from? A: The error is caused by IPython inserting an indent automatically. To turn off automatic indent, use %autoindent command in IPython. To keep the option off when you restart IPython, add the line c.TerminalInteractiveShell.autoindent=False to your ipython_config.py which is located in a profile_profilename folder under the ~/.ipython directory on Linux. The default config would be located at ~/.ipython/profile_default/ipython_config.py. If you don't already have a config file, run ipython profile create default to create a default profile or name it something else by replacing default in above command with the desired profile name. A: The interactive shell you're using isn't made for use with pasted code. It tries to be helpful and indents lines to where it thinks you want them to be indented To illustrate I'll mark leading spaces provided by the repl with '.' and spaces you pasted with ';' for name in names: ....;;;;count += 1 ........;;;;nc[name] += count So the problem is the repl trying to assist you. Try to find out a way to either load python code into your repl or to enable a "paste" mode where it will not try to guess an indentation level for you.
PyShell and IPython are showing an extra indentation that is not there
I just started using tmux along with slime, PyShell and IPython and I have ran into the following problem. I am trying to run the following code: names = ['a', 'b', 'c'] nc = { name : 0 for name in names} count = 1 for name in names: nc[name] += count count += 1 print(nc) and when I normally run the file in terminal using python3 file.py, it correctly returns {'a': 1, 'b': 2, 'c': 3}. However, when running this with slime, it is saying that there is an unexpected indent and the error message is showing that the following is being inputted: names = ['a', 'b', 'c'] nc = { name : 0 for name in names} count = 1 for name in names: nc[name] += count count += 1 print However, this is not what I am inputting. Here is a to show this. Where is the problem coming from?
[ "The error is caused by IPython inserting an indent automatically. To turn off automatic indent, use %autoindent command in IPython. To keep the option off when you restart IPython, add the line\nc.TerminalInteractiveShell.autoindent=False\n\nto your ipython_config.py which is located in a profile_profilename folder under the ~/.ipython directory on Linux. The default config would be located at ~/.ipython/profile_default/ipython_config.py. If you don't already have a config file, run\nipython profile create default\n\nto create a default profile or name it something else by replacing default in above command with the desired profile name.\n", "The interactive shell you're using isn't made for use with pasted code.\nIt tries to be helpful and indents lines to where it thinks you want them to be indented\nTo illustrate I'll mark leading spaces provided by the repl with '.' and spaces you pasted with ';'\nfor name in names:\n....;;;;count += 1\n........;;;;nc[name] += count\n\nSo the problem is the repl trying to assist you. Try to find out a way to either load python code into your repl or to enable a \"paste\" mode where it will not try to guess an indentation level for you.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "slime", "tmux", "vim" ]
stackoverflow_0074483618_python_slime_tmux_vim.txt
Q: How to get number of values in each row of a sparse tensor? I have a Sparse Tensor as follows: st = tf.sparse.from_dense([[1, 0, 2, 5], [3, 0, 0, 4], [0, 0, 0, 0], [1, 1, 3, 0], [1, 2, 2, 2]]) print(st) SparseTensor(indices=tf.Tensor( [[0 0] [0 2] [0 3] [1 0] [1 3] [3 0] [3 1] [3 2] [4 0] [4 1] [4 2] [4 3]], shape=(12, 2), dtype=int64), values=tf.Tensor([1 2 5 3 4 1 1 3 1 2 2 2], shape=(12,), dtype=int32), dense_shape=tf.Tensor([5 4], shape=(2,), dtype=int64)) I want to convert this sparse tensor to another 1D tensor of shape (5, 1) where the only column represents the number (or size) of values in each of the rows. For example, for the above sparse tensor, desired 1D tensor would be [3, 2, 0, 3, 4]. How do you think I could do it? Sorry, I tried going through the TensorFlow api docs but couldn't find anything to try that I could paste here on what I have already tried. Thanks in advance. A: You can use bin count on the indices. tf.math.bincount(tf.cast(st.indices[:,0], tf.int32))
How to get number of values in each row of a sparse tensor?
I have a Sparse Tensor as follows: st = tf.sparse.from_dense([[1, 0, 2, 5], [3, 0, 0, 4], [0, 0, 0, 0], [1, 1, 3, 0], [1, 2, 2, 2]]) print(st) SparseTensor(indices=tf.Tensor( [[0 0] [0 2] [0 3] [1 0] [1 3] [3 0] [3 1] [3 2] [4 0] [4 1] [4 2] [4 3]], shape=(12, 2), dtype=int64), values=tf.Tensor([1 2 5 3 4 1 1 3 1 2 2 2], shape=(12,), dtype=int32), dense_shape=tf.Tensor([5 4], shape=(2,), dtype=int64)) I want to convert this sparse tensor to another 1D tensor of shape (5, 1) where the only column represents the number (or size) of values in each of the rows. For example, for the above sparse tensor, desired 1D tensor would be [3, 2, 0, 3, 4]. How do you think I could do it? Sorry, I tried going through the TensorFlow api docs but couldn't find anything to try that I could paste here on what I have already tried. Thanks in advance.
[ "You can use bin count on the indices.\ntf.math.bincount(tf.cast(st.indices[:,0], tf.int32))\n\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074481219_python_tensorflow.txt
Q: Create a function called square that takes in a number and returns the square of that number Question:- Create a function called square that takes in a number and returns the square of that number. If what's passed in is not a float or an int, return "None" Code:- def square(x): if x % 2 == 0: return x**x else: return None print(square(5)) Error:- None !- 25 : square should return 25 Your Output None A: why are you doing modulus 2 here? def square(x): if isinstance(x,int) or isinstance(x,float): return x**2 else: return none print(square(5))
Create a function called square that takes in a number and returns the square of that number
Question:- Create a function called square that takes in a number and returns the square of that number. If what's passed in is not a float or an int, return "None" Code:- def square(x): if x % 2 == 0: return x**x else: return None print(square(5)) Error:- None !- 25 : square should return 25 Your Output None
[ "why are you doing modulus 2 here?\ndef square(x):\n if isinstance(x,int) or isinstance(x,float):\n return x**2\n else:\n return none\nprint(square(5))\n\n" ]
[ -1 ]
[]
[]
[ "python" ]
stackoverflow_0074484388_python.txt
Q: Get the Excel column label (A, B, ..., Z, AA, ..., AZ, BA, ..., ZZ, AAA, AAB, ...) Given the letter(s) of an Excel column header I need to output the column number. It goes A-Z, then AA-AZ then BA-BZ and so on. I want to go through it like it's base 26, I just don't know how to implement that. It works fine for simple ones like AA because 26^0 = 1 + 26^1 = 26 = 27. But with something like ZA, if I do 26 ^ 26(z is the 26th letter) the output is obviously too large. What am I missing? A: If we decode "A" as 0, "B" as 1, ... then "Z" is 25 and "AA" is 26. So it is not a pure 26-base encoding, as then a prefixed "A" would have no influence on the value, and "AAAB" would have to be the same as "B", just like in the decimal system 0001 is equal to 1. But this is not the case here. The value of "AA" is 1*261 + 0, and "ZA" is 26*261 + 0. We can generalise and say that "A" should be valued 1, "B" 2, ...etc (with the exception of a single letter encoding). So in "AAA", the right most "A" represents a coefficient of 0, while the other "A"s represent ones: 1*262 + 1*261 + 0 This leads to the following code: def decode(code): val = 0 for ch in code: # base-26 decoding "plus 1" val = val * 26 + ord(ch) - ord("A") + 1 return val - 1 Of course, if we want the column numbers to start with 1 instead of 0, then just replace that final statement with: return val A: sum of powers You can sum the multiples of the powers of 26: def xl2int(s): s = s.strip().upper() return sum((ord(c)-ord('A')+1)*26**i for i,c in enumerate(reversed(s))) xl2int('A') # 1 xl2int('Z') # 26 xl2int('AA') # 27 xl2int('ZZ') # 702 xl2int('AAA') # 703 int builtin You can use a string translation table and the int builtin with the base parameter. As you have a broken base you need to add 26**n+26**(n-1)+...+26**0 for an input of length n, which you can obtain with int('11...1', base=26) where there are as many 1s as the length of the input string. from string import ascii_uppercase, digits t = str.maketrans(dict(zip(ascii_uppercase, digits+ascii_uppercase))) def xl2int(s): s = s.strip().upper().translate(t) return int(s, base=26)+int('1'*len(s), base=26) xl2int('A') # 1 xl2int('Z') # 26 xl2int('AA') # 27 xl2int('ZZ') # 702 xl2int('AAA') # 703 How the translation works It shifts each character so that A -> 0, B -> 1... J -> 9, K -> A... Z -> P. Then it converts it to integer using int. However the obtained number is incorrect as we are missing 26**x for each digit position in the number, so we add as many power of 26 as there are digits in the input. A: Another way to do it, written in VBA: Function nColumn(sColumn As String) As Integer ' Return column number for a given column letter. ' 676 = 26^2 ' 64 = Asc("A") - 1 nColumn = _ (IIf(Len(sColumn) < 3, 0, Asc(Left( sColumn , 1)) - 64) * 676) + _ (IIf(Len(sColumn) = 1, 0, Asc(Left(Right(sColumn, 2), 1)) - 64) * 26) + _ (Asc( Right(sColumn , 1)) - 64) End Function Or you can do it directly in the worksheet: =(if(len(<clm>) < 3, 0, code(left( <clm> , 1)) - 64) * 676) + (if(len(<clm>) = 1, 0, code(left(right(<clm>, 2), 1)) - 64) * 26) + (code( right(<clm> , 1)) - 64) I've also posted the inverse operation done similarly.
Get the Excel column label (A, B, ..., Z, AA, ..., AZ, BA, ..., ZZ, AAA, AAB, ...)
Given the letter(s) of an Excel column header I need to output the column number. It goes A-Z, then AA-AZ then BA-BZ and so on. I want to go through it like it's base 26, I just don't know how to implement that. It works fine for simple ones like AA because 26^0 = 1 + 26^1 = 26 = 27. But with something like ZA, if I do 26 ^ 26(z is the 26th letter) the output is obviously too large. What am I missing?
[ "If we decode \"A\" as 0, \"B\" as 1, ... then \"Z\" is 25 and \"AA\" is 26.\nSo it is not a pure 26-base encoding, as then a prefixed \"A\" would have no influence on the value, and \"AAAB\" would have to be the same as \"B\", just like in the decimal system 0001 is equal to 1. But this is not the case here.\nThe value of \"AA\" is 1*261 + 0, and \"ZA\" is 26*261 + 0.\nWe can generalise and say that \"A\" should be valued 1, \"B\" 2, ...etc (with the exception of a single letter encoding). So in \"AAA\", the right most \"A\" represents a coefficient of 0, while the other \"A\"s represent ones: 1*262 + 1*261 + 0\nThis leads to the following code:\ndef decode(code):\n val = 0\n for ch in code: # base-26 decoding \"plus 1\"\n val = val * 26 + ord(ch) - ord(\"A\") + 1 \n return val - 1\n\nOf course, if we want the column numbers to start with 1 instead of 0, then just replace that final statement with:\nreturn val\n\n", "sum of powers\nYou can sum the multiples of the powers of 26:\ndef xl2int(s):\n s = s.strip().upper()\n return sum((ord(c)-ord('A')+1)*26**i\n for i,c in enumerate(reversed(s)))\n\nxl2int('A')\n# 1\n\nxl2int('Z')\n# 26\n\nxl2int('AA')\n# 27\n\nxl2int('ZZ')\n# 702\n\nxl2int('AAA')\n# 703\n\nint builtin\nYou can use a string translation table and the int builtin with the base parameter.\nAs you have a broken base you need to add 26**n+26**(n-1)+...+26**0 for an input of length n, which you can obtain with int('11...1', base=26) where there are as many 1s as the length of the input string.\nfrom string import ascii_uppercase, digits\nt = str.maketrans(dict(zip(ascii_uppercase, digits+ascii_uppercase)))\n\ndef xl2int(s):\n s = s.strip().upper().translate(t)\n return int(s, base=26)+int('1'*len(s), base=26)\n\nxl2int('A')\n# 1\n\nxl2int('Z')\n# 26\n\nxl2int('AA')\n# 27\n\nxl2int('ZZ')\n# 702\n\nxl2int('AAA')\n# 703\n\nHow the translation works\nIt shifts each character so that A -> 0, B -> 1... J -> 9, K -> A... Z -> P. Then it converts it to integer using int. However the obtained number is incorrect as we are missing 26**x for each digit position in the number, so we add as many power of 26 as there are digits in the input.\n", "Another way to do it, written in VBA:\nFunction nColumn(sColumn As String) As Integer\n\n' Return column number for a given column letter.\n\n' 676 = 26^2\n' 64 = Asc(\"A\") - 1\n\nnColumn = _\n (IIf(Len(sColumn) < 3, 0, Asc(Left( sColumn , 1)) - 64) * 676) + _\n (IIf(Len(sColumn) = 1, 0, Asc(Left(Right(sColumn, 2), 1)) - 64) * 26) + _\n (Asc( Right(sColumn , 1)) - 64)\n\nEnd Function\n\nOr you can do it directly in the worksheet:\n=(if(len(<clm>) < 3, 0, code(left( <clm> , 1)) - 64) * 676) + \n (if(len(<clm>) = 1, 0, code(left(right(<clm>, 2), 1)) - 64) * 26) + \n (code( right(<clm> , 1)) - 64)\n\nI've also posted the inverse operation done similarly.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "base", "excel", "python" ]
stackoverflow_0072383708_base_excel_python.txt
Q: How return a value with the input function? Hi guys I'm new to python. I've been trying to return a value with an input function to the return can anyone help me out? def bike_wash(amount): print("Welcome to your bike wash") print("Please enter your desired wash") if (amount == 100): print("Thanks for choosing basic wash") print("Enjoy water wash with spray") if (amount == 200): print("Thanks for choosing Premium wash") print("Enjoy foam wash to the entire body") amount = input() bike_wash(amount) A: The answer depends on which version of Python you're using. Python 3 You can simply pass the result of input (a string) to int (a function which turns a string into an integer). amount = int(input("Enter a number")) Python 2 The python2 equivalent (to the input function from python3) is raw_input amount = int(raw_input("Enter a number")) Additionally it might be helpful to make your own parse_input function: def parse_input(parser, prompt='', defaultValue=None): try: return parser(input(prompt)) except ValueError: return defaultValue replace input with raw_input for python2 Typical usage: amount = parse_input(int, "Enter a number", 0)
How return a value with the input function?
Hi guys I'm new to python. I've been trying to return a value with an input function to the return can anyone help me out? def bike_wash(amount): print("Welcome to your bike wash") print("Please enter your desired wash") if (amount == 100): print("Thanks for choosing basic wash") print("Enjoy water wash with spray") if (amount == 200): print("Thanks for choosing Premium wash") print("Enjoy foam wash to the entire body") amount = input() bike_wash(amount)
[ "The answer depends on which version of Python you're using.\nPython 3\nYou can simply pass the result of input (a string) to int (a function which turns a string into an integer).\n amount = int(input(\"Enter a number\"))\n\nPython 2\nThe python2 equivalent (to the input function from python3) is raw_input\n amount = int(raw_input(\"Enter a number\"))\n\nAdditionally it might be helpful to make your own parse_input function:\ndef parse_input(parser, prompt='', defaultValue=None):\n try:\n return parser(input(prompt))\n except ValueError:\n return defaultValue\n\n\nreplace input with raw_input for python2\nTypical usage:\n amount = parse_input(int, \"Enter a number\", 0)\n\n" ]
[ 0 ]
[]
[]
[ "input", "python", "return", "user_input" ]
stackoverflow_0074484461_input_python_return_user_input.txt
Q: Python Reverse a string using recursion, explanation I need to reverse a string using recursion, I was able to accidentally write a code that successfully accomplishes the task, but I don't really understand why. Here's what I have import stdio import sys # Entry point def main(): s = sys.argv[1] stdio.writeln(_reverse(s)) # Returns the reverse of the string s. def _reverse(s): # Base case: if s is the empty string, return an empty string. if len(s) == 0: return "" # Recursive step: return last character in s + _reverse(s excluding last character). else: return s[-1] + _reverse(s[:len(s)-1]) if __name__ == '__main__': main() This makes sense to me just for the first recursive call. Lets say the input is "Bolton" the length of this string is 6, the first recursive call would simply call the _reverse function on s [0:5] What I don't understand is that how do the next recursive calls work? Because len(s) would remain the same? To my understanding, each recursive call to the _reverse() would subtract 1 from len(s) -- which is 6. Can someone please explain why thats not the case? How does the the len decrement? A: s[:len(s)-1] or the same value but shorter s[:-1] is essentially a string with the last element removed, the length of it is 1 shorter than the original. You then call the function with that shorter string. So a step by step resolution would look something like this: reverse("hello") # len("hello") != 0 so we substitute with else "hello"[-1] + reverse("hello"[:-1]) "o" + reverse("hell") "o" + "hell"[-1] + reverse("hell"[:-1]) "o" + "l" + reverse("hel") "o" + "l" + "hel"[-1] + reverse("hel"[:-1]) "o" + "l" + "l" + reverse("he") "o" + "l" + "l" + "he"[-1] + reverse("he"[:-1]) "o" + "l" + "l" + "e" + reverse("h") "o" + "l" + "l" + "e" + "h"[-1] + reverse("h"[:-1]) "o" + "l" + "l" + "e" + "h" + reverse("") # len("") == 0 so we substitute "" "o" + "l" + "l" + "e" + "h" + "" "olleh"
Python Reverse a string using recursion, explanation
I need to reverse a string using recursion, I was able to accidentally write a code that successfully accomplishes the task, but I don't really understand why. Here's what I have import stdio import sys # Entry point def main(): s = sys.argv[1] stdio.writeln(_reverse(s)) # Returns the reverse of the string s. def _reverse(s): # Base case: if s is the empty string, return an empty string. if len(s) == 0: return "" # Recursive step: return last character in s + _reverse(s excluding last character). else: return s[-1] + _reverse(s[:len(s)-1]) if __name__ == '__main__': main() This makes sense to me just for the first recursive call. Lets say the input is "Bolton" the length of this string is 6, the first recursive call would simply call the _reverse function on s [0:5] What I don't understand is that how do the next recursive calls work? Because len(s) would remain the same? To my understanding, each recursive call to the _reverse() would subtract 1 from len(s) -- which is 6. Can someone please explain why thats not the case? How does the the len decrement?
[ "s[:len(s)-1] or the same value but shorter s[:-1] is essentially a string with the last element removed, the length of it is 1 shorter than the original.\nYou then call the function with that shorter string.\nSo a step by step resolution would look something like this:\nreverse(\"hello\") # len(\"hello\") != 0 so we substitute with else\n\"hello\"[-1] + reverse(\"hello\"[:-1])\n\"o\" + reverse(\"hell\")\n\"o\" + \"hell\"[-1] + reverse(\"hell\"[:-1])\n\"o\" + \"l\" + reverse(\"hel\")\n\"o\" + \"l\" + \"hel\"[-1] + reverse(\"hel\"[:-1])\n\"o\" + \"l\" + \"l\" + reverse(\"he\")\n\"o\" + \"l\" + \"l\" + \"he\"[-1] + reverse(\"he\"[:-1])\n\"o\" + \"l\" + \"l\" + \"e\" + reverse(\"h\")\n\"o\" + \"l\" + \"l\" + \"e\" + \"h\"[-1] + reverse(\"h\"[:-1])\n\"o\" + \"l\" + \"l\" + \"e\" + \"h\" + reverse(\"\") # len(\"\") == 0 so we substitute \"\"\n\"o\" + \"l\" + \"l\" + \"e\" + \"h\" + \"\"\n\"olleh\"\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074484470_python.txt
Q: Python asyncio: how are tasks scheduled? I'm new to Python asyncio and I'm doing some experiments. I have the following code: async def say_after(n, s): await asyncio.sleep(n) print(s) async def main(): task1 = asyncio.create_task(say_after(2, 'a')) task2 = asyncio.create_task(say_after(1, 'b')) await task1 print('x', flush=True) await task2 print('y', flush=True) asyncio.run(main()) And the output: b a x y I don't understand the order here. Can someone help explain? Especially why x comes after b and a? A: Executing say_after (without await) creates a coroutine object, but does not start it yet. If you await on the coroutine object, then you are executing the coroutine until the Python encounters one of await or return (or end of function) in the coroutine. "Executing" here means transforming the coroutine into a Task object and put that object in the async loop. However, create_task immediately 'starts' the coroutine and put them tasks in the async loop (though, because this is async instead of parallel, execution does not actually begin until Python encounters await in main()). In your situation, as soon as Python sees the await task1, it 'leaves' main() and loops among task1 and task2 back and forth (because both tasks have been put in the async loop by create_task) until task1 is completed (because task1 is the one being await-ed on). Because task2 had scheduled itself to wait for a shorter time, it finishes first. About 1 second later, task1 completes, and only then execution returns to main() (because, remember, it was task1 that main() had been await-ing on). At this point, both task1 and task2 has completed; the await task2 line practically does nothing; it's just "wrapping up" task2 and (almost) immediately returns. A: Especially why x comes after b and a? b is printed in task2 about 1 second after the start of main, and a is printed in task1 about 2 seconds after the start of main. The await task1 waits for task1, and so waits about 2 seconds. So by the time await task1 completes, both b and a would have been printed. (The "about"s in the above are deliberate... there would be variations, but in most situations, they would be small) A: await task1 basically says that do not execute the next lines of code until task1 is finished (i.e. the execution of say_after(2, 'a')). task1 takes longer than task2 to execute, so by the time you "awaited" task1, task2 is already finished executing. So putting await task2 below await task1 is somewhat useless here. If you swap these two lines, the output will be different. That's why 'b' is printed before 'a'. And not until 'a' is printed, 'x' and 'y' could be printed.
Python asyncio: how are tasks scheduled?
I'm new to Python asyncio and I'm doing some experiments. I have the following code: async def say_after(n, s): await asyncio.sleep(n) print(s) async def main(): task1 = asyncio.create_task(say_after(2, 'a')) task2 = asyncio.create_task(say_after(1, 'b')) await task1 print('x', flush=True) await task2 print('y', flush=True) asyncio.run(main()) And the output: b a x y I don't understand the order here. Can someone help explain? Especially why x comes after b and a?
[ "Executing say_after (without await) creates a coroutine object, but does not start it yet.\nIf you await on the coroutine object, then you are executing the coroutine until the Python encounters one of await or return (or end of function) in the coroutine. \"Executing\" here means transforming the coroutine into a Task object and put that object in the async loop.\nHowever, create_task immediately 'starts' the coroutine and put them tasks in the async loop (though, because this is async instead of parallel, execution does not actually begin until Python encounters await in main()).\nIn your situation, as soon as Python sees the await task1, it 'leaves' main() and loops among task1 and task2 back and forth (because both tasks have been put in the async loop by create_task) until task1 is completed (because task1 is the one being await-ed on). Because task2 had scheduled itself to wait for a shorter time, it finishes first. About 1 second later, task1 completes, and only then execution returns to main() (because, remember, it was task1 that main() had been await-ing on).\nAt this point, both task1 and task2 has completed; the await task2 line practically does nothing; it's just \"wrapping up\" task2 and (almost) immediately returns.\n", "\nEspecially why x comes after b and a?\n\nb is printed in task2 about 1 second after the start of main, and a is printed in task1 about 2 seconds after the start of main. The await task1 waits for task1, and so waits about 2 seconds. So by the time await task1 completes, both b and a would have been printed.\n(The \"about\"s in the above are deliberate... there would be variations, but in most situations, they would be small)\n", "await task1 basically says that do not execute the next lines of code until task1 is finished (i.e. the execution of say_after(2, 'a')).\ntask1 takes longer than task2 to execute, so by the time you \"awaited\" task1, task2 is already finished executing. So putting await task2 below await task1 is somewhat useless here. If you swap these two lines, the output will be different.\nThat's why 'b' is printed before 'a'. And not until 'a' is printed, 'x' and 'y' could be printed.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0070813763_python_python_asyncio.txt
Q: Merge two spark dataframes with different columns to get all columns Lets say I have 2 spark dataframes: Location Date Date_part Sector units USA 7/1/2021 7/1/2021 Cars 200 IND 7/1/2021 7/1/2021 Scooters 180 COL 7/1/2021 7/1/2021 Trucks 100 Location Date Brands units values UK null brand1 400 120 AUS null brand2 450 230 CAN null brand3 150 34 I need my resultant dataframe as Location Date Date_part Sector Brands units values USA 7/1/2021 7/1/2021 Cars 200 IND 7/1/2021 7/1/2021 Scooters 180 COL 7/1/2021 7/1/2021 Trucks 100 UK null 7/1/2021 brand1 400 120 AUS null 7/1/2021 brand2 450 230 CAN null 7/1/2021 brand3 150 34 So my desired df should contain all column from both dataframes also I need Date_part in all rows This is what I tried: df_result= df1.union(df_2) But Im getting this as my result. The values are being swapped and one column from second dataframe is missing. Location Date Date_part Sector Brands units USA 7/1/2021 7/1/2021 Cars 200 IND 7/1/2021 7/1/2021 Scooters 180 COL 7/1/2021 7/1/2021 Trucks 100 UK null brand1 400 120 AUS null brand2 450 230 CAN null brand3 150 34 Any suggestions plsss A: union : this function resolves columns by position (not by name) That is the reason why you believed "The values are being swapped and one column from second dataframe is missing." You should use unionByName, but this functions requires both dataframe to have the same structure. I offer you this simple code to harmonize the structure of your dataframes and then do the union(ByName). from pyspark.sql import DataFrame from pyspark.sql import functions as F def add_missing_columns(df: DataFrame, ref_df: DataFrame) -> DataFrame: """Add missing columns from ref_df to df Args: df (DataFrame): dataframe with missing columns ref_df (DataFrame): referential dataframe Returns: DataFrame: df with additionnal columns from ref_df """ for col in ref_df.schema: if col.name not in df.columns: df = df.withColumn(col.name, F.lit(None).cast(col.dataType)) return df df1 = add_missing_columns(df1, df2) df2 = add_missing_columns(df2, df1) df_result = df1.unionByName(df2) A: This is an add-on to @Steven's response (since I don't have enough reputation to comment directly under his post): Apart from the optional argument suggested by @minus34 for Spark 3.1+ and above, @Steven's solution (add_missing_columns) is a perfect workaround. However, calling withColumn introduces a projection internally, which when called in a large loop generates big plans that can potentially cause performance issues, eventually amounting to a StackOverflowError for large datasets. A scalable modification of @Steven's code could be: from pyspark.sql import DataFrame from pyspark.sql import functions as F from pyspark.sql import types as T def add_missing_columns(df: DataFrame, ref_df: DataFrame) -> DataFrame: """Add missing columns from ref_df to df Args: df (DataFrame): dataframe with missing columns ref_df (DataFrame): referential dataframe Returns: DataFrame: df with additionnal columns from ref_df """ missing_col = [] for col in ref_df.schema: if col.name not in df.columns: missing_col.append(col.name) df = df.select(['*'] + [F.lit(None).cast(T.NullType()).alias(c) for c in missing_col]) return df select is therefore a possible alternative, and it might be better to cast new empty columns of value None to NullType(), as you needn't specify the specific data type to cast this empty column to! (NullType() works fine in union and unionByName with any data type in spark)
Merge two spark dataframes with different columns to get all columns
Lets say I have 2 spark dataframes: Location Date Date_part Sector units USA 7/1/2021 7/1/2021 Cars 200 IND 7/1/2021 7/1/2021 Scooters 180 COL 7/1/2021 7/1/2021 Trucks 100 Location Date Brands units values UK null brand1 400 120 AUS null brand2 450 230 CAN null brand3 150 34 I need my resultant dataframe as Location Date Date_part Sector Brands units values USA 7/1/2021 7/1/2021 Cars 200 IND 7/1/2021 7/1/2021 Scooters 180 COL 7/1/2021 7/1/2021 Trucks 100 UK null 7/1/2021 brand1 400 120 AUS null 7/1/2021 brand2 450 230 CAN null 7/1/2021 brand3 150 34 So my desired df should contain all column from both dataframes also I need Date_part in all rows This is what I tried: df_result= df1.union(df_2) But Im getting this as my result. The values are being swapped and one column from second dataframe is missing. Location Date Date_part Sector Brands units USA 7/1/2021 7/1/2021 Cars 200 IND 7/1/2021 7/1/2021 Scooters 180 COL 7/1/2021 7/1/2021 Trucks 100 UK null brand1 400 120 AUS null brand2 450 230 CAN null brand3 150 34 Any suggestions plsss
[ "union : this function resolves columns by position (not by name)\nThat is the reason why you believed \"The values are being swapped and one column from second dataframe is missing.\"\nYou should use unionByName, but this functions requires both dataframe to have the same structure.\nI offer you this simple code to harmonize the structure of your dataframes and then do the union(ByName).\nfrom pyspark.sql import DataFrame\nfrom pyspark.sql import functions as F\n\ndef add_missing_columns(df: DataFrame, ref_df: DataFrame) -> DataFrame:\n \"\"\"Add missing columns from ref_df to df\n\n Args:\n df (DataFrame): dataframe with missing columns\n ref_df (DataFrame): referential dataframe\n\n Returns:\n DataFrame: df with additionnal columns from ref_df\n \"\"\"\n for col in ref_df.schema:\n if col.name not in df.columns:\n df = df.withColumn(col.name, F.lit(None).cast(col.dataType))\n\n return df\n\n\ndf1 = add_missing_columns(df1, df2)\ndf2 = add_missing_columns(df2, df1)\n\ndf_result = df1.unionByName(df2)\n\n", "This is an add-on to @Steven's response (since I don't have enough reputation to comment directly under his post):\nApart from the optional argument suggested by @minus34 for Spark 3.1+ and above, @Steven's solution (add_missing_columns) is a perfect workaround. However, calling withColumn introduces a projection internally, which when called in a large loop generates big plans that can potentially cause performance issues, eventually amounting to a StackOverflowError for large datasets.\nA scalable modification of @Steven's code could be:\nfrom pyspark.sql import DataFrame\nfrom pyspark.sql import functions as F\nfrom pyspark.sql import types as T\n\ndef add_missing_columns(df: DataFrame, ref_df: DataFrame) -> DataFrame:\n \"\"\"Add missing columns from ref_df to df\n\n Args:\n df (DataFrame): dataframe with missing columns\n ref_df (DataFrame): referential dataframe\n\n Returns:\n DataFrame: df with additionnal columns from ref_df\n \"\"\"\n missing_col = []\n for col in ref_df.schema:\n if col.name not in df.columns:\n missing_col.append(col.name)\n \n df = df.select(['*'] + [F.lit(None).cast(T.NullType()).alias(c) for c in missing_col])\n\n return df\n\nselect is therefore a possible alternative, and it might be better to cast new empty columns of value None to NullType(), as you needn't specify the specific data type to cast this empty column to! (NullType() works fine in union and unionByName with any data type in spark)\n" ]
[ 2, 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0068844904_apache_spark_pyspark_python.txt
Q: Python giving a key error while inside a Try/Except loop I am running the code: CODE def create_hec_kw(self, kw): print(f'Creating Keyword {kw}') data = {'name': kw, 'slug': kw.lower().replace(' ', '-')} response = requests.post(self.create_url('tags'), headers=self.get_headers(), json=data) # created_kw_id = response.json()['data']['term_id'] if response.json()['code'] else response.json()['id'] print(f'The keyword response is {response.json()}') try: if response.json()['code']: created_kw_id = response.json()['data']['term_id'] else: created_kw_id = response.json()['id'] print(f'The id is {created_kw_id}') return created_kw_id except TypeError: created_kw_id = '' return created_kw_id I am getting an error key not found "code" when the response doesn't contain code. I understand why the error is occurring (the JSON response) doesn't contain that key. What I want to understand is why is it crashing my app (Flask hosted on Heroku) instead of gracefully going to the except TypeError part of my code. Isn't this the reason I would have a try loop? I am sure I have done some thing wrong, but I wanted to better understand the behavior. A: Use KeyError instead of TypeError to catch it.
Python giving a key error while inside a Try/Except loop
I am running the code: CODE def create_hec_kw(self, kw): print(f'Creating Keyword {kw}') data = {'name': kw, 'slug': kw.lower().replace(' ', '-')} response = requests.post(self.create_url('tags'), headers=self.get_headers(), json=data) # created_kw_id = response.json()['data']['term_id'] if response.json()['code'] else response.json()['id'] print(f'The keyword response is {response.json()}') try: if response.json()['code']: created_kw_id = response.json()['data']['term_id'] else: created_kw_id = response.json()['id'] print(f'The id is {created_kw_id}') return created_kw_id except TypeError: created_kw_id = '' return created_kw_id I am getting an error key not found "code" when the response doesn't contain code. I understand why the error is occurring (the JSON response) doesn't contain that key. What I want to understand is why is it crashing my app (Flask hosted on Heroku) instead of gracefully going to the except TypeError part of my code. Isn't this the reason I would have a try loop? I am sure I have done some thing wrong, but I wanted to better understand the behavior.
[ "Use KeyError instead of TypeError to catch it.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074484004_python.txt
Q: How do I isolate a specific key from a dictionary using greater or less than arguments on a string of values? Just started coding; so, I am happy to clarify if there are questions. I have a dictionary where each key is associated with a string of 2 values my_dict = {'KEY##' : (X, Y)} e.g., my_dict = {'CAR10' : (4, -3), 'BAT15' : (2, 5), 'DOG22' : (-2, 1)} I would like to isolate and print out any key(s) where, for example, -1<X<3 and 3<Y<7 I've tried doing this using an iterative process and basic if/then statements; however, nothing I have tried has been "legal", so to speak (I always get error messages, all of them different). A: I think this list comprehenshion is what you want: my_filtered_keys = [k for (k, (x, y)) in my_dict.items() if -1<x<3 and 3<y<7] print(my_filtered_keys)
How do I isolate a specific key from a dictionary using greater or less than arguments on a string of values?
Just started coding; so, I am happy to clarify if there are questions. I have a dictionary where each key is associated with a string of 2 values my_dict = {'KEY##' : (X, Y)} e.g., my_dict = {'CAR10' : (4, -3), 'BAT15' : (2, 5), 'DOG22' : (-2, 1)} I would like to isolate and print out any key(s) where, for example, -1<X<3 and 3<Y<7 I've tried doing this using an iterative process and basic if/then statements; however, nothing I have tried has been "legal", so to speak (I always get error messages, all of them different).
[ "I think this list comprehenshion is what you want:\nmy_filtered_keys = [k for (k, (x, y)) in my_dict.items() if -1<x<3 and 3<y<7]\nprint(my_filtered_keys)\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074484468_dictionary_python.txt
Q: Logistic growth curve using scipy is not quite right I'm trying to fit a simple logistic growth model to dummy data using Python's Scipy package. The code is shown below, along with the output that I get. The correct output is shown below it. I'm not quite sure what's going wrong here. import scipy.optimize as optim from scipy.integrate import odeint import numpy as np import pandas as pd N0 = 0.37 parsic = [.25, 12.9] df_yeast = pd.DataFrame({'cd': [9.6, 18.3, 29., 47.2, 71.1, 119.1, 174.6, 257.3, 350.7, 441., 513.3, 559.7, 594.8, 629.4, 640.8, 651.1, 655.9, 659.6], 'td': np.arange(18)}) def logistic_de(t, N, r, K): return r*N*(1 - N/K) def logistic_solution(t, r, K): return odeint(logistic_de, N0, t, (r, K), tfirst=True).ravel() params, _ = optim.curve_fit(logistic_solution, df_yeast['td'], df_yeast['cd'], p0=parsic) N1 = odeint(logistic_de, N0, np.linspace(0, 20, 10000), (params[0], params[1]), tfirst=True) plt.plot(np.linspace(0, 20, 10000), N1) plt.scatter(df_yeast['td'], df_yeast['cd']) plt.ylabel('num yeast') plt.xlabel('time') My output: Correct output: A: Your optimization does not allow changing N0, which is dramatically different from the actual t=0 value in the list. A: This is the edit they're hinting at, maybe this'll help you understand: # include N0 as an argument def logistic_solution(t, N0, r, K): return odeint(logistic_de, N0, t, (r, K), tfirst=True).ravel() # N0 thus included as parameter to fit params, _ = optim.curve_fit(logistic_solution, df_yeast['td'], df_yeast['cd'], p0=[N0, *parsic]) # N1 integral factors in the fitted N0 parameter # (not the same as the global variable named N0, # should change global variable to something like N0_guess) N1 = odeint(logistic_de, params[0], np.linspace(0, 20, 10000), tuple(params[1:]), tfirst=True) A: why not try fit growth curve directly def my_logistic(t, a, b, c): return c / (1 + a * np.exp(-b*t)) params, _ = optim.curve_fit(my_logistic, df_yeast['td'], df_yeast['cd'], p0=np.random.exponential(size=3), bounds=(0,[100000., 3., 700])) N1 = my_logistic(np.linspace(0, 20, 10000),*params) plt.plot(np.linspace(0, 20, 10000), N1) plt.scatter(df_yeast['td'], df_yeast['cd']) plt.ylabel('num yeast') plt.xlabel('time') get the curve below: and params: [7.18068070e+01 5.47614074e-01 6.62655252e+02]
Logistic growth curve using scipy is not quite right
I'm trying to fit a simple logistic growth model to dummy data using Python's Scipy package. The code is shown below, along with the output that I get. The correct output is shown below it. I'm not quite sure what's going wrong here. import scipy.optimize as optim from scipy.integrate import odeint import numpy as np import pandas as pd N0 = 0.37 parsic = [.25, 12.9] df_yeast = pd.DataFrame({'cd': [9.6, 18.3, 29., 47.2, 71.1, 119.1, 174.6, 257.3, 350.7, 441., 513.3, 559.7, 594.8, 629.4, 640.8, 651.1, 655.9, 659.6], 'td': np.arange(18)}) def logistic_de(t, N, r, K): return r*N*(1 - N/K) def logistic_solution(t, r, K): return odeint(logistic_de, N0, t, (r, K), tfirst=True).ravel() params, _ = optim.curve_fit(logistic_solution, df_yeast['td'], df_yeast['cd'], p0=parsic) N1 = odeint(logistic_de, N0, np.linspace(0, 20, 10000), (params[0], params[1]), tfirst=True) plt.plot(np.linspace(0, 20, 10000), N1) plt.scatter(df_yeast['td'], df_yeast['cd']) plt.ylabel('num yeast') plt.xlabel('time') My output: Correct output:
[ "Your optimization does not allow changing N0, which is dramatically different from the actual t=0 value in the list.\n", "This is the edit they're hinting at, maybe this'll help you understand:\n# include N0 as an argument\ndef logistic_solution(t, N0, r, K):\n return odeint(logistic_de, N0, t, (r, K), tfirst=True).ravel()\n\n# N0 thus included as parameter to fit\nparams, _ = optim.curve_fit(logistic_solution, df_yeast['td'], df_yeast['cd'], \n p0=[N0, *parsic])\n\n# N1 integral factors in the fitted N0 parameter\n# (not the same as the global variable named N0,\n# should change global variable to something like N0_guess)\nN1 = odeint(logistic_de, params[0], np.linspace(0, 20, 10000), \n tuple(params[1:]), tfirst=True)\n\n", "why not try fit growth curve directly\ndef my_logistic(t, a, b, c):\n return c / (1 + a * np.exp(-b*t))\n\nparams, _ = optim.curve_fit(my_logistic, \n df_yeast['td'], df_yeast['cd'],\n p0=np.random.exponential(size=3),\n bounds=(0,[100000., 3., 700]))\nN1 = my_logistic(np.linspace(0, 20, 10000),*params)\n\nplt.plot(np.linspace(0, 20, 10000), N1)\nplt.scatter(df_yeast['td'], df_yeast['cd'])\nplt.ylabel('num yeast')\nplt.xlabel('time')\n\nget the curve below:\n\nand params:\n[7.18068070e+01 5.47614074e-01 6.62655252e+02]\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "differential_equations", "python", "scipy" ]
stackoverflow_0069292456_differential_equations_python_scipy.txt
Q: Return position of columns with the same name in pandas I would like to get the position of columns with the same name (that is column A). DataFrame a: A B A C text1 text3 text5 text7 text2 text4 text6 text8 I can get position of column A but how to get the position of the second column. There are multiple dataframe with different number of columns and position of A are not the same across the dataframes. Thank you. for col in a.columns: if col == 'A': indx1 = a.columns.get_loc(col) #if second column A indx2 = a.columns.get_loc(col) A: Your result can be easily achieved using np.where(). df = pd.DataFrame( data=[["text1", "text2", "text5", "text7"], ["text2", "text4", "text6", "text8"]], columns=["A", "B", "A", "D"], ) np.where(df.columns == "A")[0] Output: array([0, 2], dtype=int64) A: res = [] for index, col in enumerate(a.columns): if col == 'A': res.append(index) print(res) This will give you the position of all columns with the same name A: As a one liner, this returns the index positions of columns which are repeated: indexes = [i for i, j in zip(range(len(df.columns)), df.columns) if j in df.loc[:, df.columns.value_counts() > 1].columns] It returns: [0, 2] in this case because column A is repeated. A: if find 'A': np.where(df.columns == 'A')[0] result: array([0, 2], dtype=int64) if find all duplicated column name: np.where(df.columns.duplicated(keep=False))[0] result: array([0, 2], dtype=int64)
Return position of columns with the same name in pandas
I would like to get the position of columns with the same name (that is column A). DataFrame a: A B A C text1 text3 text5 text7 text2 text4 text6 text8 I can get position of column A but how to get the position of the second column. There are multiple dataframe with different number of columns and position of A are not the same across the dataframes. Thank you. for col in a.columns: if col == 'A': indx1 = a.columns.get_loc(col) #if second column A indx2 = a.columns.get_loc(col)
[ "Your result can be easily achieved using np.where().\ndf = pd.DataFrame(\n data=[[\"text1\", \"text2\", \"text5\", \"text7\"], [\"text2\", \"text4\", \"text6\", \"text8\"]],\n columns=[\"A\", \"B\", \"A\", \"D\"],\n)\nnp.where(df.columns == \"A\")[0]\n\nOutput:\narray([0, 2], dtype=int64)\n\n", "res = []\nfor index, col in enumerate(a.columns):\n if col == 'A':\n res.append(index)\n\nprint(res)\n\nThis will give you the position of all columns with the same name\n", "As a one liner, this returns the index positions of columns which are repeated:\nindexes = [i for i, j in zip(range(len(df.columns)), df.columns) if j in df.loc[:, df.columns.value_counts() > 1].columns]\n\nIt returns: [0, 2] in this case because column A is repeated.\n", "if find 'A':\nnp.where(df.columns == 'A')[0]\n\nresult:\narray([0, 2], dtype=int64)\n\n\nif find all duplicated column name:\nnp.where(df.columns.duplicated(keep=False))[0]\n\nresult:\narray([0, 2], dtype=int64)\n\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074484498_pandas_python.txt
Q: Get class that defined method How can I get the class that defined a method in Python? I'd want the following example to print "__main__.FooClass": class FooClass: def foo_method(self): print "foo" class BarClass(FooClass): pass bar = BarClass() print get_class_that_defined_method(bar.foo_method) A: import inspect def get_class_that_defined_method(meth): for cls in inspect.getmro(meth.im_class): if meth.__name__ in cls.__dict__: return cls return None A: I don't know why no one has ever brought this up or why the top answer has 50 upvotes when it is slow as hell, but you can also do the following: def get_class_that_defined_method(meth): return meth.im_class.__name__ For python 3 I believe this changed and you'll need to look into .__qualname__. A: In Python 3, if you need the actual class object you can do: import sys f = Foo.my_function vars(sys.modules[f.__module__])[f.__qualname__.split('.')[0]] # Gets Foo object If the function could belong to a nested class you would need to iterate as follows: f = Foo.Bar.my_function vals = vars(sys.modules[f.__module__]) for attr in f.__qualname__.split('.')[:-1]: vals = vals[attr] # vals is now the class Foo.Bar A: Thanks Sr2222 for pointing out I was missing the point... Here's the corrected approach which is just like Alex's but does not require to import anything. I don't think it's an improvement though, unless there's a huge hierarchy of inherited classes as this approach stops as soon as the defining class is found, instead of returning the whole inheritance as getmro does. As said, this is a very unlikely scenario. def get_class_that_defined_method(method): method_name = method.__name__ if method.__self__: classes = [method.__self__.__class__] else: #unbound method classes = [method.im_class] while classes: c = classes.pop() if method_name in c.__dict__: return c else: classes = list(c.__bases__) + classes return None And the Example: >>> class A(object): ... def test(self): pass >>> class B(A): pass >>> class C(B): pass >>> class D(A): ... def test(self): print 1 >>> class E(D,C): pass >>> get_class_that_defined_method(A().test) <class '__main__.A'> >>> get_class_that_defined_method(A.test) <class '__main__.A'> >>> get_class_that_defined_method(B.test) <class '__main__.A'> >>> get_class_that_defined_method(C.test) <class '__main__.A'> >>> get_class_that_defined_method(D.test) <class '__main__.D'> >>> get_class_that_defined_method(E().test) <class '__main__.D'> >>> get_class_that_defined_method(E.test) <class '__main__.D'> >>> E().test() 1 Alex solution returns the same results. As long as Alex approach can be used, I would use it instead of this one. A: Python 3 Solved it in a very simple way: str(bar.foo_method).split(" ", 3)[-2] This gives 'FooClass.foo_method' Split on the dot to get the class and the function name separately A: I found __qualname__ is useful in Python3. I test it like that: class Cls(object): def func(self): print('1') c = Cls() print(c.func.__qualname__) # output is: 'Cls.func' def single_func(): print(2) print(single_func.__module__) # output: '__main__' print(single_func.__qualname__) # output: 'single_func' After my test, I found another answer here. A: I started doing something somewhat similar, basically the idea was checking whenever a method in a base class had been implemented or not in a sub class. Turned out the way I originally did it I could not detect when an intermediate class was actually implementing the method. My workaround for it was quite simple actually; setting a method attribute and testing its presence later. Here's an simplification of the whole thing: class A(): def method(self): pass method._orig = None # This attribute will be gone once the method is implemented def run_method(self, *args, **kwargs): if hasattr(self.method, '_orig'): raise Exception('method not implemented') self.method(*args, **kwargs) class B(A): pass class C(B): def method(self): pass class D(C): pass B().run_method() # ==> Raises Exception: method not implemented C().run_method() # OK D().run_method() # OK UPDATE: Actually call method() from run_method() (isn't that the spirit?) and have it pass all arguments unmodified to the method. P.S.: This answer does not directly answer the question. IMHO there are two reasons one would want to know which class defined a method; first is to point fingers at a class in debug code (such as in exception handling), and the second is to determine if the method has been re-implemented (where method is a stub meant to be implemented by the programmer). This answer solves that second case in a different way.
Get class that defined method
How can I get the class that defined a method in Python? I'd want the following example to print "__main__.FooClass": class FooClass: def foo_method(self): print "foo" class BarClass(FooClass): pass bar = BarClass() print get_class_that_defined_method(bar.foo_method)
[ "import inspect\n\ndef get_class_that_defined_method(meth):\n for cls in inspect.getmro(meth.im_class):\n if meth.__name__ in cls.__dict__: \n return cls\n return None\n\n", "I don't know why no one has ever brought this up or why the top answer has 50 upvotes when it is slow as hell, but you can also do the following: \ndef get_class_that_defined_method(meth):\n return meth.im_class.__name__\n\nFor python 3 I believe this changed and you'll need to look into .__qualname__.\n", "In Python 3, if you need the actual class object you can do:\nimport sys\nf = Foo.my_function\nvars(sys.modules[f.__module__])[f.__qualname__.split('.')[0]] # Gets Foo object\n\nIf the function could belong to a nested class you would need to iterate as follows:\nf = Foo.Bar.my_function\nvals = vars(sys.modules[f.__module__])\nfor attr in f.__qualname__.split('.')[:-1]:\n vals = vals[attr]\n# vals is now the class Foo.Bar\n\n", "Thanks Sr2222 for pointing out I was missing the point...\nHere's the corrected approach which is just like Alex's but does not require to import anything. I don't think it's an improvement though, unless there's a huge hierarchy of inherited classes as this approach stops as soon as the defining class is found, instead of returning the whole inheritance as getmro does. As said, this is a very unlikely scenario.\ndef get_class_that_defined_method(method):\n method_name = method.__name__\n if method.__self__: \n classes = [method.__self__.__class__]\n else:\n #unbound method\n classes = [method.im_class]\n while classes:\n c = classes.pop()\n if method_name in c.__dict__:\n return c\n else:\n classes = list(c.__bases__) + classes\n return None\n\nAnd the Example:\n>>> class A(object):\n... def test(self): pass\n>>> class B(A): pass\n>>> class C(B): pass\n>>> class D(A):\n... def test(self): print 1\n>>> class E(D,C): pass\n\n>>> get_class_that_defined_method(A().test)\n<class '__main__.A'>\n>>> get_class_that_defined_method(A.test)\n<class '__main__.A'>\n>>> get_class_that_defined_method(B.test)\n<class '__main__.A'>\n>>> get_class_that_defined_method(C.test)\n<class '__main__.A'>\n>>> get_class_that_defined_method(D.test)\n<class '__main__.D'>\n>>> get_class_that_defined_method(E().test)\n<class '__main__.D'>\n>>> get_class_that_defined_method(E.test)\n<class '__main__.D'>\n>>> E().test()\n1\n\nAlex solution returns the same results. As long as Alex approach can be used, I would use it instead of this one.\n", "Python 3\nSolved it in a very simple way:\nstr(bar.foo_method).split(\" \", 3)[-2]\nThis gives\n'FooClass.foo_method'\nSplit on the dot to get the class and the function name separately\n", "I found __qualname__ is useful in Python3.\nI test it like that:\nclass Cls(object):\n def func(self):\n print('1')\n\nc = Cls()\nprint(c.func.__qualname__)\n# output is: 'Cls.func'\n\ndef single_func():\n print(2)\n\nprint(single_func.__module__)\n# output: '__main__'\nprint(single_func.__qualname__)\n# output: 'single_func'\n\nAfter my test, I found another answer here.\n", "I started doing something somewhat similar, basically the idea was checking whenever a method in a base class had been implemented or not in a sub class. Turned out the way I originally did it I could not detect when an intermediate class was actually implementing the method.\nMy workaround for it was quite simple actually; setting a method attribute and testing its presence later. Here's an simplification of the whole thing:\nclass A():\n def method(self):\n pass\n method._orig = None # This attribute will be gone once the method is implemented\n\n def run_method(self, *args, **kwargs):\n if hasattr(self.method, '_orig'):\n raise Exception('method not implemented')\n self.method(*args, **kwargs)\n\nclass B(A):\n pass\n\nclass C(B):\n def method(self):\n pass\n\nclass D(C):\n pass\n\nB().run_method() # ==> Raises Exception: method not implemented\nC().run_method() # OK\nD().run_method() # OK\n\nUPDATE: Actually call method() from run_method() (isn't that the spirit?) and have it pass all arguments unmodified to the method.\nP.S.: This answer does not directly answer the question. IMHO there are two reasons one would want to know which class defined a method; first is to point fingers at a class in debug code (such as in exception handling), and the second is to determine if the method has been re-implemented (where method is a stub meant to be implemented by the programmer). This answer solves that second case in a different way.\n" ]
[ 78, 13, 9, 8, 2, 2, 1 ]
[]
[]
[ "python", "python_2.6", "python_datamodel" ]
stackoverflow_0000961048_python_python_2.6_python_datamodel.txt
Q: how to remove dictionary element by outlier values Python Suppose my dictionary contains > 100 elements and one or two elements have values different than other values; most values are the same (12 in the below example). How can I remove these a few elements? Diction = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2} I want a dictionary object: Diction = {1:12,2:12,4:12,5:12,6:12,7:12} A: d = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2} new_d = {} unique_values = [] unique_count = [] most_occurence = 0 # Find unique values for k, v in d.items(): if v not in unique_values: unique_values.append(v) # Count their occurrences def count(dict, unique_value): count = 0 for k, v in d.items(): if v == unique_value: count +=1 return count for value in unique_values: occurrences = count(d, value) unique_count.append( (value, occurrences) ) # Find which value has most occurences for occurrence in unique_count: if occurrence[1] > most_occurence: most_occurence = occurrence[0] # Create new dict with keys of most occurred value for k, v in d.items(): if v == most_occurence: new_d[k] = v print(new_d) Nothing fancy, but direct to the point. There should be many ways to optimize this. Output: {1: 12, 2: 12, 4: 12, 5: 12, 6: 12, 7: 12} A: It may be a bit slow because of the looping (especially as the size of the dictionary gets very large) and have to use numpy, but this will work import numpy as np Diction = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2} dict_list = [] for x in Diction: dict_list.append(Diction[x]) dict_array = np.array(dict_list) unique, counts = np.unique(dict_array, return_counts=True) most_common = unique[np.argmax(counts)] new_Diction = {} for x in Diction: if Diction[x] == most_common: new_Diction[x] = most_common print(new_Diction) Output {1: 12, 2: 12, 4: 12, 5: 12, 6: 12, 7: 12}
how to remove dictionary element by outlier values Python
Suppose my dictionary contains > 100 elements and one or two elements have values different than other values; most values are the same (12 in the below example). How can I remove these a few elements? Diction = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2} I want a dictionary object: Diction = {1:12,2:12,4:12,5:12,6:12,7:12}
[ "d = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2}\nnew_d = {}\n\nunique_values = []\nunique_count = []\nmost_occurence = 0\n\n# Find unique values\nfor k, v in d.items():\n if v not in unique_values:\n unique_values.append(v)\n\n# Count their occurrences\ndef count(dict, unique_value):\n count = 0\n for k, v in d.items():\n if v == unique_value:\n count +=1\n\n return count\n\nfor value in unique_values:\n occurrences = count(d, value)\n unique_count.append( (value, occurrences) )\n\n# Find which value has most occurences\nfor occurrence in unique_count:\n if occurrence[1] > most_occurence:\n most_occurence = occurrence[0]\n\n# Create new dict with keys of most occurred value\nfor k, v in d.items():\n if v == most_occurence:\n new_d[k] = v\n\nprint(new_d)\n\nNothing fancy, but direct to the point. There should be many ways to optimize this.\nOutput: {1: 12, 2: 12, 4: 12, 5: 12, 6: 12, 7: 12}\n\n", "It may be a bit slow because of the looping (especially as the size of the dictionary gets very large) and have to use numpy, but this will work\nimport numpy as np\n\nDiction = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2}\n\ndict_list = []\nfor x in Diction:\n dict_list.append(Diction[x])\n \ndict_array = np.array(dict_list)\nunique, counts = np.unique(dict_array, return_counts=True)\nmost_common = unique[np.argmax(counts)]\n\nnew_Diction = {}\nfor x in Diction:\n if Diction[x] == most_common:\n new_Diction[x] = most_common\n \nprint(new_Diction)\n\nOutput\n{1: 12, 2: 12, 4: 12, 5: 12, 6: 12, 7: 12}\n\n" ]
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074484416_dictionary_python.txt
Q: How to send 'Headers' in websocket python how can i make this This is my code import websockets async def test(): async with websockets.connect('ws://iqoption.com') as websocket: response = await websocket.recv() print(response) # Client async code The cuestion is , can i send this headers to get Authenticated in the server Headers 'Host':'iqoption.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0', 'Accept' : '*/*', 'Accept-Encoding': 'gzip, deflate', 'Sec-WebSocket-Version' : '13', 'Origin' : 'https://iqoption.com', 'Sec-WebSocket-Key': 'iExBWv1j6sC1uee2qD+QPQ==', 'Connection' : 'keep-alive, Upgrade', 'Upgrade': 'websocket'} I could do it with this other code but the messages were still encrypted with tls proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"} urllib3.disable_warnings() r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers, proxies=proxies, verify=False) #r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers) s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM) def receive_and_print(): #for message in iter(lambda: s.recv(1024).decode("utf-8", errors="replace"), ''): for message in iter(lambda: s.recv(1024).decode( errors="replace"), ''): print(":", message) print("") import threading background_thread = threading.Thread(target=receive_and_print) background_thread.daemon = True background_thread.start() while 1: s.send(input("Please enter your message: ").encode()) print("Sent") print("") Any advice?? A: I think you are currently missing a basic understanding of WebSockets as is shown on your previous experiments. WebSockets are not plain sockets. WebSockets are some socket-like think created after a HTTP handshake. You cannot just take the socket from the connection as you've tried after requests but you have to explicitly speak the WebSocket application protocol, defined in RFC 6455. That said, using a library like websockets is much better. But you still have to use the actual WebSocket endpoint as target and not just some arbitrary URL on the same server. The endpoint in this case is not ws://iqoption.com but wss://iqoption.com/echo/websocket, i.e. a longer path and wss:// instead of ws://. Without the proper URL you get error messages you seem to interpret as authentication problems. But there is no authentication involved here at all. Once you use the proper endpoint it simply works without any need to send specific headers: async def test(): async with websockets.connect("wss://iqoption.com/echo/websocket") as websocket: response = await websocket.recv() print(response) A: I think you can directly add headers in the request. Here's my example using websockets. async def hello(uri): async with websockets.connect(uri=uri, extra_headers= {'Auth':'yourTokenHere'}) as websocket: await websocket.send(json.dumps({"action":"hello", "message":"hi"})) # AWS.APIGateway style for example message = await websocket.recv() Btw, the way I figured out about the extra_headers is but directly checking the code here. And they do have a good documentation here.
How to send 'Headers' in websocket python
how can i make this This is my code import websockets async def test(): async with websockets.connect('ws://iqoption.com') as websocket: response = await websocket.recv() print(response) # Client async code The cuestion is , can i send this headers to get Authenticated in the server Headers 'Host':'iqoption.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0', 'Accept' : '*/*', 'Accept-Encoding': 'gzip, deflate', 'Sec-WebSocket-Version' : '13', 'Origin' : 'https://iqoption.com', 'Sec-WebSocket-Key': 'iExBWv1j6sC1uee2qD+QPQ==', 'Connection' : 'keep-alive, Upgrade', 'Upgrade': 'websocket'} I could do it with this other code but the messages were still encrypted with tls proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"} urllib3.disable_warnings() r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers, proxies=proxies, verify=False) #r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers) s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM) def receive_and_print(): #for message in iter(lambda: s.recv(1024).decode("utf-8", errors="replace"), ''): for message in iter(lambda: s.recv(1024).decode( errors="replace"), ''): print(":", message) print("") import threading background_thread = threading.Thread(target=receive_and_print) background_thread.daemon = True background_thread.start() while 1: s.send(input("Please enter your message: ").encode()) print("Sent") print("") Any advice??
[ "I think you are currently missing a basic understanding of WebSockets as is shown on your previous experiments. WebSockets are not plain sockets. WebSockets are some socket-like think created after a HTTP handshake. You cannot just take the socket from the connection as you've tried after requests but you have to explicitly speak the WebSocket application protocol, defined in RFC 6455.\nThat said, using a library like websockets is much better. But you still have to use the actual WebSocket endpoint as target and not just some arbitrary URL on the same server. The endpoint in this case is not\nws://iqoption.com but wss://iqoption.com/echo/websocket, i.e. a longer path and wss:// instead of ws://.\nWithout the proper URL you get error messages you seem to interpret as authentication problems. But there is no authentication involved here at all. Once you use the proper endpoint it simply works without any need to send specific headers:\nasync def test():\n async with websockets.connect(\"wss://iqoption.com/echo/websocket\") as websocket:\n response = await websocket.recv()\n print(response)\n\n", "I think you can directly add headers in the request. Here's my example using websockets.\nasync def hello(uri):\n async with websockets.connect(uri=uri, extra_headers= {'Auth':'yourTokenHere'}) as websocket:\n await websocket.send(json.dumps({\"action\":\"hello\", \"message\":\"hi\"})) # AWS.APIGateway style for example\n message = await websocket.recv()\n\nBtw, the way I figured out about the extra_headers is but directly checking the code here. And they do have a good documentation here.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "sockets", "websocket" ]
stackoverflow_0060308749_python_python_3.x_sockets_websocket.txt
Q: Creating a table with nested loops in python I'm learning abort nested loops and I've gotten an assignment to create a function that takes two integer inputs. Then it should create something like in this image. Only problem is that when I use an odd number for columns it doesnt work. It has to be an "advanced nested loop" for the assignment to be approved. def createTable(rows, columns): rows = int(input("Enter number of rows: ")) columns = int(input("Enter number of columns: ")) for row in range(rows): if row%2 == 0: for col in range(0, columns): if col%2 == 1: if col != columns - 1: print(" ", end="") else: print(" ") else: print("|", end="") else: print("-" * (columns - 1)) return True createTable(1, 2) A: I have made one iteration of the code which you want. It prints the correct output for even and odd number of rows and columns. It is very similar to the outputs you want. When you provide further clarification for your question, I can provide an updated code. rows = 20 columns = 41 for i in range(rows): if i%2 == 0: output = "| " * (columns//2) print(output) else: output = "-" * ((columns//2)*2 - 1) print(output) The output can be visualised below. Hope this solves your query. Based on the code provided by the question provider, I have edited the code and the following code will work in the same manner as you want it to with nested loops. def createtable(rows, columns): for row in range(rows): if row%2 == 0: for col in range(0, ((columns+1)//2)*2, 2): print("| ", end="") print() else: print("-" * (((columns+1)//2)*2 - 1)) return True Tested for both these cases. createTable(20, 40) createTable(20, 41) createTable(2, 1) A: def createTable(rows, columns): rows = int(input("Enter number of rows: ")) columns = int(input("Enter number of columns: ")) for row in range(rows): if row%2 == 0: for col in range(0, columns): if col%2 == 1: if col != columns - 1: print(" ", end="") else: print(" ") else: print("|", end="") else: print("-" * (columns - 1)) return True
Creating a table with nested loops in python
I'm learning abort nested loops and I've gotten an assignment to create a function that takes two integer inputs. Then it should create something like in this image. Only problem is that when I use an odd number for columns it doesnt work. It has to be an "advanced nested loop" for the assignment to be approved. def createTable(rows, columns): rows = int(input("Enter number of rows: ")) columns = int(input("Enter number of columns: ")) for row in range(rows): if row%2 == 0: for col in range(0, columns): if col%2 == 1: if col != columns - 1: print(" ", end="") else: print(" ") else: print("|", end="") else: print("-" * (columns - 1)) return True createTable(1, 2)
[ "I have made one iteration of the code which you want. It prints the correct output for even and odd number of rows and columns. It is very similar to the outputs you want. When you provide further clarification for your question, I can provide an updated code.\nrows = 20\ncolumns = 41\n\nfor i in range(rows):\n if i%2 == 0:\n output = \"| \" * (columns//2)\n print(output)\n else: \n output = \"-\" * ((columns//2)*2 - 1)\n print(output) \n\nThe output can be visualised below. Hope this solves your query.\n\nBased on the code provided by the question provider, I have edited the code and the following code will work in the same manner as you want it to with nested loops.\ndef createtable(rows, columns): \n for row in range(rows):\n if row%2 == 0: \n for col in range(0, ((columns+1)//2)*2, 2):\n print(\"| \", end=\"\")\n print()\n else:\n print(\"-\" * (((columns+1)//2)*2 - 1))\n\n return True\n\nTested for both these cases.\ncreateTable(20, 40)\ncreateTable(20, 41)\ncreateTable(2, 1)\n\n", "def createTable(rows, columns):\n rows = int(input(\"Enter number of rows: \"))\n columns = int(input(\"Enter number of columns: \"))\n\n for row in range(rows):\n if row%2 == 0: \n for col in range(0, columns):\n if col%2 == 1:\n if col != columns - 1:\n print(\" \", end=\"\")\n else:\n print(\" \")\n else:\n print(\"|\", end=\"\")\n else:\n print(\"-\" * (columns - 1))\n \n return True\n\n" ]
[ 0, 0 ]
[]
[]
[ "nested_loops", "python" ]
stackoverflow_0065792749_nested_loops_python.txt
Q: How to properly import the ConfigServiceV2Client attribute from google-cloud-logging_v2 package in Python? I tried importing the ConfigServiceV2Client attribute as follows: from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2Client And I got the following error: AttributeError: module 'google.cloud.logging_v2' has no attribute 'ConfigServiceV2Client' How should I import it? A: Based on the error that you're getting it seems like you are missing some updated features, Install the google-cloud-logging package using pip as follows: pip install --upgrade google-cloud-logging based on the google documentation. After installing it try importing it in to your project. Or just uninstall the package: pip uninstall google-cloud-logging And then reinstall it.
How to properly import the ConfigServiceV2Client attribute from google-cloud-logging_v2 package in Python?
I tried importing the ConfigServiceV2Client attribute as follows: from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2Client And I got the following error: AttributeError: module 'google.cloud.logging_v2' has no attribute 'ConfigServiceV2Client' How should I import it?
[ "Based on the error that you're getting it seems like you are missing some updated features, Install the google-cloud-logging package using pip as follows:\npip install --upgrade google-cloud-logging\nbased on the google documentation.\nAfter installing it try importing it in to your project.\nOr just uninstall the package:\npip uninstall google-cloud-logging\nAnd then reinstall it.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_logging", "python" ]
stackoverflow_0074479034_google_cloud_logging_python.txt
Q: What is causing the error (index out of range) def main(): plate = input("Plate: ") if is_valid(plate): print("Valid") else: print("Invalid") def is_valid(s): index = [] for i in s: if i.isdigit(): index += i break print(index) if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0': return True main() Before I added and index[0] != '0' the code worked perfectly, but for some reason after adding that piece of code, when I go to input "KEVIN" an error(index out of range) pops up. How do I prevent this error from popping while still checking out the requirements for the code in the if statement? A: A smaller example shows the problem def is_valid(s): index = [] for i in s: if i.isdigit(): index += i break print(index) if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0': return True is_valid("KEVIN") "KEVIN" doesn't contain any digits, i.isdigit() is never True and the index list remains empty. Add a check for that case. def is_valid(s): index = [] for i in s: if i.isdigit(): index += i break print(index) if (6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index and index[0] != '0'): return True A: The code does not consider the edge case for when the string s has no digits. In that case, index will be an empty list and index[0] != '0' will throw an error. Consider adding a condition to check for the length of s.
What is causing the error (index out of range)
def main(): plate = input("Plate: ") if is_valid(plate): print("Valid") else: print("Invalid") def is_valid(s): index = [] for i in s: if i.isdigit(): index += i break print(index) if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0': return True main() Before I added and index[0] != '0' the code worked perfectly, but for some reason after adding that piece of code, when I go to input "KEVIN" an error(index out of range) pops up. How do I prevent this error from popping while still checking out the requirements for the code in the if statement?
[ "A smaller example shows the problem\ndef is_valid(s):\n index = []\n for i in s:\n if i.isdigit():\n index += i\n break\n print(index)\n if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0':\n return True\n\nis_valid(\"KEVIN\")\n\n\"KEVIN\" doesn't contain any digits, i.isdigit() is never True and the index list remains empty. Add a check for that case.\ndef is_valid(s):\n index = []\n for i in s:\n if i.isdigit():\n index += i\n break\n print(index)\n if (6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() \n and index and index[0] != '0'):\n return True\n\n", "The code does not consider the edge case for when the string s has no digits. In that case, index will be an empty list and index[0] != '0' will throw an error. Consider adding a condition to check for the length of s.\n" ]
[ 1, 0 ]
[]
[]
[ "for_loop", "if_statement", "python", "python_3.x", "return" ]
stackoverflow_0074484709_for_loop_if_statement_python_python_3.x_return.txt
Q: Why doesn't httpx ssl context set cipher ctx = httpx.create_ssl_context() ctx.set_ciphers("TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_128_CBC_SHA:TLS_RSA_WITH_AES_256_CBC_SHA") That are the cipher suites I've got from my http debugger, but after running this it says ssl.SSLError: ('No cipher can be selected.',) I didn't even make a request so I think it's unsupported? Thanks in advance A: You need to ensure that every single cipher name there use OpenSSL's naming for the ciphers. There's a possibility one or more of the ciphers you used there are the "public" names, but OpenSSL has their own names for those ciphers. Take a look at this for the mapping: https://www.openssl.org/docs/man1.1.1/man1/ciphers.html
Why doesn't httpx ssl context set cipher
ctx = httpx.create_ssl_context() ctx.set_ciphers("TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_128_CBC_SHA:TLS_RSA_WITH_AES_256_CBC_SHA") That are the cipher suites I've got from my http debugger, but after running this it says ssl.SSLError: ('No cipher can be selected.',) I didn't even make a request so I think it's unsupported? Thanks in advance
[ "You need to ensure that every single cipher name there use OpenSSL's naming for the ciphers.\nThere's a possibility one or more of the ciphers you used there are the \"public\" names, but OpenSSL has their own names for those ciphers.\nTake a look at this for the mapping:\nhttps://www.openssl.org/docs/man1.1.1/man1/ciphers.html\n" ]
[ 0 ]
[]
[]
[ "encryption", "http", "httpx", "python", "ssl" ]
stackoverflow_0072265009_encryption_http_httpx_python_ssl.txt
Q: How to edit python3.10 resources to include collections.abc in place of collections due to AttributeError no attribute 'MutableMapping' Trying to install some image editing software (face recognition type). Ubuntu 18.04, python3.10 which took too much work to get it upgraded but was needed for the image software. Getting the AttributeError when I install numpy and none of the online threads solve this for me. Tried to install packages and the central issue seems to be python-numpy When I try to install numpy I get: AttributeError: module 'collections' has no attribute 'MutableMapping' Various threads give solutions that have worked for people but I am not finding any simple solution to solve my packages. In particular the wheel seems to import resources from a zip file. I've unzipped /usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl.zip that was listed in the log and edited pyparsing.py to import collections.abc NO LUCK THERE. Tried editing various other files such as main.py and init.py no success either. Is there a simple way maybe in the install with options to direct the build to include collections.abc, or even when I try to import numpy ? This seems to be one of the ongoing frustrations with linux that various software packages upgrade or ubuntu upgrades and it is difficult to keep them compatible. A: Looks like there are a lot of SO threads dealing with this. Since I had problems with my last Ubuntu upgrade, I'm currently using the windows boot, and Anaconda. Here: In [591]: sys.version Out[591]: '3.9.12 (main, Apr 4 2022, 05:22:27) [MSC v.1916 64 bit (AMD64)]' In [592]: np.__version__ Out[592]: '1.21.5' Looking at collections: In [594]: import collections In [595]: collections.MutableMapping C:\Users\paul\AppData\Local\Temp\ipykernel_7972\1388547110.py:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working collections.MutableMapping Out[595]: collections.abc.MutableMapping In [596]: collections.abc.MutableMapping Out[596]: collections.abc.MutableMapping So if a module tried to use collections.MutableMapping with your 3.10 it would encounter this error. I assume common packages like numpy have made such an correction, but I don't know as of when. I'm not an expert on these versions. Mostly I use what ever Python version is easiest to install, make sure I have the latest setup tools, and then use its pip3 to install the latest package versions.
How to edit python3.10 resources to include collections.abc in place of collections due to AttributeError no attribute 'MutableMapping'
Trying to install some image editing software (face recognition type). Ubuntu 18.04, python3.10 which took too much work to get it upgraded but was needed for the image software. Getting the AttributeError when I install numpy and none of the online threads solve this for me. Tried to install packages and the central issue seems to be python-numpy When I try to install numpy I get: AttributeError: module 'collections' has no attribute 'MutableMapping' Various threads give solutions that have worked for people but I am not finding any simple solution to solve my packages. In particular the wheel seems to import resources from a zip file. I've unzipped /usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl.zip that was listed in the log and edited pyparsing.py to import collections.abc NO LUCK THERE. Tried editing various other files such as main.py and init.py no success either. Is there a simple way maybe in the install with options to direct the build to include collections.abc, or even when I try to import numpy ? This seems to be one of the ongoing frustrations with linux that various software packages upgrade or ubuntu upgrades and it is difficult to keep them compatible.
[ "Looks like there are a lot of SO threads dealing with this. Since I had problems with my last Ubuntu upgrade, I'm currently using the windows boot, and Anaconda.\nHere:\nIn [591]: sys.version\nOut[591]: '3.9.12 (main, Apr 4 2022, 05:22:27) [MSC v.1916 64 bit (AMD64)]'\n\nIn [592]: np.__version__\nOut[592]: '1.21.5'\n\nLooking at collections:\nIn [594]: import collections\n\nIn [595]: collections.MutableMapping\nC:\\Users\\paul\\AppData\\Local\\Temp\\ipykernel_7972\\1388547110.py:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working\n collections.MutableMapping\nOut[595]: collections.abc.MutableMapping\n\nIn [596]: collections.abc.MutableMapping\nOut[596]: collections.abc.MutableMapping\n\nSo if a module tried to use collections.MutableMapping with your 3.10 it would encounter this error. I assume common packages like numpy have made such an correction, but I don't know as of when.\nI'm not an expert on these versions. Mostly I use what ever Python version is easiest to install, make sure I have the latest setup tools, and then use its pip3 to install the latest package versions.\n" ]
[ 0 ]
[]
[]
[ "collections", "numpy", "python", "python_3.10" ]
stackoverflow_0074484232_collections_numpy_python_python_3.10.txt
Q: Replace some string in python I have two address like: first_address = 'Красноярский край, г Красноярск, пр-кт им газеты Красноярский Рабочий, 152г, квартира (офис) /1' second_address = 'Красноярский край, г Красноярск, пр-кт им.газеты "Красноярский рабочий", 152г' And I want to replace all text before квартира (офис) /1 My code looks like: c = first_address.split(',') v = second_address.split(',') b = c[:len(v)] b = v n = c[len(v)::] f = ''.join(str(b)) + ''.join(str(n)) I get output: ['Красноярский край', ' г Красноярск', ' пр-кт им.газеты "Красноярский рабочий"', ' 152г'][' квартира (офис) /1'] How can I easily make this? A: Looks like you want to take substrings from second_address until they run out, then use substrings from first_address. Here's a straightforward way to do it. first_subs = first_address.split(',') second_subs = second_address.split(',') [(f if s is None else s) for (f, s) in zip(first_subs, second_subs + [None] * (len(first_subs) - len(second_subs)))]
Replace some string in python
I have two address like: first_address = 'Красноярский край, г Красноярск, пр-кт им газеты Красноярский Рабочий, 152г, квартира (офис) /1' second_address = 'Красноярский край, г Красноярск, пр-кт им.газеты "Красноярский рабочий", 152г' And I want to replace all text before квартира (офис) /1 My code looks like: c = first_address.split(',') v = second_address.split(',') b = c[:len(v)] b = v n = c[len(v)::] f = ''.join(str(b)) + ''.join(str(n)) I get output: ['Красноярский край', ' г Красноярск', ' пр-кт им.газеты "Красноярский рабочий"', ' 152г'][' квартира (офис) /1'] How can I easily make this?
[ "Looks like you want to take substrings from second_address until they run out, then use substrings from first_address. Here's a straightforward way to do it.\nfirst_subs = first_address.split(',')\nsecond_subs = second_address.split(',')\n[(f if s is None else s) \n for (f, s) in zip(first_subs, \n second_subs + [None] * (len(first_subs) - len(second_subs)))]\n\n" ]
[ 0 ]
[]
[]
[ "algorithm", "python", "replace", "string" ]
stackoverflow_0074484803_algorithm_python_replace_string.txt
Q: How to analyze source code by pygments(using pygount) and get a SUM Using pygount I am trying to get the SUM of: Codes, Comments and Empty. I do not have any errors but I think I messed my relative paths. Firstly check the tree below for a visualization C:\...\Projects\TestProject ├───utils │ ├───__init__.py │ └───loc.py └───launcher.py ROOT_DIR const def is inside __init__ of util folder. I am not sure if my relative path should have 1x or 2x .parent to reach "TestProject"(which is the root dir). from pathlib import Path from .loc import test ROOT_DIR = Path(__file__).parent.parent Below is the the .loc file from utils import ROOT_DIR class Counter: def __init__(self): self.code = 0 self.docs = 0 self.empty = 0 def count(self): for subdir, _, files in os.walk(ROOT_DIR / "TestProject"): for file in (f for f in files if f.endswith(".py")): analysis = SourceAnalysis.from_file(f"{subdir}/{file}", "pygount", encoding="utf-8") self.code += analysis.code_count self.docs += analysis.documentation_count self.empty += analysis.empty_count A: You can use os.path.join instead of /
How to analyze source code by pygments(using pygount) and get a SUM
Using pygount I am trying to get the SUM of: Codes, Comments and Empty. I do not have any errors but I think I messed my relative paths. Firstly check the tree below for a visualization C:\...\Projects\TestProject ├───utils │ ├───__init__.py │ └───loc.py └───launcher.py ROOT_DIR const def is inside __init__ of util folder. I am not sure if my relative path should have 1x or 2x .parent to reach "TestProject"(which is the root dir). from pathlib import Path from .loc import test ROOT_DIR = Path(__file__).parent.parent Below is the the .loc file from utils import ROOT_DIR class Counter: def __init__(self): self.code = 0 self.docs = 0 self.empty = 0 def count(self): for subdir, _, files in os.walk(ROOT_DIR / "TestProject"): for file in (f for f in files if f.endswith(".py")): analysis = SourceAnalysis.from_file(f"{subdir}/{file}", "pygount", encoding="utf-8") self.code += analysis.code_count self.docs += analysis.documentation_count self.empty += analysis.empty_count
[ "You can use os.path.join instead of /\n" ]
[ 0 ]
[]
[]
[ "pygments", "python" ]
stackoverflow_0067830036_pygments_python.txt
Q: Monte Carlo Python Question: Simulation of three dice in which the sum > 10, returns True, otherwise return False This is a Monte Carlo Simulation question. Here is my code. def simulate(): """ Simulate three dice and return true if sum is > 10 """ die_1 = randint(1,6) die_2 = randint(1, 6) die_3 = randint(1,6) sum = die_1 + die_2 + die_3 if sum > 10: return True else: return False The next steps are to use a for loop and call the simulate function to sum up the number of results that end up as True. My idea of doing this: true_results = 0 for trial in range(1000): true_results += simulate() However, how would I determine what is a True or False result? And does this code make sense? A: For checking, you can store all summation result to see whether the occurrence, and probability roughly match your expectation. Your code is fine if it is error-free although the indentation is weird. And i suggest not to use 'sum' as a variable name as it is a build in function name. It still works, but this may get u into trouble in the future.
Monte Carlo Python Question: Simulation of three dice in which the sum > 10, returns True, otherwise return False
This is a Monte Carlo Simulation question. Here is my code. def simulate(): """ Simulate three dice and return true if sum is > 10 """ die_1 = randint(1,6) die_2 = randint(1, 6) die_3 = randint(1,6) sum = die_1 + die_2 + die_3 if sum > 10: return True else: return False The next steps are to use a for loop and call the simulate function to sum up the number of results that end up as True. My idea of doing this: true_results = 0 for trial in range(1000): true_results += simulate() However, how would I determine what is a True or False result? And does this code make sense?
[ "For checking, you can store all summation result to see whether the occurrence, and probability roughly match your expectation.\nYour code is fine if it is error-free although the indentation is weird. And i suggest not to use 'sum' as a variable name as it is a build in function name. It still works, but this may get u into trouble in the future.\n" ]
[ 0 ]
[]
[]
[ "montecarlo", "python" ]
stackoverflow_0074484774_montecarlo_python.txt
Q: Find last duplicate character from string I have a string abbccdeefght,I want to find the last duplicate character from the string. For above string the result should be character 'e'. I tried using Counter from collections module in python. from collections import Counter c=Counter('abbccdeefght') c >>> Counter({'c': 2, 'b': 2, 'e': 2, 'a': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 't': 1}) but not sure how to proceed A: This way you will get index of last duplicate character def last_duplicate(line): c=Counter(line) #>>> Counter({'c': 2, 'b': 2, 'e': 2, 'a': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 't': 1}) for i, x in reversed(line): if c[x] > 1: return len(line) - i - 1 Surely you can find character itself easy enough A: Your problem is equivalent to finding the first duplicated character, if you move from right to left. For each character you check if it is already contained in the part to the right. Something like this: my_string = "abbccdeefght" for idx in range(len(my_string) - 2, -1, -1): char = my_string[idx] if char in my_string[idx + 1:]: print("Last duplicated character is: " + char) break Explanation: Using range we iterate idx from number that is 2 less than the lenght of the string, all the way to 0. Every time we take a character from position idx and see if it is already contained in the part of my_string that is to the right of character at position idx. If it is, we do print() and end our loop. Edit: Upon your further explanation, here is fixed code (it wasn't clear from your question). Now we also iterate characters from right to left, but check if the character is contained in the part to the left. my_string = "abba" for idx in range(len(my_string) - 1, 0, -1): char = my_string[idx] if char in my_string[:idx]: print("Last duplicated character is: " + char) break A: input_string='abbccdeefght' last_duplicate_string=[single_letter for single_letter in input_string if input_string.count(single_letter) > 1] if last_duplicate_string: print "Last duplicate character from the string %s",last_duplicate_string[-1] else: print "No duplicate character" A: You can do it with simple algorithm mystr = 'abbccdeefght' size = len(mystr)-1 found = 0 i=0 while (1): if (mystr[size]==mystr[i]): print ("found ",mystr[size]," on index ",i+1," and index ",size+1) break i+=1 if (i==size): i=0 size-=1 if (size==1): print ("not found") break The loops will break upon 2 condition. Found and no more data to be checked. Hope it helps A: You can try this code. Tested for "", "abba", "zzasd", "zxcv", "abbccdeefght" # enumerates reversed list def reverse_enumerate(seq): p = -1 for elem in seq[::-1]: yield p, elem p -= 1 str = "abbccdeefght" for i, c in reverse_enumerate(str): # check element in left side if c in str[i-1::-1]: print(c, i) # print element, position break A: a = 'abbccdeefght' a=a[::-1] #reverse the string and helps to get the last repeating characters for char in a: counter = a.count(char) #checking count of the character in string if counter > 1: #if count is greater than 1 then it is duplicate print(char+' is the last repeting character in string') #printing the result break
Find last duplicate character from string
I have a string abbccdeefght,I want to find the last duplicate character from the string. For above string the result should be character 'e'. I tried using Counter from collections module in python. from collections import Counter c=Counter('abbccdeefght') c >>> Counter({'c': 2, 'b': 2, 'e': 2, 'a': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 't': 1}) but not sure how to proceed
[ "This way you will get index of last duplicate character \ndef last_duplicate(line):\n c=Counter(line)\n #>>> Counter({'c': 2, 'b': 2, 'e': 2, 'a': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 't': 1})\n\n for i, x in reversed(line):\n if c[x] > 1:\n return len(line) - i - 1\n\nSurely you can find character itself easy enough\n", "Your problem is equivalent to finding the first duplicated character, if you move from right to left. For each character you check if it is already contained in the part to the right.\nSomething like this:\nmy_string = \"abbccdeefght\"\nfor idx in range(len(my_string) - 2, -1, -1):\n char = my_string[idx]\n if char in my_string[idx + 1:]:\n print(\"Last duplicated character is: \" + char)\n break\n\nExplanation: Using range we iterate idx from number that is 2 less than the lenght of the string, all the way to 0. Every time we take a character from position idx and see if it is already contained in the part of my_string that is to the right of character at position idx. If it is, we do print() and end our loop.\nEdit:\nUpon your further explanation, here is fixed code (it wasn't clear from your question). Now we also iterate characters from right to left, but check if the character is contained in the part to the left.\nmy_string = \"abba\"\nfor idx in range(len(my_string) - 1, 0, -1):\n char = my_string[idx]\n if char in my_string[:idx]:\n print(\"Last duplicated character is: \" + char)\n break\n\n", "input_string='abbccdeefght'\n\nlast_duplicate_string=[single_letter for single_letter in input_string if input_string.count(single_letter) > 1]\n\nif last_duplicate_string:\n print \"Last duplicate character from the string %s\",last_duplicate_string[-1]\nelse:\n print \"No duplicate character\"\n\n", "You can do it with simple algorithm\nmystr = 'abbccdeefght'\nsize = len(mystr)-1\nfound = 0\ni=0\nwhile (1):\n if (mystr[size]==mystr[i]):\n print (\"found \",mystr[size],\" on index \",i+1,\" and index \",size+1)\n break\n i+=1\n if (i==size):\n i=0\n size-=1\n if (size==1):\n print (\"not found\")\n break\n\nThe loops will break upon 2 condition. Found and no more data to be checked. \nHope it helps\n", "You can try this code. Tested for \"\", \"abba\", \"zzasd\", \"zxcv\", \"abbccdeefght\"\n# enumerates reversed list\ndef reverse_enumerate(seq):\n p = -1\n for elem in seq[::-1]:\n yield p, elem\n p -= 1\n\nstr = \"abbccdeefght\"\n\nfor i, c in reverse_enumerate(str):\n # check element in left side\n if c in str[i-1::-1]:\n print(c, i)\n # print element, position\n break\n\n", "a = 'abbccdeefght'\na=a[::-1] #reverse the string and helps to get the last repeating characters\nfor char in a:\n counter = a.count(char) #checking count of the character in string\n if counter > 1: #if count is greater than 1 then it is duplicate\n print(char+' is the last repeting character in string') #printing the result\n break\n\n" ]
[ 1, 0, 0, 0, 0, 0 ]
[ "I think this I quite pretty solution:\nfrom collections import Counter\nc=dict(Counter('abbccdeefght'))# get counts as dictionary\nlast_duplicate = list(filter(lambda k: c[k] == 2, c.keys()))[-1]#get only duplicates and take the last one\n\n" ]
[ -1 ]
[ "python", "string" ]
stackoverflow_0040452159_python_string.txt
Q: Pythonnet cann't load System.IO.Path (.net 6.0) I use Python 3.10 and Net 6.0. And my C# code call Directory.GetFiles function from System.IO. When I call dll from python using Pythonnet, it showed cannot load type: System.IO.Path. Please provide some instructions. Thanks. A: from clr_loader import get_coreclr from pythonnet import set_runtime rt = get_coreclr(runtime_config = r"D:\runtimeConfig.json") set_runtime(rt) and json file: { "runtimeOptions": { "tfm": "net6.0", "framework": { "name": "Microsoft.NETCore.App", "version": "6.0.0" } } }
Pythonnet cann't load System.IO.Path (.net 6.0)
I use Python 3.10 and Net 6.0. And my C# code call Directory.GetFiles function from System.IO. When I call dll from python using Pythonnet, it showed cannot load type: System.IO.Path. Please provide some instructions. Thanks.
[ "from clr_loader import get_coreclr\nfrom pythonnet import set_runtime\nrt = get_coreclr(runtime_config = r\"D:\\runtimeConfig.json\")\nset_runtime(rt)\n\nand json file:\n{\n \"runtimeOptions\": {\n \"tfm\": \"net6.0\",\n \"framework\": {\n \"name\": \"Microsoft.NETCore.App\",\n \"version\": \"6.0.0\"\n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "c#", "python", "python.net" ]
stackoverflow_0074479097_c#_python_python.net.txt
Q: Is there a way to list all video URLs of YouTube search results in Python? I'm using Playwright and BeautifulSoup, I can see important part of the URL (href="/watch?v=5iK4_44i8jU") but have not been able to list it, what am I missing? # pip install playwright # playwright install from playwright.sync_api import sync_playwright import regex as re from bs4 import BeautifulSoup with sync_playwright() as p: browser=p.chromium.launch(headless=True) page=browser.new_page() page.goto('https://www.youtube.com/results?search_query=apple+pokemon', wait_until='networkidle') html = page.inner_html('#content') soup = BeautifulSoup(html, 'html.parser') print(soup.find_all("a", {"class":"yt-simple-endpoint style-scope ytd-video-renderer"})) browser.close() A: I believe you want something like this: for element in soup.find_all("a", {"class":"..."}): print(element['href'])
Is there a way to list all video URLs of YouTube search results in Python?
I'm using Playwright and BeautifulSoup, I can see important part of the URL (href="/watch?v=5iK4_44i8jU") but have not been able to list it, what am I missing? # pip install playwright # playwright install from playwright.sync_api import sync_playwright import regex as re from bs4 import BeautifulSoup with sync_playwright() as p: browser=p.chromium.launch(headless=True) page=browser.new_page() page.goto('https://www.youtube.com/results?search_query=apple+pokemon', wait_until='networkidle') html = page.inner_html('#content') soup = BeautifulSoup(html, 'html.parser') print(soup.find_all("a", {"class":"yt-simple-endpoint style-scope ytd-video-renderer"})) browser.close()
[ "I believe you want something like this:\nfor element in soup.find_all(\"a\", {\"class\":\"...\"}):\n print(element['href'])\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "playwright", "python", "web_scraping" ]
stackoverflow_0074484963_beautifulsoup_playwright_python_web_scraping.txt
Q: a password checker with an error i can't find username ="fay" password ="321" user_name = input("What is your username?:") if user_name==username: passWord= input("Please enter your password:") if passWord == password: print("welcome!") else: password_=("please re-enter password:") else: user_name=("please re-enter username:") #i wanted it to check the username and ask for username again if it's wrong and check password if it's correct and to ask for the password again if it's incorrect`
a password checker with an error i can't find
username ="fay" password ="321" user_name = input("What is your username?:") if user_name==username: passWord= input("Please enter your password:") if passWord == password: print("welcome!") else: password_=("please re-enter password:") else: user_name=("please re-enter username:") #i wanted it to check the username and ask for username again if it's wrong and check password if it's correct and to ask for the password again if it's incorrect`
[]
[]
[ "I think you should to try this:\nusername =\"fay\"\npassword =\"321\"\nuser_name = input(\"What is your username?:\")\nwhile user_name!=username:\n user_name=input(\"please re-enter username:\")\n\npassWord= input(\"Please enter your password:\")\n\nwhile passWord != password:\n passWord=input(\"please re-enter password:\") \n \nprint(\"welcome!\") \n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074484949_python.txt
Q: how can I turn cell into a dataframe I have this data: df['profile'] = { 'symbol': 'AAPL', 'price': 150.72, 'beta': 1.246644, 'volAvg': 89576498, 'mktCap': 2397668846469, 'lastDiv': 0.91, 'range': '129.04-182.94', 'changes': 1.93, 'companyName': 'Apple Inc.', 'currency': 'USD', 'cik': '0000320193', 'isin': 'US0378331005', 'cusip': '037833100', 'isFund': False} how do i break this into a dataframe with headers of symbol, price, beta, etc and have the one row with the values? A: I guess you have something like this: df = pd.DataFrame({ 'ID' : 0, 'status' : [{ 'symbol': 'AAPL', 'price': 150.72, 'beta': 1.246644, 'volAvg': 89576498, 'mktCap': 2397668846469, 'lastDiv': 0.91, 'range': '129.04-182.94', 'changes': 1.93, 'companyName': 'Apple Inc.', 'currency': 'USD', 'cik': '0000320193', 'isin': 'US0378331005', 'cusip': '037833100', 'isFund': False}] }) print(df) ID status 0 0 {'symbol': 'AAPL', 'price': 150.72, 'beta': 1.... Convert the status column to a new dataframe like this: out = df['status'].apply(pd.Series) print(out) symbol price beta volAvg mktCap lastDiv range changes companyName currency cik isin cusip isFund 0 AAPL 150.72 1.246644 89576498 2397668846469 0.91 129.04-182.94 1.93 Apple Inc. USD 0000320193 US0378331005 037833100 False A: example data = {'symbol': 'AAPL', 'price': 150.72, 'beta': 1.246644, 'volAvg': 89576498, 'mktCap': 2397668846469, 'lastDiv': 0.91, 'range': '129.04-182.94', 'changes': 1.93, 'companyName': 'Apple Inc.', 'currency': 'USD', 'cik': '0000320193', 'isin': 'US0378331005', 'cusip': '037833100', 'isFund': False} code pd.DataFrame([data]) result symbol price beta volAvg mktCap lastDiv range changes companyName currency cik isin cusip isFund 0 AAPL 150.72 1.246644 89576498 2397668846469 0.91 129.04-182.94 1.93 Apple Inc. USD 0000320193 US0378331005 037833100 False
how can I turn cell into a dataframe
I have this data: df['profile'] = { 'symbol': 'AAPL', 'price': 150.72, 'beta': 1.246644, 'volAvg': 89576498, 'mktCap': 2397668846469, 'lastDiv': 0.91, 'range': '129.04-182.94', 'changes': 1.93, 'companyName': 'Apple Inc.', 'currency': 'USD', 'cik': '0000320193', 'isin': 'US0378331005', 'cusip': '037833100', 'isFund': False} how do i break this into a dataframe with headers of symbol, price, beta, etc and have the one row with the values?
[ "I guess you have something like this:\ndf = pd.DataFrame({\n 'ID' : 0, \n 'status' : [{\n 'symbol': 'AAPL', \n 'price': 150.72, \n 'beta': 1.246644, \n 'volAvg': 89576498, \n 'mktCap': 2397668846469, \n 'lastDiv': 0.91, \n 'range': '129.04-182.94', \n 'changes': 1.93, \n 'companyName': 'Apple Inc.', \n 'currency': 'USD', \n 'cik': '0000320193', \n 'isin': 'US0378331005', \n 'cusip': '037833100',\n 'isFund': False}]\n})\nprint(df)\n\n ID status\n0 0 {'symbol': 'AAPL', 'price': 150.72, 'beta': 1....\n\nConvert the status column to a new dataframe like this:\nout = df['status'].apply(pd.Series)\nprint(out)\n\n symbol price beta volAvg mktCap lastDiv range changes companyName currency cik isin cusip isFund\n0 AAPL 150.72 1.246644 89576498 2397668846469 0.91 129.04-182.94 1.93 Apple Inc. USD 0000320193 US0378331005 037833100 False\n\n", "example\ndata = {'symbol': 'AAPL',\n 'price': 150.72,\n 'beta': 1.246644,\n 'volAvg': 89576498,\n 'mktCap': 2397668846469,\n 'lastDiv': 0.91,\n 'range': '129.04-182.94',\n 'changes': 1.93,\n 'companyName': 'Apple Inc.',\n 'currency': 'USD',\n 'cik': '0000320193',\n 'isin': 'US0378331005',\n 'cusip': '037833100',\n 'isFund': False}\n\ncode\npd.DataFrame([data])\n\nresult\n symbol price beta volAvg mktCap lastDiv range changes companyName currency cik isin cusip isFund\n0 AAPL 150.72 1.246644 89576498 2397668846469 0.91 129.04-182.94 1.93 Apple Inc. USD 0000320193 US0378331005 037833100 False\n\n" ]
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074484951_dataframe_pandas_python.txt
Q: Python, non-blocking pipe, flushing, and missing stdout/stderr I have two python processes connected by a pipe. The pipe was created with: read_file_descriptor, write_file_descriptor = os.pipe() os.set_blocking(read_file_descriptor, False) os.set_inheritable(read_file_descriptor, True) The parent process forks off a child, and the child reads from the read file descriptor using code that in essence boils down to this: lines = [] read_handle = os.fdopen(read_file_descriptor) while True: line = read_handle.readline() if _TERMINATION_CHAR in line: # trigger final upload line = line[: line.index(_TERMINATION_CHAR)] received_stream_termination = True elif len(line) == 0: # The line would at least have the newline char if it was a blank. # no more to read right now; just keep looping and trying to read # until the timeout or the termination character tell us to stop time.sleep(0.01) continue fp.write(line) fp.flush() if received_stream_termination: break # handle lines... The parent process, meanwhile, redirects its stdout and stderr to point at the write_file_descriptor. When the parent is done, it does: logger.info("Cleaning up") print(_TERMINATION_CHAR) # tell the reader that the stream is done sys.stdout.flush() sys.stderr.flush() The process is running with PYTHONUNBUFFERED=1 set in the environment. I am stressing this code by having the parent write ~20k lines (10k each to stdout and stderr, interleaved): for i in range(10000): time.sleep(0.01) print(f"From stdout: {i}") print(f"From stderr: {i}", file=sys.stderr) return a + b With this, the lines the handler sees are: # ... there are more lines before this. Nothing seems to be missing up to this point From stdout: 9012 From stderr: 9012 From stdout: 9013 From stderr: 9013 From stdout: 9014 From stderr: 9014 From stdout: 9015 From stderr: 9015 2022-11-15 23:01:28,536 - INFO : Cleaning up So... a lot of lines at the end are missing. But we still see the log message. Any ideas why this may be happening? A: The problem turned out to be a race condition between two different mechanisms for indicating completion. One mechanism was the termination character, the other was a sigterm handler. The sigterm was sent between when the print statements completed their execution and when the terminating character was written. Simplifying to always use the termination character only solved the issue. So nothing funky with i/o, just your run-of-the-mill race condition!
Python, non-blocking pipe, flushing, and missing stdout/stderr
I have two python processes connected by a pipe. The pipe was created with: read_file_descriptor, write_file_descriptor = os.pipe() os.set_blocking(read_file_descriptor, False) os.set_inheritable(read_file_descriptor, True) The parent process forks off a child, and the child reads from the read file descriptor using code that in essence boils down to this: lines = [] read_handle = os.fdopen(read_file_descriptor) while True: line = read_handle.readline() if _TERMINATION_CHAR in line: # trigger final upload line = line[: line.index(_TERMINATION_CHAR)] received_stream_termination = True elif len(line) == 0: # The line would at least have the newline char if it was a blank. # no more to read right now; just keep looping and trying to read # until the timeout or the termination character tell us to stop time.sleep(0.01) continue fp.write(line) fp.flush() if received_stream_termination: break # handle lines... The parent process, meanwhile, redirects its stdout and stderr to point at the write_file_descriptor. When the parent is done, it does: logger.info("Cleaning up") print(_TERMINATION_CHAR) # tell the reader that the stream is done sys.stdout.flush() sys.stderr.flush() The process is running with PYTHONUNBUFFERED=1 set in the environment. I am stressing this code by having the parent write ~20k lines (10k each to stdout and stderr, interleaved): for i in range(10000): time.sleep(0.01) print(f"From stdout: {i}") print(f"From stderr: {i}", file=sys.stderr) return a + b With this, the lines the handler sees are: # ... there are more lines before this. Nothing seems to be missing up to this point From stdout: 9012 From stderr: 9012 From stdout: 9013 From stderr: 9013 From stdout: 9014 From stderr: 9014 From stdout: 9015 From stderr: 9015 2022-11-15 23:01:28,536 - INFO : Cleaning up So... a lot of lines at the end are missing. But we still see the log message. Any ideas why this may be happening?
[ "The problem turned out to be a race condition between two different mechanisms for indicating completion. One mechanism was the termination character, the other was a sigterm handler. The sigterm was sent between when the print statements completed their execution and when the terminating character was written. Simplifying to always use the termination character only solved the issue. So nothing funky with i/o, just your run-of-the-mill race condition!\n" ]
[ 0 ]
[]
[]
[ "file_descriptor", "io", "posix", "python" ]
stackoverflow_0074466173_file_descriptor_io_posix_python.txt
Q: Outer join to check existence each records of two pandas dataframes like SQL I have to tables looks like following: Table T1 ColumnA ColumnB A 1 A 3 B 1 C 2 Table T2 ColumnA ColumnB A 1 A 4 B 1 D 2 in SQL I will do following query to check the existence of each record select COALESCE(T1.ColumnA,T2.ColumnA) as ColumnA ,T1.ColumnB as ExistT1 ,T2.ColumnB as ExistT2 from T1 full join T2 on T1.ColumnA=T2.ColumnA and T1.ColumnB=T2.ColumnB where (T1.ColumnA is null or T2.ColumnA is null) I have tried many way in Pandas like concate, join, merge, etc, but it seems that the two merge keys would be combined into one. I think the problem is that I want to check is not 'data columns' but 'key columns'. Is there any good idea to do this in Python? Thanks! ColumnA ExistT1 ExistT2 A 3 null A null 4 C 2 null D null 2 A: pd.merge has an indicator parameter that could be helpful here: (t1 .merge(t2, how = 'outer', indicator=True) .loc[lambda df: df._merge!="both"] .assign(ExistT1 = lambda df: df.ColumnB.where(df._merge.eq('left_only')), ExistT2 = lambda df: df.ColumnB.where(df._merge.eq('right_only')) ) .drop(columns=['ColumnB', '_merge']) ) ColumnA ExistT1 ExistT2 1 A 3.0 NaN 3 C 2.0 NaN 4 A NaN 4.0 5 D NaN 2.0 A: First merge 2 dataframes following code: (df1.assign(ExistT1=df1['ColumnB']) .merge(df2.assign(ExistT2=df2['ColumnB']), how='outer')) output: ColumnA ColumnB ExistT1 ExistT2 0 A 1 1.00 1.00 1 A 3 3.00 NaN 2 B 1 1.00 1.00 3 C 2 2.00 NaN 4 A 4 NaN 4.00 5 D 2 NaN 2.00 Second drop ColumnB and same value rows (like row 0 and row2) include full code: (df1.assign(ExistT1=df1['ColumnB']) .merge(df2.assign(ExistT2=df2['ColumnB']), how='outer') .drop('ColumnB', axis=1) .loc[lambda x: x.isnull().any(axis=1)]) output: ColumnA ExistT1 ExistT2 1 A 3.00 NaN 3 C 2.00 NaN 4 A NaN 4.00 5 D NaN 2.00 Final sort_values and reset_index (full code) (df1.assign(ExistT1=df1['ColumnB']) .merge(df2.assign(ExistT2=df2['ColumnB']), how='outer') .drop('ColumnB', axis=1) .loc[lambda x: x.isnull().any(axis=1)] .sort_values(['ColumnA']).reset_index(drop=True)) result: ColumnA ExistT1 ExistT2 0 A 3.00 NaN 1 A NaN 4.00 2 C 2.00 NaN 3 D NaN 2.00
Outer join to check existence each records of two pandas dataframes like SQL
I have to tables looks like following: Table T1 ColumnA ColumnB A 1 A 3 B 1 C 2 Table T2 ColumnA ColumnB A 1 A 4 B 1 D 2 in SQL I will do following query to check the existence of each record select COALESCE(T1.ColumnA,T2.ColumnA) as ColumnA ,T1.ColumnB as ExistT1 ,T2.ColumnB as ExistT2 from T1 full join T2 on T1.ColumnA=T2.ColumnA and T1.ColumnB=T2.ColumnB where (T1.ColumnA is null or T2.ColumnA is null) I have tried many way in Pandas like concate, join, merge, etc, but it seems that the two merge keys would be combined into one. I think the problem is that I want to check is not 'data columns' but 'key columns'. Is there any good idea to do this in Python? Thanks! ColumnA ExistT1 ExistT2 A 3 null A null 4 C 2 null D null 2
[ "pd.merge has an indicator parameter that could be helpful here:\n(t1\n.merge(t2, how = 'outer', indicator=True)\n.loc[lambda df: df._merge!=\"both\"]\n.assign(ExistT1 = lambda df: df.ColumnB.where(df._merge.eq('left_only')), \n ExistT2 = lambda df: df.ColumnB.where(df._merge.eq('right_only')) )\n.drop(columns=['ColumnB', '_merge'])\n)\n\n ColumnA ExistT1 ExistT2\n1 A 3.0 NaN\n3 C 2.0 NaN\n4 A NaN 4.0\n5 D NaN 2.0\n\n", "First\n\nmerge 2 dataframes\n\nfollowing code:\n(df1.assign(ExistT1=df1['ColumnB'])\n .merge(df2.assign(ExistT2=df2['ColumnB']), how='outer'))\n\noutput:\n ColumnA ColumnB ExistT1 ExistT2\n0 A 1 1.00 1.00\n1 A 3 3.00 NaN\n2 B 1 1.00 1.00\n3 C 2 2.00 NaN\n4 A 4 NaN 4.00\n5 D 2 NaN 2.00\n\n\nSecond\n\ndrop ColumnB and same value rows (like row 0 and row2)\n\ninclude full code:\n (df1.assign(ExistT1=df1['ColumnB'])\n .merge(df2.assign(ExistT2=df2['ColumnB']), how='outer')\n .drop('ColumnB', axis=1)\n .loc[lambda x: x.isnull().any(axis=1)])\n\noutput:\n ColumnA ExistT1 ExistT2\n1 A 3.00 NaN\n3 C 2.00 NaN\n4 A NaN 4.00\n5 D NaN 2.00\n\n\nFinal\nsort_values and reset_index (full code)\n(df1.assign(ExistT1=df1['ColumnB'])\n .merge(df2.assign(ExistT2=df2['ColumnB']), how='outer')\n .drop('ColumnB', axis=1)\n .loc[lambda x: x.isnull().any(axis=1)]\n .sort_values(['ColumnA']).reset_index(drop=True))\n\nresult:\n ColumnA ExistT1 ExistT2\n0 A 3.00 NaN\n1 A NaN 4.00\n2 C 2.00 NaN\n3 D NaN 2.00\n\n" ]
[ 1, 0 ]
[]
[]
[ "merge", "outer_join", "pandas", "python" ]
stackoverflow_0074484411_merge_outer_join_pandas_python.txt
Q: Not being able to round float at end of function I have the code finished up in fact it is entirely done but I just need help at the end of my function for it to return a rounded float. def average_area(glacier_list): average=0 Sum=0 for row in glacier_list: Sum += float(row[9]) average = Sum / len(glacier_list) return average def main(): print('Average Area:, '(average_area(csv_reader(file)))) if __name__ == '__main__': main() When the code runs through I get 'Average Area: 2.0335740566037788' but I need to get 'Average Area: 2.03' A: You'll want to use round(average, 2) to round the average to the 2nd decimal point, and then convert it to a string and format it to only include 2 characters after the "." decimal point, and then convert it back to a float before returning it. credit where it's due: this was a paraphrasing of the best answer on the linked question by Ken Y-N above, which was written by Rex Logan in the question. Good luck with everything!
Not being able to round float at end of function
I have the code finished up in fact it is entirely done but I just need help at the end of my function for it to return a rounded float. def average_area(glacier_list): average=0 Sum=0 for row in glacier_list: Sum += float(row[9]) average = Sum / len(glacier_list) return average def main(): print('Average Area:, '(average_area(csv_reader(file)))) if __name__ == '__main__': main() When the code runs through I get 'Average Area: 2.0335740566037788' but I need to get 'Average Area: 2.03'
[ "You'll want to use round(average, 2) to round the average to the 2nd decimal point, and then convert it to a string and format it to only include 2 characters after the \".\" decimal point, and then convert it back to a float before returning it.\ncredit where it's due: this was a paraphrasing of the best answer on the linked question by Ken Y-N above, which was written by Rex Logan in the question.\nGood luck with everything!\n" ]
[ 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0074484986_for_loop_list_python.txt
Q: Why am I not able to see the random numbers generated using python for large input values? So I am trying to generate my own adjacency list using random.randint. I am not able to view the output. Its just few values and then dots. I want to input these values into my algorithm. How to view these generated values. This is the output I'am getting. Thank you for your help! A: The below code should help: import numpy as np import pandas as pd a = np.random.randint(0,2, size=(500,500)) print(a) df = pd.DataFrame(a) print(df) df.to_csv("output.csv")
Why am I not able to see the random numbers generated using python for large input values?
So I am trying to generate my own adjacency list using random.randint. I am not able to view the output. Its just few values and then dots. I want to input these values into my algorithm. How to view these generated values. This is the output I'am getting. Thank you for your help!
[ "The below code should help:\nimport numpy as np\nimport pandas as pd\n\na = np.random.randint(0,2, size=(500,500))\nprint(a)\n\ndf = pd.DataFrame(a)\nprint(df)\ndf.to_csv(\"output.csv\")\n\n" ]
[ 0 ]
[]
[]
[ "adjacency_matrix", "python", "random" ]
stackoverflow_0074485068_adjacency_matrix_python_random.txt
Q: How to use QFileDialog to open file with .mid suffix I have created a subclass for an option to Open File. Alongside PYQT5, I have imported the python library Mido & py-midi in order to read the MIDI files. If my logic is correct. I will use PYQT5's FileDialog in order to retrieve a file, assign it to a variable and then use Mido to read that said MIDI file when I Will then use py-midi to edit these files class OpenDialog(QFileDialog): def __init__(self, *args, **kwargs): super(OpenDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Open") self.setFixedSize(1000, 450) buttons = QDialogButtonBox.Open | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(buttons) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout = QVBoxLayout() self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) # OpenedFile = I have commented out OpenedFile becuase i plan to use this as a variable to link to the opened files. However, I am unsure how this can be done in PYQ5. Furthermore, how to do this with a specific file extension. A: I believe you're a bit confused on how QFileDialog works. First of all, by default Qt tries to use the native file dialog the system provides, so generally you should not try to create your own by subclassing, unless you need very special behavior. Then, QFileDialog is a QDialog that already has its own (private) layout and widgets, including the area in which files and folders are shown, a text field for the path, and standard Open/Cancel buttons. Since you only need to open a specific file type, there's absolutely no need for subclassing, as explained at the very beginning of the documentation: The easiest way to create a QFileDialog is to use the static functions. Those are listed in the static members and you are probably interested in getOpenFileName(); do note that the static functions for files (not those for directories) always return a tuple including the path(s) and selected file type filter: def showOpenFileDialog(self): fileName, filter = QFileDialog.getOpenFileName(self, 'Open file', 'some/default/path/', 'MIDI files (*.mid)') if fileName: self.openMidiFile(fileName) A: Try the following script: class FileDialog(QtWidgets.QFileDialog): def __init__(self, *args, **kwargs): super(FileDialog, self).__init__(*args, **kwargs) self.setOption(QFileDialog.DontUseNativeDialog, True) self.setNameFilters(["Excel File (*.xlsx *.xls)","CSV File (*.csv)","Log File (*.log)"]) self.setFileMode(QFileDialog.ExistingFiles) def accept(self): super(FileDialog, self).accept()
How to use QFileDialog to open file with .mid suffix
I have created a subclass for an option to Open File. Alongside PYQT5, I have imported the python library Mido & py-midi in order to read the MIDI files. If my logic is correct. I will use PYQT5's FileDialog in order to retrieve a file, assign it to a variable and then use Mido to read that said MIDI file when I Will then use py-midi to edit these files class OpenDialog(QFileDialog): def __init__(self, *args, **kwargs): super(OpenDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Open") self.setFixedSize(1000, 450) buttons = QDialogButtonBox.Open | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(buttons) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout = QVBoxLayout() self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) # OpenedFile = I have commented out OpenedFile becuase i plan to use this as a variable to link to the opened files. However, I am unsure how this can be done in PYQ5. Furthermore, how to do this with a specific file extension.
[ "I believe you're a bit confused on how QFileDialog works.\nFirst of all, by default Qt tries to use the native file dialog the system provides, so generally you should not try to create your own by subclassing, unless you need very special behavior.\nThen, QFileDialog is a QDialog that already has its own (private) layout and widgets, including the area in which files and folders are shown, a text field for the path, and standard Open/Cancel buttons.\nSince you only need to open a specific file type, there's absolutely no need for subclassing, as explained at the very beginning of the documentation:\n\nThe easiest way to create a QFileDialog is to use the static functions.\n\nThose are listed in the static members and you are probably interested in getOpenFileName(); do note that the static functions for files (not those for directories) always return a tuple including the path(s) and selected file type filter:\n def showOpenFileDialog(self):\n fileName, filter = QFileDialog.getOpenFileName(self, 'Open file', \n 'some/default/path/', 'MIDI files (*.mid)')\n if fileName:\n self.openMidiFile(fileName)\n\n", "Try the following script:\nclass FileDialog(QtWidgets.QFileDialog):\n\n def __init__(self, *args, **kwargs):\n super(FileDialog, self).__init__(*args, **kwargs)\n self.setOption(QFileDialog.DontUseNativeDialog, True)\n self.setNameFilters([\"Excel File (*.xlsx *.xls)\",\"CSV File (*.csv)\",\"Log File (*.log)\"])\n self.setFileMode(QFileDialog.ExistingFiles)\n\n def accept(self):\n super(FileDialog, self).accept()\n\n" ]
[ 1, 0 ]
[]
[]
[ "file_extension", "mido", "pyqt5", "python", "qfiledialog" ]
stackoverflow_0066153996_file_extension_mido_pyqt5_python_qfiledialog.txt
Q: pandas Series plot color I'm writing a generic plotting function that's used in a few different cases. Its input is sometimes a Series, sometimes a DataFrame. Sometimes I specify the plot color, sometimes I want to use the default behavior. I would think that passing color=None would allow the default color logic to work, but it is not a valid input to Series.plot. DataFrame.plot allows it, though. EDIT: Code sample. >>> pd.Series([1, 2, 3]).plot(color=None) ValueError: Invalid color None >>> pd.DataFrame([[1, 2, 3]]).plot(color=None) <AxesSubplot:> # works I'm using pandas v1.4.4. A: If you don't supply color, the function will use default value (i.e. pd.DataFrame([[1, 2, 3]]).plot()). It also seems that neither DataFrame nor Series have a keyword color. So, if you want to supply None use colormap. #Both work pd.Series([1, 2, 3]).plot(colormap=None) pd.DataFrame([[1, 2, 3]]).plot(colormap=None) https://pandas.pydata.org/pandas-docs/version/1.4/reference/api/pandas.Series.plot.html https://pandas.pydata.org/pandas-docs/version/1.4/reference/api/pandas.DataFrame.plot.html?highlight=dataframe%20plot#pandas.DataFrame.plot
pandas Series plot color
I'm writing a generic plotting function that's used in a few different cases. Its input is sometimes a Series, sometimes a DataFrame. Sometimes I specify the plot color, sometimes I want to use the default behavior. I would think that passing color=None would allow the default color logic to work, but it is not a valid input to Series.plot. DataFrame.plot allows it, though. EDIT: Code sample. >>> pd.Series([1, 2, 3]).plot(color=None) ValueError: Invalid color None >>> pd.DataFrame([[1, 2, 3]]).plot(color=None) <AxesSubplot:> # works I'm using pandas v1.4.4.
[ "If you don't supply color, the function will use default value (i.e. pd.DataFrame([[1, 2, 3]]).plot()).\nIt also seems that neither DataFrame nor Series have a keyword color. So, if you want to supply None use colormap.\n#Both work\npd.Series([1, 2, 3]).plot(colormap=None)\npd.DataFrame([[1, 2, 3]]).plot(colormap=None)\n\nhttps://pandas.pydata.org/pandas-docs/version/1.4/reference/api/pandas.Series.plot.html\nhttps://pandas.pydata.org/pandas-docs/version/1.4/reference/api/pandas.DataFrame.plot.html?highlight=dataframe%20plot#pandas.DataFrame.plot\n" ]
[ 0 ]
[]
[]
[ "pandas", "plot", "python" ]
stackoverflow_0074484799_pandas_plot_python.txt
Q: Pygame WINDOWRESIZED black screen I'm trying to resize a window in pygame but only get a black screen. See the before and after pictures below. What am I doing wrong? import pygame as pg from pygame.locals import * pg.init() yellow = (255, 255, 134) grey = (142, 142, 142) square_size = 100 width = 7 * square_size height = 7 * square_size radius = int(square_size / 2 - 10) screen = pg.display.set_mode((width, height), RESIZABLE) screen.fill(grey) pg.draw.circle(screen,yellow,(square_size,square_size),radius) pg.display.flip() while True: for ev in pg.event.get(): if ev.type == pg.QUIT: print("quit game") pg.quit() sys.exit() if ev.type == pg.WINDOWRESIZED: width, height = screen.get_width(), screen.get_height() pg.display.flip() A: You need to redraw the scene after resizing the window. I recommend redrawing the scene in each frame. The typical PyGame application loop has to: limit the frames per second to limit CPU usage with pygame.time.Clock.tick handle the events by calling either pygame.event.pump() or pygame.event.get(). update the game states and positions of objects dependent on the input events and time (respectively frames) clear the entire display or draw the background draw the entire scene (blit all the objects) update the display by calling either pygame.display.update() or pygame.display.flip() import sys import pygame as pg from pygame.locals import * pg.init() yellow = (255, 255, 134) grey = (142, 142, 142) square_size = 100 width = 7 * square_size height = 7 * square_size radius = int(square_size / 2 - 10) screen = pg.display.set_mode((width, height), RESIZABLE) clock = pg.time.Clock() run = True while run: # limit the frames per second clock.tick(100) # handle the events for ev in pg.event.get(): if ev.type == pg.QUIT: print("quit game") run = False if ev.type == pg.WINDOWRESIZED: width, height = screen.get_width(), screen.get_height() # clear display screen.fill(grey) # draw scene pg.draw.circle(screen,yellow,(square_size,square_size),radius) # update the display pg.display.flip() pg.quit() sys.exit()
Pygame WINDOWRESIZED black screen
I'm trying to resize a window in pygame but only get a black screen. See the before and after pictures below. What am I doing wrong? import pygame as pg from pygame.locals import * pg.init() yellow = (255, 255, 134) grey = (142, 142, 142) square_size = 100 width = 7 * square_size height = 7 * square_size radius = int(square_size / 2 - 10) screen = pg.display.set_mode((width, height), RESIZABLE) screen.fill(grey) pg.draw.circle(screen,yellow,(square_size,square_size),radius) pg.display.flip() while True: for ev in pg.event.get(): if ev.type == pg.QUIT: print("quit game") pg.quit() sys.exit() if ev.type == pg.WINDOWRESIZED: width, height = screen.get_width(), screen.get_height() pg.display.flip()
[ "You need to redraw the scene after resizing the window. I recommend redrawing the scene in each frame. The typical PyGame application loop has to:\n\nlimit the frames per second to limit CPU usage with pygame.time.Clock.tick\nhandle the events by calling either pygame.event.pump() or pygame.event.get().\nupdate the game states and positions of objects dependent on the input events and time (respectively frames)\nclear the entire display or draw the background\ndraw the entire scene (blit all the objects)\nupdate the display by calling either pygame.display.update() or pygame.display.flip()\n\nimport sys\nimport pygame as pg\nfrom pygame.locals import *\n\npg.init()\n\nyellow = (255, 255, 134)\ngrey = (142, 142, 142)\n\nsquare_size = 100\nwidth = 7 * square_size\nheight = 7 * square_size\nradius = int(square_size / 2 - 10)\n\nscreen = pg.display.set_mode((width, height), RESIZABLE)\nclock = pg.time.Clock()\n\nrun = True\nwhile run:\n\n # limit the frames per second \n clock.tick(100)\n\n # handle the events\n for ev in pg.event.get():\n if ev.type == pg.QUIT:\n print(\"quit game\")\n run = False\n if ev.type == pg.WINDOWRESIZED:\n width, height = screen.get_width(), screen.get_height()\n \n # clear display\n screen.fill(grey)\n\n # draw scene\n pg.draw.circle(screen,yellow,(square_size,square_size),radius)\n\n # update the display\n pg.display.flip()\n\npg.quit()\nsys.exit()\n\n" ]
[ 1 ]
[]
[]
[ "pygame", "python", "resize" ]
stackoverflow_0074483012_pygame_python_resize.txt
Q: Kernel died restarting whenever training a model Here's the code: # import libraries from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # import dataset from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator() test_datagen = ImageDataGenerator() training_set = train_datagen.flow_from_directory( 'data/spectrogramme/ensemble_de_formation', target_size = (64, 64), batch_size = 128, class_mode = 'binary') test_set = test_datagen.flow_from_directory('data/spectrogramme/ensemble_de_test', target_size = (64, 64), batch_size = 128, class_mode = 'binary') # initializing reseau = Sequential() # 1. convolution reseau.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) reseau.add(Conv2D(32, (3, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) reseau.add(Conv2D(64, (3, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) reseau.add(Conv2D(64, (3, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) # 2. flatenning reseau.add(Flatten()) # 3. fully connected from keras.layers import Dropout reseau.add(Dense(units = 64, activation = 'relu')) reseau.add(Dropout(0.1)) reseau.add(Dense(units = 128, activation = 'relu')) reseau.add(Dropout(0.05)) reseau.add(Dense(units = 256, activation = 'relu')) reseau.add(Dropout(0.03)) reseau.add(Dense(units = 1, activation = 'sigmoid')) # 4. compile reseau.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # 5. fit reseau.fit_generator(training_set, steps_per_epoch = 8000, epochs = 1, validation_data = test_set, validation_steps = 2000) This should prove that I have tensorflow GPU with CUDA and CUDNN installed pic I don't know what to do, I have reinstalled CUDA and CUDNN multiple times HOWEVER, if I uninstall tensorflow-gpu, the program runs flawlessly... with the exception of needing 5000 seconds per epoch... I'd like to avoid that FYI, this is all happening on Windows Any help is appreciated. A: A very cumbersome issue with tensorflow-gpu. It took me days to find the best working solution. What seems to be the problem: I know you might have installed cudnn and cuda (just like me) after watching youtube videos or internet documentation. But since cuda and cudnn are very strict about version clashes so it's possible that there might have been a version mismatch between your tensorflow , cuda or cudnn version. What's the solution: The tensorflow build automatically selected by Anaconda on Windows 10 during the installation of tensorflow-gpu 2.3 seems to be faulty. Please find a workaround here (consider upvoting the GitHub answer if you have a GitHub account). Python 3.7: conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py37h936c3e2_0 Python 3.8: conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0 These snippets automatically download cuda and cudnn drivers along with the tensorflow-gpu. After trying out this solution i was able to fit() the tensorflow models as well as boost up the speed due to GPU installed. A word of advice: If you are working with machine learning / data science. I would strongly advice you shift to anaconda instead of pip. This would allow you to create virtual environments and easy integration with jupyter-notebooks. You can create a separate virtual environment for machine learning tasks as they often require upgradation or downgradation of libraries. With virtual environments it won't hurt your other packages outside the environment. A: I had a similar problem because I had cuda and cuDNN versions way higher than what is mentioned in the compatibility chart. The Dense layers would work fine for me but using Conv2D/Conv3D would kill my kernel. Solution Make sure you have the zlib file copied and pasted into your CUDA\v11.x\bin directory. I had issues downloading it from NVIDIA's website but found a way around. In NVIDIA website, they referred to zlibwapi.dll- I was able to locate this file in “C:\Program Files\Microsoft Office\root\Office16\ODBC Drivers\Salesforce\lib” (I installed using Microsoft 365 x64 in windows 11) and copy pasted this file into “C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin” I was able to run Tensorflow 2.8.0 thereafter Thanks to srikkanth_kn's solution I was able to find the zlibwapi.dll file (in MS Office) and pasted it into the CUDA's bin folder (make sure CUDA's bin folder is in your PATH). After that everything was working fine. Hope this helps you and saves your time. A: in my case I needed to install conda install keras A: I had the same problem. In my case, the Notebook kernel was crashing as soon as I run the block with all model.add() code. I went to Jupyter Home and found out that another notebook, which I had used earlier to train a model on GPU, was running, even though I had closed the notebook browser tab. As suggested by @Ian Henry. I shutdown the ones I wasn't using, restarted the kernel and run all the blocks again, and this time it worked perfectly fine. Note that, the notebooks run in background even when you close the browser. You can verify this with if you check the icon for the respective notebook, which should be green if running and grey if not. To shutdown the running notebook, simply go to the Running tab, anc click the shutdown button next to the notebook name A: If you are using Jupyter check for any running notebooks, and as I've found that they hang on to the GPU memory even when they are actively running. In jupyter shutdown any unused running ones. A: The problem is with the Jupyter notebook. I have the same problem going on with Jupyter notebook. If you run the same code in CPU based environment or in Terminal with GPU, it will work for sure. A: I had the same issue running model.fit() on Jupyter Notebook. A good starting point for debugging is always downloading the notebook as a .py file and run it. This way you get all errors and warnings. In terms of a solution - I doubt that this will solve most cases, but I installed cuDNN 7.2(.1) via .deb files, reinstalled tensorflow-gpu, and it worked. After all, it wasn't a version issue the driver (I had CUDA 9.0 and 384.xx which was correct), but one with cuDNN. A: I had the same issue. After all, running the file as .py helped to see the problem was with cuDNN. Not all files were installed. A: I had Exactelly the same problem, I tried every solutions mentioned in this post and never works. After soo much tries, I found the problem, was the cuda installation, during the installation. I followed the Nvidia tutorial, but, at step of copy the 3 files from cudnn directory (like as tutorial) you should copy the 3 paths and just paste (substitute) at the nvidia directory, after this, my gpu works wothout problems A: The CUDA, CuDNN, Tensorflow and Python Version Compatibility table can be referred at https://www.tensorflow.org/install/source#gpu but I did with the following version installation and it works perfectly. The problem can be solve by: Install the latest anaconda navigator. Install Python v3.8.x Install Tensorflow v2.10.0 Install CUDA v11.8 Install CuDNN v8.6.x Paste the zlibwapi.dll file in the CUDA bin folder. The file can be downloaded from https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html#install-windows Follow the instructions give on the above link. This is working for me. I was not placing the zlibwapi.dll in the CUDA/bin folder earlier, that was the reason I faced the same problem. I hope this helps. A: import os os.environ['KMP_DUPLICATE_LIB_OK']='True' This solution is provided by Krishna Kankipati at Kaggle site A: Please check cudnn. I had same problem and it was solved after using correct cudnn
Kernel died restarting whenever training a model
Here's the code: # import libraries from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # import dataset from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator() test_datagen = ImageDataGenerator() training_set = train_datagen.flow_from_directory( 'data/spectrogramme/ensemble_de_formation', target_size = (64, 64), batch_size = 128, class_mode = 'binary') test_set = test_datagen.flow_from_directory('data/spectrogramme/ensemble_de_test', target_size = (64, 64), batch_size = 128, class_mode = 'binary') # initializing reseau = Sequential() # 1. convolution reseau.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) reseau.add(Conv2D(32, (3, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) reseau.add(Conv2D(64, (3, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) reseau.add(Conv2D(64, (3, 3), activation = 'relu')) reseau.add(MaxPooling2D(pool_size = (2, 2))) # 2. flatenning reseau.add(Flatten()) # 3. fully connected from keras.layers import Dropout reseau.add(Dense(units = 64, activation = 'relu')) reseau.add(Dropout(0.1)) reseau.add(Dense(units = 128, activation = 'relu')) reseau.add(Dropout(0.05)) reseau.add(Dense(units = 256, activation = 'relu')) reseau.add(Dropout(0.03)) reseau.add(Dense(units = 1, activation = 'sigmoid')) # 4. compile reseau.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # 5. fit reseau.fit_generator(training_set, steps_per_epoch = 8000, epochs = 1, validation_data = test_set, validation_steps = 2000) This should prove that I have tensorflow GPU with CUDA and CUDNN installed pic I don't know what to do, I have reinstalled CUDA and CUDNN multiple times HOWEVER, if I uninstall tensorflow-gpu, the program runs flawlessly... with the exception of needing 5000 seconds per epoch... I'd like to avoid that FYI, this is all happening on Windows Any help is appreciated.
[ "A very cumbersome issue with tensorflow-gpu. It took me days to find the best working solution.\nWhat seems to be the problem:\nI know you might have installed cudnn and cuda (just like me) after watching youtube videos or internet documentation. But since cuda and cudnn are very strict about version clashes so it's possible that there might have been a version mismatch between your tensorflow , cuda or cudnn version.\nWhat's the solution:\nThe tensorflow build automatically selected by Anaconda on Windows 10 during the installation of tensorflow-gpu 2.3 seems to be faulty. Please find a workaround here (consider upvoting the GitHub answer if you have a GitHub account).\nPython 3.7: conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py37h936c3e2_0\nPython 3.8: conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0\nThese snippets automatically download cuda and cudnn drivers along with the tensorflow-gpu. After trying out this solution i was able to fit() the tensorflow models as well as boost up the speed due to GPU installed.\nA word of advice:\nIf you are working with machine learning / data science. I would strongly advice you shift to anaconda instead of pip. This would allow you to create virtual environments and easy integration with jupyter-notebooks. You can create a separate virtual environment for machine learning tasks as they often require upgradation or downgradation of libraries. With virtual environments it won't hurt your other packages outside the environment.\n", "I had a similar problem because I had cuda and cuDNN versions way higher than what is mentioned in the compatibility chart. The Dense layers would work fine for me but using Conv2D/Conv3D would kill my kernel.\nSolution\nMake sure you have the zlib file copied and pasted into your CUDA\\v11.x\\bin directory. I had issues downloading it from NVIDIA's website but found a way around.\n\nIn NVIDIA website, they referred to zlibwapi.dll- I was able to locate this file in “C:\\Program Files\\Microsoft Office\\root\\Office16\\ODBC Drivers\\Salesforce\\lib” (I installed using Microsoft 365 x64 in windows 11) and copy pasted this file into “C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.6\\bin” I was able to run Tensorflow 2.8.0 thereafter\n\nThanks to srikkanth_kn's solution I was able to find the zlibwapi.dll file (in MS Office) and pasted it into the CUDA's bin folder (make sure CUDA's bin folder is in your PATH). After that everything was working fine. Hope this helps you and saves your time.\n", "in my case I needed to install\n\nconda install keras\n\n", "I had the same problem. In my case, the Notebook kernel was crashing as soon as I run the block with all model.add() code.\nI went to Jupyter Home and found out that another notebook, which I had used earlier to train a model on GPU, was running, even though I had closed the notebook browser tab. As suggested by @Ian Henry. I shutdown the ones I wasn't using, restarted the kernel and run all the blocks again, and this time it worked perfectly fine. \nNote that, the notebooks run in background even when you close the browser. You can verify this with if you check the icon for the respective notebook, which should be green if running and grey if not. To shutdown the running notebook, simply go to the Running tab, anc click the shutdown button next to the notebook name\n", "If you are using Jupyter check for any running notebooks, and as I've found that they hang on to the GPU memory even when they are actively running.\nIn jupyter shutdown any unused running ones.\n", "The problem is with the Jupyter notebook. I have the same problem going on with Jupyter notebook. If you run the same code in CPU based environment or in Terminal with GPU, it will work for sure. \n", "I had the same issue running model.fit() on Jupyter Notebook. A good starting point for debugging is always downloading the notebook as a .py file and run it. This way you get all errors and warnings.\nIn terms of a solution - I doubt that this will solve most cases, but I installed cuDNN 7.2(.1) via .deb files, reinstalled tensorflow-gpu, and it worked. After all, it wasn't a version issue the driver (I had CUDA 9.0 and 384.xx which was correct), but one with cuDNN.\n", "I had the same issue. After all, running the file as .py helped to see the problem was with cuDNN. Not all files were installed.\n", "I had Exactelly the same problem, I tried every solutions mentioned in this post and never works. After soo much tries, I found the problem, was the cuda installation, during the installation. I followed the Nvidia tutorial, but, at step of copy the 3 files from cudnn directory (like as tutorial) you should copy the 3 paths and just paste (substitute) at the nvidia directory, after this, my gpu works wothout problems\n", "The CUDA, CuDNN, Tensorflow and Python Version Compatibility table can be referred at https://www.tensorflow.org/install/source#gpu but I did with the following version installation and it works perfectly.\nThe problem can be solve by:\n\nInstall the latest anaconda navigator.\nInstall Python v3.8.x\nInstall Tensorflow v2.10.0\nInstall CUDA v11.8\nInstall CuDNN v8.6.x\nPaste the zlibwapi.dll file in the CUDA bin folder. The file can be downloaded from https://docs.nvidia.com/deeplearning/cudnn/install-guide/index.html#install-windows\nFollow the instructions give on the above link.\n\nThis is working for me. I was not placing the zlibwapi.dll in the CUDA/bin folder earlier, that was the reason I faced the same problem.\nI hope this helps.\n", "import os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nThis solution is provided by Krishna Kankipati at Kaggle site\n", "Please check cudnn.\nI had same problem and it was solved after using correct cudnn\n" ]
[ 4, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0044110799_keras_python_tensorflow.txt
Q: SQLalchemy select from postgresql table I have this model import os from dotenv import load_dotenv from sqlalchemy import Column, Date, Float, Integer, String,Numeric from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import declarative_base, Session Base = declarative_base() class MS(Base): try: __tablename__ = 'ms' column_not_exist_in_db = Column(Integer, primary_key=True) PROVIDER = Column(String) except SQLAlchemyError as e: error = str(e.__dict__['orig']) raise error this query import pandas as pd import sqlalchemy from sqlalchemy import select,func,distinct from sqlalchemy.orm import Session from sqlalchemy.sql import func as sql_function from sqlalchemy.exc import SQLAlchemyError from db.models.market_share_postgresql import MS def run_stmt(stmt,engine): df = pd.DataFrame() try: session = Session(engine, future=True) data = session.execute(stmt) df = pd.DataFrame(data.all()) if len(df) > 0: df.columns = data.keys() else: columns = data.keys() df = pd.DataFrame(columns=columns) df= df.rename(columns=str.lower) except SQLAlchemyError as e: error = str(e.__dict__['orig']) session.rollback() raise error else: session.commit() finally: engine.dispose() session.close() return df def ms_providers(engine): df = pd.DataFrame() try: stmt = select( distinct( MS.PROVIDER).label("PROVIDER") ) df=run_stmt(stmt,engine) except SQLAlchemyError as e: error = str(e.__dict__['orig']) raise error return df and this engine: dbschema='schema1,public' ConnectionString="postgresql+psycopg2://"+POSTGRESQL_USER+":"+POSTGRESQL_PASSWORD+"@"+POSTGRESQL_ACCOUNT+":"+POSTGRESQL_PORT+"/"+POSTGRESQL_DATABASE print(ConnectionString) engine = create_engine(ConnectionString,connect_args={'options': '-csearch_path={}'.format(dbschema)}) but after running the query, I get this error: psycopg2.errors.UndefinedTable: relation "database1.schema1.ms" does not exist LINE 2: FROM "database1.schema1".ms databse1,schema1,and ms table exist but seems sqlalchemy puts " in a wrong place as shown in the error: [SQL: SELECT DISTINCT "databse1.schema1".ms."PROVIDER" AS "PROVIDER" FROM "databse1.schema1".ms] How can I fix this? A: The problem was that PostgreSQL is case-sensitive and the data model was using the upper-case spelling of a column in the table which is all in lower-case (in my case) so fixed it as this PROVIDER = Column("provider",String)
SQLalchemy select from postgresql table
I have this model import os from dotenv import load_dotenv from sqlalchemy import Column, Date, Float, Integer, String,Numeric from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import declarative_base, Session Base = declarative_base() class MS(Base): try: __tablename__ = 'ms' column_not_exist_in_db = Column(Integer, primary_key=True) PROVIDER = Column(String) except SQLAlchemyError as e: error = str(e.__dict__['orig']) raise error this query import pandas as pd import sqlalchemy from sqlalchemy import select,func,distinct from sqlalchemy.orm import Session from sqlalchemy.sql import func as sql_function from sqlalchemy.exc import SQLAlchemyError from db.models.market_share_postgresql import MS def run_stmt(stmt,engine): df = pd.DataFrame() try: session = Session(engine, future=True) data = session.execute(stmt) df = pd.DataFrame(data.all()) if len(df) > 0: df.columns = data.keys() else: columns = data.keys() df = pd.DataFrame(columns=columns) df= df.rename(columns=str.lower) except SQLAlchemyError as e: error = str(e.__dict__['orig']) session.rollback() raise error else: session.commit() finally: engine.dispose() session.close() return df def ms_providers(engine): df = pd.DataFrame() try: stmt = select( distinct( MS.PROVIDER).label("PROVIDER") ) df=run_stmt(stmt,engine) except SQLAlchemyError as e: error = str(e.__dict__['orig']) raise error return df and this engine: dbschema='schema1,public' ConnectionString="postgresql+psycopg2://"+POSTGRESQL_USER+":"+POSTGRESQL_PASSWORD+"@"+POSTGRESQL_ACCOUNT+":"+POSTGRESQL_PORT+"/"+POSTGRESQL_DATABASE print(ConnectionString) engine = create_engine(ConnectionString,connect_args={'options': '-csearch_path={}'.format(dbschema)}) but after running the query, I get this error: psycopg2.errors.UndefinedTable: relation "database1.schema1.ms" does not exist LINE 2: FROM "database1.schema1".ms databse1,schema1,and ms table exist but seems sqlalchemy puts " in a wrong place as shown in the error: [SQL: SELECT DISTINCT "databse1.schema1".ms."PROVIDER" AS "PROVIDER" FROM "databse1.schema1".ms] How can I fix this?
[ "The problem was that PostgreSQL is case-sensitive and the data model was using the upper-case spelling of a column in the table which is all in lower-case (in my case)\nso fixed it as this\n PROVIDER = Column(\"provider\",String) \n\n" ]
[ 0 ]
[]
[]
[ "orm", "postgresql", "python", "python_3.x", "sqlalchemy" ]
stackoverflow_0074485023_orm_postgresql_python_python_3.x_sqlalchemy.txt
Q: Don't indent first level of tree in a recursive tree printer I would like to refactor a recursive tree-printing function I wrote so that the root node, the first call, is not indented at all. Tree = dict[str, 'Tree'] def print_tree(tree: Tree, prefix: str=''): if not tree: return markers = [('├── ', '│   '), ('└── ', ' ')] children = list(tree.items()) for key, subtree in children: is_last_child = (key, subtree) == children[-1] key_prefix, subtree_prefix = markers[is_last_child] print(prefix + key_prefix + key) print_tree(subtree, prefix + subtree_prefix) tree = {'.': {'alpha':{}, 'beta': {'beta.alpha':{}, 'beta.beta':{}}, 'charlie': {'charlie.alpha':{}, 'charlie.beta':{}, 'charlie.charlie':{}}, 'delta':{}}} print_tree(tree) Current output is └── . ├── alpha ├── beta │   ├── beta.alpha │   └── beta.beta ├── charlie │   ├── charlie.alpha │   ├── charlie.beta │   └── charlie.charlie └── delta But I would like the output to be . ├── alpha ├── beta │   ├── beta.alpha │   └── beta.beta ├── charlie │   ├── charlie.alpha │   ├── charlie.beta │   └── charlie.charlie └── delta I can't think of a way to do it elegantly, as in without special-casing the first call like this: def print_tree(tree: Tree, prefix: str='', root: bool=True): if not tree: return markers = [('├── ', '│   '), ('└── ', ' ')] if root: markers = [('', ''), ('', '')] children = list(tree.items()) for key, subtree in children: is_last_child = (key, subtree) == children[-1] key_prefix, subtree_prefix = markers[is_last_child] print(prefix + key_prefix + key) print_tree(subtree, prefix + subtree_prefix, root=False) How can I change the way I'm recursing to accomplish this? I don't want to add an extra argument to the function or otherwise require more information about state. I like how simple my current function is, it just prefixes the first level when I don't really want it to. A: Beautiful algorithm, I like it! (Much better than mine) This is the best I could do with your given restraints: Tree = dict[str, 'Tree'] def print_tree(tree: Tree, prefix: str=None): markers = [('├── ', '│ '), ('└── ', ' '), ('', '')] for i, (key, subtree) in enumerate(tree.items()): is_last_child = i == len(tree) - 1 marker_index = 2 if prefix is None else is_last_child prefix = prefix or "" key_prefix, subtree_prefix = markers[marker_index] print(prefix + key_prefix + key) print_tree(subtree, prefix + subtree_prefix) tree = {'.': {'alpha':{}, 'beta': {'beta.alpha':{}, 'beta.beta':{}}, 'charlie': {'charlie.alpha':{}, 'charlie.beta':{}, 'charlie.charlie':{}}, 'delta':{}}} print_tree(tree) . ├── alpha ├── beta │ ├── beta.alpha │ └── beta.beta ├── charlie │ ├── charlie.alpha │ ├── charlie.beta │ └── charlie.charlie └── delta Storing the root indicator inside the prefix by making the default None Added a third marker option which only root uses Replaced children list with enumerate using i to check if it's the last child Removed unnecessary empty tree check A: It does not yet do what you want, but you can maybe tweak it. Basically, I've just added a level parameter to track where you are at. It defaults to 0 so your initial call is much the same. Tree = dict[str, 'Tree'] def print_tree(tree: Tree, prefix: str='',level=0): # level starts out at zero.... if not tree: return markers = [('├── ', '│ '), ('└── ', ' ')] children = list(tree.items()) for key, subtree in children: is_last_child = (key, subtree) == children[-1] key_prefix, subtree_prefix = markers[is_last_child] #only if on level 1+ if level: #hack to avoid the extra blanks on the left print((prefix + key_prefix + key).lstrip()) print_tree(subtree, prefix + subtree_prefix,level=level+1) tree = {'.': {'alpha':{}, 'beta': {'beta.alpha':{}, 'beta.beta':{}}, 'charlie': {'charlie.alpha':{}, 'charlie.beta':{}, 'charlie.charlie':{}}, 'delta':{}}} print_tree(tree) output: ├── alpha ├── beta │ ├── beta.alpha │ └── beta.beta ├── charlie │ ├── charlie.alpha │ ├── charlie.beta │ └── charlie.charlie └── delta Awesome little thing, looks much like the Linux tree utility, which I have long wanted to filter somehow. Probably will re-use your code, once I've understood how it works. Hmmm, on second reading, that does look a bit like your special-casing first call. Oh well...
Don't indent first level of tree in a recursive tree printer
I would like to refactor a recursive tree-printing function I wrote so that the root node, the first call, is not indented at all. Tree = dict[str, 'Tree'] def print_tree(tree: Tree, prefix: str=''): if not tree: return markers = [('├── ', '│   '), ('└── ', ' ')] children = list(tree.items()) for key, subtree in children: is_last_child = (key, subtree) == children[-1] key_prefix, subtree_prefix = markers[is_last_child] print(prefix + key_prefix + key) print_tree(subtree, prefix + subtree_prefix) tree = {'.': {'alpha':{}, 'beta': {'beta.alpha':{}, 'beta.beta':{}}, 'charlie': {'charlie.alpha':{}, 'charlie.beta':{}, 'charlie.charlie':{}}, 'delta':{}}} print_tree(tree) Current output is └── . ├── alpha ├── beta │   ├── beta.alpha │   └── beta.beta ├── charlie │   ├── charlie.alpha │   ├── charlie.beta │   └── charlie.charlie └── delta But I would like the output to be . ├── alpha ├── beta │   ├── beta.alpha │   └── beta.beta ├── charlie │   ├── charlie.alpha │   ├── charlie.beta │   └── charlie.charlie └── delta I can't think of a way to do it elegantly, as in without special-casing the first call like this: def print_tree(tree: Tree, prefix: str='', root: bool=True): if not tree: return markers = [('├── ', '│   '), ('└── ', ' ')] if root: markers = [('', ''), ('', '')] children = list(tree.items()) for key, subtree in children: is_last_child = (key, subtree) == children[-1] key_prefix, subtree_prefix = markers[is_last_child] print(prefix + key_prefix + key) print_tree(subtree, prefix + subtree_prefix, root=False) How can I change the way I'm recursing to accomplish this? I don't want to add an extra argument to the function or otherwise require more information about state. I like how simple my current function is, it just prefixes the first level when I don't really want it to.
[ "Beautiful algorithm, I like it! (Much better than mine)\nThis is the best I could do with your given restraints:\nTree = dict[str, 'Tree']\ndef print_tree(tree: Tree, prefix: str=None):\n markers = [('├── ', '│ '), ('└── ', ' '), ('', '')]\n for i, (key, subtree) in enumerate(tree.items()):\n is_last_child = i == len(tree) - 1\n marker_index = 2 if prefix is None else is_last_child\n prefix = prefix or \"\"\n key_prefix, subtree_prefix = markers[marker_index]\n print(prefix + key_prefix + key)\n print_tree(subtree, prefix + subtree_prefix)\n\ntree = {'.': {'alpha':{}, 'beta': {'beta.alpha':{}, 'beta.beta':{}}, 'charlie': {'charlie.alpha':{}, 'charlie.beta':{}, 'charlie.charlie':{}}, 'delta':{}}}\nprint_tree(tree)\n\n.\n├── alpha\n├── beta\n│ ├── beta.alpha\n│ └── beta.beta\n├── charlie\n│ ├── charlie.alpha\n│ ├── charlie.beta\n│ └── charlie.charlie\n└── delta\n\n\nStoring the root indicator inside the prefix by making the default None\nAdded a third marker option which only root uses\nReplaced children list with enumerate using i to check if it's the last child\nRemoved unnecessary empty tree check\n\n", "It does not yet do what you want, but you can maybe tweak it.\nBasically, I've just added a level parameter to track where you are at. It defaults to 0 so your initial call is much the same.\nTree = dict[str, 'Tree']\ndef print_tree(tree: Tree, prefix: str='',level=0):\n # level starts out at zero....\n if not tree:\n return\n markers = [('├── ', '│ '), ('└── ', ' ')]\n children = list(tree.items())\n for key, subtree in children:\n is_last_child = (key, subtree) == children[-1]\n key_prefix, subtree_prefix = markers[is_last_child]\n\n #only if on level 1+\n if level:\n #hack to avoid the extra blanks on the left\n print((prefix + key_prefix + key).lstrip())\n print_tree(subtree, prefix + subtree_prefix,level=level+1)\n\n\ntree = {'.': {'alpha':{}, 'beta': {'beta.alpha':{}, 'beta.beta':{}}, 'charlie': {'charlie.alpha':{}, 'charlie.beta':{}, 'charlie.charlie':{}}, 'delta':{}}}\n\n\nprint_tree(tree)\n\n\noutput:\n├── alpha\n├── beta\n│ ├── beta.alpha\n│ └── beta.beta\n├── charlie\n│ ├── charlie.alpha\n│ ├── charlie.beta\n│ └── charlie.charlie\n└── delta\n\n\nAwesome little thing, looks much like the Linux tree utility, which I have long wanted to filter somehow. Probably will re-use your code, once I've understood how it works.\nHmmm, on second reading, that does look a bit like your special-casing first call. Oh well...\n" ]
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "recursion" ]
stackoverflow_0074484283_python_python_3.x_recursion.txt
Q: django KeyError: 'some-ForeignKey-field-in-model' I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words. The error is coming when I am trying to insert data into the DB table using python manage.py shell > from app_name.models import Usermanagement > from app_name.models import Inquery i = Inquery( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18", totalshipmentunits=56, unitid=100, grossweight=100, volumemetricweight=100, remark="test", dateofcreation="2018-11-20 00:00:00", dateofmodification="2018-11-20 00:00:00", createdby = Usermanagement(userid=0), modifiedby = Usermanagement(userid=0)) #error KeyError: 'createdby' #traceback File C:\Python310\lib\site-packages\django\db\models\base.py:768, in Model.save(self, force_insert, force_update, using, update_fields) 757 def save( 758 self, force_insert=False, force_update=False, using=None, update_fields=None 759 ): 760 """ 761 Save the current instance. Override this in a subclass if you want to 762 control the saving process. (...) 766 non-SQL backends), respectively. Normally, they should not be set. 767 """ --> 768 self._prepare_related_fields_for_save(operation_name="save") 770 using = using or router.db_for_write(self.__class__, instance=self) 771 if force_insert and (force_update or update_fields): File C:\Python310\lib\site-packages\django\db\models\base.py:1092, in Model._prepare_related_fields_for_save(self, operation_name, fields) 1087 # If the relationship's pk/to_field was changed, clear the 1088 # cached relationship. 1089 if getattr(obj, field.target_field.attname) != getattr( 1090 self, field.attname 1091 ): -> 1092 field.delete_cached_value(self) 1093 # GenericForeignKeys are private. 1094 for field in self._meta.private_fields: File C:\Python310\lib\site-packages\django\db\models\fields\mixins.py:28, in FieldCacheMixin.delete_cached_value(self, instance) 27 def delete_cached_value(self, instance): ---> 28 del instance._state.fields_cache[self.get_cache_name()] KeyError: 'createdby' #models.py (only some part of it, for sort Question) # this model is in freight app class Inquery(models.Model): inqueryid = models.BigAutoField(db_column='InqueryID', primary_key=True) inquerynumber = models.CharField(db_column='InqueryNumber', max_length=45) sourceairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='SourceAirportID',related_name="Flight_inquery_source") destinationairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='DestinationAirportID',related_name="Flight_inquery_destination") stageid = models.ForeignKey('Stage', on_delete=models.CASCADE, db_column='StageID') commoditytypeid = models.IntegerField(db_column='CommodityTypeID') customerid = models.ForeignKey(Customer, on_delete=models.CASCADE, db_column='CustomerID') branchid = models.IntegerField(db_column='BranchID') transactiontype = models.CharField(db_column='TransactionType', max_length=10) businesstype = models.CharField(db_column='BusinessType', max_length=15) hodate = models.DateTimeField(db_column='HODate') totalshipmentunits = models.CharField(db_column='TotalShipmentUnits', max_length=20) unitid = models.CharField(db_column='UnitID', max_length=3) grossweight = models.FloatField(db_column='GrossWeight') volumemetricweight = models.FloatField(db_column='VolumemetricWeight') remark = models.CharField(db_column='Remark', max_length=8000) dateofcreation = models.DateTimeField(db_column='DateOfCreation') dateofmodification = models.DateTimeField(db_column='DateOfModification') createdby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='CreatedBy', to_field='createdby',related_name="Usermanagement_Inquery_createdby") modifiedby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='ModifiedBy', to_field='modifiedby',related_name="Usermanagement_Inquery_modifiedby") isactive = models.IntegerField(db_column='IsActive') def __str__(self): return self.inquerynumber class Meta: managed = False db_table = 'Inquery' #another app model class Usermanagement(AbstractBaseUser): userid = models.BigAutoField(db_column='UserID', primary_key=True) emailid = models.CharField(db_column='EmailID', unique=True, max_length=45) roleid = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='RoleID') organizationid = models.ForeignKey(Organization, on_delete=models.CASCADE, db_column='OrganizationID') firstname = models.CharField(db_column='FirstName', max_length=45) middlename = models.CharField(db_column='MiddleName', max_length=45, blank=True, null=True) lastname = models.CharField(db_column='LastName', max_length=45, blank=True, null=True) numberofretry = models.IntegerField(db_column='NumberOfRetry',default=0) timeoffset = models.CharField(db_column='TimeOffSet', max_length=6,default="+5:30") password = models.CharField(db_column='Password', max_length=45) passwordexpirydate = models.DateTimeField(db_column='PasswordExpiryDate',default='2022-12-30 12:30:59') dateofcreation = models.DateTimeField(db_column='DateOfCreation',auto_now_add = True) dateofmodification = models.DateTimeField(db_column='DateOfModification',auto_now = True) createdby = models.BigIntegerField(db_column='CreatedBy',unique=True) #this field is FK in many other models modifiedby = models.BigIntegerField(db_column='ModifiedBy',unique=True) #this field is FK in many other models isactive = models.BooleanField(db_column='IsActive',default=1) last_login = False objects = UsermanagementCustomUserManager() USERNAME_FIELD = "emailid" EMAIL_FIELD = "emailid" REQUIRED_FIELDS = ["roleid","organizationid","firstname","passwordexpirydate","createdby","modifiedby"] def __str__(self): return self.emailid --------------------- some more code ------------------ A: You probably want to use Usermanagement.objects.get(userid=0) instead of Usermanagement(userid=0) To get an existing foreignkey and not create an instance of a User not saved in the database and thus not reachable A: as answered by @vctrd my query now is : Inquery ( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18", totalshipmentunits=56,unitid=100, grossweight=100, volumemetricweight=100,remark="test", dateofcreation="2018-11-20 00:00:00", dateofmodification="2018-11-20 00:00:00", createdby = Usermanagement.objects.get(userid=0), modifiedby = Usermanagement.objects.get(userid=0), isactive=1)
django KeyError: 'some-ForeignKey-field-in-model'
I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words. The error is coming when I am trying to insert data into the DB table using python manage.py shell > from app_name.models import Usermanagement > from app_name.models import Inquery i = Inquery( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18", totalshipmentunits=56, unitid=100, grossweight=100, volumemetricweight=100, remark="test", dateofcreation="2018-11-20 00:00:00", dateofmodification="2018-11-20 00:00:00", createdby = Usermanagement(userid=0), modifiedby = Usermanagement(userid=0)) #error KeyError: 'createdby' #traceback File C:\Python310\lib\site-packages\django\db\models\base.py:768, in Model.save(self, force_insert, force_update, using, update_fields) 757 def save( 758 self, force_insert=False, force_update=False, using=None, update_fields=None 759 ): 760 """ 761 Save the current instance. Override this in a subclass if you want to 762 control the saving process. (...) 766 non-SQL backends), respectively. Normally, they should not be set. 767 """ --> 768 self._prepare_related_fields_for_save(operation_name="save") 770 using = using or router.db_for_write(self.__class__, instance=self) 771 if force_insert and (force_update or update_fields): File C:\Python310\lib\site-packages\django\db\models\base.py:1092, in Model._prepare_related_fields_for_save(self, operation_name, fields) 1087 # If the relationship's pk/to_field was changed, clear the 1088 # cached relationship. 1089 if getattr(obj, field.target_field.attname) != getattr( 1090 self, field.attname 1091 ): -> 1092 field.delete_cached_value(self) 1093 # GenericForeignKeys are private. 1094 for field in self._meta.private_fields: File C:\Python310\lib\site-packages\django\db\models\fields\mixins.py:28, in FieldCacheMixin.delete_cached_value(self, instance) 27 def delete_cached_value(self, instance): ---> 28 del instance._state.fields_cache[self.get_cache_name()] KeyError: 'createdby' #models.py (only some part of it, for sort Question) # this model is in freight app class Inquery(models.Model): inqueryid = models.BigAutoField(db_column='InqueryID', primary_key=True) inquerynumber = models.CharField(db_column='InqueryNumber', max_length=45) sourceairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='SourceAirportID',related_name="Flight_inquery_source") destinationairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='DestinationAirportID',related_name="Flight_inquery_destination") stageid = models.ForeignKey('Stage', on_delete=models.CASCADE, db_column='StageID') commoditytypeid = models.IntegerField(db_column='CommodityTypeID') customerid = models.ForeignKey(Customer, on_delete=models.CASCADE, db_column='CustomerID') branchid = models.IntegerField(db_column='BranchID') transactiontype = models.CharField(db_column='TransactionType', max_length=10) businesstype = models.CharField(db_column='BusinessType', max_length=15) hodate = models.DateTimeField(db_column='HODate') totalshipmentunits = models.CharField(db_column='TotalShipmentUnits', max_length=20) unitid = models.CharField(db_column='UnitID', max_length=3) grossweight = models.FloatField(db_column='GrossWeight') volumemetricweight = models.FloatField(db_column='VolumemetricWeight') remark = models.CharField(db_column='Remark', max_length=8000) dateofcreation = models.DateTimeField(db_column='DateOfCreation') dateofmodification = models.DateTimeField(db_column='DateOfModification') createdby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='CreatedBy', to_field='createdby',related_name="Usermanagement_Inquery_createdby") modifiedby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='ModifiedBy', to_field='modifiedby',related_name="Usermanagement_Inquery_modifiedby") isactive = models.IntegerField(db_column='IsActive') def __str__(self): return self.inquerynumber class Meta: managed = False db_table = 'Inquery' #another app model class Usermanagement(AbstractBaseUser): userid = models.BigAutoField(db_column='UserID', primary_key=True) emailid = models.CharField(db_column='EmailID', unique=True, max_length=45) roleid = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='RoleID') organizationid = models.ForeignKey(Organization, on_delete=models.CASCADE, db_column='OrganizationID') firstname = models.CharField(db_column='FirstName', max_length=45) middlename = models.CharField(db_column='MiddleName', max_length=45, blank=True, null=True) lastname = models.CharField(db_column='LastName', max_length=45, blank=True, null=True) numberofretry = models.IntegerField(db_column='NumberOfRetry',default=0) timeoffset = models.CharField(db_column='TimeOffSet', max_length=6,default="+5:30") password = models.CharField(db_column='Password', max_length=45) passwordexpirydate = models.DateTimeField(db_column='PasswordExpiryDate',default='2022-12-30 12:30:59') dateofcreation = models.DateTimeField(db_column='DateOfCreation',auto_now_add = True) dateofmodification = models.DateTimeField(db_column='DateOfModification',auto_now = True) createdby = models.BigIntegerField(db_column='CreatedBy',unique=True) #this field is FK in many other models modifiedby = models.BigIntegerField(db_column='ModifiedBy',unique=True) #this field is FK in many other models isactive = models.BooleanField(db_column='IsActive',default=1) last_login = False objects = UsermanagementCustomUserManager() USERNAME_FIELD = "emailid" EMAIL_FIELD = "emailid" REQUIRED_FIELDS = ["roleid","organizationid","firstname","passwordexpirydate","createdby","modifiedby"] def __str__(self): return self.emailid --------------------- some more code ------------------
[ "You probably want to use Usermanagement.objects.get(userid=0) instead of Usermanagement(userid=0)\nTo get an existing foreignkey and not create an instance of a User not saved in the database and thus not reachable\n", "as answered by @vctrd\nmy query now is :\nInquery ( inqueryid=6, inquerynumber=\"INQ765758499\", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype=\"AGENT\", businesstype=\"Self\", hodate=\"2020-11-18\", totalshipmentunits=56,unitid=100, grossweight=100, volumemetricweight=100,remark=\"test\", dateofcreation=\"2018-11-20 00:00:00\", dateofmodification=\"2018-11-20 00:00:00\", createdby = Usermanagement.objects.get(userid=0), modifiedby = Usermanagement.objects.get(userid=0), isactive=1)\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_orm", "django_views", "python" ]
stackoverflow_0074479899_django_django_models_django_orm_django_views_python.txt
Q: Find the closing price of stocks in last 90 days using python Details of Case: There are 161 stocks in excel file, you have to find closing price for these stocks for last 90days Download files using following links : https://drive.google.com/drive/folders/1utGBygI2vcs0hYlnTpCA_i3Uo8VRj1lH?usp=sharing File 1: List of Stocks case study : Symbol of stocks File 2: Sample Output Format for one stock: This file has desired output format for one stock. A: I think you shoud try pandas_datareader package . It will help you to find a data as you want. import pandas as pd from pandas_datareader import data symbol = 'INFY' # pass the symbol name end = pd.datetime.now() # current date and time - can be changed as per requirement start = end - pd.Timedelta(days=90) # ninety days before df = data.DataReader(symbol, 'yahoo', start, end) # get close price close_price = df['Close'] # get last n close prices n = 3 last_n_close_price = close_price.tail(n) print("Last {} close prices:".format(n)) print(last_n_close_price)
Find the closing price of stocks in last 90 days using python
Details of Case: There are 161 stocks in excel file, you have to find closing price for these stocks for last 90days Download files using following links : https://drive.google.com/drive/folders/1utGBygI2vcs0hYlnTpCA_i3Uo8VRj1lH?usp=sharing File 1: List of Stocks case study : Symbol of stocks File 2: Sample Output Format for one stock: This file has desired output format for one stock.
[ "I think you shoud try pandas_datareader package .\nIt will help you to find a data as you want.\nimport pandas as pd\nfrom pandas_datareader import data\n\nsymbol = 'INFY' # pass the symbol name\nend = pd.datetime.now() # current date and time - can be changed as per requirement\nstart = end - pd.Timedelta(days=90) # ninety days before\n\ndf = data.DataReader(symbol, 'yahoo', start, end)\n\n# get close price\nclose_price = df['Close']\n\n# get last n close prices\nn = 3\nlast_n_close_price = close_price.tail(n)\n\nprint(\"Last {} close prices:\".format(n))\nprint(last_n_close_price)\n\n" ]
[ 0 ]
[]
[]
[ "excel", "python", "stock" ]
stackoverflow_0074484328_excel_python_stock.txt
Q: `Building wheel for opencv-python (PEP 517) ... -` runs forever When I run !pip install imgaug==0.4.0 the following is the output Collecting imgaug==0.4.0 Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl Requirement already satisfied: Pillow in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (5.4.1) Requirement already satisfied: numpy>=1.15 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.15.4) Collecting Shapely (from imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/9d/18/557d4f55453fe00f59807b111cc7b39ce53594e13ada88e16738fb4ff7fb/Shapely-1.7.1-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied: six in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.12.0) Requirement already satisfied: matplotlib in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (3.0.2) Collecting scikit-image>=0.14.2 (from imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/0e/ba/53e1bfbdfd0f94514d71502e3acea494a8b4b57c457adbc333ef386485da/scikit_image-0.17.2-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied: imageio in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (2.4.1) Collecting opencv-python (from imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/77/f5/49f034f8d109efcf9b7e98fbc051878b83b2f02a1c73f92bbd37f317288e/opencv-python-4.4.0.42.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Requirement already satisfied: scipy in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.2.0) Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (1.0.1) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.3.1) Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.7.5) Collecting tifffile>=2019.7.26 (from scikit-image>=0.14.2->imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/3c/13/4f873f6b167c2e77288ce8db1c9f742d1e0e1463644e2df4e3bd3c40a422/tifffile-2020.8.25-py3-none-any.whl Requirement already satisfied: networkx>=2.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (2.2) Collecting PyWavelets>=1.1.1 (from scikit-image>=0.14.2->imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/59/bb/d2b85265ec9fa3c1922210c9393d4cdf7075cc87cce6fe671d7455f80fbc/PyWavelets-1.1.1-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied: setuptools in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib->imgaug==0.4.0) (40.8.0) Requirement already satisfied: decorator>=4.3.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from networkx>=2.0->scikit-image>=0.14.2->imgaug==0.4.0) (4.3.2) Building wheels for collected packages: opencv-python Building wheel for opencv-python (PEP 517) ... - But the Building wheel for opencv-python (PEP 517) ... - runs forever, how to resolve this problem? A: i had the same problem, everything worked out: pip install --upgrade pip setuptools wheel A: Solve by install openCV-Python explicitly first using !pip install opencv-python==4.3.0.38 If this version does not exist it would open version that exist. Then you can run !pip install imgaug. As the older version of opencv-python doesn't require wheel compilation. A: It happened to me as well while i was downloading pip install opencv-python Just go to the preferences, go to python interpreter and then check for the wheels package and delete it by clicking on it and pressing the minus mark next to the add mark. This error comes because to download it, the package should first build thousands of dependencies for wheels as opencv is a big package. If you uninstall wheels then they don't have to build dependencies. Note that uninstalling wheels won't affect anything in the code. I have a mac and use pycharm as the IDE so, i am not sure whether it works on other devices. This is a image of the the interpreter that is after uninstalling wheels A: If you are using Raspberry pi then use command pip install opencv-python==4.5.3.56 then update numpy using pip install -U numpy and then install package you need to install which has OpenCV dependency. A: python -m pip install --upgrade opencv-python --user
`Building wheel for opencv-python (PEP 517) ... -` runs forever
When I run !pip install imgaug==0.4.0 the following is the output Collecting imgaug==0.4.0 Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl Requirement already satisfied: Pillow in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (5.4.1) Requirement already satisfied: numpy>=1.15 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.15.4) Collecting Shapely (from imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/9d/18/557d4f55453fe00f59807b111cc7b39ce53594e13ada88e16738fb4ff7fb/Shapely-1.7.1-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied: six in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.12.0) Requirement already satisfied: matplotlib in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (3.0.2) Collecting scikit-image>=0.14.2 (from imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/0e/ba/53e1bfbdfd0f94514d71502e3acea494a8b4b57c457adbc333ef386485da/scikit_image-0.17.2-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied: imageio in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (2.4.1) Collecting opencv-python (from imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/77/f5/49f034f8d109efcf9b7e98fbc051878b83b2f02a1c73f92bbd37f317288e/opencv-python-4.4.0.42.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Requirement already satisfied: scipy in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.2.0) Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (1.0.1) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.3.1) Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.7.5) Collecting tifffile>=2019.7.26 (from scikit-image>=0.14.2->imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/3c/13/4f873f6b167c2e77288ce8db1c9f742d1e0e1463644e2df4e3bd3c40a422/tifffile-2020.8.25-py3-none-any.whl Requirement already satisfied: networkx>=2.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (2.2) Collecting PyWavelets>=1.1.1 (from scikit-image>=0.14.2->imgaug==0.4.0) Using cached https://files.pythonhosted.org/packages/59/bb/d2b85265ec9fa3c1922210c9393d4cdf7075cc87cce6fe671d7455f80fbc/PyWavelets-1.1.1-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied: setuptools in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib->imgaug==0.4.0) (40.8.0) Requirement already satisfied: decorator>=4.3.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from networkx>=2.0->scikit-image>=0.14.2->imgaug==0.4.0) (4.3.2) Building wheels for collected packages: opencv-python Building wheel for opencv-python (PEP 517) ... - But the Building wheel for opencv-python (PEP 517) ... - runs forever, how to resolve this problem?
[ "i had the same problem, everything worked out:\npip install --upgrade pip setuptools wheel\n\n", "Solve by install openCV-Python explicitly first using\n!pip install opencv-python==4.3.0.38\nIf this version does not exist it would open version that exist.\nThen you can run !pip install imgaug.\nAs the older version of opencv-python doesn't require wheel compilation.\n", "It happened to me as well while i was downloading pip install opencv-python\nJust go to the preferences, go to python interpreter and then check for the wheels package and delete it by clicking on it and pressing the minus mark next to the add mark. This error comes because to download it, the package should first build thousands of dependencies for wheels as opencv is a big package. If you uninstall wheels then they don't have to build dependencies. Note that uninstalling wheels won't affect anything in the code. I have a mac and use pycharm as the IDE so, i am not sure whether it works on other devices.\nThis is a image of the the interpreter that is after uninstalling wheels\n\n", "If you are using Raspberry pi then use command pip install opencv-python==4.5.3.56 then update numpy using pip install -U numpy and then install package you need to install which has OpenCV dependency.\n", "python -m pip install --upgrade opencv-python --user\n" ]
[ 45, 22, 1, 1, 0 ]
[ "pip install opencv-python==4.5.3.56\n\nuse this , its work for me 100%.\nand it will save your time too.\n", "Small PSA for anyone trying to run the command pip install opencv-contrib-python on a Raspberry Pi.\nIf it seems stuck, know that the installation will take 2 hours.\n", "try using old version of python. for example,python3.7\n" ]
[ -1, -1, -5 ]
[ "opencv_python", "python", "python_3.x" ]
stackoverflow_0063669752_opencv_python_python_python_3.x.txt
Q: Python MetaTrader5 indicators I'm using Metatrader5 module for python and this is my code ''' #python from datetime import datetime import MetaTrader5 as mt5 # display data on the MetaTrader 5 package print("MetaTrader5 package author: ", mt5.__author__) print("MetaTrader5 package version: ", mt5.__version__) # import the 'pandas' module for displaying data obtained in the tabular form import pandas as pd pd.set_option('display.max_columns', 500) # number of columns to be displayed pd.set_option('display.width', 1500) # max table width to display # import pytz module for working with time zone import pytz # establish connection to MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed") mt5.shutdown() # set time zone to UTC timezone = pytz.timezone("Etc/UTC") # create 'datetime' object in UTC time zone to avoid the implementation of a local time zone offset utc_from = datetime(2020, 1, 10, tzinfo=timezone) # get 10 EURUSD H4 bars starting from 01.10.2020 in UTC time zone rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_H4, utc_from, 10) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() # display each element of obtained data in a new line print("Display obtained data 'as is'") for rate in rates: print(rate) # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the datetime format rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') # display data print("\nDisplay dataframe with data") print(rates_frame) ''' My question is s there any easy way to calculate stock indicators like RSI and MFI and other indicators using this module? A: No. Its possible if using other modules though. Here is a method using another that could achieve it: https://www.mql5.com/en/articles/5691 Alternatively, you can pull the data from MT5 and throw it in TA-lib for analysis. TA-lib consumes the data and provides values for the indicators outside MT5. Check out TA-lib: https://mrjbq7.github.io/ta-lib/ A: Since your data will be in a pandas df, I would check out pandas-ta, https://pypi.org/project/pandas-ta, all technical indicators. Also, thats a lot of code to pull your data, this is what I use; import MetaTrader5 as mt import pandas as pd from datetime import datetime mt.initialize() df = pd.DataFrame( mt.copy_rates_range( '@MNQ', #micro nasd100 mt.TIMEFRAME_D1, datetime( 2022, 1, 1 ), datetime.now() ) ) # manipulate as you please mt.shutdown() and i didnt like the GMT+2 timezone used by metatrader at first but Ive found its easier to get used to it as the date change is timed to the daily futures market open at 5pm central, which in GMT+2 is day+1 00:00.
Python MetaTrader5 indicators
I'm using Metatrader5 module for python and this is my code ''' #python from datetime import datetime import MetaTrader5 as mt5 # display data on the MetaTrader 5 package print("MetaTrader5 package author: ", mt5.__author__) print("MetaTrader5 package version: ", mt5.__version__) # import the 'pandas' module for displaying data obtained in the tabular form import pandas as pd pd.set_option('display.max_columns', 500) # number of columns to be displayed pd.set_option('display.width', 1500) # max table width to display # import pytz module for working with time zone import pytz # establish connection to MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed") mt5.shutdown() # set time zone to UTC timezone = pytz.timezone("Etc/UTC") # create 'datetime' object in UTC time zone to avoid the implementation of a local time zone offset utc_from = datetime(2020, 1, 10, tzinfo=timezone) # get 10 EURUSD H4 bars starting from 01.10.2020 in UTC time zone rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_H4, utc_from, 10) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() # display each element of obtained data in a new line print("Display obtained data 'as is'") for rate in rates: print(rate) # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the datetime format rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') # display data print("\nDisplay dataframe with data") print(rates_frame) ''' My question is s there any easy way to calculate stock indicators like RSI and MFI and other indicators using this module?
[ "No. Its possible if using other modules though.\nHere is a method using another that could achieve it: \nhttps://www.mql5.com/en/articles/5691\nAlternatively, you can pull the data from MT5 and throw it in TA-lib for analysis. TA-lib consumes the data and provides values for the indicators outside MT5.\nCheck out TA-lib: https://mrjbq7.github.io/ta-lib/\n", "Since your data will be in a pandas df, I would check out pandas-ta, https://pypi.org/project/pandas-ta, all technical indicators. Also, thats a lot of code to pull your data, this is what I use;\nimport MetaTrader5 as mt\nimport pandas as pd\nfrom datetime import datetime\n\nmt.initialize()\n\ndf = pd.DataFrame( mt.copy_rates_range( '@MNQ', #micro nasd100\n mt.TIMEFRAME_D1, \n datetime( 2022, 1, 1 ), \n datetime.now() ) )\n\n# manipulate as you please\n\nmt.shutdown()\n\nand i didnt like the GMT+2 timezone used by metatrader at first but Ive found its easier to get used to it as the date change is timed to the daily futures market open at 5pm central, which in GMT+2 is day+1 00:00.\n" ]
[ 1, 0 ]
[]
[]
[ "metatrader5", "python" ]
stackoverflow_0060404229_metatrader5_python.txt
Q: Error trying to migrate my database. Typing error Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations). I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is: (paginas) root@janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations Traceback (most recent call last): File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection conn = Database.connect(**conn_params) TypeError: argument 1 must be str, not PosixPath During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/home/paginas/lib/python3.6/site-packages/django/db/utils.py", line 230, in close_all connection.close() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 261, in close if not self.is_in_memory_db(): File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable Try changing this: For this: Sorry if I added the images wrong I'm new to this page. This is my settings.py file: """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-k3d35^_5m3-=t-7&-!4qq78o+h%-ra6atz-a9m1)19a7()$8u2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['31.220.48.123'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'mainapp', 'pages.apps.PagesConfig', 'blog.apps.BlogConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ProyectoDjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'pages.context_processors.get_pages', 'blog.processor.get_categories', ], }, }, ] WSGI_APPLICATION = 'ProyectoDjango.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } """ """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'proyectodjango', 'USER': 'root', 'PASSWORD': '12345', 'HOST': 'localhost', 'PORT': 3306 } } """ # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'es-es' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') """ and this is my manage.py file: enter image description here A: In the error message it says that you need a string instead of 'PosixPath' try turning the path into a string. A: You can also use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } A: Simply you can try this way: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } After adding above code in settings.py file, first you need to delete db file and delete all migration folders of each app and then run below commands: python manage.py makemigrations appname python manage.py sqlmigrate appname 0001 python manage.py migrate And now your problem will solve.
Error trying to migrate my database. Typing error
Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations). I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is: (paginas) root@janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations Traceback (most recent call last): File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection conn = Database.connect(**conn_params) TypeError: argument 1 must be str, not PosixPath During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/home/paginas/lib/python3.6/site-packages/django/db/utils.py", line 230, in close_all connection.close() File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 261, in close if not self.is_in_memory_db(): File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable Try changing this: For this: Sorry if I added the images wrong I'm new to this page. This is my settings.py file: """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-k3d35^_5m3-=t-7&-!4qq78o+h%-ra6atz-a9m1)19a7()$8u2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['31.220.48.123'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'mainapp', 'pages.apps.PagesConfig', 'blog.apps.BlogConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ProyectoDjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'pages.context_processors.get_pages', 'blog.processor.get_categories', ], }, }, ] WSGI_APPLICATION = 'ProyectoDjango.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } """ """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'proyectodjango', 'USER': 'root', 'PASSWORD': '12345', 'HOST': 'localhost', 'PORT': 3306 } } """ # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'es-es' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') """ and this is my manage.py file: enter image description here
[ "In the error message it says that you need a string instead of 'PosixPath' try turning the path into a string.\n", "You can also use:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n }\n\n", "Simply you can try this way:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\nAfter adding above code in settings.py file, first you need to delete db file and delete all migration folders of each app and then run below commands:\npython manage.py makemigrations appname\n\npython manage.py sqlmigrate appname 0001\n\npython manage.py migrate\n\nAnd now your problem will solve.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "django", "django_database", "django_settings", "python" ]
stackoverflow_0074478247_django_django_database_django_settings_python.txt
Q: Count the number of tokens/expressions in a Python program There exist many tools to count the source lines of code in a program. I currently use cloc. I often use this as a proxy to measure complexity of a project I'm working on, and occasionally spend a few weeks trying to minimize this measure. However, it's not ideal, because it's affected by things like the length of variable names. Is there an easy way, maybe by leveraging bits of the python interpreter/AST parser itself, to count the number of distinct tokens in a Python program? For example: grammar = grammar_path.read_text(encoding="UTF-8") this line would have maybe 6 tokens, if we count the second argument to getattr() and then assignment operator. I'm hoping there's an implementation of this somewhere, and I just don't know what to google to find it. It would also be helpful to know if there are any existing tools for doing this in other languages. A: The line grammar = grammar_path.read_text(encoding="UTF-8") has ten tokens, or eleven if you count the NEWLINE token at the end of the line. You can easily see that, using the generate_tokens method from built-in tokenize standard library module. (Although I use v3.11 in the examples below, the tokenize model has been available since v2.2. There have been changes to the details of the produced tokens, though.) Note that the generate_token method expects its argument to be a function which iterates over input lines. For a simple demonstration, I just used sys.stdin.readline, which reads successive lines from stdin. A more normal usage would be to supply the readline method for a file open for reading. I used enumerate in the example in order to number the successive tokens. $ python3.11 Python 3.11.0 (main, Oct 24 2022, 19:56:01) [GCC 7.5.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tokenize >>> import sys >>> for i, token in enumerate(tokenize.generate_tokens(sys.stdin.readline), start=1): ... print(f"""{i:3}: {token}""") ... grammar = grammar_path.read_text(encoding="UTF-8") 1: TokenInfo(type=1 (NAME), string='grammar', start=(1, 0), end=(1, 7), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 2: TokenInfo(type=54 (OP), string='=', start=(1, 8), end=(1, 9), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 3: TokenInfo(type=1 (NAME), string='grammar_path', start=(1, 10), end=(1, 22), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 4: TokenInfo(type=54 (OP), string='.', start=(1, 22), end=(1, 23), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 5: TokenInfo(type=1 (NAME), string='read_text', start=(1, 23), end=(1, 32), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 6: TokenInfo(type=54 (OP), string='(', start=(1, 32), end=(1, 33), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 7: TokenInfo(type=1 (NAME), string='encoding', start=(1, 33), end=(1, 41), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 8: TokenInfo(type=54 (OP), string='=', start=(1, 41), end=(1, 42), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 9: TokenInfo(type=3 (STRING), string='"UTF-8"', start=(1, 42), end=(1, 49), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 10: TokenInfo(type=54 (OP), string=')', start=(1, 49), end=(1, 50), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') 11: TokenInfo(type=4 (NEWLINE), string='\n', start=(1, 50), end=(1, 51), line='grammar = grammar_path.read_text(encoding="UTF-8")\n') At this point, the loop is waiting for the next line; in order to terminate the loop, I need to type an end-of-input marker (Control-D on Unix; Control-Z on Windows; in both cases, followed by Enter). The tokenizer will then return a final ENDMARKER token: 12: TokenInfo(type=0 (ENDMARKER), string='', start=(2, 0), end=(2, 0), line='') As explained in the docs, you can also use the standard library module as a command-line utility to list tokens. Again, I had to terminate the input by typing the end-of-input marker, after which the last line was printed: $ python3.11 -m tokenize grammar = grammar_path.read_text(encoding="UTF-8") 1,0-1,7: NAME 'grammar' 1,8-1,9: OP '=' 1,10-1,22: NAME 'grammar_path' 1,22-1,23: OP '.' 1,23-1,32: NAME 'read_text' 1,32-1,33: OP '(' 1,33-1,41: NAME 'encoding' 1,41-1,42: OP '=' 1,42-1,49: STRING '"UTF-8"' 1,49-1,50: OP ')' 1,50-1,51: NEWLINE '\n' 2,0-2,0: ENDMARKER ''
Count the number of tokens/expressions in a Python program
There exist many tools to count the source lines of code in a program. I currently use cloc. I often use this as a proxy to measure complexity of a project I'm working on, and occasionally spend a few weeks trying to minimize this measure. However, it's not ideal, because it's affected by things like the length of variable names. Is there an easy way, maybe by leveraging bits of the python interpreter/AST parser itself, to count the number of distinct tokens in a Python program? For example: grammar = grammar_path.read_text(encoding="UTF-8") this line would have maybe 6 tokens, if we count the second argument to getattr() and then assignment operator. I'm hoping there's an implementation of this somewhere, and I just don't know what to google to find it. It would also be helpful to know if there are any existing tools for doing this in other languages.
[ "The line grammar = grammar_path.read_text(encoding=\"UTF-8\") has ten tokens, or eleven if you count the NEWLINE token at the end of the line. You can easily see that, using the generate_tokens method from built-in tokenize standard library module. (Although I use v3.11 in the examples below, the tokenize model has been available since v2.2. There have been changes to the details of the produced tokens, though.)\nNote that the generate_token method expects its argument to be a function which iterates over input lines. For a simple demonstration, I just used sys.stdin.readline, which reads successive lines from stdin. A more normal usage would be to supply the readline method for a file open for reading. I used enumerate in the example in order to number the successive tokens.\n$ python3.11\nPython 3.11.0 (main, Oct 24 2022, 19:56:01) [GCC 7.5.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import tokenize\n>>> import sys\n>>> for i, token in enumerate(tokenize.generate_tokens(sys.stdin.readline), start=1):\n... print(f\"\"\"{i:3}: {token}\"\"\")\n... \ngrammar = grammar_path.read_text(encoding=\"UTF-8\")\n 1: TokenInfo(type=1 (NAME), string='grammar', start=(1, 0), end=(1, 7), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 2: TokenInfo(type=54 (OP), string='=', start=(1, 8), end=(1, 9), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 3: TokenInfo(type=1 (NAME), string='grammar_path', start=(1, 10), end=(1, 22), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 4: TokenInfo(type=54 (OP), string='.', start=(1, 22), end=(1, 23), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 5: TokenInfo(type=1 (NAME), string='read_text', start=(1, 23), end=(1, 32), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 6: TokenInfo(type=54 (OP), string='(', start=(1, 32), end=(1, 33), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 7: TokenInfo(type=1 (NAME), string='encoding', start=(1, 33), end=(1, 41), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 8: TokenInfo(type=54 (OP), string='=', start=(1, 41), end=(1, 42), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 9: TokenInfo(type=3 (STRING), string='\"UTF-8\"', start=(1, 42), end=(1, 49), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 10: TokenInfo(type=54 (OP), string=')', start=(1, 49), end=(1, 50), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n 11: TokenInfo(type=4 (NEWLINE), string='\\n', start=(1, 50), end=(1, 51), line='grammar = grammar_path.read_text(encoding=\"UTF-8\")\\n')\n\nAt this point, the loop is waiting for the next line; in order to terminate the loop, I need to type an end-of-input marker (Control-D on Unix; Control-Z on Windows; in both cases, followed by Enter). The tokenizer will then return a final ENDMARKER token:\n 12: TokenInfo(type=0 (ENDMARKER), string='', start=(2, 0), end=(2, 0), line='')\n\nAs explained in the docs, you can also use the standard library module as a command-line utility to list tokens. Again, I had to terminate the input by typing the end-of-input marker, after which the last line was printed:\n$ python3.11 -m tokenize\ngrammar = grammar_path.read_text(encoding=\"UTF-8\") \n1,0-1,7: NAME 'grammar' \n1,8-1,9: OP '=' \n1,10-1,22: NAME 'grammar_path' \n1,22-1,23: OP '.' \n1,23-1,32: NAME 'read_text' \n1,32-1,33: OP '(' \n1,33-1,41: NAME 'encoding' \n1,41-1,42: OP '=' \n1,42-1,49: STRING '\"UTF-8\"' \n1,49-1,50: OP ')' \n1,50-1,51: NEWLINE '\\n' \n2,0-2,0: ENDMARKER '' \n\n" ]
[ 1 ]
[]
[]
[ "abstract_syntax_tree", "interpreter", "parsing", "python" ]
stackoverflow_0074484976_abstract_syntax_tree_interpreter_parsing_python.txt
Q: appending a CSV column to a list using a for loop Code written by Abdulmalik import csv def loadCSVData(filename): list = [] #list for storing file content with open(filename, newline='') as file:# fileContent = csv.DictReader(file) for line in fileContent: list.append(line['Score']) print(list) fileContent.close() return list expected output: ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4', '88.2', '88', '87.8', '87.6', '87.5', '87.3', '87.2', '87', '86.9', '86.8', '86.6', '86.5', '86.4', '86.3', '86.1', '86', '85.9', '85.8', '85.7', '85.6', '85.5', '85.4', '85.3', '85.2', '85.1', '85', '85', '84.9', '84.8', '84.7', '84.6', '84.5', '84.5', '84.4', '84.3', '84.2', '84.2', '84.1', '84', '84', '83.9', '83.8', '83.8', '83.7', '83.6', '83.6', '83.5', '83.4', '83.4', '83.3', '83.3', '83.2', '83.1', '83.1', '83', '83', '82.9', '82.9', '82.8', '82.8', '82.7', '82.6', '82.6', '82.5', '82.5', '82.4', '82.4', '82.3', '82.3', '82.2', '82.2', '82.2', '82.1', '82.1', '82', '82', '81.9', '81.9', '81.8', '81.8', '81.8'] actual output: '100'] ['100', '96.7'] ['100', '96.7', '95.1'] ['100', '96.7', '95.1', '94.1'] ['100', '96.7', '95.1', '94.1', '93.3'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4', '88.2'] Too long to paste the whole outcome, that's my attempt so far, my main goal is too strip(), and split(',') but I can't do that with ctv, I am adding the data from one column to the list, if you can please try to show it with dict and list that would be wounderful, but list is good for now. A: You writen print statement inside the loop .That's why it's printing output like this. You need to write print out side from a loop, like this. with open(filename, newline='') as file:# fileContent = csv.DictReader(file) for line in fileContent: list.append(line['Score']) print(list) fileContent.close()
appending a CSV column to a list using a for loop
Code written by Abdulmalik import csv def loadCSVData(filename): list = [] #list for storing file content with open(filename, newline='') as file:# fileContent = csv.DictReader(file) for line in fileContent: list.append(line['Score']) print(list) fileContent.close() return list expected output: ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4', '88.2', '88', '87.8', '87.6', '87.5', '87.3', '87.2', '87', '86.9', '86.8', '86.6', '86.5', '86.4', '86.3', '86.1', '86', '85.9', '85.8', '85.7', '85.6', '85.5', '85.4', '85.3', '85.2', '85.1', '85', '85', '84.9', '84.8', '84.7', '84.6', '84.5', '84.5', '84.4', '84.3', '84.2', '84.2', '84.1', '84', '84', '83.9', '83.8', '83.8', '83.7', '83.6', '83.6', '83.5', '83.4', '83.4', '83.3', '83.3', '83.2', '83.1', '83.1', '83', '83', '82.9', '82.9', '82.8', '82.8', '82.7', '82.6', '82.6', '82.5', '82.5', '82.4', '82.4', '82.3', '82.3', '82.2', '82.2', '82.2', '82.1', '82.1', '82', '82', '81.9', '81.9', '81.8', '81.8', '81.8'] actual output: '100'] ['100', '96.7'] ['100', '96.7', '95.1'] ['100', '96.7', '95.1', '94.1'] ['100', '96.7', '95.1', '94.1', '93.3'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4'] ['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4', '88.2'] Too long to paste the whole outcome, that's my attempt so far, my main goal is too strip(), and split(',') but I can't do that with ctv, I am adding the data from one column to the list, if you can please try to show it with dict and list that would be wounderful, but list is good for now.
[ "You writen print statement inside the loop .That's why it's printing output like this.\nYou need to write print out side from a loop, like this.\nwith open(filename, newline='') as file:# \n fileContent = csv.DictReader(file)\n for line in fileContent:\n list.append(line['Score'])\n print(list)\n fileContent.close()\n\n" ]
[ 1 ]
[]
[]
[ "csv", "for_loop", "list", "python", "python_3.x" ]
stackoverflow_0074483539_csv_for_loop_list_python_python_3.x.txt
Q: Cant find Funktion Screenshot() from pyautogui is Not find in Visual Studio I installed the package pyautogui with pip install pyautogui. All functions of this Package worked fine, But when I type „pyautogui.“ there is no Option to choose the function „Screenshot()“. So only the function Screenshot() is Not found. I dont know where the issue is but I Hope that I can find the Solution here. Thanks. Visual Studio Code Python A: One way is to change the language server to Jedi by adding the following configuration in settings.json. "python.languageServer": "Jedi",
Cant find Funktion Screenshot() from pyautogui is Not find in Visual Studio
I installed the package pyautogui with pip install pyautogui. All functions of this Package worked fine, But when I type „pyautogui.“ there is no Option to choose the function „Screenshot()“. So only the function Screenshot() is Not found. I dont know where the issue is but I Hope that I can find the Solution here. Thanks. Visual Studio Code Python
[ "One way is to change the language server to Jedi by adding the following configuration in settings.json.\n \"python.languageServer\": \"Jedi\",\n\n\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074474688_python_visual_studio_code.txt
Q: Pandas Dataframe - Replacing None-like Values with None in All Columns I need to clean up a dataframe whose columns come from different sources and have different types. This means that I can have, for example, string columns that contain "nan", "none", "NULL", (as a string instead of a None value). My goal is to find all empty values and replace them with None. This works fine: for column in df.columns: for idx, row in df.iterrows(): if (str(row[column]).lower() == "none") or if (str(row[column]).lower() == "nan") or (str(row[column]).lower() == "null"): df.at[row.name, column] = None But it is obviously not the best or fastest way to do it. How can I take advantage of Pandas operations or list comprehensions to do this substitution? Thanks! A: This seems to be a somewhat controversial topic (see e.g. this thread) but it's often said that list comprehensions are more computationally efficient than for loops, especially when iterating over pandas dataframes. I also prefer using list comprehensions stylistically as it leads to fewer levels of indentation from nested loops/if statements. Here's what it looks like for your use case: for column in df.columns: vals_list = df[column].to_list() replaced = [None if str(x).lower() in ['nan', 'none', 'null'] else x for x in vals_list] df[column] = replaced A: Simple approach, use isin and mask: df = pd.DataFrame([[1,2,'nan'], ['none',3,'NULL']]) df_clean = df.mask(df.isin(["nan", "none", "NULL"])) Or, if you want to update in place: df[df.isin(["nan", "none", "NULL"])] = float('nan') Output: 0 1 2 0 1 2 NaN 1 NaN 3 NaN A: A quick, and easy optimization: for column in df.columns: for idx, row in df.iterrows(): col = str(row[column]).lower() if (col == "none") or if (col == "nan") or (col == "null"): df.at[row.name, column] = None No need to convert row[column] to a str and then iterate over each character 3 times. Shorter code: its_none = ['none', 'nan', 'null'] for column in df.columns: for idx, row in df.iterrows(): if str(row[column]).lower() in its_none: df.at[row.name, column] = None Even shorter (I imagine you're expecting a number) and more optimized: for column in df.columns: for idx, row in df.iterrows(): if str(row[column]).lower().startswith('n'): df.at[row.name, column] = None A: If you want to use numpy you could do this as well (if the values in the fields are truly a string) import pandas as pd import numpy as np df = pd.DataFrame({ 'name' : ['one', 'two', 'one', 'two'], 'A' : ['null', 'none', 'empty', 'Keep'] }) df['A'] = np.where(df['A'].isin(['null', 'none', 'empty']), '', df['A']) df
Pandas Dataframe - Replacing None-like Values with None in All Columns
I need to clean up a dataframe whose columns come from different sources and have different types. This means that I can have, for example, string columns that contain "nan", "none", "NULL", (as a string instead of a None value). My goal is to find all empty values and replace them with None. This works fine: for column in df.columns: for idx, row in df.iterrows(): if (str(row[column]).lower() == "none") or if (str(row[column]).lower() == "nan") or (str(row[column]).lower() == "null"): df.at[row.name, column] = None But it is obviously not the best or fastest way to do it. How can I take advantage of Pandas operations or list comprehensions to do this substitution? Thanks!
[ "This seems to be a somewhat controversial topic (see e.g. this thread) but it's often said that list comprehensions are more computationally efficient than for loops, especially when iterating over pandas dataframes.\nI also prefer using list comprehensions stylistically as it leads to fewer levels of indentation from nested loops/if statements.\nHere's what it looks like for your use case:\nfor column in df.columns:\n vals_list = df[column].to_list()\n replaced = [None if str(x).lower() in ['nan', 'none', 'null'] else x for x in vals_list]\n df[column] = replaced\n\n", "Simple approach, use isin and mask:\ndf = pd.DataFrame([[1,2,'nan'],\n ['none',3,'NULL']])\n\ndf_clean = df.mask(df.isin([\"nan\", \"none\", \"NULL\"]))\n\nOr, if you want to update in place:\ndf[df.isin([\"nan\", \"none\", \"NULL\"])] = float('nan')\n\nOutput:\n 0 1 2\n0 1 2 NaN\n1 NaN 3 NaN\n\n", "A quick, and easy optimization:\nfor column in df.columns:\n for idx, row in df.iterrows():\n col = str(row[column]).lower()\n if (col == \"none\") or if (col == \"nan\") or (col == \"null\"):\n df.at[row.name, column] = None\n\nNo need to convert row[column] to a str and then iterate over each character 3 times.\nShorter code:\nits_none = ['none', 'nan', 'null']\nfor column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower() in its_none:\n df.at[row.name, column] = None\n\nEven shorter (I imagine you're expecting a number) and more optimized:\nfor column in df.columns:\n for idx, row in df.iterrows():\n if str(row[column]).lower().startswith('n'):\n df.at[row.name, column] = None\n\n", "If you want to use numpy you could do this as well (if the values in the fields are truly a string)\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\n 'name' : ['one', 'two', 'one', 'two'],\n 'A' : ['null', 'none', 'empty', 'Keep']\n})\n\ndf['A'] = np.where(df['A'].isin(['null', 'none', 'empty']), '', df['A'])\ndf\n\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074485204_pandas_python.txt
Q: How to create a new instance from a class object in Python I need to dynamically create an instance of a class in Python. Basically I am using the load_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object. A: I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it. class k: pass a = k() k2 = a.__class__ a2 = k2() At this point, a and a2 are both instances of the same class (class k). A: Just call the "type" built in using three parameters, like this: ClassName = type("ClassName", (Base1, Base2,...), classdictionary) update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does. To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class: instance = ClassObject() The mechanism for instantiation is thus: Python does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable: Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root. So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations) class type: ... def __call__(cls, *args, **kw): constructor = getattr(cls, "__new__") instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw) instance.__init__(cls, *args, **kw) return instance (I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally) A: This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object... The code below defines __init__() and then associates it with the class. >>> child_name = "Child" >>> child_parents = (Parent,) >>> child body = """ def __init__(self, arg1): # Initialization for the Child class self.foo = do_something(arg1) """ >>> child_dict = {} >>> exec(child_body, globals(), child_dict) >>> childobj = type(child_name, child_parents, child_dict) >>> childobj.__name__ 'Child' >>> childobj.__bases__ (<type 'object'>,) >>> # Instantiating the new Child object... >>> childinst = childobj() >>> childinst <__main__.Child object at 0x1c91710> >>> A: If you have a module with a class you want to import, you can do it like this. module = __import__(filename) instance = module.MyClass() If you do not know what the class is named, you can iterate through the classes available from a module. import inspect module = __import__(filename) for c in module.__dict__.values(): if inspect.isclass(c): # You may need do some additional checking to ensure # it's the class you want instance = c() A: If you have some class object, you can instantiate it by just calling it (with parenthesis). class MyClass: pass some_class = MyClass some_instance = some_class() # -> instance of MyClass A: I think the neat way would be using type. Here is an example: >>> class Foo: ... def __init__(self, s): ... self.s = s ... >>> a = Foo("hello") >>> a.s 'hello' >>> b = type(a)("world") >>> b.s 'world' >>> assert isinstance(a, Foo) >>> assert isinstance(b, Foo) b is an instance which has the same type as a.
How to create a new instance from a class object in Python
I need to dynamically create an instance of a class in Python. Basically I am using the load_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object.
[ "I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.\nclass k:\n pass\n\na = k()\nk2 = a.__class__\na2 = k2()\n\nAt this point, a and a2 are both instances of the same class (class k).\n", "Just call the \"type\" built in using three parameters, like this:\nClassName = type(\"ClassName\", (Base1, Base2,...), classdictionary)\n\nupdate \nas stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.\nTo create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:\ninstance = ClassObject()\n\nThe mechanism for instantiation is thus:\nPython does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:\nIts class' __call__ method is invoked (in the case of a class, its class is the \"metaclass\" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.\nSo calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)\nclass type:\n ...\n def __call__(cls, *args, **kw):\n constructor = getattr(cls, \"__new__\")\n instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)\n instance.__init__(cls, *args, **kw)\n return instance\n\n(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen \"in real life\" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally) \n", "This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...\nThe code below defines __init__() and then associates it with the class.\n>>> child_name = \"Child\"\n>>> child_parents = (Parent,)\n>>> child body = \"\"\"\ndef __init__(self, arg1):\n # Initialization for the Child class\n self.foo = do_something(arg1)\n\"\"\"\n>>> child_dict = {}\n>>> exec(child_body, globals(), child_dict)\n>>> childobj = type(child_name, child_parents, child_dict)\n>>> childobj.__name__\n'Child'\n>>> childobj.__bases__\n(<type 'object'>,)\n>>> # Instantiating the new Child object...\n>>> childinst = childobj()\n>>> childinst\n<__main__.Child object at 0x1c91710>\n>>>\n\n", "If you have a module with a class you want to import, you can do it like this.\nmodule = __import__(filename)\ninstance = module.MyClass()\n\nIf you do not know what the class is named, you can iterate through the classes available from a module.\nimport inspect\nmodule = __import__(filename)\nfor c in module.__dict__.values():\n if inspect.isclass(c):\n # You may need do some additional checking to ensure \n # it's the class you want\n instance = c()\n\n", "If you have some class object, you can instantiate it by just calling it (with parenthesis).\nclass MyClass: pass \nsome_class = MyClass \nsome_instance = some_class() # -> instance of MyClass\n\n", "I think the neat way would be using type. Here is an example:\n>>> class Foo:\n... def __init__(self, s):\n... self.s = s\n... \n>>> a = Foo(\"hello\")\n>>> a.s\n'hello'\n>>> b = type(a)(\"world\")\n>>> b.s\n'world'\n>>> assert isinstance(a, Foo)\n>>> assert isinstance(b, Foo)\n\nb is an instance which has the same type as a.\n" ]
[ 154, 25, 3, 2, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005924879_oop_python.txt
Q: High/low game in Pycharm import random name = input("Enter your name:") print("Hello and welcome to the game", name + "!") lower_num = int(input("Enter the Lower bound:")) print() higher_num = int(input("Enter the Higher bound:")) print() user_num = random.randint(0, 10) guess_num = int(input()) while True: if user_num == guess_num: print('\n"You guessed correctly!"\n') break elif user_num > guess_num: print('\n"Wrong, is too low."\n') elif user_num < guess_num: print('\n"Number is too high."\n') This is what I have so far but is not working for me in Python. A: You have to write the input inside the loop. If the person don't guess right num then the loop continue. For this, you need to write 'continue' under the elif. Then he can guess again. while True: guess_num = int(input("Guess a number now:")) if user_num == guess_num: print('\n"You guessed correctly!"\n') break elif user_num > guess_num: print('\n"Wrong, is too low."\n') continue elif user_num < guess_num: print('\n"Number is too high."\n') continue And what is the lower bound and higher bound for?
High/low game in Pycharm
import random name = input("Enter your name:") print("Hello and welcome to the game", name + "!") lower_num = int(input("Enter the Lower bound:")) print() higher_num = int(input("Enter the Higher bound:")) print() user_num = random.randint(0, 10) guess_num = int(input()) while True: if user_num == guess_num: print('\n"You guessed correctly!"\n') break elif user_num > guess_num: print('\n"Wrong, is too low."\n') elif user_num < guess_num: print('\n"Number is too high."\n') This is what I have so far but is not working for me in Python.
[ "You have to write the input inside the loop. If the person don't guess right num then the loop continue. For this, you need to write 'continue' under the elif. Then he can guess again.\nwhile True:\n guess_num = int(input(\"Guess a number now:\"))\n if user_num == guess_num:\n print('\\n\"You guessed correctly!\"\\n')\n break\n elif user_num > guess_num:\n print('\\n\"Wrong, is too low.\"\\n')\n continue\n elif user_num < guess_num:\n print('\\n\"Number is too high.\"\\n')\n continue\n\nAnd what is the lower bound and higher bound for?\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074483837_python.txt
Q: How to forward a graphic message to a bot and return the text Some questions about using python-telegram-bot I'm using python-telegram-bot to create a telegram bot. I want to forward a graphic message (similar to the one below) to the robot, and the robot removes the image and returns the text. I didn't find an example in the official documentation. I hope someone can help me. I read about Combining filters,like handler = MessageHandler(Filters.forwarded & Filters.photo, callback) but I don't know how to use them to separate images and text A: I sloved it just use the code below def callback(update: Update, context: CallbackContext): print(update.message.caption) then python will print out the text don't forget to import CallbackContext and Updater
How to forward a graphic message to a bot and return the text
Some questions about using python-telegram-bot I'm using python-telegram-bot to create a telegram bot. I want to forward a graphic message (similar to the one below) to the robot, and the robot removes the image and returns the text. I didn't find an example in the official documentation. I hope someone can help me. I read about Combining filters,like handler = MessageHandler(Filters.forwarded & Filters.photo, callback) but I don't know how to use them to separate images and text
[ "I sloved it\njust use the code below\ndef callback(update: Update, context: CallbackContext):\n print(update.message.caption)\n\nthen python will print out the text\ndon't forget to import CallbackContext and Updater\n" ]
[ 0 ]
[]
[]
[ "python", "python_telegram_bot", "telegram" ]
stackoverflow_0074484764_python_python_telegram_bot_telegram.txt
Q: Sqlalchemy dynamic filtering of multiple options Using SQLAlchemy, I want to query the following SQL-Statement for table 'Tab1' with a column 'Col1': Select * from Tab1 where Tab1.Col1 == value1 or Tab1.Col1 == value2 'value1' and 'value2' come from a list which is potentially longer and dynamic. Following the answer in here how to dynamic "_or" in filter query sqlalchemy I use the following code: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine(...) Session = sessionmaker(engine) with Session() as session: data = ['value1', 'value2'] data_comparisons = [Tab1.Col1 == field for field in data] q_cat = session.query(Tab1).filter_by(*data_comparisons).all() I get however the error message: TypeError: filter_by() takes 1 positional argument but 3 were given Does anybody have an idea what is wrong and how this could be implemented? A: You can pass the comparisons to the or_ function and it will create an expression that will evaluate to COMPARISON0 OR COMPARISON1 OR ... from sqlalchemy.sql import or_ q_cat = session.query(Tab1).filter(or_(*data_comparisons)).all() Although if you are just using equality then I think in_ might be better: q_cat = session.query(Tab1).filter(Tab1.Col1.in_(data)).all()
Sqlalchemy dynamic filtering of multiple options
Using SQLAlchemy, I want to query the following SQL-Statement for table 'Tab1' with a column 'Col1': Select * from Tab1 where Tab1.Col1 == value1 or Tab1.Col1 == value2 'value1' and 'value2' come from a list which is potentially longer and dynamic. Following the answer in here how to dynamic "_or" in filter query sqlalchemy I use the following code: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine(...) Session = sessionmaker(engine) with Session() as session: data = ['value1', 'value2'] data_comparisons = [Tab1.Col1 == field for field in data] q_cat = session.query(Tab1).filter_by(*data_comparisons).all() I get however the error message: TypeError: filter_by() takes 1 positional argument but 3 were given Does anybody have an idea what is wrong and how this could be implemented?
[ "You can pass the comparisons to the or_ function and it will create an expression that will evaluate to COMPARISON0 OR COMPARISON1 OR ...\nfrom sqlalchemy.sql import or_\n\nq_cat = session.query(Tab1).filter(or_(*data_comparisons)).all()\n\n\nAlthough if you are just using equality then I think in_ might be better:\nq_cat = session.query(Tab1).filter(Tab1.Col1.in_(data)).all()\n\n" ]
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074479466_python_sqlalchemy.txt
Q: Widget-based web framework in Python (similar to vaadin, GWT or zkoss) I am basically from Java, but I need to use Python for a new project. I prefer widget based web framework like zkoss, vaadin, GWT etc. Does python has widget based framework? A: You can use Muntjac, it is a semi-automatic translation of vaadin, and depending on your needs about python you just can use jython inside vaadin, but you will lost the 3th party c extesions to python... A: Pyjs is a GWT port in python, and should do what you are looking for. A: Note that Vaadin can be used with Python. A: As of 2022, Justpy seems to be the only one which is still actively maintained. A: lona is an option as well as all the candidates in the purepython-list If you are just interested in the widget approach the: Flask Bootstrap4 Widgets justpy widgets might be interesting for your. Please note that i am maintainer for justpy
Widget-based web framework in Python (similar to vaadin, GWT or zkoss)
I am basically from Java, but I need to use Python for a new project. I prefer widget based web framework like zkoss, vaadin, GWT etc. Does python has widget based framework?
[ "You can use Muntjac, it is a semi-automatic translation of vaadin, and depending on your needs about python you just can use jython inside vaadin, but you will lost the 3th party c extesions to python...\n", "Pyjs is a GWT port in python, and should do what you are looking for.\n", "Note that Vaadin can be used with Python.\n", "As of 2022, Justpy seems to be the only one which is still actively maintained.\n", "lona is an option as well as all the candidates in the purepython-list\nIf you are just interested in the widget approach the:\n\nFlask Bootstrap4 Widgets\njustpy widgets\n\nmight be interesting for your. Please note that i am maintainer for justpy\n" ]
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "justpy", "python" ]
stackoverflow_0012963531_justpy_python.txt
Q: Selenium and beautiful soup unable to find video tag tag on webpage I need a web scraping experts help. Im trying to get the src from the video tag of this website. When I try to use selenium or beautifulsoup4 to catch it, its as if doesnt exist. find_elements returns an empty list. This "//*[@id="player"]/div[2]/div[3]/video" is the XPATH for that element from inspect elements in safari. I can see it while inspecting the webpage but I cannot scrape it. Ive also tried using the find_element("src") method to no success. It throws an exception saying no such element found. This is my code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(options=options) # Navigate to Url driver.get("https://anime47.com/xem-phim-chainsaw-man-ep-01/187898.html") # Get all the elements available with tag name 'p' elements = driver.find_element(By.TAG_NAME, "iframe") for e in elements: print(e.text) A: The element can be found using this code: video = driver.find_element(By.XPATH, '//*[@id="player"]/div[2]/div[3]/video') But this element doesn't have the src attribute, so you will not be able to get it from the element. And looks like there is no possibility to get the video from this page.
Selenium and beautiful soup unable to find video tag tag on webpage
I need a web scraping experts help. Im trying to get the src from the video tag of this website. When I try to use selenium or beautifulsoup4 to catch it, its as if doesnt exist. find_elements returns an empty list. This "//*[@id="player"]/div[2]/div[3]/video" is the XPATH for that element from inspect elements in safari. I can see it while inspecting the webpage but I cannot scrape it. Ive also tried using the find_element("src") method to no success. It throws an exception saying no such element found. This is my code: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(options=options) # Navigate to Url driver.get("https://anime47.com/xem-phim-chainsaw-man-ep-01/187898.html") # Get all the elements available with tag name 'p' elements = driver.find_element(By.TAG_NAME, "iframe") for e in elements: print(e.text)
[ "The element can be found using this code:\nvideo = driver.find_element(By.XPATH, '//*[@id=\"player\"]/div[2]/div[3]/video')\n\nBut this element doesn't have the src attribute, so you will not be able to get it from the element. And looks like there is no possibility to get the video from this page.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "selenium", "web_scraping" ]
stackoverflow_0074484584_beautifulsoup_html_python_selenium_web_scraping.txt
Q: Azure text to speech and play it in virtual microphone using python My use case is to convert text to speech using Azure and then play it into a virtual microphone. option 1 - with an intermediate .wav file I tried both steps manually on a Jupiter notebook. The problem is, the output .wav file of Azure cannot be played directly on the python "error: No file 'file.wav' found in working directory". When I restart the python kernal, audio can be played. text-to-speech audio_config = speechsdk.audio.AudioOutputConfig(filename="file.wav") ... speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) speech_synthesis_result = speech_synthesizer.speak_text_async(text).get() audio play mixer.init(devicename = 'Line 1 (Virtual Audio Cable)') mixer.music.load("file.wav") mixer.music.play() option 2 - direct stream to audio device I tried to configure the audio output device of azure SDK. this method worked for output devices. but when I add an ID of the virtual microphone, it won't play any sound. audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=False,device_name="{0.0.0.00000000}.{9D30BDBF-1418-4AFC-A709-CD4C431833E2}") Also it will be much better if there is any other method that can direct the audio to a virtual microphone instead of the speaker. A: Create a speech service and get the key and location of the service. Then set the environment with that key. Open command prompt and use the below code block. setx SPEECH_KEY yourkey Use import azure.cognitiveservices.speech as speechsdk After conversion, use the below code block to get the virtual device. audio_config = AudioConfig(device_name="<device id>"); Get the device speaker information and set it in this location. A: I found a solution by changing the output a stream, saving to a file and then play it through pygame as follows, speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=None) speech_synthesis_result = speech_synthesizer.speak_text_async(text).get() stream = speechsdk.AudioDataStream(speech_synthesis_result) stream.save_to_wav_file("file.wav") mixer.init(devicename = 'Line 1 (Virtual Audio Cable)') mixer.music.load("file.wav") mixer.music.play() Also much appreciated if there is any other method that doesn't need any intermediate audio file.
Azure text to speech and play it in virtual microphone using python
My use case is to convert text to speech using Azure and then play it into a virtual microphone. option 1 - with an intermediate .wav file I tried both steps manually on a Jupiter notebook. The problem is, the output .wav file of Azure cannot be played directly on the python "error: No file 'file.wav' found in working directory". When I restart the python kernal, audio can be played. text-to-speech audio_config = speechsdk.audio.AudioOutputConfig(filename="file.wav") ... speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config) speech_synthesis_result = speech_synthesizer.speak_text_async(text).get() audio play mixer.init(devicename = 'Line 1 (Virtual Audio Cable)') mixer.music.load("file.wav") mixer.music.play() option 2 - direct stream to audio device I tried to configure the audio output device of azure SDK. this method worked for output devices. but when I add an ID of the virtual microphone, it won't play any sound. audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=False,device_name="{0.0.0.00000000}.{9D30BDBF-1418-4AFC-A709-CD4C431833E2}") Also it will be much better if there is any other method that can direct the audio to a virtual microphone instead of the speaker.
[ "Create a speech service and get the key and location of the service.\n\nThen set the environment with that key. Open command prompt and use the below code block.\nsetx SPEECH_KEY yourkey\n\nUse import azure.cognitiveservices.speech as speechsdk\nAfter conversion, use the below code block to get the virtual device.\naudio_config = AudioConfig(device_name=\"<device id>\");\n\nGet the device speaker information and set it in this location.\n", "I found a solution by changing the output a stream, saving to a file and then play it through pygame as follows,\nspeech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=None)\nspeech_synthesis_result = speech_synthesizer.speak_text_async(text).get()\nstream = speechsdk.AudioDataStream(speech_synthesis_result)\nstream.save_to_wav_file(\"file.wav\")\n\nmixer.init(devicename = 'Line 1 (Virtual Audio Cable)')\nmixer.music.load(\"file.wav\")\nmixer.music.play()\n\nAlso much appreciated if there is any other method that doesn't need any intermediate audio file.\n" ]
[ 0, 0 ]
[]
[]
[ "azure", "azure_cognitive_services", "python", "text_to_speech" ]
stackoverflow_0074376903_azure_azure_cognitive_services_python_text_to_speech.txt
Q: MT5 python not returning updated data MT5 is not returning data for the most recent index import MetaTrader5 as mt5 mt5.initialize() import pandas as pd instrument = mt5.copy_rates_from_pos('BTCUSD',mt5.TIMEFRAME_H1,0,20) instrument = pd.DataFrame(instrument) instrument['time'] = pd.to_datetime(instrument['time'], unit = 's') instrument = instrument.set_index(['time']) When I run this code every hour, it always returns the previous bar as the last index (instead of the most recent bar). It should return the most recent bar since the initial bar index is set to 0. Example of data not being updated: In() instrument['open'].tail(5) Out() 2022-10-29 11:00:00 20767.92 2022-10-29 12:00:00 20917.95 2022-10-29 13:00:00 20945.44 2022-10-29 14:00:00 20763.64 2022-10-29 15:00:00 20690.48 If I run the same code 10 seconds later, it returns the correct information (most recent bar as the last index). Correct (updated) data: In() instrument['open'].tail(5) Out() 2022-10-29 12:00:00 20917.95 2022-10-29 13:00:00 20945.44 2022-10-29 14:00:00 20763.64 2022-10-29 15:00:00 20690.48 2022-10-29 16:00:00 20756.35 So from what I can tell the terminal has not updated the information when - mt5.copy_rates_from_pos - is executed. How can I force the terminal to download and update the data before? Thanks for any help A: you can actually update the close price every second if you want to. You have to run it with datetime otherwise you wont return the updated date and time from mt5. and run your function to pull the data from inside loop. from datetime import datetime import time import MetaTrader5 as mt import pandas as pd q = 0 while q < 1: dt = datetime.now() mt = dt.strftime( '%H:%M:%S' ) if dt.second > dt.second - 1: pull your data here print output time.sleep( 1 ) remember only the close price will update every second, unless new highs or lows are made within the bar interval, then they will update as well. Hope that helps
MT5 python not returning updated data
MT5 is not returning data for the most recent index import MetaTrader5 as mt5 mt5.initialize() import pandas as pd instrument = mt5.copy_rates_from_pos('BTCUSD',mt5.TIMEFRAME_H1,0,20) instrument = pd.DataFrame(instrument) instrument['time'] = pd.to_datetime(instrument['time'], unit = 's') instrument = instrument.set_index(['time']) When I run this code every hour, it always returns the previous bar as the last index (instead of the most recent bar). It should return the most recent bar since the initial bar index is set to 0. Example of data not being updated: In() instrument['open'].tail(5) Out() 2022-10-29 11:00:00 20767.92 2022-10-29 12:00:00 20917.95 2022-10-29 13:00:00 20945.44 2022-10-29 14:00:00 20763.64 2022-10-29 15:00:00 20690.48 If I run the same code 10 seconds later, it returns the correct information (most recent bar as the last index). Correct (updated) data: In() instrument['open'].tail(5) Out() 2022-10-29 12:00:00 20917.95 2022-10-29 13:00:00 20945.44 2022-10-29 14:00:00 20763.64 2022-10-29 15:00:00 20690.48 2022-10-29 16:00:00 20756.35 So from what I can tell the terminal has not updated the information when - mt5.copy_rates_from_pos - is executed. How can I force the terminal to download and update the data before? Thanks for any help
[ "you can actually update the close price every second if you want to. You have to run it with datetime otherwise you wont return the updated date and time from mt5. and run your function to pull the data from inside loop.\nfrom datetime import datetime\nimport time\nimport MetaTrader5 as mt\nimport pandas as pd\n\nq = 0\nwhile q < 1:\n dt = datetime.now()\n mt = dt.strftime( '%H:%M:%S' )\n if dt.second > dt.second - 1:\n pull your data here\n print output\n time.sleep( 1 )\n\nremember only the close price will update every second, unless new highs or lows are made within the bar interval, then they will update as well. Hope that helps\n" ]
[ 0 ]
[]
[]
[ "metatrader5", "python" ]
stackoverflow_0074245502_metatrader5_python.txt
Q: Efficent way to find index of member in string enum I have a constant Enum class that looks something like this: class Animals(Enum): Dog= 'dog' Cat= 'cat' Chicken = 'chicken' Horse = 'horse' I need to find a simple and efficient way to find the index of one of the members of the Enum. so I came up with the following oneliner: list(Animals).index(Animals.Chicken) output: 2 The problem is, parsing to a list and searching it again is not efficient enough, and I can't change the constant. It feels like there should be a simple solution that I'm missing. A: You have a few options: Use the index values as the values of your Enum, or perhaps IntEnum class Animals(Enum): Dog= 0 Cat= 1 Chicken = 2 Horse = 3 Animals.Chicken.value #returns 2 If you want to keep the textual description too, then subclass Enum, and add the needed attributes (see the Planet example in the docs): class Animals(Enum): Dog = ('dog',0) Cat = ('cat',1) Chicken = ('chicken',2) Horse = ('horse',3) def __init__(self, textval, idx): self.textval = textval self.idx = idx Animals.Chicken.value #returns ('chicken', 2) Animals.Chicken.textval #returns 'chicken' Animals.Chicken.idx #returns 2 A: Since Enum member names do not start with numbers, you can simply make your Enum subclass' _member_map_ attribute, a dict that stores the member name-to-value mapping, to also store the index number-to-value mapping. This can be done by subclassing Enum's metaclass, EnumMeta, and adding indices as new keys to all corresponding values for the _member_map_ attribute, in the class object returned by the original __new__ method: from enum import Enum, EnumMeta class IndexableEnumType(EnumMeta): def __new__(metacls, cls, bases, classdict, **kwargs): enum_class = super().__new__(metacls, cls, bases, classdict, **kwargs) for i, v in enumerate(list(enum_class._member_map_.values())): enum_class._member_map_[i] = v return enum_class So that: class Animals(Enum, metaclass=IndexableEnumType): Dog= 'dog' Cat= 'cat' Chicken = 'chicken' Horse = 'horse' print(Animals[2]) print(Animals['Chicken']) print(Animals.Chicken) would output: Animals.Chicken Animals.Chicken Animals.Chicken Since dict lookups costs O(1) in average time complexity, this is much more efficient than your current solution of calling list.index, which costs O(n) in time complexity. Demo: https://replit.com/@blhsing/AdventurousVapidCollaborativesoftware
Efficent way to find index of member in string enum
I have a constant Enum class that looks something like this: class Animals(Enum): Dog= 'dog' Cat= 'cat' Chicken = 'chicken' Horse = 'horse' I need to find a simple and efficient way to find the index of one of the members of the Enum. so I came up with the following oneliner: list(Animals).index(Animals.Chicken) output: 2 The problem is, parsing to a list and searching it again is not efficient enough, and I can't change the constant. It feels like there should be a simple solution that I'm missing.
[ "You have a few options:\n\nUse the index values as the values of your Enum, or perhaps IntEnum\n\nclass Animals(Enum):\n Dog= 0\n Cat= 1\n Chicken = 2\n Horse = 3\nAnimals.Chicken.value #returns 2\n\n\nIf you want to keep the textual description too, then subclass Enum, and add the needed attributes (see the Planet example in the docs):\n\nclass Animals(Enum):\n Dog = ('dog',0)\n Cat = ('cat',1)\n Chicken = ('chicken',2)\n Horse = ('horse',3)\n def __init__(self, textval, idx):\n self.textval = textval\n self.idx = idx\nAnimals.Chicken.value #returns ('chicken', 2)\nAnimals.Chicken.textval #returns 'chicken'\nAnimals.Chicken.idx #returns 2\n\n", "Since Enum member names do not start with numbers, you can simply make your Enum subclass' _member_map_ attribute, a dict that stores the member name-to-value mapping, to also store the index number-to-value mapping.\nThis can be done by subclassing Enum's metaclass, EnumMeta, and adding indices as new keys to all corresponding values for the _member_map_ attribute, in the class object returned by the original __new__ method:\nfrom enum import Enum, EnumMeta\n\nclass IndexableEnumType(EnumMeta):\n def __new__(metacls, cls, bases, classdict, **kwargs):\n enum_class = super().__new__(metacls, cls, bases, classdict, **kwargs)\n for i, v in enumerate(list(enum_class._member_map_.values())):\n enum_class._member_map_[i] = v\n return enum_class\n\nSo that:\nclass Animals(Enum, metaclass=IndexableEnumType):\n Dog= 'dog'\n Cat= 'cat'\n Chicken = 'chicken'\n Horse = 'horse'\n\nprint(Animals[2])\nprint(Animals['Chicken'])\nprint(Animals.Chicken)\n\nwould output:\nAnimals.Chicken\nAnimals.Chicken\nAnimals.Chicken\n\nSince dict lookups costs O(1) in average time complexity, this is much more efficient than your current solution of calling list.index, which costs O(n) in time complexity.\nDemo: https://replit.com/@blhsing/AdventurousVapidCollaborativesoftware\n" ]
[ 0, 0 ]
[]
[]
[ "enums", "performance", "python" ]
stackoverflow_0074472714_enums_performance_python.txt
Q: How to convert HTML tag into string using python I have my html content as: html = <div>new notes</div><div><ol><li>kssd</li></ol><ul><li>cds</li><li>dsdsk</li></ul><font color=\"#66717b\">ndsmnd</font></div> When I convert the above expression to string, it throws error html_str = str(html) I can see the " are already escaped here. do I need to replace /" with //" and then convert to string? A: I think you need to use get_text() from bs4 import BeautifulSoup htmlvar = BeautifulSoup(html) print(htmlvar.get_text()) A: you can try this: from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') print(soup.prettify()) tag = soup.html string = str(tag) print(string)
How to convert HTML tag into string using python
I have my html content as: html = <div>new notes</div><div><ol><li>kssd</li></ol><ul><li>cds</li><li>dsdsk</li></ul><font color=\"#66717b\">ndsmnd</font></div> When I convert the above expression to string, it throws error html_str = str(html) I can see the " are already escaped here. do I need to replace /" with //" and then convert to string?
[ "I think you need to use get_text()\nfrom bs4 import BeautifulSoup\nhtmlvar = BeautifulSoup(html)\nprint(htmlvar.get_text())\n\n", "you can try this:\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(html, 'html.parser')\n\nprint(soup.prettify())\n\ntag = soup.html\n\nstring = str(tag)\n\nprint(string)\n\n" ]
[ 0, 0 ]
[]
[]
[ "html", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074485126_html_python_python_2.7_python_3.x.txt
Q: Folium and ColorMap -- is not JSON serializable The problem in question is: Object of type LinearColormap is not JSON serializable maps['Zona de tarifa'] = maps['Zona de tarifa'].astype('int') linear = cm.LinearColormap(["green", "yellow", "red"], vmin=maps['Zona de tarifa'].min(), vmax=maps['Zona de tarifa'].max()) map = folium.Map(location=[maps.new_latitud.mean(), maps.new_longitud.mean()], zoom_start=14, control_scale=True) for index, location_info in maps.iterrows(): folium.Marker([location_info["new_latitud"], location_info["new_longitud"]],icon=folium.Icon(color=linear),popup=location_info["Cliente"]+' '+location_info["Conductor"]).add_to(map) map I want to add color to my markers but that markers related to the variable or atributte "zona de tarifa" but i can't make it A: Since the colors available for markers are limited, you can color-code them by specifying colors from the color list. We have applied your code using sample data. import folium import pandas as pd import random maps = pd.DataFrame({'new_latitud': [random.uniform(36, 43.48) for _ in range(10)], 'new_longitud': [random.uniform(-9.18, 3.19) for _ in range(10)], 'Zona de tarifa': [random.randint(0,10) for _ in range(10)]}) # List of colors available for icons colors= ['lightgray', 'darkred', 'lightgreen', 'green', 'pink', 'darkgreen', 'lightblue', 'darkpurple', 'black', 'lightred', 'gray', 'orange', 'cadetblue', 'blue', 'purple', 'beige', 'white', 'darkblue', 'red'] m = folium.Map(location=[maps.new_latitud.mean(), maps.new_longitud.mean()], zoom_start=6, control_scale=True) for index, location_info in maps.iterrows(): folium.Marker([location_info["new_latitud"], location_info["new_longitud"]], icon=folium.Icon(color=colors[int(location_info['Zona de tarifa'])]), #popup=location_info["Cliente"]+' '+location_info["Conductor"] ).add_to(m) m
Folium and ColorMap -- is not JSON serializable
The problem in question is: Object of type LinearColormap is not JSON serializable maps['Zona de tarifa'] = maps['Zona de tarifa'].astype('int') linear = cm.LinearColormap(["green", "yellow", "red"], vmin=maps['Zona de tarifa'].min(), vmax=maps['Zona de tarifa'].max()) map = folium.Map(location=[maps.new_latitud.mean(), maps.new_longitud.mean()], zoom_start=14, control_scale=True) for index, location_info in maps.iterrows(): folium.Marker([location_info["new_latitud"], location_info["new_longitud"]],icon=folium.Icon(color=linear),popup=location_info["Cliente"]+' '+location_info["Conductor"]).add_to(map) map I want to add color to my markers but that markers related to the variable or atributte "zona de tarifa" but i can't make it
[ "Since the colors available for markers are limited, you can color-code them by specifying colors from the color list. We have applied your code using sample data.\nimport folium\nimport pandas as pd\nimport random\n\nmaps = pd.DataFrame({'new_latitud': [random.uniform(36, 43.48) for _ in range(10)],\n 'new_longitud': [random.uniform(-9.18, 3.19) for _ in range(10)],\n 'Zona de tarifa': [random.randint(0,10) for _ in range(10)]})\n\n# List of colors available for icons\ncolors= ['lightgray', 'darkred', 'lightgreen', 'green', 'pink', 'darkgreen', 'lightblue', 'darkpurple', 'black', \n 'lightred', 'gray', 'orange', 'cadetblue', 'blue', 'purple', 'beige', 'white', 'darkblue', 'red']\n\nm = folium.Map(location=[maps.new_latitud.mean(), maps.new_longitud.mean()], zoom_start=6, control_scale=True)\n\nfor index, location_info in maps.iterrows():\n folium.Marker([location_info[\"new_latitud\"], location_info[\"new_longitud\"]],\n icon=folium.Icon(color=colors[int(location_info['Zona de tarifa'])]),\n #popup=location_info[\"Cliente\"]+' '+location_info[\"Conductor\"]\n ).add_to(m)\nm\n\n\n" ]
[ 1 ]
[]
[]
[ "colormap", "folium", "python" ]
stackoverflow_0074480861_colormap_folium_python.txt
Q: Can not retrieve likes and dislikes in youtube with the pytube module I using pytube library However, I didn't find functions for getting likes and dislikes in YouTube video There are functions for fetching title, description, etc. but no functions for fetching channel name or number of likes i tried this code from pytube import YouTube link = input('Enter your link:') video = YouTube(link) print(f"The video title is:\n{video.title} \n------------------------------") print(f"The video rating is:\n{video.rating} \n------------------------------") print(f"The video Views is:\n{video.viewcount} \n------------------------------") print(f"The video author is:\n{video.author} \n------------------------------") print(f"The video length is:\n{video.length} \n------------------------------") print(f"The video duration is:\n{video.duration} \n------------------------------") print(f"The video likes is:\n{video.likes} \n------------------------------") print(f"The video dislikes is:\n{video.dislikes} \n------------------------------") python baba.py Enter your link:https://www.youtube.com/watch?v=1_gXTjBZOms The video title is: كيفيى إضافة عناصر إلى قائمة جديد new في جميع إصدارات windows ------------------------------ The video rating is: 5.0 ------------------------------ Traceback (most recent call last): File "C:\Users\MesterPerfect\Desktop\baba.py", line 6, in <module> print(f"The video Views is:\n{video.viewcount} \n--------------------------- ---") AttributeError: 'YouTube' object has no attribute 'viewcount' Are there solutions? A: For finding views you can use views method the method you are looking for is available in another module named pafy from pytube import YouTube link ="https://www.youtube.com/watch?v=1_gXTjBZOms" video = YouTube(link) print(f"The video title is:\n{video.title} \n------------------------------") print(f"The video rating is:\n{video.rating} \n------------------------------") print(f"The video Views is:\n{video.views} \n------------------------------") print(f"The video author is:\n{video.author} \n------------------------------") print(f"The video length is:\n{video.length} \n------------------------------") Also you can install pafy and try out from docs With pafy import pafy url = "https://www.youtube.com/watch?v=1_gXTjBZOms" video = pafy.new(url) print(f"The video title is:\n{video.title} \n------------------------------") print(f"The video rating is:\n{video.rating} \n------------------------------") print(f"The video Views is:\n{video.viewcount} \n------------------------------") print(f"The video author is:\n{video.author} \n------------------------------") print(f"The video length is:\n{video.length} \n------------------------------") print(f"The video duration is:\n{video.duration} \n------------------------------") print(f"The video likes is:\n{video.likes} \n------------------------------") print(f"The video dislikes is:\n{video.dislikes} \n------------------------------") with pyfy and pytube just create separate instance from it used according what methods are include from pytube import YouTube import pafy link ="https://www.youtube.com/watch?v=1_gXTjBZOms" video = YouTube(link) video1=pafy.new(link) # Git video info using pytube print(f"The video title is:\n{video.title} \n------------------------------") print(f"The video rating is:\n{video.rating} \n------------------------------") print(f"The video Views is:\n{video.views} \n------------------------------") print(f"The video author is:\n{video.author} \n------------------------------") # Git video info using pafy print(f"The video duration is:\n{video1.duration} \n------------------------------") print(f"The video likes is:\n{video1.likes} \n------------------------------") print(f"The video dislikes is:\n{video1.dislikes} \n------------------------------") A: Try it :) from pytube import YouTube import re like_template = r'[0-9]{1,3},?[0-9]{0,3},?[0-9]{0,3} like' yt = YouTube('https://www.youtube.com/watch?v=ysSxxIqKNN0') str_likes = re.search(like_template, str(yt.initial_data)).group(0) likes = int(str_likes.split(' ')[0].replace(',', '')) print(str_likes) # 2,486,532 like print(likes) # 2486532 A: # import libraries from pytube import YouTube import pafy link ="https://www.youtube.com/watch?v=1_gXTjBZOms" video = YouTube(link) # Git video info using pytube print(f"The video title is:\n{video.title} \n------------------------------") print(f"The video rating is:\n{video.rating} \n------------------------------") print(f"The video Views is:\n{video.views} \n------------------------------") print(f"The video author is:\n{video.author} \n------------------------------") # Git video info using pafy print(f"The video duration is:\n{video.duration} \n------------------------------") print(f"The video likes is:\n{video.likes} \n------------------------------") print(f"The video dislikes is:\n{video.dislikes} \n------------------------------")``` Output: The video title is: كيفيى إضافة عناصر إلى قائمة جديد new في جميع إصدارات windows ------------------------------ The video rating is: 5.0 ------------------------------ The video Views is: 48 ------------------------------ The video author is: زينب بهاء ------------------------------ Traceback (most recent call last): File "c:\Users\MesterPerfect\Desktop\qais.py", line 17, in <module> print(f"The video duration is:\n{video.duration} \n------------------------- -----") AttributeError: 'YouTube' object has no attribute 'duration'
Can not retrieve likes and dislikes in youtube with the pytube module
I using pytube library However, I didn't find functions for getting likes and dislikes in YouTube video There are functions for fetching title, description, etc. but no functions for fetching channel name or number of likes i tried this code from pytube import YouTube link = input('Enter your link:') video = YouTube(link) print(f"The video title is:\n{video.title} \n------------------------------") print(f"The video rating is:\n{video.rating} \n------------------------------") print(f"The video Views is:\n{video.viewcount} \n------------------------------") print(f"The video author is:\n{video.author} \n------------------------------") print(f"The video length is:\n{video.length} \n------------------------------") print(f"The video duration is:\n{video.duration} \n------------------------------") print(f"The video likes is:\n{video.likes} \n------------------------------") print(f"The video dislikes is:\n{video.dislikes} \n------------------------------") python baba.py Enter your link:https://www.youtube.com/watch?v=1_gXTjBZOms The video title is: كيفيى إضافة عناصر إلى قائمة جديد new في جميع إصدارات windows ------------------------------ The video rating is: 5.0 ------------------------------ Traceback (most recent call last): File "C:\Users\MesterPerfect\Desktop\baba.py", line 6, in <module> print(f"The video Views is:\n{video.viewcount} \n--------------------------- ---") AttributeError: 'YouTube' object has no attribute 'viewcount' Are there solutions?
[ "For finding views you can use views method the method you are looking for is available in another module named pafy\nfrom pytube import YouTube\nlink =\"https://www.youtube.com/watch?v=1_gXTjBZOms\"\nvideo = YouTube(link)\nprint(f\"The video title is:\\n{video.title} \\n------------------------------\")\nprint(f\"The video rating is:\\n{video.rating} \\n------------------------------\")\nprint(f\"The video Views is:\\n{video.views} \\n------------------------------\")\nprint(f\"The video author is:\\n{video.author} \\n------------------------------\")\nprint(f\"The video length is:\\n{video.length} \\n------------------------------\")\n\nAlso you can install pafy and try out from docs\nWith pafy\nimport pafy\nurl = \"https://www.youtube.com/watch?v=1_gXTjBZOms\"\nvideo = pafy.new(url)\nprint(f\"The video title is:\\n{video.title} \\n------------------------------\")\nprint(f\"The video rating is:\\n{video.rating} \\n------------------------------\")\nprint(f\"The video Views is:\\n{video.viewcount} \\n------------------------------\")\nprint(f\"The video author is:\\n{video.author} \\n------------------------------\")\nprint(f\"The video length is:\\n{video.length} \\n------------------------------\")\nprint(f\"The video duration is:\\n{video.duration} \\n------------------------------\")\nprint(f\"The video likes is:\\n{video.likes} \\n------------------------------\")\nprint(f\"The video dislikes is:\\n{video.dislikes} \\n------------------------------\")\n\nwith pyfy and pytube just create separate instance from it used according what methods are include\nfrom pytube import YouTube\nimport pafy\n\nlink =\"https://www.youtube.com/watch?v=1_gXTjBZOms\"\nvideo = YouTube(link)\nvideo1=pafy.new(link)\n\n# Git video info using pytube\nprint(f\"The video title is:\\n{video.title} \\n------------------------------\")\nprint(f\"The video rating is:\\n{video.rating} \\n------------------------------\")\nprint(f\"The video Views is:\\n{video.views} \\n------------------------------\")\nprint(f\"The video author is:\\n{video.author} \\n------------------------------\")\n\n# Git video info using pafy\nprint(f\"The video duration is:\\n{video1.duration} \\n------------------------------\")\nprint(f\"The video likes is:\\n{video1.likes} \\n------------------------------\")\nprint(f\"The video dislikes is:\\n{video1.dislikes} \\n------------------------------\")\n\n", "Try it :)\nfrom pytube import YouTube\nimport re\n\n\nlike_template = r'[0-9]{1,3},?[0-9]{0,3},?[0-9]{0,3} like'\nyt = YouTube('https://www.youtube.com/watch?v=ysSxxIqKNN0')\nstr_likes = re.search(like_template, str(yt.initial_data)).group(0)\nlikes = int(str_likes.split(' ')[0].replace(',', ''))\nprint(str_likes) # 2,486,532 like\nprint(likes) # 2486532\n\n", "# import libraries\nfrom pytube import YouTube\nimport pafy\n\nlink =\"https://www.youtube.com/watch?v=1_gXTjBZOms\"\nvideo = YouTube(link)\n\n# Git video info using pytube\nprint(f\"The video title is:\\n{video.title} \\n------------------------------\")\nprint(f\"The video rating is:\\n{video.rating} \\n------------------------------\")\nprint(f\"The video Views is:\\n{video.views} \\n------------------------------\")\nprint(f\"The video author is:\\n{video.author} \\n------------------------------\")\n\n# Git video info using pafy\nprint(f\"The video duration is:\\n{video.duration} \\n------------------------------\")\nprint(f\"The video likes is:\\n{video.likes} \\n------------------------------\")\nprint(f\"The video dislikes is:\\n{video.dislikes} \\n------------------------------\")```\n\nOutput:\nThe video title is:\nكيفيى إضافة عناصر إلى قائمة جديد new في جميع إصدارات windows\n------------------------------\nThe video rating is:\n5.0\n------------------------------\nThe video Views is:\n48\n------------------------------\nThe video author is:\nزينب بهاء\n------------------------------\nTraceback (most recent call last):\n File \"c:\\Users\\MesterPerfect\\Desktop\\qais.py\", line 17, in <module>\n print(f\"The video duration is:\\n{video.duration} \\n-------------------------\n-----\")\nAttributeError: 'YouTube' object has no attribute 'duration'\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python", "pytube" ]
stackoverflow_0067668286_python_pytube.txt
Q: Transpose data from column to row in excel with python I have many text file Data, and I selected my data from the text and inserted it into one Excel File, but I have one problem: Data exported in the column, Like below: David 1253.2500 2568.000 8566.236 Jack 3569.00 5269.22 4586.00 But I want to output the data in rows, like the one below: David 1253.2500 2568.000 8566.236 Jack 3569.00 5269.22 4586.00 Code: import glob import pandas as pd while True: path = input("Insert location:") file_list = glob.glob(path + "/*.txt") df_list = [] for file in file_list: df = pd.read_csv(file) df_list.append(df.take([0,-1,-4,-7])) excl_merged = pd.concat(df_list, ignore_index=False) #part two of the code writer = pd.ExcelWriter('Total.xlsx', engine='xlsxwriter') excl_merged.to_excel(writer, sheet_name='Sheet1', index=False, header=False) writer.close() print('success!!') I have tested many methods, but they did not work; for example, I tested pandas.transpose() I tried to do this in Excel, But it did not work too. A: Assuming this input: df = pd.DataFrame({'col': ['David', '1253.2500', '2568.000', '8566.236', 'Jack', '3569.00', '5269.22', '4586.00']}) You can use: s = pd.to_numeric(df['col'], errors='coerce') m = s.isna() out = (df .assign(col=df['col'].where(m).ffill(), value=s, index=m.groupby(m.cumsum()).cumcount()) .loc[~m] .pivot(index='index', columns='col', values='value') ) print(out) Output: col David Jack index 1 1253.250 3569.00 2 2568.000 5269.22 3 8566.236 4586.00
Transpose data from column to row in excel with python
I have many text file Data, and I selected my data from the text and inserted it into one Excel File, but I have one problem: Data exported in the column, Like below: David 1253.2500 2568.000 8566.236 Jack 3569.00 5269.22 4586.00 But I want to output the data in rows, like the one below: David 1253.2500 2568.000 8566.236 Jack 3569.00 5269.22 4586.00 Code: import glob import pandas as pd while True: path = input("Insert location:") file_list = glob.glob(path + "/*.txt") df_list = [] for file in file_list: df = pd.read_csv(file) df_list.append(df.take([0,-1,-4,-7])) excl_merged = pd.concat(df_list, ignore_index=False) #part two of the code writer = pd.ExcelWriter('Total.xlsx', engine='xlsxwriter') excl_merged.to_excel(writer, sheet_name='Sheet1', index=False, header=False) writer.close() print('success!!') I have tested many methods, but they did not work; for example, I tested pandas.transpose() I tried to do this in Excel, But it did not work too.
[ "Assuming this input:\ndf = pd.DataFrame({'col': ['David', '1253.2500', '2568.000', '8566.236', 'Jack', '3569.00', '5269.22', '4586.00']})\n\nYou can use:\ns = pd.to_numeric(df['col'], errors='coerce')\nm = s.isna()\n\nout = (df\n .assign(col=df['col'].where(m).ffill(),\n value=s, index=m.groupby(m.cumsum()).cumcount())\n .loc[~m]\n .pivot(index='index', columns='col', values='value')\n )\n\nprint(out)\n\nOutput:\ncol David Jack\nindex \n1 1253.250 3569.00\n2 2568.000 5269.22\n3 8566.236 4586.00\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "excel", "pandas", "python" ]
stackoverflow_0074485384_dataframe_excel_pandas_python.txt
Q: Elasticsearch indexing stops in middle When i am indexing my data it stops in middle, i have attached screenshot. one thing i have noticed is when ES is not indexing, python start to use swap memory upto 50 GB, and every-time my indexing stops at 54%. Any help is appreciated. Thanks ` for ok, action in parallel_bulk( client=client, index=product_index_name, actions=actions, thread_count=4, request_timeout=100, chunk_size=100, raise_on_error=True, raise_on_exception=True ): ` A: i have used parallel bulk, to increase indexing speed. Also i had very very huge data set, which i reduced. That helped a lot https://elasticsearch-py.readthedocs.io/en/7.x/helpers.html#elasticsearch.helpers.parallel_bulk
Elasticsearch indexing stops in middle
When i am indexing my data it stops in middle, i have attached screenshot. one thing i have noticed is when ES is not indexing, python start to use swap memory upto 50 GB, and every-time my indexing stops at 54%. Any help is appreciated. Thanks ` for ok, action in parallel_bulk( client=client, index=product_index_name, actions=actions, thread_count=4, request_timeout=100, chunk_size=100, raise_on_error=True, raise_on_exception=True ): `
[ "i have used parallel bulk, to increase indexing speed. Also i had very very huge data set, which i reduced. That helped a lot\nhttps://elasticsearch-py.readthedocs.io/en/7.x/helpers.html#elasticsearch.helpers.parallel_bulk\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "python", "runtime_error" ]
stackoverflow_0074358258_elasticsearch_python_runtime_error.txt
Q: Adding custom title to django form fields I would like to add custom title to one of my form fields. I made some modifications but it still not working. My forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30) phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] labels = {'fixed_by' : 'Fixed by/Assigned to'} ` my models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') ` Need to change the form field title "Fixed by" to "Fixed by/Assigned to" A: In forms.py: Just add label directly to form field so: fixed_by = forms.CharField(max_length=30, label="Fixed by/Assigned to")
Adding custom title to django form fields
I would like to add custom title to one of my form fields. I made some modifications but it still not working. My forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30) phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] labels = {'fixed_by' : 'Fixed by/Assigned to'} ` my models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') ` Need to change the form field title "Fixed by" to "Fixed by/Assigned to"
[ "In forms.py:\nJust add label directly to form field so:\nfixed_by = forms.CharField(max_length=30, label=\"Fixed by/Assigned to\")\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_forms", "django_models", "django_templates", "python" ]
stackoverflow_0074485359_django_django_forms_django_models_django_templates_python.txt
Q: How can I save my results in the same file as different columns in case of a 'for-cylce' def get_df(): df = pd.DataFrame() os.chdir("C:/Users/s/Desktop/P") for file in os.listdir(): if file.endswith('.csv'): av_a = np.average(a, axis=0) np.savetxt('merged_average.csv', av_a, delimiter=',') I've tried to save it but it always overwrites with the next file and deletes the previous results A: At the moment, your code is a bit hard to read, as you are declaring variables which are not used (df) and using variables which are not declared (a). In the future, try to give a minimal reproducible example of your problematic code. I'll still try to give you an interpreted answer: If you want to store multiple columns from different files next to each other, the job becomes simpler by first acquiring all columns, and then afterwardds save them to the file in a single action. Here is an interpretation of your code: def get_df(): # create an empty list to collect all results average_results = [] os.chdir("C:/Users/s/Desktop/P") for file in os.listdir(): if file.endswith('.csv'): a = something(file) # unknown to me average_results.append(np.average(a, axis=0)) # convert the results to a 2d numpy matrix, # optionally transpose it to get the desired data orientation data = np.array(average_results).transpose() # save the full dataset np.savetxt('merged_average.csv', data , delimiter=',')
How can I save my results in the same file as different columns in case of a 'for-cylce'
def get_df(): df = pd.DataFrame() os.chdir("C:/Users/s/Desktop/P") for file in os.listdir(): if file.endswith('.csv'): av_a = np.average(a, axis=0) np.savetxt('merged_average.csv', av_a, delimiter=',') I've tried to save it but it always overwrites with the next file and deletes the previous results
[ "At the moment, your code is a bit hard to read, as you are declaring variables which are not used (df) and using variables which are not declared (a). In the future, try to give a minimal reproducible example of your problematic code.\nI'll still try to give you an interpreted answer:\nIf you want to store multiple columns from different files next to each other, the job becomes simpler by first acquiring all columns, and then afterwardds save them to the file in a single action.\nHere is an interpretation of your code:\ndef get_df():\n # create an empty list to collect all results\n average_results = []\n os.chdir(\"C:/Users/s/Desktop/P\")\n for file in os.listdir():\n if file.endswith('.csv'):\n a = something(file) # unknown to me \n average_results.append(np.average(a, axis=0))\n # convert the results to a 2d numpy matrix,\n # optionally transpose it to get the desired data orientation\n data = np.array(average_results).transpose()\n # save the full dataset\n np.savetxt('merged_average.csv', data , delimiter=',')\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074479757_python.txt
Q: AssertionError: Shape of new values must be compatible with manager shape Error with pandas apply I have a pandas data frame with following columns col = ["File_Path", "Function_Body", "Prediction", "Line_Number"] I am applying get_prediction() function on column Function body and it returns three values List (Prediction): Ex. [1,1,0,0,0] List (Confidence): Ex. [64.000, 88.000,0,0,0] List of List (Top 5 Tokens with line Number): [['int', 5], ['ret', 6],['char', 5],['sum', 4],['i', 2]] Following piece of code, runs fine for one dataset but gives subjected error for other dataset. final_df["Prediction"], final_df["Confidence"], final_df["Tokens"] = zip(*final_df["Function_Body"].apply(lambda x:get_prediction(x))) Error: File "nginx_fast.py", line 404, in <module> final_df["Prediction"], final_df["Confidence"], final_df["Tokens"] = zip(*final_df["Function_Body"].apply(lambda x:get_prediction(x))) File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 2938, in __setitem__ self._set_item(key, value) File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 3001, in _set_item NDFrame._set_item(self, key, value) File "/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py", line 3624, in _set_item self._data.set(key, value) File "/usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py", line 1067, in set "Shape of new values must be compatible with manager shape" AssertionError: Shape of new values must be compatible with manager shape I checked the shape and type of value being returned before return statement, it looks fine to me. A: I also encountered this problem. This is how I solved it final_df["Prediction"], final_df["Confidence"], c = zip(*final_df["Function_Body"].apply(lambda x:get_prediction(x))) final_df["Tokens"] = list(c) because the output 'c' is a tuple, DataFrame should get a list, so you should convert the tuple to a list.
AssertionError: Shape of new values must be compatible with manager shape
Error with pandas apply I have a pandas data frame with following columns col = ["File_Path", "Function_Body", "Prediction", "Line_Number"] I am applying get_prediction() function on column Function body and it returns three values List (Prediction): Ex. [1,1,0,0,0] List (Confidence): Ex. [64.000, 88.000,0,0,0] List of List (Top 5 Tokens with line Number): [['int', 5], ['ret', 6],['char', 5],['sum', 4],['i', 2]] Following piece of code, runs fine for one dataset but gives subjected error for other dataset. final_df["Prediction"], final_df["Confidence"], final_df["Tokens"] = zip(*final_df["Function_Body"].apply(lambda x:get_prediction(x))) Error: File "nginx_fast.py", line 404, in <module> final_df["Prediction"], final_df["Confidence"], final_df["Tokens"] = zip(*final_df["Function_Body"].apply(lambda x:get_prediction(x))) File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 2938, in __setitem__ self._set_item(key, value) File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 3001, in _set_item NDFrame._set_item(self, key, value) File "/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py", line 3624, in _set_item self._data.set(key, value) File "/usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py", line 1067, in set "Shape of new values must be compatible with manager shape" AssertionError: Shape of new values must be compatible with manager shape I checked the shape and type of value being returned before return statement, it looks fine to me.
[ "I also encountered this problem. This is how I solved it\nfinal_df[\"Prediction\"], final_df[\"Confidence\"], c = zip(*final_df[\"Function_Body\"].apply(lambda x:get_prediction(x)))\n\nfinal_df[\"Tokens\"] = list(c)\n\nbecause the output 'c' is a tuple, DataFrame should get a list, so you should convert the tuple to a list.\n" ]
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "python_3.x" ]
stackoverflow_0062610174_numpy_pandas_python_python_3.x.txt
Q: decision boundary for classification I have trained my machine learning classification model in Python. For the result analysis when I am trying to draw a decision surface or boundary in google colab using sklearn(scikit-learn) inspection module from sklearn.inspection import DecisionBoundaryDisplay I am getting the following error. I have upgraded sklearn pip install -U scikit-learn After the upgrade sklearn version is 1.0.2 why am I encountering the error and what is the solution to this problem? A: sklearn v1.0.2 does not have DecisionBoundaryDisplay: https://scikit-learn.org/1.0/modules/classes.html#module-sklearn.inspection sklearn v1.1.3 does: https://scikit-learn.org/stable/modules/classes.html#module-sklearn.inspection
decision boundary for classification
I have trained my machine learning classification model in Python. For the result analysis when I am trying to draw a decision surface or boundary in google colab using sklearn(scikit-learn) inspection module from sklearn.inspection import DecisionBoundaryDisplay I am getting the following error. I have upgraded sklearn pip install -U scikit-learn After the upgrade sklearn version is 1.0.2 why am I encountering the error and what is the solution to this problem?
[ "sklearn v1.0.2 does not have DecisionBoundaryDisplay: https://scikit-learn.org/1.0/modules/classes.html#module-sklearn.inspection\nsklearn v1.1.3 does: https://scikit-learn.org/stable/modules/classes.html#module-sklearn.inspection\n" ]
[ 0 ]
[]
[]
[ "analysis", "classification", "evaluation", "python", "scikit_learn" ]
stackoverflow_0074485529_analysis_classification_evaluation_python_scikit_learn.txt
Q: How to not make the program restart after a value error? So I recently started coding and just learned about 'try' and 'except' for 'ValueError'. I made this calculator but it restarts if you don't input an int on the 'second' input. How do I make it ask for pnly the 'second' variable instead of asking for the first one again? while True: try: first = int(input("First: ")) second = int(input("Second: ")) sum = first + second print(f"Sum: {sum}") break except ValueError: print("I didn't understand that") I tried this but it just asked for the second variable then restarted the program while True: try: first = int(input("First: ")) second = int(input("Second: ")) sum = first + second print(f"Sum: {sum}") break except ValueError: print("I didn't understand that") int(input("Second: ")) A: Use a separate while with try/except blocks for the two prompts. And since you are doing the same thing multiple times, put the common part in a function def get_input(prompt, cast_to=int): while True: try: return cast_to(input(prompt)) except ValueError: print("I didn't understand that") first = get_input("First: ") second = get_input("Second: ") sum = first + second print(f"Sum {sum}") A: Make a separate function for inputting the number: def GetNumberInput(text: str) -> int: while True: try: return int(input(text)) except ValueError: print("I didn't understand that") first = GetNumberInput("First: ") second = GetNumberInput("Second: ") sum = first + second print(f"Sum: {sum}") Output: First: 123 Second: aaa I didn't understand that Second: 456 Sum: 579 A: the problem you are facing is because as you exit the try-except block, the loop reiterates which leads to the first input again. You can avoid this behavior by taking the loop in a separate function, like so: def take_input(text): while True: try: return int(input(text)) except ValueError: print("I didn't understand that") You can then call this function whenever you require the input like, num = take_input("Input: "). The complete implementation of your calculator would look like this: def take_input(text): while True: try: return int(input(text)) except ValueError: print("I didn't understand that") first = GetNumberInput("First: ") second = GetNumberInput("Second: ") sum = first + second print(f"Sum: {sum}") Now the loop only runs when the return value is hit, else you go through another iteration of the loop, and so on and so forth. Hope you understand the logic behind this!
How to not make the program restart after a value error?
So I recently started coding and just learned about 'try' and 'except' for 'ValueError'. I made this calculator but it restarts if you don't input an int on the 'second' input. How do I make it ask for pnly the 'second' variable instead of asking for the first one again? while True: try: first = int(input("First: ")) second = int(input("Second: ")) sum = first + second print(f"Sum: {sum}") break except ValueError: print("I didn't understand that") I tried this but it just asked for the second variable then restarted the program while True: try: first = int(input("First: ")) second = int(input("Second: ")) sum = first + second print(f"Sum: {sum}") break except ValueError: print("I didn't understand that") int(input("Second: "))
[ "Use a separate while with try/except blocks for the two prompts. And since you are doing the same thing multiple times, put the common part in a function\ndef get_input(prompt, cast_to=int):\n while True:\n try:\n return cast_to(input(prompt))\n except ValueError:\n print(\"I didn't understand that\")\n\nfirst = get_input(\"First: \")\nsecond = get_input(\"Second: \")\nsum = first + second\nprint(f\"Sum {sum}\")\n\n", "Make a separate function for inputting the number:\ndef GetNumberInput(text: str) -> int:\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n \n\nfirst = GetNumberInput(\"First: \")\nsecond = GetNumberInput(\"Second: \")\nsum = first + second\nprint(f\"Sum: {sum}\")\n\nOutput:\nFirst: 123\nSecond: aaa\nI didn't understand that\nSecond: 456\nSum: 579\n\n", "the problem you are facing is because as you exit the try-except block, the loop reiterates which leads to the first input again. You can avoid this behavior by taking the loop in a separate function, like so:\ndef take_input(text):\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n\nYou can then call this function whenever you require the input like, num = take_input(\"Input: \"). The complete implementation of your calculator would look like this:\ndef take_input(text):\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"I didn't understand that\")\n\nfirst = GetNumberInput(\"First: \")\nsecond = GetNumberInput(\"Second: \")\nsum = first + second\nprint(f\"Sum: {sum}\")\n\nNow the loop only runs when the return value is hit, else you go through another iteration of the loop, and so on and so forth. Hope you understand the logic behind this!\n" ]
[ 3, 1, 1 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074485597_pycharm_python.txt
Q: Putting Result of Multiplication in a List I am trying to put a series of multiplications inside a list, I am using the code below: listx = [] for i in range (2): list = [(3*i)] listx.append(list) The problem is that this will put the two results inside two separate lists inside a lists, I just wants the floats to be inside the first list. A: listx = [] for i in range (2): listx.append(3*i) Just use this one. There is no need to create another list for storing the result. You created another list to store the value and appended that list into your listx A: You can also use list comprehensions. Basically it's the same with for cycles but it's much shorter and for simpler operations like yours it's easier to read. listx = [i*3 for i in range(2)] This should produce a single list with values multiplied by 3 as integers
Putting Result of Multiplication in a List
I am trying to put a series of multiplications inside a list, I am using the code below: listx = [] for i in range (2): list = [(3*i)] listx.append(list) The problem is that this will put the two results inside two separate lists inside a lists, I just wants the floats to be inside the first list.
[ "listx = []\nfor i in range (2):\n listx.append(3*i)\n\nJust use this one. There is no need to create another list for storing the result. You created another list to store the value and appended that list into your listx\n", "You can also use list comprehensions. Basically it's the same with for cycles but it's much shorter and for simpler operations like yours it's easier to read.\nlistx = [i*3 for i in range(2)]\n\nThis should produce a single list with values multiplied by 3 as integers\n" ]
[ 2, 2 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0074485583_append_list_python.txt
Q: Is there a better way to get to the file from a python stack trace referencing it? From a Python stack trace in either Output or Terminal, how to go to the file, or even better, the line where the error was raised? Ctrl-click doesn't respond. I have been doing ctrl-e and type the file name, but is there a faster way? A: Using ctrl+click in the terminal can go directly to the error line of the error file. If you need to achieve the same effect in the OUTPUT panel you can submit a feature request on GitHub.
Is there a better way to get to the file from a python stack trace referencing it?
From a Python stack trace in either Output or Terminal, how to go to the file, or even better, the line where the error was raised? Ctrl-click doesn't respond. I have been doing ctrl-e and type the file name, but is there a faster way?
[ "Using ctrl+click in the terminal can go directly to the error line of the error file.\n\nIf you need to achieve the same effect in the OUTPUT panel you can submit a feature request on GitHub.\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074332623_python_visual_studio_code.txt
Q: What is the function for Varied amount input data for Python? Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max. Ex: If the input is: 15 20 0 5 the output is: 10 20 nums = [] # initialse number = 0 # loop until there isn't an input while number != "": # ask for user input number = input('Enter number:') # validate the input isn't blank # prevents errors if number != "": # make input integer and add it to list nums.append(int(number)) avg = sum(nums) / len(nums) print(max(nums), avg) All is gives me is Enter number: A: I solved the problem correctly using this: user_input = input() tokens = user_input.split() # Split into separate strings nums = [] for token in tokens: # Convert strings to integers nums.append(int(token)) avg = sum(nums) / len(nums) # Calculates average of all integers in nums print(int(avg), max(nums)) # Prints avg as an Integer instead of a Float A: nums = [] # loop until there isn't an input while not nums: # ask for user input number = input() nums = [int(x) for x in number.split() if x] avg = int(sum(nums) / len(nums)) print(avg, max(nums)) A: Zybooks 9.16 LAB: Varied amount of input data user_input = input().split(" ") average = 0.00 for x in range(len(user_input)): average += float(user_input[x]) user_input[x] = float(user_input[x]) average = float(average) / len(user_input) print(f'{max(user_input):.2f} {round(average,2):.2f}')
What is the function for Varied amount input data for Python?
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max. Ex: If the input is: 15 20 0 5 the output is: 10 20 nums = [] # initialse number = 0 # loop until there isn't an input while number != "": # ask for user input number = input('Enter number:') # validate the input isn't blank # prevents errors if number != "": # make input integer and add it to list nums.append(int(number)) avg = sum(nums) / len(nums) print(max(nums), avg) All is gives me is Enter number:
[ "I solved the problem correctly using this:\nuser_input = input()\n\ntokens = user_input.split() # Split into separate strings\n\nnums = [] \nfor token in tokens: # Convert strings to integers\n nums.append(int(token))\n\navg = sum(nums) / len(nums) # Calculates average of all integers in nums\nprint(int(avg), max(nums)) # Prints avg as an Integer instead of a Float\n\n", "nums = []\n\n# loop until there isn't an input\nwhile not nums:\n # ask for user input\n number = input()\n nums = [int(x) for x in number.split() if x]\n\navg = int(sum(nums) / len(nums))\nprint(avg, max(nums))\n\n", "Zybooks\n9.16 LAB: Varied amount of input data\nuser_input = input().split(\" \")\naverage = 0.00\n\nfor x in range(len(user_input)):\n average += float(user_input[x])\n user_input[x] = float(user_input[x])\naverage = float(average) / len(user_input)\n\n\nprint(f'{max(user_input):.2f} {round(average,2):.2f}')\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0071744679_python.txt
Q: In PySimpleGUI, how can I have a hyperlink in a text field? I am creating a search engine based on this Youtube tutorial which gives the output of the search result in a sg.Output element. I want each result to be clickable and open in Windows File Explorer with the file selected. My issues is in a PySimpleGUI output box (sg.Output) I can only seem to have text. How can I have text with a link attached to run a subprocess like this? My guess is it is something like what was discussed here: sg.Text('Here', is_link=True, key='link') # then link the key to an event However, as previously mentioned, if I add anything but text to sg.Output it does not work, i.e., the following does not work: sg.window.FindElement('-OUTPUT-').Update(sg.Text('Here', is_link=True, key='link')) A: It will be much complex to enable hyperlink function for sg.Output or sg.Multiline. Here's simple code to provide hyperlink function for sg.Text, also work for some other elements, by using options enable_events=True and tooltip. import webbrowser import PySimpleGUI as sg urls = { 'Google':'https://www.google.com', 'Amazon':'https://www.amazon.com/', 'NASA' :'https://www.nasa.gov/', 'Python':'https://www.python.org/', } items = sorted(urls.keys()) sg.theme("DarkBlue") font = ('Courier New', 16, 'underline') layout = [[sg.Text(txt, tooltip=urls[txt], enable_events=True, font=font, key=f'URL {urls[txt]}')] for txt in items] window = sg.Window('Hyperlink', layout, size=(250, 150), finalize=True) while True: event, values = window.read() if event == sg.WINDOW_CLOSED: break elif event.startswith("URL "): url = event.split(' ')[1] webbrowser.open(url) print(event, values) window.close() A: This took awhile, however I'm sure I'll use it a lot. xD Additional you can specify the tooltip parameter to show the site it'll go to. import PySimpleGUI as sg import webbrowser layout = [ [ sg.Text("My Awesome Link", text_color="#0000EE", font=(None, 20), enable_events=True, key="-LINK-") ] ] window = sg.Window("Hyperlink", layout, finalize=True) window["-LINK-"].set_cursor("hand2") window["-LINK-"].Widget.bind("<Enter>", lambda _: window["-LINK-"].update(font=(None, 20, "underline"))) window["-LINK-"].Widget.bind("<Leave>", lambda _: window["-LINK-"].update(font=(None, 20))) while True: event, values = window.read() if event == sg.WIN_CLOSED: break elif event == "-LINK-": webbrowser.open("https://www.pysimplegui.org/") window.close()
In PySimpleGUI, how can I have a hyperlink in a text field?
I am creating a search engine based on this Youtube tutorial which gives the output of the search result in a sg.Output element. I want each result to be clickable and open in Windows File Explorer with the file selected. My issues is in a PySimpleGUI output box (sg.Output) I can only seem to have text. How can I have text with a link attached to run a subprocess like this? My guess is it is something like what was discussed here: sg.Text('Here', is_link=True, key='link') # then link the key to an event However, as previously mentioned, if I add anything but text to sg.Output it does not work, i.e., the following does not work: sg.window.FindElement('-OUTPUT-').Update(sg.Text('Here', is_link=True, key='link'))
[ "It will be much complex to enable hyperlink function for sg.Output or sg.Multiline.\nHere's simple code to provide hyperlink function for sg.Text, also work for some other elements, by using options enable_events=True and tooltip.\n\nimport webbrowser\nimport PySimpleGUI as sg\n\nurls = {\n 'Google':'https://www.google.com',\n 'Amazon':'https://www.amazon.com/',\n 'NASA' :'https://www.nasa.gov/',\n 'Python':'https://www.python.org/',\n}\n\nitems = sorted(urls.keys())\n\nsg.theme(\"DarkBlue\")\nfont = ('Courier New', 16, 'underline')\n\nlayout = [[sg.Text(txt, tooltip=urls[txt], enable_events=True, font=font,\n key=f'URL {urls[txt]}')] for txt in items]\nwindow = sg.Window('Hyperlink', layout, size=(250, 150), finalize=True)\n\nwhile True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED:\n break\n elif event.startswith(\"URL \"):\n url = event.split(' ')[1]\n webbrowser.open(url)\n print(event, values)\n\nwindow.close()\n\n", "This took awhile, however I'm sure I'll use it a lot. xD\nAdditional you can specify the tooltip parameter to show the site it'll go to.\nimport PySimpleGUI as sg\nimport webbrowser\n\nlayout = [\n [\n sg.Text(\"My Awesome Link\", text_color=\"#0000EE\", font=(None, 20), enable_events=True, key=\"-LINK-\")\n ]\n]\n\nwindow = sg.Window(\"Hyperlink\", layout, finalize=True)\n\nwindow[\"-LINK-\"].set_cursor(\"hand2\")\nwindow[\"-LINK-\"].Widget.bind(\"<Enter>\", lambda _: window[\"-LINK-\"].update(font=(None, 20, \"underline\")))\nwindow[\"-LINK-\"].Widget.bind(\"<Leave>\", lambda _: window[\"-LINK-\"].update(font=(None, 20)))\n\nwhile True:\n event, values = window.read()\n\n if event == sg.WIN_CLOSED:\n break\n\n elif event == \"-LINK-\":\n webbrowser.open(\"https://www.pysimplegui.org/\")\n\nwindow.close()\n\n" ]
[ 4, 0 ]
[]
[]
[ "pysimplegui", "python" ]
stackoverflow_0066866390_pysimplegui_python.txt
Q: python selenium send_keys CONTROL, 'c' not copying actual text I successfully highlight the section in a web page, but send_keys, .send_keys(Keys.CONTROL, "c"), does not place the intended text to copy in clipboard, only the last thing I manually copied is in clipboard: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.somesite.com") driver.find_element_by_id("some id").send_keys(Keys.CONTROL, "a") #this successfully highlights section I need to copy elem.send_keys(Keys.CONTROL, "c") # this does not actually copy text** I tried then using the Firefox edit menu to select all and copy text, but didn't work either and cant find anything online to assist other than possible mention of a bug (tried old version of Firefox, but didn't solve issue). Any ideas? A: Try using the code below: Include the header below to import ActionChains from selenium.webdriver.common.action_chains import ActionChains actions = ActionChains(driver) actions.key_down(Keys.CONTROL) actions.send_keys("c") actions.key_up(Keys.CONTROL) A: Try this: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.somesite.com") driver.find_element_by_id("some id").send_keys(Keys.CONTROL, "a") driver.find_element_by_id("some id").send_keys(Keys.CONTROL, "c") A: This one actually works, it is updated to this date and also tested several times. from selenium.webdriver.common.action_chains import ActionChains def clear_text(self): webdriver.ActionChains(self.driver).key_down(Keys.CONTROL).perform() webdriver.ActionChains(self.driver).send_keys("a").perform() webdriver.ActionChains(self.driver).key_up(Keys.CONTROL).perform() webdriver.ActionChains(self.driver).send_keys(Keys.DELETE).perform() ActionChains are very useful nowdays, don't forget to .perform() every action To use this functionswhile in a class: text_box.click() #or other clicking function so you are actually typing self.clear_text() # Because it stands by itself A: You did not define what "elim" is try: elim = driver.find_element_by_id("some_id") elim.send_keys(Keys.CONTROL, "a") elim.send_keys(Keys.CONTROL, "c") A: NameError: name 'Keys' is not defined It means you have to import Keys in your Selenium Project. from selenium.webdriver.common.keys import Keys
python selenium send_keys CONTROL, 'c' not copying actual text
I successfully highlight the section in a web page, but send_keys, .send_keys(Keys.CONTROL, "c"), does not place the intended text to copy in clipboard, only the last thing I manually copied is in clipboard: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.somesite.com") driver.find_element_by_id("some id").send_keys(Keys.CONTROL, "a") #this successfully highlights section I need to copy elem.send_keys(Keys.CONTROL, "c") # this does not actually copy text** I tried then using the Firefox edit menu to select all and copy text, but didn't work either and cant find anything online to assist other than possible mention of a bug (tried old version of Firefox, but didn't solve issue). Any ideas?
[ "Try using the code below:\nInclude the header below to import ActionChains\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\nactions = ActionChains(driver)\n\nactions.key_down(Keys.CONTROL)\n\nactions.send_keys(\"c\")\n\nactions.key_up(Keys.CONTROL)\n\n", "Try this:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys \n\ndriver = webdriver.Firefox()\ndriver.get(\"http://www.somesite.com\") \ndriver.find_element_by_id(\"some id\").send_keys(Keys.CONTROL, \"a\")\ndriver.find_element_by_id(\"some id\").send_keys(Keys.CONTROL, \"c\")\n\n", "This one actually works, it is updated to this date and also tested several times.\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\ndef clear_text(self):\n webdriver.ActionChains(self.driver).key_down(Keys.CONTROL).perform()\n webdriver.ActionChains(self.driver).send_keys(\"a\").perform()\n webdriver.ActionChains(self.driver).key_up(Keys.CONTROL).perform()\n webdriver.ActionChains(self.driver).send_keys(Keys.DELETE).perform()\n \n\nActionChains are very useful nowdays, don't forget to .perform() every action\nTo use this functionswhile in a class:\ntext_box.click() #or other clicking function so you are actually typing\nself.clear_text() # Because it stands by itself\n\n", "You did not define what \"elim\" is\ntry:\nelim = driver.find_element_by_id(\"some_id\")\nelim.send_keys(Keys.CONTROL, \"a\")\nelim.send_keys(Keys.CONTROL, \"c\")\n\n", "NameError: name 'Keys' is not defined\nIt means you have to import Keys in your Selenium Project.\nfrom selenium.webdriver.common.keys import Keys\n\n" ]
[ 7, 4, 3, 1, 0 ]
[]
[]
[ "python", "screen_scraping", "selenium" ]
stackoverflow_0037763110_python_screen_scraping_selenium.txt
Q: How is throttling disabled for testing in Django Rest Framework? Upon implementing a throttle for a REST API, I'm encountering an issue when running my tests all at once. Upon isolating the subject TestCase and running the test runner, the TestCase passes its assertions. However when all the tests are ran I get the following error: AssertionError: 429 != 400. Which that type of error of course is due to the requests exceeding a rate limit. How can I disable throttling for the tests so the assertion error is not raised. I decorated the TestCase with @override_settings but that doesn't have any effect. from copy import deepcopy from django.conf import settings from django.test import TestCase, override_settings from django.contrib.auth.models import User from rest_framework.test import APITestCase, APIClient from django.urls import reverse from ..models import QuestionVote, Question from users.models import UserAccount from tags.models import Tag from .model_test_data import mock_questions_submitted REST_FRAMEWORK = deepcopy(settings.REST_FRAMEWORK) del REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] @override_settings(REST_FRAMEWORK=REST_FRAMEWORK) class TestUserVoteOnOwnQuestion(APITestCase): '''Verify that a User cannot vote on their own Question''' @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("Me", password="topsecretcode") cls.user1_account = UserAccount.objects.create(user=cls.user1) cls.tag = Tag.objects.create(name="Tag") cls.q = mock_questions_submitted[2] cls.q.update({'user_account': cls.user1_account}) cls.question = Question(**cls.q) cls.question.save() cls.question.tags.add(cls.tag) def test_vote_on_own_posted_question(self): self.client.login(username="Me", password="topsecretcode") response = self.client.put( reverse("questions_api:vote", kwargs={'id': 1}), data={"vote": "upvote"} ) self.assertEqual(response.status_code, 400) self.assertEquals( response.data['vote'], "Cannot vote on your own question" ) REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_THROTTLE_RATES': { 'voting': '5/minute' } } class UserQuestionVoteView(APIView): renderer_classes = [JSONRenderer, ] parser_classes = [JSONParser, ] permission_classes = [IsAuthenticated, ] authentication_classes = [SessionAuthentication, ] throttle_classes = [ScopedRateThrottle, ] throttle_scope = "voting" def put(self, request, id): # import pdb; pdb.set_trace() account = UserAccount.objects.get(user=request.user) question = Question.objects.get(id=id) if account == question.user_account: return Response(data={ 'vote': "Cannot vote on your own question" }, status=400) try: stored_vote = QuestionVote.objects.get( account=account, question=question ) serializer = QuestionVoteSerializer(stored_vote, request.data) except QuestionVote.DoesNotExist: serializer = QuestionVoteSerializer(data=request.data) finally: if serializer.is_valid(raise_exception=True): question_vote = serializer.save( account=account, question=question ) vote = serializer.validated_data['vote'] if vote == "downvote": question.vote_tally = F('vote_tally') - 1 else: question.vote_tally = F('vote_tally') + 1 question.save() question.refresh_from_db() return Response(data={ 'id': question.id, 'tally': question.vote_tally }) return Response(serializer.errors) A: One way to do this is by setting your config files up to support testing versions: # config.py REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_THROTTLE_RATES': { 'voting': '5/minute' } } TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test' if TESTING: del REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] The pro of this approach is you're not hacking away at your application in tests and hiding modifications to the config file - all of your testing based changes are in the same config file as their true values. The con of this approach is unless your developers know this setting and values are there, they may be scratching their heads as to why the throttling doesn't work in tests, but does at runtime. A: My solution was to apply some monkey patching. I have a throttles.py file where I have custom throttles, such as class UserBurstRateThrottle(UserRateThrottle): rate = '120/minute' What I've done is create a stub allow_request function to always return true, so something like def apply_monkey_patching_for_test(): def _allow_request(self, request, view): return True UserBurstRateThrottle.allow_request = _allow_request Then, in the test_whatever.py file, I add the following at the top. from my_proj import throttles throttles.apply_monkey_patching_for_test()
How is throttling disabled for testing in Django Rest Framework?
Upon implementing a throttle for a REST API, I'm encountering an issue when running my tests all at once. Upon isolating the subject TestCase and running the test runner, the TestCase passes its assertions. However when all the tests are ran I get the following error: AssertionError: 429 != 400. Which that type of error of course is due to the requests exceeding a rate limit. How can I disable throttling for the tests so the assertion error is not raised. I decorated the TestCase with @override_settings but that doesn't have any effect. from copy import deepcopy from django.conf import settings from django.test import TestCase, override_settings from django.contrib.auth.models import User from rest_framework.test import APITestCase, APIClient from django.urls import reverse from ..models import QuestionVote, Question from users.models import UserAccount from tags.models import Tag from .model_test_data import mock_questions_submitted REST_FRAMEWORK = deepcopy(settings.REST_FRAMEWORK) del REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] @override_settings(REST_FRAMEWORK=REST_FRAMEWORK) class TestUserVoteOnOwnQuestion(APITestCase): '''Verify that a User cannot vote on their own Question''' @classmethod def setUpTestData(cls): cls.user1 = User.objects.create_user("Me", password="topsecretcode") cls.user1_account = UserAccount.objects.create(user=cls.user1) cls.tag = Tag.objects.create(name="Tag") cls.q = mock_questions_submitted[2] cls.q.update({'user_account': cls.user1_account}) cls.question = Question(**cls.q) cls.question.save() cls.question.tags.add(cls.tag) def test_vote_on_own_posted_question(self): self.client.login(username="Me", password="topsecretcode") response = self.client.put( reverse("questions_api:vote", kwargs={'id': 1}), data={"vote": "upvote"} ) self.assertEqual(response.status_code, 400) self.assertEquals( response.data['vote'], "Cannot vote on your own question" ) REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_THROTTLE_RATES': { 'voting': '5/minute' } } class UserQuestionVoteView(APIView): renderer_classes = [JSONRenderer, ] parser_classes = [JSONParser, ] permission_classes = [IsAuthenticated, ] authentication_classes = [SessionAuthentication, ] throttle_classes = [ScopedRateThrottle, ] throttle_scope = "voting" def put(self, request, id): # import pdb; pdb.set_trace() account = UserAccount.objects.get(user=request.user) question = Question.objects.get(id=id) if account == question.user_account: return Response(data={ 'vote': "Cannot vote on your own question" }, status=400) try: stored_vote = QuestionVote.objects.get( account=account, question=question ) serializer = QuestionVoteSerializer(stored_vote, request.data) except QuestionVote.DoesNotExist: serializer = QuestionVoteSerializer(data=request.data) finally: if serializer.is_valid(raise_exception=True): question_vote = serializer.save( account=account, question=question ) vote = serializer.validated_data['vote'] if vote == "downvote": question.vote_tally = F('vote_tally') - 1 else: question.vote_tally = F('vote_tally') + 1 question.save() question.refresh_from_db() return Response(data={ 'id': question.id, 'tally': question.vote_tally }) return Response(serializer.errors)
[ "One way to do this is by setting your config files up to support testing versions:\n\n# config.py \n\nREST_FRAMEWORK = {\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json',\n 'DEFAULT_THROTTLE_RATES': {\n 'voting': '5/minute'\n }\n}\n\n\nTESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'\n\nif TESTING:\n del REST_FRAMEWORK['DEFAULT_THROTTLE_RATES']\n\n\nThe pro of this approach is you're not hacking away at your application in tests and hiding modifications to the config file - all of your testing based changes are in the same config file as their true values.\nThe con of this approach is unless your developers know this setting and values are there, they may be scratching their heads as to why the throttling doesn't work in tests, but does at runtime.\n", "My solution was to apply some monkey patching.\nI have a throttles.py file where I have custom throttles, such as\nclass UserBurstRateThrottle(UserRateThrottle):\n rate = '120/minute'\n\nWhat I've done is create a stub allow_request function to always return true, so something like\ndef apply_monkey_patching_for_test():\n def _allow_request(self, request, view):\n return True\n \n UserBurstRateThrottle.allow_request = _allow_request\n\n\nThen, in the test_whatever.py file, I add the following at the top.\nfrom my_proj import throttles\n\nthrottles.apply_monkey_patching_for_test()\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0067463665_django_django_rest_framework_python.txt
Q: Roblox won't detect mouse movement from autopygui I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press the button. After some troubleshooting, I have figured out that the mouse movement wont register with the game, as if I move my mouse manually, it clicks the button. In short, the game won't detect mouse movement from autopygui. If I move my mouse manually, it registers. Video example: https://youtu.be/VvAfHHXul8Q Code: import pyautogui as py import keyboard import tkinter import requests from ctypes import windll from time import sleep key = "m" toggled = False rjcolor = 16777215 root = tkinter.Tk() root.withdraw() width, height = root.winfo_screenwidth(), root.winfo_screenheight() dc= windll.user32.GetDC(0) def getpixel(x,y): return windll.gdi32.GetPixel(dc,x,y) while True: if keyboard.is_pressed(key): toggled = not toggled print("toggled to " + str(toggled)) sleep(0.5) if toggled == True: py.moveTo(width / 2, 800) py.click(button='left') if getpixel(1050, 600) == rjcolor: print("disconnected, waiting until internet back online!") while True: try: requests.head("http://www.google.com/", timeout=3) print('The internet connection is active, rejoining.') py.moveTo(1050, 590) py.mouseDown(button='left') sleep(0.1) py.mouseUp(button='left') break except requests.ConnectionError: print("The internet connection is down") sleep(3) sleep(0.1) A: Pyautogui has issues with clicking on roblox, but i've found a workaround: Replace py.click(button="left") with autoit.mouse_click("left") import autoit autoit.mouse_click("left")
Roblox won't detect mouse movement from autopygui
I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press the button. After some troubleshooting, I have figured out that the mouse movement wont register with the game, as if I move my mouse manually, it clicks the button. In short, the game won't detect mouse movement from autopygui. If I move my mouse manually, it registers. Video example: https://youtu.be/VvAfHHXul8Q Code: import pyautogui as py import keyboard import tkinter import requests from ctypes import windll from time import sleep key = "m" toggled = False rjcolor = 16777215 root = tkinter.Tk() root.withdraw() width, height = root.winfo_screenwidth(), root.winfo_screenheight() dc= windll.user32.GetDC(0) def getpixel(x,y): return windll.gdi32.GetPixel(dc,x,y) while True: if keyboard.is_pressed(key): toggled = not toggled print("toggled to " + str(toggled)) sleep(0.5) if toggled == True: py.moveTo(width / 2, 800) py.click(button='left') if getpixel(1050, 600) == rjcolor: print("disconnected, waiting until internet back online!") while True: try: requests.head("http://www.google.com/", timeout=3) print('The internet connection is active, rejoining.') py.moveTo(1050, 590) py.mouseDown(button='left') sleep(0.1) py.mouseUp(button='left') break except requests.ConnectionError: print("The internet connection is down") sleep(3) sleep(0.1)
[ "Pyautogui has issues with clicking on roblox, but i've found a workaround:\nReplace py.click(button=\"left\") with autoit.mouse_click(\"left\")\n import autoit\n autoit.mouse_click(\"left\")\n\n" ]
[ 1 ]
[]
[]
[ "pyautogui", "python", "roblox" ]
stackoverflow_0074351571_pyautogui_python_roblox.txt
Q: pandas read specific table how can i get only AP ' "EO7" Hardware Information ' table from output like below. can i do this with pandas. AP "EO7" Basic Information --------------------------------------- Item Value ---- ----- AP IP Address 11.22.33.44 LMS IP Address 2.2.2.2 Group aa Location Name N/A Standby AAC 1.1.1.1 (last assigned at Fri Nov 11 03:14:06 2022 (5h:20m:50s ago); last sent at Fri Nov 11 03:14:06 2022 (5h:20m:50s ago), total sent 3) Status Up Up time 8d:9h:14m:14s AP Flags: ; Licensed; Ready for Standby; Standby Not Connected Installation indoor AP "EO7" Hardware Information ------------------------------------------ Item Value ---- ----- AP Type 105 Serial # BEaaaaaaa Wired MAC Address d8:c7:c8:c9:aa:aa Radio 0 BSSID d8:c7:c8:15:ac:a8 Radio 1 BSSID d8:c7:c8:15:ac:da Radio 2 BSSID N/A Enet 1 MAC Address N/A Enet 2 MAC Address N/A Enet 3 MAC Address N/A Enet 4 MAC Address N/A Enet 5 MAC Address N/A Enet 6 MAC Address N/A Enet 7 MAC Address N/A AP "EO7" Operating Information ------------------------------------------- Item Value ---- ----- AP State Running Entry created 2022-11-10 09:15:24 Last activity 2022-11-11 08:32:27 Reboots 30 Bootstraps 35596 Bootstrap Threshold 8 Port N/A AP "EO7" Radio 0 Operating Information --------------------------------------------------- Item Value Source ---- ----- ------ High throughput Enabled Configuration Mode AP Configuration Band 802.11a Max SSIDs 8 Configuration Primary Channel 120 AirMatch 40MHz Secondary Channel 116 AirMatch EIRP 17.0 AirMatch Cell size reduction 0 dB AP "EO7" Radio 1 Operating Information --------------------------------------------------- Item Value Source ---- ----- ------ High throughput Enabled Configuration Mode AP Configuration Band 802.11g Max SSIDs 8 Configuration Channel 1 AirMatch 40MHz Secondary Channel None AirMatch EIRP 6.0 AirMatch 802.11b Protection Enabled Configuration Cell size reduction 0 dB AP "EO7" Provisioning Parameters --------------------------------------------- Item Value ---- ----- AP Name EO7 AP Group AVM Location name N/A SNMP sysLocation mor Master N/A Gateway N/A IPv6 Gateway N/A Netmask N/A IP Addr N/A IPv6 Addr N/A IPv6 Prefix 64 DNS IP N/A DNS IPv6 N/A Domain Name N/A Server Name N/A Server IP N/A Antenna gain for 802.11a N/A Radio 0 5GHz Antenna gain for APs support Dual 5GHz mode N/A Radio 1 5GHz Antenna gain for APs support Dual 5GHz mode N/A Antenna gain for 802.11g N/A Antenna for 802.11a both Antenna for 802.11g both PKCS12 PASSPHRASE N/A Single chain mode for Radio 0 0 Single chain mode for Radio 1 0 External antenna polarization for 5GHz Radio 0 External antenna polarization for 2.4GHz Radio 0 Radio 0 5GHz Antenna polarization for APs support Dual 5GHz mode 0 Radio 1 5GHz Antenna polarization for APs support Dual 5GHz mode 0 TrustAnchor N/A IKE PSK N/A ikepsk-hex-based No PAP User Name N/A PAP Password N/A PPPOE User Name N/A PPPOE Password N/A PPPOE Service Name N/A PPPOE CHAP Secret N/A USB User Name N/A USB Password N/A USB Device Type none USB CSR-Key Storage No USB Device Identifier N/A USB Dial String N/A USB Initialization String N/A USB TTY device data path N/A USB TTY device control path N/A USB modeswitch parameters N/A Uplink VLAN 0 Remote AP No OCSP Default N/A certificate DN N/A Link Priority Ethernet 0 Link Priority Cellular 0 Link Priority WiFi 0 Cellular modem network preference auto AP POE Power optimization false AP LLDP PSE detection disabled AP2xx prestandard POE detection Disabled Mesh Role none Installation default Latitude N/A Longitude N/A Altitude N/A Antenna bearing for 802.11a N/A Antenna bearing for 802.11g N/A Antenna tilt angle for 802.11a N/A Antenna tilt angle for 802.11g N/A Username of AP so that AP can authenticate to 802.1x using PEAP N/A Password of AP so that AP can authenticate to 802.1x using PEAP N/A Enable AP to 802.1x using EAP-TLS Disabled Enable AP to use factory certificates when doing 802.1x EAP-TLS Disabled AP dot1x EAP-TLS username suffix Disabled AP dot1x EAP-TLS username suffix domain aruba.ap AP Preferred Uplink Interface N/A AP WiFi uplink Disabled Mesh SAE sae-disable* A: Here is a starting point. info = {} capture = False for line in open("x.txt"): if not capture: capture = "Hardware Information" in line continue if "EO7" in line: break if "Item" in line: f1 = line.find("Item") f2 = line.find("Value") elif "----" not in line: key = line[f1:f2-1].strip() value = line[f2:].strip() if key: info[key] = value from pprint import pprint pprint(info) Output: {'AP Type': '105', 'Enet 1 MAC Address': 'N/A', 'Enet 2 MAC Address': 'N/A', 'Enet 3 MAC Address': 'N/A', 'Enet 4 MAC Address': 'N/A', 'Enet 5 MAC Address': 'N/A', 'Enet 6 MAC Address': 'N/A', 'Enet 7 MAC Address': 'N/A', 'Radio 0 BSSID': 'd8:c7:c8:15:ac:a8', 'Radio 1 BSSID': 'd8:c7:c8:15:ac:da', 'Radio 2 BSSID': 'N/A', 'Serial #': 'BEaaaaaaa', 'Wired MAC Address': 'd8:c7:c8:c9:aa:aa'}
pandas read specific table
how can i get only AP ' "EO7" Hardware Information ' table from output like below. can i do this with pandas. AP "EO7" Basic Information --------------------------------------- Item Value ---- ----- AP IP Address 11.22.33.44 LMS IP Address 2.2.2.2 Group aa Location Name N/A Standby AAC 1.1.1.1 (last assigned at Fri Nov 11 03:14:06 2022 (5h:20m:50s ago); last sent at Fri Nov 11 03:14:06 2022 (5h:20m:50s ago), total sent 3) Status Up Up time 8d:9h:14m:14s AP Flags: ; Licensed; Ready for Standby; Standby Not Connected Installation indoor AP "EO7" Hardware Information ------------------------------------------ Item Value ---- ----- AP Type 105 Serial # BEaaaaaaa Wired MAC Address d8:c7:c8:c9:aa:aa Radio 0 BSSID d8:c7:c8:15:ac:a8 Radio 1 BSSID d8:c7:c8:15:ac:da Radio 2 BSSID N/A Enet 1 MAC Address N/A Enet 2 MAC Address N/A Enet 3 MAC Address N/A Enet 4 MAC Address N/A Enet 5 MAC Address N/A Enet 6 MAC Address N/A Enet 7 MAC Address N/A AP "EO7" Operating Information ------------------------------------------- Item Value ---- ----- AP State Running Entry created 2022-11-10 09:15:24 Last activity 2022-11-11 08:32:27 Reboots 30 Bootstraps 35596 Bootstrap Threshold 8 Port N/A AP "EO7" Radio 0 Operating Information --------------------------------------------------- Item Value Source ---- ----- ------ High throughput Enabled Configuration Mode AP Configuration Band 802.11a Max SSIDs 8 Configuration Primary Channel 120 AirMatch 40MHz Secondary Channel 116 AirMatch EIRP 17.0 AirMatch Cell size reduction 0 dB AP "EO7" Radio 1 Operating Information --------------------------------------------------- Item Value Source ---- ----- ------ High throughput Enabled Configuration Mode AP Configuration Band 802.11g Max SSIDs 8 Configuration Channel 1 AirMatch 40MHz Secondary Channel None AirMatch EIRP 6.0 AirMatch 802.11b Protection Enabled Configuration Cell size reduction 0 dB AP "EO7" Provisioning Parameters --------------------------------------------- Item Value ---- ----- AP Name EO7 AP Group AVM Location name N/A SNMP sysLocation mor Master N/A Gateway N/A IPv6 Gateway N/A Netmask N/A IP Addr N/A IPv6 Addr N/A IPv6 Prefix 64 DNS IP N/A DNS IPv6 N/A Domain Name N/A Server Name N/A Server IP N/A Antenna gain for 802.11a N/A Radio 0 5GHz Antenna gain for APs support Dual 5GHz mode N/A Radio 1 5GHz Antenna gain for APs support Dual 5GHz mode N/A Antenna gain for 802.11g N/A Antenna for 802.11a both Antenna for 802.11g both PKCS12 PASSPHRASE N/A Single chain mode for Radio 0 0 Single chain mode for Radio 1 0 External antenna polarization for 5GHz Radio 0 External antenna polarization for 2.4GHz Radio 0 Radio 0 5GHz Antenna polarization for APs support Dual 5GHz mode 0 Radio 1 5GHz Antenna polarization for APs support Dual 5GHz mode 0 TrustAnchor N/A IKE PSK N/A ikepsk-hex-based No PAP User Name N/A PAP Password N/A PPPOE User Name N/A PPPOE Password N/A PPPOE Service Name N/A PPPOE CHAP Secret N/A USB User Name N/A USB Password N/A USB Device Type none USB CSR-Key Storage No USB Device Identifier N/A USB Dial String N/A USB Initialization String N/A USB TTY device data path N/A USB TTY device control path N/A USB modeswitch parameters N/A Uplink VLAN 0 Remote AP No OCSP Default N/A certificate DN N/A Link Priority Ethernet 0 Link Priority Cellular 0 Link Priority WiFi 0 Cellular modem network preference auto AP POE Power optimization false AP LLDP PSE detection disabled AP2xx prestandard POE detection Disabled Mesh Role none Installation default Latitude N/A Longitude N/A Altitude N/A Antenna bearing for 802.11a N/A Antenna bearing for 802.11g N/A Antenna tilt angle for 802.11a N/A Antenna tilt angle for 802.11g N/A Username of AP so that AP can authenticate to 802.1x using PEAP N/A Password of AP so that AP can authenticate to 802.1x using PEAP N/A Enable AP to 802.1x using EAP-TLS Disabled Enable AP to use factory certificates when doing 802.1x EAP-TLS Disabled AP dot1x EAP-TLS username suffix Disabled AP dot1x EAP-TLS username suffix domain aruba.ap AP Preferred Uplink Interface N/A AP WiFi uplink Disabled Mesh SAE sae-disable*
[ "Here is a starting point.\ninfo = {}\ncapture = False\nfor line in open(\"x.txt\"):\n if not capture:\n capture = \"Hardware Information\" in line\n continue\n if \"EO7\" in line:\n break\n if \"Item\" in line:\n f1 = line.find(\"Item\")\n f2 = line.find(\"Value\")\n elif \"----\" not in line:\n key = line[f1:f2-1].strip()\n value = line[f2:].strip()\n if key:\n info[key] = value\n\nfrom pprint import pprint\npprint(info)\n\nOutput:\n{'AP Type': '105',\n 'Enet 1 MAC Address': 'N/A',\n 'Enet 2 MAC Address': 'N/A',\n 'Enet 3 MAC Address': 'N/A',\n 'Enet 4 MAC Address': 'N/A',\n 'Enet 5 MAC Address': 'N/A',\n 'Enet 6 MAC Address': 'N/A',\n 'Enet 7 MAC Address': 'N/A',\n 'Radio 0 BSSID': 'd8:c7:c8:15:ac:a8',\n 'Radio 1 BSSID': 'd8:c7:c8:15:ac:da',\n 'Radio 2 BSSID': 'N/A',\n 'Serial #': 'BEaaaaaaa',\n 'Wired MAC Address': 'd8:c7:c8:c9:aa:aa'}\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074428303_pandas_python.txt
Q: Reading multiple Json files and combining into one file as per the date in Python I get JSON extracts throughout a day which is executed for different dates. As a preprocess step I would like to combine all JSONs with same date and merge them into common file with date as name. Multiple Json files tmp/emp1.json tmp/emp2.json tmp/emp3.json tmp/emp4.json tmp/emp5.json tmp/emp6.json Format of each json file is somewhat like below with StartTime mentioned for each row { "SQLS": [ { "ID": "0001", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "GP", "db": "emp_db", "StartTime": "2022-11-16 20:24:45.979057", "QueryID": "q101" }, "ID": "0002", "SQLText": "INSERT INTO sales as Select * from employee where emp department = 'sales'", "Properties": { "Type": "Static", "Source": "sybase", "db": "emp_db", "StartTime": "2022-11-17 20:24:45.979057", "QueryID": "q102" }, "ID": "0003", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "postgres", "db": "emp_db", "StartTime": "2022-11-16 20:24:45.979057", "QueryID": "q103" }, "ID": "0004", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "GP", "db": "emp_db", "StartTime": "2022-11-17 20:24:45.979057", "QueryID": "q104" } } ] } I want to read each of these files and put them into respective directory as per the date. Destination directory would belike below tmp/20221115/ tmp/20221116/ tmp/20221117/ Let me know if more clarity is required. Appreciate your suggestions on this. A: Here, is the solution for the issue. I have made one function you just need to pass the input directory path and output directory path. Rest it will handle. First, I converted the JSON into a pandas data frame. Then grouped them based on the startTime. After that club the data with the same date into the dictionary and at the end save them to the output path. import os import json import glob import pandas as pd output_dict = {} input_dirpath = 'filepath' output_dirpath = 'Dir_path' def merge_jsons(input_dirpath, output_dirpath): all_files = glob.glob(rf'{input_dirpath}/*.json') for file in all_files: with open(file) as file: data = json.loads(file.read()) df = pd.DataFrame(data['SQLS']) df['StartTime'] = pd.to_datetime(df['Properties'].apply(lambda x: x['StartTime'])).dt.date.astype(str) grps = df.groupby('StartTime') for start_time, data_obj in grps: date = start_time.replace('-','') data_obj = data_obj.drop('StartTime',axis=1).to_dict('records') if date not in output_dict: output_dict[date] = data_obj else: output_dict[date].append(data_obj) for filename, data in output_dict.items(): with open(os.path.join(output_dirpath,filename+'.json'),'w') as writer: writer.write(json.dumps({'SQLS':data})) print('filename: ',os.path.join(output_dirpath,filename+'.json'), 'saved..') A: import json filenames = ['emp1', 'emp2'] data_list = [] new_filenames = [] # Open files and concatenate objects for filename in filenames: f = open(f'./data/tmp/{filename}.json') data = json.load(f) data_list.append(data['SQLS']) # Find unique different dates contained in objects # Process them into new filenames for data in data_list: for obj in data: date = obj['Properties']['StartTime'].split(' ')[0] new_filename = date.replace('-', '') if new_filename not in new_filenames: new_filenames.append(new_filename) # Find objects with the right date/filename def find_objects(data, filename): new_data = { 'SQLS': [] } for data in data_list: for obj in data: date = obj['Properties']['StartTime'].split(' ')[0] new_filename = date.replace('-', '') if new_filename == filename: new_data['SQLS'].append(obj) return new_data # Write new files for filename in new_filenames: with open(f'./data/tmp/new_files/{filename}.json', 'w') as outfile: data = find_objects(data_list, filename) json_data = json.dumps(data, indent = 4) outfile.write(json_data)
Reading multiple Json files and combining into one file as per the date in Python
I get JSON extracts throughout a day which is executed for different dates. As a preprocess step I would like to combine all JSONs with same date and merge them into common file with date as name. Multiple Json files tmp/emp1.json tmp/emp2.json tmp/emp3.json tmp/emp4.json tmp/emp5.json tmp/emp6.json Format of each json file is somewhat like below with StartTime mentioned for each row { "SQLS": [ { "ID": "0001", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "GP", "db": "emp_db", "StartTime": "2022-11-16 20:24:45.979057", "QueryID": "q101" }, "ID": "0002", "SQLText": "INSERT INTO sales as Select * from employee where emp department = 'sales'", "Properties": { "Type": "Static", "Source": "sybase", "db": "emp_db", "StartTime": "2022-11-17 20:24:45.979057", "QueryID": "q102" }, "ID": "0003", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "postgres", "db": "emp_db", "StartTime": "2022-11-16 20:24:45.979057", "QueryID": "q103" }, "ID": "0004", "SQLText": "INSERT INTO tech as Select * from employee where emp department = 'tech'", "Properties": { "Type": "Static", "Source": "GP", "db": "emp_db", "StartTime": "2022-11-17 20:24:45.979057", "QueryID": "q104" } } ] } I want to read each of these files and put them into respective directory as per the date. Destination directory would belike below tmp/20221115/ tmp/20221116/ tmp/20221117/ Let me know if more clarity is required. Appreciate your suggestions on this.
[ "Here, is the solution for the issue. I have made one function you just need to pass the input directory path and output directory path. Rest it will handle.\n\nFirst, I converted the JSON into a pandas data frame.\n\nThen grouped them based on the startTime.\n\nAfter that club the data with the same date into the dictionary and at the end save them to the output path.\n import os\n import json\n import glob\n import pandas as pd\n output_dict = {}\n input_dirpath = 'filepath'\n output_dirpath = 'Dir_path'\n def merge_jsons(input_dirpath, output_dirpath):\n all_files = glob.glob(rf'{input_dirpath}/*.json')\n for file in all_files:\n with open(file) as file:\n data = json.loads(file.read())\n\n df = pd.DataFrame(data['SQLS'])\n df['StartTime'] = pd.to_datetime(df['Properties'].apply(lambda x: \n x['StartTime'])).dt.date.astype(str)\n grps = df.groupby('StartTime')\n\n for start_time, data_obj in grps:\n date = start_time.replace('-','')\n data_obj = data_obj.drop('StartTime',axis=1).to_dict('records')\n if date not in output_dict:\n output_dict[date] = data_obj\n else:\n output_dict[date].append(data_obj)\n\n for filename, data in output_dict.items():\n with open(os.path.join(output_dirpath,filename+'.json'),'w') as writer:\n writer.write(json.dumps({'SQLS':data}))\n print('filename: ',os.path.join(output_dirpath,filename+'.json'), 'saved..')\n\n\n\n", "import json\n\nfilenames = ['emp1', 'emp2']\ndata_list = []\nnew_filenames = []\n\n# Open files and concatenate objects\nfor filename in filenames:\n f = open(f'./data/tmp/{filename}.json')\n data = json.load(f)\n data_list.append(data['SQLS'])\n\n# Find unique different dates contained in objects\n# Process them into new filenames\nfor data in data_list:\n for obj in data:\n date = obj['Properties']['StartTime'].split(' ')[0]\n new_filename = date.replace('-', '')\n if new_filename not in new_filenames:\n new_filenames.append(new_filename)\n\n# Find objects with the right date/filename\ndef find_objects(data, filename):\n new_data = { 'SQLS': [] }\n\n for data in data_list:\n for obj in data:\n date = obj['Properties']['StartTime'].split(' ')[0]\n new_filename = date.replace('-', '')\n if new_filename == filename:\n new_data['SQLS'].append(obj)\n return new_data\n\n# Write new files\nfor filename in new_filenames:\n with open(f'./data/tmp/new_files/{filename}.json', 'w') as outfile:\n data = find_objects(data_list, filename)\n json_data = json.dumps(data, indent = 4) \n outfile.write(json_data)\n\n" ]
[ 2, 1 ]
[]
[]
[ "collections", "dataframe", "json", "pandas", "python" ]
stackoverflow_0074484870_collections_dataframe_json_pandas_python.txt
Q: Is there a way to discern an object from the background with OpenCV? I always wanted to have a device that, from a live camera feed, could detect an object, create a 3D model of it, and then identify it. It would work a lot like the Scanner tool from Subnautica. Imagine my surprise when I found OpenCV, a free-to-use computer vision tool for Python! My first step is to get the computer to recognize that there is an object at the center of the camera feed. To do this, I found a Canny() function that could detect edges and display them as white lines in a black image, which should make a complete outline of the object in the center. I also used the floodFill() function to fill in the black zone between the white lines with gray, which would show that the computer recognizes that there is an object there. My attempt is in the following image. The red dot is the center of the live video. The issue is that the edge lines can have holes in them due to a blur between two colors, which can range from individual pixels to entire missing lines. As a result, the gray gets out and doesn't highlight me as the only object, and instead highlights the entire wall as well. Is there a way to fill those missing pixels in or is there a better way of doing this? A: Welcome to SO and the exiting world of machine vision ! What you are describing is a very classical problem in the field, and not a trivial one at all. It depends heavily on the shape and appearance of what you define as the object of interest and the overall structure, homogeneity and color of the background. Remember, the computer has no concept of what an "object" is, the only thing it 'knows' is a matrix of numbers. In your example, you might start out with selecting the background area by color (or hue, look up HSV). Everything else is your object. This is what classical greenscreening techniques do, and it only works with (a) a homogenous background, which does not share a color with your object and (b) a single or multiple not overlapping objects. The problem with your edge based approach is that you won't get a closed edge safely, and deciding where the inside and outside of the object is might get tricky. Advanced ways to do this would get you into Neural Network territory, but maybe try to get the basics down first. Here are two links to tutorials on converting color spaces and extracting contours: https://docs.opencv.org/4.x/df/d9d/tutorial_py_colorspaces.html https://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html If you got that figured out, look into stereo vision or 3D imaging in general, and that subnautica scanner might just become reality some day ;) Good luck !
Is there a way to discern an object from the background with OpenCV?
I always wanted to have a device that, from a live camera feed, could detect an object, create a 3D model of it, and then identify it. It would work a lot like the Scanner tool from Subnautica. Imagine my surprise when I found OpenCV, a free-to-use computer vision tool for Python! My first step is to get the computer to recognize that there is an object at the center of the camera feed. To do this, I found a Canny() function that could detect edges and display them as white lines in a black image, which should make a complete outline of the object in the center. I also used the floodFill() function to fill in the black zone between the white lines with gray, which would show that the computer recognizes that there is an object there. My attempt is in the following image. The red dot is the center of the live video. The issue is that the edge lines can have holes in them due to a blur between two colors, which can range from individual pixels to entire missing lines. As a result, the gray gets out and doesn't highlight me as the only object, and instead highlights the entire wall as well. Is there a way to fill those missing pixels in or is there a better way of doing this?
[ "Welcome to SO and the exiting world of machine vision !\nWhat you are describing is a very classical problem in the field, and not a trivial one at all. It depends heavily on the shape and appearance of what you define as the object of interest and the overall structure, homogeneity and color of the background. Remember, the computer has no concept of what an \"object\" is, the only thing it 'knows' is a matrix of numbers.\nIn your example, you might start out with selecting the background area by color (or hue, look up HSV). Everything else is your object. This is what classical greenscreening techniques do, and it only works with (a) a homogenous background, which does not share a color with your object and (b) a single or multiple not overlapping objects.\nThe problem with your edge based approach is that you won't get a closed edge safely, and deciding where the inside and outside of the object is might get tricky.\nAdvanced ways to do this would get you into Neural Network territory, but maybe try to get the basics down first.\nHere are two links to tutorials on converting color spaces and extracting contours:\nhttps://docs.opencv.org/4.x/df/d9d/tutorial_py_colorspaces.html\nhttps://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html\nIf you got that figured out, look into stereo vision or 3D imaging in general, and that subnautica scanner might just become reality some day ;)\nGood luck !\n" ]
[ 0 ]
[]
[]
[ "object_detection", "opencv", "python" ]
stackoverflow_0074484556_object_detection_opencv_python.txt
Q: Python How to find if the given inputted strings can be found inside the second inputted strings? ** I AM NEW TO PYTHON ** I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Also by writing the code, it should not be case sensitive; by using islower() or isupper(). Example Outputs: 1st String: lol 2nd String: Hilol True 1st String: IDK 2nd String: whatidk True My code: a1 = str(input("first string: ")) a2 = str(input("second string: ")) if a2 in a1: print(True) else: print(False) It outputs: 1st String: lol 2nd String: lol True 1st String: lol 2nd String: HIlol False #This should be true, IDK why it is false. I only came this far with my code (I KNOW IT LACKS A LOT FROM THE INSTRUCTION). Hoping someone could teach me what to do. Thank you! EDIT: I FOUND OUT THAT, MY CODE SHOULD HAVE BEEN: a1 = str(input("Enter the first string: ")) a2 = str(input("Enter the second string: ")) if a1 in a2: print(True) else: print(False) But now, how do I make it not case sensitive? A: Is this what you're looking for? string_1 = input("first string: ") string_2 = input("second string: ") if string_1.lower() in string_2.lower(): print(True) else: print(False) A "function" would be: def check_occuring(substring, string): if substring.lower() in string.lower(): return True else: return False string_1 = input("first string: ") string_2 = input("second string: ") print(check_occuring(string_1, string_2)) Please note that you can also just print or return substring.lower() in string.lower() A: If you want the Program to be case sensitive, just make everything lowercase substring = input("substring: ").lower() text = input("text: ").lower() To check if a substring can be found in another string can be done by using the keyword in >>> "lol" in "HIlol" True maybe check your inputs here. The whole program would be substring = input("substring: ").lower() text = input("text: ").lower() print(substring in text) note: <str> in <str> gives you a boolean so you can use it in if conditions. In this case you can just print the boolean directly.
Python How to find if the given inputted strings can be found inside the second inputted strings?
** I AM NEW TO PYTHON ** I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Also by writing the code, it should not be case sensitive; by using islower() or isupper(). Example Outputs: 1st String: lol 2nd String: Hilol True 1st String: IDK 2nd String: whatidk True My code: a1 = str(input("first string: ")) a2 = str(input("second string: ")) if a2 in a1: print(True) else: print(False) It outputs: 1st String: lol 2nd String: lol True 1st String: lol 2nd String: HIlol False #This should be true, IDK why it is false. I only came this far with my code (I KNOW IT LACKS A LOT FROM THE INSTRUCTION). Hoping someone could teach me what to do. Thank you! EDIT: I FOUND OUT THAT, MY CODE SHOULD HAVE BEEN: a1 = str(input("Enter the first string: ")) a2 = str(input("Enter the second string: ")) if a1 in a2: print(True) else: print(False) But now, how do I make it not case sensitive?
[ "Is this what you're looking for?\nstring_1 = input(\"first string: \")\nstring_2 = input(\"second string: \")\n\nif string_1.lower() in string_2.lower(): \n print(True)\nelse:\n print(False)\n\nA \"function\" would be:\ndef check_occuring(substring, string):\n if substring.lower() in string.lower(): \n return True\n else:\n return False\n\nstring_1 = input(\"first string: \")\nstring_2 = input(\"second string: \")\nprint(check_occuring(string_1, string_2)) \n\nPlease note that you can also just print or return substring.lower() in string.lower()\n", "If you want the Program to be case sensitive, just make everything lowercase\nsubstring = input(\"substring: \").lower()\ntext = input(\"text: \").lower()\n\nTo check if a substring can be found in another string can be done by using the keyword in\n>>> \"lol\" in \"HIlol\"\nTrue\n\nmaybe check your inputs here. The whole program would be\nsubstring = input(\"substring: \").lower()\ntext = input(\"text: \").lower()\n\nprint(substring in text)\n\nnote: <str> in <str> gives you a boolean so you can use it in if conditions. In this case you can just print the boolean directly.\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074485862_python.txt
Q: What does "bound method" error mean when I call a function? I am creating a word parsing class and I keep getting a bound method Word_Parser.sort_word_list of <__main__.Word_Parser instance at 0x1037dd3b0> error when I run this: class Word_Parser: """docstring for Word_Parser""" def __init__(self, sentences): self.sentences = sentences def parser(self): self.word_list = self.sentences.split() def sort_word_list(self): self.sorted_word_list = self.word_list.sort() def num_words(self): self.num_words = len(self.word_list) test = Word_Parser("mary had a little lamb") test.parser() test.sort_word_list() test.num_words() print test.word_list print test.sort_word_list print test.num_words A: There's no error here. You're printing a function, and that's what functions look like. To actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For example: print test.sort_word_list() On the other hand, if you want the function to mutate the object's state, and then print the state some other way, that's fine too. Now, your code seems to work in some places, but not others; let's look at why: parser sets a variable called word_list, and you later print test.word_list, so that works. sort_word_list sets a variable called sorted_word_list, and you later print test.sort_word_list—that is, the function, not the variable. So, you see the bound method. (Also, as Jon Clements points out, even if you fix this, you're going to print None, because that's what sort returns.) num_words sets a variable called num_words, and you again print the function—but in this case, the variable has the same name as the function, meaning that you're actually replacing the function with its output, so it works. This is probably not what you want to do, however. (There are cases where, at first glance, that seems like it might be a good idea—you only want to compute something once, and then access it over and over again without constantly recomputing that. But this isn't the way to do it. Either use a @property, or use a memoization decorator.) A: This problem happens as a result of calling a method without brackets. Take a look at the example below: class SomeClass(object): def __init__(self): print 'I am starting' def some_meth(self): print 'I am a method()' x = SomeClass() ''' Not adding the bracket after the method call would result in method bound error ''' print x.some_meth ''' However this is how it should be called and it does solve it ''' x.some_meth() A: You have an instance method called num_words, but you also have a variable called num_words. They have the same name. When you run num_words(), the function replaces itself with its own output, which probably isn't what you want to do. Consider returning your values. To fix your problem, change def num_words to something like def get_num_words and your code should work fine. Also, change print test.sort_word_list to print test.sorted_word_list. A: For this thing you can use @property as an decorator, so you could use instance methods as attributes. For example: class Word_Parser: def __init__(self, sentences): self.sentences = sentences @property def parser(self): self.word_list = self.sentences.split() @property def sort_word_list(self): self.sorted_word_list = self.word_list.sort() @property def num_words(self): self.num_words = len(self.word_list) test = Word_Parser("mary had a little lamb") test.parser() test.sort_word_list() test.num_words() print test.word_list print test.sort_word_list print test.num_words so you can use access the attributes without calling (i.e., without the ()). A: I think you meant print test.sorted_word_list instead of print test.sort_word_list. In addition list.sort() sorts a list in place and returns None, so you probably want to change sort_word_list() to do the following: self.sorted_word_list = sorted(self.word_list) You should also consider either renaming your num_words() function, or changing the attribute that the function assigns to, because currently you overwrite the function with an integer on the first call. A: The syntax problem is shadowing method and variable names. In the current version sort_word_list() is a method, and sorted_word_list is a variable, whereas num_words is both. Also, list.sort() modifies the list and replaces it with a sorted version; the sorted(list) function actually returns a new list. But I suspect this indicates a design problem. What's the point of calls like test.parser() test.sort_word_list() test.num_words() which don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something. E.G., def sort_word_list(self): if self.sorted_word_list is not None: self.sorted_word_list = sorted(self.word_list) return self.sorted_word_list (Alternately, you could use properties.) A: Your helpful comments led me to the following solution: class Word_Parser: """docstring for Word_Parser""" def __init__(self, sentences): self.sentences = sentences def parser(self): self.word_list = self.sentences.split() word_list = [] word_list = self.word_list return word_list def sort_word_list(self): self.sorted_word_list = sorted(self.sentences.split()) sorted_word_list = self.sorted_word_list return sorted_word_list def get_num_words(self): self.num_words = len(self.word_list) num_words = self.num_words return num_words test = Word_Parser("mary had a little lamb") test.parser() test.sort_word_list() test.get_num_words() print test.word_list print test.sorted_word_list print test.num_words and returns: ['mary', 'had', 'a', 'little', 'lamb'] ['a', 'had', 'lamb', 'little', 'mary'] 5 Thank you all. A: Bound method error also occurs (in a Django app for instnce) , if you do a thing as below: class Products(models.Model): product_category = models.ForeignKey(ProductCategory, on_delete=models.Protect) def product_category(self) return self.product_category If you name a method, same way you named a field.
What does "bound method" error mean when I call a function?
I am creating a word parsing class and I keep getting a bound method Word_Parser.sort_word_list of <__main__.Word_Parser instance at 0x1037dd3b0> error when I run this: class Word_Parser: """docstring for Word_Parser""" def __init__(self, sentences): self.sentences = sentences def parser(self): self.word_list = self.sentences.split() def sort_word_list(self): self.sorted_word_list = self.word_list.sort() def num_words(self): self.num_words = len(self.word_list) test = Word_Parser("mary had a little lamb") test.parser() test.sort_word_list() test.num_words() print test.word_list print test.sort_word_list print test.num_words
[ "There's no error here. You're printing a function, and that's what functions look like.\nTo actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For example:\nprint test.sort_word_list()\n\nOn the other hand, if you want the function to mutate the object's state, and then print the state some other way, that's fine too.\nNow, your code seems to work in some places, but not others; let's look at why:\n\nparser sets a variable called word_list, and you later print test.word_list, so that works.\nsort_word_list sets a variable called sorted_word_list, and you later print test.sort_word_list—that is, the function, not the variable. So, you see the bound method. (Also, as Jon Clements points out, even if you fix this, you're going to print None, because that's what sort returns.)\nnum_words sets a variable called num_words, and you again print the function—but in this case, the variable has the same name as the function, meaning that you're actually replacing the function with its output, so it works. This is probably not what you want to do, however.\n\n(There are cases where, at first glance, that seems like it might be a good idea—you only want to compute something once, and then access it over and over again without constantly recomputing that. But this isn't the way to do it. Either use a @property, or use a memoization decorator.)\n", "This problem happens as a result of calling a method without brackets. Take a look at the example below:\nclass SomeClass(object):\n def __init__(self):\n print 'I am starting'\n\n def some_meth(self):\n print 'I am a method()'\n\nx = SomeClass()\n''' Not adding the bracket after the method call would result in method bound error '''\nprint x.some_meth\n''' However this is how it should be called and it does solve it '''\nx.some_meth()\n\n", "You have an instance method called num_words, but you also have a variable called num_words. They have the same name. When you run num_words(), the function replaces itself with its own output, which probably isn't what you want to do. Consider returning your values.\nTo fix your problem, change def num_words to something like def get_num_words and your code should work fine. Also, change print test.sort_word_list to print test.sorted_word_list.\n", "For this thing you can use @property as an decorator, so you could use instance methods as attributes. For example:\nclass Word_Parser:\n def __init__(self, sentences):\n self.sentences = sentences\n\n @property\n def parser(self):\n self.word_list = self.sentences.split()\n\n @property\n def sort_word_list(self):\n self.sorted_word_list = self.word_list.sort()\n\n @property\n def num_words(self):\n self.num_words = len(self.word_list)\n\ntest = Word_Parser(\"mary had a little lamb\")\ntest.parser()\ntest.sort_word_list()\ntest.num_words()\nprint test.word_list\nprint test.sort_word_list\nprint test.num_words\n\nso you can use access the attributes without calling (i.e., without the ()).\n", "I think you meant print test.sorted_word_list instead of print test.sort_word_list.\nIn addition list.sort() sorts a list in place and returns None, so you probably want to change sort_word_list() to do the following:\nself.sorted_word_list = sorted(self.word_list)\n\nYou should also consider either renaming your num_words() function, or changing the attribute that the function assigns to, because currently you overwrite the function with an integer on the first call.\n", "The syntax problem is shadowing method and variable names. In the current version sort_word_list() is a method, and sorted_word_list is a variable, whereas num_words is both. Also, list.sort() modifies the list and replaces it with a sorted version; the sorted(list) function actually returns a new list.\nBut I suspect this indicates a design problem. What's the point of calls like \ntest.parser()\ntest.sort_word_list()\ntest.num_words()\n\nwhich don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something.\nE.G.,\ndef sort_word_list(self):\n if self.sorted_word_list is not None:\n self.sorted_word_list = sorted(self.word_list)\n return self.sorted_word_list\n\n(Alternately, you could use properties.)\n", "Your helpful comments led me to the following solution:\nclass Word_Parser:\n \"\"\"docstring for Word_Parser\"\"\"\n def __init__(self, sentences):\n self.sentences = sentences\n\n def parser(self):\n self.word_list = self.sentences.split()\n word_list = []\n word_list = self.word_list\n return word_list\n\n def sort_word_list(self):\n self.sorted_word_list = sorted(self.sentences.split())\n sorted_word_list = self.sorted_word_list\n return sorted_word_list\n\n def get_num_words(self):\n self.num_words = len(self.word_list)\n num_words = self.num_words\n return num_words\n\ntest = Word_Parser(\"mary had a little lamb\")\ntest.parser()\ntest.sort_word_list()\ntest.get_num_words()\nprint test.word_list\nprint test.sorted_word_list\nprint test.num_words\n\nand returns:\n['mary', 'had', 'a', 'little', 'lamb']\n['a', 'had', 'lamb', 'little', 'mary']\n5\nThank you all.\n", "Bound method error also occurs (in a Django app for instnce) , if you do a thing as below:\nclass Products(models.Model):\n product_category = models.ForeignKey(ProductCategory, on_delete=models.Protect)\n\n def product_category(self)\n return self.product_category\n\nIf you name a method, same way you named a field.\n" ]
[ 85, 18, 4, 3, 1, 0, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0013130574_class_python.txt
Q: Moviepy write_videofile works the second time but not the first? I'm concatenating a list of video objects together then writing them with write_videofile, weirdly enough the first time I write the file, it plays fine for the first halfish then the first few frames of each clip in the file afterwards plays before freezing. But here's the odd part, If I write the exact same video object right after the first video writes, it writes just fine and plays perfectly. Here's my code from moviepy.editor import VideoFileClip, concatenate_videoclips clipslist = [] clips = ['https://clips-media-assets2.twitch.tv/AT-cm%7C787619651.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787628097.mp4', 'https://clips-media-assets2.twitch.tv/2222789345-offset-20860.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787624765.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787539697.mp4', 'https://clips-media-assets2.twitch.tv/39235981488-offset-3348.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788412970.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787682495.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787962593.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787627256.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787573008.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788543065.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787593688.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788079881.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788707738.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788021727.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787595029.mp4', 'https://clips-media-assets2.twitch.tv/39233367648-offset-9536.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788517651.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788087743.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787497542.mp4', 'https://clips-media-assets2.twitch.tv/39233367648-offset-9154.mp4', 'https://clips-media-assets2.twitch.tv/7109626012888880881-offset-4818.mp4', 'https://clips-media-assets2.twitch.tv/72389234-offset-760.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787774924.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787565708.mp4'] for clip in clips: dlclip = VideoFileClip(clip, target_resolution=(1080, 1920)) # Download clip clipslist.append(dlclip) videofile = concatenate_videoclips(clipslist) videofile.write_videofile("final1.mp4") # Broken after the first halfish videofile.write_videofile("final2.mp4") # Works entirely fine. videofile.close Any ideas? Any suggestions appreciated. Sometimes when the video is small enough it seems to write the first time just fine too. It seems there is no set point where it breaks, each time I write it for the first time it typically breaks at a different spot. I've tried waiting for the thread to exit and sleeping after the concatenation and that doesn't seem to fix the issue. A: If you cannot consistently replicate the issue, it's most likely not an issue with your code. Try opening the produced clip with a different program, such as VLC. A: I came across with the same problem when writting multiple videos at the same time with write_videofile, it seems like the later tasks will cause the wrong outputs of the previous write_videofile tasks by hanging their writting processes, although the processes will continue after the later tasks finish, the result videos of previous tasks break at the hanging spots, haven't found a solution
Moviepy write_videofile works the second time but not the first?
I'm concatenating a list of video objects together then writing them with write_videofile, weirdly enough the first time I write the file, it plays fine for the first halfish then the first few frames of each clip in the file afterwards plays before freezing. But here's the odd part, If I write the exact same video object right after the first video writes, it writes just fine and plays perfectly. Here's my code from moviepy.editor import VideoFileClip, concatenate_videoclips clipslist = [] clips = ['https://clips-media-assets2.twitch.tv/AT-cm%7C787619651.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787628097.mp4', 'https://clips-media-assets2.twitch.tv/2222789345-offset-20860.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787624765.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787539697.mp4', 'https://clips-media-assets2.twitch.tv/39235981488-offset-3348.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788412970.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787682495.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787962593.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787627256.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787573008.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788543065.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787593688.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788079881.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788707738.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788021727.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787595029.mp4', 'https://clips-media-assets2.twitch.tv/39233367648-offset-9536.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788517651.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C788087743.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787497542.mp4', 'https://clips-media-assets2.twitch.tv/39233367648-offset-9154.mp4', 'https://clips-media-assets2.twitch.tv/7109626012888880881-offset-4818.mp4', 'https://clips-media-assets2.twitch.tv/72389234-offset-760.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787774924.mp4', 'https://clips-media-assets2.twitch.tv/AT-cm%7C787565708.mp4'] for clip in clips: dlclip = VideoFileClip(clip, target_resolution=(1080, 1920)) # Download clip clipslist.append(dlclip) videofile = concatenate_videoclips(clipslist) videofile.write_videofile("final1.mp4") # Broken after the first halfish videofile.write_videofile("final2.mp4") # Works entirely fine. videofile.close Any ideas? Any suggestions appreciated. Sometimes when the video is small enough it seems to write the first time just fine too. It seems there is no set point where it breaks, each time I write it for the first time it typically breaks at a different spot. I've tried waiting for the thread to exit and sleeping after the concatenation and that doesn't seem to fix the issue.
[ "If you cannot consistently replicate the issue, it's most likely not an issue with your code.\nTry opening the produced clip with a different program, such as VLC.\n", "I came across with the same problem when writting multiple videos at the same time with write_videofile, it seems like the later tasks will cause the wrong outputs of the previous write_videofile tasks by hanging their writting processes, although the processes will continue after the later tasks finish, the result videos of previous tasks break at the hanging spots, haven't found a solution\n" ]
[ 0, 0 ]
[]
[]
[ "ffmpeg", "moviepy", "python", "video" ]
stackoverflow_0064542559_ffmpeg_moviepy_python_video.txt
Q: How I can replace values with src.replace method in pandas? I want to replace values in certain column. example of datatable is below, Name of datatable is df column1 column2 aaaa cup bbbb coffee cccc juice dddd tea What I want to this result below column1 column2 aaaa pink bbbb brown cccc orange dddd white So I tried this below df['column2'] = df['column2'].str.replace('cup', 'pink') df['column2'] = df['column2'].str.replace('coffee', 'brown') df['column2'] = df['column2'].str.replace('juice', 'orange') df['column2'] = df['column2'].str.replace('tea', 'white') I got the result with this code, but I think that it's so messy code So I tried this, change_word = { 'cup':'pink' ,'coffee':'brown', 'juice':'orange','tea':'white' } df['column2'].str.replace(change_word, inplace=True) but it doesn't work. Doesn't str.replace method have a function that converts all at once? I tried .replace method but for the .replace method, the entire character must match. So it comes out a little different from the result I want. Is there any idea? A: We can try using str.replace with a callback function: change_word = { 'cup':'pink' ,'coffee':'brown', 'juice':'orange','tea':'white' } regex = r'\b(?:' + r'|'.join(change_word.keys()) + r')\b' df["column2"] = df["column2"].str.replace(regex, lambda m: change_word[m.group()], regex=True) If you are certain that every value in the second column would appear in the dictionary, then you could also use this simplified version: df["column2"] = df["column2"].str.replace(r'\w+', lambda m: change_word[m.group()], regex=True)
How I can replace values with src.replace method in pandas?
I want to replace values in certain column. example of datatable is below, Name of datatable is df column1 column2 aaaa cup bbbb coffee cccc juice dddd tea What I want to this result below column1 column2 aaaa pink bbbb brown cccc orange dddd white So I tried this below df['column2'] = df['column2'].str.replace('cup', 'pink') df['column2'] = df['column2'].str.replace('coffee', 'brown') df['column2'] = df['column2'].str.replace('juice', 'orange') df['column2'] = df['column2'].str.replace('tea', 'white') I got the result with this code, but I think that it's so messy code So I tried this, change_word = { 'cup':'pink' ,'coffee':'brown', 'juice':'orange','tea':'white' } df['column2'].str.replace(change_word, inplace=True) but it doesn't work. Doesn't str.replace method have a function that converts all at once? I tried .replace method but for the .replace method, the entire character must match. So it comes out a little different from the result I want. Is there any idea?
[ "We can try using str.replace with a callback function:\nchange_word = {\n 'cup':'pink' ,'coffee':'brown',\n 'juice':'orange','tea':'white'\n}\nregex = r'\\b(?:' + r'|'.join(change_word.keys()) + r')\\b'\ndf[\"column2\"] = df[\"column2\"].str.replace(regex, lambda m: change_word[m.group()], regex=True)\n\nIf you are certain that every value in the second column would appear in the dictionary, then you could also use this simplified version:\ndf[\"column2\"] = df[\"column2\"].str.replace(r'\\w+', lambda m: change_word[m.group()], regex=True)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074485980_pandas_python.txt
Q: I want to convert a list of lists of tuples to list of dictionaries Input is [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')] The needed output is [{'dayOfweek': 'monday', 'time': ['09:00:00', '17:00:00']}, {'dayOfweek': 'tuesday', 'time': ['09:00:00', '17:00:00']}, {'dayOfweek': 'wednesday', 'time': ['09:00:00', '17:00:00']}] I am a beginner in this please help me out. A: We will use a list comprehension: list1=[('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')] we create a new_list new_list=[{'dayOfweek': list1[i][0], 'time': list(list1[i][1:3])} for i in range(len(list1))] Output >>> print(new_list) [{'dayOfweek': 'monday', 'time': ['09:00:00', '17:00:00']}, {'dayOfweek': 'tuesday', 'time': ['09:00:00', '17:00:00']}, {'dayOfweek': 'wednesday', 'time': ['09:00:00', '17:00:00']}] A: Beginner friendly solution: tuple_list = [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')] dict_list = [] for t in tuple_list: temp_dict = {} temp_dict['dayOfWeek'] = t[0] temp_dict['time'] = [t[1], t[2]] dict_list.append(temp_dict) Output: print(dict_list) [{'dayOfWeek': 'monday', 'time': ['09:00:00', '17:00:00']}, {'dayOfWeek': 'tuesday', 'time': ['09:00:00', '17:00:00']}, {'dayOfWeek': 'wednesday', 'time': ['09:00:00', '17:00:00']}] A: Iterate over the list l_in and build the output list l_out. Each entry is decomposed by using sequence unpacking : day, *time = Here using a list comprehension a Python mechanism to easily create a list. l_in = [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')] l_out = [{"dayOfWeek:": {"day": day, "time": time}} for day, *time in l_in] Here using a "traditional" loop. l_in = [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')] l_out = [] for x in l_in: day, *time = x l_out.append({"dayOfWeek:": {"day": day, "time": time}}) A: The concept is to iterate through all input values and breaking them down to constituent parts. from __future__ import annotations def convert(input:list[tuple])->list[dict]: """ This function takes in a list of tuples and returns a list of dictionaries Use of annotations help you define your input types """ # your output list output=[] for x in input: # dictionary to store each intermediate value dict={} dict['dayOfweek']=x[0] # iterate through the remaining tuples to get the time component dict['time']=[t for t in x[1:]] # add this dictionary record to your output list output.append(dict) print(output) return output
I want to convert a list of lists of tuples to list of dictionaries
Input is [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')] The needed output is [{'dayOfweek': 'monday', 'time': ['09:00:00', '17:00:00']}, {'dayOfweek': 'tuesday', 'time': ['09:00:00', '17:00:00']}, {'dayOfweek': 'wednesday', 'time': ['09:00:00', '17:00:00']}] I am a beginner in this please help me out.
[ "We will use a list comprehension:\nlist1=[('monday', '09:00:00', '17:00:00'), \n('tuesday', '09:00:00', '17:00:00'), \n('wednesday', '09:00:00', '17:00:00')]\n\nwe create a new_list\nnew_list=[{'dayOfweek': list1[i][0], 'time': list(list1[i][1:3])} for i in range(len(list1))]\n\nOutput\n>>> print(new_list)\n\n[{'dayOfweek': 'monday', 'time': ['09:00:00', '17:00:00']},\n {'dayOfweek': 'tuesday', 'time': ['09:00:00', '17:00:00']},\n {'dayOfweek': 'wednesday', 'time': ['09:00:00', '17:00:00']}]\n\n", "Beginner friendly solution:\ntuple_list = [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')]\ndict_list = []\nfor t in tuple_list:\n temp_dict = {}\n temp_dict['dayOfWeek'] = t[0]\n temp_dict['time'] = [t[1], t[2]]\n dict_list.append(temp_dict)\n\nOutput:\nprint(dict_list)\n\n[{'dayOfWeek': 'monday', 'time': ['09:00:00', '17:00:00']},\n {'dayOfWeek': 'tuesday', 'time': ['09:00:00', '17:00:00']},\n {'dayOfWeek': 'wednesday', 'time': ['09:00:00', '17:00:00']}]\n\n", "Iterate over the list l_in and build the output list l_out.\nEach entry is decomposed by using sequence unpacking : day, *time =\nHere using a list comprehension a Python mechanism to easily create a list.\nl_in = [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')]\nl_out = [{\"dayOfWeek:\": {\"day\": day, \"time\": time}} for day, *time in l_in]\n\nHere using a \"traditional\" loop.\nl_in = [('monday', '09:00:00', '17:00:00'), ('tuesday', '09:00:00', '17:00:00'), ('wednesday', '09:00:00', '17:00:00')]\nl_out = []\nfor x in l_in:\n day, *time = x\n l_out.append({\"dayOfWeek:\": {\"day\": day, \"time\": time}})\n\n\n", "The concept is to iterate through all input values and breaking them down to constituent parts.\nfrom __future__ import annotations\n\ndef convert(input:list[tuple])->list[dict]:\n \"\"\"\n This function takes in a list of tuples and returns a list of dictionaries\n\n Use of annotations help you define your input types\n \"\"\"\n # your output list\n output=[]\n for x in input:\n # dictionary to store each intermediate value\n dict={}\n dict['dayOfweek']=x[0]\n\n # iterate through the remaining tuples to get the time component\n dict['time']=[t for t in x[1:]]\n\n # add this dictionary record to your output list\n output.append(dict)\n\n print(output)\n return output\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "dictionary_comprehension", "list", "nested_lists", "python" ]
stackoverflow_0074485821_dictionary_dictionary_comprehension_list_nested_lists_python.txt
Q: selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python I am currently working on a project which fills a form automatically. And the next button appears when the form is filled, that's why it gives me an error. I have tried: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//input[@type='button' and @class='button']"))) Next = driver.find_element_by_xpath("//input[@type='button' and @class='button']") Next.click() HTML: <span class="btn"> <input type="button" value="Next" class="button" payoneer="Button" data-controltovalidate="PersonalDetails" data-onfieldsvalidation="ToggleNextButton" data-onclick="UpdateServerWithCurrentSection();" id="PersonalDetailsButton"> </input> <div class="clearfix"></div> </span> ERROR: selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (203, 530). Other element would receive the click: ... (Session info: chrome=76.0.3809.132) A: If the path of the xpath is right, maybe you can try this method to solve this problem. Replace the old code with the following code: button = driver.find_element_by_xpath("xpath") driver.execute_script("arguments[0].click();", button) I solved this problem before, but to be honestly, I don't know the reason. A: This error message... selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (203, 530). Other element would receive the click: ... (Session info: chrome=76.0.3809.132) ...implies that the click() on the desired element was intercepted by some other element and the desired element wasn't clickable. There are a couple of things which you need to consider as follows: While using Selenium for automation using time.sleep(secs) without any specific condition to achieve defeats the purpose of automation and should be avoided at any cost. As per the documentation: time.sleep(secs) suspends the execution of the current thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. You can find a detailed discussion in How to sleep webdriver in python for milliseconds As WebDriverWait returns the WebElement you can invoke the click() method directly. Solution To click on the button with value as Next you can use either of the following Locator Strategies: Using CSS_SELECTOR: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.button#PersonalDetailsButton[data-controltovalidate='PersonalDetails']"))).click() Using XPATH: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='button' and @id='PersonalDetailsButton'][@data-controltovalidate='PersonalDetails']"))).click() Note : You have to add the following imports : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC A: i faced similar issues, the .click() always returns a Not clickable exception. the driver.execute_script('arguments[0].click()', button) does the magic. You can also use it to execute any other js script this way script = 'your JavaScript goes here' element = driver.find_element_by_*('your element identifier goes here') driver.execute_script(script, element) A: I looked at the exact element that was causing it and it was a banner about consent/cookies. So at first, I made sure it clicked "OK" on the consent banner and then I clicked the other button that I needed. Hope it helps someone. A: It look's like there are some other elements which are having the same xpath try changing the xpath something like this Next = driver.find_element_by_xpath("//input[@id='PersonalDetailsButton']"); Next.Click(); or Next = driver.find_element_by_xpath(//input[@value='Next' and @id='PersonalDetailsButton']); Next.Click(); Try first xpath if that doesn't work go with the second one . If that also doesn't work try using sikuli. I am pretty sure that first xpath will work A: I faced a similar issue and I observed something that might help to understand the root cause of the issue. In my case, I was able to click at an element being in PC view mode of the website but failed to do so in mobile view (in which I needed my script to run). I found out that in mobile view, ordering of elements (li in my case) changed in view while they remained same in the html document. That's why I was not able to click on it without actually scrolling to it first. It might also explain why this works: - driver.execute_script("arguments[0].click();", button) A: I don't have enough rep to comment but the common reason for this error might be Selenium locates the element from DOM on screen and locate the x-y coordinates (300, 650) then clicks on them but if some changes takes place on screen in between the click duration, for example google ads or some pop-up then it's unable to click on it resulting in this exception I'm just guessing if anyone has a proper explanation to pls share A: I had the same problem too. But my problem was not with the element. The button was activated with href. I changed the code from <a class="services-button" href="desired url"> To <a class="services-button" onclick="location.href='{% url "desired url" %}'";"> A: This solution worked for me : from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Firefox(executable_path="") driver.get("https://UrlToOpen") action = ActionChains(driver) firstLevelMenu = driver.find_element_by_id("menu") firstLevelMenu.click() source : http://allselenium.info/mouse-over-actions-using-python-selenium-webdriver/ A: "selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable ... " This exception occurs when element is not found on a web page (When the element we are looking for is at bottom part of the page which is not loaded yet) So we you can scroll the page using javascript and load complete page and from selenium.webdriver.common.by import By from selenium import webdriver url = "YOUR URL" SCROLL_PAUSE_TIME = 0.5 driver = webdriver.Chrome() driver.maximize_window() driver.get(url) def scroll_page(): i = 0 while i < 5: # Scroll down to 500 pixel driver.execute_script("window.scrollBy(0, 500)", "") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Will scroll only for 4 increments of 500px i += 1
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python
I am currently working on a project which fills a form automatically. And the next button appears when the form is filled, that's why it gives me an error. I have tried: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//input[@type='button' and @class='button']"))) Next = driver.find_element_by_xpath("//input[@type='button' and @class='button']") Next.click() HTML: <span class="btn"> <input type="button" value="Next" class="button" payoneer="Button" data-controltovalidate="PersonalDetails" data-onfieldsvalidation="ToggleNextButton" data-onclick="UpdateServerWithCurrentSection();" id="PersonalDetailsButton"> </input> <div class="clearfix"></div> </span> ERROR: selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (203, 530). Other element would receive the click: ... (Session info: chrome=76.0.3809.132)
[ "If the path of the xpath is right, maybe you can try this method to solve this problem. Replace the old code with the following code:\nbutton = driver.find_element_by_xpath(\"xpath\")\ndriver.execute_script(\"arguments[0].click();\", button)\n\nI solved this problem before, but to be honestly, I don't know the reason.\n", "\n\n\nThis error message...\nselenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (203, 530). Other element would receive the click: ... (Session info: chrome=76.0.3809.132)\n\n...implies that the click() on the desired element was intercepted by some other element and the desired element wasn't clickable.\n\nThere are a couple of things which you need to consider as follows:\n\nWhile using Selenium for automation using time.sleep(secs) without any specific condition to achieve defeats the purpose of automation and should be avoided at any cost. As per the documentation:\n\n\ntime.sleep(secs) suspends the execution of the current thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.\n\n\nYou can find a detailed discussion in How to sleep webdriver in python for milliseconds\nAs WebDriverWait returns the WebElement you can invoke the click() method directly.\n\n\nSolution\nTo click on the button with value as Next you can use either of the following Locator Strategies:\n\nUsing CSS_SELECTOR:\nWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"input.button#PersonalDetailsButton[data-controltovalidate='PersonalDetails']\"))).click()\n\nUsing XPATH:\nWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, \"//input[@class='button' and @id='PersonalDetailsButton'][@data-controltovalidate='PersonalDetails']\"))).click()\n\nNote : You have to add the following imports :\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n", "i faced similar issues, the .click() always returns a Not clickable exception. the\ndriver.execute_script('arguments[0].click()', button)\n\ndoes the magic. You can also use it to execute any other js script this way\nscript = 'your JavaScript goes here'\nelement = driver.find_element_by_*('your element identifier goes here')\ndriver.execute_script(script, element)\n\n", "I looked at the exact element that was causing it and it was a banner about consent/cookies. So at first, I made sure it clicked \"OK\" on the consent banner and then I clicked the other button that I needed. Hope it helps someone. \n", "It look's like there are some other elements which are having the same xpath try changing the xpath something like this \nNext = driver.find_element_by_xpath(\"//input[@id='PersonalDetailsButton']\");\nNext.Click();\n\nor \nNext = driver.find_element_by_xpath(//input[@value='Next' and @id='PersonalDetailsButton']);\nNext.Click();\n\nTry first xpath if that doesn't work go with the second one . If that also doesn't work try using sikuli. I am pretty sure that first xpath will work \n", "I faced a similar issue and I observed something that might help to understand the root cause of the issue. In my case, I was able to click at an element being in PC view mode of the website but failed to do so in mobile view (in which I needed my script to run). I found out that in mobile view, ordering of elements (li in my case) changed in view while they remained same in the html document. That's why I was not able to click on it without actually scrolling to it first. It might also explain why this works: -\ndriver.execute_script(\"arguments[0].click();\", button)\n\n", "I don't have enough rep to comment but the common reason for this error might be Selenium locates the element from DOM on screen and locate the x-y coordinates (300, 650) then clicks on them but if some changes takes place on screen in between the click duration, for example google ads or some pop-up then it's unable to click on it resulting in this exception\nI'm just guessing if anyone has a proper explanation to pls share\n", "I had the same problem too. But my problem was not with the element. The button was activated with href. I changed the code from\n<a class=\"services-button\" href=\"desired url\">\n\nTo\n<a class=\"services-button\" onclick=\"location.href='{% url \"desired url\" %}'\";\">\n\n", "This solution worked for me :\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\ndriver = webdriver.Firefox(executable_path=\"\")\ndriver.get(\"https://UrlToOpen\") \naction = ActionChains(driver)\n\nfirstLevelMenu = driver.find_element_by_id(\"menu\")\nfirstLevelMenu.click()\n\nsource : http://allselenium.info/mouse-over-actions-using-python-selenium-webdriver/\n", "\n\"selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable ... \"\n\nThis exception occurs when element is not found on a web page (When the element we are looking for is at bottom part of the page which is not loaded yet)\nSo we you can scroll the page using javascript and load complete page and\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\n\nurl = \"YOUR URL\"\nSCROLL_PAUSE_TIME = 0.5\ndriver = webdriver.Chrome()\ndriver.maximize_window()\ndriver.get(url)\n\ndef scroll_page():\n i = 0\n while i < 5:\n # Scroll down to 500 pixel\n driver.execute_script(\"window.scrollBy(0, 500)\", \"\")\n\n # Wait to load page\n time.sleep(SCROLL_PAUSE_TIME)\n\n # Will scroll only for 4 increments of 500px\n i += 1\n\n" ]
[ 70, 6, 4, 1, 0, 0, 0, 0, 0, 0 ]
[ "You could try:\ndriver.execute_script(\"arguments[0].click();\", button)\n\n\nThis solution solved my problems when I faced similar issues.\n" ]
[ -1 ]
[ "css_selectors", "python", "selenium", "webdriverwait", "xpath" ]
stackoverflow_0057741875_css_selectors_python_selenium_webdriverwait_xpath.txt
Q: Calculating YTD change for weekly data I have a table with weekly data like below: Date A B C D 1/1/2022 4 5 5 2 1/7/2022 3 5 9 4 1/14/2022 4 8 5 6 1/21/2022 4 6 1 4 I want to create an YTD change table like the below where YTD change is calculated as ('last value of the year' - 'first value of the year') / 'first value of the year' (i.e., basic % change). I have just started out so am not sure how to approach this in the most efficient manner. Desired output format: Date A B C D 2022 x x x x 2021 x x x x 2020 x x x x 2019 x x x x A: You could achieve this by using groupby with apply (the pct_change method is closely related by can only be applied on consecutive rows in a group). df['Date'] = pd.to_datetime(df['Date']) df = df.sort_values('Date').set_index('Date') df.groupby(df.index.year).apply(lambda x: x.iloc[-1].subtract(x.iloc[0]).div(x.iloc[0])) Result on the sample data: A B C D Date 2022 0.0 0.2 -0.8 1.0
Calculating YTD change for weekly data
I have a table with weekly data like below: Date A B C D 1/1/2022 4 5 5 2 1/7/2022 3 5 9 4 1/14/2022 4 8 5 6 1/21/2022 4 6 1 4 I want to create an YTD change table like the below where YTD change is calculated as ('last value of the year' - 'first value of the year') / 'first value of the year' (i.e., basic % change). I have just started out so am not sure how to approach this in the most efficient manner. Desired output format: Date A B C D 2022 x x x x 2021 x x x x 2020 x x x x 2019 x x x x
[ "You could achieve this by using groupby with apply (the pct_change method is closely related by can only be applied on consecutive rows in a group).\ndf['Date'] = pd.to_datetime(df['Date'])\ndf = df.sort_values('Date').set_index('Date')\ndf.groupby(df.index.year).apply(lambda x: x.iloc[-1].subtract(x.iloc[0]).div(x.iloc[0]))\n\nResult on the sample data:\n A B C D\nDate \n2022 0.0 0.2 -0.8 1.0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074485885_dataframe_pandas_python.txt
Q: Spectral and Spatial Measures of Sharpness - How to calculate slope of magnitude spectrum? I am trying to implement the S1 measure (Spectral Measure of Sharpness - Section III-A) from this paper. Here we have to calculate slope (alpha) of the magnitude spectrum for an image in order to measure sharpness. I am able to write the other part of the algorithm, but unable to calculate the slope. Here is my code. Function 'alpha' is where I calculate the magnitude_spectrum and I think using this we can calculate the slope but am not sure how to do that - def aplha(image_block): img_float32 = np.float32(image_block) dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT) dft_shift = np.fft.fftshift(dft) magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1])) return output (??) Rest of the code: def S1_calc(alpha): tou1 = -3 tou2 = 2 output = 1 - (1 / (1 + np.exp(tou1 * (alpha - tou2)))) return output def lx(image_block): b = 0.7656 k = 0.0364 y = 2.2 return np.power((b + k * image_block), y) def contrast(lx_val): T1 = 5 T2 = 2 max_val = np.max(lx_val) min_val = np.min(lx_val) mean_val = np.mean(lx_val) return (((max_val - min_val) < T1) or (mean_val < T2)) def image_gray(image_RGB): output = (0.2989 * image_RGB[:,:,0] + 0.5870 * image_RGB[:,:,1] + 0.1140 * image_RGB[:,:,2]) return output def S1(gray_image, m = 32, d = 24): ### SPECTRAL MEASURE OF SHARPNESS ### # m = each block size # d = overlapping pixels of neighbouring blocks h,w = gray_image.shape output = gray_image.copy() row = 0 while (row < h): col = 0 while (col < w): top = row bottom = min(row + m, h) left = col right = min(col + m, w) image_block = gray_image[top : bottom, left : right] lx_val = lx(image_block) contrast_bool = contrast(lx_val) if contrast_bool==True: output[top : bottom, left : right] = 0 else: alpha_val = aplha(image_block) output[top : bottom, left : right] = S1_calc(alpha_val) col = col + m - d row = row + m - d return output Am using jupyter notebook, python 3.6 A: You could check this MATLAB code. See also another MATLAB code. According to the latter one, we need to know freq and power value, and then we could fit these two var with a linear function, the slope of the line is what we need. We could get the slope with np.polyfit. Now, our question is how to get the freq of a image, you could do this: from skimage.data import camera import numpy as np image = camera() height, width = image.shape u, v = np.meshgrid(np.arange(height // 2), np.arange(width // 2)) freq = np.round(np.sqrt(u**2 + v**2)).astype(np.int64) Now freq should be the same shape as fft transform of the input image. You need to sum all value of the magnitude_spectrum where they have the same freq, like this: freq_uniq = np.unique(freq.flatten()) y = [] for value in f_uniq: y.append(magnitude_spectrum[f == value].sum()) y = np.array(y) Finally, you could just fit freq_uniq and y and get the slope. You might need to scale them with np.log first.
Spectral and Spatial Measures of Sharpness - How to calculate slope of magnitude spectrum?
I am trying to implement the S1 measure (Spectral Measure of Sharpness - Section III-A) from this paper. Here we have to calculate slope (alpha) of the magnitude spectrum for an image in order to measure sharpness. I am able to write the other part of the algorithm, but unable to calculate the slope. Here is my code. Function 'alpha' is where I calculate the magnitude_spectrum and I think using this we can calculate the slope but am not sure how to do that - def aplha(image_block): img_float32 = np.float32(image_block) dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT) dft_shift = np.fft.fftshift(dft) magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1])) return output (??) Rest of the code: def S1_calc(alpha): tou1 = -3 tou2 = 2 output = 1 - (1 / (1 + np.exp(tou1 * (alpha - tou2)))) return output def lx(image_block): b = 0.7656 k = 0.0364 y = 2.2 return np.power((b + k * image_block), y) def contrast(lx_val): T1 = 5 T2 = 2 max_val = np.max(lx_val) min_val = np.min(lx_val) mean_val = np.mean(lx_val) return (((max_val - min_val) < T1) or (mean_val < T2)) def image_gray(image_RGB): output = (0.2989 * image_RGB[:,:,0] + 0.5870 * image_RGB[:,:,1] + 0.1140 * image_RGB[:,:,2]) return output def S1(gray_image, m = 32, d = 24): ### SPECTRAL MEASURE OF SHARPNESS ### # m = each block size # d = overlapping pixels of neighbouring blocks h,w = gray_image.shape output = gray_image.copy() row = 0 while (row < h): col = 0 while (col < w): top = row bottom = min(row + m, h) left = col right = min(col + m, w) image_block = gray_image[top : bottom, left : right] lx_val = lx(image_block) contrast_bool = contrast(lx_val) if contrast_bool==True: output[top : bottom, left : right] = 0 else: alpha_val = aplha(image_block) output[top : bottom, left : right] = S1_calc(alpha_val) col = col + m - d row = row + m - d return output Am using jupyter notebook, python 3.6
[ "You could check this MATLAB code. See also another MATLAB code.\nAccording to the latter one, we need to know freq and power value, and then we could fit these two var with a linear function, the slope of the line is what we need. We could get the slope with np.polyfit.\nNow, our question is how to get the freq of a image, you could do this:\nfrom skimage.data import camera\nimport numpy as np\n\nimage = camera()\nheight, width = image.shape\nu, v = np.meshgrid(np.arange(height // 2), np.arange(width // 2))\nfreq = np.round(np.sqrt(u**2 + v**2)).astype(np.int64)\n\nNow freq should be the same shape as fft transform of the input image. You need to sum all value of the magnitude_spectrum where they have the same freq, like this:\nfreq_uniq = np.unique(freq.flatten())\ny = []\nfor value in f_uniq:\n y.append(magnitude_spectrum[f == value].sum())\ny = np.array(y)\n\nFinally, you could just fit freq_uniq and y and get the slope. You might need to scale them with np.log first.\n" ]
[ 0 ]
[]
[]
[ "dft", "fft", "image_processing", "python", "signal_processing" ]
stackoverflow_0054825974_dft_fft_image_processing_python_signal_processing.txt