content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to split a Multiindex row into two Multiindex rows?
I have a dataframe with multiple levels of Multiindex. One of the levels is latlon, which is a string of the numbers with an ; between them.
However, for further processing, it makes much more sense to have a lat level and a lon level. with floats for the num... | How to split a Multiindex row into two Multiindex rows? | I have a dataframe with multiple levels of Multiindex. One of the levels is latlon, which is a string of the numbers with an ; between them.
However, for further processing, it makes much more sense to have a lat level and a lon level. with floats for the numbers, instead of the combined string.
How do I best partition... | [
"I would temporarily convert the MultiIndex to DataFrame to benefit from DataFrame's methods:\nnew_idx = pd.MultiIndex.from_frame(\n df.columns.to_frame()\n .pipe(lambda d: d.join(d.pop('latlon')\n .str.split(';', expand=True)\n .set_axis(['lat', 'lon'], axis=1)... | [
2,
1
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074545649_multi_index_pandas_python.txt |
Q:
Using OracleDB OS.Environment Password
I am trying to connect to an oracle database with Python code. I am using the OracleDB package but want it so that the user is able to connect to the DB with their own password machine and password rather than coding it into the code itself.
So far I have this,
import oracled... | Using OracleDB OS.Environment Password | I am trying to connect to an oracle database with Python code. I am using the OracleDB package but want it so that the user is able to connect to the DB with their own password machine and password rather than coding it into the code itself.
So far I have this,
import oracledb
import os
username=os.environ.get("Userna... | [
"Source the environment variables (Make them available to the python process)\n$cat env.sh\nexport USERNAME=app_schema\nexport PASSWORD=secret\n\n$cat connect.py\nimport oracledb\nimport os\n\nusername=os.environ.get(\"USERNAME\")\npw=os.environ.get(\"PASSWORD\")\nconn = oracledb.connect(user=username, password=pw,... | [
0
] | [] | [] | [
"oracle",
"python"
] | stackoverflow_0074539834_oracle_python.txt |
Q:
Failing to install lxml using pip
I am attempting to use pip to install lxml. I have Windows 11 and Python version python-3.10.2-amd64. I am using Visual Studio Code (VSC) as well. I realized I needed lxml from this error message in my VSC terminal:
Traceback (most recent call last):
File "Vegas.py", line 13, in <... | Failing to install lxml using pip | I am attempting to use pip to install lxml. I have Windows 11 and Python version python-3.10.2-amd64. I am using Visual Studio Code (VSC) as well. I realized I needed lxml from this error message in my VSC terminal:
Traceback (most recent call last):
File "Vegas.py", line 13, in <module>
soup = BeautifulSoup(html_text,... | [
"I am using windows 11 and python 3.11 so for the easy solution first I downloaded the latest 'lxml-4.9.0-cp311-cp311-win_amd64.whl' from the https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml\nThen copied it to my user folder which is \"C:\\Users\\memon\"\nAnd then run this command from the terminal:\npip install lx... | [
6,
0
] | [] | [] | [
"lxml",
"python",
"python_wheel"
] | stackoverflow_0071152710_lxml_python_python_wheel.txt |
Q:
How can you group a data frame and reshape from long to wide?
I am fairly new to Python, so excuse me if this question has been answered before or can be easily solved.
I have a long data frame with numerical variables and categorical variables. It looks something like this:
Category Detail Gender Weight
Food ... | How can you group a data frame and reshape from long to wide? | I am fairly new to Python, so excuse me if this question has been answered before or can be easily solved.
I have a long data frame with numerical variables and categorical variables. It looks something like this:
Category Detail Gender Weight
Food Apple Female 30
Food Apple Male 40
Beverage Milk ... | [
"Like so\ndf2 = df.pivot_table(\n index=['Category', 'Detail'], \n columns='Gender', \n values='Weight', \n aggfunc='sum'\n).fillna(0)\nfinal = df2[['Female', 'Male']].div(df2.sum(axis=1), axis=0)\n\nGender Female Male\nCategory Detail \nBeverage Milk 0.285714 0.7... | [
3,
3
] | [] | [] | [
"group_by",
"melt",
"pandas",
"pivot",
"python"
] | stackoverflow_0074545972_group_by_melt_pandas_pivot_python.txt |
Q:
Python : How to properly implement a raise an exception in a function
I am trying to make a function that receives a list/array and returns the index of the maximum
value in that sequence. The function should raise an exception if non-numerical values are
present in the list.
def maxvalue(values):
"""
Func... | Python : How to properly implement a raise an exception in a function | I am trying to make a function that receives a list/array and returns the index of the maximum
value in that sequence. The function should raise an exception if non-numerical values are
present in the list.
def maxvalue(values):
"""
Function that receives a list/array and returns the index of the maximum
va... | [
"The 'Comparison' happens in max function which raises an exception.\nYou should do all checks, before your logic.\ndef maxvalue(values):\n \"\"\"\n Function that receives a list/array and returns the index of the maximum\n value in that sequence\n\n \"\"\"\n\n try:\n max_value = max(values)\n... | [
1,
0
] | [] | [] | [
"function",
"indexing",
"max",
"python",
"typeerror"
] | stackoverflow_0074545604_function_indexing_max_python_typeerror.txt |
Q:
Column created with label() returns no values
this is the query
query = (
select(
User.id,
(func.sqrt(func.pow(User.dist[0] - (-4.23), 2))).label("dist"),
)
.order_by("dist")
.limit(1)
)
when I execute it I get the id but in place of dist I get None
A:
This query is correct and w... | Column created with label() returns no values | this is the query
query = (
select(
User.id,
(func.sqrt(func.pow(User.dist[0] - (-4.23), 2))).label("dist"),
)
.order_by("dist")
.limit(1)
)
when I execute it I get the id but in place of dist I get None
| [
"This query is correct and will work, I just did not realize indexing an Array in Postgres starts at 1 and not zero. It kept returning None with no errors so I thought my query had something to do with it.\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074536053_python_sqlalchemy.txt |
Q:
How to get particular index number of list items
my_list = ['A', 'B', 'C', 'D', 'E', 'B', 'F', 'D', 'C', 'B']
idx = my_list.index('B')
print("index :", idx)
In here I used the '.index()' function.
for i in my_list:
print(f"index no. {my_list.index(i)}")
I tried to find each index number of the items of the ... | How to get particular index number of list items | my_list = ['A', 'B', 'C', 'D', 'E', 'B', 'F', 'D', 'C', 'B']
idx = my_list.index('B')
print("index :", idx)
In here I used the '.index()' function.
for i in my_list:
print(f"index no. {my_list.index(i)}")
I tried to find each index number of the items of the (my_list) list.
But it gave same result for same value... | [
"There might be a more pythonic way to reorganize this array, however, with the following function you can loop through the list and append [letter, value] if value is a number, append [letter, ''] if value is a letter.\ndef_setter = []\ni = 0\nwhile i < len(my_list_2):\n if i + 1 == len(my_list_2):\n if ... | [
2
] | [] | [] | [
"arraylist",
"data_science",
"python"
] | stackoverflow_0074545933_arraylist_data_science_python.txt |
Q:
Python: How to check what types are in defined types.UnionType?
I am using Python 3.11 and I would need to detect if an optional class attribute is type of Enum (i.e. type of a subclass of Enum).
With typing.get_type_hints() I can get the type hints as a dict, but how to check if a field's type is optional Enum (s... | Python: How to check what types are in defined types.UnionType? | I am using Python 3.11 and I would need to detect if an optional class attribute is type of Enum (i.e. type of a subclass of Enum).
With typing.get_type_hints() I can get the type hints as a dict, but how to check if a field's type is optional Enum (subclass)? Even better if I could get the type of any optional field r... | [
"When you are dealing with a parameterized type (generic or special like typing.Optional), you can inspect it via get_args/get_origin.\nDoing that you'll see that T | S is implemented slightly differently than typing.Union[T, S]. The origin of the former is types.UnionType, while that of the latter is typing.Union.... | [
0
] | [] | [] | [
"python",
"python_3.11",
"type_hinting",
"union_types"
] | stackoverflow_0074544539_python_python_3.11_type_hinting_union_types.txt |
Q:
Numpy Array Iteration, starting with third value
I need to iterate through an numpy array, but I need to start with the third value.
My exact problem is the following.
I get an array like this:
data([0.0000, 1], [0.0011, 2], [0.0036, 3], ....)
I need to subtract the 0.0011 from 0.0036 and all the following values... | Numpy Array Iteration, starting with third value | I need to iterate through an numpy array, but I need to start with the third value.
My exact problem is the following.
I get an array like this:
data([0.0000, 1], [0.0011, 2], [0.0036, 3], ....)
I need to subtract the 0.0011 from 0.0036 and all the following values, from the first column.
I wanted to do something like... | [
"You could enumerate from index 2 and beyond, something like this:\nfor i, n in enumerate(data):\n if i < 2:\n continue\n data[:, 0] = data[i, 0] - data[i+1, 0]\n\n"
] | [
0
] | [] | [] | [
"iteration",
"loops",
"numpy",
"python"
] | stackoverflow_0074545981_iteration_loops_numpy_python.txt |
Q:
Similarity between each users always 0 while using the KNNBasic of the python Surprise package based on user
The actual situation is that I need to find users with similar interests according to the url favorites of a large number of users. So my data only have "like" without "dislike" and "ignore". And for the nu... | Similarity between each users always 0 while using the KNNBasic of the python Surprise package based on user | The actual situation is that I need to find users with similar interests according to the url favorites of a large number of users. So my data only have "like" without "dislike" and "ignore". And for the number of urls is almost unlimited, it is also impossible to assume that all urls without "like" are "dislike" or "i... | [
"You need to include information about items that users do not like so that you have both 0s and 1s in your dataset. The data should look like this (just screenshotting the top part here):\n\nI got this dataframe with this code:\nusers_and_items = {e[0]:e[1] for e in s_data}\nusers = sorted(list(users_and_items.key... | [
1
] | [] | [] | [
"collaborative_filtering",
"cosine_similarity",
"knn",
"machine_learning",
"python"
] | stackoverflow_0074545697_collaborative_filtering_cosine_similarity_knn_machine_learning_python.txt |
Q:
How to override model field in Django for library model?
I need to override library model field in Django. This model is integrated in that library and used there. The changes I need is to add a unique constraint to one of the model fields. But this is not the abstract model so I can't inherit this model as I unde... | How to override model field in Django for library model? | I need to override library model field in Django. This model is integrated in that library and used there. The changes I need is to add a unique constraint to one of the model fields. But this is not the abstract model so I can't inherit this model as I understand.
The question: is there a way to override usual model f... | [
"Not that I'm aware of. I'd be looking at modifying (forking) the \"library\" model, although there might be issues if it's proprietary 3rd party code for which you do not have source.\nThe usual thing against concrete inheritance is that it causes a new DB table to be created and thereafter, every query involves a... | [
0
] | [] | [] | [
"django",
"inheritance",
"integration",
"overriding",
"python"
] | stackoverflow_0074546024_django_inheritance_integration_overriding_python.txt |
Q:
How to plot a colored gantt chart with plotly keeping the correct bar height
I have the following code to plot a gantt chart in plotly:
import datetime
import pandas
import plotly.express as px
task_list = [{
'Task': 'T-3', 'y': 0, 'Start': datetime.date(2022, 2, 24),
'Finish': datetime.date(2022, 3, 17),... | How to plot a colored gantt chart with plotly keeping the correct bar height | I have the following code to plot a gantt chart in plotly:
import datetime
import pandas
import plotly.express as px
task_list = [{
'Task': 'T-3', 'y': 0, 'Start': datetime.date(2022, 2, 24),
'Finish': datetime.date(2022, 3, 17), 'Status': 'Scheduled'}, {
'Task': 'SNP-350', 'y': 1, 'Start': datetime.date(2... | [
"\nusing color creates a trace for each Status, hence change in heights\nhave put Status into hover_data\nbuilt colormap and then updated trace to use value of Status to lookup color\n\nimport datetime\nimport pandas\nimport plotly.express as px\nimport numpy as np\n\n# fmt: off\ntask_list = [{\n 'Task': 'T-3', ... | [
2,
1
] | [] | [] | [
"gantt_chart",
"plotly",
"python"
] | stackoverflow_0071254131_gantt_chart_plotly_python.txt |
Q:
Python: Why is 0x01 an integer?
The following:
print(type(0x01))
Returns:
<class 'int'>
Whereas, the following:
print(0x01)
Returns
1
Now let's say we have:
x = "0x01"
How do I convert x such that it returns 1 when printed?
Thank you!
A:
You would need to convert using base 16 as suggested by @Joran Beasley... | Python: Why is 0x01 an integer? | The following:
print(type(0x01))
Returns:
<class 'int'>
Whereas, the following:
print(0x01)
Returns
1
Now let's say we have:
x = "0x01"
How do I convert x such that it returns 1 when printed?
Thank you!
| [
"You would need to convert using base 16 as suggested by @Joran Beasley\nx = \"0x01\"\nprint(x)\nx = int(x, 16)\nprint(x)\n\nReturns:\n0x01\n1\n\n",
"Actually 0x01 is an hexadecimal format which is base16 so to convert it to decimal format you need to use int() method as shown below\nx =\"0x01\"\nx = int(x, 16)\n... | [
1,
0
] | [] | [] | [
"integer",
"python",
"windows"
] | stackoverflow_0074524902_integer_python_windows.txt |
Q:
Python List count() using a class and text file
I am a beginner at python and have a question.
I have 2 text files:
The first one contains a schedule for programs:
------------------------------------------------------------------
Channel 1
16.00-17.45 Matinee: The kiss on the cross
17.45-17.50 The stock market to... | Python List count() using a class and text file | I am a beginner at python and have a question.
I have 2 text files:
The first one contains a schedule for programs:
------------------------------------------------------------------
Channel 1
16.00-17.45 Matinee: The kiss on the cross
17.45-17.50 The stock market today
-------------------------------------------------... | [
"You could create a list that accepts that channel number for each time the channel is switched on(the list looks like:[1,2,1,1,4,4....] then use the list.count(the channel num) function to return the number of times for each channel. so you will create a function that returns the value from the list and does other... | [
1
] | [] | [] | [
"class",
"count",
"list",
"python",
"ranking"
] | stackoverflow_0074546163_class_count_list_python_ranking.txt |
Q:
Is there a faster way of reading two files line by line, then adding one line at the end of the other?
so here's my problem:
I have two CSV files with each files having around 500 000 lines.
File 1 looks like this:
ID|NAME|OTHER INFO
353253453|LAURENT|STUFF 1
563636345|MARK|OTHERS
786970908|GEORGES|THINGS
File 2 ... | Is there a faster way of reading two files line by line, then adding one line at the end of the other? | so here's my problem:
I have two CSV files with each files having around 500 000 lines.
File 1 looks like this:
ID|NAME|OTHER INFO
353253453|LAURENT|STUFF 1
563636345|MARK|OTHERS
786970908|GEORGES|THINGS
File 2 looks like this:
LOCATION;ID_PERSON;PHONE
CA;786970908;555555
NY;353253453;555666
So what I have to do is l... | [
"As Alex pointed out in his comment, you can merge both files using pandas.\nimport pandas as pd\n\n# Load files\nfile_1 = pd.read_csv(\"file_1.csv\", index_col=0, delimiter=\"|\")\nfile_2 = pd.read_csv(\"file_2.csv\", index_col=1, delimiter=\";\")\n\n# Rename PERSON_ID as ID\nfile_2.index.name = \"ID\"\n\n# Merge ... | [
0,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074545816_csv_python.txt |
Q:
Run python script when a file has been added to a folder?
I have a folder where files are continuously added, approximately every 3 seconds. I want to create a while loop that keeps running, checking, analysing, moving and deleting files in said folder.
So far my to do list is:
I need to make the while loop that ... | Run python script when a file has been added to a folder? | I have a folder where files are continuously added, approximately every 3 seconds. I want to create a while loop that keeps running, checking, analysing, moving and deleting files in said folder.
So far my to do list is:
I need to make the while loop that keeps checking the folder for new files.
It then has to run an ... | [
"Hope this will resolve your problem\nimport csv\nimport os\nimport shutil\nimport test_folder.test\n\n# Folder where files are added\npath_to_watch = \".\"\n\nbefore = dict([(f, None) for f in os.listdir(path_to_watch)])\nwhile 1:\n after = dict([(f, None) for f in os.listdir(path_to_watch)])\n\n added = [f ... | [
1
] | [] | [] | [
"directory",
"python",
"while_loop",
"windows"
] | stackoverflow_0074544783_directory_python_while_loop_windows.txt |
Q:
Check if a python list contains numeric data
I am checking whether a list in python contains only numeric data. For simple ints and floats I can use the following code:
if all(isinstance(x, (int, float)) for x in lstA):
If there any easy way to check whether another list is embedded in the first list also containi... | Check if a python list contains numeric data | I am checking whether a list in python contains only numeric data. For simple ints and floats I can use the following code:
if all(isinstance(x, (int, float)) for x in lstA):
If there any easy way to check whether another list is embedded in the first list also containing numeric data?
| [
"You can do a recursive check for all lists within the list, like so\ndef is_all_numeric(lst):\n for elem in lst:\n if isinstance(elem, list):\n if not is_all_numeric(elem):\n return False\n elif not isinstance(elem, (int, float)):\n return False\n return Tru... | [
3
] | [
"I don't know if there is another way to do this, but you could just do a for loop for each item, and if any of those items is not a number, just set on bool to false:\nnumbers = [1,2,3,4,5,6,7,8]\n\nallListIsNumber = True\n\nfor i in numbers:\n if i.isnumeric() == False:\n allListIsNumber = False\n\nYou ... | [
-1
] | [
"iteration",
"list",
"python"
] | stackoverflow_0074546288_iteration_list_python.txt |
Q:
Efficiently mask an image with a label mask
I have an image that I read in with tifffile.imread and it is turned into a 3D matrix, with the first dimension representing the Y coordinate, the second the X and the third the channel of the image (these images are not RGB and so there can be an arbitrary number of cha... | Efficiently mask an image with a label mask | I have an image that I read in with tifffile.imread and it is turned into a 3D matrix, with the first dimension representing the Y coordinate, the second the X and the third the channel of the image (these images are not RGB and so there can be an arbitrary number of channels).
Each of these images has a label mask whi... | [
"Your code is slow because you iterate over the whole image for each of the labels. This is an operation of O(n k), for n pixels and k labels. You could instead iterate over the image, and for each pixel examine the label, then update the measurements for that label with the pixel values. This is an operation of O(... | [
1,
0,
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0074341139_image_processing_python.txt |
Q:
How to convert JSON to CSV file from s3 and save it in same s3 bucket using Glue job
Please help me with the coding part
I googled for the code, but it only shows with using lambda handler. My project requires use gluejob.
A:
Here you can find the answer for converting json to csv.
GlueContext glueContext = new ... | How to convert JSON to CSV file from s3 and save it in same s3 bucket using Glue job | Please help me with the coding part
I googled for the code, but it only shows with using lambda handler. My project requires use gluejob.
| [
"Here you can find the answer for converting json to csv.\nGlueContext glueContext = new GlueContext(Spark.getActiveSession())\n\nval jsonDf = glueContext.getSource(\n connectionType = \"s3\",\n connectionOptions = JsonOptions(Map(\"paths\" -> \"s3://:sourcePath/data.json\")),\n format = \"json\",... | [
0
] | [] | [] | [
"amazon_glue",
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"python"
] | stackoverflow_0074546278_amazon_glue_amazon_s3_amazon_web_services_aws_lambda_python.txt |
Q:
Is there a way to run my code for different values of probability?
I am working on a probability question. In my code when I enter the red and blue archers' probability, the code runs fine.
from IPython.core import history
rng = default_rng(42)
def trial(red,blue , red_accurcy = 1, blue_accurcy = 1, history = Fal... | Is there a way to run my code for different values of probability? | I am working on a probability question. In my code when I enter the red and blue archers' probability, the code runs fine.
from IPython.core import history
rng = default_rng(42)
def trial(red,blue , red_accurcy = 1, blue_accurcy = 1, history = False ,debug = False):
if history:
red_history = [red]
... | [
"This answer will work for the above code.\n\nred_accurcy = np.linspace(0,1,10)\nN = 10\nn_max = 100\nn_values = range(2,n_max)\n\nsimulate_results = []\nfor n in n_values:\n results = [trial(90,45,red_accurcy= r ,blue_accurcy= 1) for r in red_accurcy]\n\nCheck if blue wins\nblue_win = [(red,blue,red_accurcy,blu... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074467049_numpy_python.txt |
Q:
Run mod_wsgi with virtualenv or Python with version different that system default
I am trying to make my Flask application work on CentOS server. Basically the issue is that I have Python 2.6 installed in /usr/bin which is system default and Python 3.4 installed in /usr/local/bin. I would like to use Python 3.4 vi... | Run mod_wsgi with virtualenv or Python with version different that system default | I am trying to make my Flask application work on CentOS server. Basically the issue is that I have Python 2.6 installed in /usr/bin which is system default and Python 3.4 installed in /usr/local/bin. I would like to use Python 3.4 virtualenv or at least Python 3.4 interpreter for mod_wsgi to run my application.
I have ... | [
"You have to add the following line in your apache.conf in order to give the right executable and the path to the virtualenv.\nWSGIPythonHome /usr/local/bin\nWSGIPythonPath /home/fenikso/virtualenv/lib/python3.4/site-packages\n\nYou will find all the options of these two command in the mod_wsgi documentation\nBe aw... | [
10,
2,
0,
0
] | [] | [] | [
"apache",
"flask",
"mod_wsgi",
"python"
] | stackoverflow_0027450998_apache_flask_mod_wsgi_python.txt |
Q:
how to get proxy in python on scraping with request?
how to get proxy randomly? and get only one?
I've made the code as below but I don't know how to get the proxy randomly, and I want to get the proxy also based on the page, anyone know how?
import requests
from bs4 import BeautifulSoup
url = 'https://hidemy.nam... | how to get proxy in python on scraping with request? | how to get proxy randomly? and get only one?
I've made the code as below but I don't know how to get the proxy randomly, and I want to get the proxy also based on the page, anyone know how?
import requests
from bs4 import BeautifulSoup
url = 'https://hidemy.name/en/proxy-list/?anon=34#list'
r = requests.get(url,heade... | [
"This link should help you get going. Check out the table section, will be most salient to what you're trying to do.\nhttps://www.pluralsight.com/guides/extracting-data-html-beautifulsoup\nYou need to get further into the soup and put your desired data into some kind of container to then be able to extract an item... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0067802543_beautifulsoup_python_web_scraping.txt |
Q:
Is there a way to map english letter(s) (or graphemes) in word from correspondent phoneme(s) in Python?
e.g. let's assume we have something like:
WOULD | YOU | LIKE | A | CUP | OF | TEA
w ʊ d | j uː | l a ɪ k | ə | k ʌ p | ʊ v | t iː
W UH D | Y UW | L AY K | AH | K AH P | AH V | T IY
And besides th... | Is there a way to map english letter(s) (or graphemes) in word from correspondent phoneme(s) in Python? | e.g. let's assume we have something like:
WOULD | YOU | LIKE | A | CUP | OF | TEA
w ʊ d | j uː | l a ɪ k | ə | k ʌ p | ʊ v | t iː
W UH D | Y UW | L AY K | AH | K AH P | AH V | T IY
And besides that I need to solve P2G problem, I also want to get some mapping of each phoneme and corresponding grapheme (l... | [
"You can use CMU pronouncing dictionary and aspell or enchant spell checker.\nCMU pronouncing dictionary is a list of English words and their pronunciations, where each pronunciation is a list of phonemes.\nThe pronunciation dictionary can be downloaded in text format here:\nhttp://www.speech.cs.cmu.edu/cgi-bin/cmu... | [
0
] | [] | [] | [
"grapheme",
"phoneme",
"python"
] | stackoverflow_0074546260_grapheme_phoneme_python.txt |
Q:
Office365 smtp server does not respond to ehlo() in python
I am trying to use Office365 smtp server for automatically sending out emails. My code works previously with gmail server, but not the Office365 server in Python using smtplib.
My code:
import smtplib
server_365 = smtplib.SMTP('smtp.office365.com', '587'... | Office365 smtp server does not respond to ehlo() in python | I am trying to use Office365 smtp server for automatically sending out emails. My code works previously with gmail server, but not the Office365 server in Python using smtplib.
My code:
import smtplib
server_365 = smtplib.SMTP('smtp.office365.com', '587')
server_365.ehlo()
server_365.starttls()
The response for th... | [
"The smtplib ehlo function automatically adds the senders host name to the EHLO command, but Office365 requires that the domain be all lowercase, so when youe default host name is uppercase it errors.\nYou can fix by explicitly setting sender host name in the ehlo command to anything lowercase.\nimport smtplib\n\ns... | [
0,
0
] | [] | [] | [
"office365",
"python",
"smtp"
] | stackoverflow_0044763856_office365_python_smtp.txt |
Q:
TypeError: Workbook.__init__() got an unexpected keyword argument 'options'
I am getting this error
Traceback (most recent call last): File
"C:\Python310\lib\tkinter_init_.py", line 1921, in call
return self.func(*args) File "C:\Users\achille.gouttard\Documents\synergie\11_16_2021\app.py", line
861, in select... | TypeError: Workbook.__init__() got an unexpected keyword argument 'options' | I am getting this error
Traceback (most recent call last): File
"C:\Python310\lib\tkinter_init_.py", line 1921, in call
return self.func(*args) File "C:\Users\achille.gouttard\Documents\synergie\11_16_2021\app.py", line
861, in selectItem
self.find_match(1) File "C:\Users\achille.gouttard\Documents\synergie\11_1... | [
"It is because engine openpyxl does not support engine kwargs.\nYou need to change the engine parametr (for example 'xlsxwriter' works perfect).\nwith pd.ExcelWriter(name, engine='xlsxwriter', engine_kwargs={'options': {'strings_to_numbers': True}}) as writer:\n stuff()\n\nAlso be note that if you do not have xl... | [
1
] | [] | [] | [
"openpyxl",
"python",
"sysadmin"
] | stackoverflow_0071479516_openpyxl_python_sysadmin.txt |
Q:
Python list comprehension filtering out files in directory
#To pull content from dirNames directory
dirNames = str(glob.glob('.\\Output'+ globalData.__TWO_BACK_SLASH_SEPERATORS__ + globalData.__MANUAL_STRING_OUTPUT__ + globalData.__TWO_BACK_SLASH_SEPERATORS__ +'*'))
print ("Dir Names:: "+dirNames)
#Seperate the c... | Python list comprehension filtering out files in directory | #To pull content from dirNames directory
dirNames = str(glob.glob('.\\Output'+ globalData.__TWO_BACK_SLASH_SEPERATORS__ + globalData.__MANUAL_STRING_OUTPUT__ + globalData.__TWO_BACK_SLASH_SEPERATORS__ +'*'))
print ("Dir Names:: "+dirNames)
#Seperate the contents of dirNames into list dirNames[0], dirNames[1]....etc
di... | [
"Your problem is that you're passing a list of strings to os.path.isdir, which isn't what it expects. Either pass it each directory name individually, or split on the newlines.\ndirNames = [dir for dir in dirNames.split('\\n') if os.path.isdir( dir)]\n\n"
] | [
0
] | [] | [] | [
"automation",
"database",
"directory",
"file",
"python"
] | stackoverflow_0074546238_automation_database_directory_file_python.txt |
Q:
to extract the data in a csv file which is given in the config.json file
i have a config.json file and the data inside the config.json is
""
{
"mortalityfile":"C:/Users/DELL/mortality.csv"
}
and the mortality file is a csv file with some data..i want to extract the csv file data from the cofig.json.The c... | to extract the data in a csv file which is given in the config.json file | i have a config.json file and the data inside the config.json is
""
{
"mortalityfile":"C:/Users/DELL/mortality.csv"
}
and the mortality file is a csv file with some data..i want to extract the csv file data from the cofig.json.The code which i wrote is
js = open('config.json').read()
results = []
for line in ... | [
"I think you are confusing reading your .csv and reading your .json files.\nimport json\n\n# open the json\nconfig_file = open('config.json')\n\n# convert it to a dict\ndata = json.load(config_file)\n\n# open your csv\nwith open(data['mortalityfile'], 'r') as f:\n # do stuff with you csv data\n csv_data = f.r... | [
0
] | [] | [] | [
"config.json",
"csv",
"json",
"python"
] | stackoverflow_0074546380_config.json_csv_json_python.txt |
Q:
Whenever I run '!pip list' or some command inside jupyter notebook it returns '& was unexpected at this time.'
I'm using a conda (miniconda3) env. Inside my conda env I've Jupyter Notebook.
If I run some command from the notebook it returns & was unexpected at this time..
%pip list also shows the same result
Som... | Whenever I run '!pip list' or some command inside jupyter notebook it returns '& was unexpected at this time.' | I'm using a conda (miniconda3) env. Inside my conda env I've Jupyter Notebook.
If I run some command from the notebook it returns & was unexpected at this time..
%pip list also shows the same result
Some Info:
OS: Windows 10;
Python Version: 3.9.15 ( miniconda3 )
I didn't find any good solution.
I'm expecting to ha... | [
"Please see here for detailed anwser:\nWhat is the meaning of exclamation and question marks in Jupyter notebook?\nWhat !pip is doing in your case is:\ncmd> pip\nand pip is not a valid windows cmd command.\nWhat you're looking for might be:\n%pip list\nedit: this is my guess, I don't have a windows computer here to... | [
0
] | [] | [] | [
"conda",
"jupyter_notebook",
"powershell",
"python",
"windows"
] | stackoverflow_0074546483_conda_jupyter_notebook_powershell_python_windows.txt |
Q:
How to consolidate different methods in Python
I have this operation of filling missing values.
mean_impute = df['column'].fillna(value=df['column'].mean())
median_impute = df['column'].fillna(value=df['column'].median())
mode_impute = df['column'].fillna(value=df['column'].mode())
Is there any way on how to repl... | How to consolidate different methods in Python | I have this operation of filling missing values.
mean_impute = df['column'].fillna(value=df['column'].mean())
median_impute = df['column'].fillna(value=df['column'].median())
mode_impute = df['column'].fillna(value=df['column'].mode())
Is there any way on how to replicate this line of code in a much cleaner way, is th... | [
"This might not be best practice (because of eval) but you could avoid to repeat yourself by storing your results in a dictionary:\nimpute = dict()\n\nfor fun in [\"mean\", \"median\", \"mode\"]:\n impute[fun] = eval(f\"df['column'].fillna(value=df['column'].{fun}())\")\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"statistics"
] | stackoverflow_0074543298_dataframe_pandas_python_statistics.txt |
Q:
Subsequent Django Unittests raise "MySQLdb.OperationalError: (2006, '')"
I am unittesting a method creating an HttpReponse and delivering a CSV file.
def _generate_csv(self):
filename = self._get_filename('csv')
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(... | Subsequent Django Unittests raise "MySQLdb.OperationalError: (2006, '')" | I am unittesting a method creating an HttpReponse and delivering a CSV file.
def _generate_csv(self):
filename = self._get_filename('csv')
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; fi... | [
"Ok, found it! Closing the response is killing the database connection (2206 means \"Database gone away\")\nresponse.close()\n\nJust mock the close away in your tests:\n@mock.patch.object(HttpResponse, 'close')\ndef test_generate_csv_case_x(self, *args):\n ...\n\n"
] | [
0
] | [] | [] | [
"django",
"mysql_error_1064",
"python",
"unit_testing"
] | stackoverflow_0074546616_django_mysql_error_1064_python_unit_testing.txt |
Q:
how do i remove characters between 2 different characters inside a string
So i have this inside a text file :
"00:00:25,58 --> 00:00:27,91 (DRAMATIC MUSIC PLAYING)"
I want to remove characters inside and including the braces itself so :
"00:00:25,58 --> 00:00:27,91 "
eng_sub = open(text).read()
eng_sub2 = re.sub(... | how do i remove characters between 2 different characters inside a string | So i have this inside a text file :
"00:00:25,58 --> 00:00:27,91 (DRAMATIC MUSIC PLAYING)"
I want to remove characters inside and including the braces itself so :
"00:00:25,58 --> 00:00:27,91 "
eng_sub = open(text).read()
eng_sub2 = re.sub("\(", "", eng_sub)
new_eng_sub = re.sub("\)", "", eng_sub2)
open(text, "w").wr... | [
"You may try matching on the pattern \\(.*?\\):\neng_sub = open(text).read()\neng_sub2 = re.sub(r'\\(.*?\\)', '', eng_sub)\n\nopen(text, \"w\").write(eng_sub2)\n\n",
"Indeed, you can't use the \"sub\" method which will simply delete the pattern.\nBut what you can do (and which is not too complex) is to use \"find... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0074546461_python_python_3.x_string.txt |
Q:
Generating embedding for long documents using pre-trained word vectors
I have a set of pre-trained word embeddings from the Wikipedia corpus. I also have 300 dimension embeddings of Wikipedia article pages. I am looking to build a similarity engine by running a simple cosine similarity algorithm for any new query ... | Generating embedding for long documents using pre-trained word vectors | I have a set of pre-trained word embeddings from the Wikipedia corpus. I also have 300 dimension embeddings of Wikipedia article pages. I am looking to build a similarity engine by running a simple cosine similarity algorithm for any new query (long documents) against these pre-trained embeddings. To do this, I want to... | [
"You can use doc2vec model for representing documents as a vector. It is a generalizing of the word2vec method.\n"
] | [
0
] | [] | [] | [
"huggingface_transformers",
"nlp",
"python",
"sentence_similarity",
"word_embedding"
] | stackoverflow_0074450390_huggingface_transformers_nlp_python_sentence_similarity_word_embedding.txt |
Q:
cross check if two df have different values and print any if there
i have two df and i wanna check for the id if the value differs in both df if so i need to print those.
example:
df1 = |id |check_column1|
|1|abc|
|1|bcd|
|2|xyz|
|2|mno|
|2|mmm|
df2 =
|id |check_column2|
... | cross check if two df have different values and print any if there | i have two df and i wanna check for the id if the value differs in both df if so i need to print those.
example:
df1 = |id |check_column1|
|1|abc|
|1|bcd|
|2|xyz|
|2|mno|
|2|mmm|
df2 =
|id |check_column2|
|1|bcd|
|1|abc|
|2|xyz|
|2|mno|
|2|kkk|
here t... | [
"Idea is sorting values per id in both columns and join with helper counter by GroupBy.cumcount, then is possible filtering not matched rows:\ndf1 = df1.sort_values(['id','check_column1'])\ndf2 = df2.sort_values(['id','check_column2'])\n \ndf = pd.merge(df1,df2, left_on= ['id',df1.groupby('id').cumcount()], \n ... | [
3,
0,
0
] | [] | [] | [
"dataframe",
"lambda",
"merge",
"pandas",
"python"
] | stackoverflow_0074546214_dataframe_lambda_merge_pandas_python.txt |
Q:
SQLAlchemy select : How to assign a column name to an ORM entity?
Given the SQLAlchemy 1.4 query below, I am selecting an ORM entity, models.Person with two additional calculated columns, prev and next.
@pytest.mark.wip
@pytest.mark.asyncio
async def test_sqlalchemy(people: AsyncSession) -> None:
sessi... | SQLAlchemy select : How to assign a column name to an ORM entity? | Given the SQLAlchemy 1.4 query below, I am selecting an ORM entity, models.Person with two additional calculated columns, prev and next.
@pytest.mark.wip
@pytest.mark.asyncio
async def test_sqlalchemy(people: AsyncSession) -> None:
session = people
query = (
select(
models.Per... | [
"Solved based on information given here. The method was to retrieve each column into a variable, e.g\nperson, navigation = rows[0]\n print(f\"person = {person.surname}\")\n print(f\"next={navigation.next} prev={navigation.prev}\")\n\nFull listing solution\n @pytest.mark.wip\n @pytest.mark.asyncio\n asy... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074546525_python_sqlalchemy.txt |
Q:
Is it possible to check if a phone number is real or not in Python?
I have thousands of random phone numbers and I wanted to check which one of them are real and working right now. is_valid_number and is_possible_number methods in phonenumbers library won't solve my issue.
Is there any way to identify through Pyth... | Is it possible to check if a phone number is real or not in Python? | I have thousands of random phone numbers and I wanted to check which one of them are real and working right now. is_valid_number and is_possible_number methods in phonenumbers library won't solve my issue.
Is there any way to identify through Python? Any way maybe through which we send a ping as an sms to the list of n... | [
"There are a few possible solutions that come to mind:\n\nusing regex and dataset of all the supported countries code, to check but it will not be 100% bulletproof\nlike @DamDam Suggested you can use Twillo Confirm Delivery but it will probably wont work on landlines for example\nfrom a quick internet search I have... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074545014_python_python_3.x.txt |
Q:
How to split the prefix of currency symbol in separate column in Pandas Data Frame
Amount
0 250000
1 ₹40,000,000
2 ₹65,000,000
3 2000000
4 —
... ...
521 225000000
522 —
523 7500
524 ₹35,000,000
525 35000000
526 rows × 1 columns
how can we split the Amount column in separate of Currency Symbol and am... | How to split the prefix of currency symbol in separate column in Pandas Data Frame | Amount
0 250000
1 ₹40,000,000
2 ₹65,000,000
3 2000000
4 —
... ...
521 225000000
522 —
523 7500
524 ₹35,000,000
525 35000000
526 rows × 1 columns
how can we split the Amount column in separate of Currency Symbol and amount in separate column
| [
"You can use str.extract:\ndf[['currency', 'Amount']] = df['Amount'].str.extract(r'(\\D*)(\\d.*)')\n\nOutput:\n Amount currency\n0 250000 \n1 40,000,000 ₹\n2 65,000,000 ₹\n3 2000000 \n4 NaN NaN\n521 225000000 \n522 NaN Na... | [
0
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074546695_data_science_dataframe_pandas_python.txt |
Q:
How can i make selenium to parse every network request?
I am trying to capture all requests with their responses using this code
capabilities = DesiredCapabilities.CHROME
capabilities["goog:loggingPrefs"] = {"performance": "ALL"}
driver.get("<URL>")
def log_filter(log_):
return (
# is an actual resp... | How can i make selenium to parse every network request? | I am trying to capture all requests with their responses using this code
capabilities = DesiredCapabilities.CHROME
capabilities["goog:loggingPrefs"] = {"performance": "ALL"}
driver.get("<URL>")
def log_filter(log_):
return (
# is an actual response
log_["method"] == "Network.responseReceived"
... | [
"You can use the browsermob proxy for this.\nfrom selenium import webdriver\nfrom browsermobproxy import Server\n\nserver = Server(\"/path/to/browsermob-proxy\")\nserver.start()\nproxy = server.create_proxy()\n\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument(\"--proxy-server={0}\".format(pr... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074546174_python_selenium_selenium_webdriver.txt |
Q:
Explaining the memory usage pattern of a multiprocessing pool used for ETL
I am using a multiprocessing.Pool for an ETL processing of several thousands parquet files. Each worker applies a processing function on the parquet and returns the processing result to the main process which aggregates data from all worker... | Explaining the memory usage pattern of a multiprocessing pool used for ETL | I am using a multiprocessing.Pool for an ETL processing of several thousands parquet files. Each worker applies a processing function on the parquet and returns the processing result to the main process which aggregates data from all workers.
The pool is configured with 16 workers and maxtasksperchild=1
I measured the ... | [
"Following @juanpa-arrivillaga comments, I understand the potential caveats of naively using free to track memory usage. To this extent, I switched to using mprof, configured to include memory usage of the child processes, as well as track each one separately:\nmprof run --include-children --multiprocess <cmd>\n\nT... | [
1
] | [] | [] | [
"memory",
"multiprocessing",
"python"
] | stackoverflow_0074543932_memory_multiprocessing_python.txt |
Q:
Fresh install of conda not working due to "KeyError('pkgs_dirs')" and missing DLLs
I installed a fresh new version of Miniconda, but no matter what i try to do (Install new module in Anaconda: Keyerror('pkgs_dirs',), Download error for us package (KeyError: 'pkgs_dirs'), Change conda default pkgs_dirs and envs dir... | Fresh install of conda not working due to "KeyError('pkgs_dirs')" and missing DLLs | I installed a fresh new version of Miniconda, but no matter what i try to do (Install new module in Anaconda: Keyerror('pkgs_dirs',), Download error for us package (KeyError: 'pkgs_dirs'), Change conda default pkgs_dirs and envs dirs) installing packages or reading conda info doesn't seem to work.
An exception is throw... | [
"Maybe it is a bit late but this error on windows should be related to the pywin32 package. A solution is to reinstall this package. You could do this running this command from your base environment:\nconda install -n name-your-environment -c anaconda pywin32\n\n"
] | [
0
] | [] | [] | [
"anaconda",
"conda",
"python"
] | stackoverflow_0073168204_anaconda_conda_python.txt |
Q:
Add rank to dataframe of IDs
I have a dataframe of just IDs e.g.
data=pd.DataFrame({'ID':['D29305C3-6652-E911-B81F-005056962850','570AE90B-CB53-EA11-B836-005056962850','5F21D4D2-E156-EA11-B836-005056962850','73579A31-1252-E911-B81F-005056962850']})
I want to add a row from 1-30 for each ID. I tried making a separ... | Add rank to dataframe of IDs | I have a dataframe of just IDs e.g.
data=pd.DataFrame({'ID':['D29305C3-6652-E911-B81F-005056962850','570AE90B-CB53-EA11-B836-005056962850','5F21D4D2-E156-EA11-B836-005056962850','73579A31-1252-E911-B81F-005056962850']})
I want to add a row from 1-30 for each ID. I tried making a separate list and joining it (range is ... | [
"Let us do cross merge\ndata.merge(pd.Series(range(1, 31), name='rank'), how='cross')\n\n\n ID rank\n0 D29305C3-6652-E911-B81F-005056962850 1\n1 D29305C3-6652-E911-B81F-005056962850 2\n2 D29305C3-6652-E911-B81F-005056962850 3\n3 D29305C3-6652-E911-B81F-... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074546708_dataframe_pandas_python.txt |
Q:
weights & biases : ERROR Failed to sample metric: Not Supported
I am training a yolox model and using wandb (weight & biases library) to follow training evolution. My problem is that when I am loading wandb library (version 0.13.5) I get an error message, which is:
wandb: ERROR Failed to sample metric: Not Support... | weights & biases : ERROR Failed to sample metric: Not Supported | I am training a yolox model and using wandb (weight & biases library) to follow training evolution. My problem is that when I am loading wandb library (version 0.13.5) I get an error message, which is:
wandb: ERROR Failed to sample metric: Not Supported
The surprising thing is that when I run the exact same code on goo... | [
"Engineer from W&B here! Would it be possible if you could share the console log so that we can find the line where the error originates.\n"
] | [
1
] | [] | [] | [
"python",
"tensorboard",
"wandb",
"yolo"
] | stackoverflow_0074520555_python_tensorboard_wandb_yolo.txt |
Q:
Select the features with positive contribution to each class using SHAP values
I am trying to get the features which are important for a class and have a positive contribution (having red points on the positive side of the SHAP plot).
I can get the shap_values and plot the shap summary for each class (e.g. class 2... | Select the features with positive contribution to each class using SHAP values | I am trying to get the features which are important for a class and have a positive contribution (having red points on the positive side of the SHAP plot).
I can get the shap_values and plot the shap summary for each class (e.g. class 2 here) using the following code:
import shap
explainer = shap.TreeExplainer(clf)
s... | [
"You can do the following steps - where basically we are trying to get only the values that effect the classification positively (shap_values>0) when shap_values<0 it means don't classify\nLater you take mean and sort the results.\nIf you prefers the global values then use .abs() instead of [shap_df>0]\nand for the... | [
0
] | [] | [] | [
"classification",
"feature_engineering",
"python",
"shap"
] | stackoverflow_0072661604_classification_feature_engineering_python_shap.txt |
Q:
Python RegEx , how to find words that start with uppercase followed by lower case?
I have the following string
Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01
I'm applying findall as a way to split my string when I apply findall it split I & P how can I change expression to get this output
['Date: 20/8/202... | Python RegEx , how to find words that start with uppercase followed by lower case? | I have the following string
Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01
I'm applying findall as a way to split my string when I apply findall it split I & P how can I change expression to get this output
['Date: 20/8/2020 ', 'Duration: 0.33 ', 'IP: 110.1.x.x ', 'Server:01']
text = "Date: 20/8/2020 Duratio... | [
"Look for any string that begins with either two uppercase letters, or an uppercase followed by a lowercase, and then match until you find either the same pattern or end of line.\n>>> re.findall(r'([A-Z][a-zA-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text)\n['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\... | [
2,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074543261_python_regex.txt |
Q:
What Happens when Combining the 'in' Operator with the 'for in' Operator in Python?
When looking for a secure random password generator in Python I came across this script:
# necessary imports
import secrets
import string
# define the alphabet
letters = string.ascii_letters
digits = string.digits
special_chars = ... | What Happens when Combining the 'in' Operator with the 'for in' Operator in Python? | When looking for a secure random password generator in Python I came across this script:
# necessary imports
import secrets
import string
# define the alphabet
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
alphabet = letters + digits + special_chars
# fix password length
pw... | [
"This is known as a list comprehension.\nA very simple example of this is:\n[i for i in range(5)] => [0, 1, 2, 3, 4]\n\nNow, breaking down your example.\nThe second half of the list comprehension for char in pwd is looping through every character in the password.\nNow the first part char in special_chars is giving ... | [
0,
0
] | [] | [] | [
"for_loop",
"in_operator",
"python"
] | stackoverflow_0074546455_for_loop_in_operator_python.txt |
Q:
How do i add numbers to variables?
So, i have been trying to build a python number guessing game. I am new, and i can't figure out how i add +1 to my chance variable. I have tried +=1 like here but it always shows 1 as the output no matter what. And i know that there is a lot of things wrong with this code but, ke... | How do i add numbers to variables? | So, i have been trying to build a python number guessing game. I am new, and i can't figure out how i add +1 to my chance variable. I have tried +=1 like here but it always shows 1 as the output no matter what. And i know that there is a lot of things wrong with this code but, keep in mind that i am new to coding.
impo... | [
"You have to pass the variable chance to the function when you call it. You can then increment chance directly when you recursively call upon the function:\nimport random\n\nnumbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\nuser = None\nhidden = random.choice(numbers)\n\nprint(\"Welcome to volty's's number guessing game!\")... | [
1,
0,
0,
-1
] | [] | [] | [
"android",
"python",
"python_3.x"
] | stackoverflow_0074546696_android_python_python_3.x.txt |
Q:
Hi, while I was trying to run this code this mensage came up ModuleNotFoundError: No module named 'spacy.lemmatizer'
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, ... | Hi, while I was trying to run this code this mensage came up ModuleNotFoundError: No module named 'spacy.lemmatizer' | import spacy
nlp = spacy.load('en_core_web_sm')
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
lemmattizer('chunkles', 'NOUN')
Can anyone help me? I'm using Version 3 of python
| [
"The official document shows that after spacy 3.0, the lemmatizer has become a standalone pipeline component. Therefore, you should install the spacy whose version is smaller than 3.0. The link is as follow: https://spacy.io/api/lemmatizer\n",
"try:\ndoc = nlp('chuckles')\ndoc[0].lemma_\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0070021042_python.txt |
Q:
How to modify this multiple argument method to kwargs only?
class SalesforceConnectionLiaison:
def __init__(self, *, organisation_id, mongo_client):
self.organisation_id = organisation_id
self.mongo_client = mongo_client
self.salesforce_manager = SalesforceConnectionManager(
... | How to modify this multiple argument method to kwargs only? |
class SalesforceConnectionLiaison:
def __init__(self, *, organisation_id, mongo_client):
self.organisation_id = organisation_id
self.mongo_client = mongo_client
self.salesforce_manager = SalesforceConnectionManager(
organisation_id=organisation_id, mongo_client=mongo_cli... | [
"Assuming that your question is about connection_enable().\nJust use **kwargs that allows to receive your args as a dictionary.\nThen inside the function if you want to use variables, you can use get().\nThe advantage of get() is that it returns None if the key is not present (this arg hasn't been provided as an ar... | [
0
] | [] | [] | [
"arguments",
"keyword_argument",
"methods",
"parameters",
"python"
] | stackoverflow_0074546713_arguments_keyword_argument_methods_parameters_python.txt |
Q:
Opencv save last N seconds of a camera stream
Is there a way to save last N seconds of a video stream to a file with openCV? E.g. The camera recording starts at 0s and ends at 20s leading to a recorded file which contains the video from 10s -> 20s.
One way I can think of is to save last N seconds in a memory buffe... | Opencv save last N seconds of a camera stream | Is there a way to save last N seconds of a video stream to a file with openCV? E.g. The camera recording starts at 0s and ends at 20s leading to a recorded file which contains the video from 10s -> 20s.
One way I can think of is to save last N seconds in a memory buffer and write them to file once the process finishes,... | [
"The best solution is to use a fifo buffer for the last 10 seconds or stream and past it into a file when the process stop (as you've explained).\nwhy would it imply a latency though ? just need to use 2 buffer.\na short buffer for display and long fifo buffer for recording last 10 sec\n",
"Common \"dashcam\"/CCT... | [
0,
0
] | [] | [] | [
"opencv",
"python",
"video",
"video_encoding"
] | stackoverflow_0074545126_opencv_python_video_video_encoding.txt |
Q:
For a large array (16,000+ rows): How to find index value of a 2D array that satisfies a certain condition, as quickly as possible?
I have a dataset having x coordinates, y coordinates, and a function value. I have a function that checks for input coordinates, and does something whether or not the value is found. ... | For a large array (16,000+ rows): How to find index value of a 2D array that satisfies a certain condition, as quickly as possible? | I have a dataset having x coordinates, y coordinates, and a function value. I have a function that checks for input coordinates, and does something whether or not the value is found. But for the large sized numpy array,it takes too long, a second to check through two such arrays (x and y).
The reason it is a 'long time... | [
"If one of your performance problems is reading the file countless time, like that :\nread_excel_count = 0\ndef pd_read_excel(filename): # fake for demo\n global read_excel_count\n read_excel_count += 1\n print(f\"call pd_read_excel, {filename=!r}, {read_excel_count=}\")\n\n\ndef assign_to_new_grid(p):\n ... | [
0
] | [] | [] | [
"arrays",
"large_files",
"python"
] | stackoverflow_0074537402_arrays_large_files_python.txt |
Q:
Add Array to pandas column
I need to iterate over a dataframe. In each iteration row.Text is converted into a vector-representation and stored as a numpy.ndarray (newData). Now i want to add a column (Vektoren) to the original dataframe and apply to each row the newData array
for idx,row in data.iterrows():
... | Add Array to pandas column | I need to iterate over a dataframe. In each iteration row.Text is converted into a vector-representation and stored as a numpy.ndarray (newData). Now i want to add a column (Vektoren) to the original dataframe and apply to each row the newData array
for idx,row in data.iterrows():
doc = nlp(row.Text)
... | [
"Make your solution concise with map\ndata['Vektoren'] = data['Text'].map(lambda s: nlp(s).vector)\n\n"
] | [
1
] | [] | [] | [
"iteration",
"pandas",
"python"
] | stackoverflow_0074546445_iteration_pandas_python.txt |
Q:
image is too big for OpenCV imshow window, how do I make it smaller?
I'm comparing two images - a complete image & a small part of the same image. If a match is found, then a rectangular box is drawn around that part of the image which contains the smaller image.
To implement this, I have used the matchTemplate me... | image is too big for OpenCV imshow window, how do I make it smaller? | I'm comparing two images - a complete image & a small part of the same image. If a match is found, then a rectangular box is drawn around that part of the image which contains the smaller image.
To implement this, I have used the matchTemplate method.
The code works as expected, but if the original image's dimensions a... | [
"Before imshow, call namedWindow() with the WINDOW_NORMAL flag. That makes it resizable and scales the image to the size of the window.\ncv.namedWindow(\"img\", cv.WINDOW_NORMAL)\n# then imshow()...\n\n"
] | [
1
] | [] | [] | [
"opencv",
"python",
"user_interface"
] | stackoverflow_0074546171_opencv_python_user_interface.txt |
Q:
How can I handle 400 bad request error using DRF in Django
I am trying to perform a POST request using DRF in Django, the program is raising a 400 error (this is the error, Bad Request: /api/menu_items/, the frontend is raising the following error (This field is required) the problem is I cannot see the exact fi... | How can I handle 400 bad request error using DRF in Django | I am trying to perform a POST request using DRF in Django, the program is raising a 400 error (this is the error, Bad Request: /api/menu_items/, the frontend is raising the following error (This field is required) the problem is I cannot see the exact field that is missing. How can I locate the missing field? The err... | [
"I got solved the error, I wasn't passing the right values is the useState() function.\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"generics",
"python",
"rest"
] | stackoverflow_0074546188_django_django_rest_framework_generics_python_rest.txt |
Q:
merging dataframes by country and year while the countries are not named the same (for example US,United states )
Hello I am trying to drop rows that have in a specific column string that is not a year.
For example I have the in last rows year formats that have decimal points or '-'.
I have tried to convert the y... | merging dataframes by country and year while the countries are not named the same (for example US,United states ) | Hello I am trying to drop rows that have in a specific column string that is not a year.
For example I have the in last rows year formats that have decimal points or '-'.
I have tried to convert the year column into a string and then drop them using the code below but it only removes the row with 2011-21, the ones wit... | [
"You can filter all rows where level_1 contains non digit characters:\ndf[~df.level_1.str.contains('\\D')]\n\n",
"you can use regex:\ndf['level_1']=df['level_1'].astype(str)\ndf = df[df['level_1'].str.contains('\\d\\d\\d\\d-\\d\\d',regex=True)]\n\n"
] | [
1,
0
] | [] | [] | [
"data_science",
"dataframe",
"fuzzy_logic",
"pandas",
"python"
] | stackoverflow_0074545960_data_science_dataframe_fuzzy_logic_pandas_python.txt |
Q:
Why do I not get the expected result when concatenating a square wave and f(x)=x^2?
When I plot each t and f variable individually, I get the 4 parts of the signal I am looking for, but when I concatenate them it is not resulting in the signal I am expecting.
Here is the wave I am trying to replicate:
Here is the... | Why do I not get the expected result when concatenating a square wave and f(x)=x^2? | When I plot each t and f variable individually, I get the 4 parts of the signal I am looking for, but when I concatenate them it is not resulting in the signal I am expecting.
Here is the wave I am trying to replicate:
Here is the current output I am getting:
Here is the code:
T = 0.5
dutycycle = 0.5
samples = 10000
... | [
"The order of points in plt.plot matters in a line-plot. You put the time-intervals not in ascending order. In your example, you need to change the lines:\nt = np.concatenate((t2, t3, t4, t5))\nf = np.concatenate((f2, f3, f4, f5))\n\nto\nt = np.concatenate((t4, t2, t5, t3))\nf = np.concatenate((f4, f2, f5, f3))\n\n... | [
0
] | [] | [] | [
"concatenation",
"numpy",
"python"
] | stackoverflow_0074540078_concatenation_numpy_python.txt |
Q:
drop_duplicates not working in pandas?
The purpose of my code is to import 2 Excel files, compare them, and print out the differences to a new Excel file.
However, after concatenating all the data, and using the drop_duplicates function, the code is accepted by the console. But, when printed to the new excel file,... | drop_duplicates not working in pandas? | The purpose of my code is to import 2 Excel files, compare them, and print out the differences to a new Excel file.
However, after concatenating all the data, and using the drop_duplicates function, the code is accepted by the console. But, when printed to the new excel file, duplicates still remain within the day.
Am ... | [
"You've got inplace=False so you're not modifying df. You want either\n df.drop_duplicates(subset=None, keep=\"first\", inplace=True)\n\nor\n df = df.drop_duplicates(subset=None, keep=\"first\", inplace=False)\n\n",
"I have just had this issue, and this was not the solution. \nIt may be in the docs - I admittedly... | [
28,
12,
10,
8,
4,
0,
0
] | [] | [] | [
"duplicates",
"excel",
"pandas",
"python"
] | stackoverflow_0046489695_duplicates_excel_pandas_python.txt |
Q:
Pandas Dataframe - Droping Certain Hours of the Day from 20 Years of Historical Data
I have stock market data for a single security going back 20 years. The data is currently in an Pandas DataFrame, in the following format:
The problem is, I do not want any "after hours" trading data in my DataFrame. The market i... | Pandas Dataframe - Droping Certain Hours of the Day from 20 Years of Historical Data | I have stock market data for a single security going back 20 years. The data is currently in an Pandas DataFrame, in the following format:
The problem is, I do not want any "after hours" trading data in my DataFrame. The market in question is open from 9:30AM to 4PM (09:30 to 16:00 on each trading day). I would like t... | [
"Problem here is how you are importing data. There is no indicator whether 04:00 is am or pm? but based on your comments we need to assume it is PM. However input is showing it as AM.\nTo solve this we need to include two conditions with OR clause. \n\n9:30-11:59\n0:00-4:00\n\nInput:\ndf = pd.DataFrame({'date': {... | [
9,
5,
1,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0060895196_dataframe_numpy_pandas_python.txt |
Q:
pyinstaller Unable to access file
I wrote a simple code in python/pygame, and the game was running fine in both sublime text and cmd, but when I tried to make it a exe file pyinstaller --onefile version2.py, I got an error and I don't know what is the problem ?
A:
Well bro, I don't know if I will be helpfull to ... | pyinstaller Unable to access file | I wrote a simple code in python/pygame, and the game was running fine in both sublime text and cmd, but when I tried to make it a exe file pyinstaller --onefile version2.py, I got an error and I don't know what is the problem ?
| [
"Well bro, I don't know if I will be helpfull to you know after 6 days, I am having 2 solutions for you which worked for me today.\n\nDisable Antivirus OR put that folder in which you are building app.exe to Exception, like I have done below [Mandatory Process].\n\n\n\nDont' run pyinstaller command from the directo... | [
1
] | [
"Try to disable the anti-virus, that worked for me\n"
] | [
-1
] | [
"pygame",
"pyinstaller",
"python"
] | stackoverflow_0069989638_pygame_pyinstaller_python.txt |
Q:
list out of range when using embeddings
I have the following list:
list1=[['brute-force',
'password-guessing',
'password-guessing',
'default-credentials',
'shell'],
['malware',
'ddos',
'phishing',
'spam',
'botnet',
'cryptojacking',
'xss',
'sqli',
'vulnerability'],
['sensitive-information'... | list out of range when using embeddings | I have the following list:
list1=[['brute-force',
'password-guessing',
'password-guessing',
'default-credentials',
'shell'],
['malware',
'ddos',
'phishing',
'spam',
'botnet',
'cryptojacking',
'xss',
'sqli',
'vulnerability'],
['sensitive-information']]
I am trying the example from here enter l... | [
"You need to flatten your input nested list first.\nfrom nltk import flatten\nflattened_list1 = flatten(list1)\nembeddings1 = sbert_model.encode(flattened_list1, convert_to_tensor=True)\n\n"
] | [
0
] | [] | [] | [
"list",
"nlp",
"python",
"python_3.x",
"word_embedding"
] | stackoverflow_0073681331_list_nlp_python_python_3.x_word_embedding.txt |
Q:
Implode rows and create new col
How could I create a unique detail colum, which is conditoinal on fruit being followed by fruit -2 in the type column. detail1 or detail2 could be NaN
df type detail1 detail2 name
0 fruit apple
1 fruit -2 best best a... | Implode rows and create new col | How could I create a unique detail colum, which is conditoinal on fruit being followed by fruit -2 in the type column. detail1 or detail2 could be NaN
df type detail1 detail2 name
0 fruit apple
1 fruit -2 best best apple
2 yellow yellowis... | [
"The exact logic is not fully clear, but you should use a custom function for groupby.apply:\ndef process(df):\n m1 = df['type'].shift().eq('fruit')\n m2 = df['type'].ne('fruit -2')\n m3 = df['type'].isnull()\n \n prefix = next(iter(df.loc[m1&m2, 'type']), '')\n if prefix:\n prefix += ': '\... | [
0
] | [] | [] | [
"pandas",
"python",
"shift"
] | stackoverflow_0074546777_pandas_python_shift.txt |
Q:
How to convert PNG to JPG in Python?
I'm trying to compare two images, one a .png and the other a .jpg. So I need to convert the .png file to a .jpg to get closer values for SSIM. Below is the code that I've tried, but I'm getting this error:
AttributeError: 'tuple' object has no attribute 'dtype'
image2 = imrea... | How to convert PNG to JPG in Python? | I'm trying to compare two images, one a .png and the other a .jpg. So I need to convert the .png file to a .jpg to get closer values for SSIM. Below is the code that I've tried, but I'm getting this error:
AttributeError: 'tuple' object has no attribute 'dtype'
image2 = imread(thisPath + caption)
image2 = io.imsave("... | [
"Before demonstrating how to convert an image from .png to .jpg format, I want to point out that you should be consistent on the library that you use. Currently, you're mixing scikit-image with opencv. It's best to choose one library and stick with it instead of reading in an image with scikit and then converting t... | [
17,
3,
1,
0
] | [] | [] | [
"image",
"image_processing",
"opencv",
"python",
"scikit_image"
] | stackoverflow_0060048149_image_image_processing_opencv_python_scikit_image.txt |
Q:
Pyrogram forward + edit message
How can I make it so that the text can be changed in the forwarded message in PYROGRAM?
@app.on_message(filters.chat(publics))
def new_channel_post(client, message):
message.forward(private_public)
A message is sent to a private public and I haven't figured out how to change it... | Pyrogram forward + edit message | How can I make it so that the text can be changed in the forwarded message in PYROGRAM?
@app.on_message(filters.chat(publics))
def new_channel_post(client, message):
message.forward(private_public)
A message is sent to a private public and I haven't figured out how to change it.
@app.on_message(filters.chat(public... | [
"Forwarded messages cannot be edited. Neither by the original author, nor by the user forwarding. If you need, you can copy a message (app.copy_message()), in which case the forwarded message will look as though you sent the message yourself and will not link back the the original user/channel.\nAn example flow cou... | [
0
] | [] | [] | [
"pyrogram",
"python",
"telegram"
] | stackoverflow_0074546893_pyrogram_python_telegram.txt |
Q:
How to use python dataframe styling in streamlit
I have styled my dataframe using the below code:
th_props = [
('font-size', '14px'),
('text-align', 'center'),
('font-weight', 'bold'),
('color', '#6d6d6d'),
('background-color', '#f7ffff')
]
td_props = [
('font-si... | How to use python dataframe styling in streamlit | I have styled my dataframe using the below code:
th_props = [
('font-size', '14px'),
('text-align', 'center'),
('font-weight', 'bold'),
('color', '#6d6d6d'),
('background-color', '#f7ffff')
]
td_props = [
('font-size', '12px')
]
st... | [
"You should use st.table instead of st.dataframe. Here is some reproducible code:\n# import packages\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\n\n# Example dataframe\noutputdframe = pd.DataFrame(np.array([[\"CS\", \"University\", \"KR\", 7032], [\"IE\", \"Bangalore\", \"Bengaluru\", 7861], [\... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"python",
"streamlit",
"styling"
] | stackoverflow_0068379442_dataframe_python_streamlit_styling.txt |
Q:
Selenium: element is not attached to the page document restaurant get free food script
Trying to make a free food finder but get unknown error
I'm trying to make this code to get every free product in this food delivery restaurant
I expect it to iterate through this 'hbaEIe.sc-5674cfe4-2' elements, that look like ... | Selenium: element is not attached to the page document restaurant get free food script | Trying to make a free food finder but get unknown error
I'm trying to make this code to get every free product in this food delivery restaurant
I expect it to iterate through this 'hbaEIe.sc-5674cfe4-2' elements, that look like this:
Restaurant div
url = 'https://www.rappi.com.ar/restaurantes'
for restaurant in all_re... | [
"This happens when the page is refreshed but you keep the old reference in your varibale. Try rediscovering element in the dom after refresh.\n",
"I suspect that your attempt to open the individual restaurant link in a new tab is not successful. As a result you are no longer on the main page when iterating to th... | [
0,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074546372_python_selenium.txt |
Q:
How to make the Open3D read the pandas DataFrame and generate points clouds in Python
I extracted certain data from the original CSV file (which contains the XYZ coordinates) by using the following code
.
data=pd.read_csv("./assets/landmarks_frame0.csv",header=None,usecols=range(1,4))
print(data)
The printing out... | How to make the Open3D read the pandas DataFrame and generate points clouds in Python | I extracted certain data from the original CSV file (which contains the XYZ coordinates) by using the following code
.
data=pd.read_csv("./assets/landmarks_frame0.csv",header=None,usecols=range(1,4))
print(data)
The printing output looks fine as below. Recall that the first (started with 0.524606), second and third co... | [
"Open3D supports NumPy arrays. So, firstly you have to convert your dataframe with XYZ coordinates to a NumPy array. This will allow you to convert the NumPy array to the Open3D point cloud. You can check the documentation (here) of Open3D for further details.\nThe important lines (of documentation) for the conve... | [
0
] | [] | [] | [
"open3d",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0073464667_open3d_pandas_python_python_3.x.txt |
Q:
Python if statement executes but condition false
As the subject says, I have some live trading code, in Python. I had been using it successfully for well over a week before my issue began. Suddenly, yesterday morning, when my code began running, it would open trades and close them almost as soon as they had been o... | Python if statement executes but condition false | As the subject says, I have some live trading code, in Python. I had been using it successfully for well over a week before my issue began. Suddenly, yesterday morning, when my code began running, it would open trades and close them almost as soon as they had been opened [as opposed to waiting until a certain amount of... | [
"I managed to solve the issue quite some time ago, but I seem to have neglected to post and update. Oh well, better late than never.\nThe issue was remedied simply by replacing the if statement with the one below:\ndatetime.datetime.utcnow() >= (openTime + datetime.timedelta(seconds= ExitThreshold))\n\nThe two stat... | [
1
] | [] | [] | [
"if_statement",
"oanda",
"python",
"spyder"
] | stackoverflow_0067586652_if_statement_oanda_python_spyder.txt |
Q:
How to lookup a specific value in a range of one DataFrame an put in in another
df1:
**Tarif von bis GK**
FedEx 0.0 1.0 G001
FedEx 1.0 2.0 G002
...
DHL. 0.0 0.5 G001
DHL. 0.5 1.0 G002
...
DPD 0.0 5.0 G001
DPD 5.0 10.0 G002
df2:
**Tarif Weight GK**
FedEx ... | How to lookup a specific value in a range of one DataFrame an put in in another | df1:
**Tarif von bis GK**
FedEx 0.0 1.0 G001
FedEx 1.0 2.0 G002
...
DHL. 0.0 0.5 G001
DHL. 0.5 1.0 G002
...
DPD 0.0 5.0 G001
DPD 5.0 10.0 G002
df2:
**Tarif Weight GK**
FedEx 0.6
DHL 0.6
FedEx 0.5
DPD 7.5
My attempt:
for i in range(len(df2)... | [
"Another possible solution, which is based on the following ideas:\n\nMerge the two dataframes as usual with pandas.DataFrame.merge.\n\nFilter out the cases that do not satisfy the conditions.\n\n\nout = df2.iloc[:,:2].merge(df1, on='Tarif')\nout = out.loc[out['von'].lt(out['Weight']) & out['bis'].ge(out['Weight'])... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074546896_pandas_python.txt |
Q:
A little game using Matrix, code doesn't work
We have a n to n matrix (made of nested lists) whose elements are either "+" or "-". What I need to do is to write something that changes "+" to "-" or "-" to "+" with a X-shaped pattern (i.e itself and diagonal upperleft, upperright, lowerleft, lowerright, example bel... | A little game using Matrix, code doesn't work | We have a n to n matrix (made of nested lists) whose elements are either "+" or "-". What I need to do is to write something that changes "+" to "-" or "-" to "+" with a X-shaped pattern (i.e itself and diagonal upperleft, upperright, lowerleft, lowerright, example below).
So for example if user input of coordinates (i... | [
"Your all-enveloping try/catch is the issue. Never do that if you don't know what exactly you are catching.\nIn this case, your code proceeds in the order:\n\ncenter\ntop left\ntop right\nbottom left\nbottom right\n\nBut the top left corner is out of bounds, so it throws an IndexError and exits. It will only have p... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074546839_python_python_3.x.txt |
Q:
Change dictionary values with for-loop
I have a dictionary that I want to modify. Not the strings, but only the numbers. The function below should convert all the numbers in the dictionary to two decimal floats:
def roundup(resultdict):
print("resultdict is: " +str(resultdict))
for item in resultdict.items... | Change dictionary values with for-loop | I have a dictionary that I want to modify. Not the strings, but only the numbers. The function below should convert all the numbers in the dictionary to two decimal floats:
def roundup(resultdict):
print("resultdict is: " +str(resultdict))
for item in resultdict.items():
print("item is: " + str(item))
... | [
"Thanks for your suggestions. The solution was to iterate over key, value pairs and modify the dictionary key with a value, not the iterator. The rounding is now fixed as well.\ndef roundup(resultdict):\n print(\"resultdict is: \" +str(resultdict))\n for key, value in resultdict.items():\n print(\"item... | [
0
] | [] | [] | [
"dictionary",
"for_loop",
"python"
] | stackoverflow_0074539045_dictionary_for_loop_python.txt |
Q:
Cannot assign a value to a string in a loop
import re
import os
path ="/data/notebook_files/"
Filelist = []
txt = ''
for home, dirs, files in os.walk(path):
for filename in files:
Filelist.append(os.path.join(home, filename))
for file in Filelist:
with open(file,"r+",encoding='utf-8',errors... | Cannot assign a value to a string in a loop | import re
import os
path ="/data/notebook_files/"
Filelist = []
txt = ''
for home, dirs, files in os.walk(path):
for filename in files:
Filelist.append(os.path.join(home, filename))
for file in Filelist:
with open(file,"r+",encoding='utf-8',errors='ignore') as f:
print (file)
for... | [
"import re\nimport os\nimport codecs\npath =\"/data/notebook_files/bible\"\nFilelist = []\nfor home, dirs, files in os.walk(path):\n for filename in files:\n if str(filename)[len(str(filename))-3:] != '.py':\n Filelist.append(os.path.join(home, filename))\nfor file in Filelist:\n ... | [
0
] | [] | [] | [
"for_loop",
"python",
"string"
] | stackoverflow_0074538487_for_loop_python_string.txt |
Q:
pipenv requires python 3.7 but installed version is 3.8 and won't install
I know a little of Python and more than a year ago I wrote a small script, using pipenv to manage the dependencies.
The old platform was Windows 7, the current platform is Windows 10.
At that time I probably had Python 3.7 installed, now I h... | pipenv requires python 3.7 but installed version is 3.8 and won't install | I know a little of Python and more than a year ago I wrote a small script, using pipenv to manage the dependencies.
The old platform was Windows 7, the current platform is Windows 10.
At that time I probably had Python 3.7 installed, now I have 3.8.3 but running:
pipenv install
Complained that:
Warning: Python 3.7 was... | [
"[requires]\npython_version = \"3.7\"\n\nand the error:\nWarning: Python 3.7 was not found on your system…\nSort of hints that pipenv is installed but when it reads your config file, it sees that it should create environment with python 3.7, So, logically, you should install 3.7 or update the pipfile to use the pyt... | [
12,
9,
8,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"pipenv",
"python",
"python_3.x"
] | stackoverflow_0063247803_pipenv_python_python_3.x.txt |
Q:
How to plot multiple lines from a loop on one 3d plot in Python?
Basically, I am looping generation of rays in Python and I'm trying to plot them all on the same graph. They should all be on a circle of radius 0.1. Each ray should be at a position on the circle that is varied by the arg which is in this case the t... | How to plot multiple lines from a loop on one 3d plot in Python? | Basically, I am looping generation of rays in Python and I'm trying to plot them all on the same graph. They should all be on a circle of radius 0.1. Each ray should be at a position on the circle that is varied by the arg which is in this case the theta. Also, just to mention (although I don't think it's that relevant... | [
"Expanding on the comment by Mercury, the figure and also axes object must be created outside the loop.\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nr = 0.1\narg = 0\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\nfor i in range(0,24):\n arg += np.pi/12 * i\n v1 = r*np.sin(arg)\n v2 = r*n... | [
0
] | [] | [] | [
"3d",
"matplotlib",
"python",
"raytracing"
] | stackoverflow_0074539989_3d_matplotlib_python_raytracing.txt |
Q:
How to get html form, process it with py script and display it on screen?
I have a question about how html+py script works.
....
I get 3 values of trapezoidal data from html: height, length of side 1 and length of side 2, then press submit.
and send the value that the user has entered let's calculate with py scr... | How to get html form, process it with py script and display it on screen? | I have a question about how html+py script works.
....
I get 3 values of trapezoidal data from html: height, length of side 1 and length of side 2, then press submit.
and send the value that the user has entered let's calculate with py script
Then show the secret result on the screen.
But the results showed that Ther... | [
"You set all your variables to 0.0 before checking their values, which means your condition (if w1 > 0 and w2 > 0 and h > 0) will always evaluate to False, thus never printing anything in your output element.\nRemove the following lines and your script will work:\nw1 = 0.0\nw2 = 0.0\nh = 0.0\n\nAlso if you meant to... | [
1
] | [] | [] | [
"html",
"python",
"python_3.x",
"typescript"
] | stackoverflow_0074543367_html_python_python_3.x_typescript.txt |
Q:
Way to use twiiter hashtags in python sentiment analysis?
Is there any way to extract twitter hashtags in this code instead of tweets from a single user. I am working on sentiment analysis in python/
# Extract 100 tweets from the twitter user
posts = api.user_timeline(screen_name="OlectraEbus", count = 100, lang =... | Way to use twiiter hashtags in python sentiment analysis? | Is there any way to extract twitter hashtags in this code instead of tweets from a single user. I am working on sentiment analysis in python/
# Extract 100 tweets from the twitter user
posts = api.user_timeline(screen_name="OlectraEbus", count = 100, lang ="en", tweet_mode="extended")
# Print the last 5 tweets
print(... | [
"I recommend two link to read :\n\nLink 1\n\nLink 2\n\n\n",
"What worked for my team was making a data frame. Each row represents a tweet and the columns include mentions, hashtags, time, date, etc. Since one of the columns is the \"hashtag\" column, containing the hashtags of each tweet, you can easily select tw... | [
0,
0
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0066254893_python_twitter.txt |
Q:
error OSError: [Errno 30] Read-only file system: '/ '
I was trying to install new packages in an application with pip, but I got this error
from pip._internal import main as pipmain
pipmain(['install','mechanize','-t .'])
A:
If you want to add packages to your app, don't run pip at runtime, use Chaquopy's built... | error OSError: [Errno 30] Read-only file system: '/ ' | I was trying to install new packages in an application with pip, but I got this error
from pip._internal import main as pipmain
pipmain(['install','mechanize','-t .'])
| [
"If you want to add packages to your app, don't run pip at runtime, use Chaquopy's built-in pip support as documented here.\n"
] | [
0
] | [] | [] | [
"chaquopy",
"pip",
"python"
] | stackoverflow_0074534787_chaquopy_pip_python.txt |
Q:
How to use variables inside query in Pandas?
I have problem quering the data frame in panda when I use variable instead of value.
df2 = pd.read_csv('my.csv')
query=df2.query('cc_vehicle_line==7')
works fine but
df2 = pd.read_csv('my.csv')
query=df2.query('cc_vehicle_line==variable_name')
It throws the message th... | How to use variables inside query in Pandas? | I have problem quering the data frame in panda when I use variable instead of value.
df2 = pd.read_csv('my.csv')
query=df2.query('cc_vehicle_line==7')
works fine but
df2 = pd.read_csv('my.csv')
query=df2.query('cc_vehicle_line==variable_name')
It throws the message that variable_name is undefined.But it is defined. I... | [
"You should use @variable_name with @\nquery=df2.query('cc_vehicle_line==@variable_name')\n\n",
"You can also use ->\n\nquery=df2.query(f'cc_vehicle_line==\"{variable_name}\"')\nquery=df2.query(f\"cc_vehicle_line=='{variable_name}'\")\nquery=df2.query('cc_vehicle_line==@variable_name')\nquery=df2.query(\"cc_vehic... | [
23,
0
] | [] | [] | [
"indexing",
"pandas",
"python",
"variables"
] | stackoverflow_0030340277_indexing_pandas_python_variables.txt |
Q:
Menu option in python
I have the problem of implementing these programs to find the root of a polynomial (bisection, regular falsi, raphson, secant), I want to make a menu to select the program that I want to execute but when I make the menu I do not get the menu as such only programs are executed.
# Defining Func... | Menu option in python | I have the problem of implementing these programs to find the root of a polynomial (bisection, regular falsi, raphson, secant), I want to make a menu to select the program that I want to execute but when I make the menu I do not get the menu as such only programs are executed.
# Defining Function
def f(x):
return x... | [
"Here is a (high level) solution to your problem:\n\nCreate main function for your program. Check https://realpython.com/python-main-function/ for more info.\nMove input() functions and data conversions to the main function. This saves you a lot of copy/paste code. You then need to have the input functions and con... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074546872_python.txt |
Q:
QStandardItemModel delete multiple rows without problem - python
I'm coding a reddit bot and created a UI like this:
What I want to do is user selects an account from list, clicks the remove selected account and all checked accounts deleted from list. So here is my code:
def delete_selected_accounts(self):
pr... | QStandardItemModel delete multiple rows without problem - python | I'm coding a reddit bot and created a UI like this:
What I want to do is user selects an account from list, clicks the remove selected account and all checked accounts deleted from list. So here is my code:
def delete_selected_accounts(self):
print(len(self.account_list))
for i in range(self.model.rowCount()):... | [
"Hehe, I answered a similar question yesterday.\nYou're iterating over N rows (N being the original number of rows), but along the way, you remove some of the rows. The result? Eventually you'll try to access self.model.item(N - 1), which would be out of range.\nOne way to solve this is to iterate from the back (fr... | [
1
] | [] | [] | [
"python",
"qt"
] | stackoverflow_0074547384_python_qt.txt |
Q:
Active Directory Authentication of Logged-in User using ADODB/ADSDSOObject
My system is connected to Active Directory and I can query it by binding using a username and password.
I noticed that I am also able to query it without explicitly providing a username and password, when using ADO or ADSDSOObject Provider ... | Active Directory Authentication of Logged-in User using ADODB/ADSDSOObject | My system is connected to Active Directory and I can query it by binding using a username and password.
I noticed that I am also able to query it without explicitly providing a username and password, when using ADO or ADSDSOObject Provider (tried in Java/Python/VBA).
I would like to understand how the authentication is... | [
"In the second case, it's using the credentials of the account running the program, or it could even be using the computer account (every computer joined to the domain has an account on the domain, with a password that no person ever sees).\nPython's ldap3 package doesn't automatically do that, however, it appears ... | [
0
] | [] | [] | [
"active_directory",
"ado",
"python",
"vba"
] | stackoverflow_0074543730_active_directory_ado_python_vba.txt |
Q:
Bar Chart sowing wrong dates on xaxis and how can I show correct dates?
When I plot monthly data in plotly the xaxis shows me the wrong dates. For data in June it shows July on the xaxis and all upcoming month are also wrong. I found a similar question on community.plotly, but it didn't work for me. How can I show... | Bar Chart sowing wrong dates on xaxis and how can I show correct dates? | When I plot monthly data in plotly the xaxis shows me the wrong dates. For data in June it shows July on the xaxis and all upcoming month are also wrong. I found a similar question on community.plotly, but it didn't work for me. How can I show the correct dates on the xaxis?
fig = go.Figure(data=[go.Bar(
... | [
"The plotly identifies the data to be on a monthly update and assumes the starting month is July instead of June. If you zoom into the plot, you could observe the month changes to June 30.\nThe month can also be updated using the ticktext where the labels are mentioned for the concerned data point.\ndf = pd.DataFra... | [
2
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074546714_plotly_python.txt |
Q:
TypeError: classification_report() takes 2 positional arguments but 3 were given
return metrics.classification_report(y_true, y_pred, labels, **kwargs)
TypeError: classification_report() takes 2 positional arguments but 3 were given
We are currently training a crf model and we wanted to get the classification rep... | TypeError: classification_report() takes 2 positional arguments but 3 were given |
return metrics.classification_report(y_true, y_pred, labels, **kwargs)
TypeError: classification_report() takes 2 positional arguments but 3 were given
We are currently training a crf model and we wanted to get the classification report of the metrics but we got this error.
we tried to do this instead:
from sklearn.... | [
"Issue is raised in git https://github.com/TeamHG-Memex/sklearn-crfsuite/issues/66\nBut its not resolved till now.\nI was able to alternative :\npip install git+https://github.com/MeMartijn/updated-sklearn-crfsuite.git#egg=sklearn_crfsuite.\n"
] | [
0
] | [] | [] | [
"crf",
"metrics",
"multilabel_classification",
"python"
] | stackoverflow_0071351771_crf_metrics_multilabel_classification_python.txt |
Q:
ValueError: string size must be a multiple of element size while implementing Word2Vec
I am trying to implement Word2Vec but I'm getting this error:
ValueError: string size must be a multiple of element size
This is the code:
from gensim.models.keyedvectors import KeyedVectors
model_path = './data/GoogleNews-vect... | ValueError: string size must be a multiple of element size while implementing Word2Vec | I am trying to implement Word2Vec but I'm getting this error:
ValueError: string size must be a multiple of element size
This is the code:
from gensim.models.keyedvectors import KeyedVectors
model_path = './data/GoogleNews-vectors-negative300.bin'
w2v_model = KeyedVectors.load_word2vec_format(model_path, binary=True)
... | [
"You should set unicode_errors='replace' in the last line:\nw2v_model = KeyedVectors.load_word2vec_format(model_path, binary=True, unicode_errors='replace')\n\n"
] | [
0
] | [] | [] | [
"python",
"word2vec",
"word_embedding"
] | stackoverflow_0073149660_python_word2vec_word_embedding.txt |
Q:
Delete row if next row has the same first value, python
I have an array that looks like this:
data([0.000, 1], [0.0025, 2], [0.0025, 3], [0.005, 5])
I need to delete [0.0025, 3], because it has the same first value as the one before.
I have tried:
for i in data:
if data[i, 0] == data[i+1,0]:
np.delete(... | Delete row if next row has the same first value, python | I have an array that looks like this:
data([0.000, 1], [0.0025, 2], [0.0025, 3], [0.005, 5])
I need to delete [0.0025, 3], because it has the same first value as the one before.
I have tried:
for i in data:
if data[i, 0] == data[i+1,0]:
np.delete(data, (i+1), axis = 0)
But then I get the following Error:
I... | [
"input:\ndata = np.array([[0.000, 1], [0.0025, 2], [0.0025, 3], [0.005, 5]])\n\nsolution:\ndata = data[np.unique(data[:,0], return_index=True)[1]]\n\noutput:\narray([[0.0e+00, 1.0e+00],\n [2.5e-03, 2.0e+00],\n [5.0e-03, 5.0e+00]])\n\n"
] | [
3
] | [] | [] | [
"iteration",
"numpy",
"python"
] | stackoverflow_0074547401_iteration_numpy_python.txt |
Q:
Modify only a few bytes from a npz numpy file without rewriting the whole file
This works to write and load a numpy array + metadata in a .npz compressed file (here the compression is useless because it's random, but anyway):
import numpy as np
# save
D = {"x": np.random.random((10000, 1000)), "metadata": {"date"... | Modify only a few bytes from a npz numpy file without rewriting the whole file | This works to write and load a numpy array + metadata in a .npz compressed file (here the compression is useless because it's random, but anyway):
import numpy as np
# save
D = {"x": np.random.random((10000, 1000)), "metadata": {"date": "20221123", "user": "bob", "name": "abc"}}
with open("test.npz", "wb") as f:
n... | [
"Ultimately the solution that I could get to work (thus far) is the one I originally thought of with zipfile.\nimport zipfile\nimport os\nfrom contextlib import contextmanager\n\n@contextmanager\ndef archive_manager(archive_name: str, key: str):\n f, s = zipfile.ZipFile(archive_name, \"a\"), f\"{key}.npy\"\n\n ... | [
1
] | [] | [] | [
"npz_file",
"numpy",
"python",
"serialization"
] | stackoverflow_0074544551_npz_file_numpy_python_serialization.txt |
Q:
SparkContext Error - File not found /tmp/spark-events does not exist
Running a Python Spark Application via API call -
On submitting the Application - response - Failed
SSH into the Worker
My python application exists in
/root/spark/work/driver-id/wordcount.py
Error can be found in
/root/spark/work/driver-id/s... | SparkContext Error - File not found /tmp/spark-events does not exist | Running a Python Spark Application via API call -
On submitting the Application - response - Failed
SSH into the Worker
My python application exists in
/root/spark/work/driver-id/wordcount.py
Error can be found in
/root/spark/work/driver-id/stderr
Show the following error -
Traceback (most recent call last):
Fi... | [
"/tmp/spark-events is the location that Spark store the events logs. Just create this directory in the master machine and you're set.\n$mkdir /tmp/spark-events\n$ sudo /root/spark-ec2/copy-dir /tmp/spark-events/\nRSYNC'ing /tmp/spark-events to slaves...\nec2-54-175-163-32.compute-1.amazonaws.com\n\n",
"While tryi... | [
37,
9,
4,
1,
0
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0038350249_amazon_ec2_amazon_web_services_apache_spark_pyspark_python.txt |
Q:
Gigantic memory use in example pytorch program. Why?
I have been trying to debug a program using vast amounts of memory and have distilled it into the following example:
# Caution, use carefully, this can utilise all available memory on your computer
# and render it effectively unresponsive, to the point where you... | Gigantic memory use in example pytorch program. Why? | I have been trying to debug a program using vast amounts of memory and have distilled it into the following example:
# Caution, use carefully, this can utilise all available memory on your computer
# and render it effectively unresponsive, to the point where you cannot access
# the shell to kill the process; thus requi... | [
"I think PyTorch store and update the computational graph each time you call f(), and thus the graph-size just keeps getting bigger and bigger.\nCan you try to free the memory usage by using del(tens) (deleting the reference for the variable after usage), and let me know how it works? (found in PyTorch-documents he... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074547107_python_pytorch.txt |
Q:
Split the single column to 4 different columns in Dataframe
I just need need to split a single column of dataframe to 4 different columns. I tried few steps but didn't worked.
DATA1:
Dump
12525 2 153898 Winch
24798 1 147654 Gear
65116 4 Screw
46456 1 Rowing
46563 5 Nut
... | Split the single column to 4 different columns in Dataframe | I just need need to split a single column of dataframe to 4 different columns. I tried few steps but didn't worked.
DATA1:
Dump
12525 2 153898 Winch
24798 1 147654 Gear
65116 4 Screw
46456 1 Rowing
46563 5 Nut
Expected1:
Item Qty Part_no Description
12525 ... | [
"Use str.extract:\ndata_df[['Item','Qty','Part_no','Description']] = \\\ndata_df['Dump'].str.extract(r'(\\d+)\\s+(\\d+)\\s+(\\d*)\\s*(\\w+)')\n\nOutput:\n Dump Item Qty Part_no Description\n0 12525 2 153898 Winch 12525 2 153898 Winch\n1 24798 1 147654 Gear 24798 1 147654 ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074547463_dataframe_pandas_python.txt |
Q:
How does the logic behind this piece of code work?
I have typed out the following code.
la = [1,[2,[3,[4]]]]
lb = [la[1], la[1][1]]
print(la)
lb[0][1]=9
print(la)
I was expecting la to remain as in the original first line, but it changed as shown below.
[1, [2, [3, [4]]]]
[1, [2, 9]]
Does this have to do wi... | How does the logic behind this piece of code work? | I have typed out the following code.
la = [1,[2,[3,[4]]]]
lb = [la[1], la[1][1]]
print(la)
lb[0][1]=9
print(la)
I was expecting la to remain as in the original first line, but it changed as shown below.
[1, [2, [3, [4]]]]
[1, [2, 9]]
Does this have to do with shallow and deep copy? I can't seem to wrap my head a... | [
"So the answer gives you the solution to how to properly copy data in your case, but it does not explains what happens. I commented your script to get an insight into what you are doing:\nA comment on notation:\nptr(X) means a reference to somewhere in memory which I call X.\nX is a un-named address, if you will.\n... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074547471_python.txt |
Q:
Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages
10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by find... | Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages |
10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
... | [
"Working Code. Break down the code in to simple form as much i can. So it will be easy to understand for you.\nd = dict()\nlst = list()\n\nfname = input('enter the file name : ')\ntry:\n fopen = open(fname,'r')\nexcept:\n print('wrong file name !!!')\n\nfor line in fopen:\n \n stline = line.strip()\n ... | [
0,
0,
0,
0,
0,
0
] | [
"fname = input(\"Enter file:\")\nfhandle = open(fname)\ndic={}\nfor line in fhandle:\n if not line.startswith('From '):\n continue\n else:\n line=line.split()\n line=line[5] # accesing the list using index and splitting it\n line=line.split(':')\n bline=line[0]\n #for bl... | [
-1
] | [
"arrays",
"dictionary",
"list",
"python",
"tuples"
] | stackoverflow_0062247502_arrays_dictionary_list_python_tuples.txt |
Q:
Data where cells have factors separated by comma
There is data-frame with cells that have factors ('At a pub', 'At home' ...) that are separated by a comma and are not the same for each cell. See the picture bellow (how excel sees the CSV file):
How can I separate each factor into a column so that the same factor... | Data where cells have factors separated by comma | There is data-frame with cells that have factors ('At a pub', 'At home' ...) that are separated by a comma and are not the same for each cell. See the picture bellow (how excel sees the CSV file):
How can I separate each factor into a column so that the same factors would be in the same column and blanks for others - ... | [
"This can also be done in base R (plus reshape2) or in data.table as well, but here's a working premise for flow to get what you think you need.\nDF <- data.frame(id=1:2, text=c(\"Pubs in the old town,At a club\", \"House party,Pubs in the old town\"))\nlibrary(dplyr)\nlibrary(tidyr) # unnest, pivot_wider\nDF %>%\n... | [
1
] | [] | [] | [
"data_manipulation",
"dataframe",
"powerbi",
"python",
"r"
] | stackoverflow_0074547494_data_manipulation_dataframe_powerbi_python_r.txt |
Q:
Fade widgets out using animation to transition to a screen
I want to implement a button (already has a custom class) that when clicked, fades out all the widgets on the existing screen before switching to another layout (implemented using QStackedLayout)
I've looked at different documentations and guides on PySide... | Fade widgets out using animation to transition to a screen | I want to implement a button (already has a custom class) that when clicked, fades out all the widgets on the existing screen before switching to another layout (implemented using QStackedLayout)
I've looked at different documentations and guides on PySide6 on how to animate fading in/out but nothing seems to be workin... | [
"\nNot sure what is wrong with the code\n\nThe QPropertyAnimation object is destroyed before it gets a chance to start your animation. Your question has already been solved here.\nTo make it work, you must persist the object:\ndef transition_splash(self):\n opacityEffect = QGraphicsOpacityEffect(self.placeholder... | [
1
] | [] | [] | [
"opacity",
"pyside6",
"python",
"qt",
"qwidget"
] | stackoverflow_0074532883_opacity_pyside6_python_qt_qwidget.txt |
Q:
Converting dot to png in python
I have a dot file generated from my code and want to render it in my output. For this i have seen on the net that the command is something like this on cmd
dot -Tpng InputFile.dot -o OutputFile.png for Graphviz
But my problem is that I want to use this inbuilt in my python program... | Converting dot to png in python | I have a dot file generated from my code and want to render it in my output. For this i have seen on the net that the command is something like this on cmd
dot -Tpng InputFile.dot -o OutputFile.png for Graphviz
But my problem is that I want to use this inbuilt in my python program.
How can i do so ??
I looked at pydo... | [
"Load the file with pydot.graph_from_dot_file to get a pydot.Dot class instance. Then write it to a PNG file with the write_png method.\nimport pydot\n\n(graph,) = pydot.graph_from_dot_file('somefile.dot')\ngraph.write_png('somefile.png')\n\n",
"pydot needs the GraphViz binaries to be installed anyway, so if you'... | [
66,
26,
6,
4,
4,
4,
1,
0
] | [
"from graphviz import render\ndot.render(directory='doctest-output', view=True)\n\n"
] | [
-2
] | [
"dot",
"png",
"python"
] | stackoverflow_0005316206_dot_png_python.txt |
Q:
How to avoid "RuntimeError: dictionary changed size during iteration" error?
I have a dictionary of lists in which some of the values are empty:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
At the end of creating these lists, I want to remove these empty lists before returning my dictionary. I tried doing it like... | How to avoid "RuntimeError: dictionary changed size during iteration" error? | I have a dictionary of lists in which some of the values are empty:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
At the end of creating these lists, I want to remove these empty lists before returning my dictionary. I tried doing it like this:
for i in d:
if not d[i]:
d.pop(i)
but I got a RuntimeError. I ... | [
"In Python 3.x and 2.x you can use use list to force a copy of the keys to be made:\nfor i in list(d):\n\nIn Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:\nfor i in d.keys():\n\nBut note that in Python 3.x this second method doesn't help with your error becaus... | [
717,
113,
65,
35,
14,
13,
13,
9,
3,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"list",
"loops",
"python"
] | stackoverflow_0011941817_dictionary_list_loops_python.txt |
Q:
flask_mysqldb - MYSQL cursor is throwing an error - cursor is not a known member of "None"
I am writing a simple auth service in python using flask and flask_mysqldb. There is an error with the cursor.
import jwt
from flask import Flask, request
from flask_mysqldb import MySQL
server = Flask(__name__)
mysql = My... | flask_mysqldb - MYSQL cursor is throwing an error - cursor is not a known member of "None" | I am writing a simple auth service in python using flask and flask_mysqldb. There is an error with the cursor.
import jwt
from flask import Flask, request
from flask_mysqldb import MySQL
server = Flask(__name__)
mysql = MySQL(server)
# server configuration
server.config["MYSQL_HOST"] = os.environ.get("MYSQL_HOST")
... | [
"Please try\ncur = mysql.connect.cursor()\nif you use a connection it will not suggest cursor(). once you use connect.cursor() it will not show the error. Thanks\n"
] | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074422679_flask_python.txt |
Q:
Retrive firstnames from a list of names in pandas
I have a dataset with pubmed articles, and a column with the authors of each article, like this:
DOI Fullnames
0 10.1016/0022-1759(96)00092-0 B I Korelitz, S C Sommers
1 10.1038/jhg.2017.16 Avi Saskin 1 , Vanessa F... | Retrive firstnames from a list of names in pandas | I have a dataset with pubmed articles, and a column with the authors of each article, like this:
DOI Fullnames
0 10.1016/0022-1759(96)00092-0 B I Korelitz, S C Sommers
1 10.1038/jhg.2017.16 Avi Saskin 1 , Vanessa Fulginiti 1 , Ashley ...
2 10.1007/s00415-005-0964-z ... | [
"I suppose you say the results are incorrect because of the 8th row of your dataframe. You can see there that all the first names start with Y, so this shows you the potential failure mode of your method.\nIn the 8th row most of the authors are Chinese (looking at the surnames) and Chinese surnames are not very var... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074546694_pandas_python.txt |
Q:
List Directories and get the name of the Directory
I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
import os
... | List Directories and get the name of the Directory | I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
import os
for directories in os.listdir(os.getcwd()):
dir = o... | [
"This will print all the subdirectories of the current directory:\nprint [name for name in os.listdir(\".\") if os.path.isdir(name)]\n\nI'm not sure what you're doing with split(\"-\"), but perhaps this code will help you find a solution?\nIf you want the full pathnames of the directories, use abspath:\nprint [os.p... | [
97,
25,
22,
9,
4,
0
] | [] | [] | [
"directory",
"list",
"operating_system",
"python"
] | stackoverflow_0002690324_directory_list_operating_system_python.txt |
Q:
What is an Object in Python?
I am surprised that my question was not asked (worded like the above) before. I am hoping that someone could break down this basic term "object" in the context of a OOP language like Python. Explained in a way in which a beginner like myself would be able to grasp.
When I typed my ques... | What is an Object in Python? | I am surprised that my question was not asked (worded like the above) before. I am hoping that someone could break down this basic term "object" in the context of a OOP language like Python. Explained in a way in which a beginner like myself would be able to grasp.
When I typed my question on Google, the first post tha... | [
"Everything is an object\nAn object is a fundamental building block of an object-oriented language. Integers, strings, floating point numbers, even arrays and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string \"hello, world... | [
18,
8,
4,
3,
1,
0,
0
] | [
"\nAn object is simply a collection of data (variables) and methods (functions) that act on data.\n\nA class is a blueprint for that object.\n\n\n"
] | [
-2
] | [
"object",
"oop",
"python"
] | stackoverflow_0056310092_object_oop_python.txt |
Q:
Suggestions to replace nans with a mixture of previous and subsequent values
Assume I have a 1D array and want to replace / interpolate NaN blocks of length n with copies of the n/2 non-nan previous values and the n/2 non-nan subsequent values.
Example 1:
input = [1, 2, NaN, NaN, NaN, NaN, 3, 2]
output= [1, 2, 1... | Suggestions to replace nans with a mixture of previous and subsequent values | Assume I have a 1D array and want to replace / interpolate NaN blocks of length n with copies of the n/2 non-nan previous values and the n/2 non-nan subsequent values.
Example 1:
input = [1, 2, NaN, NaN, NaN, NaN, 3, 2]
output= [1, 2, 1, 2, 3, 2, 3, 2]
Example 2: if n is odd, fill with n%2+1 previous values an... | [
"Considering this comment from OP:\n\nit is no assignment. just thought that one of you guys will come up with a much nicer way to solve this.\n\nThe question is too broad in this form, but here are some leads.\nIf you are using pandas, you can have a look to the following functions which are designed to fill missi... | [
0
] | [] | [] | [
"fillna",
"interpolation",
"python"
] | stackoverflow_0074547741_fillna_interpolation_python.txt |
Q:
BFS - TypeError: 'ellipsis' object is not subscriptable - implementing algorithm
I am trying to implement the BFS algorithm but python is giving me an error that the ellipsis object is not sub scriptable.
I am unsure what these means because as far as I am aware this type should not be Ellipsis?
TypeError: 'ellips... | BFS - TypeError: 'ellipsis' object is not subscriptable - implementing algorithm | I am trying to implement the BFS algorithm but python is giving me an error that the ellipsis object is not sub scriptable.
I am unsure what these means because as far as I am aware this type should not be Ellipsis?
TypeError: 'ellipsis' object is not subscriptable
Causing error:
visited[starting_row][starting_col] = ... | [
"Your code has this line:\nvisited = ...\n\nThis ... is not commonly used, but it is a native object. The documentation on Ellipsis has:\n\nThe same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types. Ellipsis is the sole instan... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074547163_python.txt |
Q:
convert a excel file to nested json file using python
My data with multiple pages looks like this
I want to convert it to a JSON file like below.
{
"Name" : "A",
{
"Project" : "P1",
{
[
"T1" : "P1.com",
]
},
"Project" : "P2",
{
[
"T2" : "P2.com",
"T3" : "P2.com",
]
}
},
"Name" ... | convert a excel file to nested json file using python | My data with multiple pages looks like this
I want to convert it to a JSON file like below.
{
"Name" : "A",
{
"Project" : "P1",
{
[
"T1" : "P1.com",
]
},
"Project" : "P2",
{
[
"T2" : "P2.com",
"T3" : "P2.com",
]
}
},
"Name" : "B",
{
"Project" : "Q1",
{
[
"T1" : "Q1.com",
... | [
"You have many options, I'll provide you with them using the pandas library, choose which one is more suitable to you\n\nPandas Library\nPandas to_json() method\n\nExample Code:\nimport pandas as pd\n\ndata = [\n [\"A\", \"P1\", \"T1\", \"P1.com\"],\n [\"A\", \"P2\", \"T2\", \"P2.com\"],\n [\"A\", \"P2\", ... | [
2
] | [] | [] | [
"excel",
"json",
"key_value",
"python",
"xls"
] | stackoverflow_0074472792_excel_json_key_value_python_xls.txt |
Q:
Column transformers using NumPy indexing
I am studying this snippet and I don't understand how to column addition was constructed.
def column_addition(X):
return X[:, [0]] + X[:, [1]]
def addition_pipeline():
return make_pipeline(
SimpleImputer(strategy="median"),
FunctionTransformer(colum... | Column transformers using NumPy indexing | I am studying this snippet and I don't understand how to column addition was constructed.
def column_addition(X):
return X[:, [0]] + X[:, [1]]
def addition_pipeline():
return make_pipeline(
SimpleImputer(strategy="median"),
FunctionTransformer(column_addition))
preprocessing = ColumnTransforme... | [
"A couple of premises to understand how this example works:\n\nthe Pipeline is meant to apply transformations serially. Therefore, your pipeline will first impute some columns (we'll see later which ones; anticipation: they'll be ['sibsp', 'parch']) with the median value and then it will apply the column addition o... | [
0
] | [] | [] | [
"numpy",
"python",
"scikit_learn"
] | stackoverflow_0074510935_numpy_python_scikit_learn.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.