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:
Groupby to convert Pandas DataFrame to list of dictionaries
I have the following DataFrame:
print(df)
business_id software_id quantity price inventory_level
1234 abc 10 25.5 5
4820 bce 40 21.9 2
1492 ... | Groupby to convert Pandas DataFrame to list of dictionaries | I have the following DataFrame:
print(df)
business_id software_id quantity price inventory_level
1234 abc 10 25.5 5
4820 bce 40 21.9 2
1492 abc 59 25.3 1
1234 ... | [
"Can you try this:\ndfx=df.groupby(['business_id','software_id']).agg(list).T\nfinal=[]\nfor i in dfx.columns:\n final.append({'business_id':i[0], 'software_id':i[1],\n 'transactions':[{'quantity':dfx[i]['quantity'][j],'price':dfx[i]['price'][j],'inventory_level':dfx[i]['inventory_level'][j]} for... | [
0
] | [] | [] | [
"dictionary",
"group_by",
"pandas",
"python"
] | stackoverflow_0074632156_dictionary_group_by_pandas_python.txt |
Q:
FloatImage in folium map is way too big
I want to insert a legend as an image in my map with FloatImage. Last week it worked great, the image was in good quality on the bottom right. I did not change the code and the image now appears huge.
import folium
from folium.plugins import FloatImage
m = folium.Map(locat... | FloatImage in folium map is way too big | I want to insert a legend as an image in my map with FloatImage. Last week it worked great, the image was in good quality on the bottom right. I did not change the code and the image now appears huge.
import folium
from folium.plugins import FloatImage
m = folium.Map(location=[52.542100, 13.384019], zoom_start=10)
i... | [
"This is a bug that was introduced in 0.13.0. It’s fixed in the upcoming 0.14.0 release. In the meantime you can work around it by manually setting the ‘width’ argument of FloatImage.\n"
] | [
0
] | [] | [] | [
"folium",
"python"
] | stackoverflow_0074225272_folium_python.txt |
Q:
Dynamically create for loops to create lists from a dictionary
variations = {
'size':{'small':'Small',
'medium':'Medium',
'large':'Large'},
'quantity':{'20l':'20l',
'10l':'10l',
'5l':'5l'},
'color':{'red':'Red',
'blue':'Blue',
... | Dynamically create for loops to create lists from a dictionary | variations = {
'size':{'small':'Small',
'medium':'Medium',
'large':'Large'},
'quantity':{'20l':'20l',
'10l':'10l',
'5l':'5l'},
'color':{'red':'Red',
'blue':'Blue',
'green':'Green'}
}
var_list = [[i,j,k] for ... | [
"When I hear nested for loops I think the product of..\nGet the product of the values of the values of variations.\nvariations = {\n 'size':{'small':'Small',\n 'medium':'Medium', \n 'large':'Large'}, \n 'quantity':{'20l':'20l',\n '10l':'10l',\n '5l':'5l'},\n... | [
1
] | [] | [] | [
"django",
"python",
"python_3.x"
] | stackoverflow_0074631554_django_python_python_3.x.txt |
Q:
How to stop pytest_bdd from performing the teardown steps after each iteration of a Gherkin Scenario Outline?
I have the following Gherkin Scenario Outline:
Scenario: Links on main page
When I visit the main page
Then there is a link to "<site>" on the page
Examples:
|site |
|example.com ... | How to stop pytest_bdd from performing the teardown steps after each iteration of a Gherkin Scenario Outline? | I have the following Gherkin Scenario Outline:
Scenario: Links on main page
When I visit the main page
Then there is a link to "<site>" on the page
Examples:
|site |
|example.com |
|stackoverflow.com|
|nasa.gov |
and the respective test.py:
from pytest_bdd import scenario, given, ... | [
"Scenario Outlines are just a compact way of writing several individual scenarios. Cucumber and other testing frameworks work on the idea of isolating each individual test/scenario to prevent side effects from one test/scenario breaking other test/scenarios. If you try an bypass this you can end up with a very flak... | [
1
] | [] | [] | [
"cucumber",
"gherkin",
"pytest",
"pytest_bdd",
"python"
] | stackoverflow_0074629962_cucumber_gherkin_pytest_pytest_bdd_python.txt |
Q:
Why does my loop counter have an unexpected value after the loop?
I have some code like:
num_grades = 0
for num_grades in range(8):
grade = int(input("Enter grade " + str(num_grades + 1) + ": "))
# additional logic to check the grade and categorize it
print("Total number of grades:", num_grades)
# addition... | Why does my loop counter have an unexpected value after the loop? | I have some code like:
num_grades = 0
for num_grades in range(8):
grade = int(input("Enter grade " + str(num_grades + 1) + ": "))
# additional logic to check the grade and categorize it
print("Total number of grades:", num_grades)
# additional code to output more results
When I try this code, I find that the d... | [
"The last value num_grades gets assigned is 7 because of the range, the num_grades + 1 has no effect on the final value of num_grades\nYou need to either change the way num_grades changes throughout the flow of the code, or simply add a 1 to the final result.\n",
"In python the variable(s) that you use in for loo... | [
1,
1,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074633345_for_loop_python.txt |
Q:
'[Errno 13] Permission denied' from open() in python, when the file SHOULD be accessible
I've seen an error in one of our CI scripts where trying to open a file in a python script fails with the error [Errno 13] Permission denied (this is on a windows machine)
I'm wondering how it's possible, given what's going on... | '[Errno 13] Permission denied' from open() in python, when the file SHOULD be accessible | I've seen an error in one of our CI scripts where trying to open a file in a python script fails with the error [Errno 13] Permission denied (this is on a windows machine)
I'm wondering how it's possible, given what's going on:
First, we start a process in the background, which is responsible for generating this file. ... | [
"Try to run python file with sudo:\nsudo python3 python_script.py\n\nOr in Windows run console/IDE as administrator.\n"
] | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0074633400_python_windows.txt |
Q:
Getting 'KeyError: "There is no item named 'xl/sharedStrings.xml' in the archive"' when trying to open Excel
I am trying to import data into PowerBi using a Python script so that I can schedule it to refresh data at regular basis.
I am facing a challenge getting the data from an excel file and receiving the error ... | Getting 'KeyError: "There is no item named 'xl/sharedStrings.xml' in the archive"' when trying to open Excel | I am trying to import data into PowerBi using a Python script so that I can schedule it to refresh data at regular basis.
I am facing a challenge getting the data from an excel file and receiving the error 'KeyError: "There is no item named 'xl/sharedStrings.xml' in the archive"
' while importing.
When I look into the ... | [
"Solution that worked for me: Resave your file using your excel. My file also opened fine in Excel but upon zipping the file and looking inside there was no sharedStrings.xml. There seems to be a bug where saving a xlsx might not produce the sharedStrings.xml file. I found various ideas about why it might happen bu... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"powerbi",
"python"
] | stackoverflow_0072606497_dataframe_excel_pandas_powerbi_python.txt |
Q:
Python function's return type is a function?
def func(input: str) -> int: _another_func(input)
// ...
// returns some int
def _another_func(input: str) -> None
if (input == "abc"):
raise Exception
What does it mean to have the return type as a function in this case, and that function has no dependenc... | Python function's return type is a function? | def func(input: str) -> int: _another_func(input)
// ...
// returns some int
def _another_func(input: str) -> None
if (input == "abc"):
raise Exception
What does it mean to have the return type as a function in this case, and that function has no dependency on the actual return results, but instead depend... | [
"It just shows which data type should be returned in this case int.\n_another_func(input) should be in new line.\nBut if you'll try to return another data type it'll also work.\nIt's just to make maintenance/code review/life easier.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074633588_python.txt |
Q:
Django is giving me an "invalid date format" error when running tests despite specifying date format in settings
My settings file has these settings:
# settings.py
USE_L10N = False
DATE_INPUT_FORMATS = ['%m/%d/%Y']
In my test file, I'm creating an object requires a date and looks like this:
# tests.py
my_model = ... | Django is giving me an "invalid date format" error when running tests despite specifying date format in settings | My settings file has these settings:
# settings.py
USE_L10N = False
DATE_INPUT_FORMATS = ['%m/%d/%Y']
In my test file, I'm creating an object requires a date and looks like this:
# tests.py
my_model = Thing(a_date='11/22/2019').save()
When I run the test, however, the test gets stuck when it goes to create the object... | [
"You need to set DATE_INPUT_FORMATS, as DATE_FORMAT sets how Django displays the date.\nChange your code with:\nDATE_INPUT_FORMATS = ['%m/%d/%Y']\n",
"As far as I know the DATE_INPUT_FORMATS is relevant for Forms but not for Models. \nAn (invalid) ticket regarding the same problem was raised here.\n",
"Make sur... | [
1,
1,
0,
0,
0
] | [] | [] | [
"datefield",
"django",
"django_models",
"django_validation",
"python"
] | stackoverflow_0059792842_datefield_django_django_models_django_validation_python.txt |
Q:
python prime number query
number_to_check=int(input("Enter the number you want to check for prime:"))
a= 2
while number_to_check != a :
if number_to_check % a == 0:
a+=1
print("Number not prime ")
break
if number_to_check % a != 0:
a+=1
print("Number prime")... | python prime number query | number_to_check=int(input("Enter the number you want to check for prime:"))
a= 2
while number_to_check != a :
if number_to_check % a == 0:
a+=1
print("Number not prime ")
break
if number_to_check % a != 0:
a+=1
print("Number prime")
break
if number_to_che... | [
"There are better ways to do this, but this follows your philosophy:\nnumber_to_check=int(input(\"Enter the number you want to check for prime:\"))\nif number_to_check == 2:\n print(\"2 is prime\")\nelse:\n for a in range(2, number_to_check//2):\n if number_to_check % a == 0:\n print(\"Numbe... | [
0
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0074633625_primes_python.txt |
Q:
Sort coordinates of pointcloud by distance to previous point
Pointcloud of rope with desired start and end point
I have a pointcloud of a rope-like object with about 300 points. I'd like to sort the 3D coordinates of that pointcloud, so that one end of the rope has index 0 and the other end has index 300 like show... | Sort coordinates of pointcloud by distance to previous point | Pointcloud of rope with desired start and end point
I have a pointcloud of a rope-like object with about 300 points. I'd like to sort the 3D coordinates of that pointcloud, so that one end of the rope has index 0 and the other end has index 300 like shown in the image. Other pointclouds of that object might be U-shaped... | [
"First of all, obviously, there is no strict solution to this problem (and even there is no strict definition of what you want to get). So anything you may write will be a heuristic of some sort, which will be failing in some cases, especially as your point cloud gets some non-trivial form (do you allow loops in yo... | [
1,
0
] | [] | [] | [
"algorithm",
"kdtree",
"python",
"sorting"
] | stackoverflow_0074626866_algorithm_kdtree_python_sorting.txt |
Q:
How to disable SSL for a method
I have a problem. I am using easypost. The problem is that I got the following error
WARNING:urllib3.connectionpool:Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERI... | How to disable SSL for a method | I have a problem. I am using easypost. The problem is that I got the following error
WARNING:urllib3.connectionpool:Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:... | [
"There is additional context for this issue that can be found here: https://github.com/EasyPost/easypost-python/issues/222.\nEasyPost does not provide a way to disable SSL checking and has no plans to add this functionality. Some additional resources that may be helpful could be found here:\n\nhttps://stackoverflow... | [
0
] | [] | [] | [
"easypost",
"python",
"ssl",
"urllib3"
] | stackoverflow_0073358402_easypost_python_ssl_urllib3.txt |
Q:
Shift Values in column up or down for each group
I have two data frame : one with the heating starting point and one with the heating ending point and that for each room.
Heating starting point
room_id
40 2021-11-23 04:12:00
40 2021-11-23 07:16:00
40 2021-11-23 21:47:00
40 2021-11-24 05:10:00
40 2021-11-... | Shift Values in column up or down for each group | I have two data frame : one with the heating starting point and one with the heating ending point and that for each room.
Heating starting point
room_id
40 2021-11-23 04:12:00
40 2021-11-23 07:16:00
40 2021-11-23 21:47:00
40 2021-11-24 05:10:00
40 2021-11-24 08:08:00
...
78 2022-02-11 0... | [
"If df1 is your starting point dataframe and df2 ending point you can try:\n# convert and sort dataframes (if necessary) \ndf1[\"hour\"] = pd.to_datetime(df1[\"hour\"])\ndf2[\"hour\"] = pd.to_datetime(df2[\"hour\"])\n\ndf1 = df1.sort_values(by=[\"room_id\", \"hour\"])\ndf2 = df2.sort_values(by=[\"room_id\", \"hour\... | [
0
] | [] | [] | [
"group_by",
"pandas",
"python",
"shift"
] | stackoverflow_0074630702_group_by_pandas_python_shift.txt |
Q:
How to store Global variable in Django view
In Django views, is it possible to create a global / session variable and assign some value (say, sent through an Ajax call) in a view and make use of it in another view?
The scenario I'm trying to implement will be something like:
View view1 gets some variable data sent... | How to store Global variable in Django view | In Django views, is it possible to create a global / session variable and assign some value (say, sent through an Ajax call) in a view and make use of it in another view?
The scenario I'm trying to implement will be something like:
View view1 gets some variable data sent thru' Ajax call:
def view1(request):
my_glob... | [
"You can use Session Django Docs\nSome example from Django:\ndef post_comment(request, new_comment):\n if request.session.get('has_commented', False):\n return HttpResponse(\"You've already commented.\")\n c = comments.Comment(comment=new_comment)\n c.save()\n request.session['has_commented'] = T... | [
3,
0,
0
] | [] | [] | [
"django",
"django_views",
"global_variables",
"python",
"python_3.x"
] | stackoverflow_0059778199_django_django_views_global_variables_python_python_3.x.txt |
Q:
Select row in dataframe with column more than 1 values
For example I have this dataframe :
A Variant&Price Qty
AAC 7:124|25: 443 1
AAD 35:|35: 1
AAS 32:98|3:40 1
AAG 2: |25: ... | Select row in dataframe with column more than 1 values | For example I have this dataframe :
A Variant&Price Qty
AAC 7:124|25: 443 1
AAD 35:|35: 1
AAS 32:98|3:40 1
AAG 2: |25: 1
AAC 25:443|26:344 1
And I want t... | [
"str method is very useful in your case: like that we can split the type/price column into 4 parts. Then we take the minimum elements from first and third parts (the types) and if it is lower than 7, we take it in our final result.\nfrom pandas import DataFrame\n\ndf = DataFrame([['AAC', '7:124|25:443', 1],\n ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074633522_pandas_python.txt |
Q:
Auto increment starting at different offset for existing rows
I have two tables existing_students and old_students with data in them, now i want to introduce a new auto increment column say alumni_number and assign a number to all students(old and existing). First i start with old_students table say having 100 row... | Auto increment starting at different offset for existing rows | I have two tables existing_students and old_students with data in them, now i want to introduce a new auto increment column say alumni_number and assign a number to all students(old and existing). First i start with old_students table say having 100 rows
ALTER TABLE OLD_STUDENTS ADD ALUMNI_NUMBER INT UNSIGNED NOT NULL ... | [
"Demo:\nmysql> select * from mytable;\n+----------+\n| name |\n+----------+\n| Harry |\n| Ron |\n| Hermione |\n+----------+\n\nmysql> alter table mytable \n add column id int unsigned not null auto_increment, \n add key (id), \n auto_increment=101;\nQuery OK, 0 rows affected (0.02 sec)\nRecords: 0 D... | [
1
] | [] | [] | [
"database_migration",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0074633113_database_migration_mysql_python_sqlalchemy.txt |
Q:
Dealing With "0" Values in Datadog
I am currently building a set of multiple graphs for my personal company using Datadog. I love how it works but there is only one thing I have not been able to sort out. Whenever my data is generated every 5 minutes, there are times where one or multiple values will come in at '0... | Dealing With "0" Values in Datadog | I am currently building a set of multiple graphs for my personal company using Datadog. I love how it works but there is only one thing I have not been able to sort out. Whenever my data is generated every 5 minutes, there are times where one or multiple values will come in at '0' which is what I want. The problem is D... | [
"I believe you are looking for Interpolation. There are a couple of use cases you specified, you may have to experiment with a few of the options depending on what your data looks like. For example Fill Zero satisfies one of them.\nDatadog Graph Functions\n"
] | [
0
] | [] | [] | [
"datadog",
"graph",
"python"
] | stackoverflow_0074632914_datadog_graph_python.txt |
Q:
Simulating Pointers in Python
I'm trying to cross compile an in house language(ihl) to Python.
One of the ihl features is pointers and references that behave like you would expect from C or C++.
For instance you can do this:
a = [1,2]; // a has an array
b = &a; // b points to a
*b = 2; // derefernce b to... | Simulating Pointers in Python | I'm trying to cross compile an in house language(ihl) to Python.
One of the ihl features is pointers and references that behave like you would expect from C or C++.
For instance you can do this:
a = [1,2]; // a has an array
b = &a; // b points to a
*b = 2; // derefernce b to store 2 in a
print(a); // output... | [
"This can be done explicitly.\nclass ref:\n def __init__(self, obj): self.obj = obj\n def get(self): return self.obj\n def set(self, obj): self.obj = obj\n\na = ref([1, 2])\nb = a\nprint(a.get()) # => [1, 2]\nprint(b.get()) # => [1, 2]\n\nb.set(2)\nprint(a.get()) # => 2\nprint(b.get()) # => 2\n... | [
85,
24,
14,
10,
4,
4,
1,
0,
0,
0
] | [
"Negative, no pointers. You should not need them with the way the language is designed. However, I heard a nasty rumor that you could use the: ctypes module to use them. I haven't used it, but it smells messy to me.\n"
] | [
-2
] | [
"pointers",
"python"
] | stackoverflow_0001145722_pointers_python.txt |
Q:
python JSON format invalid
I'm trying to get date and time flowing into Azure IoT hub to enable me to analyze using Azure DX as time series. I can get the temperature and humidity (humidity at the moment is just a random number). If I use this code, all works well and the JSON is well formatted and flows into IoT ... | python JSON format invalid | I'm trying to get date and time flowing into Azure IoT hub to enable me to analyze using Azure DX as time series. I can get the temperature and humidity (humidity at the moment is just a random number). If I use this code, all works well and the JSON is well formatted and flows into IoT hub and onto Azure DX:
The basis... | [
"@JoeHo, thank you for pointing the sources that helped you resolve the issue. I am posting the solution here so that other community members facing similar issue would benefit. Making the below modifications to the code helped me resolve the issue.\ndef json_serial(obj):\n if isinstance(obj, (datetime, date)):\... | [
0
] | [] | [] | [
"azure",
"azure_iot_hub",
"datetime",
"python"
] | stackoverflow_0074362745_azure_azure_iot_hub_datetime_python.txt |
Q:
Check to see if text is contained within a variable in a list in Python
I am working with this code:
test_list = ['small_cat', 'big_dog', 'turtle']
if 'dog' not in test_list:
output = 'Good'
else:
output = 'Bad'
print (Output)
Because 'dog' is not in the list, 'output' will come back with a response of... | Check to see if text is contained within a variable in a list in Python | I am working with this code:
test_list = ['small_cat', 'big_dog', 'turtle']
if 'dog' not in test_list:
output = 'Good'
else:
output = 'Bad'
print (Output)
Because 'dog' is not in the list, 'output' will come back with a response of 'Good'. However, I am looking for 'output' to return 'Bad' because the word... | [
"You should iterate all the values in test_list -\noutput = 'Good'\nfor test_word in test_list:\n if 'dog' in test_word:\n output = 'Bad'\n break\n\nprint(output)\n\n",
"you need to check each one in the list:\noutput = 'Good'\nfor item in test_list:\n if 'dog' in item:\n output = 'Bad'... | [
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074633742_list_python.txt |
Q:
How to rename duplicated column names in a pandas dataframe
Quite shortly: I have this DataFrame
Dataframe
In the dataframe I have some duplicated columns with different values. How can I fix it so these have different column-names?
df_temporary.rename(columns={df_temporary.columns[3]: "OeFG%"}, inplace=True)
df_t... | How to rename duplicated column names in a pandas dataframe | Quite shortly: I have this DataFrame
Dataframe
In the dataframe I have some duplicated columns with different values. How can I fix it so these have different column-names?
df_temporary.rename(columns={df_temporary.columns[3]: "OeFG%"}, inplace=True)
df_temporary.rename(columns={df_temporary.columns[11]:"DeFG%"}, inpla... | [
"Welcome to Stackoverflow :)\nGreat that you showed us a code sample of what you tried, and that you even linked to a stackoverflow post showing that you researched this problem!\nIn the future, try to avoid posting screenshots of tables and paste them in as text so that reviewers/helpers can easily copy your stuff... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074633391_dataframe_pandas_python.txt |
Q:
How to calculate pairwise co-occurrence matrix based on dataframe?
I have a dataframe, about 800,000 rows and 16 columns, below is an example from the data,
import pandas as pd
import datetime
start = datetime.datetime.now()
print('Starting time,'+str(start))
dict1 = {'id':['person1','person2','person3','person4'... | How to calculate pairwise co-occurrence matrix based on dataframe? | I have a dataframe, about 800,000 rows and 16 columns, below is an example from the data,
import pandas as pd
import datetime
start = datetime.datetime.now()
print('Starting time,'+str(start))
dict1 = {'id':['person1','person2','person3','person4','person5'], \
'food1':['A','A','A','C','D' ], \
'food... | [
"If I understand your goal correctly you can use this:\nuniques = demo[[x for x in demo.columns if 'id' not in x]].stack().unique()\npd.DataFrame(index = uniques, columns = uniques).fillna(np.NaN)\n\n",
"You could try this:\nout = pd.get_dummies(data=demo.iloc[:,1:].stack()).sum(level=0).ne(0).astype(int)\nfinal ... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074630972_dataframe_pandas_python.txt |
Q:
how do I plot an array in python?
I have an array a with shape (43,9). I want to plot all rows of this array in one diagram. for this I used the following code:
plt.plot(a)
it produces this diagram but I think it is wrong:
I put part of a here:
30.2682 30.4287 30.4531 30.4675 30.4784 30.4893 30.5002 30.511 30.5... | how do I plot an array in python? | I have an array a with shape (43,9). I want to plot all rows of this array in one diagram. for this I used the following code:
plt.plot(a)
it produces this diagram but I think it is wrong:
I put part of a here:
30.2682 30.4287 30.4531 30.4675 30.4784 30.4893 30.5002 30.511 30.5219
28.3204 29.4246 30.5289 31.5486 31.... | [
"Try this:\ndata = []\nfor arr in a:\n data.extend(arr)\n\nplt.plot(list(range(len(data))), data)\n\nIt will combine all arrays from a into data array\n",
"From what I understand, you want to reshape the array such that each dataset is plotted into one line. If this is the correct interpretation, all you need ... | [
0,
0,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0074632184_matplotlib_plot_python.txt |
Q:
Python networkx, plotly. How to display Edges mouse-over text
I need to display text when mouse is over edges (similar to image).
Maybe someone knows how to do it?
I took the example from plotly.com and trying to modify it.
It fine works for Nodes, but I can not do it for Edges.
import networkx
import plotly.grap... | Python networkx, plotly. How to display Edges mouse-over text | I need to display text when mouse is over edges (similar to image).
Maybe someone knows how to do it?
I took the example from plotly.com and trying to modify it.
It fine works for Nodes, but I can not do it for Edges.
import networkx
import plotly.graph_objects as go
G = networkx.random_geometric_graph(n=3, radius=1)... | [
"Plotly doesn't actually have any functionality that will account for hover content over the length of a line. However, you can use a workaround.\nYou could plot transparent points at the midpoint of each edge. Alternatively, you could plot any number of transparent points on each edge.\nJust the midpoint\nWhen you... | [
1,
0
] | [] | [] | [
"edges",
"mouseover",
"networkx",
"plotly",
"python"
] | stackoverflow_0074607000_edges_mouseover_networkx_plotly_python.txt |
Q:
Numpy matmul requires way more memory than is necessary when inputs are of different types
I have a very large boolean 2d array (~1Gb) and I want to matmul it with a 1d array of float64. The output array would be large, but still considerably smaller than the 2d array. However, when I try to matmul them, my syste... | Numpy matmul requires way more memory than is necessary when inputs are of different types | I have a very large boolean 2d array (~1Gb) and I want to matmul it with a 1d array of float64. The output array would be large, but still considerably smaller than the 2d array. However, when I try to matmul them, my system freaks out and tries to allocate enough memory for the 2d array to have float64, rather than j... | [
"Numpy does not internally supports operations on different types so it uses type promotion to convert the inputs so they can be of the same type first (the conversion is done out-of-place). Indeed, when Numpy executes np.dot(a, v), it first converts a of type np.bool_[:,:] to an array of type np.float64[:,:]. This... | [
1
] | [] | [] | [
"dot_product",
"matrix_multiplication",
"memory",
"numpy",
"python"
] | stackoverflow_0074625873_dot_product_matrix_multiplication_memory_numpy_python.txt |
Q:
topleft from surface rect dont accept new tuple value
I create pygame screen.
import pygame
pygame.init()
screen = pygame.display.set_mode((330, 330))
Then i create an object of my own class and give him a tuple.
mc = MyClass((10, 10))
This class has a problem. topleft from surface don`t accept new tuple value.... | topleft from surface rect dont accept new tuple value | I create pygame screen.
import pygame
pygame.init()
screen = pygame.display.set_mode((330, 330))
Then i create an object of my own class and give him a tuple.
mc = MyClass((10, 10))
This class has a problem. topleft from surface don`t accept new tuple value.
class MyClass:
def __init__(self, pos):
self.s... | [
"A Surface has no position and the rectangle is not an attribute of the Surface. The get_rect() method creates a new rectangle object with the top left position (0, 0) each time the method is called. The instruction\n\nself.surface.get_rect().topleft = pos\n\n\nonly changes the position of an object instance that i... | [
0
] | [] | [] | [
"pygame",
"python",
"tuples"
] | stackoverflow_0074633853_pygame_python_tuples.txt |
Q:
How to store and pass a filename to as a variable in python
I have the beginnings of some python that will take columns out of a specific csv file and then rename the csv columns something else. The issue that I have is the CSV file will always be in the same directory this script is ran in, but the name won't alw... | How to store and pass a filename to as a variable in python | I have the beginnings of some python that will take columns out of a specific csv file and then rename the csv columns something else. The issue that I have is the CSV file will always be in the same directory this script is ran in, but the name won't always be the same (and there will only ever be one csv in the direc... | [
"You can use glob.glob to return a list of the files matching a pattern (e.g *.csv) and then slice.\nTry this :\nfrom glob import glob\nimport pandas as pd\n\ncsv_file = glob(\"*.csv\")[0]\n\ndf= pd.read_csv(csv_file)\n\n",
"You can get list of all files in directory(in this case csv files) using os.listdir():\ni... | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074633907_csv_python.txt |
Q:
How to print multiple patterns next to each other?
My forest pattern
I did print the forest pattern here but i have to print them next to each other instead of printing them in new lines. How can i do that? When i try to add end="" to last print section, it seems like only the first "*" is printing and the shape i... | How to print multiple patterns next to each other? | My forest pattern
I did print the forest pattern here but i have to print them next to each other instead of printing them in new lines. How can i do that? When i try to add end="" to last print section, it seems like only the first "*" is printing and the shape is ruined.
for x in range(5):
sayi = int(input("[5-13... | [
"Do you mean something like this\nsayi = int(input(\"[5-13] Aralığında tek tam sayı giriniz:\"))\nfor i in range(1, sayi + 1):\n green = \"* \" * i\n print('\\033[92m' + green.center(sayi * 2 + 2) * 5 + '\\033[0m')\nfor j in range(sayi // 2):\n trunk = \"* *\"\n print(trunk.center(sayi * 2 + 2) * 5)\n\n... | [
-1
] | [] | [] | [
"newline",
"python",
"tree"
] | stackoverflow_0074632286_newline_python_tree.txt |
Q:
I don't know why it's an empty list? max()
# Plot the highest score in history
def draw_best(background):
ip = 'redis-16784.c89.us-east-1-3.ec2.cloud.redislabs.com'
r = redis.Redis(host=ip, password=1206, port=16784, db=0, decode_responses = True)
scores = [eval(i) for i in list(r.hgetall('2048').value... | I don't know why it's an empty list? max() | # Plot the highest score in history
def draw_best(background):
ip = 'redis-16784.c89.us-east-1-3.ec2.cloud.redislabs.com'
r = redis.Redis(host=ip, password=1206, port=16784, db=0, decode_responses = True)
scores = [eval(i) for i in list(r.hgetall('2048').values())]
best_scores = max(scores)
scoreSur... | [
"Obviously, it seems like list(r.hgetall('2048').values()) is a blank sequence/list/array.\nCheck if it is really empty by defining a variable with the value list(r.hgetall('2048').values()) and then print it out to check.\nThere is a default keyword that may be helpful. It will return a value if the list is empty.... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074633901_python.txt |
Q:
'str' object has no attribute 'isin' error while using period_range in Python
I am trying to format a date column that I am reading from a csv file but I am getting Out of bounds nanosecond timestamp: 2999-12-31 00:00:00 error while formatting the high date. To solve this, I tried to use period_range as given belo... | 'str' object has no attribute 'isin' error while using period_range in Python | I am trying to format a date column that I am reading from a csv file but I am getting Out of bounds nanosecond timestamp: 2999-12-31 00:00:00 error while formatting the high date. To solve this, I tried to use period_range as given below:
low_date = '1900-01-01 00:00:00'
high_date = '2999-12-31 00:00:00'
r = pd.pe... | [
"The Error\nIn your code...\n low_date = '1900-01-01 00:00:00' \n high_date = '2999-12-31 00:00:00'\n r = pd.period_range(low_date,high_date)\n for i in range(len(Df[date])): \n if Df[date][i].isin(r):\n Df[date] = pd.to_datetime(Df[date]).dt.strftime(\"%m/%d/%Y %H:%M:%S.0\")\n\nyour conditional fails be... | [
0
] | [] | [] | [
"dataframe",
"datetime_format",
"pandas",
"python"
] | stackoverflow_0074632971_dataframe_datetime_format_pandas_python.txt |
Q:
Pyspark cannot export large dataframe to csv. Session setup incorrect?
My session in pyspark 2.3:
spark = SparkSession\
.builder\
.appName("test_app")\
.config('spark.executor.instances','4')\
.config('spark.executor.cores', '4')\
.config('spark.executor.memory', '24g')\
.config('spark.driv... | Pyspark cannot export large dataframe to csv. Session setup incorrect? | My session in pyspark 2.3:
spark = SparkSession\
.builder\
.appName("test_app")\
.config('spark.executor.instances','4')\
.config('spark.executor.cores', '4')\
.config('spark.executor.memory', '24g')\
.config('spark.driver.maxResultSize', '24g')\
.config('spark.rpc.message.maxSize', '512')\
... | [
"I'm not experienced with pyspark, but maybe this SO post can help you in some way. Have you started up your pyspark environment before running this code? The error AttributeError: 'NoneType' object has no attribute '_jvm' seems to hint at something wrong in the setup.\nAlso, unless you have very specific (and stro... | [
0
] | [] | [] | [
"apache_spark",
"hadoop",
"pyspark",
"python"
] | stackoverflow_0074630633_apache_spark_hadoop_pyspark_python.txt |
Q:
Issues compiling mediapipe with pyinstaller on macos
I have issues compiling a project with mediapipe via pyinstaller on macos
so far I tried:
pyinstaller --windowed --noconsole pose_edge.py
pyinstaller --onefile --windowed --noconsole pose_edge.py
pyinstaller --noconsole pose_edge.py
The .app does not open, ... | Issues compiling mediapipe with pyinstaller on macos | I have issues compiling a project with mediapipe via pyinstaller on macos
so far I tried:
pyinstaller --windowed --noconsole pose_edge.py
pyinstaller --onefile --windowed --noconsole pose_edge.py
pyinstaller --noconsole pose_edge.py
The .app does not open, and if I try the unix exec, I get
Traceback (most recent... | [
"I ran into this issue too and just figured it out a few minutes ago -- so far, I'm getting around it the manual way, but I'm sure there's an idiomatic way to do it in pyinstaller using the spec file and the data imports. For this answer, I'm assuming you're not using the --onefile option for pyinstaller, but rathe... | [
3,
0
] | [] | [] | [
"build",
"mediapipe",
"pyinstaller",
"python"
] | stackoverflow_0067887088_build_mediapipe_pyinstaller_python.txt |
Q:
Python AttributeError when importing module resolves after calling 'help()'
I'm getting started with packaging a Python library, and I'm experiencing odd behavior when trying to import a function. I built a wheel for this library and installed in my conda environment using pip. The structure of my library is:
|- s... | Python AttributeError when importing module resolves after calling 'help()' | I'm getting started with packaging a Python library, and I'm experiencing odd behavior when trying to import a function. I built a wheel for this library and installed in my conda environment using pip. The structure of my library is:
|- setup.py
|- test_package
|- __init__.py
|- module1.py
|- myutils.py
T... | [
"While some packages do automatically import their subpackages (usually for historical reasons, e.g. import os provides os.path to this day because it originally did so, and they don't want to break programs that rely on it), the recommendation is, and has been, to import the subpackages/submodules you rely on, not... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074633905_python.txt |
Q:
How do I make this Python program interactive?
I am trying to modify the example found here (https://towardsdatascience.com/intro-to-dynamic-visualization-with-python-animations-and-interactive-plots-f72a7fb69245) to run outside of a Jupyter notebook.
The program below produces a *.gif that is animated but not int... | How do I make this Python program interactive? | I am trying to modify the example found here (https://towardsdatascience.com/intro-to-dynamic-visualization-with-python-animations-and-interactive-plots-f72a7fb69245) to run outside of a Jupyter notebook.
The program below produces a *.gif that is animated but not interactive. Can anyone find the error?
#Based on the e... | [
"@Wayne pointed out that I need to add an additional package so that the slider bars are interactive. Here is a useful resource\nhttps://towardsdatascience.com/4-python-packages-to-create-interactive-dashboards-d50861d1117e\n"
] | [
0
] | [] | [] | [
"interactive",
"python"
] | stackoverflow_0074633978_interactive_python.txt |
Q:
Pandas: count number of times between specific range
I have a dataset of part numbers, and for each of those part numbers, they were replaced at a certain cycle count. For example, in the below table is an example of my data, first column being the part number, and the second being the cycle count it was replaced ... | Pandas: count number of times between specific range | I have a dataset of part numbers, and for each of those part numbers, they were replaced at a certain cycle count. For example, in the below table is an example of my data, first column being the part number, and the second being the cycle count it was replaced (ie: part abc was replaced at 100 cycles, and then again a... | [
"We can use np.arange to create some Cycle Count Range bins and pd.cut to assign the values of Cycle Count to said bins.\nfrom io import StringIO\nimport numpy as np\nimport pandas as pd\n\n\ndf = pd.read_csv(StringIO(\"\"\"Part # Cycle Count\nabc 100\nabc 594\nabc 1230\nabc 2291\ndef 329\ndef 2001\nghi 1671\njkl 2... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"sql"
] | stackoverflow_0074633352_dataframe_pandas_python_sql.txt |
Q:
How to safe a column from diagonal element to the bottom
I'm trying to get the L and U--matrices from the following Gauss-elimination code I wrote
matrix = np.array ([[2,1,4,1], [3,4,-1,-1] , [1,-4,1,5] , [2,-2,1,3]], dtype = float)
vector = np.array([-4, 3, 9, 7], float)
length = len(vector)
L_matrix = np.zeros((... | How to safe a column from diagonal element to the bottom | I'm trying to get the L and U--matrices from the following Gauss-elimination code I wrote
matrix = np.array ([[2,1,4,1], [3,4,-1,-1] , [1,-4,1,5] , [2,-2,1,3]], dtype = float)
vector = np.array([-4, 3, 9, 7], float)
length = len(vector)
L_matrix = np.zeros((4,4), float)
U_matrix = np.zeros((4,4), float)
for m in range... | [
"The issue here is that the provided code does not perform the elimination. Try this:\nfor m in range(length):\n div = matrix[m, m]\n L_matrix[:, m] = matrix[:, m] / div\n U_matrix[m, :] = matrix[m, :]\n matrix -= np.outer(L_matrix[:, m], U_matrix[m, :])\n\nSee this article for more details. For actuall... | [
1
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0074633974_matrix_numpy_python.txt |
Q:
How to use an input file with netcat in a subprocess
I would like to use netcat in subprocess and send some text when nc client connect it.
The command in bash nc -nlvp 8080 < /home/welcome.txt works perfectly when my chat client is connected with the command nc 127.0.0.1 1234. The client receive the welcome messa... | How to use an input file with netcat in a subprocess | I would like to use netcat in subprocess and send some text when nc client connect it.
The command in bash nc -nlvp 8080 < /home/welcome.txt works perfectly when my chat client is connected with the command nc 127.0.0.1 1234. The client receive the welcome message and I can respond, the listener print the client messag... | [
"Because you use stdout=subprocess.PIPE and stderr=subprocess.PIPE, when nc tries to print it gets stuck waiting for Python code to read from those pipes, and none of your code ever does.\nJust take them out. To make things even smoother, you can stop running a shell altogether; and, to wait for nc to finish before... | [
0
] | [] | [] | [
"netcat",
"python",
"stdin",
"stdout",
"subprocess"
] | stackoverflow_0074621232_netcat_python_stdin_stdout_subprocess.txt |
Q:
Dynamically using INSERT for cx_Oracle - Python
I've been looking around so hopefully someone here can assist:
I'm attempting to use cx_Oracle in python to interface with a database; my task is to insert data from an excel file to an empty (but existing) table.
I have the excel file with almost all of the same col... | Dynamically using INSERT for cx_Oracle - Python | I've been looking around so hopefully someone here can assist:
I'm attempting to use cx_Oracle in python to interface with a database; my task is to insert data from an excel file to an empty (but existing) table.
I have the excel file with almost all of the same column names as the columns in the database's table, so ... | [
"Look at https://github.com/oracle/python-oracledb/blob/main/samples/load_csv.py\nYou would replace the CSV reading bit with parsing your data frame. You need to construct a SQL statement similar to the one used in that example:\nsql = \"insert into LoadCsvTab (id, name) values (:1, :2)\"\n\nFor each spreadsheet c... | [
0
] | [] | [] | [
"cx_oracle",
"excel",
"pandas",
"python",
"sql"
] | stackoverflow_0074621928_cx_oracle_excel_pandas_python_sql.txt |
Q:
Comma separated number after specific substring in middle of string
I need to extract a sequence of coma separated numbers after specific substring. When the substring is in the beginning of the string it works fine, but not when its in the middle.
The regex 'Port':\ .([0-9]+) works fine with the example below to ... | Comma separated number after specific substring in middle of string | I need to extract a sequence of coma separated numbers after specific substring. When the substring is in the beginning of the string it works fine, but not when its in the middle.
The regex 'Port':\ .([0-9]+) works fine with the example below to get the value 2.
String example:
{'Port': '2', 'Array': '[0, 0]', 'Field'... | [
"I found the regex to be like this, not sure if thats what you want:\nimport re\n\nstring = \"{'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'}\"\n\noutput = re.findall(r\"\\'Field\\'\\: \\'\\[([0-9]+)\\,([0-9]+)\\]\\'\",string)\n\nprint(output)\n\noutput:\n[('2', '2')]\n\nif you... | [
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074632019_python_regex.txt |
Q:
TypeError: 'str' object is not callable, how do i fix this?
I'm under the impression this means my variables are messed up but I can't figure out which one it's upset with nor why.
It looks like it happens after it reads my command for k1. I don't know what to do to make it work, I've been trying for a while to fi... | TypeError: 'str' object is not callable, how do i fix this? | I'm under the impression this means my variables are messed up but I can't figure out which one it's upset with nor why.
It looks like it happens after it reads my command for k1. I don't know what to do to make it work, I've been trying for a while to find where the issue may be to no avail. I'm extremely new to codin... | [
"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\n#defining functions\nH0=7 #initial height, meters\ndef f2a(t,H,k,Vin,D):\n Vin=150 #m^3/min\n D=7 #diameter, m**2\n k=10\n dhdt=4/(math.pi*D**2)*(Vin-k*np.sqrt(H))\n return(dhdt)\n\nx0=1 #initial cond.\ny0=1\ndef fb2(J,t):\n x=... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074634143_python.txt |
Q:
How do I send myself an email using Python?
I know this has been answered before, but recently gmail updated the "Less secure apps" ToS or something. So with this update, is there a way to do this? (Sorry for short explanation + old duplicates)
Tried this tutorial and when trying to connect to my google acc, less ... | How do I send myself an email using Python? | I know this has been answered before, but recently gmail updated the "Less secure apps" ToS or something. So with this update, is there a way to do this? (Sorry for short explanation + old duplicates)
Tried this tutorial and when trying to connect to my google acc, less secure apps option disabled
UPDATE: I'll be using... | [
"You can or should be able to use the same code that you are using now. The easest solution would be to enable 2fa on your google account and create an apps password. Quick fix for SMTP username and password not accepted error\nOnce you have created the apps password you can use that in place of your standard gma... | [
1
] | [] | [] | [
"gmail",
"python",
"smtp"
] | stackoverflow_0074634185_gmail_python_smtp.txt |
Q:
How to automatically start a python http server
I am using python http.server 80 to expose my downloaded files to my twilio whatsapp bot
is there a way that as my django-twillio app starts it automatically runs the server on port 80 as well
python -m http.server 80
A:
Adding this code to your django-twilio app w... | How to automatically start a python http server | I am using python http.server 80 to expose my downloaded files to my twilio whatsapp bot
is there a way that as my django-twillio app starts it automatically runs the server on port 80 as well
python -m http.server 80
| [
"Adding this code to your django-twilio app will programmatically start your server on localhost:80\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\n\nhttpd = HTTPServer(('localhost', 80), SimpleHTTPRequestHandler)\nhttpd.serve_forever()\n\n"
] | [
1
] | [] | [] | [
"django",
"httpserver",
"python",
"selenium",
"twilio_api"
] | stackoverflow_0074631869_django_httpserver_python_selenium_twilio_api.txt |
Q:
converting dict of list of lists to dict of dicts with pandas dataframe
trying to convert pandas dataframe column from a to b as below -
import pandas as pd
a = {'01AB': [["ABC",5],["XYZ",4],["LMN",1]],
'02AB_QTY': [["Other",20],["not_Other",150],["another",15]]}
b = {'01AB': {"ABC":5,"XYZ":4,"LMN":1},
... | converting dict of list of lists to dict of dicts with pandas dataframe | trying to convert pandas dataframe column from a to b as below -
import pandas as pd
a = {'01AB': [["ABC",5],["XYZ",4],["LMN",1]],
'02AB_QTY': [["Other",20],["not_Other",150],["another",15]]}
b = {'01AB': {"ABC":5,"XYZ":4,"LMN":1},
'02AB_QTY': {"Other":20,"not_Other":150,"another":150}}
df = pd.DataFrame(a... | [
"for key, list_item in a.items():\n a[key] = {v[0]:v[1] for v in list_item}\n\nOR\nb = {}\nfor key, list_item in a.items():\n b[key] = {v[0]:v[1] for v in list_item}\n\nOR\nb = {key: {v[0]:v[1] for v in list_item} for key, list_item in a.items()}\n\n",
"To example be more clear, the following code using loo... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074634070_pandas_python.txt |
Q:
Detecting a repeated sequence with regex
I have a text example like
0s11 0s12 0s33 my name is 0sgfh 0s1 0s22 0s87
I want to detect the consecutive sequences that start 0s.
So, the expected output should be 0s11 0s12 0s33, 0sgfh 0s1 0s22 0s87
I tried using regex
(0s\w+)
but that would detect each 0s11, 0s12, 0s3... | Detecting a repeated sequence with regex | I have a text example like
0s11 0s12 0s33 my name is 0sgfh 0s1 0s22 0s87
I want to detect the consecutive sequences that start 0s.
So, the expected output should be 0s11 0s12 0s33, 0sgfh 0s1 0s22 0s87
I tried using regex
(0s\w+)
but that would detect each 0s11, 0s12, 0s33, etc. individually.
Any idea on how to modi... | [
"To get those 2 matches where there are at least 2 consecutive parts:\n\\b0s\\w+(?:\\s+0s\\w+)+\n\nExplanation\n\n\\b A word boundary to prevent a partial word match\n0s\\w+ Match os and 1+ word chars\n(?:\\s+0s\\w+)+ Repeat 1 or more times whitespace chars followed by 0s and 1+ word chars\n\nRegex demo\nIf you al... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074631480_python_regex.txt |
Q:
How do I use a file like a memory buffer in Python?
I don't know the correct terminology, maybe it's called page file, but I'm not sure. I need a way to use an on-disk file as a buffer, like bytearray. It should be able to do things like a = buffer[100:200] and buffer[33] = 127 without the code having to be aware ... | How do I use a file like a memory buffer in Python? | I don't know the correct terminology, maybe it's called page file, but I'm not sure. I need a way to use an on-disk file as a buffer, like bytearray. It should be able to do things like a = buffer[100:200] and buffer[33] = 127 without the code having to be aware that it's reading from and writing to a file in the backg... | [
"Can something like this work for you?\nclass Memfile:\n\n def __init__(self, file):\n self.file = file\n\n def __getitem__(self,key):\n if type(key) is int:\n self.file.seek(key)\n return self.file.read(1)\n if type(key) is slice:\n self.file.seek(key.sta... | [
1
] | [] | [] | [
"buffer",
"file",
"memory",
"micropython",
"python"
] | stackoverflow_0074633047_buffer_file_memory_micropython_python.txt |
Q:
SNMP library for python failed return SNMP details
Unable to get Fetch SNMP variable details using sample posted at (https://snmplabs.thola.io/pysnmp/quick-start.html) and got error response . please advice how to fix the error . Thanks in advance
Traceback (most recent call last):
File "d:/WorkFiles/SNMPTest/SN... | SNMP library for python failed return SNMP details | Unable to get Fetch SNMP variable details using sample posted at (https://snmplabs.thola.io/pysnmp/quick-start.html) and got error response . please advice how to fix the error . Thanks in advance
Traceback (most recent call last):
File "d:/WorkFiles/SNMPTest/SNMP.py", line 6, in <module>
UdpTransportTarget(('snm... | [
"My company is trying to take over PySNMP ecosystem, as documented here.\nSo, you can use demo.pysnmp.com to test out typical SNMP commands/operations.\n"
] | [
0
] | [] | [] | [
"net_snmp",
"pysnmp",
"python",
"snmp",
"snmp_trap"
] | stackoverflow_0072285619_net_snmp_pysnmp_python_snmp_snmp_trap.txt |
Q:
Can Python's strptime handle Python's logging time format?
By default, Python's logging module uses a special format for times, which includes milliseconds: 2003-01-23 00:29:50,411.
Notably, strftime and strptime don't have a standard "milliseconds" specifier (so logging first prints everything else with strftime ... | Can Python's strptime handle Python's logging time format? | By default, Python's logging module uses a special format for times, which includes milliseconds: 2003-01-23 00:29:50,411.
Notably, strftime and strptime don't have a standard "milliseconds" specifier (so logging first prints everything else with strftime and then inserts the milliseconds separately). This means there'... | [
"This is in fact standard—for Python, at least. (%f is not a C-standard directive, which is why I couldn't find it in man strptime.) It's in the notes under Technical Detail:\n\nWhen used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to th... | [
1,
1
] | [] | [] | [
"datetime",
"python",
"strptime"
] | stackoverflow_0074632508_datetime_python_strptime.txt |
Q:
How to convert a URI containing partial relative path like '/../' in the middle?
LibreOffice API object is returning a URI path that contains relative path in the middle of the string, like:
file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav
How to convert this to the absolute like:
... | How to convert a URI containing partial relative path like '/../' in the middle? | LibreOffice API object is returning a URI path that contains relative path in the middle of the string, like:
file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav
How to convert this to the absolute like:
file:///C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav
How would I con... | [
"Use os.path.normpath:\nimport os\n\nos.path.normpath(\"file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav\")\n\nOutput:\n'file:/C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav'\n\nNote that the prefix is not correct anymore. So you may have to remove the \"file:///\" p... | [
2,
0
] | [] | [] | [
"python",
"relative_path",
"uri"
] | stackoverflow_0074632802_python_relative_path_uri.txt |
Q:
Denoise noisy straight lines / make noisy lines solid Python
I am attempting to denoise / make solid lines in a very noisy image of a floorplan in python to no success. The methods I have used are:
masking
bluring
and houghlinesp
I have even tried a combination of the first two. here is the sample input image I ... | Denoise noisy straight lines / make noisy lines solid Python | I am attempting to denoise / make solid lines in a very noisy image of a floorplan in python to no success. The methods I have used are:
masking
bluring
and houghlinesp
I have even tried a combination of the first two. here is the sample input image I am trying to make into solid straight lines: original image
With u... | [
"There are a few different things you could try, but to start I would recommend the following:\n\nFirst, threshold the image to identify only the parts that constitute the floor plan\nNext, dilate the image to connect any broken segments\nFinally, erode the image to prevent your lines from being too thick\n\nYou'll... | [
0
] | [] | [] | [
"image_processing",
"mask",
"noise_reduction",
"opencv",
"python"
] | stackoverflow_0074633128_image_processing_mask_noise_reduction_opencv_python.txt |
Q:
What am I doing wrong with Numba here?
I'm trying to learn how to use the Numba module. So far I haven't been able to get anything working because of some problem interfacing with NumPy. This is the code I'm running (from the Numba docs) and the error I get:
from numba import jit
import numpy as np
x = np.arange(... | What am I doing wrong with Numba here? | I'm trying to learn how to use the Numba module. So far I haven't been able to get anything working because of some problem interfacing with NumPy. This is the code I'm running (from the Numba docs) and the error I get:
from numba import jit
import numpy as np
x = np.arange(100).reshape(10, 10)
@jit(nopython=True) # ... | [
"Update to 0.53.1 works. It failed on 0.47.x as well for me. Seems more of numpy issue. One way to resolve install numpy >=1.20.0 and numba v>0.52.\nMore information on this issue:\nhttps://github.com/numba/numba/issues/6041\nP.S: not sure if you still have this error, just wanted to update, was facing similar issu... | [
5,
0
] | [] | [] | [
"dtype",
"numba",
"numpy",
"python"
] | stackoverflow_0067016356_dtype_numba_numpy_python.txt |
Q:
How to convert all values of a nested dictionary into strings?
I am writing a python application where I have a variable dictionary that can be nested upto any level.
The keys in any level can be either int or string. But I want to convert all keys and values at all levels into strings. How nested the dictionary w... | How to convert all values of a nested dictionary into strings? | I am writing a python application where I have a variable dictionary that can be nested upto any level.
The keys in any level can be either int or string. But I want to convert all keys and values at all levels into strings. How nested the dictionary will be is variable which makes it a bit complicated.
{
"col1": {... | [
"This is the most straightforward way I can think of doing it:\nimport json\n\ndata = {'col4': {'1': 'na', '0': 5, '3': 9, '2': '9', '4': 'na'}, 'col2': {'1': 1, '0': 'na', '3': 'na', '2': 'na', '4': 'na'}, 'col3': {'1': 3, '0': 1, '3': 6, '2': 3, '4': 3}, 'col1': {'1': 8, '0': 0, '3': 4, '2': {0: 2}, '4': 5}}\nstr... | [
6,
4,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0054565160_dictionary_python.txt |
Q:
Is there a way of creating Biglake Tables through Python?
In the documentation I see no reference to BigLake tables. I wonder if there's a way of setting ExternalDataConfiguration to use them.
A:
Found it out: if you provide a connection ID it will be used for setting the table as a BigLake Table (see https://st... | Is there a way of creating Biglake Tables through Python? | In the documentation I see no reference to BigLake tables. I wonder if there's a way of setting ExternalDataConfiguration to use them.
| [
"Found it out: if you provide a connection ID it will be used for setting the table as a BigLake Table (see https://stackoverflow.com/a/73987775/9944075 on how to create the connection)\n"
] | [
0
] | [] | [] | [
"google_bigquery",
"google_cloud_platform",
"python"
] | stackoverflow_0074629305_google_bigquery_google_cloud_platform_python.txt |
Q:
how to send image from url using telethon
I want to know how to send image or media from a URL link,
file = BOT.upload_file('/user/home/photo.jpg')
BOT.send_file(chat , file)
I know that using this method we can send image from path, but I want to know if its possible to send it from a URL link. but I am trying t... | how to send image from url using telethon | I want to know how to send image or media from a URL link,
file = BOT.upload_file('/user/home/photo.jpg')
BOT.send_file(chat , file)
I know that using this method we can send image from path, but I want to know if its possible to send it from a URL link. but I am trying to run the code on Heruku so uploading it from t... | [
"\nyou don't have to explicitly upload a file, telethon does it internally, so:\n\nBOT.send_file(chat , '/user/home/photo.jpg')\n\nis enough (unless you're willing to resend something pre-uploaded multiple times)\n\nlikewise, you can pass a URL to send_file, Telegram servers will fetch it and send by itself (note t... | [
0
] | [] | [] | [
"python",
"telethon"
] | stackoverflow_0074634287_python_telethon.txt |
Q:
Can I use Boto3 to automatically generate visualization from Athena to QuickSight?
Right now using Boto3 to run Python script to automate Athena queries. After getting the output, can I also use Boto3 to run another Python script and have the output populated in a specific dashboard template?
Non-technical, not su... | Can I use Boto3 to automatically generate visualization from Athena to QuickSight? | Right now using Boto3 to run Python script to automate Athena queries. After getting the output, can I also use Boto3 to run another Python script and have the output populated in a specific dashboard template?
Non-technical, not sure about feasibility. Just need a simply Y/N answer. Thanks!
| [
"What exactly do you need QuickSight to do?\nIf you need to ingest new data so that existing dashboard starts showing new data, you can use CreateIngestion API from here https://docs.aws.amazon.com/quicksight/latest/APIReference/qs-data.html\nIf you need to automate QuickSight dashboard creation, see https://aws.am... | [
1
] | [] | [] | [
"amazon_athena",
"amazon_quicksight",
"boto3",
"python",
"visualization"
] | stackoverflow_0074632473_amazon_athena_amazon_quicksight_boto3_python_visualization.txt |
Q:
Pandas substracting number of days from date
I am trying to create a new column "Starting_time" by subtracting 60 days out of "Harvest_date" but I get the same date each time. Can someone point out what did I do wrong please?
Harvest_date
20.12.21
12.01.21
10.03.21
import pandas as pd
from datetime import tim... | Pandas substracting number of days from date | I am trying to create a new column "Starting_time" by subtracting 60 days out of "Harvest_date" but I get the same date each time. Can someone point out what did I do wrong please?
Harvest_date
20.12.21
12.01.21
10.03.21
import pandas as pd
from datetime import timedelta
df1 = pd.read_csv (r'C:\Flower... | [
"You're overwriting the series on each iteration of the last loop\nfor harvest_date in df1['Harvest_date']:\n df1[\"Starting_date\"]=subtract_days_from_date(harvest_date,60)\n\nYou can do away with the loop by vectorizing the subtract_days_from_date function.\nYou could also reference an index with enumerate\nnp... | [
2,
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074633999_dataframe_pandas_python.txt |
Q:
Django: Quizapp with Question and Answer Model
I would like to create a Quiz app with Django.
Where the Questions can be stored in a DB and more users can add more questions in Admin.
and each question can have an answer from the user input.
This is a basic version of what I tried so far,
Simple example of My Mode... | Django: Quizapp with Question and Answer Model | I would like to create a Quiz app with Django.
Where the Questions can be stored in a DB and more users can add more questions in Admin.
and each question can have an answer from the user input.
This is a basic version of what I tried so far,
Simple example of My Models:
QuestionModel
ID
question
author
AnswerModel
... | [
"I am not good in django, but I think you can use these structure:\nQuestion Model:\nclass Question(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n title = models.CharField(max_length=60,)\n created_at = models.DateTimeField(auto_now_add=True)\n slug = models.SlugField(unique... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0074634170_django_django_forms_django_models_python.txt |
Q:
How to get this info with BS4?
I think soup.findall("dd", {"class": "clearfix"})['idk what goes here'] and then index it and save it could work but im not familiar with what ::before and ::after does to the output here
I only need the info that is in between ::before and ::after
A:
content = [] # create list
fo... | How to get this info with BS4? | I think soup.findall("dd", {"class": "clearfix"})['idk what goes here'] and then index it and save it could work but im not familiar with what ::before and ::after does to the output here
I only need the info that is in between ::before and ::after
| [
"content = [] # create list\nfor x in soup.findall(\"dd\", {\"class\": \"clearfix\"}): # for each element\n inner = x.encode_contents() # get inner html\n content.append(inner.removeprefix(\"::before\").removesuffix(\"::after\")) # add to content without ::before and ::after\n\nObviously, could become a oneli... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074634302_beautifulsoup_python.txt |
Q:
Python: Call static method from subclass
Is it possible to call a static method defined in a superclass from a method in subclass? Something like:
class A:
@staticmethod
def a():
...
class B(A):
def b(self):
A.a()
A.a() doesn't work, neither does B.a(), super.a() or self.a(). Is there a way ... | Python: Call static method from subclass | Is it possible to call a static method defined in a superclass from a method in subclass? Something like:
class A:
@staticmethod
def a():
...
class B(A):
def b(self):
A.a()
A.a() doesn't work, neither does B.a(), super.a() or self.a(). Is there a way to do this?
EDIT:
The problem was a stale .pyc... | [
"Works for me - except of course for super().whatever() which only works on Python 3.x. Please explain what you mean by \"doesn't work\"...\nPython 2.7.3 (default, Dec 18 2014, 19:10:20) \n[GCC 4.6.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> class Foo(object):\n... | [
0,
0
] | [] | [] | [
"python",
"static_methods"
] | stackoverflow_0028457008_python_static_methods.txt |
Q:
Apply fuzzy string matching of two columns in two Pandas dataframes while preserving a similarity score and output a Pandas DataFrame
I have two data frames that I'm trying to merge, based on a primary & foreign key of company name. One data set has ~50,000 unique company names, the other one has about 5,000. Dupl... | Apply fuzzy string matching of two columns in two Pandas dataframes while preserving a similarity score and output a Pandas DataFrame | I have two data frames that I'm trying to merge, based on a primary & foreign key of company name. One data set has ~50,000 unique company names, the other one has about 5,000. Duplicate company names are possible within each list.
To that end, I've tried to follow along the first solution from Figure out if a business... | [
"Here is a class I wrote using difflib should be close to what you need.\nimport difflib\n\nimport pandas as pd\n\n\nclass FuzzyMerge:\n \"\"\"\n Works like pandas merge except merges on approximate matches.\n \"\"\"\n def __init__(self, **kwargs):\n self.left = kwargs.get(\"left\")\n self... | [
0
] | [] | [] | [
"fuzzywuzzy",
"pandas",
"python",
"python_3.x",
"string_matching"
] | stackoverflow_0074633110_fuzzywuzzy_pandas_python_python_3.x_string_matching.txt |
Q:
Replace values in Pandas Dataframe using another Dataframe as a lookup table
I'm looking to replace values in a Dataframe with the values in a second Dataframe by matching the values in the first Dataframe with the columns from the second Dataframe.
Example:
import numpy as np
import pandas as pd
dt_index = pd.to_... | Replace values in Pandas Dataframe using another Dataframe as a lookup table | I'm looking to replace values in a Dataframe with the values in a second Dataframe by matching the values in the first Dataframe with the columns from the second Dataframe.
Example:
import numpy as np
import pandas as pd
dt_index = pd.to_datetime(['2003-05-01', '2003-05-02', '2003-05-03', '2003-05-04'])
df = pd.DataFra... | [
"One approach is to use stack() to reshape df2 into a Series and reindex() it using the values in df; reshape back into original shape using unstack().\ntmp = df2.stack().reindex(df.stack().droplevel(-1).items())\ntmp.index = pd.MultiIndex.from_arrays([tmp.index.get_level_values(0), df.columns.tolist()*len(df)])\nd... | [
1
] | [] | [] | [
"arrays",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074634131_arrays_dataframe_pandas_python.txt |
Q:
SNMP Simulator for Testing PySNMP?
I am looking for a way to test PySNMP scripts, since it seems like demo.snmplabs.com and snmpsim.try.thola.io are down - at least I can't get a response with the following example script from the PySNMP docs. Are there any other hosts I could try?
from pysnmp.hlapi import *
for ... | SNMP Simulator for Testing PySNMP? | I am looking for a way to test PySNMP scripts, since it seems like demo.snmplabs.com and snmpsim.try.thola.io are down - at least I can't get a response with the following example script from the PySNMP docs. Are there any other hosts I could try?
from pysnmp.hlapi import *
for (errorIndication,
errorStatus,
... | [
"While there were so many attempts to fill the gaps, you will find demo.pysnmp.com a more reliable option from me, as I plan to take over the whole ecosystem, https://github.com/etingof/pysnmp/issues/429\n"
] | [
0
] | [] | [] | [
"pysnmp",
"python",
"snmp"
] | stackoverflow_0066771211_pysnmp_python_snmp.txt |
Q:
RE: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.plt.show() in PyCharm
Previously Found here
The answers given are great, however they only address the problem in the form of Python/Linux Terminal commands. i.e., sudo install ....
What about when I am in a I... | RE: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.plt.show() in PyCharm | Previously Found here
The answers given are great, however they only address the problem in the form of Python/Linux Terminal commands. i.e., sudo install ....
What about when I am in a IDE such as PyCharm? I could use the Python Console to make the necessary changes, but there seems to be more straight forward ways to... | [
"I found examples and answers\nIs there some reason I should not just use the examples here;\nfor example:\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\nfrom matplotlib.figure import Figure\n\nimport numpy as np\n\nfrom PIL import Image\n\nThe simplest answer to this question would be \"There is n... | [
0
] | [] | [] | [
"matplotlib",
"pycharm",
"python"
] | stackoverflow_0074634590_matplotlib_pycharm_python.txt |
Q:
How do I verify an SSL certificate in python?
I need to verify that a certificate was signed by my custom CA. Using OpenSSL command-line utilities this is easy to do:
# Custom CA file: ca-cert.pem
# Cert signed by above CA: bob.cert
$ openssl verify -CAfile test-ca-cert.pem bob.cert
bob.cert: OK
But I need to do... | How do I verify an SSL certificate in python? | I need to verify that a certificate was signed by my custom CA. Using OpenSSL command-line utilities this is easy to do:
# Custom CA file: ca-cert.pem
# Cert signed by above CA: bob.cert
$ openssl verify -CAfile test-ca-cert.pem bob.cert
bob.cert: OK
But I need to do the same thing in Python, and I really don't want ... | [
"You can't do this with plain M2Crypto, since it does not wrap some of the required functions. Good news is if you have SWIG installed you can wrap those yourself and use with M2Crypto code. I've made a module with some extra functions for myself some time ago, and decided to publish it now, since it does this kind... | [
5,
0
] | [
"You can use the unfortunately undocumented X509.verify method to check whether the certificate was signed with the CA's private key. As this calls OpenSSL's x509_verify in the background, I'm sure this also checks all parameters (like expiration) correctly:\nfrom M2Crypto X509\n\ncert = X509.load_cert(\"certificat... | [
-1,
-3
] | [
"m2crypto",
"openssl",
"python",
"ssl",
"x509certificate"
] | stackoverflow_0004403012_m2crypto_openssl_python_ssl_x509certificate.txt |
Q:
How to type hint a generic numpy array?
Is there any way to type a Numpy array as generic?
I'm currently working with Numpy 1.23.5 and Python 3.10, and I can't type hint the following example.
import numpy as np
import numpy.typing as npt
E = TypeVar("E") # Should be bounded to a numpy type
def double_arr(arr: n... | How to type hint a generic numpy array? | Is there any way to type a Numpy array as generic?
I'm currently working with Numpy 1.23.5 and Python 3.10, and I can't type hint the following example.
import numpy as np
import numpy.typing as npt
E = TypeVar("E") # Should be bounded to a numpy type
def double_arr(arr: npt.NDArray[E]) -> npt.NDArray[E]:
return... | [
"Looking at the source, it seems the generic type variable used to parameterize numpy.dtype of numpy.typing.NDArray is bounded by numpy.generic (and declared covariant). Thus any type argument to NDArray must be a subtype of numpy.generic, whereas your type variable is unbounded. This should work:\nfrom typing impo... | [
1
] | [] | [] | [
"mypy",
"numpy",
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0074633074_mypy_numpy_python_python_typing_type_hinting.txt |
Q:
Execute task at specific times django
I am in the process of writing my own task app using Django and would like a few specific functions to be executed every day at a certain time (updating tasks, checking due dates, etc.). Is there a way to have Django run functions on a regular basis or how do I go about this i... | Execute task at specific times django | I am in the process of writing my own task app using Django and would like a few specific functions to be executed every day at a certain time (updating tasks, checking due dates, etc.). Is there a way to have Django run functions on a regular basis or how do I go about this in general?
Does it make sense to write an e... | [
"Celery is a good option here:\n\nFirst steps with Django\n\nPeriodic Tasks\n\napp.conf.beat_schedule = {\n'add-every-30-seconds': {\n 'task': 'tasks.add',\n 'schedule': 30.0,\n 'args': (16, 16)\n },\n}\napp.conf.timezone = 'UTC'\n\n\n\n\nWith celery you can define periodic tasks at any give... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074634127_django_python.txt |
Q:
Getting error when sending request to a website using Scrapy shell
I was learning Scrapy framework. I tried to use scrapy shell. There I was trying to fetch response from "https://quotes.toscrape.com/". The commands are below-
python -m scrapy shell
Inside the shell-
>> from scrapy import Request
>> req = Request... | Getting error when sending request to a website using Scrapy shell | I was learning Scrapy framework. I tried to use scrapy shell. There I was trying to fetch response from "https://quotes.toscrape.com/". The commands are below-
python -m scrapy shell
Inside the shell-
>> from scrapy import Request
>> req = Request("https://quotes.toscrape.com/")
>> fetch(req)
Then I found the error l... | [
"If you are using windows. This is caused by a bug.\nHere is the github issue.\nThis has absolutely nothing to do with the robots.txt file.\n",
"I recreated the same steps and had no problem getting the page. I would recommend you to change this setting in the settings.py:\nROBOTSTXT_OBEY = False because as you ... | [
1,
-1
] | [] | [] | [
"python",
"python_asyncio",
"scrapy",
"scrapy_shell",
"web_scraping"
] | stackoverflow_0074625783_python_python_asyncio_scrapy_scrapy_shell_web_scraping.txt |
Q:
Display Pandas Dataframe PowerBI
PowerBi does not allow display of pandas dataframe in page. Requires a plot.
I am working with the python scripting function in PowerBi. I would like to display a pandas dataframe in the page but when I try to print(dataset) I get the following error (https://i.stack.imgur.com/4BWv... | Display Pandas Dataframe PowerBI | PowerBi does not allow display of pandas dataframe in page. Requires a plot.
I am working with the python scripting function in PowerBi. I would like to display a pandas dataframe in the page but when I try to print(dataset) I get the following error (https://i.stack.imgur.com/4BWvT.png)
Is there a neat way to display ... | [
"The Python visual turns data into an image. You can sue the Python step in Power Query if you want to output the Dataframe for use in your report.\n"
] | [
0
] | [] | [] | [
"pandas",
"powerbi",
"powerbi_custom_visuals",
"python"
] | stackoverflow_0074632255_pandas_powerbi_powerbi_custom_visuals_python.txt |
Q:
index 5 is out of bounds for axis 1 with size 1- python
I have used Markov clustering (MCL) to cluster data of (6) points, the input to MCL is a matrix.
my data:
import warnings
import math
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linear_sum_as... | index 5 is out of bounds for axis 1 with size 1- python | I have used Markov clustering (MCL) to cluster data of (6) points, the input to MCL is a matrix.
my data:
import warnings
import math
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linear_sum_assignment
import scipy.spatial.distance as distance
from sklea... | [
"In that line, Matrix would need to be an int. Did you maybe mean to use Matrix.shape[0] in np.zeros()?\n"
] | [
0
] | [] | [] | [
"cluster_analysis",
"pandas",
"python"
] | stackoverflow_0074634612_cluster_analysis_pandas_python.txt |
Q:
how to add keys from an existing dictionary to a new dictionary
I have a dictionary that looks like this:
pris = {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'citroner': [20,13,14,15,16], 'hallon': [23,34,45,46,57], 'kokos': [12,45,67,89]}
an another:
t={'äpplen', 'bananer', 'hallon'}
What I'm trying ... | how to add keys from an existing dictionary to a new dictionary | I have a dictionary that looks like this:
pris = {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'citroner': [20,13,14,15,16], 'hallon': [23,34,45,46,57], 'kokos': [12,45,67,89]}
an another:
t={'äpplen', 'bananer', 'hallon'}
What I'm trying to do is to create a new dictionary with only the elements in t.
New_... | [
"try this:\nnew_d = dict()\nfor key in t:\n if key in pris:\n new_d[key] = pris[key]\n\nhere is how in 1 line\nnew_d = {key:pris[key] for key in t if key in pris}\n\n",
"Try this:\nnew_dict = {}\nfor e in t:\n if e in pris.keys():\n new_dict[e] = pris[e]\n\n"
] | [
0,
0
] | [
"New_dictionary={k:pris[k] for k in t}\n"
] | [
-1
] | [
"del",
"dictionary",
"list",
"python"
] | stackoverflow_0074598269_del_dictionary_list_python.txt |
Q:
ImportError: cannot import name 'transpose'
I try to run a script which starts like this:
import os, sys, subprocess, argparse, random, transposer, numpy, csv, scipy, gzip
BUT, I got this error:
ImportError: cannot import name 'transpose'
I work on slurm cluster. Should I install transposer? I work with conda as w... | ImportError: cannot import name 'transpose' | I try to run a script which starts like this:
import os, sys, subprocess, argparse, random, transposer, numpy, csv, scipy, gzip
BUT, I got this error:
ImportError: cannot import name 'transpose'
I work on slurm cluster. Should I install transposer? I work with conda as we don't have permission to install on cluster. Bu... | [
"pip install transposer ? worked for me.\n"
] | [
0
] | [] | [] | [
"conda",
"python",
"transpose"
] | stackoverflow_0074634768_conda_python_transpose.txt |
Q:
How to generate Sankey diagrams using Brightway2?
I know that we can get Sankey diagrams using activity-browser. Is there a way we can generate a sankey diagram for one of the ecoinvent activities using brightway2 functions and python?
I looked into brightway2 functions but couldn't find one that I can readily use... | How to generate Sankey diagrams using Brightway2? | I know that we can get Sankey diagrams using activity-browser. Is there a way we can generate a sankey diagram for one of the ecoinvent activities using brightway2 functions and python?
I looked into brightway2 functions but couldn't find one that I can readily use for sankey diagrams.
| [
"Unfortunately not, at least right now. The activity-browser implementation is licensed LGPL, which isn't compatible with the Brightway license, so we can't just copy what they have done. There are also technical limitations, as an interactive graphic would need a server/client architecture for new calculations (e.... | [
1
] | [] | [] | [
"brightway",
"python",
"sankey_diagram"
] | stackoverflow_0074634021_brightway_python_sankey_diagram.txt |
Q:
Are there any priority "or" in python?
Is there any "priority or" function in python? For instance if i am out of range
vec = [1, 2, 3, 4, 5]
new_vec = []
for index, number in enumerate(vec):
try:
new_value += vec[index + 1] + vec[index + 2] or if i am out of range do += vec[index +1] and if i am still ou... | Are there any priority "or" in python? | Is there any "priority or" function in python? For instance if i am out of range
vec = [1, 2, 3, 4, 5]
new_vec = []
for index, number in enumerate(vec):
try:
new_value += vec[index + 1] + vec[index + 2] or if i am out of range do += vec[index +1] and if i am still out of range pass
except IndexError:
pass ... | [
"You can use sum() and regular list slicing. Unlike regular indexing which raises an error when out of range, slicing continues to work.\nfive = [0, 1, 2, 3, 4]\n\nprint(five[4]) # 4\nprint(five[5]) # Error\nprint(five[2:4]) # [2, 3]\nprint(five[2:1000]) # [2, 3, 4]; no error\nprint(five[1000:1001]) # []; still no ... | [
1
] | [] | [] | [
"for_loop",
"index_error",
"list",
"python",
"try_except"
] | stackoverflow_0074634520_for_loop_index_error_list_python_try_except.txt |
Q:
Calculate lat/lon of 4 corners of rectangle using Python
I need to find the latitude and longitude coordinates of the four corners of a rectangle in a Python script, given the center coordinate, length, width, and bearing of the shape. Length and width are in statute miles, but honestly converting those to meters ... | Calculate lat/lon of 4 corners of rectangle using Python | I need to find the latitude and longitude coordinates of the four corners of a rectangle in a Python script, given the center coordinate, length, width, and bearing of the shape. Length and width are in statute miles, but honestly converting those to meters is probably one of the easiest parts. I have some examples of ... | [
"Rectangle on the earth sphere.. this is doubtful thing.\nAnyway, look at this page.\nUsing formula from section Destination point given distance and bearing from start point, calculate two middles at distance width/2 and bearings bearing, bearing + 180.\nFor every middle point do the same with height/2 and bearing... | [
0,
0,
0
] | [] | [] | [
"coordinates",
"geometry",
"geospatial",
"haversine",
"python"
] | stackoverflow_0074607356_coordinates_geometry_geospatial_haversine_python.txt |
Q:
Python DOCX font size Pt() not defined
I am trying to get this document to change the font size but it keeps saying Pt() is not defined.
I have this:
import docx
doc = docx.Document(r"C:\Users\jconshick\Desktop\CodeTest\Spellbook.docx")
para = doc.add_paragraph('').add_run("This is a test")
para.font.size = Pt(12... | Python DOCX font size Pt() not defined | I am trying to get this document to change the font size but it keeps saying Pt() is not defined.
I have this:
import docx
doc = docx.Document(r"C:\Users\jconshick\Desktop\CodeTest\Spellbook.docx")
para = doc.add_paragraph('').add_run("This is a test")
para.font.size = Pt(12)
doc.save(r"C:\Users\jconshick\Desktop\Code... | [
"Try\ndocx.shared.Pt(12)\n\ninstead of\nPt(12)\n\nBy this answer from @PieterduToit\n"
] | [
1
] | [] | [] | [
"docx",
"python",
"python_3.x",
"python_docx"
] | stackoverflow_0074634807_docx_python_python_3.x_python_docx.txt |
Q:
Is it possible to get to the code from egg-link?
I made some modifications to the code for a deep learning model implemented in MxNet.
On my local computer, I installed MxNet by conda/pip, so I could just go to the installation folder, where I found the files where the model architecture is specified and made my c... | Is it possible to get to the code from egg-link? | I made some modifications to the code for a deep learning model implemented in MxNet.
On my local computer, I installed MxNet by conda/pip, so I could just go to the installation folder, where I found the files where the model architecture is specified and made my changes. The structure is like:
.../environment_folder/... | [
"If you can open a python shell prompt (with the environment loaded) on the machine in question, try:\nimport mxnet\nmxnet.__file__\n\n"
] | [
0
] | [] | [] | [
"egg",
"python"
] | stackoverflow_0074191226_egg_python.txt |
Q:
ValueError: Invalid endpoint: https://s3..amazonaws.com
When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error:
ValueError: Invalid endpoint: https://s3..amazonaws.com
When I'm trying to set up a new machine it can suddenly work.
Attached the full error:
s... | ValueError: Invalid endpoint: https://s3..amazonaws.com | When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error:
ValueError: Invalid endpoint: https://s3..amazonaws.com
When I'm trying to set up a new machine it can suddenly work.
Attached the full error:
self.client = boto3.client("s3")
File "/usr/local/lib/python... | [
"It looks like you have an invalid region.\nCheck your ~/.aws/config\n",
"Set the region in your ~/.aws/credentials or ~/.aws/config files. You can set the region as an environment variable as well e.g. \nIn bash\nexport AWS_REGION=\"eu-west-2\"\n\nor in Powershell\n$Env:AWS_REGION=\"eu-west-2\"\n\n",
"In my ca... | [
19,
11,
0
] | [] | [] | [
"amazon_emr",
"amazon_s3",
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0057943053_amazon_emr_amazon_s3_amazon_web_services_boto3_python.txt |
Q:
How do I create any regular polygon using turtle?
So I have an assignment that asked me to draw any regular polygon using Turtle and I created the code. It works but my mentor said to try again. I would like to know what I did wrong, Thank you!
The requirements for this assignment are:
The program should take in ... | How do I create any regular polygon using turtle? | So I have an assignment that asked me to draw any regular polygon using Turtle and I created the code. It works but my mentor said to try again. I would like to know what I did wrong, Thank you!
The requirements for this assignment are:
The program should take in input from the user.
The program should have a function... | [
"This is the function I used to draw a polygon using Turtle:\nDraws an n-sided polygon of a given length. t is a turtle.\ndef polygon(t, n, length):\nangle = 360.0 / n\npolyline(t, n, length, angle)\n\n",
"I think this might be better suited on math stackexchange.\nA regular polygon has interior angles (n−2) × 18... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"python_turtle"
] | stackoverflow_0074633650_python_python_3.x_python_turtle.txt |
Q:
How to make a lower triangle array of 10 but repeated across a diagonal n times?
I am trying to create an array of 10 for each item I have, but then put those arrays of 10 into a larger array diagonally with zeros filling the missing spaces.
Here is an example of what I am looking for, but only with arrays of 3.
i... | How to make a lower triangle array of 10 but repeated across a diagonal n times? | I am trying to create an array of 10 for each item I have, but then put those arrays of 10 into a larger array diagonally with zeros filling the missing spaces.
Here is an example of what I am looking for, but only with arrays of 3.
import numpy as np
arr = np.tri(3,3)
arr
This creates an array that looks like this:
[... | [
"Now I got it... AFAIU, the OP wants those np.tri triangles in the diagonal of a bigger, multiple of 3 square shaped array.\nAs per example, for n=2:\nimport numpy as np\n\nn = 2\n\ntri = np.tri(3)\n\narr = np.zeros((n*3, n*3))\n\nfor i in range(0, n*3, 3):\n arr[i:i+3,i:i+3] = tri\n\narr.astype(int)\n\n# Out: \... | [
0,
0
] | [] | [] | [
"arrays",
"matrix",
"pandas",
"python"
] | stackoverflow_0074634540_arrays_matrix_pandas_python.txt |
Q:
Import excel file and loop run for each row in Excel file
I have this code to scrape the results from google. If I have a list of terms I need to search in Excel/Csv format, how can I write the code to
After import the excel file, search each row values and print out the results for that row.
Repeat for the next... | Import excel file and loop run for each row in Excel file | I have this code to scrape the results from google. If I have a list of terms I need to search in Excel/Csv format, how can I write the code to
After import the excel file, search each row values and print out the results for that row.
Repeat for the next row value in the Excel file.
Here's my code. Please help with... | [
"If this is the content of your .csv file called file.csv:\na,b,c\n1,2,3\nk,l,m\n\nthen you can read it and loop row by row like so:\nimport csv\n\n# read file.csv and print each row\nwith open('file.csv', 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n print(row)\n\nThis answer doesn'... | [
0
] | [] | [] | [
"module",
"python",
"web_scraping"
] | stackoverflow_0074634922_module_python_web_scraping.txt |
Q:
Python subprocess with dynamic variables and arguments
I want to ask how can I run subprocess.run() or subprocess.call() in python when the arguments are dynamic. I have already stored all commands in an external batch file, and I want to use Python to run the batch file after I update the arguments. I will give m... | Python subprocess with dynamic variables and arguments | I want to ask how can I run subprocess.run() or subprocess.call() in python when the arguments are dynamic. I have already stored all commands in an external batch file, and I want to use Python to run the batch file after I update the arguments. I will give more details in the following:
the batch file is like this:
e... | [
"A slightly simpler implementation might look like:\n#!/usr/bin/env python\nimport yaml\n\nparam_temp = 'pathway for parameter input yaml file'+'param_input.yml'\nbatch_path = 'batch file path'\n\nparam = yaml.safe_load(param_temp)\nparams = [ 'Year', 'Month', 'Date', 'Path1', 'Path2', 'yyyymmdd' ]\nparam_values = ... | [
0
] | [] | [] | [
"python",
"subprocess",
"variables"
] | stackoverflow_0074634932_python_subprocess_variables.txt |
Q:
c$50 finance non-integers being rejected causing Buy to fail check50
Everything seems to be working fine with my code, however I am running into a single error for /buy when running check50. :( buy handles fractional, negative, and non-numeric shares. expected status code 400, but got 200.
I thinks check50 is rece... | c$50 finance non-integers being rejected causing Buy to fail check50 | Everything seems to be working fine with my code, however I am running into a single error for /buy when running check50. :( buy handles fractional, negative, and non-numeric shares. expected status code 400, but got 200.
I thinks check50 is receiving status code 200 when checking a non-integer such as 1.5 or string, b... | [
"I was able to solve the problem. The problem was that the python code did not check for negative numbers and therefore accepted them (which should not).\n",
"I was able to solve this by taking the shares value from the form and putting it into a try block to typecast it into an int, if it receives a value error ... | [
1,
0
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0055561427_flask_html_python.txt |
Q:
Find all possible paths in a python graph data structure without using recursive function
I have a serious issue with finding all possible paths in my csv file that looks like this :
Source
Target
Source_repo
Target_repo
SOURCE1
Target2
repo-1
repo-2
SOURCE5
Target3
repo-5
repo-3
SOURCE8
Target5
repo-8
repo-5
... | Find all possible paths in a python graph data structure without using recursive function | I have a serious issue with finding all possible paths in my csv file that looks like this :
Source
Target
Source_repo
Target_repo
SOURCE1
Target2
repo-1
repo-2
SOURCE5
Target3
repo-5
repo-3
SOURCE8
Target5
repo-8
repo-5
There a large amount of lines in the datasets, more than 5000 lines. I want to gene... | [
"I'm not sure if you want all paths or paths specifically from node to another node. Either way this looks like a job for networkx.\nSetup (nx.from_pandas_edgelist)\nimport networkx as nx\nimport pandas as pd\n\n\ndf = pd.read_csv(\"...\")\n\ngraph = nx.from_pandas_edgelist(df, create_using=nx.DiGraph)\n\nAll paths... | [
1
] | [] | [] | [
"dataframe",
"graph_theory",
"pandas",
"python",
"recursion"
] | stackoverflow_0074631517_dataframe_graph_theory_pandas_python_recursion.txt |
Q:
Computing the mean of an array considering only some indices
I have two 2d arrays, one containing float values, one containing bool. I want to create an array containing the mean values of the first matrix for each column considering only the values corresponding to False in the second matrix.
For example:
A = [[1... | Computing the mean of an array considering only some indices | I have two 2d arrays, one containing float values, one containing bool. I want to create an array containing the mean values of the first matrix for each column considering only the values corresponding to False in the second matrix.
For example:
A = [[1 3 5]
[2 4 6]
[3 1 0]]
B = [[True False False]
[Fa... | [
"Where B is False, keep the value of A, make it NaN otherwise and then use the nanmean function which ignores NaN's for operations.\nnp.nanmean(np.where(~B, A, np.nan), axis=0)\n\n>>> array([2. , 3.5 , 3.66666667])\n\n",
"Using numpy.mean using where argument to specify elements to include in the mea... | [
3,
2,
0,
0,
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0074634440_arrays_multidimensional_array_numpy_python.txt |
Q:
positional arguments are being asked for even though I have included them in my args instead?
Hi I'm writing a program that is meant to do the RK4 method for different ODEs for an assignment. One of the things we have to use is *args. When I call on my function that includes *args(the rk4 one) I list the extra par... | positional arguments are being asked for even though I have included them in my args instead? | Hi I'm writing a program that is meant to do the RK4 method for different ODEs for an assignment. One of the things we have to use is *args. When I call on my function that includes *args(the rk4 one) I list the extra parameters at the end. When I try to run it it says that my function(f2a in this case) is missing 3 re... | [
"You correctly pass in the extra arguments that will be stored in the args parameter of the function odeRK4, when running this:\n# at the end of you snippet ^^\nodeRK4(f2a, [0,20],[0,7], None, 10,150,7)\n\nHowever, as you mention f2a requires 3 arguments. Looking at the definition of odeRK4 we see that after passi... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074634946_python.txt |
Q:
How to write a MySQL Insert Into Statement with Inner Join?
The user adds information here: the form
The information gets added to the shoes table.
The database: the database
I want to insert ShoeImage, ShoeName, ShoeStyle, ShoeColor, ShoePrice, and ShoeDescr, and NOT ShoeID (which is autoincrement),ShoeBrandID, a... | How to write a MySQL Insert Into Statement with Inner Join? | The user adds information here: the form
The information gets added to the shoes table.
The database: the database
I want to insert ShoeImage, ShoeName, ShoeStyle, ShoeColor, ShoePrice, and ShoeDescr, and NOT ShoeID (which is autoincrement),ShoeBrandID, and ShoeSizeID.
My insert statement:
$sql = "INSERT INTO $tblShoes... | [
"Might works.\nINSERT INTO shoes\n(\n'ShoeImage',\n'ShoeName',\n'ShoeStyle',\n'ShoeColor',\n'ShoePrice',\n'ShoeDescr',\n'ShoeBrandID',\n'ShoeSizeID'\n)\nVALUES(\nNULL,\n'$ShoeImage',\n'$ShoeName',\n'$ShoeStyle',\n'$ShoeColor',\n'$ShoePrice',\n'$ShoeDescr',\n(SELECT BrandID FROM shoebrand WHERE BrandName = '$ShoeBra... | [
0
] | [] | [] | [
"inner_join",
"mysql",
"python",
"sql",
"sql_insert"
] | stackoverflow_0074634547_inner_join_mysql_python_sql_sql_insert.txt |
Q:
OpenCV - undistort image and create point cloud based on it
I made around 40 images with a realsense camera, which gave me rgb and corresponding aligned depth images. With rs.getintrinsic() i got the intrinsic matrix of the camera. But there is still a distortion which can be seen in the pointcloud, which can be e... | OpenCV - undistort image and create point cloud based on it | I made around 40 images with a realsense camera, which gave me rgb and corresponding aligned depth images. With rs.getintrinsic() i got the intrinsic matrix of the camera. But there is still a distortion which can be seen in the pointcloud, which can be easily generated with the depth image. Here you can see it on the ... | [
"I would suggest to use uncropped image that has same width and length of the original images that been used for camera calibration. The cropped one will has different image shape/size.\n"
] | [
0
] | [] | [] | [
"camera_calibration",
"distortion",
"opencv",
"point_clouds",
"python"
] | stackoverflow_0074027213_camera_calibration_distortion_opencv_point_clouds_python.txt |
Q:
Django: Converse of `__endswith`
Django allows me to do this:
chair = Chair.objects.filter(name__endswith='hello')
But I want to do this:
chair = Chair.objects.filter(name__isendof='hello')
I know that the lookup __isendof doesn't exist. But I want something like this. I want it to be the converse of __endswit... | Django: Converse of `__endswith` | Django allows me to do this:
chair = Chair.objects.filter(name__endswith='hello')
But I want to do this:
chair = Chair.objects.filter(name__isendof='hello')
I know that the lookup __isendof doesn't exist. But I want something like this. I want it to be the converse of __endswith. It should find all chairs such that... | [
"Django ORM is not a silver bullet, there is nothing wrong in writing parts of SQL in case handling with plain ORM is difficult or impossible. This is a really good use case of extra():\nEntry.objects.extra(where=['\"hello\" LIKE CONCAT(\"%%\", name)'])\n\nNote that, since we are writing plain SQL here - it would b... | [
6,
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0024725182_django_django_models_python.txt |
Q:
Best way to parse nested dictionary in Pandas?
I have the following code that get the submissions and comments from a subreddit tennis:
headlines = {}
comments = []
i = 1
for submission in reddit.subreddit('tennis').search("Djokovic loves", sort="relevance", limit=10):
h = {}
c = {}
h['title'] = submis... | Best way to parse nested dictionary in Pandas? | I have the following code that get the submissions and comments from a subreddit tennis:
headlines = {}
comments = []
i = 1
for submission in reddit.subreddit('tennis').search("Djokovic loves", sort="relevance", limit=10):
h = {}
c = {}
h['title'] = submission.title
h['id'] = submission.id
h['score'... | [
"data = [{'headline': {'title': 'abc', 'id':123, 'score':0.5},'comment': [{'author': 'James', 'body': 'He is good!'}]}]\n \ndf = pd.json_normalize(data, record_path='comment', meta=[['headline', 'title'],['headline', 'id'], ['headline','score']], record_prefix='comment.')\n \n | | comment.author ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074634710_dataframe_pandas_python.txt |
Q:
Is there a faster way to rebuild a dataframe based on certain values of rows?
I loaded a .csv file with around 620k rows and 6 columns into jupyter notebook. The data is like this:
col_1 col_2 col_3 col_4 col_5
ID_1 388343 388684 T.45396D 2.400000e-03
ID_1 388343 388684 T.45708S 3.40000... | Is there a faster way to rebuild a dataframe based on certain values of rows? | I loaded a .csv file with around 620k rows and 6 columns into jupyter notebook. The data is like this:
col_1 col_2 col_3 col_4 col_5
ID_1 388343 388684 T.45396D 2.400000e-03
ID_1 388343 388684 T.45708S 3.400000e-04
ID_1 388343 388684 T.48892G 2.200000e-10
ID_1 388343 388684 T.56... | [
"might not be the fastest possible implementation, but it is certainly faster than looping over all values of col_1 and iteratively dropping it.\ndf.sort_values(\"col_5\").drop_duplicates(subset=\"col_1\", keep=First)\n\nthere are two major performance considerations at issue with your implementation:\n\nvectorizat... | [
4
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074635119_dataframe_pandas_python.txt |
Q:
How can I effectively use the same orm model in two git repositories?
The initial situation is that I have two fast-api servers that access the same database. One is the real service for my application and the other is a service for loading data from different sources. Both services have their own Github repositor... | How can I effectively use the same orm model in two git repositories? | The initial situation is that I have two fast-api servers that access the same database. One is the real service for my application and the other is a service for loading data from different sources. Both services have their own Github repository, but use the same orm data model.
My question is: What are best practices... | [
"Modularisation (avoiding code repetition) is a best practice, and so the ideal thing to do would indeed be to extract the model definition to a single file and import it where needed.\nThe problem is, when you deploy your two services both of them need to be able to 'see' the model file ... otherwise they can't im... | [
0
] | [] | [] | [
"fastapi",
"python",
"sqlalchemy"
] | stackoverflow_0074634434_fastapi_python_sqlalchemy.txt |
Q:
Tkinter - How can I sync two Scrollbar's with two Text widget's to mirrow each others view?
I need to sync two scrolled bars. both of them manage a different text widget and when I scroll in the first one, I want to see the same behaviour in the second one. I don't want to use a single scrolled bar, both of them m... | Tkinter - How can I sync two Scrollbar's with two Text widget's to mirrow each others view? | I need to sync two scrolled bars. both of them manage a different text widget and when I scroll in the first one, I want to see the same behaviour in the second one. I don't want to use a single scrolled bar, both of them must to be syncronized. how can I rech my goal? below a simple example code (here the scrolled bar... | [
"You can achieve this by writing a function:\ndef sync_scroll(*args):\n template1.yview(*args)\n template2.yview(*args)\n\nand setting the scrollbars to this command:\nS1.config(command=sync_scroll)\nS2.config(command=sync_scroll)\n\nThe sync_scroll will be triggered by each of the scrollbars with the already... | [
1
] | [] | [] | [
"python",
"python_3.x",
"tkinter",
"tkinter_scrolledtext"
] | stackoverflow_0074635102_python_python_3.x_tkinter_tkinter_scrolledtext.txt |
Q:
ProcessPoolExecutor using map hang on large load
Experiencing hangs running ProcessPoolExecutor on map, only on a relatively large load.
The behaviour we see is that after about 1 minutes of hard working, job seems to hang: the CPU utilization drops sharply then becomes idle; the stack trace also seems to show the... | ProcessPoolExecutor using map hang on large load | Experiencing hangs running ProcessPoolExecutor on map, only on a relatively large load.
The behaviour we see is that after about 1 minutes of hard working, job seems to hang: the CPU utilization drops sharply then becomes idle; the stack trace also seems to show the same portion of calls as time progresses.
def work_wr... | [
"The problem you're having is due to Executor.map not handling large/infinite iterable inputs in a sane way. Before it yields a single value, it consumes the entire input iterator and submits a task for every input.\nIf your inputs are produced lazily (on the theory that this would keep memory usage down), nope, th... | [
0
] | [] | [] | [
"concurrent.futures",
"multiprocessing",
"python",
"python_3.x",
"python_multiprocessing"
] | stackoverflow_0074633896_concurrent.futures_multiprocessing_python_python_3.x_python_multiprocessing.txt |
Q:
How to match a word surrounded by a prefix and suffix?
Is there any regex to extract words from text that are surrounded by a certain prefix and suffix?
Example:
test[az5]test[az6]test
I need to extract the numbers surrounded by the prefix [az and the suffix ].
I'm a bit advanced in Python, but not really familia... | How to match a word surrounded by a prefix and suffix? | Is there any regex to extract words from text that are surrounded by a certain prefix and suffix?
Example:
test[az5]test[az6]test
I need to extract the numbers surrounded by the prefix [az and the suffix ].
I'm a bit advanced in Python, but not really familiar with regex.
The desired output is:
5
6
| [
"You are looking for the following regular expression:\n>>> import re\n>>> re.findall('\\[az(\\d+)\\]', 'test[az5]test[az6]test')\n['5', '6']\n>>> \n\n",
"import re\n\ntxt = \"test[az5]test[az6]test\"\nx = re.findall(r\"\\[az(?P<num>\\d)\\]\", txt)\nprint(x)\n\nOutput\n['5', '6']\n"
] | [
1,
0
] | [] | [] | [
"extract",
"python",
"string"
] | stackoverflow_0074635145_extract_python_string.txt |
Q:
Want to create a program to scale a linked list by a certain factor
I want to write a function where you input a linked list and a factor, and the function returns a new linked list scaled by that factor. For example:
scale(linkify([1, 2, 3]), 2)
2 -> 4 -> 6 -> None
First, I made a function that, when you input a... | Want to create a program to scale a linked list by a certain factor | I want to write a function where you input a linked list and a factor, and the function returns a new linked list scaled by that factor. For example:
scale(linkify([1, 2, 3]), 2)
2 -> 4 -> 6 -> None
First, I made a function that, when you input a list of items, converts into a linked list. This is it here:
def linkify... | [
"Is this a proper solution for your case?\nI always try to avoid using recursions.\nSure you also can add some checks on the function inputs.\nclass Node:\n def __init__(self, data = None):\n self.data = data\n self.next = None\n\nclass Linkedlist:\n def __init__(self):\n self.head = None... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074634775_python.txt |
Q:
TypeError: TimeGrouper.__init__() got multiple values for argument 'freq'
What am I doing wrong?
This is all the code needed to reproduce.
import pandas as pd
g = pd.Grouper('datetime', freq='D')
Result:
---------------------------------------------------------------------------
TypeError ... | TypeError: TimeGrouper.__init__() got multiple values for argument 'freq' | What am I doing wrong?
This is all the code needed to reproduce.
import pandas as pd
g = pd.Grouper('datetime', freq='D')
Result:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [1], line 2
1 import pa... | [
"This seems to be a bug\nIt looks like the weirdness is because Grouper.__new__() instantiates a TimeGrouper if you pass freq as a kwarg, but not if you pass freq as a positional argument. I don't know why it does that, and it's not documented, so it seems like a bug.\nThe reason for the error is that TimeGrouper._... | [
2,
1
] | [] | [] | [
"pandas",
"python",
"typeerror"
] | stackoverflow_0074634784_pandas_python_typeerror.txt |
Q:
Facebook Prophet API documenation
I'm looking for a API Python documentation for Facebook Prophet
Here there are good examples https://facebook.github.io/prophet/docs
future = m.make_future_dataframe(periods=365)
or
future = m.make_future_dataframe(periods=300, freq='H')
But it doesn't explain all possible param... | Facebook Prophet API documenation | I'm looking for a API Python documentation for Facebook Prophet
Here there are good examples https://facebook.github.io/prophet/docs
future = m.make_future_dataframe(periods=365)
or
future = m.make_future_dataframe(periods=300, freq='H')
But it doesn't explain all possible parameters in make_future_dataframe, or the ... | [
"Here is where it is defined\nhttps://github.com/facebook/prophet/blob/f123a1a7cc6ab51bd21f01e41738d97910a2b2b7/python/fbprophet/forecaster.py#L1548\n def make_future_dataframe(self, periods, freq='D', include_history=True):\n\n",
"The arguments and API usages are documented as per \"October 14, 2022\" in this... | [
0,
0
] | [] | [] | [
"facebook_prophet",
"python"
] | stackoverflow_0066590261_facebook_prophet_python.txt |
Q:
Populate list with loop
I am trying to populate a list with numbers given via input.
num_guesses = 3
user_guesses = []
The desired result would be if I entered 3 different numbers 10, 15, 5 that it would print [10,15,5].
The book I'm using does not really explain how to do this, so it's kind of frustrating.
A:
... | Populate list with loop | I am trying to populate a list with numbers given via input.
num_guesses = 3
user_guesses = []
The desired result would be if I entered 3 different numbers 10, 15, 5 that it would print [10,15,5].
The book I'm using does not really explain how to do this, so it's kind of frustrating.
| [
"\nWrite a loop to populate the list user_guesses with a number of\nguesses. The variable num_guesses is the number of guesses the user\nwill have, which is read first as an integer. Read integers one at a\ntime using int(input()).\n\nnum_guesses = int(input())\nuser_guesses = []\nfor i in range(num_guesses):\n ... | [
4,
2,
1,
0,
0
] | [
"num_guesses = int(input())\nuser_guesses = []\n\nfor i in range(num_guesses):\n user_guesses.append(int(input()))\n\nprint('user_guesses:', user_guesses)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0026595053_python.txt |
Q:
Scipy - All the Solutions of Non-linear Equations System
I have a system of non-linear equations, where can be choosed any n, so length of vector x = (x1,...,xn) can be different. For example, system can be like that:
f1(x1,...,xn) = sum( xi + xi^2 ) = 0, i={1,n}
f2(x1,...,xn) = sum( e^xi + xi + sin(xi*pi)... | Scipy - All the Solutions of Non-linear Equations System | I have a system of non-linear equations, where can be choosed any n, so length of vector x = (x1,...,xn) can be different. For example, system can be like that:
f1(x1,...,xn) = sum( xi + xi^2 ) = 0, i={1,n}
f2(x1,...,xn) = sum( e^xi + xi + sin(xi*pi) ) = 0, i={1,n}
According to this example, I use fsolve() of ... | [
"It can be difficult (or impossible ) to find numerically all the solutions even for a single non-linear equation, let along a system. For instance, consider the equation,\nsin(1/x) = 0\n\nthat has an infinity of solutions in the interval [0, 1]: you can't solve this with typical root-finding algorithms.\nIn partic... | [
3,
0
] | [] | [] | [
"equation_solving",
"nonlinear_functions",
"numpy",
"python",
"scipy"
] | stackoverflow_0030877513_equation_solving_nonlinear_functions_numpy_python_scipy.txt |
Q:
Multiple changes to the same variable within different if statements
SOLVED: I read through my code, it was a 'bug'. When I copied the dice roll method from the 'player character', since it uses the same mechanics for the enemies, I set the damage to 0 if it rolls with one die on accident.
Beginner here. (Python c... | Multiple changes to the same variable within different if statements | SOLVED: I read through my code, it was a 'bug'. When I copied the dice roll method from the 'player character', since it uses the same mechanics for the enemies, I set the damage to 0 if it rolls with one die on accident.
Beginner here. (Python crash course halfway of chapter 9)
I am trying to build a simple turn based... | [
"You have a bug.\nThere's not enough details in this (long!) narrative to identify the bug.\nHere's how you fix it:\nbreakpoint()\n\nPut that near the top of your code,\nand use n next, plus p print var,\nto see what your code is doing.\nIt is quicker and more flexible than print( ... ).\nRead up on that pair of co... | [
0
] | [] | [] | [
"if_statement",
"python",
"python_3.x",
"variable_assignment",
"variables"
] | stackoverflow_0074635290_if_statement_python_python_3.x_variable_assignment_variables.txt |
Q:
How to scrape multiple elements within a specific section of a website
Super new to python coming from a C# background.
Inside Microsoft's wiki page, https://en.wikipedia.org/wiki/Microsoft,
I'm trying to scrape all the text inside the history section.
I'm curious how to go about the situation using beautiful so... | How to scrape multiple elements within a specific section of a website | Super new to python coming from a C# background.
Inside Microsoft's wiki page, https://en.wikipedia.org/wiki/Microsoft,
I'm trying to scrape all the text inside the history section.
I'm curious how to go about the situation using beautiful soup. I understand that beautiful soup doesn't have XPath support.
The first e... | [
"Use css selectors, specifically the sibling combinator ~ and the pseudo-classes :has and:not:\nhhSel = 'h2:has(#History)'\nhtSel = f'{hhSel} ~ *:not(style):not(h2):not({hhSel} ~ h2 ~ *)'\nhSectTags = soup.select(htSel)\n\nfor hst in hSectTags:\n flatTxt = ' '.join(w for w in hst.get_text(' ').split() if w)\n ... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074632370_beautifulsoup_python_web_scraping.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.