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:
Replacing strings with special characters in pandas dataframe
I'm looking to replace strings inside DataFrame columns, these strings contain special characters.
I tried the following, but nothing changed in the DataFrame:
data = {'col1': ["series ${z_mask0}", "series ${z_mask1}", "series ${z_mask2}"]}
df = pd.Dat... | Replacing strings with special characters in pandas dataframe | I'm looking to replace strings inside DataFrame columns, these strings contain special characters.
I tried the following, but nothing changed in the DataFrame:
data = {'col1': ["series ${z_mask0}", "series ${z_mask1}", "series ${z_mask2}"]}
df = pd.DataFrame(data)
print(df)
old_values = ["${z_mask0}", "${z_mask1}", "... | [
"You need to escape the $ character using \\ in the old_values list:\nold_values = [\"\\${z_mask0}\", \"\\${z_mask1}\", \"\\${z_mask2}\"]\n\nThe above should be enough. Here is all the code:\nold_values = [\"\\${z_mask0}\", \"\\${z_mask1}\", \"\\${z_mask2}\"]\nnew_values = [\"${z_00}\", \"${z_01}\", \"${z_02}\"]\nd... | [
2,
0
] | [] | [] | [
"dataframe",
"python",
"replace"
] | stackoverflow_0074197645_dataframe_python_replace.txt |
Q:
A query to find or create relationship and increment its count property by one
I want to count "the number of times a node is connected to another node".
It seemed a bad idea to have multiple redundant relationships between the two same nodes, so I thought I should use a single relationship with a "count" property... | A query to find or create relationship and increment its count property by one | I want to count "the number of times a node is connected to another node".
It seemed a bad idea to have multiple redundant relationships between the two same nodes, so I thought I should use a single relationship with a "count" property for this purpose.
But how to update those relationships and increment the property ... | [
"Things to consider:\n\nThe statement below DOES NOT work when using a parameterized query. So your query is not returning data after this statement. Thus, no relationship will be created in the last line\n\n\nMATCH (s)-[r:$relationship_type]->(n)\n\nFix: You need to do a string replace using python when the varia... | [
1
] | [] | [] | [
"cypher",
"neo4j",
"neo4j_apoc",
"python"
] | stackoverflow_0074185400_cypher_neo4j_neo4j_apoc_python.txt |
Q:
Why is my function not removing the last occurrence of elements from the list?
I am trying to implement a function that removes all the occurrences of a given number from a list using in-place. I tried this:
def removeElement(L, n):
for i in L:
if i == n:
L.remove(i)
return L
L = [1,1,2,3,3,3,4,3]
... | Why is my function not removing the last occurrence of elements from the list? | I am trying to implement a function that removes all the occurrences of a given number from a list using in-place. I tried this:
def removeElement(L, n):
for i in L:
if i == n:
L.remove(i)
return L
L = [1,1,2,3,3,3,4,3]
n = 3
v = removeElement(L,n)
print(v)
However it is not removing the last occurrenc... | [
"You should use remove() to remove a certain number from an array, not a position.\ndef remove_elements(num_list, item):\n\n items_count = num_list.count(item)\n for i in range(items_count):\n num_list.remove(item)\n\n return num_list\n\nnum_list = [1,1,2,3,3,3,4,3]\nitem = 3\nprint(remove_elements(... | [
3,
0
] | [] | [] | [
"duplicates",
"in_place",
"list",
"python"
] | stackoverflow_0074197405_duplicates_in_place_list_python.txt |
Q:
Why there are two different flags to disable gradient computation in PyTorch
I am an intermediate learner in PyTorch and in some recent cases, I have seen people use the torch.inference_mode() instead of the famous torch.no_grad() while validating your trained agent in reinforcement learning (RL) experiments. I ch... | Why there are two different flags to disable gradient computation in PyTorch | I am an intermediate learner in PyTorch and in some recent cases, I have seen people use the torch.inference_mode() instead of the famous torch.no_grad() while validating your trained agent in reinforcement learning (RL) experiments. I checked the documentation and they have a table that consists of two flags to disabl... | [
"So I have been scraping the web for a few days and I think I got my explanation. The torch.inference() mode has been added as an even more optimized way of doing inference with PyTorch (versus the torch.no_grad()). I listened to the PyTorch podcast and they have an explanation as to why there exists to different f... | [
0
] | [] | [] | [
"autograd",
"python",
"pytorch"
] | stackoverflow_0074191070_autograd_python_pytorch.txt |
Q:
what is the using of Signals in Django?
I'm new to Django and I'm watching a tutorial on youtube, and I have a problem, he using ready functions I don't understand what is the meaning of these functions.
my question is .. can anyone explain the (Signals, Senders, and receivers) and their use?
if you can recommend... | what is the using of Signals in Django? | I'm new to Django and I'm watching a tutorial on youtube, and I have a problem, he using ready functions I don't understand what is the meaning of these functions.
my question is .. can anyone explain the (Signals, Senders, and receivers) and their use?
if you can recommend someone course for Django I will appreciate ... | [
"Honestly this isn't too bad, I like their example:\nhttps://www.geeksforgeeks.org/how-to-create-and-use-signals-in-django/\n^ Their Example:\n\nSender: When User is Created\nReceiver: Create User Profile for newly Created User\n\nAlso reading the Docs is always a good idea:\nTopic: https://docs.djangoproject.com/e... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074197507_django_python.txt |
Q:
How to get the slope for every n days per group with respect to a conditioned row using Pandas?
I have the following dataframe (sample):
import pandas as pd
n = 3
data = [['A', '2022-09-01', False, 2, -3], ['A', '2022-09-02', False, 1, -2], ['A', '2022-09-03', False, 1, -1], ['A', '2022-09-04', True, 3, 0],
... | How to get the slope for every n days per group with respect to a conditioned row using Pandas? | I have the following dataframe (sample):
import pandas as pd
n = 3
data = [['A', '2022-09-01', False, 2, -3], ['A', '2022-09-02', False, 1, -2], ['A', '2022-09-03', False, 1, -1], ['A', '2022-09-04', True, 3, 0],
['A', '2022-09-05', False, 3, 1], ['A', '2022-09-06', False, 2, 2], ['A', '2022-09-07', False, 1... | [
"This does the job but I don't know if there is any fancier pandas way of doing things.\ngroups=['A','B']\nindexs=[]\nfor i in groups:\n indexs.append(df.loc[(df['group'] == i )& (df['indicator']== True)].index[0])\nid2=[]\nid3=[]\nfor i in groups:\n id2=df.loc[(df['group'] == i )].index[:]-indexs[groups.inde... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074098617_dataframe_pandas_python.txt |
Q:
Python - grouping with conditions
I'm looking for an elegant approach to the following problem.
Working from a DataFrame with 15 columns and 1250 rows of chemical compound information (1250 compounds). One particular column named "molecular_mass" has numbers which I would like to use as a handle to create groups c... | Python - grouping with conditions | I'm looking for an elegant approach to the following problem.
Working from a DataFrame with 15 columns and 1250 rows of chemical compound information (1250 compounds). One particular column named "molecular_mass" has numbers which I would like to use as a handle to create groups containing 100 compounds each, where the... | [
"(First post in SO. Help me out on what I can do better. This is NOT an numpy answer, but I'm hoping this helps anyway)\nFor my solution I'd create an empty dict to store the groups of compounds and loop over the data given in the table while checking (or iterating) each group for the two conditions you described.\... | [
1
] | [] | [] | [
"grouping",
"python"
] | stackoverflow_0069564135_grouping_python.txt |
Q:
Dynamically define a Union of Literal string permutations in Python
I have a list of strings:
strings = ['a','b','c']
I want to declare a Union of Literal types of all the possible ordered pairs of the list. Hardcoded, this would look like:
CustomType = Literal[
'ab', 'ac', 'aa',
'ba', 'bb', 'bc',
'ca', 'cb... | Dynamically define a Union of Literal string permutations in Python | I have a list of strings:
strings = ['a','b','c']
I want to declare a Union of Literal types of all the possible ordered pairs of the list. Hardcoded, this would look like:
CustomType = Literal[
'ab', 'ac', 'aa',
'ba', 'bb', 'bc',
'ca', 'cb', 'cc'
]
How could I define CustomType dynamically such that I don't ha... | [
"The exact approach you're looking for is not possible in Python [yet], according to the mypy docs.\nOfficial code interacts with some similar issues, and the answer is just to write out every permutation, like official stubs in typeshed by core team do.\nHowever, you can get close using something like a Sequence:\... | [
3,
1
] | [] | [] | [
"pylance",
"python",
"python_3.x",
"python_typing",
"typing"
] | stackoverflow_0074075558_pylance_python_python_3.x_python_typing_typing.txt |
Q:
I cannot run any project because of gyp error. How can I fix this: npm ERR! gyp verb cli
Whenever I run my code I always get the same error. I uninstall node and npm and reinstall. But now there is no "node_modules" and I get the same error. How can I fix it?
npm ERR! code 1
npm ERR! path /Users/bng/Desktop/deneme... | I cannot run any project because of gyp error. How can I fix this: npm ERR! gyp verb cli | Whenever I run my code I always get the same error. I uninstall node and npm and reinstall. But now there is no "node_modules" and I get the same error. How can I fix it?
npm ERR! code 1
npm ERR! path /Users/bng/Desktop/deneme/12-vue-spa/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts... | [
"I solved this problem by changing the node version to 14.15.1\n",
"Please don't waste your time running the suggested command by others.\nPlease uninstall node.js and use the Node v14.x.\nIt will solve it automatically.\n",
"Do not use node-sass anymore. Remove 'node-sass' in package.json. pls use 'dart-sass'.... | [
8,
4,
2,
1,
1,
0
] | [] | [] | [
"javascript",
"node.js",
"npm",
"python",
"vue.js"
] | stackoverflow_0071599040_javascript_node.js_npm_python_vue.js.txt |
Q:
Question about sorting by date inside a database using Django
I have a database, in which it's possible to find products by their name. The DB has ID, category, name, amount and date defined, and I was trying to create a separate search field that would let me search those items by the date they were added.
The mo... | Question about sorting by date inside a database using Django | I have a database, in which it's possible to find products by their name. The DB has ID, category, name, amount and date defined, and I was trying to create a separate search field that would let me search those items by the date they were added.
The models.py looks like this:
class Expense(models.Model):
class Met... | [
"I think the behaviour you're looking for is described I. The django documentation here:\nhttps://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.DateField.auto_now\nDateField\nfield_name = DateField(auto_now=False, auto_now_add=False, **options)\n\nA date, represented in Python by a datetime.date... | [
0
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0074196609_database_django_python.txt |
Q:
Key Error when retriving values from a dictionary in a function even when the key exists
def country():
country_url= 'https://restcountries.com/v3.1/name/india'
request = urllib.request.urlopen(country_url)
result = json.loads(request.read())
for values in result:
print(values['currencies'])
indian... | Key Error when retriving values from a dictionary in a function even when the key exists | def country():
country_url= 'https://restcountries.com/v3.1/name/india'
request = urllib.request.urlopen(country_url)
result = json.loads(request.read())
for values in result:
print(values['currencies'])
indian_currency= values['currencies']['INR']['name']
capital= values["capital"]
for capi... | [
"Well I have looked at the data. In one there is 'INR' in another there is 'USD'.\nYou should write an if/else statement.\nif 'INR' in values['currencies']:\n indian_currency= values['currencies']['INR']['name']\nelse:\n indian_currency = ''\n\n",
"Well in data, there are two keys INR and USD, you are tryi... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074197477_python.txt |
Q:
azureml score.py not reading additional json file
I have a json file which I am using in score.py however, it is not being found. When making a post request to the endpoint I get the following error "No such file or directory: '/var/azureml-app/model_adjustments.json'"
json file is in the same folder as score.py... | azureml score.py not reading additional json file | I have a json file which I am using in score.py however, it is not being found. When making a post request to the endpoint I get the following error "No such file or directory: '/var/azureml-app/model_adjustments.json'"
json file is in the same folder as score.py and calling it from a script
path_to_source="path/exam... | [
"I have had not time to try this out, but I would assume that the score.py file (and any files in the same directory) will not be in the os.getcwd().\nI would try to use __file__ to get the path of score.py:\nso, instead of:\ncurrent_directory = os.getcwd()\nfile_name=\"model_adjustments.json\"\njson_file=os.path.j... | [
2
] | [] | [] | [
"azure_machine_learning_service",
"azureml_python_sdk",
"azuremlsdk",
"json",
"python"
] | stackoverflow_0074195903_azure_machine_learning_service_azureml_python_sdk_azuremlsdk_json_python.txt |
Q:
Looping through a dictionary to print out statements based on number of items in the list from the dictionary values
I am trying to figure out how to an if/else or if/elif statement along with a for loop in python to loop through a program to print out a statement based on the number of items in a list for the val... | Looping through a dictionary to print out statements based on number of items in the list from the dictionary values | I am trying to figure out how to an if/else or if/elif statement along with a for loop in python to loop through a program to print out a statement based on the number of items in a list for the value from the key value pairs.
.
favoritePlaces = {
'tom': ['alaska', 'wales', 'italy',],
'rory': ['hawaii',],
'... | [
"You can check whether places is None or an empty list:\nfavoritePlaces = {\n 'tom': ['alaska', 'wales', 'italy',],\n 'rory': ['hawaii',],\n 'frank': ['greenland', 'south africa',],\n 'test1': None,\n 'test2': [],\n }\n\nfor person, places in favoritePlaces.items():\n if places:\n print(... | [
0,
0
] | [] | [] | [
"dictionary",
"for_loop",
"if_statement",
"list",
"python"
] | stackoverflow_0074197943_dictionary_for_loop_if_statement_list_python.txt |
Q:
The running time per epoch keeps increasing when using code torch.autograd.grad()
I am using torch.autograd.grad() function to calculate the grads for two loss functions (which is used to balance the weight of these two loss),
loss1_grads = torch.autograd.grad(loss1, model.parameters(), retain_graph=True)
loss2_g... | The running time per epoch keeps increasing when using code torch.autograd.grad() | I am using torch.autograd.grad() function to calculate the grads for two loss functions (which is used to balance the weight of these two loss),
loss1_grads = torch.autograd.grad(loss1, model.parameters(), retain_graph=True)
loss2_grads = torch.autograd.grad(loss2, model.parameters(), retain_graph=True)
.....
loss = l... | [] | [] | [
"So there are two different flags in torch.autograd which helps in remembering the gradients of the variables in your code.\n\nWhen we use requires_grad=True, PyTorch remembers the gradients till you call the backward() function and updates the variables and flushes out the gradients after calculations are over.\nI... | [
-1
] | [
"autograd",
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074197848_autograd_deep_learning_python_pytorch.txt |
Q:
Pandas regex row by row
i' m here to describe my problem: i have to do a lot of change in my pandas dataframe. To be clearer i try to explain better. I have a pandas dataframe of shape (1914163, 16). Among this columns, there is one column named ' MODELLO' which has a lot of values that i have to normalize. Saying... | Pandas regex row by row | i' m here to describe my problem: i have to do a lot of change in my pandas dataframe. To be clearer i try to explain better. I have a pandas dataframe of shape (1914163, 16). Among this columns, there is one column named ' MODELLO' which has a lot of values that i have to normalize. Saying normalize i mean that there ... | [
"I managed to write code which I assume would fit your need:\nimport re\nimport pandas as pd\n\ndef replacer(arg):\n result = pd.NA\n if match := re.search(r'(RC+\\d*)+-+\\d*', arg):\n result = match.group(1)\n elif match := re.search(r'CESPRO 998 Cl', arg):\n result = \"R0998Cl\"\n return... | [
1
] | [] | [] | [
"pandas",
"python",
"regex"
] | stackoverflow_0074197861_pandas_python_regex.txt |
Q:
NotImplementedError: Conversion 'py2rpy' not defined for objects of type ''
I'm building a Plotly Dash in Python and I need to use the rpy2 package to import some functions not supported in Python, so I get this error when I call (%R-i df) in the dash,
The strange thing is that the R code works fine outside the da... | NotImplementedError: Conversion 'py2rpy' not defined for objects of type '' | I'm building a Plotly Dash in Python and I need to use the rpy2 package to import some functions not supported in Python, so I get this error when I call (%R-i df) in the dash,
The strange thing is that the R code works fine outside the dash, but with it it cannot totally implement any code of R.
I tried all the soluti... | [
"You need to add the r context within your Dash/Plotly plot function - the one with the callback updates. Something like this.\n@app.callback(\n Output('graph-to-update', 'figure'),\n Input('input-slide', 'value')\n)\ndef my_graph_func(var):\n\n with localconverter(ro.default_converter + pandas2ri.converte... | [
1
] | [] | [] | [
"plotly_dash",
"python",
"r",
"rpy2"
] | stackoverflow_0073553237_plotly_dash_python_r_rpy2.txt |
Q:
how scrape - span aria-hidden="true" - text
I am trying to web scrape using selenium and beautiful soupe but i cannot get selenium to find the element I need and return the text.
here is the html:
<span class="t-14 t-normal">
<span aria-hidden="true"><!---->Crédit Agricole CIB · Full-time<!----></span>... | how scrape - span aria-hidden="true" - text | I am trying to web scrape using selenium and beautiful soupe but i cannot get selenium to find the element I need and return the text.
here is the html:
<span class="t-14 t-normal">
<span aria-hidden="true"><!---->Crédit Agricole CIB · Full-time<!----></span><span class="visually-hidden"><!---->Crédit Agric... | [
"I can't confirm without knowing exactly what the full HTML looks like - there might be other very similarly nested elements before the snippet shared in the question, but if there aren't then you can use soup.select_one with the css selectors used below:\nspanTxt1 = soup.select_one('span.t-14.t-normal span[aria-hi... | [
0
] | [] | [] | [
"beautifulsoup",
"hidden_field",
"python",
"web_scraping"
] | stackoverflow_0074197370_beautifulsoup_hidden_field_python_web_scraping.txt |
Q:
Python - get selected Text in third party app without clipboard
I have a translation application for a niche language.
If the user selects/highlights text (typically in the browser) I want the translation func to get triggered. It manually checks and if the language is detected it translates.
I do have my onMouseU... | Python - get selected Text in third party app without clipboard | I have a translation application for a niche language.
If the user selects/highlights text (typically in the browser) I want the translation func to get triggered. It manually checks and if the language is detected it translates.
I do have my onMouseUp Listener that triggers. However I don’t know how to get the select... | [
"So it is not a problem for you to use the clipboard, provided you can keep the old clipboard -- right? So would it be possible for you to save the old clipboard first. Do whatever you want to do and then later restore the clipboard?\nSome ideas when using Windows: How do I read text from the clipboard? From there ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074197353_python.txt |
Q:
Is there better way to compare a main dataframe with controle dataframe for rows (30000)?
This question is auxiliary to question asked in this post Is there better way to iterate over nested loop for rows (30000)?. I created a for loop if an email address from my main dataframe (df) appears in my control datafram... | Is there better way to compare a main dataframe with controle dataframe for rows (30000)? | This question is auxiliary to question asked in this post Is there better way to iterate over nested loop for rows (30000)?. I created a for loop if an email address from my main dataframe (df) appears in my control dataframe (df_controle) and add a column value with 'ja' in main dataframe (df)
import pandas as pd
dat... | [
"If you combine these two dataframes and find the ones that don't match, wouldn't it work ? Unmatched emails will be returned as nan.\nimport numpy as np\ndf_controle=df_controle.rename(columns={'Email':'control_email'})\n\nfinal=df.merge(df_controle,how='left',left_on='Email',right_on='control_email')\nfinal['emai... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074196699_dataframe_pandas_python.txt |
Q:
PyModbus - trigger an action/function when holding register is read
I've setup a running Pymodbus server based on the 'Updating Server' (v2.5.3) example.
https://pymodbus.readthedocs.io/en/v2.5.3/source/example/updating_server.html
Everything works ok.
Now i want to trigger a function (which will simply increment ... | PyModbus - trigger an action/function when holding register is read | I've setup a running Pymodbus server based on the 'Updating Server' (v2.5.3) example.
https://pymodbus.readthedocs.io/en/v2.5.3/source/example/updating_server.html
Everything works ok.
Now i want to trigger a function (which will simply increment a value by 1), when (any) client is requesting to read/poll the contents... | [
"There is likely a way to overload the StartTCPServer function, though looking through the source code it seems tricky since it's built on asyncio (not like that's bad, just less conducive to easily overloading this one thing you're trying to do).\nHowever there are several modbus libraries you can use, and sourcep... | [
0
] | [] | [] | [
"pymodbus",
"pymodbustcp",
"python"
] | stackoverflow_0074126766_pymodbus_pymodbustcp_python.txt |
Q:
Custom types that are wrappers on simple types on pydantic
I am trying to create custom types that are wrappers on simple types (like int, float and str) in order to perform value validation (i.e. reject values that are forbidden, invalid and/or undesired). For that, I'm using mypy and pydantic.
However, when I ad... | Custom types that are wrappers on simple types on pydantic | I am trying to create custom types that are wrappers on simple types (like int, float and str) in order to perform value validation (i.e. reject values that are forbidden, invalid and/or undesired). For that, I'm using mypy and pydantic.
However, when I add those custom types into data objects and/or data models, they ... | [
"Validator callable should raise-or-return, because it is responsible for both converting to proper type (like int returns an integer, given a string) and checking input validity.\nCode below should work. I have also removed __init__, improved typing for __new__ and __get_validators__ (so that subclass' __new__ ret... | [
2
] | [] | [] | [
"mypy",
"pydantic",
"python",
"python_3.x"
] | stackoverflow_0074196205_mypy_pydantic_python_python_3.x.txt |
Q:
How can I run python script when a google sheet get new value?
I have a google sheet that 5 times a day append a new value to the sheet. I need to run a local python script everytime a value is included, how can I do it?
A:
Are you familiar with the Google Sheet API yet?
https://developers.google.com/sheets/api/... | How can I run python script when a google sheet get new value? | I have a google sheet that 5 times a day append a new value to the sheet. I need to run a local python script everytime a value is included, how can I do it?
| [
"Are you familiar with the Google Sheet API yet?\nhttps://developers.google.com/sheets/api/quickstart/python\nThat should get your started. As for automatizing running the script every time the sheet is overwritten, check the metadata section to give you an idea of how to sync the data. Then, choose your favorite w... | [
5
] | [] | [] | [
"airtable",
"automation",
"google_apps_script",
"google_sheets",
"python"
] | stackoverflow_0074198007_airtable_automation_google_apps_script_google_sheets_python.txt |
Q:
Searching for a string character in a list with different types of values
I have a list consisting of different types of values - that is, ints and strings. I want to use a loop to find character indexes that are not numbers.
#for a list
list = [2, 3, 4, '*', 2, '^', '+']
#Output should look like this
3, 5, 6
A:
... | Searching for a string character in a list with different types of values | I have a list consisting of different types of values - that is, ints and strings. I want to use a loop to find character indexes that are not numbers.
#for a list
list = [2, 3, 4, '*', 2, '^', '+']
#Output should look like this
3, 5, 6
| [
"For ints only, you can do something like\n[idx for idx,val in enumerate(lst) if type(val) != int]\n\nLater, you said \"not numbers\". For that, there are few options - one uses the answer here to check if a value is a number: https://stackoverflow.com/a/4187266/2506943\nimport numbers\n[idx for idx,val in enumerat... | [
2,
1,
0
] | [
"listA = [2, 3, 4, '*', 2, '^', '+']\nres=set(listA)\nfor i in res:\n if str(i).isalnum()!=True:\n print(listA.index(i))\n\nyou can simply use listA instead of converting that to set to remove duplicates.\n"
] | [
-1
] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074197627_list_python_python_3.x.txt |
Q:
How to perform same operation on multiple text files and save the output in different files using python?
I have written a code which extracts stop words from a text file and outputs two new text files. One file contains the stop words from that text file and another file contains the data without stop words. Now ... | How to perform same operation on multiple text files and save the output in different files using python? | I have written a code which extracts stop words from a text file and outputs two new text files. One file contains the stop words from that text file and another file contains the data without stop words. Now I have more than 100 text file in a folder, I would like to perform the same operation on all those file simult... | [
"You can use OS.listdir to get the number of text files, and use a for loop to run each time. To assign a name to the output file you can use an f-string in its creation so it looks like f'Stop_Word_Consist_{fileName}':\nfor entry in OS.listdir(folder location):\n all_reviews , stop_words = clean_text(data_1)\n ... | [
0
] | [] | [] | [
"file",
"for_loop",
"nlp",
"python",
"text_files"
] | stackoverflow_0074197670_file_for_loop_nlp_python_text_files.txt |
Q:
I get an error about wrong dictionary update sequence length when trying to read lines from txt file into a dictionary
I'm trying to loop through multiple lines and add that into a dictionary, then a dataframe.
I've had many attempts but no solution yet.
I have a txt file with multiple lines like this for example,... | I get an error about wrong dictionary update sequence length when trying to read lines from txt file into a dictionary | I'm trying to loop through multiple lines and add that into a dictionary, then a dataframe.
I've had many attempts but no solution yet.
I have a txt file with multiple lines like this for example, and I'm trying to iterate through each line, add it to a dictionary and then append the dictionary to a dataframe.
So textf... | [
"One suggestion is to parse each line with regex, and then insert the matches (if found) into the dictionary. You can change the regex pattern as needed, but this one matches words on the left side of = with numbers on the right which start with ' or \".\nimport re\nimport pandas as pd\n\npattern = r'(\\w+)=[\\'\\... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074187783_dictionary_python.txt |
Q:
How to append to a list two numbers from within the list that add up to a number in the list?
First, I want to find the highest number in the list which is the second number in the list, then split it in two parts. The first part contains the 2nd highest number, while the second part contains the number from the l... | How to append to a list two numbers from within the list that add up to a number in the list? | First, I want to find the highest number in the list which is the second number in the list, then split it in two parts. The first part contains the 2nd highest number, while the second part contains the number from the list that sums to the highest number. Then, return the list
eg: input: [4,9,6,3,2], expected output:... | [
"The main issue in your code seems to be that you are editing the list s whilst iterating through it, which can cause issues with the compiler and is generally just something you want to avoid doing in programming. A solution to this could be iterating through a copy of the original list.\nThe second problem is tha... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074197301_python.txt |
Q:
Split Pandas column [{}] into several columns? in python
im getting confused with the data type of my pandas dataframe and dont know how to split my entries into several columns.
Data looks like:
Name1 Name2
0 [0.1,0.2,0.3] [{'label': 'Neutral', 'score': 0.60}]
1 [0.4,0.5,0... | Split Pandas column [{}] into several columns? in python | im getting confused with the data type of my pandas dataframe and dont know how to split my entries into several columns.
Data looks like:
Name1 Name2
0 [0.1,0.2,0.3] [{'label': 'Neutral', 'score': 0.60}]
1 [0.4,0.5,0.6] [{'label': 'Negative', 'score': 0.60}]
2 [0.7,0.8,0.9... | [
"You can use to_list() function on a specific column to make columns out of list.\nMore of that you can find under this link:\nhttps://datascienceparichay.com/article/split-pandas-column-of-lists-into-multiple-columns/\nTo do a similar thing with dict refer to this page:https://stackoverflow.com/questions/38231591/... | [
-1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074198105_dataframe_pandas_python.txt |
Q:
how to find a list in a bunch of lists in python
I want a way to make it so that I can use list B to find out if a copy of it's self exists in list A.
I want a way to make it so that I can use list B to find out if a copy of it's self exists in list A.
this is the way data a has been collected:
for i in range(len(... | how to find a list in a bunch of lists in python | I want a way to make it so that I can use list B to find out if a copy of it's self exists in list A.
I want a way to make it so that I can use list B to find out if a copy of it's self exists in list A.
this is the way data a has been collected:
for i in range(len(fsa)):
if fsa[i] < fsb[i]:
kol.append('1')... | [
"As many pointed out, the code provided is not properly formatted, so I made some assumptions. Here is a half-solution to get you unstuck, try to modify this to get what you want. You will learn more by modifying this code than if I were to give you the final solution.\nfrom collections import Counter # for compar... | [
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074197710_list_python.txt |
Q:
In what object can i add both lists and floats so i can find the list with the lowest float value
Say i have some iterations. In each iteration, a list of integers and a float number are created.
1st iteration: [0,2,4,3,0] , 285 are created
2nd iteration: [0,8,5,6,0] , 230 are created
...
nth iteration: [0,9,8,1,0... | In what object can i add both lists and floats so i can find the list with the lowest float value | Say i have some iterations. In each iteration, a list of integers and a float number are created.
1st iteration: [0,2,4,3,0] , 285 are created
2nd iteration: [0,8,5,6,0] , 230 are created
...
nth iteration: [0,9,8,1,0] , 340 are created
I want to iteratively append each list-float pair to an object, so I can later get... | [
"\nI want to iteratively append each list-float pair to an object, so I can later get the list with the lowest float value.\n\nReading the motivation literally, \"so I can later get the list with the lowest float value,\"\nsuggests that you don't want a data structure at all.\nRather, you want to simply assign mini... | [
0,
0
] | [] | [] | [
"dictionary",
"iteration",
"list",
"object",
"python"
] | stackoverflow_0074197914_dictionary_iteration_list_object_python.txt |
Q:
Find the index of maximum values in a window size of each rows of data frames
I have two dataframes, df and df1. I want to find the maximum in each 4 columns and each rows in df and then the value of that column in df1.
import pandas as pd
df = pd.DataFrame()
df['a'] = [ 1, 2]
df[... | Find the index of maximum values in a window size of each rows of data frames | I have two dataframes, df and df1. I want to find the maximum in each 4 columns and each rows in df and then the value of that column in df1.
import pandas as pd
df = pd.DataFrame()
df['a'] = [ 1, 2]
df['b'] = [ 2, 20]
df['c'] = [ 4, 2]
df['d'] = [ 6, 2]
df['e']... | [
"Let's try to get the column name of max value in each 4 columns then pass its row and column name as tuple to index the df1.stack()\nout = pd.concat([df1.stack()[df[df.columns[i:i+4]].idxmax(axis=1).items()].droplevel(level=-1)\n for i in range(0, len(df.columns), 4)], axis=1)\n\nprint(out)\n\n 0... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074196614_dataframe_pandas_python.txt |
Q:
How to make strings not repeat in a random word generator
I am making a random string generator, however I am having issues making the strings not repeat when generating
Here's the Code:
import random
import string
repeat = True
pp = input("What's your text? ").lower()
pl = len(pp)
while repeat == True:
let... | How to make strings not repeat in a random word generator | I am making a random string generator, however I am having issues making the strings not repeat when generating
Here's the Code:
import random
import string
repeat = True
pp = input("What's your text? ").lower()
pl = len(pp)
while repeat == True:
letters = string.ascii_lowercase
result_str = ''.join(random.c... | [
"You can try like below. In the below example, I suppose you want the length of each string==10 and you want to generate 10 strings that don't have repeating. In each iteration, we generate a random string and if generated string doesn't exist in seen we add generate string to seen and increase one-time cnt. Until ... | [
1
] | [] | [] | [
"python",
"random",
"string",
"while_loop"
] | stackoverflow_0074198212_python_random_string_while_loop.txt |
Q:
Split CSV file which contains multiple tables into different pandas dataFrames (Python)
I have multiple CSV files which are formatted with multiple tables inside separated by line breaks.
Example:
Technology C_inv [MCHF/y] C_maint [MCHF/y]
NUCLEAR 70.308020 33.374568
HYDRO_DAM_EXISTING 0.000000 195.051200
... | Split CSV file which contains multiple tables into different pandas dataFrames (Python) | I have multiple CSV files which are formatted with multiple tables inside separated by line breaks.
Example:
Technology C_inv [MCHF/y] C_maint [MCHF/y]
NUCLEAR 70.308020 33.374568
HYDRO_DAM_EXISTING 0.000000 195.051200
HYDRO_DAM 67.717942 1.271600
HYDRO_RIVER_EXISTING 0.000000 204.820000
IND_BOILER_OI... | [
"I would do it the following way.\nIterate through each row, append each chunk seperated by a newline to a list and build dataframes from the lists. The problem with the column names with spaces, use re.split and split only if there are two or more spaces.\nSave the different df's in a dictionary where the key is t... | [
2
] | [] | [] | [
"csv",
"import",
"pandas",
"python",
"txt"
] | stackoverflow_0074196913_csv_import_pandas_python_txt.txt |
Q:
mysql_config not found when installing mysqldb python interface
I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,
python setup.py install
I get the fol... | mysql_config not found when installing mysqldb python interface | I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,
python setup.py install
I get the following error report related to the mysql_config command.
sh: mysql_co... | [
"mySQLdb is a python interface for mysql, but it is not mysql itself. And apparently mySQLdb needs the command 'mysql_config', so you need to install that first.\nCan you confirm that you did or did not install mysql itself, by running \"mysql\" from the shell? That should give you a response other than \"mysql: co... | [
898,
224,
83,
52,
46,
37,
28,
23,
21,
19,
19,
16,
15,
12,
11,
10,
8,
7,
4,
4,
4,
4,
3,
3,
2,
2,
2,
2,
1,
1,
1,
1,
1,
0
] | [
"sudo apt-get install libmysqlclient-dev\nsudo apt-get install python-dev\nsudo apt-get install MySQL-python\nNOtice you should install python-dev as well, the packages like MySQL-python are compiled from source. The pythonx.x-dev packages contain the necessary header files for linking against python. Why does inst... | [
-2
] | [
"linux",
"mysql_python",
"python",
"ssh"
] | stackoverflow_0007475223_linux_mysql_python_python_ssh.txt |
Q:
How to get specific items with requests
I'm trying to get just one currency with the exchangerate-api
here is what I tried:
import requests
url = 'https://v6.exchangerate-
api.com/v6/API-KEY/latest/EUR'
response = requests.get(url, params={"conversion_rates": "BGN"})
data = response.json()
print(data)
I just ... | How to get specific items with requests | I'm trying to get just one currency with the exchangerate-api
here is what I tried:
import requests
url = 'https://v6.exchangerate-
api.com/v6/API-KEY/latest/EUR'
response = requests.get(url, params={"conversion_rates": "BGN"})
data = response.json()
print(data)
I just want to get a specific one and only its rate ... | [
"If you know which specific rate you want, do\nrate = data[\"conversion_rates\"][\"BGN\"]\nprint(1./rate)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074198250_python.txt |
Q:
Celery - Programmatically list workers
How can I programmatically, using Python code, list current workers and their corresponding celery.worker.consumer.Consumer instances?
A:
You can use celery.control.inspect to inspect the running workers:
>>> import celery
>>> celery.current_app.control.inspect().ping()
{u... | Celery - Programmatically list workers | How can I programmatically, using Python code, list current workers and their corresponding celery.worker.consumer.Consumer instances?
| [
"You can use celery.control.inspect to inspect the running workers:\n>>> import celery\n>>> celery.current_app.control.inspect().ping()\n {u'celery@host': {u'ok': u'pong'}}\n\n",
"Short answer:\nyour_celery_app.control.inspect().stats().keys()\nIn general that stats() dictionary gives a lot of info. Here's an exa... | [
31,
13,
1,
0
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0014142150_celery_python.txt |
Q:
string into dict of list - python
I am trying to figure out the best way to parse the string you get from using pytesseract.image_to_data("image.png").
When I usually get databack it comes out like this:
level page_num block_num par_num line_num word_num left top width height conf text
1 1 ... | string into dict of list - python | I am trying to figure out the best way to parse the string you get from using pytesseract.image_to_data("image.png").
When I usually get databack it comes out like this:
level page_num block_num par_num line_num word_num left top width height conf text
1 1 0 0 0 0 0 0 1920 1080 ... | [
"I figured out the answer at the same time @shawncaza did. The function for image_to_data has a param option for output type which you can set to dict. Here is a basic example of how to convert this type of string into a dict/list:\nimport pytesseract\nfrom pytesseract import Output\n\npytesseract.pytesseract.tesse... | [
0
] | [] | [] | [
"python",
"python_tesseract",
"string"
] | stackoverflow_0074196771_python_python_tesseract_string.txt |
Q:
Solving a cubic equation
As part of a program I'm writing, I need to solve a cubic equation exactly (rather than using a numerical root finder):
a*x**3 + b*x**2 + c*x + d = 0.
I'm trying to use the equations from here. However, consider the following code (this is Python but it's pretty generic code):
a = 1.0
b ... | Solving a cubic equation | As part of a program I'm writing, I need to solve a cubic equation exactly (rather than using a numerical root finder):
a*x**3 + b*x**2 + c*x + d = 0.
I'm trying to use the equations from here. However, consider the following code (this is Python but it's pretty generic code):
a = 1.0
b = 0.0
c = 0.2 - 1.0
d = -0.7... | [
"Wikipedia's notation (rho^(1/3), theta/3) does not mean that rho^(1/3) is the real part and theta/3 is the imaginary part. Rather, this is in polar coordinates. Thus, if you want the real part, you would take rho^(1/3) * cos(theta/3).\nI made these changes to your code and it worked for me:\ntheta = arccos(r/rho... | [
24,
2,
1,
0,
0
] | [
"In case someone needs C++ code, you can use this piece of OpenCV: \nhttps://github.com/opencv/opencv/blob/master/modules/calib3d/src/polynom_solver.cpp\n"
] | [
-2
] | [
"algorithm",
"cubic",
"math",
"python"
] | stackoverflow_0001829330_algorithm_cubic_math_python.txt |
Q:
AWS s3 presigned url not downloading
I am trying to download file from S3 pre Signed URL.I am getting access denied error The url looks like this.
https://s3.us.amazonaws.com/test1/xxxxxxxx
Here my python code.
def getfile(self, url):
url2 = str(url).replace("['", "")
s3 = boto3.client('s3')
key = "xxxxx... | AWS s3 presigned url not downloading | I am trying to download file from S3 pre Signed URL.I am getting access denied error The url looks like this.
https://s3.us.amazonaws.com/test1/xxxxxxxx
Here my python code.
def getfile(self, url):
url2 = str(url).replace("['", "")
s3 = boto3.client('s3')
key = "xxxxxxxxxxdd"
filename = "file_name.hex"
... | [
"Can you generate pre signed url like this:\n s3.generate_presigned_url(\n 'get_object',\n Params = {'Bucket': 'bucket-1', 'Key': key},\n ExpiresIn = SIGNED_URL_TIMEOUT\n)\n\nMake sure ExpiresIn is in seconds\nFor more : https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html\n... | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto3",
"python",
"python_3.x"
] | stackoverflow_0074197225_amazon_s3_amazon_web_services_boto3_python_python_3.x.txt |
Q:
Python PIllow Tkinter - How to edit a photo twice without losing the previous change?
How do I edit a photo without losing previous edits? Below is my code.
After uploading a photo and pressing the blur button, the photo blurs, but if I then press rotate, the blurring of the photo disappears. How do I keep the res... | Python PIllow Tkinter - How to edit a photo twice without losing the previous change? | How do I edit a photo without losing previous edits? Below is my code.
After uploading a photo and pressing the blur button, the photo blurs, but if I then press rotate, the blurring of the photo disappears. How do I keep the result of both effects?
Do I have to save the photo to a separate file after using each functi... | [
"the reason why the previous change is lost is because each of your functions is reading the image again from disk, and while saving it back to disk temporarily is what some image processing applications do to prevent loss of work on power outage, you can simply work from memory for the application by hand.\n\ndefi... | [
0
] | [] | [] | [
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0074198208_python_python_imaging_library_tkinter.txt |
Q:
Browser cant find file or directory in Django
I am trying to create a qr code and store it on disk. Running the program from my pc works fine, but when I run it on the server (deploy is done in docker), I get this error:
[Errno 2] No such file or directory: '/app/static/QR/QR-1-9.png'
and the browser also poi... | Browser cant find file or directory in Django | I am trying to create a qr code and store it on disk. Running the program from my pc works fine, but when I run it on the server (deploy is done in docker), I get this error:
[Errno 2] No such file or directory: '/app/static/QR/QR-1-9.png'
and the browser also points me to this line of my code
with open(UPLOAD... | [
"I see a space here /QR /\n[Errno 2] No such file or directory: '/app/static/QR /QR-1-9.png'\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074198329_django_python.txt |
Q:
"list index out of range" in Python when referencing list in if statement
This is part of a program in Python that reads through a file, word by word, and counts instances of unique mail ID's from all lines that begin with 'From'. To achieve this, I make a list of all words in one line and go line by line to read ... | "list index out of range" in Python when referencing list in if statement | This is part of a program in Python that reads through a file, word by word, and counts instances of unique mail ID's from all lines that begin with 'From'. To achieve this, I make a list of all words in one line and go line by line to read through the list entry 0. If it is From, it adds its entry to a dict(). But I c... | [
"The problem is that when you split an empty line word is set to an empty list.\nWhen you try to access any index of an empty list you get an 'list index out of range' error\ntry this code instead\nname = \"mbox-short.txt\"\nhandle = open(name)\ntable = dict()\nfor line in handle:\n word = line.split()\n if w... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0056207769_python.txt |
Q:
Does xgboost have feature_importances_?
I'm calling xgboost via its scikit-learn-style Python interface:
model = xgboost.XGBRegressor()
%time model.fit(trainX, trainY)
testY = model.predict(testX)
Some sklearn models tell you which importance they assign to features via the attribute feature_importances. This ... | Does xgboost have feature_importances_? | I'm calling xgboost via its scikit-learn-style Python interface:
model = xgboost.XGBRegressor()
%time model.fit(trainX, trainY)
testY = model.predict(testX)
Some sklearn models tell you which importance they assign to features via the attribute feature_importances. This doesn't seem to exist for the XGBRegressor:
m... | [
"How did you install xgboost? Did you build the package after cloning it from github, as described in the doc? \nhttp://xgboost.readthedocs.io/en/latest/build.html\nAs in this answer: \nFeature Importance with XGBClassifier\nThere always seems to be a problem with the pip-installation and xgboost. Building and inst... | [
2,
0
] | [
"This is useful for you,maybe. \nxgb.plot_importance(bst)\nAnd this is the link:plot\n"
] | [
-1
] | [
"c++",
"machine_learning",
"python",
"scikit_learn",
"xgboost"
] | stackoverflow_0041565091_c++_machine_learning_python_scikit_learn_xgboost.txt |
Q:
Save an excel file from a dataframe pandas to sharepoint (office365 API)
I have this dataframe, and I want to save it as a excel file in a sharepoint folder.
This is my code:
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
# auth
... | Save an excel file from a dataframe pandas to sharepoint (office365 API) | I have this dataframe, and I want to save it as a excel file in a sharepoint folder.
This is my code:
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
# auth
client_credentials = ClientCredential(var_client_id, var_client_secret)
ctx = ... | [
"I'm investigating this issue right now. Not solved yet buy I can give you a work around: use .save()\nwb = pd.ExcelWriter( outputFile, mode='w', engine=\"openpyxl\" )\nmyDataFrame.to_excel( wb, sheet_name='sheet1', index=False )\nwb.save()\n\nFrom error to warning ;)\n"
] | [
0
] | [] | [] | [
"excel",
"office365api",
"pandas",
"python",
"sharepoint"
] | stackoverflow_0072884885_excel_office365api_pandas_python_sharepoint.txt |
Q:
Using a .csv file to populate a ledger (.docx) of generated documents
I work in an educational institution and we need to keep track of all documents issued. Since we don't have databases, we are recording each document issued in a word document, which is then approved by the institution's system.
This is a exampl... | Using a .csv file to populate a ledger (.docx) of generated documents | I work in an educational institution and we need to keep track of all documents issued. Since we don't have databases, we are recording each document issued in a word document, which is then approved by the institution's system.
This is a example of how we store the data on the .csv file:
name
email
document
jo... | [
"In the example below I processed the csv in pandas and wrote the output to docx with python-docx:\nimport io\nimport pandas as pd\nfrom docx import Document\n\ncsv_data = '''name email document\njohn john@gmail.com 00x1\nmaria maria@gmail.com 00x2'''\n\n# open csv in pandas; you can run df = pd.read_csv('... | [
0
] | [] | [] | [
"csv",
"docx",
"python",
"python_3.x",
"python_docx"
] | stackoverflow_0074198160_csv_docx_python_python_3.x_python_docx.txt |
Q:
Regular expression in Python won't match end of a string
I'm just learning Python, and I can't seem to figure out regular expressions.
r1 = re.compile("$.pdf")
if r1.match("spam.pdf"):
print 'yes'
else:
print 'no'
I want this code to print 'yes', but it obstinately prints 'no'. I've also tried each of the... | Regular expression in Python won't match end of a string | I'm just learning Python, and I can't seem to figure out regular expressions.
r1 = re.compile("$.pdf")
if r1.match("spam.pdf"):
print 'yes'
else:
print 'no'
I want this code to print 'yes', but it obstinately prints 'no'. I've also tried each of the following:
r1 = re.compile(r"$.pdf")
r1 = re.compile("$ .pdf... | [
"You've tried all the variations except the one that works. The $ goes at the end of the pattern. Also, you'll want to escape the period so it actually matches a period (usually it matches any character).\nr1 = re.compile(r\"\\.pdf$\")\n\nHowever, an easier and clearer way to do this is using the string's .endswit... | [
60,
29,
8,
1,
1
] | [
"#This will work for regular expression\nr1 = re.compile(r\".+\\.pdf$\")\nif r1.match(\"spam.pdf\"):\n print 'yes'\nelse:\n print 'no'\n#alternative soln\nif filename.endswith(\".pdf\"):\n print 'yes'\nelse:\n print 'no\n\n"
] | [
-1
] | [
"python",
"regex"
] | stackoverflow_0012187799_python_regex.txt |
Q:
Creating own module
I am new to Python. Please help me with this simple question
In the exercise, we already have the main program in the module, which is as follows:
# -*- coding: cp1252 -*-
import mymodule
mymodule.printme("Exampleline")
The objective is to implement this mymodule-module applied in the... | Creating own module | I am new to Python. Please help me with this simple question
In the exercise, we already have the main program in the module, which is as follows:
# -*- coding: cp1252 -*-
import mymodule
mymodule.printme("Exampleline")
The objective is to implement this mymodule-module applied in the exercise. Create a modu... | [
"You can create a module very easily. It's just another file.\nThe easiest way to do this is to create the mymodule.py file.\nAnd in the mymodule.py file, you will need a function.\n# mymodule.py\ndef printme(string):\n print('I got: {0}'.format(string))\n print('The parameter was {} characters long.'.format(... | [
2,
1
] | [
"def printme(sth):\n print(\"I got:\",(sth))\n print(\"The parameter was\",len(sth),\"characters long.\")\n\nTry this, it works\n"
] | [
-1
] | [
"python"
] | stackoverflow_0064203434_python.txt |
Q:
how do i manually parse output of .dump() file into a text widget
how do i manually parse output of .dump() from a text widget that has italic and bold text in it to a different text widget to load it along with its text format.
this is the code if it helps, the text should be saved along with text format but when... | how do i manually parse output of .dump() file into a text widget | how do i manually parse output of .dump() from a text widget that has italic and bold text in it to a different text widget to load it along with its text format.
this is the code if it helps, the text should be saved along with text format but when the file is open the text format is gone:
from tkinter import *
from t... | [
"The Text widget dump method returns a list of tuples. Each tuple will be of the form (key, value, index). key will be one of the following: text, mark, tagon, tagoff, image, or window. value will be dependent on the key. index is the location in the text. For example, with tagon and tagoff the value will be the na... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074192814_python_tkinter.txt |
Q:
How to take data from a line and update a field for a point in arcmap?
So, I have a point and a line on my map (20,000 of them actually). The line has a MATERIAL field that shows the specific type of material and the point has a MATERIAL field that needs to be updated to show the material in the line. The problem ... | How to take data from a line and update a field for a point in arcmap? | So, I have a point and a line on my map (20,000 of them actually). The line has a MATERIAL field that shows the specific type of material and the point has a MATERIAL field that needs to be updated to show the material in the line. The problem is that these two items do not have any connecting fields but they do physic... | [
"The solution was to use definition queries and ten select by location if anyone is having a similar issue.\n"
] | [
0
] | [] | [] | [
"arcgis",
"arcmap",
"python"
] | stackoverflow_0074196433_arcgis_arcmap_python.txt |
Q:
Is it possible to cancel an exec() in python after 5 seconds
I am working on a python script that runs small user generated scripts. There is a problem though when a user submits a script that infinitely loops. I was wondering if it would be possible to stop an exec() after 5 seconds of running.
x = exec(user_code... | Is it possible to cancel an exec() in python after 5 seconds | I am working on a python script that runs small user generated scripts. There is a problem though when a user submits a script that infinitely loops. I was wondering if it would be possible to stop an exec() after 5 seconds of running.
x = exec(user_code)
delay(5)
x.cancel()
something like this ^
So far I tried usin... | [
"You could use multiprocessing:\nimport multiprocessing\nimport time\n\ndef exec(n):\n for i in range(10000 * n):\n print(\"Whatever\") #Your code\n\nif __name__ == '__main__':\n process = multiprocessing.Process(target=exec, name=\"Exec\", args=(10,))\n process.start()\n time.sleep(1) #How much ... | [
-1
] | [] | [] | [
"eval",
"multithreading",
"python",
"time"
] | stackoverflow_0074198526_eval_multithreading_python_time.txt |
Q:
How to send prettytable through email using python
I have created a prettytable in python and I have to send the output of prettytable through email
env = "Dev"
cost = 25.3698
line = [env, "${:,.2f}".format(cost)]
totalcostofenv = PrettyTable(['Environment', 'Cost'])
totalcostofenv.add_row(line)
print(totalcostof... | How to send prettytable through email using python | I have created a prettytable in python and I have to send the output of prettytable through email
env = "Dev"
cost = 25.3698
line = [env, "${:,.2f}".format(cost)]
totalcostofenv = PrettyTable(['Environment', 'Cost'])
totalcostofenv.add_row(line)
print(totalcostofenv)
Below attached is the output :
Table Output
Can an... | [
"You can use MJML templating like this\n<mjml>\n <mj-head>\n <mj-title>Set the title, usually for accessibility tools</mj-title>\n <mj-preview>Set inbox preview text here, otherwise it might be something nonsensical</mj-preview>\n <mj-attributes>\n <mj-all font-family=\"Helvetica, Arial, sans-serif\"... | [
0
] | [] | [] | [
"prettytable",
"python",
"python_3.x",
"smtp"
] | stackoverflow_0074198471_prettytable_python_python_3.x_smtp.txt |
Q:
Check if document has been updated or inserted mongodb in python
I have the following code in node js which checks if a document has been updated/inserted.
studentSchool = await this.studentSchoolModel.findOneAndUpdate(
{ student: studentID, phase: "Secondary" },
{ student: studentID, school: schoolID, phase... | Check if document has been updated or inserted mongodb in python | I have the following code in node js which checks if a document has been updated/inserted.
studentSchool = await this.studentSchoolModel.findOneAndUpdate(
{ student: studentID, phase: "Secondary" },
{ student: studentID, school: schoolID, phase: "Secondary"},
{ new: false, upsert: true, rawResult: true });
I ... | [
"It seems Mongoose adds the rawResult argument, which is not supported natively in latest MongoDB(v6.0) and Pymongo.\nYou can set ReturnDocument to before and if upsert is made, result will be None, otherwise the dictionary of existing document.\nSo your query becomes\n\n\nfrom pymongo.collection import ReturnDocum... | [
0
] | [] | [] | [
"bson",
"mongodb",
"node.js",
"python"
] | stackoverflow_0074196488_bson_mongodb_node.js_python.txt |
Q:
AWS EC2 SSH crashes on running a script/program/process
Problem:
I am running into an issue with my AWS EC2 instance where I am trying to ssh to the instance from both the mac terminal and Visual studio code. The ssh gets connected initially without any problem from the terminal & VS Code but when I try to edit on... | AWS EC2 SSH crashes on running a script/program/process | Problem:
I am running into an issue with my AWS EC2 instance where I am trying to ssh to the instance from both the mac terminal and Visual studio code. The ssh gets connected initially without any problem from the terminal & VS Code but when I try to edit one of the files and start running some script the ssh communic... | [
"I was able to solve the issue. In such cases, the following can be possible considerations:\n\nThe EC2 Instance type you are using and the amount of RAM that is\nbeing consumed. See here to understand the instance types and find a\nsuitable one for you.\n\nIf you ssh through VSCode, I recommend not installing any ... | [
2,
1
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"connection_refused",
"python",
"ssh"
] | stackoverflow_0074174352_amazon_ec2_amazon_web_services_connection_refused_python_ssh.txt |
Q:
Ordinal Encoder causing issues during testing Machine Learning Model
I have the model with Accuracy of 97% and I am using Ordinal Encoder to fit and transform the data to numeric value. Saving both objects to .pkl. I am using Random Forest Classifier.
OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value... | Ordinal Encoder causing issues during testing Machine Learning Model | I have the model with Accuracy of 97% and I am using Ordinal Encoder to fit and transform the data to numeric value. Saving both objects to .pkl. I am using Random Forest Classifier.
OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-1)
Testing: I loaded both objects and then I have TestData.csv where the... | [
"I found a work around for this. Created two Ordinal Object X features and Y feature (Predictive Values) to train the ML model.\ndef fitData(self):\n self.XODE.fit(self.originalDF[self.cols])\n self.YODE.fit(self.originalDF['Col_name'].values.reshape(-1,1))\n joblib.dump(self.XOE,open(\"XOrdinalEnc.pkl\",'... | [
0
] | [] | [] | [
"encoder",
"machine_learning",
"python",
"random_forest",
"scikit_learn"
] | stackoverflow_0074182650_encoder_machine_learning_python_random_forest_scikit_learn.txt |
Q:
"Unsupported image object", using Tesseract
I am building a character identifier from an image using Tesseract and Python.
This is my code:
from PIL import Image
import pytesseract as pyt
image_file = 'location'
im = Image.open(image_file)
text = pyt.image_to_string(image_file)
print (text)
I am getting th... | "Unsupported image object", using Tesseract | I am building a character identifier from an image using Tesseract and Python.
This is my code:
from PIL import Image
import pytesseract as pyt
image_file = 'location'
im = Image.open(image_file)
text = pyt.image_to_string(image_file)
print (text)
I am getting the following error while executing this program:
... | [
"First, remember to add the line\n pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'\n\nwhere\nC:/Program Files/Tesseract-OCR/tesseract.exe is the location where your tesseract is installed.\nYou have indicated that the image file is a string, which is ok, but you did not add an... | [
3,
2,
0
] | [] | [] | [
"python",
"python_3.x",
"python_imaging_library",
"python_tesseract"
] | stackoverflow_0051364353_python_python_3.x_python_imaging_library_python_tesseract.txt |
Q:
Working on a python problem trying to guess a randomly generated number im generally new to python and would appreciate some advice
having trouble when it trys comparing the input and the random integer
import random
target = random.randint(1,100)
counter = 0
print(target)
print(int(input('Guess an integer between... | Working on a python problem trying to guess a randomly generated number im generally new to python and would appreciate some advice | having trouble when it trys comparing the input and the random integer
import random
target = random.randint(1,100)
counter = 0
print(target)
print(int(input('Guess an integer between 1 and 100 ')))
guess = input
while guess != target():
if guess > target():
print("Guess is to high")
elif guess < target... | [
"You have several issues with your code:\n\nYou have print(int(input('Guess an integer between 1 and 100 '))) followed by guess = input. You are not assigning to guess what was entered but rather setting it to refer to a function.\nIn several places you have target(). But target is of type int, not a function, and ... | [
1,
1,
0
] | [
"Try these changes,\nimport random\ntarget = random.randint(1,100)\ncounter = 0\nprint(target)\nguess = int(input('Guess an integer between 1 and 100 '))\nwhile guess != target:\n if guess > target:\n print(\"Guess is to high\")\n elif guess < target:\n print(\"Guess was to low\")\ncounter = counter + 1... | [
-1,
-1
] | [
"if_statement",
"input",
"python",
"random",
"while_loop"
] | stackoverflow_0074198400_if_statement_input_python_random_while_loop.txt |
Q:
Difference of rows on one col (Spotfire expression, ipython or python)
Spotfire difference of previous date and previous period data using python or expression. whatever works. here is the expected output.
ID col End_date output1 output 2
1 12/2/2020 NaN NaN
2 11/3/... | Difference of rows on one col (Spotfire expression, ipython or python) | Spotfire difference of previous date and previous period data using python or expression. whatever works. here is the expected output.
ID col End_date output1 output 2
1 12/2/2020 NaN NaN
2 11/3/2020 Diff of 1n2 NaN
3 9/5/2020 Diff of 2n3 Di... | [
"Getting Previous date difference from one column\nGet the RowId()\nParseDate(String([date]),\"yyyyMMdd\") format the date\nMax([date]) OVER (Previous([ID],1)) calculate the first date over actual date1\nMax([date]) OVER (Previous([ID],2)) calculate the first date over actual date2\nDateDiff('Day',[date],[Max1]) ca... | [
0
] | [] | [] | [
"expression",
"ipython",
"python"
] | stackoverflow_0073898279_expression_ipython_python.txt |
Q:
Getting a single line from a txt file, turning it to string then an int and getting "ValueError: invalid literal for int() with base 10:"
I created a program that retrieves every single line from a txt file (Numbers and text written inside) one by one, filtering it based around if it's an int or specific string. I... | Getting a single line from a txt file, turning it to string then an int and getting "ValueError: invalid literal for int() with base 10:" | I created a program that retrieves every single line from a txt file (Numbers and text written inside) one by one, filtering it based around if it's an int or specific string. If it's an int,I use it with a function from Pyauogui(An automation library that controls keyboard and mouse) that makes it click a position on ... | [
"Here is another solution. The only difference from @NoDakker's solution is that I moved the logic outside of the loop to keep your code clean. Also this solution tries to follow pythonic idioms such as list-comps and gen-exps\n\ndef process_numbers(line: str) -> int:\n for n in line.strip(\" ( )\\n\").split(','):... | [
1,
0
] | [] | [] | [
"file",
"integer",
"python",
"string",
"text"
] | stackoverflow_0074198282_file_integer_python_string_text.txt |
Q:
Why "while loop" does not run in txt file reading in Python?
I have the following code which reads txt file.
def get_line(filepath):
f = open(filepath, "r")
while True:
line = f.readline()
print(line)
f.close()
print ("Start...")
get_line("/path/to/file/textfile.txt")
prin... | Why "while loop" does not run in txt file reading in Python? | I have the following code which reads txt file.
def get_line(filepath):
f = open(filepath, "r")
while True:
line = f.readline()
print(line)
f.close()
print ("Start...")
get_line("/path/to/file/textfile.txt")
print ("Stop...")
The code runs without the "while" loop. Once I add ... | [
"f.readline() on a file open in text mode returns the empty string when it reaches the end of the file; the black screen is the infinite series of prints that produce a newline and nothing else.\nYou don't want a while loop for this case generally; the Pythonic solution is:\ndef get_line(filepath):\n with open(f... | [
1,
0,
0,
0
] | [
"The True will produce an infinite loop. Try this instead\ndef get_line(filepath): \n with open(filepath, \"r\") as f: \n for line in f.readlines(): ... | [
-1
] | [
"python",
"while_loop"
] | stackoverflow_0074198615_python_while_loop.txt |
Q:
sys:1: RuntimeWarning: coroutine was never awaited
I'm trying to write a request handler to help me send request in async mode. It prompt when I close the python terminal with Ctrl+D or exit()
It shows sys:1: RuntimeWarning: coroutine was never awaited
import asyncio
import urllib.request
import json
class Reque... | sys:1: RuntimeWarning: coroutine was never awaited | I'm trying to write a request handler to help me send request in async mode. It prompt when I close the python terminal with Ctrl+D or exit()
It shows sys:1: RuntimeWarning: coroutine was never awaited
import asyncio
import urllib.request
import json
class RequestHandler:
def SendPostRequest(method="post",url=Non... | [
"I think you're confusing JS async API with Python's. In Python, when you call a coroutine function it returns a coroutine (similar to an armed generator) but doesn't schedule it in the event loop. (i.e. doesn't run/consume it)\nYou have two options:\n1) You can await it via await or the older yield from.\n2) You c... | [
27,
6
] | [
"I got the same error with test() as shown below:\nasync def test():\n print(\"test\")\n\ntest() # Here\n\n\nRuntimeWarning: coroutine 'test' was never awaited RuntimeWarning:\nEnable tracemalloc to get the object allocation traceback\n\nSo, I used asyncio.run() for test(), then the error above is solved:\nimpor... | [
-1
] | [
"asynchronous",
"coroutine",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0055756888_asynchronous_coroutine_python_python_3.x_python_asyncio.txt |
Q:
The Yahoo Finance S&P500 data (^GSPC) reaches back to 1950, why can I only download data from 1970 onwards?
import pandas_datareader.data as web
df = web.DataReader('^GSPC', 'yahoo', start='1950-01-03', end='2017-09-14')
If I go on the Yahoo Finance website I can manually download data from 1950, so why can't I... | The Yahoo Finance S&P500 data (^GSPC) reaches back to 1950, why can I only download data from 1970 onwards? | import pandas_datareader.data as web
df = web.DataReader('^GSPC', 'yahoo', start='1950-01-03', end='2017-09-14')
If I go on the Yahoo Finance website I can manually download data from 1950, so why can't I do that using pandas datareader? I mean I got the data already, just curious about why it didn't work.
Edit: I g... | [
"You may try package yfinance.\nsp500 = yf.Ticker('^GSPC')\n\nsp500.history(period = 'max')\n\n",
"It is because 1970,1,1 is the beginning of time as far as datetime is concerned.\nRefer to: https://kb.narrative.io/what-is-unix-time\n"
] | [
0,
0
] | [] | [] | [
"pandas_datareader",
"python"
] | stackoverflow_0046232774_pandas_datareader_python.txt |
Q:
Compare two folders have same files
I'm new to python and I'm trying to compare two folders and have them both have the same files. These files have the same name. That is, in folder 'A' it has the files 'image1.jpg', 'image2.jpg', image3.jpg' and folder 'B' has only 'image1.jpg', 'image2.jpg'. I would like both f... | Compare two folders have same files | I'm new to python and I'm trying to compare two folders and have them both have the same files. These files have the same name. That is, in folder 'A' it has the files 'image1.jpg', 'image2.jpg', image3.jpg' and folder 'B' has only 'image1.jpg', 'image2.jpg'. I would like both folders to be compared and, in this exampl... | [
"Simply read file names to list & compare list. #Not tested#Logic you can try\nimport glob\nfrom pathlib import Path \nimport os\n\nimg_folder_A_list = []\nfor img in glob.glob(\"C:/Users/Lenovo/OneDrive/Escritorio/0/*.jpg\"):\n fname= Path(img).name\n img_folder_A_list.append(fname)\n\nimg_folder_B_list = ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074198482_python.txt |
Q:
How do I determine if a Python sqlite UPDATE worked?
I'm using sqlite3 in Python. I want to know if my UPDATE statement worked or not without doing another database query:
c.execute('update students set gpa=3.5 where stuid=123')
If there isn't a student with stuid 123 then obviously the update fails.
A:
cursor.... | How do I determine if a Python sqlite UPDATE worked? | I'm using sqlite3 in Python. I want to know if my UPDATE statement worked or not without doing another database query:
c.execute('update students set gpa=3.5 where stuid=123')
If there isn't a student with stuid 123 then obviously the update fails.
| [
"cursor.rowcount will be 1 if the update was successful (affecting 1 row) or 0 if it failed.\n",
"For a slightly more complete answer for if you want to handle error and success:\nc.execute('update students set gpa=3.5 where stuid=123')\n\nif c.rowcount < 1:\n #error\nelse:\n #success\n\n",
"command = \"\... | [
48,
1,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005006835_python_sqlite.txt |
Q:
Pandas groupby cumulative sum,mean,median based on the flag values
I need to calculate cumulative calculations (sum,mean,median,etc) based on the values of Indicator
It should do the calculations for all the false indicator and print it adjacent to the true.
then calculated value should reset and start from true ... | Pandas groupby cumulative sum,mean,median based on the flag values | I need to calculate cumulative calculations (sum,mean,median,etc) based on the values of Indicator
It should do the calculations for all the false indicator and print it adjacent to the true.
then calculated value should reset and start from true until true appears again for Indicator.
Input data frame
Amount
Indi... | [
"Let's use cumsum of Indicator column as group key to get cumsum and size of Amount column\nm = df['Indicator'].cumsum()\n\ndf['Sum'] = df.groupby(m)['Amount'].cumsum().shift().where(df['Indicator'])\ndf['Mean'] = df['Sum'].shift(-1).div(df.groupby(m)['Amount'].transform('size')).shift()\n\nprint(df)\n\n Amount ... | [
1,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074198265_numpy_pandas_python.txt |
Q:
How to properly explode json and map to respective objects within arrays?
I have a dataframe with an array column in the below structure :
valueA
value B
First
[{"posts":[{"body":"post A"},{"body":"post B"},{"body":"post C"}],"subject":[{"id":"5571196","name":"author A","timestamp":"2021-10-20T08:41:09.124Z"},{"... | How to properly explode json and map to respective objects within arrays? | I have a dataframe with an array column in the below structure :
valueA
value B
First
[{"posts":[{"body":"post A"},{"body":"post B"},{"body":"post C"}],"subject":[{"id":"5571196","name":"author A","timestamp":"2021-10-20T08:41:09.124Z"},{"id":"1076004","name":"author B","timestamp":"2021-12-25T07:34:27.524Z"},{... | [
"If the json format is always consistent as in your example:\n\nuse the json module to read the string in valueB --> stuff\nstuff is a list with one item so stuff = stuff[0]\nthe body and posts are associated positionally in the data so zip them then iterate\nfor (body,post) in zip(stuff['posts'],stuff['subject']):... | [
0
] | [] | [] | [
"arrays",
"json",
"pyspark",
"python"
] | stackoverflow_0074197023_arrays_json_pyspark_python.txt |
Q:
How do I transfer data from an asynchronous loop running in a thread?
import asyncio
import threading
async def asyncio_loop():
i = 1
while True:
i += 1 # This value must be passed to mainloop()
def thread_function():
asyncio.run(asyncio_loop())
x = threading.Thread(target=thread_funct... | How do I transfer data from an asynchronous loop running in a thread? | import asyncio
import threading
async def asyncio_loop():
i = 1
while True:
i += 1 # This value must be passed to mainloop()
def thread_function():
asyncio.run(asyncio_loop())
x = threading.Thread(target=thread_function)
x.start()
def mainloop():
while True:
pass # Here I need... | [
"You can use the normal, threading queue.Queue - it will just work, The difference for the async.Queue is that the methods for putting and retrieving data int it are async themselves -but since you will be reading then from synchronous code, that would not work.\nOn the other hand, calling a synchronous queue.put... | [
0
] | [] | [] | [
"multithreading",
"python",
"python_asyncio"
] | stackoverflow_0074198832_multithreading_python_python_asyncio.txt |
Q:
query database using sqlite3.connect and check for matching results
My Discord bot queries a database and checks if there is a matching entry. To check for a matching entry I am using an if statement like here. But somehow my code is not working as expected:
def check_db_entry():
message = 'Some Message.'
... | query database using sqlite3.connect and check for matching results | My Discord bot queries a database and checks if there is a matching entry. To check for a matching entry I am using an if statement like here. But somehow my code is not working as expected:
def check_db_entry():
message = 'Some Message.'
user_id : int = 1234
# check if user already exists in database
... | [
"fetchone() returns None, which is not the same as false, if the query did not return any rows and this is what you should check.\nSo change to this:\nif result is None:\n print(f'\\nNo user found in db with {user_id}.\\n Create user')\nelse:\n print(f'\\nUser found in db with {user_id}.\\n') \n\nAlso, you sh... | [
1,
0
] | [] | [] | [
"discord.py",
"if_statement",
"nonetype",
"python",
"sqlite"
] | stackoverflow_0069709676_discord.py_if_statement_nonetype_python_sqlite.txt |
Q:
How can I make a deepcopy of a function in Python?
I would like to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation, which says:
This module does not copy types like module, method, stack trace, stack frame, file,
socket, window, array, or any similar typ... | How can I make a deepcopy of a function in Python? | I would like to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation, which says:
This module does not copy types like module, method, stack trace, stack frame, file,
socket, window, array, or any similar types. It does “copy” functions and classes (shallow
and... | [
"The FunctionType constructor is used to make a deep copy of a function.\nimport types\ndef copy_func(f, name=None):\n return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,\n f.func_defaults, f.func_closure)\n\ndef A():\n \"\"\"A\"\"\"\n pass\nB = copy_func(A, \"B\")\nB.__doc__... | [
32,
28,
8,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"copy",
"deep_copy",
"function",
"python"
] | stackoverflow_0006527633_copy_deep_copy_function_python.txt |
Q:
Evaluate a string that contains variable name on the fly in Python?
I have a string variable that contains the name of another variable
mystring = 'var1'
I seek to create a function that takes var1 as an input:
def myfun(var1):
res = somefun(var1)
return res
but instead of using the expression var1 direc... | Evaluate a string that contains variable name on the fly in Python? | I have a string variable that contains the name of another variable
mystring = 'var1'
I seek to create a function that takes var1 as an input:
def myfun(var1):
res = somefun(var1)
return res
but instead of using the expression var1 directly, I want to use the string. So sth like this:
def myfun(eval(mystring)... | [
"As said in the comments, use a dictionary here. Something like this:\nvar1 = 'blahblah'\nmy_dict = {\"mystring\":var1}\n\ndef myfunc(a_dict):\n res = somefunc(a_dict[\"mystring\"])\n return res\n \n# or\n\ndef myfunc2(a_dict, key_name):\n res = somefunc(a_dict[key_name])\n return res\n\nHere, you wo... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074198720_python.txt |
Q:
Issue with printing selenium output as the readable text instead of HTML code
I am trying to learn how to web scrape using selenium and have been watching a youtube series by Tech with Tim. I can't get my output of info scraped using selenium to display as text, only HTML code.
I tried this
driver.get("https://www... | Issue with printing selenium output as the readable text instead of HTML code | I am trying to learn how to web scrape using selenium and have been watching a youtube series by Tech with Tim. I can't get my output of info scraped using selenium to display as text, only HTML code.
I tried this
driver.get("https://www.techwithtim.net/")
search = driver.find_element("name","s")
search.send_keys("... | [
"You probably need to use find_element there, not find_elements.\nAs following:\narticles = main.find_elements(By.TAG_NAME, \"article\")\nfor article in articles:\n header = article.find_element(By.CLASS_NAME, \"entry-summary\")\n print(header.text)\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074198852_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt |
Q:
Use an input value along with a def function
i'm a begginer at phyton, and i am trying to create a function that indicates if is true or false if an even number is true or false.
This function is already working, but now i am trying to pass the function with a value given through the input function.
This is my cod... | Use an input value along with a def function | i'm a begginer at phyton, and i am trying to create a function that indicates if is true or false if an even number is true or false.
This function is already working, but now i am trying to pass the function with a value given through the input function.
This is my code:
def isprime (value):
value=int(input("... | [
"The issue here is you need to pass the value to make the code work. However, you are taking the input inside the function. Therefore, you need to take the input outside the function.\nvalue = int(input(\"Enter a number: \"))\nisprime(value)\n\n",
"You just need to call the function with an argument int(input(\"E... | [
1,
0,
0,
0
] | [] | [] | [
"function",
"input",
"python"
] | stackoverflow_0074198812_function_input_python.txt |
Q:
Giving different names to df using a for loop
I have a df in python with different cities.
I am trying to create a df for each city.
So wrote this code in python and it works. It does what I need. But i was wondering if there is any over way to create the name of each df in a different way rather than using
globa... | Giving different names to df using a for loop | I have a df in python with different cities.
I am trying to create a df for each city.
So wrote this code in python and it works. It does what I need. But i was wondering if there is any over way to create the name of each df in a different way rather than using
globals()\["df\_"+str(ciudad)\] = new_grouped_by
If I t... | [
"A simple way would be to store the dataframes in a dictionary with the city names as keys:\nimport pandas as pd\n\ndata = zip(['Amsterdam', 'Amsterdam', 'Barcelona'],[1,22,333])\ndf = pd.DataFrame(data, columns=['Ciudad', 'data'])\nnew_dfs = dict(list(df.groupby('Ciudad')))\n\nCalling new_dfs['Amsterdam'] will the... | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"global",
"python"
] | stackoverflow_0074198651_dataframe_for_loop_global_python.txt |
Q:
Negative value prints as big number in python
im pulling data from a modbusTCP server, but when i should receive a negative value it shows as a big number.
self.export = self.c.read_holding_registers(37113, 2)[1]
I know it has something to do with it being signed or unsigned but im really having trouble solving i... | Negative value prints as big number in python | im pulling data from a modbusTCP server, but when i should receive a negative value it shows as a big number.
self.export = self.c.read_holding_registers(37113, 2)[1]
I know it has something to do with it being signed or unsigned but im really having trouble solving it.
print("export: " + "{:02f}W".format(sel... | [
"The bytes received is implicitley cast to an unsigned int.\nTo convert to a signed int we\n\nuse the Int.to_bytes() to get the bytes and\nuse the int.from_bytes() to get the signet int.\n\nvarBytes = theInteger.to_bytes(2, 'big') # getting raw bytes\nsignedInt = int.from_bytes(varByte... | [
0,
0
] | [] | [] | [
"pymodbustcp",
"python",
"unsigned"
] | stackoverflow_0074087534_pymodbustcp_python_unsigned.txt |
Q:
Assign part of a string to list
I'm trying to extract text from a PDF using PDFminer.six, is there a way to find all instances of a certain phrase appearing in that string. I know a way to find the phrases and remove them but I can't seem to save the text around the phrase to a variable or list. Is there an easy w... | Assign part of a string to list | I'm trying to extract text from a PDF using PDFminer.six, is there a way to find all instances of a certain phrase appearing in that string. I know a way to find the phrases and remove them but I can't seem to save the text around the phrase to a variable or list. Is there an easy way to do this that I've overlooked?
f... | [
"def extract_phrase(keyword='vejkode', file='test.pdf', window=30):\n text = extract_text(file)\n start = text.find(keyword)\n end = start + len(keyword)\n phrase = text[start - window:end + window]\n return phrase.split()[1:-1] # trim truncated words at each end\n\n"
] | [
0
] | [] | [] | [
"pdfminer",
"python"
] | stackoverflow_0074198927_pdfminer_python.txt |
Q:
Filter Data and use information of one filter to fill the second filter
I would like to know how to write a program to filter data into two filters. The first filter has all data with length of 2 and the second has all data with length of 3. After I get that, I would like to populate the filter with length 2 with ... | Filter Data and use information of one filter to fill the second filter | I would like to know how to write a program to filter data into two filters. The first filter has all data with length of 2 and the second has all data with length of 3. After I get that, I would like to populate the filter with length 2 with the third information from those data with length 3 and prints all data again... | [
"\nfilter data into two filters\n\nYour if statement will handle that fine. You don't need a try-catch since you could add a print statement to the else statement, where only frequency is defined.\n\ndon't want to put the data inside a dictionary or a list\n\nYou need to. Otherwise, you will be unable to track line... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074196716_python.txt |
Q:
Scrape information about Visit Page and App Name on google play store
I have created the code below to scrape the app name and Visit Page Url from the google play store page.
ASOS - Get ASOS (Line 1120)
Visit website - Get http://www.asos.com - (q=)(Line 1121 source code)
url = 'https://play.google.com/s... | Scrape information about Visit Page and App Name on google play store | I have created the code below to scrape the app name and Visit Page Url from the google play store page.
ASOS - Get ASOS (Line 1120)
Visit website - Get http://www.asos.com - (q=)(Line 1121 source code)
url = 'https://play.google.com/store/apps/details?id=com.asos.app'
r = requests.get(url)
final=[]
for line... | [
"Google Play Store has been redesigned, now it is dynamic and the data we need stored as inline JSON.\nYou can still use selenium or playwright webdriwer to parse it. However, in our case, we can use the BeautifulSoup and regular expression to extract pretty much everything from the app page.\nFirstly, extract cert... | [
2,
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0038449327_html_python.txt |
Q:
Creating a dictionary of words as keys mapped to their instances in a set of 'documents'
I need to take a list of tuples that includes sentences that are preprocessed as such (the 0 is an integer that corresponds to the publication, and the set at the end finds all unique words in the sentence):
(0, 'political com... | Creating a dictionary of words as keys mapped to their instances in a set of 'documents' | I need to take a list of tuples that includes sentences that are preprocessed as such (the 0 is an integer that corresponds to the publication, and the set at the end finds all unique words in the sentence):
(0, 'political commentators on both sides of the political divide agreed that clinton tried to hammer home the d... | [
"Parsing that string is hard and you have pretty much just done a brute force extraction of data. Instead of trying to guess whether that's going to work on all possible input, you can use python's ast module to convert literals (what you type into a python program to represent stings, tuples, sets and so forth) in... | [
2
] | [] | [] | [
"dictionary",
"nlp",
"python"
] | stackoverflow_0074197478_dictionary_nlp_python.txt |
Q:
Spotify api | my python script won't run when my Spotify app is turned off
I would like to make a script in python that retrieves what I'm listening to in real time on Spotify and allow me to send the information to an Arduino,
But the problem is that my script refuses to run when my Spotify is turned off, knowin... | Spotify api | my python script won't run when my Spotify app is turned off | I would like to make a script in python that retrieves what I'm listening to in real time on Spotify and allow me to send the information to an Arduino,
But the problem is that my script refuses to run when my Spotify is turned off, knowing that I have other information that passes between my PC and my Arduino and if ... | [
"You can catch JSONDecodeError if resource by url dont response correct json.\nfrom json.decoder import JSONDecodeError\n\ntry:\n json_resp = response.json()\nexcept JSONDecodeError:\n # Not json. No data. Return err.\n\n",
"Thank you very much for your quick response, it works!\nHere is my code now :\ndef ... | [
1,
0
] | [] | [] | [
"python",
"spotify"
] | stackoverflow_0074198556_python_spotify.txt |
Q:
How to hold a button using Python
I need to hold button ("A") for few seconds. I tried lots of libs and methods, but nothing not works. Every exemples what I tried was identical("A" pressed by one time, dont hold)
This is my code:
import pyautogui as pag
import time
pag.keyDown("a")
time.sleep(10)
pag.keyUp("a")
... | How to hold a button using Python | I need to hold button ("A") for few seconds. I tried lots of libs and methods, but nothing not works. Every exemples what I tried was identical("A" pressed by one time, dont hold)
This is my code:
import pyautogui as pag
import time
pag.keyDown("a")
time.sleep(10)
pag.keyUp("a")
But it does not work. "A" pressed only... | [
"From the pyautogui.keyDown() documentation: it \"performs a keyboard key press without the release.\" So this should put that key in a held down state.\nFor sequential pressing, try\nimport time, pyautogui\nhold_time = 10\nstart = time.time()\nwhile time.time() - start < hold_time:\n pyautogui.press('A')\n\n",
... | [
0,
0
] | [] | [] | [
"keyboard",
"pyautogui",
"python"
] | stackoverflow_0074198333_keyboard_pyautogui_python.txt |
Q:
Seaborn AttributeError: module 'seaborn' has no attribute 'displot' AND conda Solving environment fail
As per seaborn documentation here seaborn.distplot() has been deprecated with the forward going supported plots being: seaborn.displot() and seaborn.histplot().
However, when I try to use either of displot() or h... | Seaborn AttributeError: module 'seaborn' has no attribute 'displot' AND conda Solving environment fail | As per seaborn documentation here seaborn.distplot() has been deprecated with the forward going supported plots being: seaborn.displot() and seaborn.histplot().
However, when I try to use either of displot() or histplot() I get the following Attribute error:
AttributeError: module 'seaborn' has no attribute 'displot'
N... | [
"displot() has been introduced in Seaborn v0.11.0, see the changelog: https://seaborn.pydata.org/whatsnew.htmlhttps://seaborn.pydata.org/whatsnew.htmlhttps://seaborn.pydata.org/whatsnew.html\nFrom your code, you are importing v0.10.1.\n",
"Try installing with pip:\npip install seaborn==0.11.0\n",
"Just run the ... | [
3,
3,
1
] | [] | [] | [
"anaconda",
"conda",
"python",
"seaborn"
] | stackoverflow_0064487685_anaconda_conda_python_seaborn.txt |
Q:
Tiebreaker for maximum value in pandas row
The sample of the dataset I am working on:
import pandas as pd
# List of Tuples
matrix = [(1, 0.3, 0, 0.7, 30, 0, 50),
(2, 0.4, 0.4, 0.3, 20, 50, 30),
(3, 0.5, 0.2, 0.3, 30, 20, 30),
(4, 0.7, 0, 0.3, 100, 0, 40),
(5, 0.2, 0.4, 0.4, ... | Tiebreaker for maximum value in pandas row | The sample of the dataset I am working on:
import pandas as pd
# List of Tuples
matrix = [(1, 0.3, 0, 0.7, 30, 0, 50),
(2, 0.4, 0.4, 0.3, 20, 50, 30),
(3, 0.5, 0.2, 0.3, 30, 20, 30),
(4, 0.7, 0, 0.3, 100, 0, 40),
(5, 0.2, 0.4, 0.4, 50, 30, 80)
]
# Create a DataFrame
df ... | [
"Use numpy.where.\nIn the first two lines I create two subsets just for easier referencing.\nThen I use numpy.where to check whether a rows maximum occurs more than once. If yes, I check the other three columns.\nimport numpy as np\nss1 = df[[\"terror\", \"drama\", \"action\"]]\nss2 = df[[\"val_terror\", \"val_dram... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074198995_dataframe_pandas_python.txt |
Q:
Read csv with json column which is nested multiple times into dataframe
I have the following csv file with a json column data. The json data is a little bit complicated and I can't unwrap it the way I want. My goal is to get some data from configuration into columns and the corrosponding values from readings into ... | Read csv with json column which is nested multiple times into dataframe | I have the following csv file with a json column data. The json data is a little bit complicated and I can't unwrap it the way I want. My goal is to get some data from configuration into columns and the corrosponding values from readings into the row as value. I found something here but I can't go deeper in the nested ... | [
"If your_file.csv contains:\nsystem;datetime;data;\nACD;19.10.2021 11:24:00,000;{\"id\":\"device1\",\"type\":\"dataValues\",\"payload\":{\"deviceId\":\"device1\",\"start\":\"2021-10-19 11:23:00.000\",\"end\":\"2021-10-19 11:24:00.000\",\"configuration\":[{\"name\":\"DD51\",\"id\":1},{\"name\":\"VV22\",\"id\":2}],\"... | [
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074198987_json_pandas_python.txt |
Q:
Adding count information to mapreduce output
I have data that came from sys.stdout mapper.py program as follows:
input from stdout of previous mapper.py
chevy, {mod: spark | col: brown}
chevy, {mod: equinox | col: red}
honda, {mod:civic | col:black}
honda, {mod:accord | col:white}
honda, {mod:crv | col:pink}
hon... | Adding count information to mapreduce output | I have data that came from sys.stdout mapper.py program as follows:
input from stdout of previous mapper.py
chevy, {mod: spark | col: brown}
chevy, {mod: equinox | col: red}
honda, {mod:civic | col:black}
honda, {mod:accord | col:white}
honda, {mod:crv | col:pink}
honda, {mod:hrv | col:gray}
toyota, {mod:corola | co... | [
"At the time you print each total, you're only accounting for the lines you've seen up-to that point.\nYou need to read all lines, capturing the correct \"total\", then print all output. You will need to use dictionaries and lists to do this, as shown in your new question.\n"
] | [
0
] | [] | [] | [
"hadoop",
"hadoop_streaming",
"mapreduce",
"python"
] | stackoverflow_0074173010_hadoop_hadoop_streaming_mapreduce_python.txt |
Q:
Seaborn Swarmplot "hue" not coloring correctly / as expected
When I graph my data with Seaborn swarmplot, it orders the overlapping points "middle out". Meaning, the larger levels are in the middle and the smaller are on the edges (like 1,1,2,2,1,1 or 2,2,3,4,2,2). This messes up the hue coloration as confirmed by... | Seaborn Swarmplot "hue" not coloring correctly / as expected | When I graph my data with Seaborn swarmplot, it orders the overlapping points "middle out". Meaning, the larger levels are in the middle and the smaller are on the edges (like 1,1,2,2,1,1 or 2,2,3,4,2,2). This messes up the hue coloration as confirmed by getting the index of the point that I am hovering over and labeli... | [
"\n* Edit (per mwaskom) *\nAs of September 2022 and Seaborn v0.12.0 the Swarm plot no longer reorders the points for the plot, effectively making this a non-issue and my above code (in the question) viable.\n\nApparently (according to @JohanC), the swarmplot rearranges the order of the points when it is created, so... | [
1
] | [] | [] | [
"matplotlib",
"mplcursors",
"python",
"seaborn"
] | stackoverflow_0074197853_matplotlib_mplcursors_python_seaborn.txt |
Q:
Data are overwrite how to solve that
With every iteration through the loop, the previously extracted data is overwritten. How can I solve this problem?
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webd... | Data are overwrite how to solve that | With every iteration through the loop, the previously extracted data is overwritten. How can I solve this problem?
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select
from se... | [
"I think you need to define item=dict() inside the for loop. Otherwise this is the same, single item object used in all the loop iterations.\nTry this:\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.... | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"pandas",
"python",
"selenium"
] | stackoverflow_0074199150_dataframe_for_loop_pandas_python_selenium.txt |
Q:
python + opencv find image in screen area and return x, y
I'm trying to locate an image based on x, y of the screen, that is, look for the image under a certain window that I already know the coordinates and size and so check if the image is in it or not, for that I would like to use opencv , I have something simi... | python + opencv find image in screen area and return x, y | I'm trying to locate an image based on x, y of the screen, that is, look for the image under a certain window that I already know the coordinates and size and so check if the image is in it or not, for that I would like to use opencv , I have something similar that I found in a script on github
the problem is that the ... | [
"for future readers the solution found was with Imagegrab from PIL, you can pass the coords and generate an image to compare things\ndef GetImageFromScreen(coords):\n img = np.array(ImageGrab.grab(bbox=(coords)))\n img = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2RGB)\n cv2.imshow('Test', img)\n cv2.waitK... | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074195399_opencv_python.txt |
Q:
How to fetch information from web page chain wise(solving captcha)?
I have to go to here
Here I have to choose applicant name = “ltd”
But here before submitting the page, I have to solve a captcha. How to fetch the next page's information(application number, application title, date, application status etc.....) ... | How to fetch information from web page chain wise(solving captcha)? | I have to go to here
Here I have to choose applicant name = “ltd”
But here before submitting the page, I have to solve a captcha. How to fetch the next page's information(application number, application title, date, application status etc.....) in an excel format using web scrapping?
---------------- Running the foll... | [
"On this site, captcha can be solved without resorting to third-party services. When you click on the \"Captcha Audio\" button, a GET request is sent to the endpoint https://ipindiaservices.gov.in/PublicSearch/Captcha/CaptchaAudio The response is a dictionary {\"CaptchaImageText\":\"hnnxd\"} which you can access ge... | [
3,
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074167156_python_web_scraping.txt |
Q:
How do i use the "next" url for post request?
So how does python call the "next" page in a post request?
I know what i neeed to do, but not sure how to implement, all the examples in youtube use a # and not a cursor, being a semi beginner i am a bit confused
This is my code so far:
def main_request(headers, url1, ... | How do i use the "next" url for post request? | So how does python call the "next" page in a post request?
I know what i neeed to do, but not sure how to implement, all the examples in youtube use a # and not a cursor, being a semi beginner i am a bit confused
This is my code so far:
def main_request(headers, url1, params):
response = requests.post(url1, header... | [
"Given your jsonData as input, you can use this code to get the next url and assign it to url1:\nfor item in jsonData.get(\"links\", []):\n if item[\"rel\"] == \"next\":\n url1 = item[\"href\"]\n break\n\nThis only finds the first url. If you need all urls, I'd recommend adding all urls to a list.\... | [
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074199197_python_python_requests.txt |
Q:
Trying to web scrape text from a table on a website
I am a novice at this, but I've been trying to scrape data on a website (https://awards.decanter.com/DWWA/2022/search/wines?competitionType=DWWA) but I keep coming up empty. I've tried BeautifulSoup and Scrapy but I can't get the text out.
Eventually I want to ge... | Trying to web scrape text from a table on a website | I am a novice at this, but I've been trying to scrape data on a website (https://awards.decanter.com/DWWA/2022/search/wines?competitionType=DWWA) but I keep coming up empty. I've tried BeautifulSoup and Scrapy but I can't get the text out.
Eventually I want to get the row of each individual wine in the table into a dat... | [
"When you load a site you want to scrape, always inspect what it loads with the network monitor. In this case you see that it loads the data dynamically from an api. This means that you can skip scraping altogether and load the data directly from the api into pandas:\nimport pandas as pd\n\ndf = pd.read_json('https... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074199117_beautifulsoup_python_scrapy_web_scraping.txt |
Q:
how to solve it trying to solve it
Writing a python web client to access an API of an online supermarket. The API details are given below.
Base URL= http://host1.open.uom.lk:8080
Route Table
Write a python program to create a new product with the following information in JSON format. Print the response code of th... | how to solve it trying to solve it | Writing a python web client to access an API of an online supermarket. The API details are given below.
Base URL= http://host1.open.uom.lk:8080
Route Table
Write a python program to create a new product with the following information in JSON format. Print the response code of the request.
{
"productName":"Aral... | [
"import requests\n\ndata = { \"productName\":\"Araliya Basmathi Rice\", \"description\":\"White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.\", \"category\":\"Rice\", \"brand\":\"CIC\", \"expiredDate\":\"2023.05.04\", \"manufacturedDate\":\"2022.02.20\", \"batchNu... | [
1,
0
] | [] | [] | [
"api",
"json",
"python"
] | stackoverflow_0074089172_api_json_python.txt |
Q:
How to return a boolean to check if elements in two dicts are the same in python dictionaries?
I have two dictionaries:
dict1 = {
'Argentina': ['Buenos Aires'],
'Bangladesh': ['Dhaka'],
'Brazil': ['São Paulo', 'Rio de Janeiro']
dict2 = {
1392685764: 'Tokyo', 1356226629: 'Mumbai', 1156073548: 'Shan... | How to return a boolean to check if elements in two dicts are the same in python dictionaries? | I have two dictionaries:
dict1 = {
'Argentina': ['Buenos Aires'],
'Bangladesh': ['Dhaka'],
'Brazil': ['São Paulo', 'Rio de Janeiro']
dict2 = {
1392685764: 'Tokyo', 1356226629: 'Mumbai', 1156073548: 'Shanghai',
1484247881: 'Mexico City', 1156237133: 'Guangzhou', 1818253931: 'Cairo',
1156228865: ... | [
"It seems that dict1 has lists as values, so you need to \"chain\" them into a single list first. You cat try something like this:\nfrom itertools import chain\nset(chain(*dict1.values())) == set(dict2.values())\n\nIt's unclear how you want to use id and country, so I've left this out of the function.\n",
"You ne... | [
1,
1
] | [
"Both dictionaries and sets are unordered which is probably why you're getting different results. Assuming Python, you could do something like this:\ndef has_same_values(d1, d2):\n values1 = []\n values2 = []\n for key in d1.keys():\n values1.extend(d1[key])\n for key in d2.keys():\n value... | [
-1
] | [
"dictionary",
"python"
] | stackoverflow_0074199173_dictionary_python.txt |
Q:
How to remove a grid point in xarray?
I am trying to find the nearest grid point to a weather station given a latitude and longitude. The grid point that is returned when I find the nearest using df=df.sel(latitude=Lat.to_xarray(), longitude=Lon.to_xarray(), method='nearest')
is full of Nan values. Because of this... | How to remove a grid point in xarray? | I am trying to find the nearest grid point to a weather station given a latitude and longitude. The grid point that is returned when I find the nearest using df=df.sel(latitude=Lat.to_xarray(), longitude=Lon.to_xarray(), method='nearest')
is full of Nan values. Because of this I want to find the second nearest grid poi... | [
"TL;DR\nYou cannot drop an arbitrary point from the middle of an array. The array is a [hyper]cube, so it's impossible to \"remove\" a point from the middle of the cube. Instead, if you're trying to extract nearest-non-null-neighbors, you need to set up a custom interpolator to facilitate extracting your data. Luck... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_xarray"
] | stackoverflow_0074197804_numpy_pandas_python_python_xarray.txt |
Q:
Identifying different date patterns in python list
I have this sample logs data in a list
data = ["[2022-08-15 17:42:32,436: INFO/MainProces] lorqw q addadasdasdasdad",
"2022-10-24T13:29:50.579Z dasdadasdasdadadadadaddada",
"asdadadad adasdas3453 454234 fsdf53",
"Mon, 24 Oct 2022 13:29:48 GMT express:router expres... | Identifying different date patterns in python list | I have this sample logs data in a list
data = ["[2022-08-15 17:42:32,436: INFO/MainProces] lorqw q addadasdasdasdad",
"2022-10-24T13:29:50.579Z dasdadasdasdadadadadaddada",
"asdadadad adasdas3453 454234 fsdf53",
"Mon, 24 Oct 2022 13:29:48 GMT express:router expressInit : /health",
'time="2022-10-24T13:29:12Z" level=err... | [
"Since the only real repeating part of the date is the time, I'd chase the time with a regex:\nfor index, entry in enumerate(data):\n if re.search(r'(\\s|T)[0-9]{2}\\:[0-9]{2}\\:[0-9]{2}([\\.\\,][0-9]+)*', entry):\n print(f\"Found date in {index}\")\n\n\n",
"You can use this collection of regular expressions\... | [
1,
1
] | [] | [] | [
"arrays",
"list",
"python",
"python_3.x",
"string"
] | stackoverflow_0074199058_arrays_list_python_python_3.x_string.txt |
Q:
Implementing TCP Server with Python-How to?
I have searched a lot on the forums for implementing TCP server using Python. All that I could find is a multi-threaded approach to TCP Server Implementation on a single port for interacting with clients.
I am looking for Server sample code for creating sockets using dif... | Implementing TCP Server with Python-How to? | I have searched a lot on the forums for implementing TCP server using Python. All that I could find is a multi-threaded approach to TCP Server Implementation on a single port for interacting with clients.
I am looking for Server sample code for creating sockets using different ports.I have clients with distinct port nu... | [
"import socket\nfrom typing import Union\n\n\nSERVERS_PORT_LIST = []\n\n\ndef start_server(port) -> Union[socket.socket, None]:\n server_socket = socket.socket()\n try:\n server_socket.bind((\"0.0.0.0\", port))\n server_socket.listen()\n return server_socket\n except (socket.error, OSE... | [
0,
0
] | [] | [] | [
"python",
"server",
"tcp"
] | stackoverflow_0074194181_python_server_tcp.txt |
Q:
AttributeError: module 'collections' has no attribute 'MutableSet'
I've written an MLflow component to upload & log an artifact from a URL to WandB. I am trying to run the script inside a conda environment but unfortunately I am facing this error
File "C:\anaconda\envs\mlflow-4b67c93d2a95df2e00cbf3c9f644d2e3dada00... | AttributeError: module 'collections' has no attribute 'MutableSet' | I've written an MLflow component to upload & log an artifact from a URL to WandB. I am trying to run the script inside a conda environment but unfortunately I am facing this error
File "C:\anaconda\envs\mlflow-4b67c93d2a95df2e00cbf3c9f644d2e3dada00e0\lib\site-packages\wandb\__init__.py", line 38, in <module>
from w... | [
"I have this problem when I code with python, in the new version of python collections have no more MutableSet, MutableMapping, etc.. But the module collections.abc have it so if you want you can go like this:\nimport collections \nif sys.version_info.major == 3 and sys.version_info.minor >= 10\n from collection... | [
1
] | [] | [] | [
"anaconda",
"mlflow",
"python",
"wandb"
] | stackoverflow_0074006130_anaconda_mlflow_python_wandb.txt |
Q:
How to manually sort rows in a multi-index dataframe?
Yo, here's an example of a dataframe I'm currently working on
a b
_____________
0 1 1.1
1 2 1.2
2 3 2.1
3 NaN 2.2
4 NaN 2.3
5 NaN 3.1
6 NaN 3.2
7 NaN 3.3
8 NaN 3.4
Ho... | How to manually sort rows in a multi-index dataframe? | Yo, here's an example of a dataframe I'm currently working on
a b
_____________
0 1 1.1
1 2 1.2
2 3 2.1
3 NaN 2.2
4 NaN 2.3
5 NaN 3.1
6 NaN 3.2
7 NaN 3.3
8 NaN 3.4
However, I wanted to sort this dataframe in a way that it can... | [
"You can try\ndf['new']= df['b'].astype('int')\n\ndf.loc[df['new'].duplicated(), 'new'] = ''\n\n\ndf = df.drop(columns=['a'])\ndf.columns=['b','a']\n\ndf.index =df['a']\n\ndf_final = df['b'].reset_index() \n\n\nprint(df_final)\n\noutput#\n a b\n0 1 1.1\n1 1.2\n2 2 2.1\n3 2.2\n4 2.3\n5 3 3.1\... | [
0
] | [] | [] | [
"dataframe",
"indexing",
"pandas",
"python"
] | stackoverflow_0074198567_dataframe_indexing_pandas_python.txt |
Q:
Using later of two dates and then subtracting another date within groupby
I have a dataframe that looks something like this:
df = pd.DataFrame([1,'A','X','1/3/22 12:00:00AM','1/1/22 12:00:00 AM','1/2/22 12:00:00 AM'],
[1,'A','X','1/4/22 12:00:00AM','1/3/22 12:00:00 AM','1/3/22 12:00:00 AM'],
[1,'A','Y','1/3/22 12:... | Using later of two dates and then subtracting another date within groupby | I have a dataframe that looks something like this:
df = pd.DataFrame([1,'A','X','1/3/22 12:00:00AM','1/1/22 12:00:00 AM','1/2/22 12:00:00 AM'],
[1,'A','X','1/4/22 12:00:00AM','1/3/22 12:00:00 AM','1/3/22 12:00:00 AM'],
[1,'A','Y','1/3/22 12:00:00AM','1/2/22 12:00:00 AM','1/1/22 12:00:00 AM'],
[1,'B','X','1/3/22 12:00:0... | [
"Try:\ndf[\"Task Completed\"] = pd.to_datetime(\n df[\"Task Completed\"], format=\"%m/%d/%y %H:%M:%S%p\"\n)\ndf[\"Access Completed\"] = pd.to_datetime(\n df[\"Access Completed\"], format=\"%m/%d/%y %H:%M:%S %p\"\n)\ndf[\"Upload Completed\"] = pd.to_datetime(\n df[\"Upload Completed\"], format=\"%m/%d/%y %H... | [
3,
2
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074198255_group_by_pandas_python.txt |
Q:
i get wrong gdp data as error even if i didn't perform any operation on the data python pandas
AssertionError Traceback (most recent call last)
<ipython-input-4-c62566676721> in <module>
15 1589942641764.29,1664086754804.89,354237112582... | i get wrong gdp data as error even if i didn't perform any operation on the data python pandas | AssertionError Traceback (most recent call last)
<ipython-input-4-c62566676721> in <module>
15 1589942641764.29,1664086754804.89,3542371125827.81,1821872415623.62,
16 2702031788079.47,1134795571... | [
"Have you checked your data sources? It would appear that \"Q1: Wrong GDP Data!\" is an actual string that appeared while reading the GDP data leading to the error.\nI assumed you are working with this GDP dataset for \"world_bank.csv\". I downloaded it and ran the second part of your code that reads the .csv as th... | [
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074195963_pandas_python_python_3.x.txt |
Q:
Python How to I check if last element has been reached in iterator tool chain?
for elt in itertools.chain.from_iterable(node):
if elt is the last element:
do statement
How do I achieve this
A:
You can do this by manually advancing the iterator in a while loop using iter.next(), then catching the StopIteratio... | Python How to I check if last element has been reached in iterator tool chain? | for elt in itertools.chain.from_iterable(node):
if elt is the last element:
do statement
How do I achieve this
| [
"You can do this by manually advancing the iterator in a while loop using iter.next(), then catching the StopIteration exception:\n>>> from itertools import chain\n>>> it = chain([1,2,3],[4,5,6],[7,8,9])\n>>> while True:\n... try:\n... elem = it.next()\n... except StopIteration:\n... print \... | [
23,
12,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002058894_python.txt |
Q:
How to create unique name for each user’s input?
x = int(input())
for i in range(n):
x(i) = input()
print(x, x1, x2,…)
It has an error. I know it’s wrong, but can I do it?
A:
Like @Random Davis mentioned, you can append them to a list.
This snippet takes in x as how many user inputs to take, then adds each ... | How to create unique name for each user’s input? | x = int(input())
for i in range(n):
x(i) = input()
print(x, x1, x2,…)
It has an error. I know it’s wrong, but can I do it?
| [
"Like @Random Davis mentioned, you can append them to a list.\nThis snippet takes in x as how many user inputs to take, then adds each user input to input_values list:\nx = int(input())\ninput_values = []\nfor i in range(x):\n input_values.append(input())\n\nNow you can access all the user inputs in the list all... | [
0
] | [] | [] | [
"python",
"syntax",
"variables"
] | stackoverflow_0074199196_python_syntax_variables.txt |
Q:
Convert image bytestring entry in pandas dataframe to image in opencv
I am trying to convert image data saved in a rosbag file to numpy arrays and opencv images for further processing. I can not use cv_bridge or any of the other ROS utils.
I read the rosbag using the bagpy module here. And convert the data to a pa... | Convert image bytestring entry in pandas dataframe to image in opencv | I am trying to convert image data saved in a rosbag file to numpy arrays and opencv images for further processing. I can not use cv_bridge or any of the other ROS utils.
I read the rosbag using the bagpy module here. And convert the data to a pandas dataframe:
import numpy as np
import cv2
import bagpy
from bagpy impor... | [
"Your image is pure rgb8 pixels in a bytes type. That means:\n\nit isn't a str and you shouldn't treat it as such, and\nit isn't JPEG-encoded or PNG-encoded, so you shouldn't be passing it to cv2.imdecode() because that decompresses images and turns them into Numpy arrays of pixels, which is nearly what you already... | [
0,
0
] | [] | [] | [
"numpy",
"opencv",
"python",
"ros",
"rosbag"
] | stackoverflow_0073982460_numpy_opencv_python_ros_rosbag.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.