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:
ValueError: Input 0 of layer "model_10" is incompatible with the layer: expected shape=(None, 244, 244, 3), found shape=(None, 224, 224, 3)
I am training a model on top of the prebuilt imagenetV2 model to classify dog breeds.
Here is my code.
import os
import tensorflow as tf
\_URL = 'http://vision.stanford.edu/... | ValueError: Input 0 of layer "model_10" is incompatible with the layer: expected shape=(None, 244, 244, 3), found shape=(None, 224, 224, 3) | I am training a model on top of the prebuilt imagenetV2 model to classify dog breeds.
Here is my code.
import os
import tensorflow as tf
\_URL = 'http://vision.stanford.edu/aditya86/ImageNetDogs/images.tar'
path_to_zip = tf.keras.utils.get_file('images.tar', origin=\_URL, extract=True)
BATCH_SIZE = 32
IMG_SIZE = (22... | [
"The error is due to the shape mismatch. Your input image is of shape (224, 224, 3) but the shape in the input layer is (244, 244, 3). Both the shapes should be same.\nmodel.add(tf.keras.Input(shape=(224, 224, 3)))\n\nKindly change the input shape as above to avoid the error. Thank you!\n"
] | [
0
] | [] | [] | [
"classification",
"imagenet",
"python",
"tensorflow",
"transfer_learning"
] | stackoverflow_0074405887_classification_imagenet_python_tensorflow_transfer_learning.txt |
Q:
Get key by value in dictionary
I made a function which will look up ages in a Dictionary and show the matching name:
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
if age == search_age:
name = dictionary[age]
print name
I know h... | Get key by value in dictionary | I made a function which will look up ages in a Dictionary and show the matching name:
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
if age == search_age:
name = dictionary[age]
print name
I know how to compare and find the age I jus... | [
"mydict = {'george': 16, 'amber': 19}\nprint mydict.keys()[mydict.values().index(16)] # Prints george\n\nOr in Python 3.x:\nmydict = {'george': 16, 'amber': 19}\nprint(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george\n\nBasically, it separates the dictionary's values in a list, finds the posi... | [
892,
680,
334,
108,
85,
45,
40,
35,
21,
15,
12,
11,
10,
10,
8,
6,
6,
5,
5,
5,
4,
4,
4,
4,
3,
3,
3,
3,
3,
3,
2,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008023306_dictionary_python.txt |
Q:
how can i write comments on some cells of excel sheet using pandas
I didn't find anything that enable me to write comments on some specific cell while writing excel sheet using panadas.to_excel . Any help is appreciated.
A:
After searching for some time, I think the best way to handle comments or other such prop... | how can i write comments on some cells of excel sheet using pandas | I didn't find anything that enable me to write comments on some specific cell while writing excel sheet using panadas.to_excel . Any help is appreciated.
| [
"After searching for some time, I think the best way to handle comments or other such properties like color and size of text at cell or sheet level is to use XlsxWriter with pandas.\nHere is the link to the some nice examples of using XlsxWriter with pandas:\nhttp://xlsxwriter.readthedocs.org/working_with_pandas.ht... | [
4,
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0036397805_pandas_python.txt |
Q:
Determine season given timestamp in Python using datetime
I'd like to extract only the month and day from a timestamp using the datetime module (not time) and then determine if it falls within a given season (fall, summer, winter, spring) based on the fixed dates of the solstices and equinoxes.
For instance, if th... | Determine season given timestamp in Python using datetime | I'd like to extract only the month and day from a timestamp using the datetime module (not time) and then determine if it falls within a given season (fall, summer, winter, spring) based on the fixed dates of the solstices and equinoxes.
For instance, if the date falls between March 21 and June 20, it is spring. Regard... | [
"\nif the date falls between March 21 and June 20, it is spring.\n Regardless of the year. I want it to just look at the month and day\n and ignore the year in this calculation.\n\n#!/usr/bin/env python\nfrom datetime import date, datetime\n\nY = 2000 # dummy leap year to allow input X-02-29 (leap day)\nseasons =... | [
23,
18,
9,
3,
3,
2,
2,
1,
1,
1,
0
] | [] | [] | [
"date",
"python",
"python_2.6"
] | stackoverflow_0016139306_date_python_python_2.6.txt |
Q:
How to set a layout once a matplotlib Figure has been created and what are the possible choices?
Say that I created a Figure with
from matplotlib import pyplot as plt
fig = plt.figure()
and then AFTER I created I want to change its layout (I am aware that I can instantiate the Figure object by passing the argumen... | How to set a layout once a matplotlib Figure has been created and what are the possible choices? | Say that I created a Figure with
from matplotlib import pyplot as plt
fig = plt.figure()
and then AFTER I created I want to change its layout (I am aware that I can instantiate the Figure object by passing the argument layout to plt.figure, e.g. fig = plt.figure(layout="constrained"), which is not what I want).
So far... | [
"You can use the fig.set_layout_engine() with matplolib-3.6.2 :\nAs follows:\nfig = plt.figure()\nfig.set_layout_engine('constrained')\n\nThe possible layouts as per documentation are: 'constrained', 'compressed', 'tight'.\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074528897_matplotlib_python.txt |
Q:
Error tensorflow not getting imported import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow' in python 3.11.0
There is an error coming in importing tensorflow in Python 3.11 in windows 10 in a machine learning project even though I have imported tensorflow via pip.
The code is:
from mlforkids im... | Error tensorflow not getting imported import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow' in python 3.11.0 | There is an error coming in importing tensorflow in Python 3.11 in windows 10 in a machine learning project even though I have imported tensorflow via pip.
The code is:
from mlforkids import MLforKidsImageProject
# treat this key like a password and keep it secret!
key = "the key will not be revealed"
# this will tra... | [
"As per the tested build configurations from the official Tensorflow documentation, Tensorflow 2.10 is compatible with Python versions 3.7 - 3.10. Kindly try again by downgrading the version of Python. You can find the build configurations here. Thank you!\n"
] | [
0
] | [] | [] | [
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0074401578_machine_learning_python_tensorflow.txt |
Q:
How can I classify a column of strings with true and false values by comparing with another column of strings
So I have a column of strings that is listed as "compounds"
Composition (column title)
ZrMo3
Gd(CuS)3
Ba2DyInTe5
I have another column that has strings metal elements from the periodic table and i'll call ... | How can I classify a column of strings with true and false values by comparing with another column of strings | So I have a column of strings that is listed as "compounds"
Composition (column title)
ZrMo3
Gd(CuS)3
Ba2DyInTe5
I have another column that has strings metal elements from the periodic table and i'll call that column "metals"
Elements (column title)
Li
Be
Na
The objective is to check each string from "compounds" with e... | [
"assuming you are using pandas, you can use a list comprehension inside your lambda since you essentially need to iterate over all elements in the elements list\nimport pandas as pd\n\nelements = ['Li', 'Be', 'Na', 'Te']\ncompounds = ['ZrMo3', 'Gd(CuS)3', 'Ba2DyInTe5']\n\ndf = pd.DataFrame(compounds, columns=['comp... | [
2
] | [] | [] | [
"chemistry",
"python"
] | stackoverflow_0074527231_chemistry_python.txt |
Q:
Formulate strict constraints in docplex
I am trying to model the following strict constraint in python with docplex:
mdl.add_constraint(sum(a[i] * mdl.variable[i] for i in range(nrItems)) > b)
but I keep getting the error:
docplex.mp.utils.DOcplexException: Unsupported relational operator: only <=, ==, >= are all... | Formulate strict constraints in docplex | I am trying to model the following strict constraint in python with docplex:
mdl.add_constraint(sum(a[i] * mdl.variable[i] for i in range(nrItems)) > b)
but I keep getting the error:
docplex.mp.utils.DOcplexException: Unsupported relational operator: only <=, ==, >= are allowed
How can one programm a strict constraint... | [
"MIP solvers do not support < and > as these do not make much sense when continuous variables (or relaxations) are involved (both from a mathematical point and from a numerical point of view).\n",
"You could use a small epsilon and turn\nmdl.add_constraint(sum(a[i] * mdl.variable[i] for i in range(nrItems)) > b)\... | [
0,
0
] | [] | [] | [
"constraints",
"docplex",
"mathematical_optimization",
"python"
] | stackoverflow_0074475444_constraints_docplex_mathematical_optimization_python.txt |
Q:
How to sum up values in a dataframe and add them to another one?
I have two dataframes, one for individual transactions and another for the chart of accounts.
I'm trying to sum up all transactions for the last month (in this case, March) for each CompanyKey. I then want to add this result as a new column to the ch... | How to sum up values in a dataframe and add them to another one? | I have two dataframes, one for individual transactions and another for the chart of accounts.
I'm trying to sum up all transactions for the last month (in this case, March) for each CompanyKey. I then want to add this result as a new column to the chart of accounts dataframe with the CompanyKey as the column header.
He... | [
"Here is one way to do it with Pandas groupby and apply:\n# Setup\ndf[\"DateOccurred\"] = pd.to_datetime(df[\"DateOccurred\"], format=\"%d/%m/%Y\")\n\n# Sum transactions per companies and accounts\ndf_sum = (\n df.loc[df[\"DateOccurred\"].dt.month == 3, :]\n .groupby([\"CompanyKey\", \"Account.Name\"])\n .... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074426326_pandas_python.txt |
Q:
Can't add exploded data in mysql database with pandas
I want to insert in my database exploded data using pandas but I get an error, can someone help
My Code
tactic_theme = pandas.read_csv(link, usecols=(0, 7))
tactic_theme.columns = ['code_tac', 'code_th']
tactic_theme['code_th'] = tactic_theme.code_th.str.split... | Can't add exploded data in mysql database with pandas | I want to insert in my database exploded data using pandas but I get an error, can someone help
My Code
tactic_theme = pandas.read_csv(link, usecols=(0, 7))
tactic_theme.columns = ['code_tac', 'code_th']
tactic_theme['code_th'] = tactic_theme.code_th.str.split(" ")
tactic_theme.explode('code_th')
tactic_theme.to_sql(... | [
"I just saw the error,on the line tactic_theme.explode('code_th') i should write\ntactic_theme = tactic_theme.explode('code_th')\n\n"
] | [
0
] | [] | [] | [
"mysql",
"pandas",
"python"
] | stackoverflow_0074474274_mysql_pandas_python.txt |
Q:
Module "Numpy" not found despite already installed in system
I have a problem thats been stumping me for days. I wanted to run this GAIN program on my local system though command line (https://github.com/jsyoon0823/GAIN) so I downloaded it, installed Python for the first time because
Python was not found; run with... | Module "Numpy" not found despite already installed in system | I have a problem thats been stumping me for days. I wanted to run this GAIN program on my local system though command line (https://github.com/jsyoon0823/GAIN) so I downloaded it, installed Python for the first time because
Python was not found; run without arguments to install from the Microsoft Store, or disable this... | [
"The following command worked for me:\n\npython.exe -m pip install numpy\n\nOr:\nDownload and install\nhttp://sourceforge.net/projects/numpy/files/NumPy/\n$ tar xfz numpy-n.m.tar.gz\n$ cd numpy-n.m\n$ python setup.py install\n\n",
"I uninstalled Python 3.10 Microsoft Store, installed Python 3.10 for Windows from ... | [
0,
0
] | [] | [] | [
"numpy",
"path",
"python",
"python_3.x",
"virtualenv"
] | stackoverflow_0074528129_numpy_path_python_python_3.x_virtualenv.txt |
Q:
Guessing a missing value based on historical data
Let's assume i have 100 different kinds of items, each item got a name and a physical weight.
I know the names of all 100 items but only the weight of 80 items.
When i ship items, i pack them in groups of 10 and sum the weight of these items.
Due to some items are ... | Guessing a missing value based on historical data | Let's assume i have 100 different kinds of items, each item got a name and a physical weight.
I know the names of all 100 items but only the weight of 80 items.
When i ship items, i pack them in groups of 10 and sum the weight of these items.
Due to some items are missing their weight, this will give an inaccurate sum ... | [
"Forget about machine learning. This is a simple system of linear equations.\nw_71 + w_77 = 25\nw_71 + w_92 = 40\nw_77 = 15\n\nYou can solve it with sympy.solvers.solveset.linsolve, or scipy.optimize.linprog, or scipy.linalg.lstsq, or numpy.linalg.lstsq\n\nsympy.linsolve is maybe the easiest to understand if you ar... | [
0
] | [] | [] | [
"machine_learning",
"math",
"python"
] | stackoverflow_0074526673_machine_learning_math_python.txt |
Q:
How to split a file by using string as identifier with python?
I have a huge text file and need to split it to some file.
In the text file there is an identifier to split the file.
Here is some part of the text file looks like:
Comp MOFVersion 10.1
Copyright 1997-2006. All rights reserved.
------------------------... | How to split a file by using string as identifier with python? | I have a huge text file and need to split it to some file.
In the text file there is an identifier to split the file.
Here is some part of the text file looks like:
Comp MOFVersion 10.1
Copyright 1997-2006. All rights reserved.
--------------------------------------------------
Mon 11/19/2022 8:34:22.35 - Starting The... | [
"Well if the file is small enough to comfortably fit into memory (say 1GB or less), you could read the entire file into a string and then use re.findall:\nwith open('data.txt', 'r') as file:\n data = file.read()\n parts = re.findall(r'-{10,}[^-]*\\n\\w{3} \\d{2}\\/\\d{2}\\/\\d{4}.*?-{10,}.*?(?=-{10,}|$)', dat... | [
1,
0
] | [] | [] | [
"filesplitting",
"mapping",
"python",
"string"
] | stackoverflow_0074530313_filesplitting_mapping_python_string.txt |
Q:
ModuleNotFoundError: No module named 'keras' for Jupyter Notebook
I was running Jupyter Notebook and the following error occurs
ModuleNotFoundError
Traceback (most recent call last)
in
---->
from keras.models import Sequential
from keras.layers import (
Conv2D, MaxPooling2D, Flatten, Dense, Dr... | ModuleNotFoundError: No module named 'keras' for Jupyter Notebook | I was running Jupyter Notebook and the following error occurs
ModuleNotFoundError
Traceback (most recent call last)
in
---->
from keras.models import Sequential
from keras.layers import (
Conv2D, MaxPooling2D, Flatten, Dense, Dropout)
ModuleNotFoundError: No module named 'keras'
I have tried using... | [
"You have to install all the dependencies first before using it.\nTry using \n\nconda install tensorflow\nconda install keras\n\nby installing it with conda command it manage your versions compatibility with other libraries.\nwith pip install libraries will only install in your current environment and the latest ve... | [
14,
11,
1,
0,
0,
0
] | [] | [] | [
"anaconda",
"jupyter_notebook",
"keras",
"python"
] | stackoverflow_0056641165_anaconda_jupyter_notebook_keras_python.txt |
Q:
Save dict as json using python in databricks
I am trying to save a dict as json in azure data lake/databricks however I am getting a File not found error. Any clue what I am doing wrong?
import json
test_config = {
"expectations": [
{
"kwargs": {
"column": "role",
"value_set": [
... | Save dict as json using python in databricks | I am trying to save a dict as json in azure data lake/databricks however I am getting a File not found error. Any clue what I am doing wrong?
import json
test_config = {
"expectations": [
{
"kwargs": {
"column": "role",
"value_set": [
"BBV",
"GEM"
]
},
... | [
"Ensure your python environment sees the mountpoint.\nYou can use os.path.ismount for that.\nAlso, check if the folder tree structure exists. json.dumps will create your file, but only if the folder exists.\nAlso, tip: to keep indentation, use indent=2 or whatever number of spaces you want in your json, to be prett... | [
1,
1,
0
] | [] | [] | [
"azure_data_lake",
"databricks",
"json",
"python"
] | stackoverflow_0074525326_azure_data_lake_databricks_json_python.txt |
Q:
Writing the requirements/setup file for a Python package
Are there any best practices on how to select the versions of the required packages for your own python package?
You can always do pip freeze > requirements.txt, but this will set every used package to a specific version.
If this package is used with another... | Writing the requirements/setup file for a Python package | Are there any best practices on how to select the versions of the required packages for your own python package?
You can always do pip freeze > requirements.txt, but this will set every used package to a specific version.
If this package is used with another one using the same requirement with a different specific vers... | [
"In the packaging metadata of your library (in other words: in the setup.py, setup.cfg, or pyproject.toml), only the direct dependencies should be listed. The direct dependencies are the ones that are directly imported by the library's code (and the ones that are called in sub-processes, but that is quite a rare ca... | [
1
] | [] | [] | [
"python",
"python_packaging",
"requirements.txt"
] | stackoverflow_0074525503_python_python_packaging_requirements.txt.txt |
Q:
Is there any way to define app.Table without using Record in faust?
I'm currently using schema registry and faust to process stream data.
The reason I try to avoid using faust.Record is the schema can be dynamically changed and I don't like to change the code(class inheriting faust.Record) every time it happend.
B... | Is there any way to define app.Table without using Record in faust? | I'm currently using schema registry and faust to process stream data.
The reason I try to avoid using faust.Record is the schema can be dynamically changed and I don't like to change the code(class inheriting faust.Record) every time it happend.
But without faust.Record, it looks like there are many restrictions.
For e... | [
"Short answer: No, you're right, you cannot define relative_to_field without a FieldDescriptor. You can check the definiton of relative_to_field here. Then, this field is extracted here with a getattr, you need a faust.Record for this operation.\nHowever, as you use Avro you may use the library dataclasses-avrosche... | [
0
] | [] | [] | [
"faust",
"python"
] | stackoverflow_0074062969_faust_python.txt |
Q:
How to use multiple urls with PIP_EXTRA_INDEX_URL
I want to configure my pip using environmental variables. I already have two pip index urls. So I'm already using PIP_INDEX_URL and PIP_EXTRA_INDEX_URL variables.
PIP_INDEX_URL="https://example.com"
PIP_EXTRA_INDEX_URL="https://example2.com"
But I want to add one ... | How to use multiple urls with PIP_EXTRA_INDEX_URL | I want to configure my pip using environmental variables. I already have two pip index urls. So I'm already using PIP_INDEX_URL and PIP_EXTRA_INDEX_URL variables.
PIP_INDEX_URL="https://example.com"
PIP_EXTRA_INDEX_URL="https://example2.com"
But I want to add one more index url. I don't know how
I tried to add it with... | [
"Pip expects an empty space ( ) to separate the values in environment variables. In this case, for example:\nPIP_EXTRA_INDEX_URL=\"https://example2.com https://example3.com\"\n\nSee pip's documentation section \"Environment variables\".\n"
] | [
1
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074525250_pip_python.txt |
Q:
Remove last symbol in row
My code is:
n = 3
for i in range(1, n+1):
for j in range(1, n+1):
print(j*i, end='*')
print(end='\b\n')
Result of this code is:
1*2*3*
2*4*6*
3*6*9*
But I need expected result like this (without aesthetics in end of rows):
1*2*3
2*4*6
3*6*9
A:
Use '*'.join() instead of... | Remove last symbol in row | My code is:
n = 3
for i in range(1, n+1):
for j in range(1, n+1):
print(j*i, end='*')
print(end='\b\n')
Result of this code is:
1*2*3*
2*4*6*
3*6*9*
But I need expected result like this (without aesthetics in end of rows):
1*2*3
2*4*6
3*6*9
| [
"Use '*'.join() instead of the end parameter in print()\nfor i in range(1, n + 1):\n print('*'.join(f'{j * i}' for j in range(1, n + 1)), end='\\n')\n\nOutput\n1*2*3\n2*4*6\n3*6*9\n\n"
] | [
0
] | [
"Just check if you're not at the last value in the range. If you aren't print '*' if you are don't do anything. View the below code for clarification.\nn = 3\nfor i in range(1, n+1):\n for j in range(1, n+1):\n print(j*i, end='')\n if j != n:\n print('*', end='')\n print(end='\\b\\n')\... | [
-1,
-1,
-1
] | [
"python"
] | stackoverflow_0074530598_python.txt |
Q:
Element Tree - Iterate dictionary to append elements to new line xml
I am attempting to append elements to an existing .xml using ElementTree.
I have the desired attributes stored as a list of dictionaries:
myDict = [{"name": "dan",
"age": "25",
"subject":"maths"},
{"name": "susan",... | Element Tree - Iterate dictionary to append elements to new line xml | I am attempting to append elements to an existing .xml using ElementTree.
I have the desired attributes stored as a list of dictionaries:
myDict = [{"name": "dan",
"age": "25",
"subject":"maths"},
{"name": "susan",
"age": "27",
"subject":"english"},
{"name... | [
"With pointers from here (Thanks @Thicc_Gandhi), I solved it by amending the iteration to:\nfor x,y in enumerate(MyDict):\n elem = ET.Element(\"student\",attrib=myDict[x])\n elem.tail = \"\\n\"\n root.append(elem)\n\n"
] | [
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0074530128_elementtree_python_xml.txt |
Q:
Set the value in Selenium with python
I'm trying to set the value in this field
This is the inpect code:
<dnx-textfield label="First / Leading IP Address" placeholder="" name="primaryIpv4Address" hint="" maxwidth="300px" error="" regex="" message="" validator="" regextype="" type="text" validateon="onblur" hinthel... | Set the value in Selenium with python | I'm trying to set the value in this field
This is the inpect code:
<dnx-textfield label="First / Leading IP Address" placeholder="" name="primaryIpv4Address" hint="" maxwidth="300px" error="" regex="" message="" validator="" regextype="" type="text" validateon="onblur" hinthelper="" inputid="management-DnxTextfield-dep... | [
"Below is the Java code using which you can do it. You need to use java script executor.\n WebElement element = driver.findElement(By.xpath(\"enter the xpath here\"));\n JavascriptExecutor jse = (JavascriptExecutor)driver;\n jse.executeScript(\"arguments[0].value='enter the value here';\", element);\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074530221_python_selenium_selenium_webdriver.txt |
Q:
Select during vs. after insert produces different results
My database is written to every second during certain hours. It's also read from during same hours, every minute.
The read outputs different values during operational hours vs. after hours. Might be data is not written when I read. How to fix this or make s... | Select during vs. after insert produces different results | My database is written to every second during certain hours. It's also read from during same hours, every minute.
The read outputs different values during operational hours vs. after hours. Might be data is not written when I read. How to fix this or make sure data for last minute is complete before reading? Would a di... | [
"While SQLite does not support full concurrency, it doesn't mean that it can't correctly address your needs. Using Postgress or a different DB could actually worsen the problem.\nSqlite is highly reliable and is absolutely deterministic in its behaviour and is fully capable of handling scenarios with one writer and... | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074525915_python_sqlite.txt |
Q:
import cv2 in python in vs code not working
The python code I wanted to run:
import cv2
print(cv2.__verion__)
The Error code I am getting:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS D:\Program... | import cv2 in python in vs code not working | The python code I wanted to run:
import cv2
print(cv2.__verion__)
The Error code I am getting:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS D:\Programme\Visual Studio\New Projects> & C:/Users/Florian... | [
"I had the same issue in VScode using python 3.9.6. I switched to python 3.10.7 and it worked fine.\n",
"in your VScode press Ctrl+Shift+P and then type \"Python: Select Interpreter\" then select your python Interpreter and Run it again.\n",
"Try running\npip3.10 install opencv-python.\nBecause:\n\ncv2 is a par... | [
1,
0,
0
] | [] | [] | [
"opencv",
"python",
"visual_studio_code"
] | stackoverflow_0070451971_opencv_python_visual_studio_code.txt |
Q:
google colab import imagemagick PolicyError: not authorized `file.pdf'
used google colab. had to install imagemagick as a dependency for pdfplumber lib to work.
!apt install imagemagick
also
!pip install pdfplumber
then my code looked like this -
pdf = pdfplumber.open("file.pdf") # Import the PDF.
page = pdf.pag... | google colab import imagemagick PolicyError: not authorized `file.pdf' | used google colab. had to install imagemagick as a dependency for pdfplumber lib to work.
!apt install imagemagick
also
!pip install pdfplumber
then my code looked like this -
pdf = pdfplumber.open("file.pdf") # Import the PDF.
page = pdf.pages[0]
im = page.to_image()
im
when running this piece of code got this err... | [
"found this answer helpful (with the help of pdfplumber team)\ngoing into etc/ImageMagick-6/policy.xml\nHad to change this:\n<policy domain=\"coder\" rights=\"none\" pattern=\"PDF\"/>\n\nto this:\n<policy domain=\"coder\" rights=\"read|write\" pattern=\"PDF\"/>\n\nthen ran again and the photo appeared. Solved it fo... | [
1
] | [] | [] | [
"google_colaboratory",
"imagemagick",
"pdf",
"python"
] | stackoverflow_0074530824_google_colaboratory_imagemagick_pdf_python.txt |
Q:
Changing a column type in a very large pandas dataframe is too slow
I have a very large dataframe, around 80GB. I want to change the type of some of its columns from object to category. Trying to do it this way:
df[col_name] = df[col_name].astype('category')
Takes around 1 minute per column, which is a lot. My f... | Changing a column type in a very large pandas dataframe is too slow | I have a very large dataframe, around 80GB. I want to change the type of some of its columns from object to category. Trying to do it this way:
df[col_name] = df[col_name].astype('category')
Takes around 1 minute per column, which is a lot. My first question would be why does it take that long?
Just running:
df[col_n... | [
"You could use something like\ndf['col_name'].values.astype('category')\n\n",
"If reassigning the column was the slow operation, doing the conversion in-place should speed up the process :\ndf[col_name].astype('category', inplace = True)\n\n"
] | [
0,
0
] | [] | [] | [
"dataframe",
"dtype",
"pandas",
"python"
] | stackoverflow_0072807703_dataframe_dtype_pandas_python.txt |
Q:
How do I redirect from one flask app to another flask app with url parameters
I have a Python application in which for one specific API, I am trying to redirect it to another API present in another Flask application. To achieve this, I am using the below code:
`
@app.route('/hello')
def hello_name(name):
retur... | How do I redirect from one flask app to another flask app with url parameters | I have a Python application in which for one specific API, I am trying to redirect it to another API present in another Flask application. To achieve this, I am using the below code:
`
@app.route('/hello')
def hello_name(name):
return redirect("http://localhost:8000/hello", 302)
`
Now, if I try to access my API by... | [] | [] | [
"Try to use HTTP status code 307 Internal Redirect instead of 302 like below:-\n@app.route('/hello/')\ndef hello_name(name):\n return redirect(url_for('http://localhost:8000/hello', args1=name), code=307)\n\n"
] | [
-1
] | [
"flask",
"flask_restful",
"python",
"python_3.x",
"redirect"
] | stackoverflow_0074528621_flask_flask_restful_python_python_3.x_redirect.txt |
Q:
How can I use my tensorflow/keras CNN model to predict from my camera (that I loaded in) with this code?
code for predicting on live camera
It's fairly simple what I am trying to do, loading my tensorflow AI from file. trying to use it to predict on my live webcam (through google.colab).
I am trying to predict wit... | How can I use my tensorflow/keras CNN model to predict from my camera (that I loaded in) with this code? | code for predicting on live camera
It's fairly simple what I am trying to do, loading my tensorflow AI from file. trying to use it to predict on my live webcam (through google.colab).
I am trying to predict with the AI I made (using the code in the link), saved and loaded (using tensorflow: model.save and load_model)
I... | [
"You can use tensorflow.image.resize API to resize the image. The error could be due to a shape mismatch between the Input Layer's shape and the shape of the image that is passed to the model while predicting.\nimport tensorflow as tf \n\nimg=tf.keras.utils.load_img(path of the image)\nimg=tf.keras.utils.img_to_arr... | [
0
] | [] | [] | [
"artificial_intelligence",
"conv_neural_network",
"python",
"tensorflow",
"webcam"
] | stackoverflow_0074511932_artificial_intelligence_conv_neural_network_python_tensorflow_webcam.txt |
Q:
Averaging of several values
I have a dataset (df3) with five columns x, y, r, g and b, although I only need to work with x, y and r. I want to find the average of all the consecutive rows in which the value of r is equal and store it in a database (df_final). To do this, I have generated a code that stores all the... | Averaging of several values | I have a dataset (df3) with five columns x, y, r, g and b, although I only need to work with x, y and r. I want to find the average of all the consecutive rows in which the value of r is equal and store it in a database (df_final). To do this, I have generated a code that stores all the values in which r is equal to th... | [
"You may want to append to the end of the dataframe using\n\ndf_inter = df_inter.append({'x':df3.iloc[i,1],'y':df3.iloc[i,2],'r':df3.iloc[i,3]}, ignore_index=True)\n\n\n",
"If you have some knowledge of SQL, it can be intuitively done using sqldf and pandas:\nimport sqldf\nimport pandas as pd\n\ndf = pd.DataFrame... | [
0,
0
] | [] | [] | [
"database",
"pandas",
"python"
] | stackoverflow_0074530800_database_pandas_python.txt |
Q:
How to get calendar years as column names and month and day as index for one timeseries
I have looked for solutions but seem to find none that point me in the right direction, hopefully, someone on here can help. I have a stock price data set, with a frequency of Month Start. I am trying to get an output where the... | How to get calendar years as column names and month and day as index for one timeseries | I have looked for solutions but seem to find none that point me in the right direction, hopefully, someone on here can help. I have a stock price data set, with a frequency of Month Start. I am trying to get an output where the calendar years are the column names, and the day and month will be the index (there will onl... | [
"You might want to split the date into month and year and to apply a pivot:\ns = pd.to_datetime(df.index)\n\nout = (df\n .assign(year=s.year, month=s.month)\n .pivot_table(index='month', columns='year', values='Close', fill_value=0)\n)\n\noutput:\nyear 2003 2004\nmonth \n1 0 2\n2 0... | [
3,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074530461_dataframe_pandas_python_python_3.x.txt |
Q:
Proper way to implement user input with Sympy?
I am currently working on creating a python script that will do a series of calculations based on the formula entered by the user; however, it is not working as expected?
I have tried the following:
init_printing(use_unicode=True)
x, y = symbols('x y', real = True)
u... | Proper way to implement user input with Sympy? | I am currently working on creating a python script that will do a series of calculations based on the formula entered by the user; however, it is not working as expected?
I have tried the following:
init_printing(use_unicode=True)
x, y = symbols('x y', real = True)
userinput = sympify(input("testinput: "))
x_diff = d... | [
"Adding locals parameter in sympify function will help you. Here is a working code, based on yours :\nfrom sympy import *\n\ninit_printing(use_unicode=True)\n\nx, y = symbols('x y', real = True)\nuserinput = input(\"testinput: \")\nlocals = {'x':x, 'y':y}\nsympified = sympify(userinput, locals=locals)\nprint(f'deri... | [
3
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074530358_python_sympy.txt |
Q:
is it possible to override the size of a frame when something is inside?
I am trying to have two identically sized frames inside a grid, like this:
enter image description here
i have control over the frame's size when nothing is in it but when i add something into the frame, i lose control over the size itself an... | is it possible to override the size of a frame when something is inside? | I am trying to have two identically sized frames inside a grid, like this:
enter image description here
i have control over the frame's size when nothing is in it but when i add something into the frame, i lose control over the size itself and it adapts to the size of stuff placed in it. Any way to control the size of ... | [
"By default, when adding widgets to a frame using .grid() or .pack(), the size of the frame will be adjusted to fit all the widgets.\nTo change this default behavior, call .grid_propagate(0) or .pack_propagate(0) on the frame.\nFor your case, as .grid() is used on those widgets inside hrac_f frame, then hrac_f.grid... | [
0,
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_layout"
] | stackoverflow_0074528690_python_tkinter_tkinter_layout.txt |
Q:
I want to create lookup data using apache_beam.utils.shared module but it gives error TypeError: cannot create weak reference to 'list' object
`
import apache_beam as beam
from apache_beam.utils import shared
from log_elements import LogElements
class GetNthStringFn(beam.DoFn):
def __init__(self, shared_handle)... | I want to create lookup data using apache_beam.utils.shared module but it gives error TypeError: cannot create weak reference to 'list' object | `
import apache_beam as beam
from apache_beam.utils import shared
from log_elements import LogElements
class GetNthStringFn(beam.DoFn):
def __init__(self, shared_handle):
self._shared_handle = shared_handle
def process(self, element):
def initialize_list():
# Build the giant initial list.
retu... | [
"You don't reference the good link and version, the Beam version 2.24.0 is too old.\nCheck with this code and this link :\n# Several built-in types such as list and dict do not directly support weak\n# references but can add support through subclassing:\n# https://docs.python.org/3/library/weakref.html\nclass WeakR... | [
2
] | [] | [] | [
"apache_beam",
"google_cloud_dataflow",
"python"
] | stackoverflow_0074528574_apache_beam_google_cloud_dataflow_python.txt |
Q:
Can anyone reduce time complexity of this code
You are given three integers A, B, and C. You are allowed to perform the following operation any number of times (possibly zero).
• Choose any integer X such that X ≤ max (A,B, C), and replace A with
A^X, B with B^X, and C with C^X.
Here denote Bitwise XOR operation.
... | Can anyone reduce time complexity of this code | You are given three integers A, B, and C. You are allowed to perform the following operation any number of times (possibly zero).
• Choose any integer X such that X ≤ max (A,B, C), and replace A with
A^X, B with B^X, and C with C^X.
Here denote Bitwise XOR operation.
Find the maximum possible value of A+B+C.
A=2
B=2
C=... | [
"Try this:\ndef max_sum(a, b, c):\n for j in range(int.bit_length(max(a, b, c))):\n x = 2**j if sum((n & 2**j) >> j for n in (a, b, c)) < 2 else 0\n a = a ^ x\n b = b ^ x\n c = c ^ x\n return a + b + c\n\nSo here you perform a number of operations equal to the number of bits of the... | [
0
] | [] | [] | [
"binary_search",
"linear_search",
"max",
"python",
"sum"
] | stackoverflow_0074522895_binary_search_linear_search_max_python_sum.txt |
Q:
I can't able to install the psycopg2 in python 3.10.8 in ubuntu-20 | ./psycopg/psycopg.h:36:10: fatal error: libpq-fe.h: No such file or directory
I'm Using python3.10.8 & ubuntu-20, i have tried so many commands But I can't able to fixe that.
Error:
r-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fst... | I can't able to install the psycopg2 in python 3.10.8 in ubuntu-20 | ./psycopg/psycopg.h:36:10: fatal error: libpq-fe.h: No such file or directory | I'm Using python3.10.8 & ubuntu-20, i have tried so many commands But I can't able to fixe that.
Error:
r-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DPSYCOPG_VERSION=2.9.1 (dt dec pq3 ext lo64) -DPSYCOPG_DEBU... | [
"try\npip install psycopg2-binary\n\nor you can try this\nsudo apt-get install libpq-dev\n\n"
] | [
1
] | [] | [] | [
"psycopg2",
"python"
] | stackoverflow_0074530944_psycopg2_python.txt |
Q:
Python: how to merge two pandas dataframes with condition
I have two dataframes like the following
df1
A B
0 0 3
1 0 2
2 1 5
3 1 3
4 2 5
5 'Ciao' 'log'
6 3 4
df2
A B
0 0 -1
1 0 20
2 1 -2
3 1 33
4 2 1... | Python: how to merge two pandas dataframes with condition | I have two dataframes like the following
df1
A B
0 0 3
1 0 2
2 1 5
3 1 3
4 2 5
5 'Ciao' 'log'
6 3 4
df2
A B
0 0 -1
1 0 20
2 1 -2
3 1 33
4 2 17
I want to merge the two dataframes in order that the if A==... | [
"Assuming the dataframes are aligned (and that the duplicated index 3 in df1 is a typo), you do not want a merge but rather a conditional using where:\nout = df1.where(df1['A'].eq(0), df2)\n\nOutput:\n A B\n0 0 3\n1 0 2\n2 1 -2\n3 1 33\n4 2 17\n\nNB. if you really want a merge, you have to further e... | [
4
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074530992_pandas_python.txt |
Q:
Changing the Dataframe to a TimeSeries Array [Python]
I'm trying to change a date frame with the following contents:
Date
Change
1802
2017-09-14
-1.14%
462
2021-05-16
NaN
935
2020-01-29
0.04%
713
2020-09-07
2.39%
1471
2018-08-11
NaN
[1460 rows × 2 columns]
Into this:
TimeSeries (DataArray) (Month: 144compon... | Changing the Dataframe to a TimeSeries Array [Python] | I'm trying to change a date frame with the following contents:
Date
Change
1802
2017-09-14
-1.14%
462
2021-05-16
NaN
935
2020-01-29
0.04%
713
2020-09-07
2.39%
1471
2018-08-11
NaN
[1460 rows × 2 columns]
Into this:
TimeSeries (DataArray) (Month: 144component: 1sample: 1)
array([[[112.]],
[[118.]]... | [
"The solution required removing the '%' sign from the column values. Then converting the column to a float.\nftse_change['Change'] = ftse_change['Change'].str.rstrip('%').astype('float') / 100.0\n\ndid the trick\n\n"
] | [
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074482778_arrays_python.txt |
Q:
StopIteration Error in pythoncode while reading csv data
I am writing a program to read csv file. I have craeted a reader object and calling next() on it gives me the header row. But when I am calling it again it gives StopIteration error although there are rows in the csv file.I am doing file.seek(0) then it is w... | StopIteration Error in pythoncode while reading csv data | I am writing a program to read csv file. I have craeted a reader object and calling next() on it gives me the header row. But when I am calling it again it gives StopIteration error although there are rows in the csv file.I am doing file.seek(0) then it is working fine. Anyone please explains this to me? A snapshot of ... | [
"You're calling next once for each column (except the first two). So, if you have, say, 10 columns, it's going to try to read 8 rows.\nIf you have 20 rows, that's not going to raise an exception, but you'll be ignoring the last 12 rows, which you probably don't want. On the other hand, if you have only 5 rows, it's... | [
4,
0
] | [
"Why didn't you write:\nheader = next(reader)\n\nIn the last line as well? I don't know if this is your problem, but I would start there.\n"
] | [
-1
] | [
"csv",
"iterator",
"python"
] | stackoverflow_0019205807_csv_iterator_python.txt |
Q:
Merge 2 CSV files with no common column
I have 2 csv files( 2 million each) with below structure
first.csv
h1,h2
2,3
4,5
second.csv
h3,h4
5,6
7,8
I want to merge these 2 csv index wise column like below
merged.csv
h1,h2,h3,h4
2,3,5,6
4,5,7,8
A:
You might be looking for the pandas.concat() function (see here)... | Merge 2 CSV files with no common column | I have 2 csv files( 2 million each) with below structure
first.csv
h1,h2
2,3
4,5
second.csv
h3,h4
5,6
7,8
I want to merge these 2 csv index wise column like below
merged.csv
h1,h2,h3,h4
2,3,5,6
4,5,7,8
| [
"You might be looking for the pandas.concat() function (see here). Here is an example:\nimport pandas as pd\n\ndf1 = pd.DataFrame({'A':[0,0,1,1,2],'B':[3,2,5,3,5]})\ndf2 = pd.DataFrame({'C':[0,0,1,1,2],'D':[-1,20,-2,33,17]})\n\ndf3 = pd.concat((df1,df2),axis=1)\n\ndf3.to_csv('myFile.csv')\n\nYou just have to replac... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074531045_python_python_3.x.txt |
Q:
Insert a 2 horizontal lines on a bar plot
I am trying to insert 2 lines on a bar plot with the following code:
PosisEink_Liq['weights'].plot(kind='bar',color=('darkgray'))
PosisEink_Liq['TAA+1'].plot(kind='line',color=('black'),linestyle = '--')
PosisEink_Liq['TAA-1'].plot(kind='line',color=('black'),linestyle = '... | Insert a 2 horizontal lines on a bar plot | I am trying to insert 2 lines on a bar plot with the following code:
PosisEink_Liq['weights'].plot(kind='bar',color=('darkgray'))
PosisEink_Liq['TAA+1'].plot(kind='line',color=('black'),linestyle = '--')
PosisEink_Liq['TAA-1'].plot(kind='line',color=('black'),linestyle = '--')
Unfortunately, the 2 horizontal lines do ... | [
"Use\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50] #Size of Graph\nplt.rcParams[\"figure.autolayout\"] = True\nfig, ax = plt.subplots() #For multiple subplots\n\n"
] | [
1
] | [] | [] | [
"charts",
"graph",
"line",
"pandas",
"python"
] | stackoverflow_0074530748_charts_graph_line_pandas_python.txt |
Q:
color raws in xls with python with conditions
I would like to color raws of file.xls according to 3 parameters:
if a raw contain 'freq' value between 0.11 and 0.5 and has common mutation and gene patterns from 'list1' then color the raw in yellow
if a raw contain 'freq' value between 0.51 and 1 and has common mut... | color raws in xls with python with conditions | I would like to color raws of file.xls according to 3 parameters:
if a raw contain 'freq' value between 0.11 and 0.5 and has common mutation and gene patterns from 'list1' then color the raw in yellow
if a raw contain 'freq' value between 0.51 and 1 and has common mutation and gene patterns from 'list1' then color the... | [
"This is just an example on how to deal with conditional formatting:\nwb = openpyxl.load_workbook('file.xlsx') \nws = wb.worksheets[0]\n\ndef Color(s, t):\n yellow = \"FFFFFF00\"\n red = \"00FF0000\"\n blue = \"000000FF\"\n if s == 'C' and t == 'A': return openpyxl.styles.colors.Color(rgb=yellow) \n ... | [
1
] | [] | [] | [
"loops",
"openpyxl",
"python"
] | stackoverflow_0074530226_loops_openpyxl_python.txt |
Q:
Python Packages not installed
In Python, I was using Spacy library there was trying below commands:-
import spacy
Getting Below Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'spacy'
Then tried to install spacy using below command:-
pip install ... | Python Packages not installed | In Python, I was using Spacy library there was trying below commands:-
import spacy
Getting Below Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'spacy'
Then tried to install spacy using below command:-
pip install spacy
Message:
It gives Requirement... | [
"Try pip install -U spacy and python -m spacy download en_core_web_sm\n",
"\nSpacy module is a bit more finicky than others\nhttps://spacy.io/usage <-- use this guide to generate the terminal code to install the correct version.\nThis is just an example from the above code generator link.\nYou need to generate th... | [
0,
0
] | [
"Try running !pip install spacy in a cell in your notebook.\nIf that doesn't work, it might be possible that your terminal is in different environment and code is running in different environment. Activate same environment in both cases.\n"
] | [
-1
] | [
"python",
"spacy"
] | stackoverflow_0074531051_python_spacy.txt |
Q:
Function & Method description on call
I am trying to describe my functions and class methods.
What I mean is that you can force function/methods to control input and outputvalues if the type of the data is the same as defined one.
Basic definition could look like this:
def SWE4_UT1_complex(root: os.path | PurePath... | Function & Method description on call | I am trying to describe my functions and class methods.
What I mean is that you can force function/methods to control input and outputvalues if the type of the data is the same as defined one.
Basic definition could look like this:
def SWE4_UT1_complex(root: os.path | PurePath) -> (float | int, str | int): ...
First ... | [
"Did you try just defining it as 'list[KPI]' this would be a list of KPI instances. (quotations needed around the type because: \"Subscript for class \"list\" will generate runtime exception; enclose type annotation in quotes\")\nApologies if this is not what you were asking.\n"
] | [
1
] | [] | [] | [
"python",
"python_3.10",
"python_3.x"
] | stackoverflow_0074530700_python_python_3.10_python_3.x.txt |
Q:
Finding specific cell inside Pandas Dataframe based on most similar column and index labels (when compared to references)
I have dataframe with around 500 columns and 300 rows and it looks like the example below. I need to select specific dataframe cell based on most similar column label and index label when com... | Finding specific cell inside Pandas Dataframe based on most similar column and index labels (when compared to references) | I have dataframe with around 500 columns and 300 rows and it looks like the example below. I need to select specific dataframe cell based on most similar column label and index label when compared to a reference.
Let me explain my problem:
Let's say that I need to find a cell which has column label most similar to re... | [
"Assuming you fix you columns' Index to be 1D:\ndf1.columns = my_columns[0]\n# Float64Index([0.447852, 0.568911395, 0.31997079, 0.451030185, 0.45208958], dtype='float64')\n\nYou can use the minimal absolute difference to your target:\nimport numpy as np\n\nout = df1.iloc[np.argmin(abs(df1.index-y)), np.argmin(abs(d... | [
3
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074530609_dataframe_numpy_pandas_python.txt |
Q:
Importing the numpy C-extensions failed Azure function
When running one of my functions which includes pandas, I get the following error message:
Result: Failure Exception: ImportError: Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the n... | Importing the numpy C-extensions failed Azure function | When running one of my functions which includes pandas, I get the following error message:
Result: Failure Exception: ImportError: Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many rea... | [
"I have created the Azure Functions Python Version 3.9.13 with the below packages Pandas and NumPy as 1.5.1 and 1.23.5:\n\nWritten the sample code that uses pandas and NumPy packages and it is working as expected:\nimport logging\nimport pandas as pd\nimport numpy as np \nimport azure.functions as func\n... | [
0
] | [] | [] | [
"azure_functions",
"numpy",
"python"
] | stackoverflow_0074493372_azure_functions_numpy_python.txt |
Q:
ShapelyDeprecationWarnings and the use of "geoms"
Some lines to look up geographical information by given pair of coordinates, referenced from https://gis.stackexchange.com/questions/254869/projecting-google-maps-coordinate-to-lookup-country-in-shapefile.
import geopandas as gpd
from shapely.geometry import Point
... | ShapelyDeprecationWarnings and the use of "geoms" | Some lines to look up geographical information by given pair of coordinates, referenced from https://gis.stackexchange.com/questions/254869/projecting-google-maps-coordinate-to-lookup-country-in-shapefile.
import geopandas as gpd
from shapely.geometry import Point
pt = Point(8.7333333, 53.1333333)
# countries shapef... | [
"Let's start by examining the geometry column with data.geometry. This reveals that the geometry contains normal polygons and multipolygons.\n0 MULTIPOLYGON (((-61.68667 17.02444, -61.88722 ...\n1 POLYGON ((2.96361 36.80222, 4.78583 36.89472, ...\n...\n\nNew answer\nThe error is only caused by Geopandas d... | [
1
] | [] | [] | [
"geopandas",
"python",
"shapely"
] | stackoverflow_0074529728_geopandas_python_shapely.txt |
Q:
How to get pytest-cov only if total coverage lower then 90%
So as I understood, pytest-cov has an option to fail if total coverage is lower than some %. But can I output hole tablet only in case if total cov is lower then 90% and if it is upper it won't show anything?
Example of command line code
A:
pytest-cov d... | How to get pytest-cov only if total coverage lower then 90% | So as I understood, pytest-cov has an option to fail if total coverage is lower than some %. But can I output hole tablet only in case if total cov is lower then 90% and if it is upper it won't show anything?
Example of command line code
| [
"pytest-cov doesn't have this option, but you don't have to use pytest-cov to produce the report. Use the plugin to run coverage, then in a separate command, produce the report: coverage report. You can conditionally run that separate command based on whatever condition you want.\n"
] | [
0
] | [] | [] | [
"code_coverage",
"pytest",
"pytest_cov",
"python",
"test_coverage"
] | stackoverflow_0074522777_code_coverage_pytest_pytest_cov_python_test_coverage.txt |
Q:
Slice pandas dataframe column into multiple columns using substring
dataframe 'df' has the following data -
Column A
Column B
Item_ID1
Information - information for item that has ID as 1\nPrice - $7.99\nPlace - Albany, NY
Item_ID2
Information - item's information with ID as 2\nPrice - $5.99\nPlace - Ottawa, ON
... | Slice pandas dataframe column into multiple columns using substring | dataframe 'df' has the following data -
Column A
Column B
Item_ID1
Information - information for item that has ID as 1\nPrice - $7.99\nPlace - Albany, NY
Item_ID2
Information - item's information with ID as 2\nPrice - $5.99\nPlace - Ottawa, ON
How to segregate the values from column B using 'Information',... | [
"You can approach this by using pandas.Series.split :\ndf[[\"Information\", \"Price\", \"Place\"]]= df.pop(\"Column B\").str.split(r\"\\\\n\", expand=True)\n\ndf= df.astype(str).apply(lambda x: x.replace(x.name, \"\", regex=True).str.strip(\" - \"))\n\n# Output :\nprint(df.to_string())\n\n Column A ... | [
2,
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074529438_dataframe_pandas_python.txt |
Q:
Python -- Function with a Pandas dataframe as an argument
I have to create a function that takes a Pandas dataframe as an argument and returns a copy of the dataframe after replacing the null values in each column with the most frequent value in the column.
Cannot use FOR or WHILE loops.
A:
Well, to create a cop... | Python -- Function with a Pandas dataframe as an argument | I have to create a function that takes a Pandas dataframe as an argument and returns a copy of the dataframe after replacing the null values in each column with the most frequent value in the column.
Cannot use FOR or WHILE loops.
| [
"Well, to create a copy you can simply use df.copy(deep = True) (note that deep = True creates a new dataframe-object, otherwise you get a reference to the copied dataframe).\nTo replace the null values with the most frequent values, you can use the mode method for Series and DataFrames (https://pandas.pydata.org/d... | [
1
] | [] | [] | [
"anaconda",
"dataframe",
"function",
"pandas",
"python"
] | stackoverflow_0074531219_anaconda_dataframe_function_pandas_python.txt |
Q:
Can't change Column to array - int64
I have a CSV dataset with 2 columns that looks like the following:
Date
Open
25/2/21
7541.85
26/2/21
7562.32
27/2/21
7521.65
28/2/21
7509.14
Data columns (total 2 columns):
#
Column
Non-Null
Count
Dtype
0
Open
1280
non-null
object
1
Date
1280
non-null
datetime64[ns]
d... | Can't change Column to array - int64 | I have a CSV dataset with 2 columns that looks like the following:
Date
Open
25/2/21
7541.85
26/2/21
7562.32
27/2/21
7521.65
28/2/21
7509.14
Data columns (total 2 columns):
#
Column
Non-Null
Count
Dtype
0
Open
1280
non-null
object
1
Date
1280
non-null
datetime64[ns]
dtypes: datetime64ns,... | [
"Based on comments, you can try:\ndf[\"Open\"] = df[\"Open\"].str.replace(\",\", \"\").astype(float)\nprint(df)\n\nPrints:\n Date Open\n0 25/2/21 7541.85\n1 26/2/21 7562.32\n2 27/2/21 7521.65\n3 28/2/21 7509.14\n\n\ndf used:\n Date Open\n0 25/2/21 7,541.85\n1 26/2/21 7,562.32\n2 27/2... | [
1
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074531095_arrays_python.txt |
Q:
gevent not valid running Docker Registry
I am attempting to run a Docker registry on Ubuntu 14 using the following command:
sudo gunicorn --access-logfile - --debug -k gevent -b 0.0.0.0:5000 -w 1 docker_registry.wsgi:application
Unfortunately, when I attempt this I get the following failure message:
Error: class ... | gevent not valid running Docker Registry | I am attempting to run a Docker registry on Ubuntu 14 using the following command:
sudo gunicorn --access-logfile - --debug -k gevent -b 0.0.0.0:5000 -w 1 docker_registry.wsgi:application
Unfortunately, when I attempt this I get the following failure message:
Error: class uri 'gevent' invalid or not found:
[Traceba... | [
"re-Install python-gevent\napt-get install python-gevent\npip install --upgrade gevent\n",
"try it:\n1.find your python gevent package folder:\n$ cd /usr/local/lib/python2.7/dist-packages/gevent\n\n2.update ssl.py\nfrom:\ndef get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):\n\nto:\ndef get... | [
4,
1,
0
] | [] | [] | [
"docker",
"python",
"ubuntu_14.04"
] | stackoverflow_0034314222_docker_python_ubuntu_14.04.txt |
Q:
Dash duplicate paths issue
I'm working on a dash application and I got this error.
I haven't found anything on stackoverflow related to this issue.
Exception: modules ['pages..ipynb_checkpoints.app_Km-checkpoint', 'pages.app_Km'] have duplicate paths
A:
Do you use the dash multipage plugin? Could you provide you... | Dash duplicate paths issue | I'm working on a dash application and I got this error.
I haven't found anything on stackoverflow related to this issue.
Exception: modules ['pages..ipynb_checkpoints.app_Km-checkpoint', 'pages.app_Km'] have duplicate paths
| [
"Do you use the dash multipage plugin? Could you provide your code and project structure?\n\nI have encountered a similar error myself. I am using the DASH\nmultipage plugin, dash version 2.6.2\n\nMy problem was that I was running my application from a different\nPYTHONPATH than where is my app.py - because my appl... | [
0
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0073964756_plotly_dash_python.txt |
Q:
Filter model without using distinct method
I have a model with a list of products. Each product has an ID, price, brand, etc. I want return all the objects of the model where brand name is distinct. I am currently using django's built-in SQLite, so it does not support something like
products = Product.objects.all(... | Filter model without using distinct method | I have a model with a list of products. Each product has an ID, price, brand, etc. I want return all the objects of the model where brand name is distinct. I am currently using django's built-in SQLite, so it does not support something like
products = Product.objects.all().distinct('brand')
Is there another way of ret... | [
"As SQLight doesn't support .distinct('field') you need to do this directly in python. For example:\nproducts = list({p.brand: p for p in Product.objects.all()}.values())\n\n",
"Well you can do it with 2 different methods:\n\ndef MethodName(self):\nquery = \"\"\"\n SELECT DISTINCT brand FROM Product;\n \"... | [
2,
0,
0
] | [
"try this\nproducts = set(Product.objects.values_list('brand'))\n\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0074531014_django_python.txt |
Q:
Why do i keep encountering this error when i try to migrate on django app
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: theblog_categories
i expected to migrate succesfully
A:
This is because the migrations in Django are little complex and often with little ... | Why do i keep encountering this error when i try to migrate on django app | return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: theblog_categories
i expected to migrate succesfully
| [
"This is because the migrations in Django are little complex and often with little changes it doesn't reflect the changes in the DB.\nPlease delete Migrations file from the Django app and then migrate it again.\nYou can also refer this link if the problem persist:\nDjango migrate --fake and --fake-initial explained... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074529777_django_django_models_python.txt |
Q:
Why is model._meta.get_fields() returning unexpected relationship column names, and can this be prevented?
Imagine I have some models as below:
class User(AbstractUser):
pass
class Medium(models.Model):
researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="med... | Why is model._meta.get_fields() returning unexpected relationship column names, and can this be prevented? | Imagine I have some models as below:
class User(AbstractUser):
pass
class Medium(models.Model):
researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="medium_researcher")
old_medium_name = models.CharField(max_length=20, null=True, blank=True)
class Uptake(mode... | [
"\nWhy does this return uptake_medium? As this is a ForeignKey relation set within the Uptake model, it should only be present within the Uptake model right?\n\nYou can access the relation in reverse, for example:\nmy_medium.uptake_medium.all()\n\nto obtain all Updates related to the Medium instance named medium.\n... | [
1
] | [] | [] | [
"django",
"django_models",
"foreign_keys",
"metadata",
"python"
] | stackoverflow_0074530943_django_django_models_foreign_keys_metadata_python.txt |
Q:
Im getting the error "{"error":{"code":null,"message":"The URI is malformed."}}", when "&" is passed in the api below
def get_dw_dim_channel_by_channel(self, channel):
url = 'db-warehouse-dw/dim_channel?$filter=channel_name eq \'{}\''.format(channel)
print ("debug: url = {}{}".format(self.host, url))
r... | Im getting the error "{"error":{"code":null,"message":"The URI is malformed."}}", when "&" is passed in the api below | def get_dw_dim_channel_by_channel(self, channel):
url = 'db-warehouse-dw/dim_channel?$filter=channel_name eq \'{}\''.format(channel)
print ("debug: url = {}{}".format(self.host, url))
return self.get(url, headers=self.headers, auth=self.auth)
Here the value for channel_name is "WDC Kitchen & Bath Center".
... | [
"The ampersand needs to be percent-encoded.\nTry to use:\nchannel = channel.replace(\"&\", \"%26\")\n\n"
] | [
0
] | [] | [] | [
"api",
"coda",
"python",
"python_behave"
] | stackoverflow_0074531327_api_coda_python_python_behave.txt |
Q:
Compare two lists and update the properties in Python
I have two lists in Python something similar.
list1 = [
{"name": "sample1",
"place": "sampleplace1",
"value": "",
"time": "sampletime"
},
{"name": "sample2",
"place": "sampleplace2",
"value": "",
"time": "sampletime2"
... | Compare two lists and update the properties in Python | I have two lists in Python something similar.
list1 = [
{"name": "sample1",
"place": "sampleplace1",
"value": "",
"time": "sampletime"
},
{"name": "sample2",
"place": "sampleplace2",
"value": "",
"time": "sampletime2"
}
]
list2 = [
{"name": "sample1",
"value": "... | [
"Sadly, Python does not have the same abilities as LINQ.\nIf you don't want to explicitly use a function there is map, but it uses a loop under the hood, as LINQ does.\nYou need for loops, like in :\nlist1 = [\n {\"name\": \"sample1\",\n \"place\": \"sampleplace1\",\n \"value\": \"\",\n \"time\": \"s... | [
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074522485_list_python_python_3.x.txt |
Q:
Django - How to Get ID before ensuring form is valid
I am facing an issue where I have multiple forms on one page. What I am trying to do is update an item using an update form.
The issue is I am unable to display the most current data that is in DB in the template.
When I request the pk, it comes from a different... | Django - How to Get ID before ensuring form is valid | I am facing an issue where I have multiple forms on one page. What I am trying to do is update an item using an update form.
The issue is I am unable to display the most current data that is in DB in the template.
When I request the pk, it comes from a different model that is not related to this one. I need to get the ... | [
"You will need to fetch the Urls via Ajax and not by Django URL dispatcher. As per my understanding you have multiple forms and after submitting the 1st form you want to get its pk and by which you want to fill the 2nd form and store the primary key in the another model table. Please use axios to call the Urls.\nYo... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074526516_django_python.txt |
Q:
How to solve, file not found error from script, but works in notebook?
I have a code to load a json file.
with open("data/movie_data.json", "r") as j:
word_map = json.load(j)
The data folder is in current directory. However, this code works in the jupyter notebook, but while running from a script, it says, fi... | How to solve, file not found error from script, but works in notebook? | I have a code to load a json file.
with open("data/movie_data.json", "r") as j:
word_map = json.load(j)
The data folder is in current directory. However, this code works in the jupyter notebook, but while running from a script, it says, file not found error. Both the script and notebook are in same folder, that co... | [
"Try\n\"./data/movie_data.json\"\n\ninstead of\n\"data/movie_data.json\"\n\n"
] | [
0
] | [] | [] | [
"filenotfoundexception",
"json",
"python"
] | stackoverflow_0074531421_filenotfoundexception_json_python.txt |
Q:
Perform tasks when the user has responded to a recation, otherwise do nothing
I have a problem. I want that when the user writes a message, my bot should send a message. And once the user has responded to that message, the user should send further instructions.
I have the problem that when the user sends a message... | Perform tasks when the user has responded to a recation, otherwise do nothing | I have a problem. I want that when the user writes a message, my bot should send a message. And once the user has responded to that message, the user should send further instructions.
I have the problem that when the user sends a message, the bot sends the message with the reactions, but as soon as the user sends a sec... | [
"The problem with what you're trying to do, is that discord.py, and the discord API in general, is designed to run a bot on multiple servers, on multiple channels, etc.\nThis means that, if you want to forbid a user sending a second message, you have to specify what you mean with that. Not twice on the same channel... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074529815_discord_discord.py_python.txt |
Q:
Is there a better way to use numpy in that case?
My output looks like that, but isn't my code bad practice? Is there a way to replace the for with numpy functions?
[[ 1. 1.5 2. 2.5 3. ]
[ 3.5 4. 4.5 5. 5.5]
[ 6. 6.5 7. 7.5 8. ]
[ 8.5 9. 9.5 10. 10.5]
[11. 11.5 12. 12.5 13. ]
[13.5 14. ... | Is there a better way to use numpy in that case? | My output looks like that, but isn't my code bad practice? Is there a way to replace the for with numpy functions?
[[ 1. 1.5 2. 2.5 3. ]
[ 3.5 4. 4.5 5. 5.5]
[ 6. 6.5 7. 7.5 8. ]
[ 8.5 9. 9.5 10. 10.5]
[11. 11.5 12. 12.5 13. ]
[13.5 14. 14.5 15. 15.5]
[16. 16.5 17. 17.5 18. ]
[18.5 19... | [
"Not necessarily bad practice (except for calling your variable list) but it can be improved significanty by using np.arange as follows:\narr = np.arange(1,21,0.5).reshape((8,5))\n\n",
"You would not use a loop with numpy, but rather vectorial code.\nYou seem to want numpy.arange combined with reshape:\nn, m = 8,... | [
2,
2,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074531286_numpy_python.txt |
Q:
Setting the Same Icon as Application Icon in Task bar for pyqt5 application
I am finding trouble with attaching the same icon in the task bar manager for pyqt5 application as I did for the icon of pyqt5 application. I have attached below code for icon display in pyqt5, just need a bit help that how to code for dis... | Setting the Same Icon as Application Icon in Task bar for pyqt5 application | I am finding trouble with attaching the same icon in the task bar manager for pyqt5 application as I did for the icon of pyqt5 application. I have attached below code for icon display in pyqt5, just need a bit help that how to code for displaying of same icon of Application to the task bar.
import sys
from SplashScre... | [
"Guess What I found the Answer.\nI used three lines of Code at the start of my application and then run the code and windows show me same icon as it was my logo.\nimport ctypes\nmyappid = 'mycompany.myproduct.subproduct.version' # arbitrary string\nctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myapp... | [
4,
0
] | [] | [] | [
"pyqt5",
"python",
"user_interface"
] | stackoverflow_0067599432_pyqt5_python_user_interface.txt |
Q:
Dollar Universe - 'nonetype' object has no attribute 'isatty gcloud
When I run a "gcloud functions call.." I don't encouter any error.
When I run my cmd with Dollar Universe I have this error:
ERROR: gcloud crashed (AttributeError): 'NoneType' object has no attribute 'isatty
A:
Thanks to ErnestoC for helping to ... | Dollar Universe - 'nonetype' object has no attribute 'isatty gcloud | When I run a "gcloud functions call.." I don't encouter any error.
When I run my cmd with Dollar Universe I have this error:
ERROR: gcloud crashed (AttributeError): 'NoneType' object has no attribute 'isatty
| [
"Thanks to ErnestoC for helping to resolve the issue.\nFor more information, a simple update with gcloud component update didn't work for me because the Google Cloud CLI manager is disabled for my installation (see the screenshot) but my cloud console suggested me to do this:\nsudo yum makecache && sudo yum update ... | [
0
] | [] | [] | [
"gcloud",
"python"
] | stackoverflow_0072703063_gcloud_python.txt |
Q:
Django| Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)$']
I am following django tutorial by @CoreyMSchafer. I got error while practicing i can't find solution to it.
According to my understanding its problem with reversing of url. but can't find out what is wrong
E... | Django| Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)$'] | I am following django tutorial by @CoreyMSchafer. I got error while practicing i can't find solution to it.
According to my understanding its problem with reversing of url. but can't find out what is wrong
Error:
NoReverseMatch at /
Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['use... | [
"url(r'^user/(?P<username>\\w{0,50})/$', UserPostListView.as_view(), name='user-posts'),\n\njust add it in your url\nnot this\npath('user/<str:username>/', UserPostListView.as_view(),name='user-posts'),\n\n",
"I had the same question before.\nIn your user_posts.html and base.html,\nchange all the name of the 'obj... | [
3,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"django_pagination",
"django_templates",
"python"
] | stackoverflow_0060789353_django_django_pagination_django_templates_python.txt |
Q:
How to append two StringIO objects?
X = ABC (example data)
print(type(x)) ---> <class '_io.StringIO'>
Y = ABC (example data)
print(type(x)) ---> <class '_io.StringIO'>
Z=X+Y Is it possible to append of these types
data= Z.getvalue()
How to achieve this with or without converting to other data types?
Do... | How to append two StringIO objects? | X = ABC (example data)
print(type(x)) ---> <class '_io.StringIO'>
Y = ABC (example data)
print(type(x)) ---> <class '_io.StringIO'>
Z=X+Y Is it possible to append of these types
data= Z.getvalue()
How to achieve this with or without converting to other data types?
Do we have any other ways rather than this... | [
"Since StringIO has a file-like interface - which means you can merge them in the same way as you would when copying files between file-like objects:\nfrom io import StringIO\nfrom shutil import copyfileobj\n\na = StringIO('foo')\nb = StringIO('bar')\nc = StringIO()\ncopyfileobj(a, c)\ncopyfileobj(b, c)\nprint(c.ge... | [
1
] | [] | [] | [
"python",
"stringio"
] | stackoverflow_0074529822_python_stringio.txt |
Q:
Discord.py | How to remove all reactions from a message added by a specific user at once
Right now my bot sends a message and reacts with a list of emojis to its own message, multiple users react using the emojis the bot reacted with. After some time the bot needs to remove all reactions except the ones the bot cr... | Discord.py | How to remove all reactions from a message added by a specific user at once | Right now my bot sends a message and reacts with a list of emojis to its own message, multiple users react using the emojis the bot reacted with. After some time the bot needs to remove all reactions except the ones the bot created.
Lets say if a bot send a message "react text" and reacts with emojis "yes emoji"(reacte... | [
"Using message.reactions you get a list of reactions to that message, which you should iterate over. Then on that reaction, iterate over the users which reacted with it, and if the user is not the bot, remove the reaction for this user:\nfor reaction in message.reactions:\n for user in await reaction.users().fla... | [
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0068813945_discord_discord.py_python_python_3.x.txt |
Q:
password protect pdf files created using pisa
I'm converting a html file into pdf using python pisa module. I need to password protect it. I searched everywhere in pisa module and couldn't find a solution for it. Is there anyway to password protect it using python?
The constraint is I want keep my file in html for... | password protect pdf files created using pisa | I'm converting a html file into pdf using python pisa module. I need to password protect it. I searched everywhere in pisa module and couldn't find a solution for it. Is there anyway to password protect it using python?
The constraint is I want keep my file in html format. On demand basis, I want to convert it into pdf... | [
"You can with pyPdf which is optional for pisa but has an encryption method:\n\nA Pure-Python library built as a PDF toolkit. It is capable of:\nextracting document information (title, author, ...), splitting\n documents page by page, merging documents page by page, cropping\n pages, merging multiple pages into a... | [
1,
0
] | [] | [] | [
"pdf_generation",
"pisa",
"python",
"xhtml2pdf"
] | stackoverflow_0012497983_pdf_generation_pisa_python_xhtml2pdf.txt |
Q:
Solve integral symbolically by isolating integrand in sympy
I was wondering why sympy won't solve the following problem:
from sympy import *
ss = symbols('s', real = True)
a = symbols('a', real = True)
f = Function('f')
g = Function('g')
eq = Integral(a*g(ss) + f(ss),(ss,0,oo))
solve(eq, a)
The return is an empty... | Solve integral symbolically by isolating integrand in sympy | I was wondering why sympy won't solve the following problem:
from sympy import *
ss = symbols('s', real = True)
a = symbols('a', real = True)
f = Function('f')
g = Function('g')
eq = Integral(a*g(ss) + f(ss),(ss,0,oo))
solve(eq, a)
The return is an empty solution list. I want to tell sympy enough stuff so that I get a... | [
"Your assumption about the expected result is still inaccurate. For the equation to have a solution, Integral(g(ss),(ss,0,oo)) must be guaranteed to be real and non-zero, which is in no way implied by your equations, so no result is returned.\nFurther, it appears that if you want to solve equations involving an Int... | [
1,
0
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074526345_python_sympy.txt |
Q:
Calling Oracle sqlldr using Python
I am trying to load sqlldr using python so and i am using subprocess.call for that.
cmd = 'sqlldr USERID={user}/{password}@Databse_name control={controlfile} data={datafile}'
subprocess.call(cmd, shell=True)
the output shows:
sqlldr USERID={user}/{password}@Databse_name control... | Calling Oracle sqlldr using Python | I am trying to load sqlldr using python so and i am using subprocess.call for that.
cmd = 'sqlldr USERID={user}/{password}@Databse_name control={controlfile} data={datafile}'
subprocess.call(cmd, shell=True)
the output shows:
sqlldr USERID={user}/{password}@Databse_name control={controlfile} no such directory of file... | [
"Provide the full path, not only file names.\n",
"Please try with shell. Make sure u have downloaded instant_client for oracle as well sqlldr.\nimport os\nimport subprocess\n\nBASE_DIR = Path(__file__).resolve().parent\ncontrol_file = os.path.join(BASE_DIR, 'SAMPLE_ITEM_LOAD.ctrl')\ndata_file = os.path.join(BASE_... | [
0,
0
] | [] | [] | [
"oracle",
"python",
"shell",
"sql_loader"
] | stackoverflow_0071171725_oracle_python_shell_sql_loader.txt |
Q:
How can I make python change the characters in a batch file?
I'm making a script that changes your dns and then pings a website to test latency and I've created a list with all the DNS and I want to use an external batch script to change the dns. However, I'm reasonably new to python and I don't know how to make p... | How can I make python change the characters in a batch file? | I'm making a script that changes your dns and then pings a website to test latency and I've created a list with all the DNS and I want to use an external batch script to change the dns. However, I'm reasonably new to python and I don't know how to make python take data from the list and replace it in the batch file. Th... | [
"Simple string replacement should work nicely\ndns = [\"1.1.1.1\",\"1.0.0.1\",\"8.8.8.8\",\"8.8.4.4\",\"9.9.9.9\",\"149.112.112.112\",\"208.67.222.222\",\"208.67.220.220\",\"8.26.56.26\",\"8.20.247.20\",\"185.228.168.9\",\"185.228.169.9\"]\n\n# Assumes .bat and .py scripts are in the same directory\nbat_file = \"te... | [
0
] | [] | [] | [
"networking",
"python",
"python_3.x"
] | stackoverflow_0074531403_networking_python_python_3.x.txt |
Q:
How do I use a datepicker on a simple Django form?
Before you mark this as a duplicate to the most famous django datepicker question on SO, hear me out. I have gone through all the questions in the first ten pages of the search results, but no one seems to be explaining anything from the beginning.
What I am look... | How do I use a datepicker on a simple Django form? | Before you mark this as a duplicate to the most famous django datepicker question on SO, hear me out. I have gone through all the questions in the first ten pages of the search results, but no one seems to be explaining anything from the beginning.
What I am looking for is the most simple way to have a datepicker on m... | [
"This is probably somewhat hacky, but when I want to use the jQueryUI datepicker for a specific form field I do this:\nAdd the stylesheet in the <head> of my template:\n<link rel=\"stylesheet\" href=\"https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\" />\nAdd the javascript file at the end of my template... | [
2,
0,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0042165163_django_python.txt |
Q:
Google Workspace API, API call to create a user?
We're using code similar to this for creating the user. However, we get a 400 Error when we call the API. What is the correct way to call the API?
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.o... | Google Workspace API, API call to create a user? | We're using code similar to this for creating the user. However, we get a 400 Error when we call the API. What is the correct way to call the API?
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_... | [
"You appear to have an issue with how you are creating the user, who you are inserting.\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\n\n\n# If modifying thes... | [
0
] | [] | [] | [
"google_api",
"google_api_python_client",
"google_oauth",
"google_workspace",
"python"
] | stackoverflow_0074531157_google_api_google_api_python_client_google_oauth_google_workspace_python.txt |
Q:
Tried creating binary decision variable in place of conditional if statement in Gurobi. Getting constraint error
I have followed all existing discussion posts and instructions on how to code conditional constraints in Gurobi. I cannot figure out why I am getting this error.
GurobiError: Constraint has no bool valu... | Tried creating binary decision variable in place of conditional if statement in Gurobi. Getting constraint error | I have followed all existing discussion posts and instructions on how to code conditional constraints in Gurobi. I cannot figure out why I am getting this error.
GurobiError: Constraint has no bool value (are you trying "lb <= expr <= ub"?)
See below code snippet from python script:
b = {}
gap = {}
for k in range(start... | [
"Your code is very hard to read - please reformulate and post an MRE as suggested in the comments.\nI suspect that multi_df[i][...][...] already contains a linear expression and is not just holding a Gurobi variable. Hence, the warning about multiple <= or >= in one constraint.\n"
] | [
0
] | [] | [] | [
"gurobi",
"optimization",
"python"
] | stackoverflow_0074470311_gurobi_optimization_python.txt |
Q:
Error while using multiprocessing in Pygame
i'm making a text-based RPG and am trying to use multiproccessing to run both the pygame check function and the game function at the same time. This is my first time using multiprocessing so i'm not entirely sure what is going on.
Here is the (important) code:
from csv i... | Error while using multiprocessing in Pygame | i'm making a text-based RPG and am trying to use multiproccessing to run both the pygame check function and the game function at the same time. This is my first time using multiprocessing so i'm not entirely sure what is going on.
Here is the (important) code:
from csv import reader
import pygame
from sys import exit
i... | [
"Did you read the end of the error message, and the very clear instructions there? When using multiprocessing, your main code needs to be wrapped in the if __name__ == \"__main__\": idiom (this is also documented in the multiprocessing docs).\nI.e. something like\nimport multiprocessing\nfrom sys import exit\n\nimp... | [
0
] | [] | [] | [
"multiprocessing",
"pygame",
"python",
"python_multiprocessing",
"rpg"
] | stackoverflow_0074531737_multiprocessing_pygame_python_python_multiprocessing_rpg.txt |
Q:
Trim leading zero's using python pandas without changing the datatype of any columns
I have a csv file of around 42000 lines and around 80 columns, from which I need to remove leading Zero's, hence I am using Pandas to_csv and saving it back to text file by which leading Zero's are removed.
Any column may contain ... | Trim leading zero's using python pandas without changing the datatype of any columns | I have a csv file of around 42000 lines and around 80 columns, from which I need to remove leading Zero's, hence I am using Pandas to_csv and saving it back to text file by which leading Zero's are removed.
Any column may contain null values in any row, but those columns are getting converted to Float datatype and gett... | [
"First convert all values to strings and in next step remove trailing zeros:\ndf = pd.read_csv(r\"/home/ter/stest/cminxte1.txt\", sep=\"|\", dtype=str) \ndf = df.apply(lambda x: x.str.lstrip('0'))\ndf.to_csv(r\"/home/ter/stest/cminxte.txt\", sep='|', index=False)\n\n"
] | [
1
] | [] | [] | [
"export_to_csv",
"pandas",
"python"
] | stackoverflow_0074531771_export_to_csv_pandas_python.txt |
Q:
How do I solve "pythoncom39.dll could not be located error"?
It has started appearing ever since I installed Anaconda on my PC. It doesn't affect anything and when I press "Ok" it goes away. But it is quite annoying and I would like to know the reason. It has only appeared when I try to run a development server in... | How do I solve "pythoncom39.dll could not be located error"? |
It has started appearing ever since I installed Anaconda on my PC. It doesn't affect anything and when I press "Ok" it goes away. But it is quite annoying and I would like to know the reason. It has only appeared when I try to run a development server in Django or try to install python modules using pip. Is there any ... | [
"It happens because anacondaa3\\Library\\bin\\ in this folder pythondicom39.dll has crashed you need to replace it with a new file\n",
"Yes, that dll file might be corrupted. Just replace, and then try it. You can download the pythoncom39.dll files from the following link\nhttps://freeonlinestudies.com/python-dll... | [
0,
0
] | [] | [] | [
"anaconda",
"pip",
"python"
] | stackoverflow_0070557619_anaconda_pip_python.txt |
Q:
Remove part of a string from pd.to_datetime() unconverted values
I tried to convert a column of dates to datetime using pd.to_datetime(df, format='%Y-%m-%d_%H-%M-%S') but I received the error ValueError: unconverted data remains: .1
I ran:
data.loc[pd.to_datetime(data.date, format='%Y-%m-%d_%H-%M-%S', errors='coer... | Remove part of a string from pd.to_datetime() unconverted values | I tried to convert a column of dates to datetime using pd.to_datetime(df, format='%Y-%m-%d_%H-%M-%S') but I received the error ValueError: unconverted data remains: .1
I ran:
data.loc[pd.to_datetime(data.date, format='%Y-%m-%d_%H-%M-%S', errors='coerce').isnull(), 'date']
to identify the problem. 119/1037808 dates in ... | [
"You can use pandas.Series.replace to get rid of the extra dot/number :\ndata[\"date\"]= pd.to_datetime(data[\"date\"].replace(r\"\\.\\d+\", \"\",\n regex=True),\n format=\"%Y-%m-%d_%H-%M-%S\")\n\n# Output :\nprint(data)\nprint(data.dtypes... | [
1,
0
] | [] | [] | [
"datetime",
"pandas",
"python",
"string"
] | stackoverflow_0074531567_datetime_pandas_python_string.txt |
Q:
Is there a way to give ID to other tables based on an ID with one table?
I have two tables as following:
ID
Name
Age
1
aaa
23
2
bbb
21
3
ccc
25
4
ddd
20
ID
Name
Age
Phone
aaa
23
0000
bbb
21
1111
ccc
28
2222
ddd
29
3333
The first table name as T1 include ID that I gave them unique ID, however from the se... | Is there a way to give ID to other tables based on an ID with one table? | I have two tables as following:
ID
Name
Age
1
aaa
23
2
bbb
21
3
ccc
25
4
ddd
20
ID
Name
Age
Phone
aaa
23
0000
bbb
21
1111
ccc
28
2222
ddd
29
3333
The first table name as T1 include ID that I gave them unique ID, however from the second table T2 the ID column is empty. How can I ad... | [
"Try with an update query having a subquery:\nUpdate T2\nSet T2.ID = \n (Select Top 1 T1.Id \n From T1\n Where T1.Name = T2.Name)\n\n"
] | [
0
] | [] | [] | [
"csv",
"excel",
"ms_access",
"pandas",
"python"
] | stackoverflow_0074529743_csv_excel_ms_access_pandas_python.txt |
Q:
How do i generate different new objects with random attributes every time i run a function?
I am making a project where you can manage the passengers on a buss. I have created the class system, and know how to generate the random attributes. But I don't know how to generate multiple new persons, with different att... | How do i generate different new objects with random attributes every time i run a function? | I am making a project where you can manage the passengers on a buss. I have created the class system, and know how to generate the random attributes. But I don't know how to generate multiple new persons, with different attributes, when you choose to pick up a new person. I don't know how to make it so all of them does... | [
"Is it what you are trying to do? create several unique Person objects to include in a list:\nimport random\n\n\nclass Person:\n \"\"\" Person is a class for representing the persons in the bus. Each object that is created from the\n class has a name and a age, as well as methods to return alternativly modif... | [
0
] | [] | [] | [
"list",
"oop",
"python"
] | stackoverflow_0074528973_list_oop_python.txt |
Q:
Execute python script inside a python script
I have a scenario where i want to dynamically generate a python script - inside my main python script - store it as a string and then when need be, execute this dynamically generated script from my main script.
Is this possible, if so how?
thanks
A:
For a script in a... | Execute python script inside a python script | I have a scenario where i want to dynamically generate a python script - inside my main python script - store it as a string and then when need be, execute this dynamically generated script from my main script.
Is this possible, if so how?
thanks
| [
"For a script in a file use exec \nFor a script in a string use eval\n!!! But !!!\nbefore you use strings passed in from an external source, sanity check them!\nOtherwise you expose the ability to execute arbitrary code from \nwithin you program,\nso range check your variables!\nYou do not ever want to be asking th... | [
13,
6,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003418357_python.txt |
Q:
How to write a simple python program that prints letters in ascending order?
For example I would like to have:
a
.
.
.
z
aa
ab
.
.
.
az
bz
.
.
.
zz
aaa
and so on.
Currently I'm here but I am lost. So feel free to propose a completely different solution.
count = 0
string = ''
for i in range(100):
count += 1
... | How to write a simple python program that prints letters in ascending order? | For example I would like to have:
a
.
.
.
z
aa
ab
.
.
.
az
bz
.
.
.
zz
aaa
and so on.
Currently I'm here but I am lost. So feel free to propose a completely different solution.
count = 0
string = ''
for i in range(100):
count += 1
if i % 26 == 0:
count = 0
string += 'a'
ch = 'a'
x = chr(... | [
"Maybe try something like the following:\nrange(97,123) simply creates a range of numbers from 97 to 122, which converted to ASCII equates to a...z (done using chr())\nSo all our FUnction does, is it recieves a base string (starts with empty), prints out the base + range of charachters and calls its self with base ... | [
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074531610_python_string.txt |
Q:
self in Python references to variable rather than the class
So, I'm trying to code an observer pattern in Python.
Main method:
import Subject as Subj
import ConcreteStateA as Obs
Newsletter = Subj.Subject
Paul = Obs
Sara = Obs
Julien = Obs
print(Paul)
print(Sara)
Newsletter().addObserver(Paul)
Newsletter().add... | self in Python references to variable rather than the class | So, I'm trying to code an observer pattern in Python.
Main method:
import Subject as Subj
import ConcreteStateA as Obs
Newsletter = Subj.Subject
Paul = Obs
Sara = Obs
Julien = Obs
print(Paul)
print(Sara)
Newsletter().addObserver(Paul)
Newsletter().addObserver(Sara)
Newsletter().addObserver(Julien)
Newsletter().not... | [
"def notifyObservers(message, self):\n print(\"test\")\n for obs in self.ObserverList:\n print(\"Notified Observer\")\n obs.update(message)\n\nThe mistake is the way you define your parameters here. The fact is the first parameter will always be what you know as self - the Object... | [
2
] | [] | [] | [
"python",
"self"
] | stackoverflow_0074531794_python_self.txt |
Q:
Snakemake doesn't activate conda environment correctly
I have a Python module modulename installed in a conda environment called myenvname.
My snakemake file consists of one simple rule:
rule checker2:
output:
"tata.txt"
conda:
"myenvname"
script:
"scripts/test2.py"
The content... | Snakemake doesn't activate conda environment correctly | I have a Python module modulename installed in a conda environment called myenvname.
My snakemake file consists of one simple rule:
rule checker2:
output:
"tata.txt"
conda:
"myenvname"
script:
"scripts/test2.py"
The contents of the test2.py are the following:
import modulename
with ... | [
"Question is answered. Snakemake actually activates correct environment, but running a python script with the script conflicts with this directive. I don't know if this is a bug in snakemake (version is 6.14.0) or an intentional thing. I've solved the problem by running the python script via shell command with pyth... | [
0
] | [] | [] | [
"conda",
"python",
"snakemake"
] | stackoverflow_0074479965_conda_python_snakemake.txt |
Q:
Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?
I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports. However the fixed column widths are a problem... | Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter? | I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports. However the fixed column widths are a problem.
The code I have so far is simple enough. Say I have a dataframe called df:
wr... | [
"Inspired by user6178746's answer, I have the following:\n# Given a dict of dataframes, for example:\n# dfs = {'gadgets': df_gadgets, 'widgets': df_widgets}\n\nwriter = pd.ExcelWriter(filename, engine='xlsxwriter')\nfor sheetname, df in dfs.items(): # loop through `dict` of dataframes\n df.to_excel(writer, shee... | [
109,
48,
35,
35,
24,
16,
7,
6,
4,
4,
3,
3,
1,
1,
0,
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0017326973_excel_openpyxl_pandas_python.txt |
Q:
How can I use Python to convert multiple columns in the same row to another row?
I have an excel file which has multiple title names as columns within the same row where the data is given, I need to sort the data and convert the column names to rows and assign it to the data under the "column names"
enter image de... | How can I use Python to convert multiple columns in the same row to another row? | I have an excel file which has multiple title names as columns within the same row where the data is given, I need to sort the data and convert the column names to rows and assign it to the data under the "column names"
enter image description here
My expected output is for it to turn out like this:
enter image descrip... | [
"You can check rows with names of new column values by column b testing missing values, replace non matched a column values to missing values by Series.where and forward filling missing values, last filter with inverted mask and columns a,c in DataFrame.loc:\ndf = pd.read_excel('file.xlsx')\n\n#sample data\nprint (... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074531050_dataframe_excel_pandas_python.txt |
Q:
How do I get the day of week given a date?
I want to find out the following:
given a date (datetime object), what is the corresponding day of the week?
For instance, Sunday is the first day, Monday: second day.. and so on
And then if the input is something like today's date.
Example
>>> today = datetime.datetime(2... | How do I get the day of week given a date? | I want to find out the following:
given a date (datetime object), what is the corresponding day of the week?
For instance, Sunday is the first day, Monday: second day.. and so on
And then if the input is something like today's date.
Example
>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday() # what I l... | [
"Use weekday():\n>>> import datetime\n>>> datetime.datetime.today()\ndatetime.datetime(2012, 3, 23, 23, 24, 55, 173504)\n>>> datetime.datetime.today().weekday()\n4\n\nFrom the documentation:\n\nReturn the day of the week as an integer, where Monday is 0 and Sunday is 6.\n\n",
"If you'd like to have the date in En... | [
1327,
381,
220,
108,
51,
34,
18,
15,
12,
10,
9,
7,
6,
6,
5,
4,
3,
3,
3,
3,
3,
3,
2,
2,
1,
1,
1,
0,
0
] | [
"use this code:\nimport pandas as pd\nfrom datetime import datetime\nprint(pd.DatetimeIndex(df['give_date']).day)\n\n"
] | [
-1
] | [
"date",
"datetime",
"python",
"time",
"weekday"
] | stackoverflow_0009847213_date_datetime_python_time_weekday.txt |
Q:
ValueError: Target size (torch.Size([8, 1])) must be the same as input size (torch.Size([8, 4]))
I'm trying to train xlm roberta base for multi label text classification on my dataset of tweets, but I keep getting the following error:
---------------------------------------------------------------------------
Valu... | ValueError: Target size (torch.Size([8, 1])) must be the same as input size (torch.Size([8, 4])) | I'm trying to train xlm roberta base for multi label text classification on my dataset of tweets, but I keep getting the following error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [38], line 36
33 ... | [
"It seems that the model waits for a 2-dimensional input object, but you give a single-dimensional instead. It would help if you could show here your Dataset class as well, in order to have a better understanding of the batch structure.\n"
] | [
0
] | [] | [] | [
"huggingface_transformers",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0074531373_huggingface_transformers_machine_learning_python_pytorch.txt |
Q:
Convert list of tuples to list?
How do I convert
[(1,), (2,), (3,)]
to
[1, 2, 3]
A:
Using simple list comprehension:
e = [(1,), (2,), (3,)]
[i[0] for i in e]
will give you:
[1, 2, 3]
A:
@Levon's solution works perfectly for your case.
As a side note, if you have variable number of elements in the tuples, yo... | Convert list of tuples to list? | How do I convert
[(1,), (2,), (3,)]
to
[1, 2, 3]
| [
"Using simple list comprehension:\ne = [(1,), (2,), (3,)]\n[i[0] for i in e]\n\nwill give you:\n[1, 2, 3]\n\n",
"@Levon's solution works perfectly for your case.\nAs a side note, if you have variable number of elements in the tuples, you can also use chain from itertools.\n>>> a = [(1, ), (2, 3), (4, 5, 6)]\n>>> ... | [
95,
66,
31,
7,
7,
6,
4,
4,
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0010941229_python.txt |
Q:
Web Scraping with table that can be changed
I have succesfully managed to set together a script now that extracts some information from a table on this website: https://www.nordpoolgroup.com/en/Market-data1/Power-system-data/Production1/Wind-Power-Prognosis/SE/Hourly/?view=table
Now, I want to do this for all date... | Web Scraping with table that can be changed | I have succesfully managed to set together a script now that extracts some information from a table on this website: https://www.nordpoolgroup.com/en/Market-data1/Power-system-data/Production1/Wind-Power-Prognosis/SE/Hourly/?view=table
Now, I want to do this for all dates of 2021. I suppose I have to use the input id="... | [
"You would need to control the date picker and loop over all the dates. An alternative solution would be to look into the browsers dev tools and analyze the traffic from your client to the server.\nThere you see that with each change in the date picker a GET request to the server gets fired and a json with all the ... | [
1
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074530651_python_selenium_web_scraping.txt |
Q:
Implement lambda function from python to pyspark-Pyspark
Python:
I have a dataframe that I am applying a lambda function to check the conditions based on the values of a column.
In Pandas it looks like this(Example):
new_df = df1.merge(df2, how='left', left_on='lkey', right_on='rkey')
lkey value_x rkey value_y... | Implement lambda function from python to pyspark-Pyspark | Python:
I have a dataframe that I am applying a lambda function to check the conditions based on the values of a column.
In Pandas it looks like this(Example):
new_df = df1.merge(df2, how='left', left_on='lkey', right_on='rkey')
lkey value_x rkey value_y col1 col2 col3 col4 col5
0 foo one foo five 0 1... | [
"I think you can use UDF function OR when clause.\nwhen clause will be easier.\nSyntax will be like this for UDF\nfrom pyspark.sql.functions import udf\n\ndef function_name(arg):\n # Logic\n # Return value\n\n# Register the UDF\nUDF_NAME = udf(function_name, ArgType())\n\ndf.select(UDF_NAME('col').alias('new_... | [
1,
0,
0
] | [] | [] | [
"apache_spark_sql",
"pyspark",
"python",
"user_defined_functions"
] | stackoverflow_0069061074_apache_spark_sql_pyspark_python_user_defined_functions.txt |
Q:
Filter dictionary based on value in list of nested dictionary
I have the following dictionary that contains a list, in which the individual elements are nested dictionaries.
id_config = {
'expectations' : [
{
"kwargs": {
"column": "id",
"value": 14
},
"expectation_type": "ex... | Filter dictionary based on value in list of nested dictionary | I have the following dictionary that contains a list, in which the individual elements are nested dictionaries.
id_config = {
'expectations' : [
{
"kwargs": {
"column": "id",
"value": 14
},
"expectation_type": "expect_column_value_lengths_to_equal",
"meta": {}
},
{
... | [
"The pandas module can do this.\nYou can make a pandas.DataFrame from the 'expectations' list and filter out the values you don't want quite easily.\nThis provides some examples on how to do it.\n"
] | [
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074531924_dictionary_list_python.txt |
Q:
How to print all rows using iterrows method in pandas module?
birthdays.csv contain data:
name,email,year,month,day
Vishal,abc@email.com,2002,11,22
Riya,xyz@mail.com,2003,11,22
with open("birthdays.csv", "r") as file:
data = pandas.read_csv(file)
birthdays_dict = {(row['month'], row['day']): row for (inde... | How to print all rows using iterrows method in pandas module? | birthdays.csv contain data:
name,email,year,month,day
Vishal,abc@email.com,2002,11,22
Riya,xyz@mail.com,2003,11,22
with open("birthdays.csv", "r") as file:
data = pandas.read_csv(file)
birthdays_dict = {(row['month'], row['day']): row for (index, row) in data.iterrows()}
print(birthdays_dict)
output:
{(11, 22... | [
"Because birthdays_dict is a dictionary. And keys in the dictionary are unique. While your row['month'], row['day'] pair is the same in both rows, so the second row overrides the first row in birthdays_dict. You need to use a list or different key (e.x. row['year'], row['month'], row['day']).\nSide note, you can us... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074531906_pandas_python.txt |
Q:
Connect to Milvus standalone server (in docker container) from another docker container on the same host
When I run Milvus in standalone mode on docker (by executing docker-compose on the default Milvus docker-compose.yml file, resulting in the three containers being created), I cannot connect to the Milvus server... | Connect to Milvus standalone server (in docker container) from another docker container on the same host | When I run Milvus in standalone mode on docker (by executing docker-compose on the default Milvus docker-compose.yml file, resulting in the three containers being created), I cannot connect to the Milvus server from a task running in another docker container on the same host. I have configured this container to be on t... | [
"Turns out this is not a Milvus issue. The problem was caused by our corporate network, and the proxy requirement. In the dockerfile, I need to set the proxy settings to be able to pull images. However, this sets the proxy settings during builld and for the container. These proxy settings prevented communication be... | [
0
] | [] | [] | [
"docker",
"milvus",
"python"
] | stackoverflow_0074520985_docker_milvus_python.txt |
Q:
Is 'input' a keyword in Python?
I'm new to Python. I'm writing some code in Sublime and it highlights the word 'input'
I use it as a variable name and it seems to work, so I wondered whether it may be a keyword in a newer version. (I'm currently using 2.7.5)
A:
No, input is not a keyword. Instead, it is a built... | Is 'input' a keyword in Python? | I'm new to Python. I'm writing some code in Sublime and it highlights the word 'input'
I use it as a variable name and it seems to work, so I wondered whether it may be a keyword in a newer version. (I'm currently using 2.7.5)
| [
"No, input is not a keyword. Instead, it is a built-in function.\nAnd yes, you can create a variable with the name input. But please don't. Doing so is a bad practice because it overshadows the built-in (makes it unusable in the current scope).\nIf you must use the name input, the convention is to place an under... | [
54,
0
] | [] | [] | [
"python"
] | stackoverflow_0020670732_python.txt |
Q:
Get historical monthly stock close price in custom format using yfinance
I need to get historical prices of the best stocks in the following format:
[
{'AMZN': [
{'Sep 2022': 113},
{'Oct 2022': 102},
{'Nov 2022': 92}
]},
{'AAPL': [
{'Sep 2022': 137},
{'Oct 2022': 153},
{'Nov 2022': 14... | Get historical monthly stock close price in custom format using yfinance | I need to get historical prices of the best stocks in the following format:
[
{'AMZN': [
{'Sep 2022': 113},
{'Oct 2022': 102},
{'Nov 2022': 92}
]},
{'AAPL': [
{'Sep 2022': 137},
{'Oct 2022': 153},
{'Nov 2022': 147}
]},
{'MSFT': [
{'Sep 2022': 232},
{'Oct 2022': 231},
{'Nov ... | [
"Got it to work:\n[{ticker: [{str(x.strftime('%b %Y')): int(tickerdata[ticker]['Close'][x])} for x in tickerdata[ticker]['Close'].index]} for ticker in tickers]\n\n"
] | [
0
] | [] | [] | [
"data_manipulation",
"dataframe",
"python",
"python_3.x",
"yfinance"
] | stackoverflow_0074524552_data_manipulation_dataframe_python_python_3.x_yfinance.txt |
Q:
Raspberry Pi Camera streaming to multiple clients
In my project I'm making a drone with a raspberry pi. I need to stream video from my raspberry pi camera with as low latency as possible and share that stream to multiple clients. I achieved a simple stream basing on the code :
import io
import picamera
import logg... | Raspberry Pi Camera streaming to multiple clients | In my project I'm making a drone with a raspberry pi. I need to stream video from my raspberry pi camera with as low latency as possible and share that stream to multiple clients. I achieved a simple stream basing on the code :
import io
import picamera
import logging
import socketserver
from threading import Condition... | [
"Video streaming often ends up being a balance between bandwidth, latency and quality.\nMost online movie and live entertainment, sports etc streaming services use HSL or DASH streaming to provide the quality they need and will have a much higher latency that you are aiming for.\nSimilarly, serving many individual ... | [
0
] | [] | [] | [
"picamera",
"python",
"raspberry_pi",
"streaming",
"video_streaming"
] | stackoverflow_0074500671_picamera_python_raspberry_pi_streaming_video_streaming.txt |
Q:
SUMMARIZE (dax) equivalent in Python (Pandas)
I am new using Pandas in Python and I am facing an issue that i am not able to solve alone.
I connecting by odbc,SQL, to get df = the following data:
JDFEC JDCPY JDTMP PALLETS_STOCK
0 2021-06-30 164 N 1256.0
1 2022-01-27 704 ... | SUMMARIZE (dax) equivalent in Python (Pandas) | I am new using Pandas in Python and I am facing an issue that i am not able to solve alone.
I connecting by odbc,SQL, to get df = the following data:
JDFEC JDCPY JDTMP PALLETS_STOCK
0 2021-06-30 164 N 1256.0
1 2022-01-27 704 N 1.0
2 2021-03-14 799 N ... | [
"IIUC, you can use np.select to form the groups and pandas.pivot_table to reshape.\nTry this :\nimport pandas as pd\nimport numpy as np\n\nconditions = [\n df[\"JDCPY\"].isin([539, 109]),\n (df[\"JDCPY\"].eq(455)) & (df[\"JDTMP\"].eq(\"N\"))\n ]\n\ngroups= [\"GROUP-A\",\"GR... | [
0
] | [] | [] | [
"dax",
"pandas",
"python"
] | stackoverflow_0074531217_dax_pandas_python.txt |
Q:
webdriver : can't get the broken links
So I can get url with
driver.get('https://www.w3.org/')
But what I want to test is, if I give a fault link, I should get something like
This page does not exist.
But when I try to capture this, I can't get the result
This is failed, can't report the fault link
link = "https... | webdriver : can't get the broken links | So I can get url with
driver.get('https://www.w3.org/')
But what I want to test is, if I give a fault link, I should get something like
This page does not exist.
But when I try to capture this, I can't get the result
This is failed, can't report the fault link
link = "https://www.w3.org/fault_link"
if driver.find_el... | [
"Your test is failing since you expecting to find non-existing text.\nThis text This page does not exist in not presented on https://www.w3.org/fault_link page.\nWhat you should look for on that specific page is Document not found text.\nSo, this code is working for that specific page:\nurl = \"https://www.w3.org/f... | [
1,
1
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_webdriver",
"webdriver"
] | stackoverflow_0074529013_python_python_3.x_selenium_selenium_webdriver_webdriver.txt |
Q:
Pycharm Error running 'test': can't run remote python interpreter: {0}
When I want to use remote python interpreter to debug my code, but an error appeared:
Error running 'test': Can't run remote python interpreter: {0}. But I could directly run this code with remote python interpreter. I try to use command 'which... | Pycharm Error running 'test': can't run remote python interpreter: {0} | When I want to use remote python interpreter to debug my code, but an error appeared:
Error running 'test': Can't run remote python interpreter: {0}. But I could directly run this code with remote python interpreter. I try to use command 'which python' and 'which python3' to get the different interpreter, but appeared ... | [
"After testing several methods, I finally solved this problem. I clear all the remote interpreter in Pycharm, then restart Pycharm. After secondly adding the remote python interpreter, the debug works normally.\n",
"For me, the solution was to kill all containers belonging to the considered image: by clicking on ... | [
1,
0
] | [] | [] | [
"pycharm",
"python",
"remote_server"
] | stackoverflow_0071494752_pycharm_python_remote_server.txt |
Q:
How to get today's date in SPARQL?
I use Python and SPARQL to make a scheduled query for a database. I tried to use the python f-string and doc-string to inject today's date in the query, but when I try so, a conflict occurs with SPARQL syntax and the python string.
The better way would be to use SPARQL to get tod... | How to get today's date in SPARQL? | I use Python and SPARQL to make a scheduled query for a database. I tried to use the python f-string and doc-string to inject today's date in the query, but when I try so, a conflict occurs with SPARQL syntax and the python string.
The better way would be to use SPARQL to get today's date.
In my python file my query lo... | [
"now() returns the datetime (as xsd:dateTime) of the query execution:\nBIND( now() AS ?currentDateTime ) .\n\nTo get only the date (as xsd:string), you could use CONCAT() with year(), month(), and day():\nBIND( CONCAT( year(?currentDateTime), \"-\", month(?currentDateTime), \"-\", day(?currentDateTime) ) AS ?curren... | [
2
] | [] | [] | [
"date",
"python",
"sparql"
] | stackoverflow_0074532061_date_python_sparql.txt |
Q:
how to compare all values for each row in a dataframe in python
Good morning guys,
my problem is simple:
Given a dataframe like this:
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
'b': [8, 18, 27, 20, 33, 49],
'c': [2, 24, 6, 16, 20, 52]})
print(df)
I... | how to compare all values for each row in a dataframe in python | Good morning guys,
my problem is simple:
Given a dataframe like this:
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
'b': [8, 18, 27, 20, 33, 49],
'c': [2, 24, 6, 16, 20, 52]})
print(df)
I would like to retrieve for each row the maximum value and compare it... | [
"I guess, the below code can help:\nimport pandas as pd\n\ndf = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],\n 'b': [8, 18, 27, 20, 33, 49],\n 'c': [2, 24, 6, 16, 20, 52]})\n\ndef find(x):\n if x > 10:\n return \"yes\"\n else:\n return \"not\"\n\ndf[\"diff\"] = d... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"max",
"python",
"row"
] | stackoverflow_0074531768_dataframe_max_python_row.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.