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:
Why does my webpage not return an updated list after adding objects? Using Flask
This is my python code. Any idea what is wrong/missing? I am using Flask to host a local web server. I am not experienced in HTML or CSS, so I am using templates provided by my course. I am able to successfully run the program, but if... | Why does my webpage not return an updated list after adding objects? Using Flask | This is my python code. Any idea what is wrong/missing? I am using Flask to host a local web server. I am not experienced in HTML or CSS, so I am using templates provided by my course. I am able to successfully run the program, but if I add a check or deposit via the webpage, the webpage that is supposed to display all... | [
"can you also share the checkbook-result.html.\nbecause the displaying or outputting of the data happened on the template\nthanks\n"
] | [
0
] | [] | [] | [
"css",
"html",
"python",
"server"
] | stackoverflow_0074369702_css_html_python_server.txt |
Q:
how to convert the dictionary with the list item to the pandas.Series?
data_dict = {'A': [1,3,3], 'B': [2,3,3]}
convert to
A 1
A 3
A 3
B 2
B 3
B 3
I tried to loop, but it is not simple enough. Is there any more simple method?
A:
data_dict = {'A': [1,3,3], 'B': [2,3,3]}
s = pd.Series(data_dict).exp... | how to convert the dictionary with the list item to the pandas.Series? | data_dict = {'A': [1,3,3], 'B': [2,3,3]}
convert to
A 1
A 3
A 3
B 2
B 3
B 3
I tried to loop, but it is not simple enough. Is there any more simple method?
| [
"data_dict = {'A': [1,3,3], 'B': [2,3,3]}\ns = pd.Series(data_dict).explode()\nprint(s)\n\nA 1\nA 3\nA 3\nB 2\nB 3\nB 3\ndtype: object\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"pandas",
"python",
"series"
] | stackoverflow_0074369742_dictionary_pandas_python_series.txt |
Q:
Python script to search a pattern in a given file
I am looking for a script to search for a file in the directory and grep the content from the file searched. My script here searches for the file My_data.txt and I would need to use the same file to open and grep for patter Name,Age and want it to be printed.
I am ... | Python script to search a pattern in a given file | I am looking for a script to search for a file in the directory and grep the content from the file searched. My script here searches for the file My_data.txt and I would need to use the same file to open and grep for patter Name,Age and want it to be printed.
I am unable to link the below search code to the above one t... | [
"Not Python: $ grep -ER -e '{regex expression}' {directory to crawl} replace items within {}. Or you can do many things with find ... -print0 | xargs -0 grep -Ee ... to use the powerful find features and then pipe those files into a grep command. Don't recreate the wheel.\nIf I could comment I would have put this t... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074369744_python.txt |
Q:
Altair binned color values - 7 colors
How would I add a third, fourth (ideally I would like to have 7 different) color bins to this histogram?
alt.Chart(X_train).transform_bin(
'Creditworthiness_bin', 'Creditworthiness', bin=alt.Bin(step=10)
).transform_joinaggregate(
count='count()', groupby=['Creditworth... | Altair binned color values - 7 colors | How would I add a third, fourth (ideally I would like to have 7 different) color bins to this histogram?
alt.Chart(X_train).transform_bin(
'Creditworthiness_bin', 'Creditworthiness', bin=alt.Bin(step=10)
).transform_joinaggregate(
count='count()', groupby=['Creditworthiness_bin']
).mark_bar(orient='vertical')... | [
"alt.Chart(X_train).mark_bar().encode(\n x = alt.X('Creditworthiness', bin=alt.Bin(extent=[0, 100], step=5)),\n y='count()',\n color=alt.Color('Creditworthiness:Q', title='Count',\n bin=alt.Bin(extent=[0, 100], step=10), \n scale=alt.Scale(scheme='dark2')\n )\n)\n\nIn the code ... | [
1
] | [] | [] | [
"altair",
"binning",
"colors",
"python"
] | stackoverflow_0074367846_altair_binning_colors_python.txt |
Q:
What is the clean way to unittest FileField in django?
I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields?
How can I make sure that the unittests are not going to pollute the real application?
Thanks ... | What is the clean way to unittest FileField in django? | I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields?
How can I make sure that the unittests are not going to pollute the real application?
Thanks in advance
PS: My question is almost a duplicate of Django t... | [
"Django provides a great way to do this - use a SimpleUploadedFile or a TemporaryUploadedFile. SimpleUploadedFile is generally the simpler option if all you need to store is some sentinel data:\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\nmy_model.file_field = SimpleUploadedFile(\n \"best_fi... | [
126,
51,
17,
3,
2,
0
] | [] | [] | [
"django",
"django_unittest",
"filefield",
"python"
] | stackoverflow_0004283933_django_django_unittest_filefield_python.txt |
Q:
How to regex extract CAR MAKE from URL in pandas df column
I am trying to extract from URL str "/used/Mercedes-Benz/2021-Mercedes-Benz-Sprinte..."
the entire Make name, i.e. "Mercedes-Benz"
BUT my pattern only returns the first letter, i.e. "M"
Please help me come up with the correct pattern to use on pandas df.
T... | How to regex extract CAR MAKE from URL in pandas df column | I am trying to extract from URL str "/used/Mercedes-Benz/2021-Mercedes-Benz-Sprinte..."
the entire Make name, i.e. "Mercedes-Benz"
BUT my pattern only returns the first letter, i.e. "M"
Please help me come up with the correct pattern to use on pandas df.
Thank you
CODE:
URLS_by_City['Make'] = URLS_by_City['Page'].str.e... | [
"I have tried completing your requirement in Jupyter Notebook.\nPFB the code and screenshots:\n\nI have created a dummy pandas dataframe(data_df), below is a screenshot of the same\n\n\n\nI have created a pattern based on the pattern of the string to be extracted\npattern = \"^/used/(.*)/(?=[20][0-9{2}])\"\n\nUsed ... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"regex"
] | stackoverflow_0074355223_dataframe_pandas_python_regex.txt |
Q:
Python index x is out bounds for axis 0 size of n
Hey guys trying to attempt to create my own basic hockey analytic program. While trying to get all my information I gave been stumped by this error. Tried looking a bunch of things up and nothing seemed to work for me. I am new to using pandas and numpy. Any help w... | Python index x is out bounds for axis 0 size of n | Hey guys trying to attempt to create my own basic hockey analytic program. While trying to get all my information I gave been stumped by this error. Tried looking a bunch of things up and nothing seemed to work for me. I am new to using pandas and numpy. Any help would be much appreciated , thank you!!
import numpy as ... | [
"Try:\nfor i in range(len(nyr_GID)):\n nyr_GID[i] = str(nyr_GID[i])[5:]\n\n",
"The i in\n\nfor i in nyr_GID:\n\nrefers to the elements in nyr_GID.\nTo get the corresponding indices use :\nrange(nyr_GID.size)\nTiny code snippet :\ntest = np.array([234, 345, 456])\nfor i in test:\n print(i, test[i])\n\nTracebac... | [
1,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074369755_numpy_pandas_python.txt |
Q:
Is there a better way to organize class objects?
I have a bunch of ‘item’ objects and I want to organize them in the most functional way possible. I’ve checking the python formatting guide and didn’t find much information. Currently I’m doing the following:
class Items(object):
def __init__(self, name, a,... | Is there a better way to organize class objects? | I have a bunch of ‘item’ objects and I want to organize them in the most functional way possible. I’ve checking the python formatting guide and didn’t find much information. Currently I’m doing the following:
class Items(object):
def __init__(self, name, a, b)
self.name = name
etc.
def mod_b(... | [
"I can't write comments yet so this is a pseudo answer. Follow PEP8 first of all, for style/format. Otherwise parse established python projects on GitHub for practices. Use useful variable_names not b. Put globals in CAPS at the top of the module. Call your dict with .get to pass a default value. Your iterator stat... | [
0
] | [] | [] | [
"oop",
"python",
"python_3.x"
] | stackoverflow_0074369241_oop_python_python_3.x.txt |
Q:
writing to excel sheet in robot framework
I have test cases in robot framework.
Scenario is data driven scenario from excel
for example ;
I have 2 column; First column is full that from my data
rezno
Column B
resno 1
resno 2
*** Settings ***
Library SeleniumLibrary
Library BuiltIn
Resource ../../Step... | writing to excel sheet in robot framework | I have test cases in robot framework.
Scenario is data driven scenario from excel
for example ;
I have 2 column; First column is full that from my data
rezno
Column B
resno 1
resno 2
*** Settings ***
Library SeleniumLibrary
Library BuiltIn
Resource ../../StepDefinition/Operation/OperationSteps... | [
"You can use the Excel library given by Robocorp.\nInstall\npip install rpaframework\nCheck for more keywords: https://rpaframework.org/libraries/excel_files/index.html\n*** Settings ***\nLibrary RPA.Excel.Files\n\n*** Test Cases ***\nCreating new Excel\n Create Workbook ${EXECDIR}\\\\testdata\\\\Amount.xlsx... | [
0
] | [] | [] | [
"data_driven_tests",
"excel",
"python",
"robotframework"
] | stackoverflow_0074338396_data_driven_tests_excel_python_robotframework.txt |
Q:
how can I make the errors in my code appear in my terminal
Hello I have a problem with my code I have a code that allows to warn and watch the number of warn of a person but there is an error in my code
here it is :
from discord_slash import SlashCommand
slash = SlashCommand(client, sync_commands = True)
for gu... | how can I make the errors in my code appear in my terminal | Hello I have a problem with my code I have a code that allows to warn and watch the number of warn of a person but there is an error in my code
here it is :
from discord_slash import SlashCommand
slash = SlashCommand(client, sync_commands = True)
for guild in bot.guilds:
async with aiofiles.open(f"{guild.id}.txt... | [
"I suggest you use a simple print if your lazy like me\nif #do stuff\nprint(Error) #It doesn't really need any code it will print if it works\n\nPrint doesn't really need code as it'll print if the command works by itself.\n"
] | [
0
] | [] | [] | [
"discord.py",
"python",
"robot"
] | stackoverflow_0074197138_discord.py_python_robot.txt |
Q:
How do I parse an ISO 8601-formatted date?
I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type.
I have found strptime in the Python standard library, but it is not very convenient.
What is the best way to do this?
A:
isoparse function from python-dateutil
The python-da... | How do I parse an ISO 8601-formatted date? | I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type.
I have found strptime in the Python standard library, but it is not very convenient.
What is the best way to do this?
| [
"isoparse function from python-dateutil\nThe python-dateutil package has dateutil.parser.isoparse to parse not only RFC 3339 datetime strings like the one in the question, but also other ISO 8601 date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a d... | [
632,
426,
224,
187,
85,
49,
38,
38,
30,
22,
20,
16,
13,
13,
9,
9,
8,
7,
7,
7,
5,
3,
3,
2,
1,
1,
0
] | [
"Initially I tried with:\nfrom operator import neg, pos\nfrom time import strptime, mktime\nfrom datetime import datetime, tzinfo, timedelta\n\nclass MyUTCOffsetTimezone(tzinfo):\n @staticmethod\n def with_offset(offset_no_signal, signal): # type: (str, str) -> MyUTCOffsetTimezone\n return MyUTCOffset... | [
-1,
-2
] | [
"datetime",
"datetime_parsing",
"iso8601",
"python",
"rfc3339"
] | stackoverflow_0000127803_datetime_datetime_parsing_iso8601_python_rfc3339.txt |
Q:
Using Pip to install packages to Anaconda Environment
conda 4.2.13
MacOSX 10.12.1
I am trying to install packages from pip to a fresh environment (virtual) created using anaconda. In the Anaconda docs it says this is perfectly fine. It is done the same way as for virtualenv.
Activate the environment where you... | Using Pip to install packages to Anaconda Environment | conda 4.2.13
MacOSX 10.12.1
I am trying to install packages from pip to a fresh environment (virtual) created using anaconda. In the Anaconda docs it says this is perfectly fine. It is done the same way as for virtualenv.
Activate the environment where you want to put the program, then pip install a program...
I ... | [
"For others who run into this situation, I found this to be the most straightforward solution:\n\nRun conda create -n venv_name and conda activate venv_name, where venv_name is the name of your virtual environment.\n\nRun conda install pip. This will install pip to your venv directory.\n\nFind your anaconda directo... | [
510,
116,
97,
18,
11,
10,
4,
4,
4,
3,
3,
3,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"anaconda",
"environment",
"pip",
"python"
] | stackoverflow_0041060382_anaconda_environment_pip_python.txt |
Q:
Changing the base color of ploty_express parallel_categories diagram
Creating a parallel_categories with ploty express
import plotly.express as px
df = px.data.tips()
fig = px.parallel_categories(df)
fig.show()
gives a diagram with blue base color.
I would like to change the base color without using graph objec... | Changing the base color of ploty_express parallel_categories diagram | Creating a parallel_categories with ploty express
import plotly.express as px
df = px.data.tips()
fig = px.parallel_categories(df)
fig.show()
gives a diagram with blue base color.
I would like to change the base color without using graph object. Just the overall color from blue to e.g. gray.
Assigning a color via a... | [
"express\nI have found that this can be achieved with plotly.express. Create a color list and specify a continuous color scale gray.\nimport plotly.express as px\nimport numpy as np\n\ncolor = np.zeros(len(df), dtype='uint8')\n\ndf = px.data.tips()\nfig = px.parallel_categories(df, color=color, color_continuous_sca... | [
1,
0
] | [] | [] | [
"colors",
"plotly",
"plotly_express",
"python"
] | stackoverflow_0072749285_colors_plotly_plotly_express_python.txt |
Q:
AWS Cognito Authentication USER_PASSWORD_AUTH flow not enabled for this client
I have an mobile app with user pool (username & password). The app works fine with aws-amplify sdk. But, wanted to move the code out to Lambdas. So, I have written the following Lambda using Boto3.
Here is Lambda:
import boto3
def lamb... | AWS Cognito Authentication USER_PASSWORD_AUTH flow not enabled for this client | I have an mobile app with user pool (username & password). The app works fine with aws-amplify sdk. But, wanted to move the code out to Lambdas. So, I have written the following Lambda using Boto3.
Here is Lambda:
import boto3
def lambda_handler(event, context):
client = boto3.client('cognito-idp')
response = ... | [
"Figured it. I have goto user pool - > app clients - >show details -> Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH).\nThat fixed it.\n",
"Figured it. I have goto user pool - > app clients - >show details -> Enable username password auth for admin APIs for authentication... | [
92,
17,
2,
0
] | [
"I figured it out.Inspite of AuthFlow pass ExplicitAuthFlows then it should work.\n`\nimport boto3\ndef lambda_handler(event, context):\n client = boto3.client('cognito-idp')\n response = client.initiate_auth(\n UserPoolId='xxxxxxxxx',\n ClientId='xxxxxxxxxxxxxx',\n ExplicitAuthFlows='USE... | [
-1
] | [
"amazon_cognito",
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0049000676_amazon_cognito_amazon_web_services_boto3_python.txt |
Q:
Plotting 1:8 attributes on altair
How to plot graph for 1:8 attributes using altair? Here is the link to the dataset. I want to plot an interactive mark_point() graph for various attributes like fresh, frozen, etc, considering the region and channel as filters. The x-axis should have attributes, and the y-axis wi... | Plotting 1:8 attributes on altair | How to plot graph for 1:8 attributes using altair? Here is the link to the dataset. I want to plot an interactive mark_point() graph for various attributes like fresh, frozen, etc, considering the region and channel as filters. The x-axis should have attributes, and the y-axis will have the count.
The interaction is b... | [
"I guess this is the limitation of altair. you cannot club all the attributes together. You will need matplotlib for doing so. Hope this helps. !!\n",
"\nYou can create two filters: one for the region and one for the channel, and combine them with an AND operator to filter the data.\nThis gives you a subset of th... | [
0,
0
] | [] | [] | [
"altair",
"pandas",
"python"
] | stackoverflow_0074366293_altair_pandas_python.txt |
Q:
convert numpy array to list of 6 elements where each time the values should shift by one position in python
I have a dataset in numpy arrays values
array([0.74, 0.77, 0.72, 0.65, 0.24,
0.07,0.79,0.88])
I want to convert numpy array to list of 6 elements where each time the values should shift by one positi... | convert numpy array to list of 6 elements where each time the values should shift by one position in python | I have a dataset in numpy arrays values
array([0.74, 0.77, 0.72, 0.65, 0.24,
0.07,0.79,0.88])
I want to convert numpy array to list of 6 elements where each time the values should shift by one position in python
This is the list of list that I want to get.
[[0.74, 0.77, 0.72, 0.65, 0.24,0.07],[0.77, 0.72, 0.65,... | [
"So, it isn't clear how many times you want to shift your array, and why the length of the resulting sublists is what it is. But just use numpy.roll. Something to the effect of:\nresult = [np.roll(arr, -i)[:-2].tolist() for i in range(3)]\n\nBased on the comment from @hpaulj I think you want something like:\nn = 6... | [
2
] | [] | [] | [
"list",
"numpy",
"numpy_ndarray",
"pandas",
"python"
] | stackoverflow_0074370022_list_numpy_numpy_ndarray_pandas_python.txt |
Q:
Storing and retrieving Data from a list and a dictionary
-1
I'm trying to solve the following problem: Write a payroll program that stores all the user input in a list and the total of all the input in a dictionary until the user ends the program. When the program ends it will list each input given and then a tota... | Storing and retrieving Data from a list and a dictionary | -1
I'm trying to solve the following problem: Write a payroll program that stores all the user input in a list and the total of all the input in a dictionary until the user ends the program. When the program ends it will list each input given and then a total of all the input. Here is what I have so far:
import dates
... | [
"You should use class structure to store all the employee details and then loop over those objects to get individual or total statistics. You can use __ str __ (dunder method) which can help you access object of class by employee name.\n"
] | [
0
] | [] | [] | [
"dictionary",
"function",
"list",
"python"
] | stackoverflow_0074369838_dictionary_function_list_python.txt |
Q:
Convert datetime object to a String of date only in Python
I see a lot on converting a date string to an datetime object in Python, but I want to go the other way.
I've got
datetime.datetime(2012, 2, 23, 0, 0)
and I would like to convert it to string like '2/23/2012'.
A:
You can use strftime to help you format... | Convert datetime object to a String of date only in Python | I see a lot on converting a date string to an datetime object in Python, but I want to go the other way.
I've got
datetime.datetime(2012, 2, 23, 0, 0)
and I would like to convert it to string like '2/23/2012'.
| [
"You can use strftime to help you format your date.\nE.g.,\nimport datetime\nt = datetime.datetime(2012, 2, 23, 0, 0)\nt.strftime('%m/%d/%Y')\n\nwill yield:\n'02/23/2012'\n\nMore information about formatting see here\n",
"date and datetime objects (and time as well) support a mini-language to specify output, and ... | [
658,
268,
56,
18,
15,
12,
10,
9,
9,
3,
3,
2,
0,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0010624937_datetime_python.txt |
Q:
Put multiple values with same key in one row
I have such result:
{'name': name1 , 'pic': pic1}
{'name': name1 , 'pic': pic2}
{'name': name1 , 'pic': pic3}
{'name': name2 , 'pic': pic4}
{'name': name2 , 'pic': pic5}
{'name': name2 , 'pic': pic6}
{'name': name3 , 'pic': pic7}
{'name': name3 , 'pic': pic8}
{'name': n... | Put multiple values with same key in one row | I have such result:
{'name': name1 , 'pic': pic1}
{'name': name1 , 'pic': pic2}
{'name': name1 , 'pic': pic3}
{'name': name2 , 'pic': pic4}
{'name': name2 , 'pic': pic5}
{'name': name2 , 'pic': pic6}
{'name': name3 , 'pic': pic7}
{'name': name3 , 'pic': pic8}
{'name': name3 , 'pic': pic9}
{'name': name3 , 'pic': pic10... | [
"Here is one way to do it:\nAssuming you have your original dictionaries in a list pic_list:\nimport pandas as pd\n\nname1,name2,name3 = 'name1','name2','name3'\npic1,pic2,pic3,pic4,pic5,pic6,pic7,pic8,pic9,pic10 = 'pic1','pic2','pic3','pic4','pic5','pic6','pic7','pic8','pic9','pic10'\n\npic_list = [{'name': name1 ... | [
0
] | [] | [] | [
"horizontallistview",
"key_value_store",
"python"
] | stackoverflow_0074369346_horizontallistview_key_value_store_python.txt |
Q:
Converting to UNIX time
I have a .csv file that contains:
created_at
actual_delivery_time
2015-02-06 22:24:17
2015-02-06 23:27:16
2015-02-10 21:49:25
2015-02-10 22:56:29
I want to convert these columns from datetime to UNIX timestamp.
For created_at, I was able to convert:
ndf["created_unix"] = pd.to_datetime(... | Converting to UNIX time | I have a .csv file that contains:
created_at
actual_delivery_time
2015-02-06 22:24:17
2015-02-06 23:27:16
2015-02-10 21:49:25
2015-02-10 22:56:29
I want to convert these columns from datetime to UNIX timestamp.
For created_at, I was able to convert:
ndf["created_unix"] = pd.to_datetime(ndf["created_at"])
... | [
"\nI'm not sure why its producing a different result.\n\nConsult ndf.dtypes.\nYou are complaining that one column\nis of type int, while the other is a float.\nLikely one or more actual_delivery_time values\nwere blank, and pandas represented that with\na floating-point NaN.\n"
] | [
2
] | [] | [] | [
"datetime",
"pandas",
"python",
"timestamp",
"unix_timestamp"
] | stackoverflow_0074370067_datetime_pandas_python_timestamp_unix_timestamp.txt |
Q:
Keywords extracted from text using KeyBERT and lambda function appear to be similar
I am trying to extract keywords from multiple pieces of text held in a pandas dataframe column.
The dataframe's name is memo_ and the column's name is 'Text'. I am applying the KeyBERT model as shown below. I am not getting the rig... | Keywords extracted from text using KeyBERT and lambda function appear to be similar | I am trying to extract keywords from multiple pieces of text held in a pandas dataframe column.
The dataframe's name is memo_ and the column's name is 'Text'. I am applying the KeyBERT model as shown below. I am not getting the right output. The keywords seem to be similar for all rows despite the text being different.... | [
"I've created a minimal working example below using the information you've provided. The output shows that the results are not similar for all rows. This suggests one (or both) of following things may be happening in your code:\n\nYour dataframe's 'Text' column contains entries that are very similar (if not identic... | [
1
] | [] | [] | [
"bert_language_model",
"function",
"keyword",
"nlp",
"python"
] | stackoverflow_0074360815_bert_language_model_function_keyword_nlp_python.txt |
Q:
How do I print the full NumPy array, without truncation?
When I print a numpy array, I get a truncated representation, but I want the full array.
>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38, 39],
... | How do I print the full NumPy array, without truncation? | When I print a numpy array, I get a truncated representation, but I want the full array.
>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38, 39],
[ 40, 41, 42, ..., 77, 78, 79],
[ 80, 8... | [
"Use numpy.set_printoptions:\nimport sys\nimport numpy\nnumpy.set_printoptions(threshold=sys.maxsize)\n\n",
"import numpy as np\nnp.set_printoptions(threshold=np.inf)\n\nI suggest using np.inf instead of np.nan which is suggested by others. They both work for your purpose, but by setting the threshold to \"infini... | [
902,
295,
182,
161,
49,
44,
35,
15,
13,
10,
10,
7,
7,
6,
4,
3,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"output_formatting",
"python"
] | stackoverflow_0001987694_arrays_numpy_output_formatting_python.txt |
Q:
Python AutoPep8 formatting not working with max line length parameter
I noticed one strange thing that autopep8 autoformatting in VSCode doesn't work when we set
"python.formatting.autopep8Args": [
"--line-length 119"
],
But if this setting is in a default mode that is line length 79 then it works... | Python AutoPep8 formatting not working with max line length parameter | I noticed one strange thing that autopep8 autoformatting in VSCode doesn't work when we set
"python.formatting.autopep8Args": [
"--line-length 119"
],
But if this setting is in a default mode that is line length 79 then it works well. Is there some issue with autopep8 to work only with line length 79 n... | [
"experimental worked for me\n\"python.formatting.autopep8Args\": [\"--max-line-length\", \"120\", \"--experimental\"]\n\ncheck out this link for proper format specifier settings\n",
"This should work -\n\"python.formatting.provider\": \"autopep8\",\n\"python.formatting.autopep8Args\": [\n \"--max-line-length\"... | [
41,
14,
1
] | [] | [] | [
"autopep8",
"flake8",
"python",
"visual_studio_code"
] | stackoverflow_0063314452_autopep8_flake8_python_visual_studio_code.txt |
Q:
Tkinter window appears black upon running in PyCharm
Tkinter background appears black upon running script no matter how I attribute the background colour.
I'm using PyCharm CE 2021.3.2 on macOS 12.2.1.
Python Interpreter = Python 3.8 with 5 packages (as follows):
Pillow 9.0.1
future 0.18.2
pip 22.0.3
setuptools 5... | Tkinter window appears black upon running in PyCharm | Tkinter background appears black upon running script no matter how I attribute the background colour.
I'm using PyCharm CE 2021.3.2 on macOS 12.2.1.
Python Interpreter = Python 3.8 with 5 packages (as follows):
Pillow 9.0.1
future 0.18.2
pip 22.0.3
setuptools 57.0.0
wheel 0.36.2
Window looks like this:
Black, blank T... | [
"Thanks to @typedecker\nIssue was with Python 3.8 and the Monterey update.\nFix:\nFirst install Python 3.10 then follow this tutorial:\nCreating Python 3.10 Virtual Env\nThen simply select the newly created virtual env in PyCharms and run.\n",
"This worked for me in pycharm on Monterey.\nInstalled python3.10\nThe... | [
3,
0,
0
] | [] | [] | [
"pycharm",
"python",
"tkinter"
] | stackoverflow_0071294521_pycharm_python_tkinter.txt |
Q:
How to make the dictionary.Item into a key for another dictionary and keep the new key also
I have scenario A a dictionary that I would wish to transform using this method if it's possible or is there an alternative
A = {A:1,B:2,C:3}
B = {values[1] : values[1]*2 for values in A.items()}
Desired outcome:
B = {1:... | How to make the dictionary.Item into a key for another dictionary and keep the new key also | I have scenario A a dictionary that I would wish to transform using this method if it's possible or is there an alternative
A = {A:1,B:2,C:3}
B = {values[1] : values[1]*2 for values in A.items()}
Desired outcome:
B = {1:2,2:4,3:6}
| [
"How about:\nA = (1,2,3)\nB = {item:item*2 for item in A}\n\nIf you still want a dictionary A, could be:\nA = {'A':1, 'B':2, 'C':3}\nB = {item[1]:item[1]*2 for item in A.items()}\n\n",
"B = {val:val*2 for val in A.values()}.\nOrdered dicts are only ensured >= Python3.7 so while this will likely work in Python < 3... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074370076_dictionary_python.txt |
Q:
Extracting row data from a single column in a Python DataFrame
Run the following code to identify the problem.
#Import the library
import amberelectric
from amberelectric.api import amber_api
import pandas as pd
configuration = amberelectric.Configuration(access_token = 'psk_954ef8ead8c4323b4fe73064186f6362'... | Extracting row data from a single column in a Python DataFrame | Run the following code to identify the problem.
#Import the library
import amberelectric
from amberelectric.api import amber_api
import pandas as pd
configuration = amberelectric.Configuration(access_token = 'psk_954ef8ead8c4323b4fe73064186f6362')
# Create an API instance
api = amber_api.AmberApi.create(configur... | [
"I ran your code and realized although \"today\" looks like a list of dictionaries, it's actually not, so you need to convert to dictionary first before calling pd.DataFrame().\ndata = pd.DataFrame([i.to_dict() for i in today])\n\nNow it's in tabular format\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074369958_dataframe_pandas_python.txt |
Q:
How to parse info in a specific language from a multilingual site?
I am trying to parse info from a multilingual site. I fail to grab information in English, the soup I make would always return info in Russian.
The link and my code are as follows.
'https://iherb.com/c/california-gold-nutrition'
`headers = {
"A... | How to parse info in a specific language from a multilingual site? | I am trying to parse info from a multilingual site. I fail to grab information in English, the soup I make would always return info in Russian.
The link and my code are as follows.
'https://iherb.com/c/california-gold-nutrition'
`headers = {
"Accept-Language": "en",
"user-agent": "Mozilla/5.0 (Windows NT 6.3; W... | [
"I modified your code:\nfrom selenium.webdriver.chrome.service import Service as ChromeService\n\nwith webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) as browser: # included the service here\n browser.get(url)\n menue_goer = WebDriverWait(browser, 10).until(EC.element_to_be_clickable... | [
0
] | [] | [] | [
"multilingual",
"parsing",
"python",
"selenium"
] | stackoverflow_0074220909_multilingual_parsing_python_selenium.txt |
Q:
Is it possible to have a whisper function in a discord bot?
I am trying to make a discord bot that plays uno in the server the people are in. I was thinking about how I would go about it, until I realized I didn't have a way to represent what cards each person has. I then thought how I could say it to someone with... | Is it possible to have a whisper function in a discord bot? | I am trying to make a discord bot that plays uno in the server the people are in. I was thinking about how I would go about it, until I realized I didn't have a way to represent what cards each person has. I then thought how I could say it to someone without telling it to the entire world that you had those certain car... | [
"You can send a Direct Message to the user,\n\nSuppose your players are player_a and player_b (discord.Member objects), the you can simply\nplayer_a.send(cards_a)\nplayer_b.send(cards_b)\n\n",
"You can make bot send Direct Message to inform how many cards does the user have.\nThis command will show you how to do ... | [
1,
1,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0057018762_discord.py_python.txt |
Q:
How to get a data under a specific string in a file?
I have a file named input.txt .
<hello script="2.5">
<welcome>
<hgsdhjaghjdghjagdjhgjdhgdajhgdajhgdhjjgfkjg
<number new="0x0000-0x3FF" Id="bhi" Range="4" no_id="hello" />
<----jsdjhsdjndkjjdhjdJHksdkjdnknnddnekfgrejgjorgj jreg... | How to get a data under a specific string in a file? | I have a file named input.txt .
<hello script="2.5">
<welcome>
<hgsdhjaghjdghjagdjhgjdhgdajhgdajhgdhjjgfkjg
<number new="0x0000-0x3FF" Id="bhi" Range="4" no_id="hello" />
<----jsdjhsdjndkjjdhjdJHksdkjdnknnddnekfgrejgjorgj jregjgkrjglrjgojggjorjg--->
<number new="0x02" Id="b... | [
"OK, I am going to post this, minus the gzip stuff and minus the nice extraction from the regex. It uses a basic State Machine to decide when to pay attention and when not to.\ntext=\"\"\"\n<hello script=\"2.5\">\n<welcome>\n <hgsdhjaghjdghjagdjhgjdhgdajhgdajhgdhjjgfkjg\n <number new=\"0x0000-0x3FF\" Id=\"... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074369861_python_python_3.x.txt |
Q:
How to exclude lower bound when using random.uniform?
The documentation of this function indicates it includes low, but excludes high.
import random
random.uniform(low, high)
Is there a way to exclude low as well?
It should be noted that high could possibly be very close to low.
| How to exclude lower bound when using random.uniform? | The documentation of this function indicates it includes low, but excludes high.
import random
random.uniform(low, high)
Is there a way to exclude low as well?
It should be noted that high could possibly be very close to low.
| [] | [] | [
"Is this a valid answer?\nimport random\nimport sys\n\nlow = sys.float_info.epsilon\nrandom.uniform(low, high)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074369666_python.txt |
Q:
Trying to split addresses by comma with pandas
I'm trying to split an address column in a data frame, using pandas, to add to a dictionary for geocoding.
I've done it before but not using pandas and jupyterlab. there Address column looks like
123 street, city,state,zipcode
I've created a dictionary
#create Diction... | Trying to split addresses by comma with pandas | I'm trying to split an address column in a data frame, using pandas, to add to a dictionary for geocoding.
I've done it before but not using pandas and jupyterlab. there Address column looks like
123 street, city,state,zipcode
I've created a dictionary
#create Dictionary to hold address data
meeting_address = alcoholic... | [
"I think you were very close. \nHere is my answer:\n# Sample addresses inserted into a list\nmeeting_address = ['22222 Acoma St,Proston,QLD,4613',\n '534 Schoenborn St,Hamel,WA,6215',\n '69206 Jackson Ave,Talmalmo,NSW,2640',\n '808 Glen Cove Ave,Lane Cove,NSW,15... | [
1
] | [] | [] | [
"dictionary",
"jupyter_notebook",
"pandas",
"python",
"split"
] | stackoverflow_0074369992_dictionary_jupyter_notebook_pandas_python_split.txt |
Q:
Create a row that sums the rows that do not have a data in all the columns pandas
Create a row that sums the rows that do not have a data in all the columns.
I'm working on a project that keeps throwing dataframes like this:
1
2
3
4
5
108.864
INTERCAMBIADORES DE
1123.60 210.08 166.71 1333.68
CALOR... | Create a row that sums the rows that do not have a data in all the columns pandas | Create a row that sums the rows that do not have a data in all the columns.
I'm working on a project that keeps throwing dataframes like this:
1
2
3
4
5
108.864
INTERCAMBIADORES DE
1123.60 210.08 166.71 1333.68
CALOR 8419500300
147.420 5.000
PZ
1A0181810000
81039.25 15149.52 ... | [
"Question is unclear: please provide code you've tried, the error message you're getting, and expected output.\n"
] | [
0
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074367617_data_science_dataframe_pandas_python.txt |
Q:
The Matplotlib Result is Different From WolfarmAlpha
I want to plot some equation in Matplotlib. But it has different result from Wolframalpha.
This is the equation:
y = 10yt + y^2t + 20
The plot result in wolframalpha is:
But when I want to plot it in the matplotlib with these code
# Creating vectors X and Y
x... | The Matplotlib Result is Different From WolfarmAlpha | I want to plot some equation in Matplotlib. But it has different result from Wolframalpha.
This is the equation:
y = 10yt + y^2t + 20
The plot result in wolframalpha is:
But when I want to plot it in the matplotlib with these code
# Creating vectors X and Y
x = np.linspace(-2, 2, 100)
# Assuming α is 10
y = ((10*y*x... | [
"As @Him has suggested in the comments, y = ((10*y*x)+((y**2)*x)+20) won't describe a relationship, so much as make an assignment, so the fact that y appears on both sides of the equation makes this difficult.\nIt's not trivial to express y cleanly in terms of x, but it's relatively easy to express x in terms of y,... | [
3
] | [] | [] | [
"matplotlib",
"numpy",
"plot",
"python",
"wolframalpha"
] | stackoverflow_0074369865_matplotlib_numpy_plot_python_wolframalpha.txt |
Q:
Python while loop - want to repeat or exit game with Y/N option
I made a simple Battleship game. At the end of the game, whether it ends in victory of defeat, I want the user to be able to play again or quit. This code intends to take an input, make sure it's either "y" or "n" and then set a variable controling th... | Python while loop - want to repeat or exit game with Y/N option | I made a simple Battleship game. At the end of the game, whether it ends in victory of defeat, I want the user to be able to play again or quit. This code intends to take an input, make sure it's either "y" or "n" and then set a variable controling the initial while loop to false if the input is "n". Somehow, as loop r... | [] | [] | [
"def restart_game():\n try:\n restart = input(\"Enter y to play again or n to quit: \")\n if restart == \"y\":\n return True\n if restart == \"n\":\n return False\n raise ValueError\n except ValueError:\n print (\"Please enter y or n.\")\n return... | [
-1,
-1
] | [
"python",
"while_loop"
] | stackoverflow_0025153513_python_while_loop.txt |
Q:
Can you use curses syntax with normal python functions?
I want to create a software program that has a main menu with options that are navigable with arrow keys (I have the code for this). When the user clicks on the option they want, it loads in the associated function. Can I use normal python syntax as the funct... | Can you use curses syntax with normal python functions? | I want to create a software program that has a main menu with options that are navigable with arrow keys (I have the code for this). When the user clicks on the option they want, it loads in the associated function. Can I use normal python syntax as the function and have the curses syntax call the function? How can I d... | [
"Lots of ways to do this but the statements \"can you use curses syntax\" and \"have the curses syntax call the function\" doesn't make sense? There's only Python syntax and some no-so-magic from the curses module's wrapper function that you pass main to which the wrapped calls by passing it a scr that curses handl... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074369352_python.txt |
Q:
Iterate through table rows and print column text with Python Selenium
I have a table (<table>) with values in each row (<tr>) from its body (<tbody>).
The value I would lile to print out is in the <span> inside a <div> tag.
Inspecting the html, I see the value e.g. "Name" is in row 1 (tr[1]), column 2 (td[2]):
<t... | Iterate through table rows and print column text with Python Selenium | I have a table (<table>) with values in each row (<tr>) from its body (<tbody>).
The value I would lile to print out is in the <span> inside a <div> tag.
Inspecting the html, I see the value e.g. "Name" is in row 1 (tr[1]), column 2 (td[2]):
<tr class="GAT4PNUFG GAT4PNUMG" __gwt_subrow="0" __gwt_row="0">
<... | [
"The developer has put an ID into the table. I have it working now. It is printing all the cell values from column 2. The code is:\ntable_id = self.driver.find_element(By.ID, 'data_configuration_feeds_ct_fields_body0')\nrows = table_id.find_elements(By.TAG_NAME, \"tr\") # get all of the rows in the table\nfor row i... | [
42,
20,
0
] | [] | [] | [
"html_table",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0031812537_html_table_python_selenium_selenium_webdriver.txt |
Q:
How to group and aggregate two lists in Python or Scala?
Given input lists:
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("c","p3",35)]
Expected output:
[(A,p1,20,100), (B,p2,30,"not in L2"), ("c","p3",35,"not in L1")]
I have tried using two for loops one for L1 and other for L2 but it is not workin... | How to group and aggregate two lists in Python or Scala? | Given input lists:
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("c","p3",35)]
Expected output:
[(A,p1,20,100), (B,p2,30,"not in L2"), ("c","p3",35,"not in L1")]
I have tried using two for loops one for L1 and other for L2 but it is not working for iterative elements and giving repeated output which is n... | [
"First, create a dictionary holding all possible grouping keys (\"A\",\"p1\", \"B\",\"p2\", etc.). Then, loop through keys in this dictionary to find if it exists in either of the lists.\nL1 = [(\"A\",\"p1\",20), (\"B\",\"p2\",30)]\nL2 = [(\"A\",\"p1\",100), (\"c\",\"p3\",35)]\n\n\nd = {}\nfor x, y, z in L1 + L2:\n... | [
2,
1
] | [] | [] | [
"aggregate",
"grouping",
"list",
"python",
"scala"
] | stackoverflow_0074369769_aggregate_grouping_list_python_scala.txt |
Q:
How to import a module from a sibling directory that imports modules in its directory in Python 3.9 without modifying sys.path?
My project file structure looks something like this:
hyphenated-project-root/
__init__.py
src/
__init__.py
module0.py
> from module1 import MyClass
... | How to import a module from a sibling directory that imports modules in its directory in Python 3.9 without modifying sys.path? | My project file structure looks something like this:
hyphenated-project-root/
__init__.py
src/
__init__.py
module0.py
> from module1 import MyClass
> import module2
module1.py
> class MyClass: ...
module2.py
> from module1 import My... | [
"I've had similar problems in the past and thus I've created an experimental, new import library: ultraimport\nIt gives you more control over your imports and lets you do file system based imports reliably.\nIf you want to import a file from the same or a sibling directory, your module0.py could look like this:\nim... | [
1
] | [] | [] | [
"importerror",
"modulenotfounderror",
"python",
"python_3.9",
"python_import"
] | stackoverflow_0074324158_importerror_modulenotfounderror_python_python_3.9_python_import.txt |
Q:
Pandas latest update filtered Grouped by objects breaks px.bar
i have a datafarame where i want to filter using pd.CategoricalDtype() and display the result in a bar chart using px.bar.
before the last update of pandas it was working perfectly but with the latest update it crash the chart and display the below err... | Pandas latest update filtered Grouped by objects breaks px.bar | i have a datafarame where i want to filter using pd.CategoricalDtype() and display the result in a bar chart using px.bar.
before the last update of pandas it was working perfectly but with the latest update it crash the chart and display the below error:
Traceback (most recent call last): File "", line 1, in
Fil... | [
"I think you can convert column to Categorical if need default behavior - categories are inferred from the data and Categories are unordered:\nnew_df = old_df2.groupby([pd.Categorical(old_df2.name),'id2'])['id3'].count().fillna(0)\n\nIf need CategoricalDtype pass categories by unique values of old_df2.name:\nfrom p... | [
0
] | [] | [] | [
"bar_chart",
"pandas",
"plotly",
"python"
] | stackoverflow_0074370395_bar_chart_pandas_plotly_python.txt |
Q:
Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation
I just installed the latest version of Tensorflow via pip install tensorflow and whenever I run a program, I get the log message:
W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cu... | Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation | I just installed the latest version of Tensorflow via pip install tensorflow and whenever I run a program, I get the log message:
W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
Is this bad? How do I fix the error?
| [
"Tensorflow 2.1+\nWhat's going on?\nWith the new Tensorflow 2.1 release, the default tensorflow pip package contains both CPU and GPU versions of TF. In previous TF versions, not finding the CUDA libraries would emit an error and raise an exception, while now the library dynamically searches for the correct CUDA ve... | [
139,
72,
32,
20,
16,
12,
6,
5,
4,
4,
3,
2,
2,
1,
1,
1,
0,
0
] | [
"A simpler way would be to create a link called cudart64_101.dll to point to cudart64_102.dll. This is not very orthodox but since TensorFlow is looking for cudart64_101.dll exported symbols and the nvidia folks are not amateurs, they would most likely not remove symbols from 101 to 102. It works, based on this ass... | [
-4
] | [
"keras",
"python",
"python_3.x",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0059823283_keras_python_python_3.x_tensorflow_tensorflow2.0.txt |
Q:
Which method of inserting a character into a string is more efficient and/or Pythonic?
In my current project, I encountered a scenario where I needed to insert an ampersand (&) before the first equals sign (=) that occurs in a string containing multiple equals signs. I came up with two methods for solving this pro... | Which method of inserting a character into a string is more efficient and/or Pythonic? | In my current project, I encountered a scenario where I needed to insert an ampersand (&) before the first equals sign (=) that occurs in a string containing multiple equals signs. I came up with two methods for solving this problem:
First, we have the example string:
s = "x = y = z = 5"
Method 1: Convert the string i... | [
"You have two good Pythonic choices (well, more than that but there are many ways to do string manipulation):\n\nhttps://docs.python.org/3/library/stdtypes.html#str.replace\nWhich is preferred in simple cases like yours: Use Python's string.replace vs re.sub.\nhttps://docs.python.org/3/library/re.html?highlight=re#... | [
0
] | [] | [] | [
"arrays",
"list",
"performance",
"python",
"string"
] | stackoverflow_0074368846_arrays_list_performance_python_string.txt |
Q:
What is the difference between pd.value_counts(df['length']) and df['length'].value_counts()?? which one would be better?
They both end up doing the same but which one is more efficient?
I want to know the meaning behind them
A:
You should use df['class'].value_counts().
pd.value_counts is undocumented, thus not... | What is the difference between pd.value_counts(df['length']) and df['length'].value_counts()?? which one would be better? | They both end up doing the same but which one is more efficient?
I want to know the meaning behind them
| [
"You should use df['class'].value_counts().\npd.value_counts is undocumented, thus not guaranteed to remain accessible on the long term.\nThe two calls are equally fast:\ns = pd.Series(np.random.choice(list('ABCD'), size=100000))\n\n%%timeit\npd.value_counts(s)\n# 8.59 ms ± 640 µs per loop (mean ± std. dev. of 7 ru... | [
1
] | [] | [] | [
"data_science",
"pandas",
"python"
] | stackoverflow_0074370440_data_science_pandas_python.txt |
Q:
Dropping rows from a pandas dataframe on the basis of values in two columns
I have the following dataframe 'df':
df = pd.DataFrame({'a':[0,2,3],'b':[1,3,4],'c':[4,1,2]})
Now I want to drop such rows such that that row has 0 value for column'a' and non zero value for column 'b'. How can I do that?
I tried this, df... | Dropping rows from a pandas dataframe on the basis of values in two columns | I have the following dataframe 'df':
df = pd.DataFrame({'a':[0,2,3],'b':[1,3,4],'c':[4,1,2]})
Now I want to drop such rows such that that row has 0 value for column'a' and non zero value for column 'b'. How can I do that?
I tried this, df = df[df['a'] == 0 and df['b'] != 0], but got error.
| [
"For combining conditions in pandas you need to use the bitwise & operator. e.g:\ncondtion_a = df.a == 0\ncondtion_b = df.b != 0\ncondition = condtion_a & condtion_b\ndf = df[condition]\n\n\nOr in a one liner:\ndf = df[(df.a == 0) & (df.b != 0)]\n\n\nBonus: here is a nice explanation\n",
"You're almost there. You... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074370156_dataframe_python.txt |
Q:
Seaborn multi line plot with only one line colored
I am trying to plot a multi line plot using sns but only keeping the US line in red while the other countries are in grey
This is what I have so far:
df = px.data.gapminder()
sns.lineplot(x = 'year', y = 'pop', data = df, hue = 'country', color = 'grey', dashes = ... | Seaborn multi line plot with only one line colored | I am trying to plot a multi line plot using sns but only keeping the US line in red while the other countries are in grey
This is what I have so far:
df = px.data.gapminder()
sns.lineplot(x = 'year', y = 'pop', data = df, hue = 'country', color = 'grey', dashes = False, legend = False)
But this does not change the lin... | [
"You can use pandas groupby to plot:\nfig,ax=plt.subplots()\nfor c,d in df.groupby('country'):\n color = 'red' if c=='US' else 'grey'\n d.plot(x='year',y='pop', ax=ax, color=color)\n\nax.legend().remove()\n\noutput:\n\nOr you can define a specific palette as a dictionary:\npalette = {c:'red' if c=='US' else '... | [
6,
1,
0
] | [] | [] | [
"linechart",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0062020588_linechart_matplotlib_python_seaborn.txt |
Q:
Does pandas dataframe merge work with greater or less?
Now i need to merge two dataframe with the condition greater than(>=). But merge only support equal. Is there any way to deal with it? Thanks!
A:
I don't know how to achieve the following with similar merge and join syntax in pandas,
SELECT *
FROM a
INNER ... | Does pandas dataframe merge work with greater or less? | Now i need to merge two dataframe with the condition greater than(>=). But merge only support equal. Is there any way to deal with it? Thanks!
| [
"I don't know how to achieve the following with similar merge and join syntax in pandas,\nSELECT * \nFROM a \nINNER JOIN b \nON a.column1 >= b.column1 AND a.column1 <= b.column2 \n\nBut the query above can also be written implicitly as;\nSELECT * \nFROM a, b \nWHERE a.column1 >= b.column1 AND a.column1 <= b.column2... | [
5,
0
] | [] | [] | [
"dataframe",
"merge",
"pandas",
"python"
] | stackoverflow_0043059350_dataframe_merge_pandas_python.txt |
Q:
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found."
I have installed gqcnn, Pyrep and autolab_core. After that, I executed the code that my coworker wrote and, it ran fine on his computer.
However, I cannot run the code. The occurred error was
python3.7/site-packages/cv2/qt/... | qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found." | I have installed gqcnn, Pyrep and autolab_core. After that, I executed the code that my coworker wrote and, it ran fine on his computer.
However, I cannot run the code. The occurred error was
python3.7/site-packages/cv2/qt/plugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/home/bak/anaconda3/envs/pyre... | [
"This issue occurs when you use opencv with pyqt5. It looks like qt plugin internally used by opencv is not compatible with pyqt5. Just unset environment variable QT_QPA_PLATFORM_PLUGIN_PATH after import cv2 statement.\nimport os\n\nos.environ.pop(\"QT_QPA_PLATFORM_PLUGIN_PATH\")\n\nYou could also update the platfo... | [
13,
3,
3,
1,
0,
0
] | [] | [] | [
"anaconda",
"opencv",
"python",
"qt5"
] | stackoverflow_0063829991_anaconda_opencv_python_qt5.txt |
Q:
Another one lost at ModuleNotFoundError with pytest
I've read so many posts about pytest and ModuleNotFoundError and tried all the advices I've found so far. Now I feel totally lost. So I hope someone can help me out getting the correct answer.
This is my project structure trying to follow good practice:
myproject... | Another one lost at ModuleNotFoundError with pytest | I've read so many posts about pytest and ModuleNotFoundError and tried all the advices I've found so far. Now I feel totally lost. So I hope someone can help me out getting the correct answer.
This is my project structure trying to follow good practice:
myproject/
pyproject.toml #(with [tool.pytest.ini_options] / pyt... | [
"With this layout:\nmyproject/\n├── pyproject.toml\n├── src\n│ └── myproject\n│ ├── __init__.py\n│ └── scripts\n│ └── __init__.py\n└── tests\n └── test_scripts.py\n\nAnd this pyproject.toml:\n[tool.pytest.ini_options]\npythonpath = \"src\"\n\nAnd this content in tests/test_scripts.py:\nim... | [
1,
0
] | [] | [] | [
"modulenotfounderror",
"pytest",
"python"
] | stackoverflow_0074159246_modulenotfounderror_pytest_python.txt |
Q:
Problems using spherecluster package for spherical k-mean clustering
I am working with data from an accelerometer which can be in different orientations. The data lies on the surface of a sphere. I wish to identify clusters on the surface using spherical k-means clustering.
I installed the package spherecluster fr... | Problems using spherecluster package for spherical k-mean clustering | I am working with data from an accelerometer which can be in different orientations. The data lies on the surface of a sphere. I wish to identify clusters on the surface using spherical k-means clustering.
I installed the package spherecluster from Jason Laska. I was able to install the package without any problems in ... | [
"I had the same problem and had to manually edit the spherical_kmeans.py file. I changed this:\nfrom sklearn.cluster import _k_means_fast as _k_means\n\nfor this:\nfrom sklearn.cluster import _k_means_common as _k_means\n\nand it worked for me.\n",
"I have the same problems for (pip 22.3 and scikit-learn 1.1.2) w... | [
0,
0,
0
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"unsupervised_learning"
] | stackoverflow_0072572969_machine_learning_python_scikit_learn_unsupervised_learning.txt |
Q:
Is there a way to combine the following conditions in a shorter way?
The following code works but I wonder if there's a way to combine the following conditions in a shorter way?
xlist = ['a', 'b', 'c']
xlist[:] = [x for x in xlist if ('a' not in x) & ('b' not in x)]
I tried this but it didn't work
xlist[:] = [x f... | Is there a way to combine the following conditions in a shorter way? | The following code works but I wonder if there's a way to combine the following conditions in a shorter way?
xlist = ['a', 'b', 'c']
xlist[:] = [x for x in xlist if ('a' not in x) & ('b' not in x)]
I tried this but it didn't work
xlist[:] = [x for x in xlist if ['a', 'b'] not in x]
| [
"You could try something like this:\nxlist[:] = [x for x in xlist if all(i not in x for i in ['a', 'b'])]\n\nThis makes little difference if you're only looking to exclude a list of two things - but if you had a much longer list of strings you wanted to exclude, this could be a way to do it.\n",
"if the element i... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074370146_list_python.txt |
Q:
How to add drop down menu to Swagger UI autodocs based on BaseModel using FastAPI?
I have this following class:
class Quiz(BaseModel):
question: str
subject: str
choice: str = Query(choices=('eu', 'us', 'cn', 'ru'))
I can render the form bases on this class like this
@api.post("/postdata")
d... | How to add drop down menu to Swagger UI autodocs based on BaseModel using FastAPI? | I have this following class:
class Quiz(BaseModel):
question: str
subject: str
choice: str = Query(choices=('eu', 'us', 'cn', 'ru'))
I can render the form bases on this class like this
@api.post("/postdata")
def post_data(form_data: Quiz = Depends()):
return form_data
How can I display a dro... | [
"Option 1\nUse literal values. Literal type is a new feature of the Python standard library as of Python 3.8 (prior to Python 3.8, it requires the typing-extensions package) and is supported by Pydantic. Example:\nfrom fastapi import FastAPI, Depends\nfrom pydantic import BaseModel\nfrom typing import Literal\n\nap... | [
1
] | [] | [] | [
"fastapi",
"openapi",
"python",
"swagger",
"swagger_ui"
] | stackoverflow_0074366289_fastapi_openapi_python_swagger_swagger_ui.txt |
Q:
How to get the size of tree in minimax Algorithm
I'm trying to get the size of tree of this code.
I know Size of a tree = Size of left subtree + 1 + Size of right subtree, but I do not know how to implement with this code.
I want to create a function called size after the program end I call this function to print ... | How to get the size of tree in minimax Algorithm | I'm trying to get the size of tree of this code.
I know Size of a tree = Size of left subtree + 1 + Size of right subtree, but I do not know how to implement with this code.
I want to create a function called size after the program end I call this function to print the size of tree.
# Initial values of Alpha and Beta
M... | [
"The size of the tree is the number of nodes you have visited. Before your first call to the minimax function, initialize a variable, e.g. nodes = 0. Then at the top of your minimax function you increase this with nodes += 1. When minimax is done you can do whatever you want with it, print it or use it some analysi... | [
0
] | [] | [] | [
"alpha_beta_pruning",
"minimax",
"python"
] | stackoverflow_0074321723_alpha_beta_pruning_minimax_python.txt |
Q:
Convert Tensorflow Saved Model format to Keras .h5 model format
I'm trying to use a pre-trained object detection network (TridentNet) to be able to perform object detection on the images that interest me; the model was previously saved (not by me) in the Tensorflow's SavedModel format.
The TridenNet SavedModel fol... | Convert Tensorflow Saved Model format to Keras .h5 model format | I'm trying to use a pre-trained object detection network (TridentNet) to be able to perform object detection on the images that interest me; the model was previously saved (not by me) in the Tensorflow's SavedModel format.
The TridenNet SavedModel folder I downloaded has a format like:
├── assets
├── saved_model.pb
└──... | [
"Though you can use Keras basic functions .summary() and .predict() after loading the SavedModel.\nTry with this below code to convert the saved model into h5 format:\nnew_model = tf.keras.models.load_model('Path of the saved model along with the model name')\n\n# Check its architecture\nnew_model.summary()\n\n#Sav... | [
0
] | [] | [] | [
"keras",
"object_detection",
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0074151921_keras_object_detection_python_tensorflow_tensorflow2.0.txt |
Q:
ImportError: No module named matplotlib.pyplot
I am currently practicing matplotlib. This is the first example I practice.
#!/usr/bin/python
import matplotlib.pyplot as plt
radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]
plt.plot(radius, area)
plt.show()
When I run this script with... | ImportError: No module named matplotlib.pyplot | I am currently practicing matplotlib. This is the first example I practice.
#!/usr/bin/python
import matplotlib.pyplot as plt
radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]
plt.plot(radius, area)
plt.show()
When I run this script with python ./plot_test.py, it shows plot correctly. How... | [
"pip will make your life easy!\nStep 1: Install pip - Check if you have pip already simply by writing pip in the python console. If you don't have pip, get a python script called get-pip.py , via here: https://pip.pypa.io/en/latest/installing.html or directly here: https://bootstrap.pypa.io/get-pip.py (You may have... | [
222,
63,
43,
37,
18,
16,
9,
7,
6,
4,
4,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0018176591_matplotlib_python.txt |
Q:
How to get count of keys pressed on the keyboard in an minute? ( using python )
Actually I am trying to build a monitoring system that returns the total count of keystrokes made by the keyboard in a minute. The output should be an integer that holds the value of the number of keystrokes by a person in a minute? ( ... | How to get count of keys pressed on the keyboard in an minute? ( using python ) | Actually I am trying to build a monitoring system that returns the total count of keystrokes made by the keyboard in a minute. The output should be an integer that holds the value of the number of keystrokes by a person in a minute? ( in python )
| [
"This should kinda do the trick... It's not the most efficient / precise but I believe it works.\nimport sys\nimport tty\nimport time\n\n# Disable newline buffering on stdin\ntty.setcbreak(sys.stdin.fileno())\n\nseconds = 60\n\nkeys = []\nwhile x := sys.stdin.read(1):\n now = time.time()\n keys.append((now, x... | [
2,
0,
0
] | [] | [] | [
"keyboard",
"python",
"python_3.x"
] | stackoverflow_0063121670_keyboard_python_python_3.x.txt |
Q:
groupby streak of numbers in one column of pandas dataframe
This is my dataframe:
import pandas as pd
df = pd.DataFrame(
{
'a': [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
'b': [0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0]
}
)
And this is the way that I want to ... | groupby streak of numbers in one column of pandas dataframe | This is my dataframe:
import pandas as pd
df = pd.DataFrame(
{
'a': [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
'b': [0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0]
}
)
And this is the way that I want to group it:
2 1 1
3 0 1
4 0 1
5 0 1
6 0 0
7 0 0
... | [
"Use cumsum to create a helper Series for filtering/grouping, then subfilter each group with a boolean mask:\ngroup = df['a'].cumsum()\n\nfor k, g in df[group>0].groupby(group):\n # drop rows 2 places after the first 0\n m = g['b'].ne(0).cummin().shift(2, fill_value=True)\n print(g[m])\n\nOutput:\n a b\... | [
4,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073104011_pandas_python.txt |
Q:
Python Pandas DataFrame: Add a counter based on condition for 2 cases
I want to produce two counters ("counter1", "counter2") in the following dataframe examples (cases: 1 and 2) using python functions with these characteristics:
case 1:
"counter1": it counts the number of the zeros in the column "case1-0". (cumu... | Python Pandas DataFrame: Add a counter based on condition for 2 cases | I want to produce two counters ("counter1", "counter2") in the following dataframe examples (cases: 1 and 2) using python functions with these characteristics:
case 1:
"counter1": it counts the number of the zeros in the column "case1-0". (cumulative sum of the zeros)
"counter2": it counts the ones in the column "case... | [
"For count consecutive 0 values is possible use this solution with create mask by compare by 0. Alterntive is more complicated and slowier, if larger data. It create consecutive groups by compare shifted values and count by GroupBy.cumcount similar like last column counter22 with groups created by cumulative sum if... | [
0
] | [] | [] | [
"counter",
"dataframe",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074368106_counter_dataframe_if_statement_pandas_python.txt |
Q:
EC2 Linux Instance - Running python script on instance reboot
Could someone point me what I'm doing wrong? I want both of my python scripts to run whenever EC2 instance is rebooted, I'm using AWS EC2 Linux Instance & Cloud 9
I understand thats Edit user data needs to be changed in order to achieve this, but i'm no... | EC2 Linux Instance - Running python script on instance reboot | Could someone point me what I'm doing wrong? I want both of my python scripts to run whenever EC2 instance is rebooted, I'm using AWS EC2 Linux Instance & Cloud 9
I understand thats Edit user data needs to be changed in order to achieve this, but i'm not successful, currently I have tried:
Content-Type: multipart/mixed... | [
"The easiest method is to put the scripts in:\n/var/lib/cloud/scripts/per-boot/\n\nThis assumes that cloud-init is running on the instance, which is the magic that makes User Data scripts work. It is installed by default on Ubuntu and Amazon Linux AMIs.\nFor an example of running jobs when an instance boots, see: A... | [
0
] | [] | [] | [
"amazon_ec2",
"auto",
"instance",
"linux",
"python"
] | stackoverflow_0074370707_amazon_ec2_auto_instance_linux_python.txt |
Q:
How to pass variable values dynamically in pandas sql query
How to pass variable parameters dynamically
order = 10100
status = 'Shipped'
df1 = pd.read_sql_query("SELECT * from orders where orderNumber =""" +
str(10100) + """ and status = """ + 'status' +""" order by orderNumber """,cnx)
TypeError: must be s... | How to pass variable values dynamically in pandas sql query | How to pass variable parameters dynamically
order = 10100
status = 'Shipped'
df1 = pd.read_sql_query("SELECT * from orders where orderNumber =""" +
str(10100) + """ and status = """ + 'status' +""" order by orderNumber """,cnx)
TypeError: must be str, not int
getting above error although i converted to strings a... | [
"Use parametrized sql by supplying the arguments via the params keyword argument. The proper quotation of arguments will be done for you by the database adapter and the code will be less vulnerable to SQL injection attacks. (See Little Bobby Tables for an example of the kind of trouble improperly quoted, non-parame... | [
14,
1
] | [] | [] | [
"pandas",
"python",
"sql_parametrized_query"
] | stackoverflow_0048629413_pandas_python_sql_parametrized_query.txt |
Q:
Asyncio and aiohttp put requests
I'm trying to develop some code that will hit an api with a put. I want to hit the api probably a few thousand times, however I'm not sure how to handle the errors in the following example. If I wanted to stop processing, how is this done? Is there any control over each put request... | Asyncio and aiohttp put requests | I'm trying to develop some code that will hit an api with a put. I want to hit the api probably a few thousand times, however I'm not sure how to handle the errors in the following example. If I wanted to stop processing, how is this done? Is there any control over each put request?
import aiohttp
import asynci... | [
"asyncio.gather raises the first exception encountered by any of the tasks and leave the other tasks running in the background.\nIf you want each task to run “independently”, handle exception in send_payload(). Alternatively, pass return_exceptions=True to asyncio.gather() so that it waits for all tasks to complet... | [
0
] | [] | [] | [
"aiohttp",
"python",
"python_asyncio"
] | stackoverflow_0074368779_aiohttp_python_python_asyncio.txt |
Q:
No module named '_ctypes'
I'm trying to install pyautogui, but pip keeps throwing errors. How to fix it? I've tried installing libffi library. Here is some code:
python3 -m pip install pyautogui
Defaulting to user installation because normal site-packages is not writeable
Collecting pyautogui
Using cached PyAuto... | No module named '_ctypes' | I'm trying to install pyautogui, but pip keeps throwing errors. How to fix it? I've tried installing libffi library. Here is some code:
python3 -m pip install pyautogui
Defaulting to user installation because normal site-packages is not writeable
Collecting pyautogui
Using cached PyAutoGUI-0.9.50.tar.gz (57 kB)
E... | [
"Required\nInstall foreign function interface headers\nsudo apt install libffi-dev\nReinstall Python\nSubstitute desired python version\nUbuntu\nsudo add-apt-repository ppa:deadsnakes/ppa -y && sudo apt reinstall python3.9-distutils\nMacOS\nUse brew install python3.9 or port install python3.9 (I recommend port)\nWi... | [
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0063996623_python.txt |
Q:
Assign specific value from a column to specific number of rows
I would like to assign agent_code to specific number of rows in df2.
df1
df2
Thank you.
df3 (Output)
A:
First make sure in both DataFrames is default index by DataFrame.reset_index with drop=True, then repeat agent_code, convert to default index an... | Assign specific value from a column to specific number of rows | I would like to assign agent_code to specific number of rows in df2.
df1
df2
Thank you.
df3 (Output)
| [
"First make sure in both DataFrames is default index by DataFrame.reset_index with drop=True, then repeat agent_code, convert to default index and last use concat:\ndf1 = df1.reset_index(drop=True)\ndf2 = df2.reset_index(drop=True)\n\ns = df1['agent_code'].repeat(df1['number']).reset_index(drop=True)\ndf3 = pd.conc... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074371049_dataframe_pandas_python.txt |
Q:
How to resize a 2D nparray with bilinear interpolation?
I have a (x, y) shape floating numpy array and I want to resize it to (x', y') shape with bilinear interpolation (like cv2.resize image). So any one can help me?
I try to do that:
heatmap = np.stack((heatmap,)*3, axis=-1)
heatmap = tf.keras.utils.array_to_img... | How to resize a 2D nparray with bilinear interpolation? | I have a (x, y) shape floating numpy array and I want to resize it to (x', y') shape with bilinear interpolation (like cv2.resize image). So any one can help me?
I try to do that:
heatmap = np.stack((heatmap,)*3, axis=-1)
heatmap = tf.keras.utils.array_to_img(heatmap)
heatmap = heatmap.resize((img_shape[1], img_shape[0... | [
"Oh I found out how to do this with skimage.transform.resize\nresized_heatmap = skimage.transform.resize(heatmap, (img_shape[1], img_shape[0]), order=1)\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074370055_numpy_python.txt |
Q:
Implement hmset in python with dictionary of list and nested dictionary
I was trying to implement below redis code into python django application
hmset test_template:TEMPLATE_ID test_tags "[{\"key\":\"test_manual_entry_1\",\"value\":\"Some_value_1\"},{\"key\":\"test_manual_entry_2\",\"value\":\"Some_value_2\"}]"
... | Implement hmset in python with dictionary of list and nested dictionary |
I was trying to implement below redis code into python django application
hmset test_template:TEMPLATE_ID test_tags "[{\"key\":\"test_manual_entry_1\",\"value\":\"Some_value_1\"},{\"key\":\"test_manual_entry_2\",\"value\":\"Some_value_2\"}]"
I have tried hset and hmset functions but both are giving the error. Below i... | [
"Here's Python Redis hset doc: https://redis.readthedocs.io/en/stable/commands.html?highlight=hset#redis.commands.core.CoreCommands.hset\nThe function signature is hset(name, key=None, value=None, mapping=None, items=None).\nFor method 1, You passed data as key. Besides, I presume data is a dict, which is differ fr... | [
1
] | [] | [] | [
"django",
"python",
"python_3.x",
"redis"
] | stackoverflow_0074370896_django_python_python_3.x_redis.txt |
Q:
Mac Big Sur: Unable to load numpy_formathandler accelerator from OpenGL_accelerate
I keep getting an Unable to load numpy_formathandler accelerator from OpenGL_accelerate message when using OpenGL. From what I can tell, everything seems to be running fine, but message always pops up.
Here is a sample script where ... | Mac Big Sur: Unable to load numpy_formathandler accelerator from OpenGL_accelerate | I keep getting an Unable to load numpy_formathandler accelerator from OpenGL_accelerate message when using OpenGL. From what I can tell, everything seems to be running fine, but message always pops up.
Here is a sample script where it happens. It also happens with these two lines:
from glumpy import app, gloo, gl
windo... | [
"You have to do the sequence right as OpenGL.accerate is built.\n### you can use pip\n\npip3 cache purge\npip3 uninstall PyOpenGL PyOpenGL.accelerate\npip3 install numpy # SciPy\npip3 install PyOpenGL PyOpenGL.accelerate\n\n### you should be able to use that handler now\n\n"
] | [
0
] | [] | [] | [
"glumpy",
"opengl",
"pyopengl",
"python"
] | stackoverflow_0066830626_glumpy_opengl_pyopengl_python.txt |
Q:
How to update dataframe using for loop with tesseract output of selected areas for images in a folder?
roi = [[(284, 764), (996, 840), 'text', 'name'],
[(1560, 756), (2312, 836), 'text', 'cnic'],
[(2000, 704), (2060, 748), 'box', 'corporate'],
[(2296, 696), (2360, 756), 'box', 'individual'],
... | How to update dataframe using for loop with tesseract output of selected areas for images in a folder? | roi = [[(284, 764), (996, 840), 'text', 'name'],
[(1560, 756), (2312, 836), 'text', 'cnic'],
[(2000, 704), (2060, 748), 'box', 'corporate'],
[(2296, 696), (2360, 756), 'box', 'individual'],
[(1220, 844), (2360, 920), 'text', 'email']]
Above are the selections where I run tesseract if it is t... | [
"df = pd.DataFrame()\n\nfor j, y in enumerate(myPicList):\n if 'SOF' in y:\n with open('dataOutput.csv', 'a+') as f:\n f.write(y + ',')\n img = cv.imread(sof_folder + \"/\" + y)\n pixelThreshold = 1100\n myData = []\n for x, r in enumerate(roi):\n section ... | [
1
] | [] | [] | [
"dataframe",
"loops",
"ocr",
"pandas",
"python"
] | stackoverflow_0074359664_dataframe_loops_ocr_pandas_python.txt |
Q:
How to create a data frame from two Pandas Series
I am trying to create a data frame within a while loop from two Panda Series. When I print the two series, I get the following output:
Print(a)
0 0.159175
Name: Time, dtype: float64
0 0.531096
Name: Time, dtype: float64
0 0.688536
Name: Time, dtype: float6... | How to create a data frame from two Pandas Series | I am trying to create a data frame within a while loop from two Panda Series. When I print the two series, I get the following output:
Print(a)
0 0.159175
Name: Time, dtype: float64
0 0.531096
Name: Time, dtype: float64
0 0.688536
Name: Time, dtype: float64
0 0.883937
Print (b)
0 18
Name: Inventory, dtyp... | [
"To achieve the desired result, you will need to split concatenation into two parts: concat a and b along columns (axis=1), then concat with the existing df along rows (axis=0).\ndf = pd.DataFrame()\n\nwhile s.clock <= 2.0:\n s.advance_time()\n a = pd.Series([s.clock], name = 'Time')\n b = pd.Series([s.inv... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074369955_dataframe_pandas_python.txt |
Q:
Write a program that prompts the user to enter an integer number from 1 to 9 and displays two pyramids
I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(... | Write a program that prompts the user to enter an integer number from 1 to 9 and displays two pyramids |
I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
... | [
"You just need to run the second loop after the first loop. Also your code for the second pyramid is incorrect so I changed that.\nrows = int(input(\"Enter number of rows: \"))\n\nk = 0\n\nfor i in range(1, rows+1):\n for space in range(1, (rows-i)+1):\n print(end=\" \")\n \n while k!=(2*i-1):\n ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074370228_python.txt |
Q:
How can I use OpenCV DescriptorMatcher on two arrays of points?
Is it possible to use OpenCV DescriptorMatcher to match two arrays of points instead of two Descriptors generated by feature extraction functions?
I'd like to use OpenCV for point set registration, and I've obtained the two points sets without using f... | How can I use OpenCV DescriptorMatcher on two arrays of points? | Is it possible to use OpenCV DescriptorMatcher to match two arrays of points instead of two Descriptors generated by feature extraction functions?
I'd like to use OpenCV for point set registration, and I've obtained the two points sets without using feature extraction functions.
| [
"You can get descriptors for points from an image without the feature extractors. There is a DescriptorExtractor class for this. Then you can use the appropriate matcher to find the corresondences.\nIf your points have only position information select a descriptor algorithm that works without angle and octave. E.... | [
1,
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074263285_opencv_python.txt |
Q:
Is it possible to get the current axis extents of a DataRange1d object (Bokeh)?
Is it possible to get the current axis extents of a DataRange1d objects by using a callback?
I've seen quesitons about updating the start and end using a callback, but not for getting the automatically selected extents.
Many thanks.
I ... | Is it possible to get the current axis extents of a DataRange1d object (Bokeh)? | Is it possible to get the current axis extents of a DataRange1d objects by using a callback?
I've seen quesitons about updating the start and end using a callback, but not for getting the automatically selected extents.
Many thanks.
I wish I could add more informaiton but I don't think there is anything more useful to ... | [
"It is possible to change the start and end of an DataRange1d object setting the value.\nThe example below links the x-axis to two sliders. Moving the a slider has an effect on the visible range.\nfrom bokeh.layouts import column\nfrom bokeh.models import CustomJS, Slider\nfrom bokeh.plotting import figure, show, o... | [
0
] | [] | [] | [
"bokeh",
"python"
] | stackoverflow_0074350471_bokeh_python.txt |
Q:
How to find elements in soup by Tag and specific attribute
I have an HTML file structure as below with hundred of such elements in main tag:
<main>
<div id="rows">
<p data-name="First Element">
<a target="_blank" href="localhost">
<strong>First Element</strong>
<... | How to find elements in soup by Tag and specific attribute | I have an HTML file structure as below with hundred of such elements in main tag:
<main>
<div id="rows">
<p data-name="First Element">
<a target="_blank" href="localhost">
<strong>First Element</strong>
</a>
<strong class="date-field" data-date="2016-06-27... | [
"You can get all the <p> first then for every p tag, check if the p tag has data-name attribute, and also check if any strong child of that p tag has data-date attribute, if all is true, then just extract the data:\nfrom bs4 import BeautifulSoup\n\nfile = open('index.html', 'r')\nfile_text = file.read()\n\nsoup = B... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074370592_beautifulsoup_python_web_scraping.txt |
Q:
This is about the euler 11th python
nums = [8, 2, 22, 97, 38, 15, 00, 40, 00, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8,
49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 00,
81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65,
52, 70, 95, 23,... | This is about the euler 11th python |
nums = [8, 2, 22, 97, 38, 15, 00, 40, 00, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8,
49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 00,
81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65,
52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32,... | [
"There are these issues:\n\nif n < 17+20*row(n): is a condition that does not depend on the loop, so it should not appear inside the loop. It is also a quite complex way to say that the column index should be less than 17, so why not write a function col instead of row? You can use the % operator for that.\n\nThe c... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074370964_python.txt |
Q:
How to print a number using commas as thousands separators
How do I print an integer with commas as thousands separators?
1234567 ⟶ 1,234,567
It does not need to be locale-specific to decide between periods and commas.
A:
Locale unaware
'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Pyt... | How to print a number using commas as thousands separators | How do I print an integer with commas as thousands separators?
1234567 ⟶ 1,234,567
It does not need to be locale-specific to decide between periods and commas.
| [
"Locale unaware\n'{:,}'.format(value) # For Python ≥2.7\nf'{value:,}' # For Python ≥3.6\n\nLocale aware\nimport locale\nlocale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'\n\n'{:n}'.format(value) # For Python ≥2.7\nf'{value:n}' # For Python ≥3.6\n\nReference\nP... | [
2242,
318,
311,
165,
119,
44,
40,
21,
21,
14,
12,
9,
8,
7,
6,
2,
2,
2,
1,
1,
1,
1,
1,
1,
0,
0
] | [
"Here is another variant using a generator function that works for integers:\ndef ncomma(num):\n def _helper(num):\n # assert isinstance(numstr, basestring)\n numstr = '%d' % num\n for ii, digit in enumerate(reversed(numstr)):\n if ii and ii % 3 == 0 and digit.isdigit():\n ... | [
-1,
-1,
-2,
-8
] | [
"number_formatting",
"python"
] | stackoverflow_0001823058_number_formatting_python.txt |
Q:
Combine consecutive row pairs of a dataframe based on a condition
I have collected data from a piece of software has separated the contents of a message between two messages. I am relatively new to using Pandas as a whole. Lets say I have a Pandas DataFrame in the following format:
Type
Message
A
Start
A
End
A... | Combine consecutive row pairs of a dataframe based on a condition | I have collected data from a piece of software has separated the contents of a message between two messages. I am relatively new to using Pandas as a whole. Lets say I have a Pandas DataFrame in the following format:
Type
Message
A
Start
A
End
A
Start2
A
End2
I need to combine message pairs that share... | [
"You can create consecutive groups g by compare by shifted values with pairs groups by GroupBy.cumcount with integer division by 2 and pass to final groupby:\nprint (df)\n Type Message\n0 C Start\n1 C End\n2 B Start4End4\n3 A Start\n4 A End\n5 A Start2... | [
1,
0
] | [] | [] | [
"append",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074370824_append_dataframe_pandas_python.txt |
Q:
Brightway2: LCA scores & calculations
My problem is about getting emissions results of my functional unit from a ecoinvent excel spreadsheet format.
I managed to get activities/process impacts thanks to ca.annotated_top_processes(lca) or lca.top_activities()but emissions/biosphere flows can't be displayed but thro... | Brightway2: LCA scores & calculations | My problem is about getting emissions results of my functional unit from a ecoinvent excel spreadsheet format.
I managed to get activities/process impacts thanks to ca.annotated_top_processes(lca) or lca.top_activities()but emissions/biosphere flows can't be displayed but through ca.hinton_matrix(lca, rows=10, cols=10)... | [
"This is an error as of Scipy version 1.9; for now, you can force a downgrade to Scipy 1.8.something.\nThis has been noted as an issue, but the focus for BW development is in other areas currently.\n"
] | [
0
] | [] | [] | [
"brightway",
"python"
] | stackoverflow_0074219727_brightway_python.txt |
Q:
Why does my code run in the VS terminal but not from the py file?
Beginner here. I've just learned the basics of python using VS. I don't know why I get a syntax error in the VSCode text file but not on the terminal for the command.
Any assistance helping me understand would be great, thank you.
Tried to install ... | Why does my code run in the VS terminal but not from the py file? | Beginner here. I've just learned the basics of python using VS. I don't know why I get a syntax error in the VSCode text file but not on the terminal for the command.
Any assistance helping me understand would be great, thank you.
Tried to install boto3 with pip.
| [
"You cannot run shell commands from a python script.\nThis is the right way to do it. You can also use the subprocess module to do it.\nimport os\n\n# In Linux\nos.system(\"python3 -m pip install boto3\")\n\n# In Windows\nos.system(\"py -m pip install boto3\")\n\nAlthough, it's not recommended installing packages i... | [
0,
0
] | [] | [] | [
"python",
"visual_studio",
"visual_studio_code"
] | stackoverflow_0074370616_python_visual_studio_visual_studio_code.txt |
Q:
How to automate a command input in Colab
Everytime i have to agree to the speedtest terms of Ookla by typing 'Y'.
Is there any way to automate this input. (in the same cell). Such that i won't have to type 'y' personally there
I tried finding a solution on Google. But google doesn't seem to understand my query
A:... | How to automate a command input in Colab |
Everytime i have to agree to the speedtest terms of Ookla by typing 'Y'.
Is there any way to automate this input. (in the same cell). Such that i won't have to type 'y' personally there
I tried finding a solution on Google. But google doesn't seem to understand my query
| [
"You can use the pipe | to redirect stdout to stdin.\n! echo YES | speedtest\n\n"
] | [
0
] | [] | [] | [
"google_colaboratory",
"linux",
"python",
"speed_test"
] | stackoverflow_0074371003_google_colaboratory_linux_python_speed_test.txt |
Q:
Create Dataframe with a certain number of columns
I have the following Dataframe:
Now i want to copy the column "Power" as often as i want to another column in the same Dataframe.
The column names should be: Power_1; Power_2; Power_3.....
Creating the Dataframe is too complicated to share, but a simple example ho... | Create Dataframe with a certain number of columns | I have the following Dataframe:
Now i want to copy the column "Power" as often as i want to another column in the same Dataframe.
The column names should be: Power_1; Power_2; Power_3.....
Creating the Dataframe is too complicated to share, but a simple example how to add the columns with a while-loop would be suffici... | [
"for i in range(10):\n df[f\"Power_{i}\"] = df[\"Power\"]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"python",
"while_loop"
] | stackoverflow_0074371359_dataframe_python_while_loop.txt |
Q:
Discover relationship between the entities
I have a dataset like below -
List((X,Set(" 1", " 7")), (Z,Set(" 5")), (D,Set(" 2")), (E,Set(" 8")), ("F ",Set(" 5", " 9", " 108")), (G,Set(" 2", " 11")), (A,Set(" 7", " 5")), (M,Set(108)))
Here X is related to A as 7 is common between them
Z is related to A as 5 is commo... | Discover relationship between the entities | I have a dataset like below -
List((X,Set(" 1", " 7")), (Z,Set(" 5")), (D,Set(" 2")), (E,Set(" 8")), ("F ",Set(" 5", " 9", " 108")), (G,Set(" 2", " 11")), (A,Set(" 7", " 5")), (M,Set(108)))
Here X is related to A as 7 is common between them
Z is related to A as 5 is common between them
F is related to A as 5 is common ... | [
"Build an undirected graph where each label is connected to each number from the corresponding set (i.e. (A, { 1, 2 }) would give two edges: A <-> 1 and A <-> 2)\nCompute the connected components (using depth-first search, for example).\nFilter out only the labels from the connected components.\nimport util.{Left, ... | [
1,
0
] | [
"// I put some values in quotes so we have consistent string input\nval initialData :List[(String, Set[String])] = List(\n (\"X\",Set(\" 1\", \" 7\")),\n (\"Z\",Set(\" 5\")),\n (\"D\",Set(\" 2\")),\n (\"E\",Set(\" 8\")),\n (\"F \",Set(\" 5\", \" 9\", \" 108\")),\n (\"G\",Set(\" 2\", \" 11\")),\n ... | [
-1,
-2
] | [
"algorithm",
"graph",
"python",
"scala"
] | stackoverflow_0074350748_algorithm_graph_python_scala.txt |
Q:
Synchronizing two different process starting at the same time
I have a two separate cron services both of which trigger the same python script. I want only one of the invocation to execute and the other one should exit. Is there any way we can achieve this behavior?
Create a lock file based on the process start ti... | Synchronizing two different process starting at the same time | I have a two separate cron services both of which trigger the same python script. I want only one of the invocation to execute and the other one should exit. Is there any way we can achieve this behavior?
Create a lock file based on the process start time (ignoring the seconds part from the timestamp, so that the time ... | [
"A lock file should be the correct solution, as creating a file only if it does not exist via touch is atomic:\nfrom pathlib import Path\n\ndef create_lockfile(filename):\n try:\n Path(filename).touch(exist_ok=False)\n return True\n except FileExistsError:\n return False\n\nIn the source ... | [
1
] | [] | [] | [
"cron",
"filesystems",
"python",
"synchronization",
"unix"
] | stackoverflow_0074371382_cron_filesystems_python_synchronization_unix.txt |
Q:
How to fix ImportError: cannot import name 'soft_unicode' from 'markupsafe' upon opening jupyter notebook (anaconda3)?
I used to open it just fine, writing code and all, but after I tried importing pandas_profiling, which returned
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied:... | How to fix ImportError: cannot import name 'soft_unicode' from 'markupsafe' upon opening jupyter notebook (anaconda3)? | I used to open it just fine, writing code and all, but after I tried importing pandas_profiling, which returned
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'c:\programdata\anaconda3\lib\site-packages\markupsafe-1.1.1.dist-info\direct_url.json' Consider using the --user option or... | [
"I had the same problem\nTry writting the following in the console \"Anaconda Prompt (Anaconda 3)\".\npip install markupsafe==2.0.1 --force-reinstall\n\nYou should see something like this\n\nAfter this, Jupyter Notebooks launches correctly.\n"
] | [
0
] | [] | [] | [
"anaconda",
"jupyter_notebook",
"python"
] | stackoverflow_0073060545_anaconda_jupyter_notebook_python.txt |
Q:
Combine pandas DataFrame such that NaNs are overwritten
I have two DataFrames that both have missing values (NaNs) and contain data with the other's missing values. I would like to combine them such that the missing values are filled in from the other DataFrame. Here's an example:
df1 = pd.DataFrame({'color': {1: ... | Combine pandas DataFrame such that NaNs are overwritten | I have two DataFrames that both have missing values (NaNs) and contain data with the other's missing values. I would like to combine them such that the missing values are filled in from the other DataFrame. Here's an example:
df1 = pd.DataFrame({'color': {1: 'b'}}).T
df2 = pd.DataFrame({'height': {0: 2}}).T
df12 = pd.c... | [
"df1 = pd.DataFrame({'color': {1: 'b'}}).T\ndf2 = pd.DataFrame({'height': {0: 2}}).T\ndf12 = pd.concat([df1, df2])\n\ndf3 = pd.DataFrame({'color': {0:'w'}}).T\ndf4 = pd.DataFrame({'height': {1: 4}}).T\ndf34 = pd.concat([df3, df4])\n\ndf12.combine_first(df34)\n\nOutput:\n0 1\ncolor w b\nheight 2.0 4.0\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074371477_pandas_python.txt |
Q:
Does column slice of a pandas dataframe with columns of different data types create a view or a copy?
I have some dataframes as follows:
df = pd.DataFrame([[1,2.0],[3,4.0]], index = ['row1','row2'],
columns = ['a','b'])
df2 = df.iloc[:, :]
df3 = df.iloc[:1, :]
df4 = df.iloc[:, :1]
Column a is int while c... | Does column slice of a pandas dataframe with columns of different data types create a view or a copy? | I have some dataframes as follows:
df = pd.DataFrame([[1,2.0],[3,4.0]], index = ['row1','row2'],
columns = ['a','b'])
df2 = df.iloc[:, :]
df3 = df.iloc[:1, :]
df4 = df.iloc[:, :1]
Column a is int while column b is float.
Question: are df2, df3, df4 view or copy
test 1:
print(df._is_view, df._is_copy)
print(df... | [
"You are setting values on a newly created sliced data frame. Don't do it. That's a kind of chained assignment, warned by the document.\nIn your code, the df2 and df3 are views and df4 is a copy. It cannot be determined accurately from the undocumented API _is_view and _is_copy. And 'a copy of a slice' in the warni... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074312668_dataframe_pandas_python.txt |
Q:
Assign and print at the same time in Python
In Python, is there a way to assign a result to a variable and immediately print it? In other words, I am looking for a one-line equivalent to
a = something()
print(a)
(just once, not every assignment should be automatically printed).
There are REPLs, e.g. for Scala, wh... | Assign and print at the same time in Python | In Python, is there a way to assign a result to a variable and immediately print it? In other words, I am looking for a one-line equivalent to
a = something()
print(a)
(just once, not every assignment should be automatically printed).
There are REPLs, e.g. for Scala, where this happens automatically:
scala> val count ... | [
"As of Python 3.8, the answer to this has changed.\nNow, you can assign a value to a variable and return that same value using \"assignment expressions\" (colloquially called \"the Walrus operator\").\nSo, this is valid Python:\nprint(\"Hello, {}\".format((w := \"world\"))\n\nWhich will print \"Hello, world\" and a... | [
5,
4,
4,
1,
1
] | [
"Technically you can \"print\" and assign on the same line by using sys.\nSee the following:\n>>> import sys\n>>> a = sys.stdout.write(\"hello\")\nhello\n>>> print(a)\n5\n\nAs you can see, you \"print\" - by writing to standard out which is essentially the the same as print() - the string and assign the length of t... | [
-1
] | [
"python"
] | stackoverflow_0032272927_python.txt |
Q:
Search for specific string in Python output
I am trying to query an api using requests in python. My query yields a lot of output as json format. I am looking to search for a specific string to find out if the numbers changed. the string I am looking for is "item count" and I am looking for what number displays wh... | Search for specific string in Python output | I am trying to query an api using requests in python. My query yields a lot of output as json format. I am looking to search for a specific string to find out if the numbers changed. the string I am looking for is "item count" and I am looking for what number displays when I run this. My end goal is to parse out the da... | [
"To your first question, on how to search through the json object:\nAs some of the comments have noted, without having a sample of the specific json output, its difficult to provide a specific answer.\nGenerally speaking, you could try some code like below to search through a json element for a target key, and get ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074367338_python.txt |
Q:
Scrapy Response not showing any table data
I am trying to scrape this website and I tried running scrapy shell in my cli and I can get xpath response up to //table[@class='table my-table'] this xpath but after that I cannot get any data as the response is empty array [] I don't feel the contents is hidden inside ... | Scrapy Response not showing any table data | I am trying to scrape this website and I tried running scrapy shell in my cli and I can get xpath response up to //table[@class='table my-table'] this xpath but after that I cannot get any data as the response is empty array [] I don't feel the contents is hidden inside JavaScript I have missed some techniques or is m... | [
"To search for an XPATH within an element, you need to put a dot in front of xpath expression, like below:\ntr.xpath(\".//tbody//tr[position()>2 and position()<23]\")\n\nDid not test it, but this is the correct way. Scrapy documentation: https://docs.scrapy.org/en/latest/\n",
"Just remove tbody tag then it will g... | [
1,
0
] | [] | [] | [
"python",
"scrapy",
"web_scraping",
"xpath"
] | stackoverflow_0074370252_python_scrapy_web_scraping_xpath.txt |
Q:
PySpark : java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.sql.kafka010.KafkaDataConsumer$
Am trying to fetch the messages from Kafka Topic and Print it in the console. Am able to fetch the messages through reader successfully, but when i try to print it in the console through writer, am... | PySpark : java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.sql.kafka010.KafkaDataConsumer$ | Am trying to fetch the messages from Kafka Topic and Print it in the console. Am able to fetch the messages through reader successfully, but when i try to print it in the console through writer, am getting below error,
java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.sql.kafka010.KafkaDataCo... | [
"it missing the jar commons-pool2-2.11.1.jar, try to add it\n"
] | [
0
] | [] | [] | [
"apache_kafka",
"apache_spark",
"pyspark",
"python",
"spark_streaming_kafka"
] | stackoverflow_0062362361_apache_kafka_apache_spark_pyspark_python_spark_streaming_kafka.txt |
Q:
autocompletion for own gobject derived library in python using jedi-vim using gobject introspection
I'm trying to create a shared C library that uses the gobject library as foundation. So my object inherits in GObject speak from GObject. GObject allows bindings to all different scripting languages such as Python v... | autocompletion for own gobject derived library in python using jedi-vim using gobject introspection | I'm trying to create a shared C library that uses the gobject library as foundation. So my object inherits in GObject speak from GObject. GObject allows bindings to all different scripting languages such as Python via GObject introspection. Then from python one can import the library from the gi.repository.
import gi
g... | [
"I had a similar error because of a mismatch between the python version I intended to use and the one that was called.\nMake sure jedi is using the intended version of python. E.g. add let g:jedi#force_py_version = 3 to your .vimrc\n",
"I think the problem is your vim version is too low,I suggest you update to vi... | [
0,
0,
0
] | [] | [] | [
"c",
"gobject_introspection",
"jedi",
"jedi_vim",
"python"
] | stackoverflow_0067492262_c_gobject_introspection_jedi_jedi_vim_python.txt |
Q:
Create a program that will ask the user to input the number of elements and enter the values for each element, then returns the sum of all the values
Create a program that will ask the user to input the number of elements and enter the values for each element, then returns the sum of all the values.
My initial pro... | Create a program that will ask the user to input the number of elements and enter the values for each element, then returns the sum of all the values | Create a program that will ask the user to input the number of elements and enter the values for each element, then returns the sum of all the values.
My initial program:
num_ele = 0
#Create a program that will ask the user to input the number of elements
#enter the values for each element then returns the sum of al... | [
"num_ele = 0\n\n\n#Create a program that will ask the user to input the number of elements \n#enter the values for each element then returns the sum of all the values\n\nnum_ele = int(input(\"Enter the number of elements: \"))\ntotal = 0\nfor i in range(num_ele):\n val = int( input(f\"Enter value: {int(i + 1)}\"... | [
1
] | [] | [] | [
"arrays",
"list",
"python",
"range"
] | stackoverflow_0074371506_arrays_list_python_range.txt |
Q:
Convert a .Rmd notebook that contains both R and python chunks to an .R script
I would like to convert an R Markdown notebook that contains both R and python chunks to an R script for execution on a backend server. We use a python pipeline to prepare the data. R code continues the analysis. The R markdown notebook... | Convert a .Rmd notebook that contains both R and python chunks to an .R script | I would like to convert an R Markdown notebook that contains both R and python chunks to an R script for execution on a backend server. We use a python pipeline to prepare the data. R code continues the analysis. The R markdown notebook comes from someone else and might be updated in the future. It would be nice if we ... | [
"My answer is adapted from this one. The idea is to overwrite process_tangle.block(), which is used by knitr to extract the content of code chunks. I remove the if condition at the beginning of the original answer, and I add one to wrap the line in py_run_string() if the code chunk is in Python.\nIt's probably poss... | [
1
] | [] | [] | [
"knitr",
"python",
"r",
"reticulate"
] | stackoverflow_0074365408_knitr_python_r_reticulate.txt |
Q:
CSRF validation does not work on Django using HTTPS
I am developing an application which the frontend is an AngularJS API that makes requests to the backend API developed in Django Rest Framework.
The frontend is on the domain: https://front.bluemix.net
And my backend is on the domain: https://back.bluemix.net
I... | CSRF validation does not work on Django using HTTPS | I am developing an application which the frontend is an AngularJS API that makes requests to the backend API developed in Django Rest Framework.
The frontend is on the domain: https://front.bluemix.net
And my backend is on the domain: https://back.bluemix.net
I am having problems making requests from the frontend API... | [
"Django 4.0 and above\nFor Django 4.0 and above, CSRF_TRUSTED_ORIGINS must include scheme and host, e.g.:\nCSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']\n\nDjango 3.2 and lower\nFor Django 3.2 and lower, CSRF_TRUSTED_ORIGINS must contain only the hostname, without a scheme:\nCSRF_TRUSTED_ORIGINS = ['front.bl... | [
104,
12,
11,
4,
3,
0
] | [] | [] | [
"django",
"django_csrf",
"django_rest_framework",
"ibm_cloud",
"python"
] | stackoverflow_0038841109_django_django_csrf_django_rest_framework_ibm_cloud_python.txt |
Q:
react routing and django url conflict
I am using reactjs as a frontend and django as backend. React router is used for routing. When i refresh the page that has routed by react router, i get django 404 Page Not Found error. If i refresh the homepage, i dont get any such error because the homepage is rendered by dj... | react routing and django url conflict | I am using reactjs as a frontend and django as backend. React router is used for routing. When i refresh the page that has routed by react router, i get django 404 Page Not Found error. If i refresh the homepage, i dont get any such error because the homepage is rendered by django template too using its url.
Do i have... | [
"The issue is probably that you haven't configured your URLs to handle the routes that are defined in React Router. In your Django urls.py you should be using a catch all to match all URLs to your index template\nurlpatterns += [\n # match the root\n url(r'^$', base_view),\n # match all other pages\n ur... | [
40,
28,
7,
2,
0,
0
] | [] | [] | [
"django",
"javascript",
"python",
"react_router",
"reactjs"
] | stackoverflow_0040826295_django_javascript_python_react_router_reactjs.txt |
Q:
Issue with implementing sympy into newtons method
I was trying to make a calculator for newtons method given a function, I've got everything down except that I keep running into an issue when I'm trying to do log of a different base or ln(x).
I'd appreciate the help!
import sympy as sp
x = sp.symbols('x')
# ask ... | Issue with implementing sympy into newtons method | I was trying to make a calculator for newtons method given a function, I've got everything down except that I keep running into an issue when I'm trying to do log of a different base or ln(x).
I'd appreciate the help!
import sympy as sp
x = sp.symbols('x')
# ask for expression and initial guess
expression = input('i... | [
"The output of your expression = input('input function: ') is of type string. Before creating f = sp.lambdify(...) you need to convert that expression into a symbolic expression. sympify is the command you need to use:\nexpression = sp.sympify(input('input function: '))\n\n"
] | [
1
] | [] | [] | [
"newtons_method",
"python",
"sympy"
] | stackoverflow_0074369546_newtons_method_python_sympy.txt |
Q:
Append duplicate items at the end of list whithout changing the order
I am new to python and was trying to Append duplicate items at the end of list whithout changing the order
testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]
def duplicate(alist):
p = len(alist)
duplicate = False
for i in range(0, p)... | Append duplicate items at the end of list whithout changing the order | I am new to python and was trying to Append duplicate items at the end of list whithout changing the order
testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]
def duplicate(alist):
p = len(alist)
duplicate = False
for i in range(0, p):
for j in range (i + 1, p):
if alist[i] == alist[j]:
... | [
"I think that in this case the creation of a new list is more efficient and clear in comparison with the permutations in the original list:\ntestlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]\n\ndef duplicate(alist):\n\n filtered, duplicates = [], []\n for element in alist:\n if element in filtered:\n ... | [
4,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_2.7",
"scripting"
] | stackoverflow_0039697245_python_python_2.7_scripting.txt |
Q:
Store the order of arguments given to dataclass initializer
Using the Python dataclass decorator generates signatures with arguments in a particular order:
from dataclasses import dataclass
from inspect import signature
@dataclass
class Person:
age: int
name: str = 'John'
print(signature(Person))
Gives ... | Store the order of arguments given to dataclass initializer | Using the Python dataclass decorator generates signatures with arguments in a particular order:
from dataclasses import dataclass
from inspect import signature
@dataclass
class Person:
age: int
name: str = 'John'
print(signature(Person))
Gives (age: int, name: str = 'John') -> None.
Is there a way to capture... | [
"Your question can be broken down in two parts--first, how you can get the keyword arguments in the order the caller passes them, and second, how you can modify dataclasses in a way that would allow the __init__ method of the decorated class to keep track of the said order.\nTo obtain the order of the keyword argum... | [
2,
0
] | [] | [] | [
"python",
"python_dataclasses"
] | stackoverflow_0074369007_python_python_dataclasses.txt |
Q:
Why is Jupyter Notebook creating duplicate plots when making updating plots
I'm trying to make plots in a Jupyter Notebook that update every second or so. Right now, I just have a simple code which is working:
%matplotlib inline
import time
import pylab as plt
import numpy as np
from IPython import display
for i ... | Why is Jupyter Notebook creating duplicate plots when making updating plots | I'm trying to make plots in a Jupyter Notebook that update every second or so. Right now, I just have a simple code which is working:
%matplotlib inline
import time
import pylab as plt
import numpy as np
from IPython import display
for i in range(10):
plt.close()
a = np.random.randint(100,size=100)
b = np.... | [
"The inline backend is set-up so that when each cell is finished executing, any matplotlib plot created in the cell will be displayed.\nYou are displaying your figure once using the display function, and then the figure is being displayed again automatically by the inline backend.\nThe easiest way to prevent this i... | [
13,
7,
0
] | [] | [] | [
"ipython",
"jupyter_notebook",
"matplotlib",
"python"
] | stackoverflow_0036685031_ipython_jupyter_notebook_matplotlib_python.txt |
Q:
Shopify checkout Python script shipping error
I'm trying to make a Python Shopify buy bot script with the following
JSON payload
{
'utf8': '✓',
'_method': 'patch',
'authenticity_token': '',
'previous_step': 'payment_method',
'step': '',
's': 'east-66ff824e354621d8fcedf11a05967ac6',
'che... | Shopify checkout Python script shipping error | I'm trying to make a Python Shopify buy bot script with the following
JSON payload
{
'utf8': '✓',
'_method': 'patch',
'authenticity_token': '',
'previous_step': 'payment_method',
'step': '',
's': 'east-66ff824e354621d8fcedf11a05967ac6',
'checkout[payment_gateway]': '83961729',
'checkout[... | [
"You made an assumption the price is hard coded here. It is fetched from the merchant. I figured out the the issue wss because the shipping_rate:id was incorrect.\n"
] | [
0
] | [] | [] | [
"python",
"shopify",
"shopify_api",
"shopify_app"
] | stackoverflow_0074356687_python_shopify_shopify_api_shopify_app.txt |
Q:
How to I simulate these equations. So far I have written code but this gives give me errors
Equations:
$ E_1 = \sum_{j=0}^{J-1} a_j e^{-i(j\Delta+w_o )t}$
$E_2 = e^{-iw_ot} \sum_{m=J}^{J+M} e^{-im\Delta t}(a_m+b_m e^{-iw_ot})$
code:
%matplotlib inline
import random
import numpy as np
import matplotlib.pyplot as p... | How to I simulate these equations. So far I have written code but this gives give me errors | Equations:
$ E_1 = \sum_{j=0}^{J-1} a_j e^{-i(j\Delta+w_o )t}$
$E_2 = e^{-iw_ot} \sum_{m=J}^{J+M} e^{-im\Delta t}(a_m+b_m e^{-iw_ot})$
code:
%matplotlib inline
import random
import numpy as np
import matplotlib.pyplot as plt
from numpy.fft import ifft, fftshift
tstart = -10e-9
tstop = 10e-9
delta = 31.6e6 #rep rate
... | [
"The problem is that you are using a pair of square brackets inappropriately. Look at how you wrote E2[s2]: in the middle of it you are essentially creating a list of one element, an array. Removing them fixes the problem:\nE2[s2]+= (np.exp(-i*wo*t[s2]))*np.exp(-i*(m[k2]*delta)*t[s2])*(am[k2]+bm[k2]*np.exp(-i*(wo)*... | [
0
] | [] | [] | [
"data_science",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074368090_data_science_matplotlib_pandas_python.txt |
Q:
Extracting Model and VIN from URL (second time pattern appears, but with date in addition to make)
Tried:
# model_pattern = r'\d{4}\-([^/]+)\-'
model_pattern = r'[-]([^/]+)\-'
WANT MODEL:
2021-Mercedes-Benz-Sprinter+2500
AND VIN:
286f67180a0e09a8729929613aac3877
FROM:
/used/Mercedes-Benz/2021-Mercedes-Benz-Sprin... | Extracting Model and VIN from URL (second time pattern appears, but with date in addition to make) | Tried:
# model_pattern = r'\d{4}\-([^/]+)\-'
model_pattern = r'[-]([^/]+)\-'
WANT MODEL:
2021-Mercedes-Benz-Sprinter+2500
AND VIN:
286f67180a0e09a8729929613aac3877
FROM:
/used/Mercedes-Benz/2021-Mercedes-Benz-Sprinter+2500-286f67180a0e09a8729929613aac3877.htm
Another one, this one has no "+" in it:
/used/Audi/2015-Au... | [
"You can use\n/([^/]+)-([a-f0-9]{32})\\.htm\n\nSee the regex demo.\nDetails:\n\n/ - a / char\n([^/]+) - Group 1 (model): one or more chars other than /\n- - a hyphen\n([a-f0-9]{32}) - Group 2 (VIN): 32 hex chars\n\\.htm - a .htm string.\n\nIn Pandas, you can use\nClean_Make[[\"Model\", \"VIN\"]] = Clean_Make[\"Pag... | [
0
] | [] | [] | [
"dataframe",
"jupyter",
"pandas",
"python",
"regex"
] | stackoverflow_0074368684_dataframe_jupyter_pandas_python_regex.txt |
Q:
Type hinting for object with autospec'd dependencies
I am creating tests for some controller objects that obviously have dependencies. I want to test that it's interacting correctly with the dependencies without instantiating them for obvious reasons (database connections). So I have a class like
class A:
def __... | Type hinting for object with autospec'd dependencies | I am creating tests for some controller objects that obviously have dependencies. I want to test that it's interacting correctly with the dependencies without instantiating them for obvious reasons (database connections). So I have a class like
class A:
def __init__(self, some_dependency: InterfaceB):
self.some_d... | [
"I don't know if my answer could be useful for you, and if not excuse me; surely not all your questions will have an answer from the code below. I don't have checked anything about PyCharm hints.\nI have executed the code below in my IDE PyCharm and the test is passed successfully.\nI have changed your assert becau... | [
0
] | [] | [] | [
"linter",
"mocking",
"python",
"type_hinting",
"unit_testing"
] | stackoverflow_0074366004_linter_mocking_python_type_hinting_unit_testing.txt |
Q:
[IBM][CLI Driver] SQL10013N The specified library "GSKit Error: 207" could not be loaded. SQLSTATE=42724 SQLCODE=-10013
I am trying to connect to IBM DB2 on Jupyter notebook, as in the attached images. But I'm facing an error:
[IBM][CLI Driver] SQL10013N The specified library "GSKit Error: 207" could not be load... | [IBM][CLI Driver] SQL10013N The specified library "GSKit Error: 207" could not be loaded. SQLSTATE=42724 SQLCODE=-10013 | I am trying to connect to IBM DB2 on Jupyter notebook, as in the attached images. But I'm facing an error:
[IBM][CLI Driver] SQL10013N The specified library "GSKit Error: 207" could not be loaded. SQLSTATE=42724 SQLCODE=-10013
I already installed ibm-db with pip and imported it. More information about my device:
m... | [
"Reinstalling the ibm_db and ibm_db_sa packages may help:\n!pip install --force-reinstall ibm_db ibm_db_sa\n\n",
"As per https://www.ibm.com/docs/en/spectrum-protect/8.1.9?topic=codes-global-security-kit-return, GSKit Error 207 means :\n0x000000cf 207 GSK_ERROR_FIPS_NOT_SUPPORTED This installation of GSKit do... | [
4,
0
] | [] | [] | [
"db2",
"jupyter",
"jupyter_notebook",
"python",
"python_3.x"
] | stackoverflow_0068487756_db2_jupyter_jupyter_notebook_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.