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:
Trouble diplaying Altair chart on jupyter notebook
I was doing some code for Altair charts and everything was working just fine, and suddenly, when I commando to display a chart, the following message was displayed
Error loading script: Script error for "vega-embed" http://requirejs.org/docs/errors.html#scripterro... | Trouble diplaying Altair chart on jupyter notebook | I was doing some code for Altair charts and everything was working just fine, and suddenly, when I commando to display a chart, the following message was displayed
Error loading script: Script error for "vega-embed" http://requirejs.org/docs/errors.html#scripterror
I've tried clearing the cache and rebooting google chr... | [
"Slighly different problem: Jupyter in VS Code. Restarting VS Code solved the problem.\n"
] | [
0
] | [] | [] | [
"altair",
"charts",
"python"
] | stackoverflow_0066122214_altair_charts_python.txt |
Q:
i am getting an integer division or modulo by zero error on the code
a= int(input())
x=0
i=1
b=round(a/2)
for i in range(b+1):
mod=a%i
if mod != 0:
x=x+1
else:
x=x+0
i=i+1
if x>1:
print("the number is prime number")
else:
print("the number is not prime number")
this is the ... | i am getting an integer division or modulo by zero error on the code | a= int(input())
x=0
i=1
b=round(a/2)
for i in range(b+1):
mod=a%i
if mod != 0:
x=x+1
else:
x=x+0
i=i+1
if x>1:
print("the number is prime number")
else:
print("the number is not prime number")
this is the code for whether to determine a number is prime number or not
in the line ... | [
"Per the documentation for the range type here:\nclass range(stop)\nclass range(start, stop[, step])\n\nThe arguments to the range constructor must be integers (either built-in int or any object that implements the index() special method). If the step argument is omitted, it defaults to 1. If the start argument is ... | [
1
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074230629_for_loop_python.txt |
Q:
An encryption algorithm which accepts a string and does the following steps to mask the string
Following steps:
Sorts the input in descending order
For example:
Input = "zebra"
Output = "aberz
Replace the following letters into numeric
a => 0
j => 9
o => 14
z => 25
Sample Output = "0ber25"
Adds the word "sym" at ... | An encryption algorithm which accepts a string and does the following steps to mask the string | Following steps:
Sorts the input in descending order
For example:
Input = "zebra"
Output = "aberz
Replace the following letters into numeric
a => 0
j => 9
o => 14
z => 25
Sample Output = "0ber25"
Adds the word "sym" at the start of the word
Final Output = "sym0ber25"
I already have a code but it doesn't pass the asse... | [
"Yes, as you can see, the assert statement checks the value that your function returns. So, you will have to return the value. Nobody seems to have asked you to print it!\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074230685_python.txt |
Q:
Python - I can’t import openCV module in replit.com
I’m working with replit.com in python, and i can’t import the openCV module.
When i do this :
import cv2
I have that error :
Traceback (most recent call last):
File
"main. py"
, line 2, in module>
import cv2
File
"/home/runner/rickRolledInConsole/venv/lib/python3... | Python - I can’t import openCV module in replit.com | I’m working with replit.com in python, and i can’t import the openCV module.
When i do this :
import cv2
I have that error :
Traceback (most recent call last):
File
"main. py"
, line 2, in module>
import cv2
File
"/home/runner/rickRolledInConsole/venv/lib/python3.8/site-packages/cv2/.
init
.py", line 181, in
<module>
b... | [
"I didn't find any direct solution for this but you can do your project by forking another repl that doesn't have this kind of problem,here's a repl that you can fork and continue your project.\nopenCV tutorial repl\n"
] | [
0
] | [] | [] | [
"opencv",
"python",
"replit"
] | stackoverflow_0074117305_opencv_python_replit.txt |
Q:
Why does this Image averaging just generates vertical lines?
I am trying to create a program that averages image's pixel values, but so far it has just generated vertical lines.
This is my code so far:
from typing import List
import cv2 as cv
import numpy as np
def main():
# Importing two of the same imagae ... | Why does this Image averaging just generates vertical lines? | I am trying to create a program that averages image's pixel values, but so far it has just generated vertical lines.
This is my code so far:
from typing import List
import cv2 as cv
import numpy as np
def main():
# Importing two of the same imagae for debugigng purposes
a = cv.imread("Datasets/OTIS/OTIS_PNG_... | [
"The issue here is that avg is a shallow copy of a, created by the * multiplication.\nThis means that avg contains multiple references to the same row in a, so when you update avg[i][j], you're actually modifying a[i][j] as well.\nThe result is that every row of avg ends up containing identical values - the last ro... | [
1,
0
] | [] | [] | [
"image_processing",
"numpy",
"opencv",
"python"
] | stackoverflow_0074229817_image_processing_numpy_opencv_python.txt |
Q:
I'm getting this error when trying to run the mlagents-learn command. All the correct versions of the correct packages are installed in a venv
I'm trying to use this toolkit to get the hang of creating machine learning agents in simulations. It seemed like the easiest one out there, so I followed a tutorial from a... | I'm getting this error when trying to run the mlagents-learn command. All the correct versions of the correct packages are installed in a venv | I'm trying to use this toolkit to get the hang of creating machine learning agents in simulations. It seemed like the easiest one out there, so I followed a tutorial from a channel called CodeMonkey. Does anyone know what is going wrong here?
(https://www.youtube.com/watchv=zPFU30tbyKs&ab_channel=CodeMonkey).
'''
Trace... | [
"As user19218911 mentions, Python 3.9 is not compatible. Neither is Python 3.10.\nInstall Python 3.8, create the virtual environment, and download the packages using that version of python.\npy -3.8 -m venv venv\n\nvenv/Scripts/activate\n\npython install torch\n\npython install mlagents\n\nmlagents-learn --help\n\n... | [
1
] | [
"Python 3.9 is not compatible. No idea why.\n"
] | [
-1
] | [
"python",
"unity3d"
] | stackoverflow_0072052434_python_unity3d.txt |
Q:
How can I improve the structure / design of my API?
I was wondering if I could get some software design advice. Hypothetically, let's say that I'm writing an unofficial API for Reddit that lets you log into a Reddit account and manage it, manage messages, view account information, etc., with a wide array of featur... | How can I improve the structure / design of my API? | I was wondering if I could get some software design advice. Hypothetically, let's say that I'm writing an unofficial API for Reddit that lets you log into a Reddit account and manage it, manage messages, view account information, etc., with a wide array of features.
This is the typical pattern I use. All of the code is... | [
"In general, an effective API design will have the following characteristics:\n\nEasy to read and work with: A well-designed API will be easy to work with, and its resources and associated operations can quickly be memorized by developers who work with it constantly.\nHard to misuse: Implementing and integrating wi... | [
0
] | [] | [] | [
"design_patterns",
"oop",
"python",
"python_3.x"
] | stackoverflow_0074230416_design_patterns_oop_python_python_3.x.txt |
Q:
Pandas - Check if two dates are the same with determined conditions (2 more variables) and perform actions
new to pandas, I have a challenge regard checking values and performing multiple actions based on four variables (reception_date,final_date,Status,ID) the problem has the following table:
id ... | Pandas - Check if two dates are the same with determined conditions (2 more variables) and perform actions | new to pandas, I have a challenge regard checking values and performing multiple actions based on four variables (reception_date,final_date,Status,ID) the problem has the following table:
id user_email reception_date end_date status
0 42872 judahena@ia.com.co 3/30/2022 3/30/2022 Accep... | [
"You can use:\n# which rows are Accepted?\nm1 = df['status'].eq('Accepted')\n\n# which rows are In Study?\nm2 = df['status'].eq('In Study')\n\n# get In Study indices that also have an Accepted\n# on the same date\nto_change = (df[m2]\n .reset_index()\n .merge(df[m1],\n left_on=['id', 'end_date'],\n ri... | [
3
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074230740_data_science_dataframe_pandas_python.txt |
Q:
How to split a numpy array with different array lengths (unequal array lengths)
Given an example array (or list), is there a way to split the array into different lengths?
Here is desired input & output such that:
import numpy as np
# Input array
data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ... | How to split a numpy array with different array lengths (unequal array lengths) | Given an example array (or list), is there a way to split the array into different lengths?
Here is desired input & output such that:
import numpy as np
# Input array
data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
# Desired output splited arrays
[array([0, 1, 2, 3, 4, 5, 6, 7]), array... | [
"Hard to know what you want exactly, but assuming you want 8 items for the first list, use numpy.array_split:\ndata = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])\n\nout = np.array_split(data, [8])\n\noutput:\n[array([0, 1, 2, 3, 4, 5, 6, 7]),\n array([ 8, 9, 10, 11, 12, 13, 14, 15, 16,... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074230752_numpy_python.txt |
Q:
Optimum way to plot sine wave from oscilloscope .csv with matplotlib in python
I wish to plot 1 or 2 periods of a sine wave from csv data obtained from an oscilloscope.
the DF columns are
I have managed to produce something workable but it requires manual work for each new set of csv data. I am sure there is a be... | Optimum way to plot sine wave from oscilloscope .csv with matplotlib in python | I wish to plot 1 or 2 periods of a sine wave from csv data obtained from an oscilloscope.
the DF columns are
I have managed to produce something workable but it requires manual work for each new set of csv data. I am sure there is a better way.
The code I have finds the start and end times of one period by obtaining t... | [
"@Tim Roberts that works well, thank you.\nThis function works for a clear wave, with noise and a low amplitude there is an issue as the wave can pass the x axis multiple times in a period.\ndef Plot_wave(df,title, periods, time_col_iloc, amp_col_iloc):\n ## the time and columns location in DF are final 2 argument... | [
0
] | [] | [] | [
"csv",
"matplotlib",
"python"
] | stackoverflow_0074226149_csv_matplotlib_python.txt |
Q:
a program with the pyscreenshot library cannot be played without idle
import pyscreenshot as ImageGrab
image = ImageGrab.grab()
image.save('screen.png')
input()
The program is started only with IDLE, nothing happens when you try to start the program by double-clicking, What could be the problem?
I tried a lot of... | a program with the pyscreenshot library cannot be played without idle | import pyscreenshot as ImageGrab
image = ImageGrab.grab()
image.save('screen.png')
input()
The program is started only with IDLE, nothing happens when you try to start the program by double-clicking, What could be the problem?
I tried a lot of options for solving this problem, nothing came out
| [
"The problem could be multiple Python versions/environments installed on your system, where in IDLE you are in the \"correct\" environment, while the environment invoked via double-clicking is the wrong one.\nYou could check that by placing the first three statements into a try/except block to see any error message... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074224942_python.txt |
Q:
Select the previous date from a list nearest to today's date
I have a list of dates in a .csv and I would like to fetch a date nearest to today's date. How do I achieve that? Issue is in the list, Sat, Sun and holidays are omitted. Can anyone please help?
I don't know how to read data from csv and get the previou... | Select the previous date from a list nearest to today's date | I have a list of dates in a .csv and I would like to fetch a date nearest to today's date. How do I achieve that? Issue is in the list, Sat, Sun and holidays are omitted. Can anyone please help?
I don't know how to read data from csv and get the previous date.
| [
"Since .csv is a text file, you can open it with notepad.exe.\nThen just do some text parsing.\nAbout csv file format: https://en.wikipedia.org/wiki/Comma-separated_values.\nThis code from How to extract numbers from a string in Python? should work to extract numbers form the string.\n[int(s) for s in re.findall(r'... | [
0
] | [] | [] | [
"date",
"python"
] | stackoverflow_0074230852_date_python.txt |
Q:
SQLITE3.OperationalError: near ")": syntax error when creating database
I can't seem to be able to see for myself, what when wrong in this line of codes, have been staring at it for the last 20 min but I can't seem to figure anything out.
here is the error:
Traceback (most recent call last):
File "C:\Users\usera... | SQLITE3.OperationalError: near ")": syntax error when creating database | I can't seem to be able to see for myself, what when wrong in this line of codes, have been staring at it for the last 20 min but I can't seem to figure anything out.
here is the error:
Traceback (most recent call last):
File "C:\Users\usera\PycharmProjects\itptesting_2\itptesting\init_db.py", line 7, in <module>
... | [
"You have a couple of problems, this is the correct syntax:\nCREATE TABLE entries (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n stockname TEXT NOT NULL,\n partnum TEXT NOT NULL,\n company TEXT NOT NULL,\n quantity INTEGER NOT NULL,\n uom TEXT NOT NULL,\n date_recorded DATE NOT NULL DEFAULT (CURRE... | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074230821_python_sqlite.txt |
Q:
I am working with a Dataset, where few values in the Date Column are like ' 2 Months Ago', ' 28 Days Ago', how can we change these dates to Month-Year
I am thinking of trying if condition, but is there any library or method which I don't know about can solve this?
A:
You can subtract actual month-year period wit... | I am working with a Dataset, where few values in the Date Column are like ' 2 Months Ago', ' 28 Days Ago', how can we change these dates to Month-Year |
I am thinking of trying if condition, but is there any library or method which I don't know about can solve this?
| [
"You can subtract actual month-year period with months from values with decimals with month(s) and assign back to DataFrames, for days convert values to timedeltas and subtract actual datetime by Series.rsub for subtract from right side:\nprint (df)\n col\n0 28 days ago\n1 4 months ago\n2 11 month... | [
1,
0
] | [] | [] | [
"data_science",
"dataset",
"date",
"pandas",
"python"
] | stackoverflow_0074230856_data_science_dataset_date_pandas_python.txt |
Q:
ValueError: operands could not be broadcast together with shapes (540,2500) (540,)
i am trying to divide each x-value by its row mean
train_rows_mean = train_data.mean(axis=1) #calculate the mean row_wise
#divide each value by row mean
train_data/train_rows_mean #broadcasting issue
print(train_data.shape) #shape... | ValueError: operands could not be broadcast together with shapes (540,2500) (540,) | i am trying to divide each x-value by its row mean
train_rows_mean = train_data.mean(axis=1) #calculate the mean row_wise
#divide each value by row mean
train_data/train_rows_mean #broadcasting issue
print(train_data.shape) #shape of train data
print(train_rows_mean.shape) #shape of mean
but i get this error
ValueEr... | [
"Assuming train_data is a 2-dimensional array, try:\ntrain_data/train_rows_mean[:, None]\n\nThis adds a new dimension to train_rows_mean before dividing\n",
"As @Mechanic Pig mentioned in his comment, you need to to preserve the dimension so that numpy can broadcast along it. For more information, look at the doc... | [
1,
0
] | [] | [] | [
"array_broadcasting",
"image",
"numpy",
"python"
] | stackoverflow_0074054618_array_broadcasting_image_numpy_python.txt |
Q:
Replace space with underscores python string -
file = 'file1 data ut.pdf'
print(file)
print(type(file))
'file1 data ut.pdf'
<class 'str'>
file.replace(" ","_")
'_f_i_l_e_1_ _d_a_t_a_ _u_t_._p_d_f'
file.replace("","_")
Expected output:
file1_data_ut.pdf
A:
I don't know why replace on your side is not workin... | Replace space with underscores python string - | file = 'file1 data ut.pdf'
print(file)
print(type(file))
'file1 data ut.pdf'
<class 'str'>
file.replace(" ","_")
'_f_i_l_e_1_ _d_a_t_a_ _u_t_._p_d_f'
file.replace("","_")
Expected output:
file1_data_ut.pdf
| [
"I don't know why replace on your side is not working.\nTRY this.\nfile = 'file1 data ut.pdf'\n\n\nprint('_'.join(file.split(' ')))\n\n\nOUTPUT\nfile1_data_ut.pdf\n\n\nExplanation\n\nfile.split(' ') convert string to list by given operator.\n\n\n['file1', 'data', 'ut.pdf']\n\n\n'_'.join() concatenate all the string... | [
0,
0
] | [
"You need to store the updated string in the new variable.\nfile = 'file1 data ut.pdf'\n\nprint(file)\nprint(type(file))\n\nfile=file.replace(\" \",\"_\")\n\n"
] | [
-3
] | [
"python",
"string"
] | stackoverflow_0074230878_python_string.txt |
Q:
Scale Y axis of Altair chart to interactive legend selection
I've copied the interactive legend code from here:
https://altair-viz.github.io/gallery/interactive_legend.html
The difference is that my data has different orders of magnitude for the different series, so it would be nice if, when we select a set of ser... | Scale Y axis of Altair chart to interactive legend selection | I've copied the interactive legend code from here:
https://altair-viz.github.io/gallery/interactive_legend.html
The difference is that my data has different orders of magnitude for the different series, so it would be nice if, when we select a set of series (shift click), we zoom the graph so that it fills the window. ... | [
"You can achieve it by using your selection to filter the data passed to the plot via transform_filter.\nOne this to keep in mind is that we have to pass a custom scale otherwise the filtered data will only show legends for the selected field which leads us to a deadlock.\nimport altair as alt\nfrom vega_datasets i... | [
1
] | [] | [] | [
"altair",
"python",
"vega_lite"
] | stackoverflow_0074225860_altair_python_vega_lite.txt |
Q:
Heroku not recognized as an internal or external command (Windows)
Following this heroku tutorial to launch an app on heroku. But when I use the command heroku create, it says it's not recognized. I added C:\Program Files\Heroku to my PATH. How do I fix this?
A:
You're probably using an old version or the deprec... | Heroku not recognized as an internal or external command (Windows) | Following this heroku tutorial to launch an app on heroku. But when I use the command heroku create, it says it's not recognized. I added C:\Program Files\Heroku to my PATH. How do I fix this?
| [
"You're probably using an old version or the deprecated package 'heroku-cli'. The new one is just called 'heroku'\nUninstall that by \nnpm uninstall -g heroku-cli\n\nThen install the new package \nnpm i -g heroku\n\nAnd now all your works will go perfectly.Just try heroku login and any other heroku command.\nCredit... | [
36,
26,
16,
14,
9,
6,
5,
4,
2,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Close the command prompt and open it again. That fixed my issue.\n",
"Just restart the the PC after setting the path.. It should work.\n",
"This worked for me:\n$'curl https://cli-assets.heroku.com/install.sh | sh' \n\n",
"In my case closing and reopening VS code and terminal worked.\n",
"For me I was not ... | [
-1,
-1,
-1,
-2,
-2
] | [
"cloud",
"heroku",
"heroku_toolbelt",
"python",
"ruby_on_rails"
] | stackoverflow_0042170691_cloud_heroku_heroku_toolbelt_python_ruby_on_rails.txt |
Q:
How to remove a specific combination of letters from the end of every words in a dataframe column?
I want to remove the letters br from the end of every word in my Pandas dataframe column (As you will see, the rows of this column are actually sentances - all different from one another).
Unfortunately, I would alre... | How to remove a specific combination of letters from the end of every words in a dataframe column? | I want to remove the letters br from the end of every word in my Pandas dataframe column (As you will see, the rows of this column are actually sentances - all different from one another).
Unfortunately, I would already cleaned the data without giving much thought to the < br > tags, so I am now left with words like 's... | [
"Use a regex with a word boundary (\\b) to match the end of words:\ndf['text'] = df['text'].str.replace(r'br\\b', '', regex=True)\n\nExample (with assignment as a new column text2):\n text text2\n0 word wordbr bread breadbr word word bread bread\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python",
"regex"
] | stackoverflow_0074230991_dataframe_pandas_python_regex.txt |
Q:
Guided LDA in GenSim with fixed Eta
I wanted to fix topics to include some words, e.g.
Topic 0 - cloud_computing,hybrid_cloud, ...
Topic 1 - smartphone,mobile, ...
So I can across this blog http://scignconsulting.com/2019/03/09/guided-lda/ which attempts to do just that by settings priors for eta.
But what I've f... | Guided LDA in GenSim with fixed Eta | I wanted to fix topics to include some words, e.g.
Topic 0 - cloud_computing,hybrid_cloud, ...
Topic 1 - smartphone,mobile, ...
So I can across this blog http://scignconsulting.com/2019/03/09/guided-lda/ which attempts to do just that by settings priors for eta.
But what I've found is that for large collections of doc... | [
"maybe it is too late for the answer, but in case if someone also will face the same issue:\n1) Think if you really need to keep your custom words are the most important for topic consideration, and if you are sure you want this, go to the next step.\n2) Try to remove normalization for eta, it helped in my case.\nS... | [
2,
0
] | [] | [] | [
"gensim",
"lda",
"python"
] | stackoverflow_0057729538_gensim_lda_python.txt |
Q:
Can I exclude lines starting with #?
Line 4 counts number of lines from response. Trying to exclude lines that start with # from the count.Possible?
def fetch_block_count(session: requests.Session, url: str, timeout: int):
try:
with session.get(url, timeout=10) as response:
dooct = {url: le... | Can I exclude lines starting with #? | Line 4 counts number of lines from response. Trying to exclude lines that start with # from the count.Possible?
def fetch_block_count(session: requests.Session, url: str, timeout: int):
try:
with session.get(url, timeout=10) as response:
dooct = {url: len(resp.text.splitlines())}
ret... | [
"You can trivially use list comprehensions for what you are trying to do:\nUse len([l for l in response.text.splitlines() if len(l)<1 or l[0] != '#'])\n",
"You could exclude the lines that start with \"#\" by applying a filter to a list comprehension as follows:\ndooct = {\n url: len(\n [\n l... | [
1,
1
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074230898_python_python_requests.txt |
Q:
How to use fuzzy process.extract on dictionaries which having values has list of values
Thanks All
If I Want to fuzzy match a string with dictionary where values are in the form of list of values. how can I match each string inside that list and can have output as in dictionary format.
For example:
st = "HTML"... | How to use fuzzy process.extract on dictionaries which having values has list of values | Thanks All
If I Want to fuzzy match a string with dictionary where values are in the form of list of values. how can I match each string inside that list and can have output as in dictionary format.
For example:
st = "HTML"
skills = {
basic: ["HTML","CSS","JS"],
framework: ["Angular", "React"]
}... | [
"You can loop over all items in the dictionary skills and perform fuzzy match between st and the values of keys in the dictionary. Then, store that in a new list result.\nfrom fuzzywuzzy import process\n\nst = \"HTML\"\nskills = {\n \"basic\": [\"HTML\",\"CSS\",\"JS\"],\n \"framework\": [\"Angular\", \"React\"]\n... | [
1
] | [] | [] | [
"fuzzy_search",
"pandas",
"python"
] | stackoverflow_0074230842_fuzzy_search_pandas_python.txt |
Q:
how to use Unique Constraint for same models
I want to create only one object for the same users.
class MyModel(models.Model):
user1 = models.ForeignKey(settings.AUTH_USER_MODEL,...)
user2 = models.ForeignKey(settings.AUTH_USER_MODEL,...)
class Meta:
constraints = [
UniqueConstrain... | how to use Unique Constraint for same models | I want to create only one object for the same users.
class MyModel(models.Model):
user1 = models.ForeignKey(settings.AUTH_USER_MODEL,...)
user2 = models.ForeignKey(settings.AUTH_USER_MODEL,...)
class Meta:
constraints = [
UniqueConstraint(
fields=['user1', 'user2'],
... | [
"Add a constraint that user1_id should be less than user2_id. In that case if you construct a MyModel, for x and y, user1 will always take the user with the smallest primary key and vice versa:\nclass MyModel(models.Model):\n user1 = models.ForeignKey(settings.AUTH_USER_MODEL, …)\n user2 = models.ForeignKey(s... | [
3,
2,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074230719_django_django_models_python.txt |
Q:
Recognizing a new array when reading a CSV into an 3D array with Python
I have the following problem that can't find a solution for:
A .CSV file contains data for multiple 2D arrays as follows:
# Date:20221027-151458
# Array shape (number, width, height): 3, 4, 4)
# Some comments about the data
# some more
1; 2; 3... | Recognizing a new array when reading a CSV into an 3D array with Python | I have the following problem that can't find a solution for:
A .CSV file contains data for multiple 2D arrays as follows:
# Date:20221027-151458
# Array shape (number, width, height): 3, 4, 4)
# Some comments about the data
# some more
1; 2; 3; 4
5; 6; 7; 8
9; 10; 11; 12
#new slice
20; 21; 23; 24
25; 26; 27; 28
29; 30;... | [
"You can try:\ntext = '''# Date:20221027-151458\n# Array shape (number, width, height): 3, 4, 4)\n# Some comments about the data\n# some more\n1; 2; 3; 4\n5; 6; 7; 8\n9; 10; 11; 12\n#new slice\n20; 21; 23; 24\n25; 26; 27; 28\n29; 30; 31; 32\n#new slice\n100; 101; 102; 103\n104; 105; 106; 107\n108; 109; 110; 111\n#n... | [
0
] | [] | [] | [
"arrays",
"csv",
"numpy",
"pandas",
"python"
] | stackoverflow_0074230965_arrays_csv_numpy_pandas_python.txt |
Q:
generator of cartesian products of one list
How do I create a generator of cartesian products of one list without itertools or any imports?
I tried doing a simple
for x in iterable[0]:
for y in iterable[1]:
yield (x: y)
but it doesn't work for all cases
list = [(1,2), (2,3)]
output = (1, 2), (1,3), (2, 2), (2,3)
... | generator of cartesian products of one list | How do I create a generator of cartesian products of one list without itertools or any imports?
I tried doing a simple
for x in iterable[0]:
for y in iterable[1]:
yield (x: y)
but it doesn't work for all cases
list = [(1,2), (2,3)]
output = (1, 2), (1,3), (2, 2), (2,3)
the results should look like this
| [
"use itertools.product\nfrom itertools import product\nfor i in product([1, 2, 3], [4, 5, 6]):\n print(i)\n# (1, 4) (1, 5) (1, 6) (2, 4) (2, 5) (2, 6) (3, 4) (3, 5) (3, 6) \n\nwithout itertools you can use recursion like this\nfrom collections.abc import Iterable\ndef generate_product(*args):\n if not args:\n... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074231062_python.txt |
Q:
How to keep many specific strings in pandas dataframe
I have a dataframe with specific columns that looks like this:
colA
['work', 'time', 'money', 'home', 'good', 'financial']
['school', 'lazy', 'good', 'math', 'sad', 'important', 'dizzy', 'go']
['frame', 'happy', 'feel', 'youth', 'change', 'home', 'p... | How to keep many specific strings in pandas dataframe | I have a dataframe with specific columns that looks like this:
colA
['work', 'time', 'money', 'home', 'good', 'financial']
['school', 'lazy', 'good', 'math', 'sad', 'important', 'dizzy', 'go']
['frame', 'happy', 'feel', 'youth', 'change', 'home', 'past']
['first', 'eat', 'good', 'hungry', 'empty', 'fool... | [
"Use ast.literal_eval with list comprehension for filter matched values:\nimport ast\n\ns = set(word)\ndf['new'] = df['colA'].apply(lambda x: [y for y in ast.literal_eval(x) if y in s])\nprint (df)\n colA \\\n0 ['work', 'time', 'money', 'home', 'good', 'fin... \n1 ... | [
1,
0
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python",
"string"
] | stackoverflow_0074231091_dataframe_list_pandas_python_string.txt |
Q:
How to fix the issue of {sqlite3.OperationalError: unable to open database file} in aws-ec2 instance ubuntu machine?
I am trying to deploy this telegram bot(https://github.com/odysseusmax/utube/) on AWS-ec2 instance which is using ubuntu-20.
At the start everything is fine until I got this error:
sqlite3.Operation... | How to fix the issue of {sqlite3.OperationalError: unable to open database file} in aws-ec2 instance ubuntu machine? | I am trying to deploy this telegram bot(https://github.com/odysseusmax/utube/) on AWS-ec2 instance which is using ubuntu-20.
At the start everything is fine until I got this error:
sqlite3.OperationalError: unable to open database file
let me give some solution if you know how to solve this issue:
Traceback (most rece... | [
"I think there is a error in repo that why i was getting this error. Sorry for interrupt you all. I have solved it with a fresh installation. Thank You!!\n"
] | [
0
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"pyrogram",
"python",
"sqlite"
] | stackoverflow_0074230467_amazon_ec2_amazon_web_services_pyrogram_python_sqlite.txt |
Q:
How to go to another page after a function executes flask python
I have a function called getTableData() which runs another function get_table() and based on that get_table() output final function is called which renders a template and also routes to a different page.
So the problem is its not routing to a differ... | How to go to another page after a function executes flask python | I have a function called getTableData() which runs another function get_table() and based on that get_table() output final function is called which renders a template and also routes to a different page.
So the problem is its not routing to a different url (/tabdata) from get_final() function
Flask code:
@app.route('/... | [
"In getTableData(), change\nreturn get_final(df_time)\n\nto\nreturn redirect(url_for(\"get_final\", df_time=df_time))\n\nIn get_final(), change\n@app.route(\"/tabdata\") \ndef get_final(df_time):\n return render_template(\"new.html\",df_time = df_time)\n\nto\n@app.route(\"/tabdata/<df_time>\")\ndef get_final(df... | [
0,
0,
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074230975_flask_python.txt |
Q:
Creating an Altair bar chart of the frequency of each letter in a sentence entered by the user help python
Unsure how I can get this to work. Any ideas are appreciated. Thanks.
import altair
user_input = input('Enter something here')
user_input_count = user_input.count
data = altair.Data(letters = user_input, num... | Creating an Altair bar chart of the frequency of each letter in a sentence entered by the user help python | Unsure how I can get this to work. Any ideas are appreciated. Thanks.
import altair
user_input = input('Enter something here')
user_input_count = user_input.count
data = altair.Data(letters = user_input, number = user_input_count)
altair.Chart(data).mark_bar().encode(x = 'letters:N', y = 'number:N').display()
| [
"There are multiple ways to extract the frequency of a letter in a string.\nHere is an example using Counter from collections:\nimport altair\n\nfrom collections import Counter\n\nuser_input = input('Enter something here')\n# get letter frequency as a dictionairy\nuser_input_count = Counter(user_input)\n# format di... | [
0,
0
] | [] | [] | [
"altair",
"python"
] | stackoverflow_0074225697_altair_python.txt |
Q:
Install Frappe Framework - bench: command not found
I am new to python and Frappe framework. I followed the steps provided in the following link to install Frappe framework on my Mac OS Sierra.
Frappe Bench Github
After successfully installing Python, MariaDB, Node JS, Redis and wkhtmltopdf (with patched qt) I cre... | Install Frappe Framework - bench: command not found | I am new to python and Frappe framework. I followed the steps provided in the following link to install Frappe framework on my Mac OS Sierra.
Frappe Bench Github
After successfully installing Python, MariaDB, Node JS, Redis and wkhtmltopdf (with patched qt) I created new folder named "FrappeSample" and run the followin... | [
"In my case the bench command is found here:\n frappe@ubuntu:~/frappe-bench$ whereis bench\n bench: /usr/local/bin/bench\n\nwith /usr/local/bin on my PATH:\nfrappe@ubuntu:~/frappe-bench$ echo $PATH\n/home/frappe/bin:/home/frappe/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n\nTo add /us... | [
2,
0,
0,
0
] | [] | [] | [
"bash",
"git",
"installation",
"pip",
"python"
] | stackoverflow_0048005872_bash_git_installation_pip_python.txt |
Q:
Create a DataFrame in Pandas with variable number of columns
Good afternoon,
Here is my problem: I have a Pandas dataframe that looks like it:
Birth_Year Name
1964 [X, Y]
1965 [A, B]
1964 [F, G, H]
I need to transform it to the following:
Birth_Year Name_1 Name_... | Create a DataFrame in Pandas with variable number of columns | Good afternoon,
Here is my problem: I have a Pandas dataframe that looks like it:
Birth_Year Name
1964 [X, Y]
1965 [A, B]
1964 [F, G, H]
I need to transform it to the following:
Birth_Year Name_1 Name_2 Name_3
1964 X Y
1965 ... | [
"Assuming you have real lists in \"Name\", you can use:\ndf = df.join(pd.DataFrame(df.pop('Name').tolist(), index=df.index)\n .fillna('')\n .rename(columns=lambda c: f'Name_{c+1}')\n )\n\nOutput:\n Birth_Year Name_1 Name_2 Name_3\n0 1964 X Y \n1 ... | [
2,
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074226704_dataframe_pandas_python.txt |
Q:
Stuggling locating elements to click with Selenium in python - code had worked initially but unexpectedly stopped
I'm using Selenium to gather the difference in total price of several items (including taxes and shipping cost) from a Shopify based website. I've so far successfully been able to add items to my cart.... | Stuggling locating elements to click with Selenium in python - code had worked initially but unexpectedly stopped | I'm using Selenium to gather the difference in total price of several items (including taxes and shipping cost) from a Shopify based website. I've so far successfully been able to add items to my cart. This requires adding the selected items to the cart, and then going to the checkout page, updating city, zip, and stat... | [
"Looks like the position of the element is not stable. You need to search for the element more precisely.\nReplace checkout = driver.find_element(By.XPATH,'/html/body/div[2]/div[5]/div[3]/div/form/div[2]/div[2]/div[3]/div[2]').click() by checkout = driver.find_element(By.XPATH, '//button[@name=\"checkout\"]').click... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_edgedriver",
"web_scraping",
"xpath"
] | stackoverflow_0074228800_python_selenium_selenium_edgedriver_web_scraping_xpath.txt |
Q:
ImportError: No module named six
I'm trying to build OpenERP project, done with dependencies. It's giving this error now
Traceback (most recent call last):
File "openerp-client.py", line 105, in <module>
File "modules\__init__.pyo", line 23, in <module>
File "modules\gui\__init__.pyo", line 22, in <module>
... | ImportError: No module named six | I'm trying to build OpenERP project, done with dependencies. It's giving this error now
Traceback (most recent call last):
File "openerp-client.py", line 105, in <module>
File "modules\__init__.pyo", line 23, in <module>
File "modules\gui\__init__.pyo", line 22, in <module>
File "modules\gui\main.pyo", line 33,... | [
"You probably don't have the six Python module installed. You can find it on pypi.\nTo install it:\n$ easy_install six\n\n(if you have pip installed, use pip install six instead)\n",
"If pip \"says\" six is installed but you're still getting:\nImportError: No module named six.moves\ntry re-installing six (worked ... | [
156,
60,
32,
28,
5,
3,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"importerror",
"module",
"python"
] | stackoverflow_0013967428_importerror_module_python.txt |
Q:
How to get previous min and max values in new columns for each group?
In each new row of dataframe, I need to keep track of min and max values for a previous group of records.
Create dataframe with input data:
import pandas as pd
columns = ['timestamp','groupid','value']
data = [['2022-10-14 11:47:38',1000,... | How to get previous min and max values in new columns for each group? | In each new row of dataframe, I need to keep track of min and max values for a previous group of records.
Create dataframe with input data:
import pandas as pd
columns = ['timestamp','groupid','value']
data = [['2022-10-14 11:47:38',1000,200],
['2022-10-14 11:47:39',1000,210],
['2022-10-1... | [
"Build the dataframe of aggregation and shifts, and merge to get the final output:\ngrp = df.groupby('groupid')['value']\nmin_max = grp.agg(['min', 'max'])\npmin_max = min_max.add_prefix('p').shift(fill_value = 0)\nppmin_max = min_max.add_prefix('p').shift(2, fill_value = 0).add_prefix('p')\nother = pd.concat([min_... | [
2,
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074229371_group_by_pandas_python.txt |
Q:
How do I fix this code so that it doesn't take out vowels that are consecutive of one another?
Hey guys so I'm writing a code for text message abbreviations and these are the following criteria:
Spaces are maintained, and each word is encoded individually. A word is a consecutive string of alphabetic characters.
... | How do I fix this code so that it doesn't take out vowels that are consecutive of one another? | Hey guys so I'm writing a code for text message abbreviations and these are the following criteria:
Spaces are maintained, and each word is encoded individually. A word is a consecutive string of alphabetic characters.
If the word is composed only of vowels, it is written exactly as in the original message.
If the wor... | [
"Your three Vowel-functions are all using a disfunctional for-loop and are highly redundant. Also Vowel() would always return 0, as x may never be a tuple of five vowels.\nYou would need only one function that just returns True if the character is a vowel and False if it is not. Then, you can use this function in t... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074230459_python_python_3.x.txt |
Q:
Create buttons from instances of a class
So I am trying to build a restaurant menu.
I want to create buttons based on instances of class Food:
class Food:
instances=[]
def __init__(self,name,price):
self.name=name
self.price=price
Food.instances.append(self)
def __iter__(self):... | Create buttons from instances of a class | So I am trying to build a restaurant menu.
I want to create buttons based on instances of class Food:
class Food:
instances=[]
def __init__(self,name,price):
self.name=name
self.price=price
Food.instances.append(self)
def __iter__(self):
for item in Food.instances:
... | [
"All i did was adding\nlist_aux = Food.instances.copy()\n\nIn the get_buttons() function\nAnd removing it from the global space to not pollute it. This will create the buttons from the class, get all the information I wanted to get when creating the buttons, and still keep the original array in place so i can have ... | [
0
] | [] | [] | [
"oop",
"python",
"tkinter"
] | stackoverflow_0073238766_oop_python_tkinter.txt |
Q:
Selenium + Python: Why am I getting this no attribute error?
This is the error that is returned in my console:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_link_text'
When I look at the source code of the site I am using, the link I want is inside of this iframe, although I can clearly see ... | Selenium + Python: Why am I getting this no attribute error? | This is the error that is returned in my console:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_link_text'
When I look at the source code of the site I am using, the link I want is inside of this iframe, although I can clearly see the link and iframe tag are not on separate source pages, so I ass... | [
"Looks like you are using Selenium 4.\nSelenium 4 does not support find_element_by_link_text as well as any other find_element_by_* methods.\nA new syntax should be used, as following:\ndriver.find_element(By.LINK_TEXT, \"the link text goes here\").click()\n\nIn the same manner it will be\ndriver.find_element(By.XP... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium4",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074229267_python_selenium_selenium4_selenium_chromedriver_selenium_webdriver.txt |
Q:
why I am getting (TypeError: must be real number, not list) while doing gridsearchcv?
I am trying to make ML model for cifar dataset; this is the code:
clf = SVC(kernel='rbf')
grid = {'C':[1,10,100,1000],'gamma':[[1,10,100,1000]]}
res = gs(clf,grid)
res.fit(x_train,y_train)
#clf.fit(x_train,cls_train)
#y_pred = cl... | why I am getting (TypeError: must be real number, not list) while doing gridsearchcv? | I am trying to make ML model for cifar dataset; this is the code:
clf = SVC(kernel='rbf')
grid = {'C':[1,10,100,1000],'gamma':[[1,10,100,1000]]}
res = gs(clf,grid)
res.fit(x_train,y_train)
#clf.fit(x_train,cls_train)
#y_pred = clf.predict(x_test)
print(res.best_estimator_)
| [
"In the params for the grid seach try to give single dimensional list as mentioned below.\npython grid = {'C':[1,10,100,1000],'gamma':[1,10,100,1000]} \n"
] | [
0
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"svm"
] | stackoverflow_0074231216_machine_learning_python_scikit_learn_svm.txt |
Q:
custom cutter has invalid Lhs or Rhs
I'm trying to write a custom separator (aka, MIP cutter) to my SCIP model (in Python). To do this I need to detect which constraints are tight/binding at the given MIP node. I thought that I could do this by comparing LHS to RHS on the rows (aka, the constraints). However, one ... | custom cutter has invalid Lhs or Rhs | I'm trying to write a custom separator (aka, MIP cutter) to my SCIP model (in Python). To do this I need to detect which constraints are tight/binding at the given MIP node. I thought that I could do this by comparing LHS to RHS on the rows (aka, the constraints). However, one of the two always reports +/- 1e20. Why is... | [
"I think there is a misunderstanding. All rows in SCIP are ranged rows, i.e., they are of the form lhs <= a^Tx (+constant) <= rhs. When a model contains inequalities with only one side (as seems to be the case for you) then the non-existant side is set to either 1e20 for the rhs (SCIPs infinity value) or -1e20 for ... | [
0
] | [] | [] | [
"pyscipopt",
"python",
"scip",
"simplex_algorithm"
] | stackoverflow_0074227935_pyscipopt_python_scip_simplex_algorithm.txt |
Q:
Discord Bot Issues
I am extremely new to doing this. I tried making a simple Discord bot off of YouTube and it wasn't recognizing that had the pip install discord installed. When I input import discord on my script it said that there was a module error.
So then I tried recreating the bot under a new token and new ... | Discord Bot Issues | I am extremely new to doing this. I tried making a simple Discord bot off of YouTube and it wasn't recognizing that had the pip install discord installed. When I input import discord on my script it said that there was a module error.
So then I tried recreating the bot under a new token and new script in a new virtual ... | [
"Your code is probably fine. Looking at the error logs it seems your code cannot connect to discord.\n"
] | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0072468210_discord_python.txt |
Q:
How can I determine the BMI for an n amount of students, whose weights will be randomly generated in the range of 100-300lbs?
I'm stuck on this part of my homework that says:
"Generate weights for 100 students in the range of 100 to 300 pounds. Determinethe BMI for each student. Determine BMI my status for each st... | How can I determine the BMI for an n amount of students, whose weights will be randomly generated in the range of 100-300lbs? | I'm stuck on this part of my homework that says:
"Generate weights for 100 students in the range of 100 to 300 pounds. Determinethe BMI for each student. Determine BMI my status for each student."
I already have my def function to calculate the BMI status and a BMI formula, but I can't figure out a way to actually gene... | [] | [] | [
"Yes, you would have to generate random weights in between 100 and 300.\nHere's a python function for the same,\nimport random\nweights = []\nfeet = []\ninches = []\nfor x in range(100):\n weights.append(random.randint(100, 300))\n feet.append(random.randint(0, 12))\n inches.append(random.randint(1, 6))\n\... | [
-1
] | [
"python"
] | stackoverflow_0074231356_python.txt |
Q:
Why mySQLclient is not installed
I want to install the MySQLclient package on my Cpanel host through the terminal. Because I want to connect my Django project to the database.
When I want to install the necessary packages, everyone installs except MySQLClient.
It also gives an error:
Collecting mysqlclient
Using... | Why mySQLclient is not installed | I want to install the MySQLclient package on my Cpanel host through the terminal. Because I want to connect my Django project to the database.
When I want to install the necessary packages, everyone installs except MySQLClient.
It also gives an error:
Collecting mysqlclient
Using cached mysqlclient-2.1.0.tar.gz (87 k... | [
"I got the following types of error while installing mysqlclient\n\nerror: subprocess-exited-with-error (Running setup.py install for\nmysqlclient did not run successfully)\n\nPython Error: Command 'X86_64-Linux-Gnu-Gcc' Failed With Exit Status 1 With Code Examples\n\n\n\nLet's solve this problem using the followin... | [
0,
-2
] | [] | [] | [
"cpanel",
"django",
"mysql",
"pip",
"python"
] | stackoverflow_0071310570_cpanel_django_mysql_pip_python.txt |
Q:
Snakemake tutorial error: "AttributeError: 'str' object has no attribute 'name' "
When I try running the first command (snakemake -np mapped_reads/A.bam) from the Step 1 of Snakemake tutorial (https://snakemake.readthedocs.io/en/stable/tutorial/basics.html) I get the following error:
snakemake -np mapped_reads/A.b... | Snakemake tutorial error: "AttributeError: 'str' object has no attribute 'name' " | When I try running the first command (snakemake -np mapped_reads/A.bam) from the Step 1 of Snakemake tutorial (https://snakemake.readthedocs.io/en/stable/tutorial/basics.html) I get the following error:
snakemake -np mapped_reads/A.bam
Building DAG of jobs...
Traceback (most recent call last):
File "/home/jeremi1504/... | [
"You hit this bug https://github.com/snakemake/snakemake/issues/1899\nTry upgrading snakemake to the latest version or, if can't, downgrade tabulate to 0.8.\n"
] | [
2
] | [] | [] | [
"attributeerror",
"python",
"snakemake"
] | stackoverflow_0074226320_attributeerror_python_snakemake.txt |
Q:
The ways to make selenium faster
I was trying to grab some information on the one site, where I need to get phone numbers. The full telephone number is hidden, so to search for the full number I need to use selenium. However, it needs to sleep for 0.2 seconds(found it empirically). I have 10000 phones to parse, so... | The ways to make selenium faster | I was trying to grab some information on the one site, where I need to get phone numbers. The full telephone number is hidden, so to search for the full number I need to use selenium. However, it needs to sleep for 0.2 seconds(found it empirically). I have 10000 phones to parse, so alltogether it works a lot of time an... | [
"There are few possible points to optimize:\n\nStart from switch from xpath to css locators. They work the way faster.\nTry to \"play\" with querying bunches of elements and parse the collection in your code.\nParallelize your code. You could make your threads process a single page or a bunch of pages.\nCheck diffe... | [
0
] | [] | [] | [
"parsing",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074228978_parsing_python_selenium_selenium_webdriver.txt |
Q:
DLL error while adding the environment into the jupyter notebook
I recently installed anaconda and created a new environment in a different location outside of anaconda base directory.
So I created the environment:
python -m venv tfod
Activated it
.\tensorflowenv\Scripts\activate
Upgraded pip and installed ipyke... | DLL error while adding the environment into the jupyter notebook | I recently installed anaconda and created a new environment in a different location outside of anaconda base directory.
So I created the environment:
python -m venv tfod
Activated it
.\tensorflowenv\Scripts\activate
Upgraded pip and installed ipykernel
python -m pip install --upgrade pip
pip install ipykernel
Issue ... | [
"This isn't the exact \"solution\" for this but its a work around.\nI created an environment using conda navigator and downloaded the required packages from navigator itself and then added the env into jupyter kernel using\npython -m ipykernel install --user --name=tensorflowenv\n\nStill would be happy if someone c... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"virtual_environment"
] | stackoverflow_0074228149_jupyter_notebook_python_virtual_environment.txt |
Q:
How can I clean up my anaconda base environment? (e.g., I don't need astropy, statsmodels, and ~400 other packages)
How can I just uninstall all of the non-essential packages and reinstall what I need? By essential, I'm referring to just enough to run command line conda software so I can build my base environment ... | How can I clean up my anaconda base environment? (e.g., I don't need astropy, statsmodels, and ~400 other packages) | How can I just uninstall all of the non-essential packages and reinstall what I need? By essential, I'm referring to just enough to run command line conda software so I can build my base environment additively (No GUI necessary).
I've been trying to install mamba in my base environment and it's taking hours b/c of all ... | [
"As for the Mamba installation issue, uninstalling Numpy solved the problem for me.\nconda uninstall numpy\nalso uninstalled more than 100 packages that depend on it.\nAfter that,\nconda install mamba -n base -c conda-forge\nworked like a breeze after that (about a minute)\n"
] | [
0
] | [] | [] | [
"anaconda",
"conda",
"installation",
"package",
"python"
] | stackoverflow_0072468746_anaconda_conda_installation_package_python.txt |
Q:
Can't access an option element of a select tag in Selenium
I am having trouble selecting an option in a dropdown. I am using Selenium in Python.
Here is the HTML code:
<select class="hm-input hm-dropdown" type="text" id="HME-10-
widget_calendar_1" style="height: 2.2em; width: 233px; font-
family: arial; padding:... | Can't access an option element of a select tag in Selenium | I am having trouble selecting an option in a dropdown. I am using Selenium in Python.
Here is the HTML code:
<select class="hm-input hm-dropdown" type="text" id="HME-10-
widget_calendar_1" style="height: 2.2em; width: 233px; font-
family: arial; padding: 0px; margin: 0px; font-size: 11px;
display: none;" data-role="... | [
"Change your locator to (By.XPATH, '//*[@id=\"HME-10-widget_calendar_1\"]') or even better to (By.ID, 'HME-10-widget_calendar_1')\n"
] | [
0
] | [] | [] | [
"html",
"python",
"selenium"
] | stackoverflow_0074227985_html_python_selenium.txt |
Q:
How to save a predicted image in Amazon Sagemaker?
In my inference.py I have the following:
def output_fn(prediction, content_type):
assert content_type == 'application/json'
mask = prediction['mask']
mask = np.where(mask==2, 255, mask)
mask = np.where(mask==1, 128, mask)
trimap = mask.astype(n... | How to save a predicted image in Amazon Sagemaker? | In my inference.py I have the following:
def output_fn(prediction, content_type):
assert content_type == 'application/json'
mask = prediction['mask']
mask = np.where(mask==2, 255, mask)
mask = np.where(mask==1, 128, mask)
trimap = mask.astype(np.uint8)
trimap_image = Image.fromarray(trimap).resi... | [
"Based on the type of inference job, you have 2 options you can follow to fulfil your requirement.\n0. Upload during inference (less correct)\nThis is the easiest method, but less clean. In fact, you make a step that should not be included in the inference. The sagemaker inference has the task of producing a result... | [
1
] | [] | [] | [
"amazon_sagemaker",
"computer_vision",
"machine_learning",
"python"
] | stackoverflow_0074229203_amazon_sagemaker_computer_vision_machine_learning_python.txt |
Q:
Unused args [...] for include of [...]- Error launching ROS file
I'm trying to pass an argument to a launch file and I keep getting the error. The main launch file looks like this:
<?xml version="1.0"?>
<launch>
<arg name="logging" default="screen" />
<arg name="ship_velocity" default="0.1" /> <!-- velocity b... | Unused args [...] for include of [...]- Error launching ROS file | I'm trying to pass an argument to a launch file and I keep getting the error. The main launch file looks like this:
<?xml version="1.0"?>
<launch>
<arg name="logging" default="screen" />
<arg name="ship_velocity" default="0.1" /> <!-- velocity between 0 and 5 m/s -->
<arg name="ship_waypoints" default="[[2,6],[2... | [
"I think the problem could be inside your main launch file.\nIn <node pkg=\"simple_control\" type=\"ship_following_controller.py\" name=\"ship_following_controller_node\" output=\"screen\"> you have some strange arg elements\nThe node element doesn't support the arg element.\nYou can check it here\nhttp://wiki.ros.... | [
0
] | [] | [] | [
"launch",
"python",
"ros",
"xml"
] | stackoverflow_0074224058_launch_python_ros_xml.txt |
Q:
Why am I getting a html file instead of json?
#import libraries
import requests
import pandas as pd
import time
import json
#request the api endpoint
url = "https://api.opensea.io/api/v1/asset/0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb/1/owners?limit=20&order_by=created_date&order_direction=desc"
response = requ... | Why am I getting a html file instead of json? | #import libraries
import requests
import pandas as pd
import time
import json
#request the api endpoint
url = "https://api.opensea.io/api/v1/asset/0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb/1/owners?limit=20&order_by=created_date&order_direction=desc"
response = requests.get(url)
print(response.text)
I was trying g... | [
"\nfirst of all use format json in url like\n\nyour url\nhttps://api.opensea.io/api/v1/asset/0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb/1/owners?limit=20&order_by=created_date&order_direction=desc\nchanged url (just add its format to json)\nhttps://api.opensea.io/api/v1/asset/0xb47e3cd837ddf8e4c57f05d70ab865de6e193... | [
0
] | [] | [] | [
"api",
"fetch_api",
"python",
"python_requests"
] | stackoverflow_0074231401_api_fetch_api_python_python_requests.txt |
Q:
Pandas: Get cell value by row index and column name
Let's say we have a pandas dataframe:
name age sal
0 Alex 20 100
1 Jane 15 200
2 John 25 300
3 Lsd 23 392
4 Mari 21 380
Let's say, a few rows are now deleted and we don't know the indexes that have been deleted. For example, we delete r... | Pandas: Get cell value by row index and column name | Let's say we have a pandas dataframe:
name age sal
0 Alex 20 100
1 Jane 15 200
2 John 25 300
3 Lsd 23 392
4 Mari 21 380
Let's say, a few rows are now deleted and we don't know the indexes that have been deleted. For example, we delete row index 1 using df.drop([1]). And now the data frame com... | [
"Use .loc to get rows by label and .iloc to get rows by position:\n>>> df.loc[3, 'age']\n23\n\n>>> df.iloc[2, df.columns.get_loc('age')]\n23\n\nMore about Indexing and selecting data\n",
"dataset = ({'name':['Alex', 'Jane', 'John', 'Lsd', 'Mari'],\n 'age': [20, 15, 25, 23, 21],\n 'sal': [100, 200, 300... | [
10,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0070931002_pandas_python.txt |
Q:
PyTorch get all layers of model
What's the easiest way to take a pytorch model and get a list of all the layers without any nn.Sequence groupings? For example, a better way to do this?
import pretrainedmodels
def unwrap_model(model):
for i in children(model):
if isinstance(i, nn.Sequential): unwrap_mo... | PyTorch get all layers of model | What's the easiest way to take a pytorch model and get a list of all the layers without any nn.Sequence groupings? For example, a better way to do this?
import pretrainedmodels
def unwrap_model(model):
for i in children(model):
if isinstance(i, nn.Sequential): unwrap_model(i)
else: l.append(i)
mod... | [
"You can iterate over all modules of a model (including those inside each Sequential) with the modules() method. Here's a simple example:\n>>> model = nn.Sequential(nn.Linear(2, 2), \n nn.ReLU(),\n nn.Sequential(nn.Linear(2, 1),\n nn.Sigmoid... | [
34,
9,
9,
2,
2,
1,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0054846905_python_pytorch.txt |
Q:
python - Finding the user's "Downloads" folder
I already found this question that suggests to use os.path.expanduser(path) to get the user's home directory.
I would like to achieve the same with the "Downloads" folder. I know that this is possible in C#, yet I'm new to Python and don't know if this is possible her... | python - Finding the user's "Downloads" folder | I already found this question that suggests to use os.path.expanduser(path) to get the user's home directory.
I would like to achieve the same with the "Downloads" folder. I know that this is possible in C#, yet I'm new to Python and don't know if this is possible here too, preferable platform-independent (Windows, Ubu... | [
"from pathlib import Path\ndownloads_path = str(Path.home() / \"Downloads\")\n\n",
"This fairly simple solution (expanded from this reddit post) worked for me\nimport os\n\ndef get_download_path():\n \"\"\"Returns the default downloads path for linux or windows\"\"\"\n if os.name == 'nt':\n import wi... | [
40,
25,
15,
12,
1,
0
] | [] | [] | [
"directory",
"python",
"special_folders"
] | stackoverflow_0035851281_directory_python_special_folders.txt |
Q:
Operation_Precedence_in_Python
Could someone explain to me about operator precedence? For eg. Modulo(%), integer division(//), exponential(**) What comes first, second, third and so on. Also please help me with the output of the following code and with step by step explanation:
print(8 % 3 ** 4 // 3 + 2)
I coudnt... | Operation_Precedence_in_Python | Could someone explain to me about operator precedence? For eg. Modulo(%), integer division(//), exponential(**) What comes first, second, third and so on. Also please help me with the output of the following code and with step by step explanation:
print(8 % 3 ** 4 // 3 + 2)
I coudnt understand about Operator Precedenc... | [
"This is the Operator Precedence from parentheses to logical or operator.\nif you have parentheses and logical or operator in your expression.\nparentheses will be evaluated first and logical or operator will be evaluated last due to order of operator precedence.\nAssociativity is when you have operators of same pr... | [
3
] | [] | [] | [
"jupyter_notebook",
"operator_precedence",
"operators",
"python"
] | stackoverflow_0074231584_jupyter_notebook_operator_precedence_operators_python.txt |
Q:
AttributeError: Can't pickle local object 'SharedMemoryDisplay.__init__..'
I am working with this object SharedMemoryDisplay in the above script and I want to return/retrieve self.camera_container, where self.camera_container = {camera_id: (camera_id, frame, frame_properties)}
I tried to create a method to return ... | AttributeError: Can't pickle local object 'SharedMemoryDisplay.__init__..' | I am working with this object SharedMemoryDisplay in the above script and I want to return/retrieve self.camera_container, where self.camera_container = {camera_id: (camera_id, frame, frame_properties)}
I tried to create a method to return the this but it gives two errors
prop, camera_container = monitor_memory.get_... | [
"multiprocessing uses pickle under the hood. pickle can serialize only a certain set of objects. Specifically, it can not serialize defaultdict (a type for your camera_container). So, either use a normal dict and replace all the lookups to self.camera_container.get(key, None), or look into this question and try to ... | [
1
] | [] | [] | [
"pickle",
"python",
"python_multiprocessing"
] | stackoverflow_0074231547_pickle_python_python_multiprocessing.txt |
Q:
pandas groupby join data with"|" but exclude null,nan,emptystring,whitespace
here is the sample data for my question
pid
date
task
language
8522
17-09-2022
listen
english
7851
17-09-2022
read
hindi
7546
17-09-2022
telugu
3584
write
8522
18-09-2022
read
7851
19-09-2022
hindi
8522
speak
hindi
7546
19-09... | pandas groupby join data with"|" but exclude null,nan,emptystring,whitespace | here is the sample data for my question
pid
date
task
language
8522
17-09-2022
listen
english
7851
17-09-2022
read
hindi
7546
17-09-2022
telugu
3584
write
8522
18-09-2022
read
7851
19-09-2022
hindi
8522
speak
hindi
7546
19-09-2022
speak
english
3584
write
tamil
8522
25-09-2022
i t... | [
"You can use pandas.Series.dropna in the lambda expression before joining.\nHere is what works for me:\nout = (\n df\n .groupby('pid')[['date','task','language']]\n .agg(lambda x: '|'.join(x\n .replace(r'^\\s*$', np.nan, regex=True)\n .dropna()\n ... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"python"
] | stackoverflow_0074231697_dataframe_group_by_python.txt |
Q:
python Selenium taking instance of webdriver
i defined two separate functions for opening url with selenium, and fetching data with selenium.
In my second function driver variable is unassignable because it stays local inside first function.
I do not know if it s logical to separate selenium activity in two separa... | python Selenium taking instance of webdriver | i defined two separate functions for opening url with selenium, and fetching data with selenium.
In my second function driver variable is unassignable because it stays local inside first function.
I do not know if it s logical to separate selenium activity in two separate ways, I use this method first time.
Any suggest... | [
"As I see, you trying to parse data from each URL you opening in goToUrl_Se(). If so the better way is to put the parsing data code inside the loop used in goToUrl_Se() method.\nAlso, no need to define and create driver each time.\nAnd you definitely have to improve your locators. Very long absolute XPaths are extr... | [
1,
1,
0
] | [] | [] | [
"function",
"instanceof",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074231561_function_instanceof_python_selenium_selenium_webdriver.txt |
Q:
Replace single quotes with doubles to turn contents of a file into a nested JSON and normalize it afterwards
I have 70k files all of which look similar to this:
{'id': 24, 'name': None, 'city': 'City', 'region_id': 19,
'story_id': 1, 'description': 'text', 'uik': None, 'ustatus': 'status',
'wuiki_tik_name': '', 'r... | Replace single quotes with doubles to turn contents of a file into a nested JSON and normalize it afterwards | I have 70k files all of which look similar to this:
{'id': 24, 'name': None, 'city': 'City', 'region_id': 19,
'story_id': 1, 'description': 'text', 'uik': None, 'ustatus': 'status',
'wuiki_tik_name': '', 'reaction': None, 'reaction_official': '',
'created_at': '2011-09-07T07:24:44.420Z', 'lat': 54.7, 'lng': 20.5,
'regi... | [
"If you only need to change ' to \":\n...\nfor file in path:\n with open(file, \"r\") as filer:\n filer.replace(\"\\'\", \"\\\"\")\n...\n\nMaking copies and using grep would be easier\n",
"While it is not the solution I was initially expecting, this approach worked as well. I kept getting error messages... | [
1,
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074217479_json_pandas_python.txt |
Q:
How can i get a list in an os.system command, i want to do this so that i can randomise the color the text becomes
Here is part of the code, I've done most of it but I cant find a way to implement it into the command.
color_list = [0,1,2,3,4,5,6,7]
SHUFFLE(color_list)
os.system('color (color_list[0])')
A:
Use ... | How can i get a list in an os.system command, i want to do this so that i can randomise the color the text becomes | Here is part of the code, I've done most of it but I cant find a way to implement it into the command.
color_list = [0,1,2,3,4,5,6,7]
SHUFFLE(color_list)
os.system('color (color_list[0])')
| [
"Use a f-string like this:\nl = [1, 2, 3]\n\ntext = f'the first element in l is {l[0]}'\n\ntext would now be equal to: \"the first element in l is 1\"\nor for your example:\nos.system(f'color {color_list[0]}')\n\n"
] | [
0
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0074231875_operating_system_python.txt |
Q:
Cloud function get oauth2 token python api
I am having trouble sending an authenticated firestore REST API request from a cloud function. The request needs to have an oauth2 token in the header. I've followed the docs here https://cloud.google.com/functions/docs/securing/authenticating and tried the python functio... | Cloud function get oauth2 token python api | I am having trouble sending an authenticated firestore REST API request from a cloud function. The request needs to have an oauth2 token in the header. I've followed the docs here https://cloud.google.com/functions/docs/securing/authenticating and tried the python function they provided, but that still does not give th... | [
"The solution in my case was to add datastore.importExportAdmin \"Cloud Datastore Import Export Admin\" role to the service account that would generate the token. And to use the code below to generate a token from credentials:\ncredentials = service_account.Credentials.from_service_account_file(\nSERVICE_ACCOUNT_FI... | [
1
] | [] | [] | [
"google_cloud_firestore",
"google_cloud_functions",
"google_cloud_platform",
"google_oauth",
"python"
] | stackoverflow_0074229968_google_cloud_firestore_google_cloud_functions_google_cloud_platform_google_oauth_python.txt |
Q:
Nextcord Slash Command Not Responding
I am trying to make a Discord bot with slash commands using Python's nextcord module. My invite link uses both bot and applications.commands scopes.
I've started with a ping command using examples I've found online. My code looks like this:
import nextcord, os
from dotenv impo... | Nextcord Slash Command Not Responding | I am trying to make a Discord bot with slash commands using Python's nextcord module. My invite link uses both bot and applications.commands scopes.
I've started with a ping command using examples I've found online. My code looks like this:
import nextcord, os
from dotenv import load_dotenv
from nextcord.ext import com... | [
"I've discovered the answer through this StackExchange post. I needed to use embed=await embed() as shown here:\nawait interaction.followup.send(embed=await embed(...))\n\n"
] | [
0
] | [] | [] | [
"nextcord",
"python"
] | stackoverflow_0074051840_nextcord_python.txt |
Q:
finding common genes from Gene list
pathway=(list(set(genes.iloc[0]).intersection(genes.iloc[i+1]))),(list(set(genes.iloc1).intersection(genes.iloc[i+2]))),(list(set(genes.iloc[2]).intersection(genes.iloc[i+3]))),(list(set(genes.iloc[3]).intersection(genes.iloc[i+4])
Instead of writing 0,1,2 to specify indeces, ... | finding common genes from Gene list | pathway=(list(set(genes.iloc[0]).intersection(genes.iloc[i+1]))),(list(set(genes.iloc1).intersection(genes.iloc[i+2]))),(list(set(genes.iloc[2]).intersection(genes.iloc[i+3]))),(list(set(genes.iloc[3]).intersection(genes.iloc[i+4])
Instead of writing 0,1,2 to specify indeces, Is there any way to loop through the inde... | [
"for j in [0,1,2,3]:\n pathway=(list(set(genes.iloc[j]).intersection(genes.iloc[i+j+1])))\n #do something with pathway\n\nTake a look here for more info on loops\n"
] | [
2
] | [] | [] | [
"indexing",
"python"
] | stackoverflow_0074231961_indexing_python.txt |
Q:
How to write an inline-comment in Python
Is there a method of ending single line comments in Python?
Something like
/* This is my comment */ some more code here...
A:
No, there are no inline comments in Python.
From the documentation:
A comment starts with a hash character (#) that is not part of a
string l... | How to write an inline-comment in Python | Is there a method of ending single line comments in Python?
Something like
/* This is my comment */ some more code here...
| [
"No, there are no inline comments in Python. \nFrom the documentation:\n\nA comment starts with a hash character (#) that is not part of a\n string literal, and ends at the end of the physical line. A comment\n signifies the end of the logical line unless the implicit line joining\n rules are invoked. Comments ... | [
88,
46,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"comments",
"python"
] | stackoverflow_0024872745_comments_python.txt |
Q:
Python script runs without error but fails to print output to file or screen
I have been a java developer for long and this is my first encounter with python. I found a jumbled up python code and worked on it to make it readable and executable. I have achieved both, but I do not get output for the program. Can som... | Python script runs without error but fails to print output to file or screen | I have been a java developer for long and this is my first encounter with python. I found a jumbled up python code and worked on it to make it readable and executable. I have achieved both, but I do not get output for the program. Can someone help me understand if it is a syntactical or logical error that is causing th... | [
"Thank you everyone for your support. The problem was pretty simple, really. As pointed out, it was the \"continue\" statement that caused the issue.\ncorrected syntax\nApart from that, the code also has a small error that can lead to array index out of bound exception.\nPorting the code to pycharm helped. Here is ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"syntax"
] | stackoverflow_0074231542_python_python_3.x_syntax.txt |
Q:
How to check if a aws redshift table is present or not
I have an use case where I need to do the followings:
1.Check if redshift_db.redhsift_tbl is present or not? If table is present then perform operation A else perform operation B.
I was checking in boto3 documentation to get an api which will tell whether or n... | How to check if a aws redshift table is present or not | I have an use case where I need to do the followings:
1.Check if redshift_db.redhsift_tbl is present or not? If table is present then perform operation A else perform operation B.
I was checking in boto3 documentation to get an api which will tell whether or not the table is present but no luck. What is the best way to... | [
"There are 2 ways you can go. If you are using an external orchestration tool then this tool can query the catalog tables (pg_table_def or stv_tbl_perm) and issue the appropriate next commands based on the result. Or if you need Redshift to do this then you will need create a stored procedure to take the correct ... | [
1,
0
] | [] | [] | [
"amazon_redshift",
"amazon_web_services",
"python"
] | stackoverflow_0069198161_amazon_redshift_amazon_web_services_python.txt |
Q:
How to deal with Mongodb Null values
I have some sample data here. What the code is supposed to do is to remove any words inside. However, occasionally mongo throws in a Null value or an empty string.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1],[4],[25],['asd123'],['asdf1']]),
... | How to deal with Mongodb Null values | I have some sample data here. What the code is supposed to do is to remove any words inside. However, occasionally mongo throws in a Null value or an empty string.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1],[4],[25],['asd123'],['asdf1']]),
columns=['account'])
df["accou... | [
"Because you're trying to convert \"\" to an integer. Just delete the \"\" when getting the data, with this line df.drop(df[df.account == \"\"].index, inplace=True)\nThis would be your modified code\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.array([[1],[4],[25],['asd123'],['']]),\n ... | [
0
] | [] | [] | [
"dataframe",
"python",
"string"
] | stackoverflow_0074231877_dataframe_python_string.txt |
Q:
Fastest way to add column to dataframe containing boolen
If I have a pandas dataframe A that looks like:
index id some_number some_other_number
1 42 1.2 32
2 54 1.3 33
3 66 3.4 64
4 77 4.7 12
and another, dfB, with this:
index id some_number some_oth... | Fastest way to add column to dataframe containing boolen | If I have a pandas dataframe A that looks like:
index id some_number some_other_number
1 42 1.2 32
2 54 1.3 33
3 66 3.4 64
4 77 4.7 12
and another, dfB, with this:
index id some_number some_other_number
1 42 1.2 32
2 99 1.3 33
... | [
"It might be faster to do this operation outside of pandas, something like this:\nprepared_set = set(dfB(\"id\"))\ndfA[\"id_is_in_dfB\"] = [value in prepared_set for value in dfA[\"id\"].values]\n\nCan't confirm that in your exact case it will be faster, because it may depend on tables size.\nFurther improvement m... | [
0
] | [
"Try this approach:\ndfB['id_is_in_dfB'] = dfA['id']==dfB['id']\n\n"
] | [
-1
] | [
"optimization",
"pandas",
"python"
] | stackoverflow_0074224013_optimization_pandas_python.txt |
Q:
regex find long and short vowels
I have a list of words in various languages, that make use of more than the usual five vowels (a,e,i,o,u). I am using regex to divide these words into syllables after a vowel-consonant pair. For words like "ahotnikil" I use re.match("^[a|e|i|y|o|u|}|@]", word) to get the correct se... | regex find long and short vowels | I have a list of words in various languages, that make use of more than the usual five vowels (a,e,i,o,u). I am using regex to divide these words into syllables after a vowel-consonant pair. For words like "ahotnikil" I use re.match("^[a|e|i|y|o|u|}|@]", word) to get the correct segmentation, ['a', 'hot', 'ni', 'kil']
... | [
"You can use\nre.match(\"[aeiyou}@]|ɔ|ə|ī\", word)\n\nNote: re.match will look for matches at the start of string by default. If you need to detect these chars anywhere inside a word, use re.search.\nDetails:\n\n[aeiyou}@] - a char from the aeiyou}@ set\n| - or\nɔ - a ɔ char\n| - or\nə - a ə char\n| - or\nī - a ī c... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074232054_python_regex.txt |
Q:
How to set column width to bestFit in openpyxl
I have filled a worksheet with some data and I'm trying to make column widths to assume their best fit, as in here. Basically the kind of autofit that happens when you double-click the column width adjustment separator.
This is my minimal example, which, as far as my ... | How to set column width to bestFit in openpyxl | I have filled a worksheet with some data and I'm trying to make column widths to assume their best fit, as in here. Basically the kind of autofit that happens when you double-click the column width adjustment separator.
This is my minimal example, which, as far as my understanding of openpyxl documentation goes, should... | [
"After many hours of research finally, I found it.\nNOTE : In the below code, sheet is the worksheet name. Usually in the documentation, we can see it as ws. Please don't forget to change the worksheet name.\n# Imorting the necessary modules\ntry:\n from openpyxl.cell import get_column_letter\nexcept ImportE... | [
11,
3,
0
] | [
"I used some like this:\nfrom openpyxl.worksheet.dimensions import ColumnDimension\n\nwb = Workbook()\nws = wb.active\nColumnDimension(ws, bestFit=True)\n\n"
] | [
-1
] | [
"openpyxl",
"python"
] | stackoverflow_0060248319_openpyxl_python.txt |
Q:
trying to get text from html via xpath with scrapy "Mobilya"
Below is the HTML, I am working on and I am trying to get "Gardroplar" text but it return me empty
start with <ol class="nav align-items-center flex-nowrap text-nowrap overflow-auto hide-scrollbar>
<li>
<a href="/">
<svg class="icon-home m-0">
... | trying to get text from html via xpath with scrapy "Mobilya" | Below is the HTML, I am working on and I am trying to get "Gardroplar" text but it return me empty
start with <ol class="nav align-items-center flex-nowrap text-nowrap overflow-auto hide-scrollbar>
<li>
<a href="/">
<svg class="icon-home m-0">
<use
xlink:href="/_ui/responsive/theme-alpha/images/icon... | [
"In case icon-arrow2 class is fixed value there you can use the following XPath:\n\"//li[./*[contains(@class,'icon-arrow2')]]//a\"\n\nThe complete command is\nresponse.xpath(\"//li[./*[contains(@class,'icon-arrow2')]]//a/text()\").getall()\n\nUPD\nAfter you shared the actual link to that page I can give you better ... | [
3,
2
] | [] | [] | [
"html",
"python",
"scrapy",
"xpath"
] | stackoverflow_0074231883_html_python_scrapy_xpath.txt |
Q:
How to pass a JSON or DICT into a dataframe with pandas?
I have this JSON/DICT in Python and I need to pass it to a datframe:
{
"filters": [
{
"field": "example1",
"operation": "like",
"values": [
"Completed"
]
},
{
... | How to pass a JSON or DICT into a dataframe with pandas? | I have this JSON/DICT in Python and I need to pass it to a datframe:
{
"filters": [
{
"field": "example1",
"operation": "like",
"values": [
"Completed"
]
},
{
"field": "example2",
"operation": "like",
... | [
"Try:\ndct = {\n \"filters\": [\n {\"field\": \"example1\", \"operation\": \"like\", \"values\": [\"Completed\"]},\n {\n \"field\": \"example2\",\n \"operation\": \"like\",\n \"values\": [\n \"value1\",\n \"value2\",\n \"... | [
3,
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074228995_json_pandas_python.txt |
Q:
Need to match exact decimal output Python
The German mathematician Gottfried Leibniz developed the following method to approximate the value of π:
π/4 = 1 - 1/3 + 1/5 - 1/7 + . . .
Write a program that allows the user to specify the number of iterations used in this approximation and that displays the resulting va... | Need to match exact decimal output Python | The German mathematician Gottfried Leibniz developed the following method to approximate the value of π:
π/4 = 1 - 1/3 + 1/5 - 1/7 + . . .
Write a program that allows the user to specify the number of iterations used in this approximation and that displays the resulting value.
An example of the program input and output... | [
"\"\"\"pure step by step Leibniz idea\n'sign'-- sign switcher. If you need the sum of even divisors \nsumm +1/1 (n=0), +1/5 (n=2), +1/9 (n=4), sign is True.\nWith each odd divisible, 'sign' changes to False, changing the \nsign of the next term, summ -1/3 (n=1), -1/7 (n=3), -1/11 (n=5), etc..\n\"\"\"\n\niteration =... | [
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0066926911_algorithm_python.txt |
Q:
403 HTML Error Code when sending request to lexica.art using Python
I need to get all image prompts from the https://lexica.art/?q=history request, but the website returns 403 error code when I am trying to send a request.
I already tried to set User-Agent property, and copied all the request properties, but it st... | 403 HTML Error Code when sending request to lexica.art using Python | I need to get all image prompts from the https://lexica.art/?q=history request, but the website returns 403 error code when I am trying to send a request.
I already tried to set User-Agent property, and copied all the request properties, but it still isn't working.
Here is my code:
import requests
url="https://lexica.... | [
"I used selenium library instead, everything is working fine\n"
] | [
0
] | [] | [] | [
"html",
"python",
"web_scraping"
] | stackoverflow_0074180892_html_python_web_scraping.txt |
Q:
Reading saved email file with “.msg” extension, in local disk
How to read email file (saved email to local drive, with “.msg” extension)?
I tried this 2 lines and it doesn't work out.
msg = open('Departure HOUSTON EXPRESS Port NORFOLK.msg', 'r')
print msg.read()
I searched the web for an answer, which gave the... | Reading saved email file with “.msg” extension, in local disk | How to read email file (saved email to local drive, with “.msg” extension)?
I tried this 2 lines and it doesn't work out.
msg = open('Departure HOUSTON EXPRESS Port NORFOLK.msg', 'r')
print msg.read()
I searched the web for an answer, which gave the below code:
import email
def read_MSG(file):
email_File = open... | [
"The code you have now looks to be completely unworkable for what you're trying to accomplish. You need to parse Outlook \".msg\" files, which can be done in Python but not using the email module. But if you can use \".eml\" files as you mentioned, it will be easier because the email module can read those.\nTo re... | [
2,
1
] | [] | [] | [
"email",
"parsing",
"python"
] | stackoverflow_0026839088_email_parsing_python.txt |
Q:
How await in async is differ from normal execution in python?
I have two function kitchen() and waiter(). In waiter() I have awaited kitchen() function. I know that if I await the function it will be waiting untill that particular function returns. Here, in waiter await kitchen() means "Wait until the kitchen() fu... | How await in async is differ from normal execution in python? |
I have two function kitchen() and waiter(). In waiter() I have awaited kitchen() function. I know that if I await the function it will be waiting untill that particular function returns. Here, in waiter await kitchen() means "Wait until the kitchen() function returns something". I have doubt that what is the use of th... | [
"If you define an async function, say:\nasync def fun1():\n return 10\n\nwhen you call the function:\n>>> fun1()\n<coroutine object fun1 at xxxxx>\n\nAs you can see, it returns a \"coroutine\". This coroutine needs to be executed by an \"async event loop\".\nawait is the keyword that means \"execute this corouti... | [
0
] | [] | [] | [
"asynchronous",
"coroutine",
"python",
"python_asyncio"
] | stackoverflow_0074221048_asynchronous_coroutine_python_python_asyncio.txt |
Q:
How do I convert a English phrasing of a number(string) to integer in Python?
Write a Python program that takes an English phrasing of a number as a string s and outputs
the corresponding integer x. You can assume the number is positive and less than 1,000,000. You can also
assume that the s is always correct. s d... | How do I convert a English phrasing of a number(string) to integer in Python? | Write a Python program that takes an English phrasing of a number as a string s and outputs
the corresponding integer x. You can assume the number is positive and less than 1,000,000. You can also
assume that the s is always correct. s does not contain any spaces.
So far, I have my dictionary
'# ones
num2words = ... | [
"not sure whether helps: maybe using regex to search whether key matches?\nthen twenty-seven and 'twenty seven' would match key twentyseven\nimport re\n\ntxt = \"twenty seven\"\ntxt = \"twenty-seven\"\nx = re.search(\"twenty.*seven\", txt)\nprint(x)\n\n",
"This module https://pypi.org/project/word2number/ can hel... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"integer",
"python",
"string"
] | stackoverflow_0074231834_dictionary_integer_python_string.txt |
Q:
Pandas dataframe hide index functionality?
Is it possible to hide the index when displaying pandas DataFrames, so that only the column names appear at the top of the table?
This would need to work for both the html representation in ipython notebook and to_latex() function (which I'm using with nbconvert).
A:
As... | Pandas dataframe hide index functionality? | Is it possible to hide the index when displaying pandas DataFrames, so that only the column names appear at the top of the table?
This would need to work for both the html representation in ipython notebook and to_latex() function (which I'm using with nbconvert).
| [
"As has been pointed out by @waitingkuo, index=False is what you need. If you want to keep the nice table layout within your ipython notebook, you can use:\nfrom IPython.display import display, HTML\ndisplay(HTML(df.to_html(index=False)))\n\n",
"Starting from v. 0.17.1 it is possible to hide the index via styling... | [
42,
41,
35,
5,
1,
1,
1
] | [] | [] | [
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0021256013_jupyter_notebook_pandas_python.txt |
Q:
How can I arrange the output in ascending order given a list
I have to generate 13 objects in random the output must in ascending order or from highest in ranking, it is as follows
Order of suits from lowest to highest is Clubs, Diamonds, Hearts, Spades
order of values from lowest to highest is 2, 3, 4, 5, 6, 7, 8... | How can I arrange the output in ascending order given a list | I have to generate 13 objects in random the output must in ascending order or from highest in ranking, it is as follows
Order of suits from lowest to highest is Clubs, Diamonds, Hearts, Spades
order of values from lowest to highest is 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A
My code prints 13 random cards but there is no... | [
"Printing\nYou can take advantage of the sep argument to print. We'll flatten a generator expression to create string representations of each card, and specify these separate items printed should be separated by ',' with '\\n' being printed at the end.\nprint(*(f\"{c}-{s}\" for c, s in deck), sep=',', end='\\n')\n\... | [
1,
1,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074231455_python_python_3.x.txt |
Q:
problem getting data for an html in python with flask
Hello i am doing a proyect in pyhton with flask an i pretend to introduce a txt and read it.
This code is part of home.html:
<input type="file" id="gameTXT" name="gameTXT" accept="txt">
<input type="submit" id="submitTXT" value="Submit">
and this one is the pa... | problem getting data for an html in python with flask | Hello i am doing a proyect in pyhton with flask an i pretend to introduce a txt and read it.
This code is part of home.html:
<input type="file" id="gameTXT" name="gameTXT" accept="txt">
<input type="submit" id="submitTXT" value="Submit">
and this one is the part of python:
@app.route("/")
def home():
return render... | [
"if you want to get the file, you need to first know what is your form method, as you mentioned GET, I assume GET. (But I insert POST just in case).\nYou need to create the function, mentioning that the method is GET, and then you need to get the data that was send, which is request.form['name']\nGet the data recei... | [
1
] | [
"Try adding method in the route() like this :\n@app.route(\"/\", methods=[\"GET\"])\ndef home():\n return render_template('home.html')\n\n"
] | [
-2
] | [
"flask",
"python"
] | stackoverflow_0074232180_flask_python.txt |
Q:
Difference between Python2 and Python3 when bytes are written to a file
There seems to be a difference between Python2 and Python3 when bytes are written to a file.
I would like to know why Python3 suddenly starts writing bytes differently than Python2. Furthermore, what are the needed code changes to achieve the ... | Difference between Python2 and Python3 when bytes are written to a file | There seems to be a difference between Python2 and Python3 when bytes are written to a file.
I would like to know why Python3 suddenly starts writing bytes differently than Python2. Furthermore, what are the needed code changes to achieve the same output as with Python2.
The following Python code writes bytes to a file... | [
"In Python 2, the str type was used for two different kinds of values – text and bytes, whereas in Python 3, these are separate and incompatible types.\nIf you want your values to be bytes then you need to put b before the quotes.\nYou will then get an error from the write command\nTypeError: write() argument must ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074225167_python.txt |
Q:
Converting CSV to numpy NPY efficiently
How to convert a .csv file to .npy efficently?
I've tried:
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
While the above works for smallish file, the actual .csv file I'm working on has ~12 million lines... | Converting CSV to numpy NPY efficiently | How to convert a .csv file to .npy efficently?
I've tried:
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
While the above works for smallish file, the actual .csv file I'm working on has ~12 million lines with 1024 columns, it takes quite a lot to l... | [
"Nice question; Informative in itself.\nI understand you want to have the whole data set/array in memory, eventually, as a NumPy array. I assume, then, you have enough (RAM) memory to host such array -- 12M x 1K.\nI don't specifically know about how np.loadtxt (genfromtxt) is operating behind the scenes, so I will ... | [
4,
1,
1,
1,
0
] | [] | [] | [
"csv",
"feature_store",
"numpy",
"python",
"tensor"
] | stackoverflow_0074054668_csv_feature_store_numpy_python_tensor.txt |
Q:
How can I subselect a value in django querySelector?
I will exlplain my question with an example:
lets say I am able to extract an object with this form with my filter:
{ a, b, c : {x, y, z} }
But what I am trying to do, is to get the object as following:
{ a, b, c : {x} }
{ a, b, c : {y} }
{ a, b, c : {z} }
if my... | How can I subselect a value in django querySelector? | I will exlplain my question with an example:
lets say I am able to extract an object with this form with my filter:
{ a, b, c : {x, y, z} }
But what I am trying to do, is to get the object as following:
{ a, b, c : {x} }
{ a, b, c : {y} }
{ a, b, c : {z} }
if my question isn't clear enough don't hesitate to ask for mo... | [
"You can make a queryset from author for getting what you want to:\nqueryset = Author.objects.filter(entry_set__pub_date__year=2006)\nqueryset = queryset.prefetch_related(\"entry_set\")\nqueryset = queryset.prefetch_related(\"entry_set__author_set\")\nqueryset = queryset.prefetch_related(\"entry_set__blog\")\n\nWit... | [
0
] | [] | [] | [
"django",
"filter",
"python"
] | stackoverflow_0074223325_django_filter_python.txt |
Q:
How to run {gunicorn | or any python program} as python3
When I run gunicorn, python2 is always executed.
gunicorn -c gunicorn_config.py app:app
...
ps -ef | grep gunicorn
user 34877 1 0 16:31 ? 00:00:00 /usr/bin/python2 /usr/bin/gunicorn -c gunicorn_config.py app:app
user 34883 34877 0 16:... | How to run {gunicorn | or any python program} as python3 | When I run gunicorn, python2 is always executed.
gunicorn -c gunicorn_config.py app:app
...
ps -ef | grep gunicorn
user 34877 1 0 16:31 ? 00:00:00 /usr/bin/python2 /usr/bin/gunicorn -c gunicorn_config.py app:app
user 34883 34877 0 16:31 ? 00:00:00 /usr/bin/python2 /usr/bin/gunicorn -c gun... | [
"It took too much time, but it was too simple.\nI can check where the gunicorn is with the following command. (Already installed python3)\n$ whereis gunicorn\ngunicorn: /usr/bin/gunicorn /usr/local/bin/gunicorn\n\nand then, I check two file.\n$ vim /usr/local/bin/gunicorn\n \n #!/usr/bin/python3\n ...\n ... | [
0
] | [] | [] | [
"gunicorn",
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0074232372_gunicorn_python_python_2.x_python_3.x.txt |
Q:
I was creating my own palindrome program when I came across that if I use [ ] for 'if' loop, every time it printed the 'if' statement
The use of parentheses for 'if' loop results in two different output for a palindrome program!
1.) () this gives the accurate result
2.) [] this only gives you the result of 'if' st... | I was creating my own palindrome program when I came across that if I use [ ] for 'if' loop, every time it printed the 'if' statement | The use of parentheses for 'if' loop results in two different output for a palindrome program!
1.) () this gives the accurate result
2.) [] this only gives you the result of 'if' statement even if the "String" is not a palindrome
def isapalindrome(String):
if(String == String[::-1]):
return("is a palindrome... | [
"() and [] are nothing alike.\n() does what you expect it to, but wouldn't even be necessary since there is only one operator.\n[] will create a list with a single element that equals the truth value of String == String[::-1], so either [True] or [False]. Independently of what the list contains, non-empty list in p... | [
2,
0
] | [] | [] | [
"parentheses",
"python"
] | stackoverflow_0074232064_parentheses_python.txt |
Q:
calculate the average for the given assignment and will return the average. PYTHON
I've been writing this code, but it seem to work.
This function takes two parameters, the entire list of students and an integer
indicating which assignment (0, 1, 2 or 3) you wish to find the average for.
You will need to ... | calculate the average for the given assignment and will return the average. PYTHON | I've been writing this code, but it seem to work.
This function takes two parameters, the entire list of students and an integer
indicating which assignment (0, 1, 2 or 3) you wish to find the average for.
You will need to add the two parameters to the function
declaration.
The function will calculate... | [
"Erros I can see:\nYour assignment_number will never equal to a range. What you probably want to do is assignment_number in range(0,3).\nCan't see why you would assignement_number= students[0][1] this will always overwrite it with Jane's scores\n",
"Does this code solve your problem?\ndef AverageAssignment(studen... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074231921_python.txt |
Q:
GCP Cloud Logging wont add trace to structured logs
I'm trying to make structured logging where the custom logs are connected to a trace from a Python service. This is the logging payload being sent to Cloud Logging
logging_payload = {
"time": "",
"severity": "",
"message": "",
... | GCP Cloud Logging wont add trace to structured logs | I'm trying to make structured logging where the custom logs are connected to a trace from a Python service. This is the logging payload being sent to Cloud Logging
logging_payload = {
"time": "",
"severity": "",
"message": "",
"custom_labels": {},
"logging.googleapis.com/... | [
"As per your JSON Payload you didn't mention the values which need to be given in the Payload format. For LOGEntry need to mention fields and its values as below :\n\nlogging.googleapis.com/labels : \"logging.googleapis.com/labels\":\n{\"user_label_1\":\"value_1\",\"user_label_2\":\"value_2\"}\nlogging.googleapis.... | [
1
] | [] | [] | [
"google_cloud_logging",
"google_cloud_platform",
"logging",
"python"
] | stackoverflow_0074217810_google_cloud_logging_google_cloud_platform_logging_python.txt |
Q:
How do I check if PyTorch is using the GPU?
How do I check if PyTorch is using the GPU? The nvidia-smi command can detect GPU activity, but I want to check it directly from inside a Python script.
A:
These functions should help:
>>> import torch
>>> torch.cuda.is_available()
True
>>> torch.cuda.device_count()
... | How do I check if PyTorch is using the GPU? | How do I check if PyTorch is using the GPU? The nvidia-smi command can detect GPU activity, but I want to check it directly from inside a Python script.
| [
"These functions should help:\n>>> import torch\n\n>>> torch.cuda.is_available()\nTrue\n\n>>> torch.cuda.device_count()\n1\n\n>>> torch.cuda.current_device()\n0\n\n>>> torch.cuda.device(0)\n<torch.cuda.device at 0x7efce0b03be0>\n\n>>> torch.cuda.get_device_name(0)\n'GeForce GTX 950M'\n\nThis tells us:\n\nCUDA is av... | [
698,
187,
64,
49,
22,
20,
12,
9,
6,
4,
2,
2,
0
] | [
"Create a tensor on the GPU as follows:\n$ python\n>>> import torch\n>>> print(torch.rand(3,3).cuda()) \n\nDo not quit, open another terminal and check if the python process is using the GPU using:\n$ nvidia-smi\n\n",
"Using the code below\nimport torch\ntorch.cuda.is_available()\n\nwill only display whether the ... | [
-1,
-1
] | [
"gpu",
"memory_management",
"nvidia",
"python",
"pytorch"
] | stackoverflow_0048152674_gpu_memory_management_nvidia_python_pytorch.txt |
Q:
Can we reset chrome extension's trial version in selenium?
I am using selenium and have loaded an extension 'NopeCha' (which solves ReCaptchas) in my driver. But the extension in its trial version only gives 100 solves in free trial.
I was wondering if there was a trick to reset it, so I can use the 100 solves aga... | Can we reset chrome extension's trial version in selenium? | I am using selenium and have loaded an extension 'NopeCha' (which solves ReCaptchas) in my driver. But the extension in its trial version only gives 100 solves in free trial.
I was wondering if there was a trick to reset it, so I can use the 100 solves again!
My Code:
#for randomizing user agent
from fake_useragent imp... | [] | [] | [
"Have you tried your browser simulation with TOR browser, maybe it will grant your wish.\n"
] | [
-1
] | [
"google_chrome_extension",
"python",
"selenium"
] | stackoverflow_0074204290_google_chrome_extension_python_selenium.txt |
Q:
Error open file after saving it with storeFile of pysmb
I am reading an Excel file (.xlsx) with pysmb.
import tempfile
from smb.SMBConnection import SMBConnection
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
conn.connect(server_ip, 139)
file_obj = tempfile.Tempo... | Error open file after saving it with storeFile of pysmb | I am reading an Excel file (.xlsx) with pysmb.
import tempfile
from smb.SMBConnection import SMBConnection
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
conn.connect(server_ip, 139)
file_obj = tempfile.TemporaryFile()
file_attributes, filesize = conn.retrieveFile(ser... | [
"I found a solution an I will post it here in case someone face a similar issue.\nExcel can be save as a binary stream.\nfrom io import BytesIO\n\ndf = pd.read_excel(file_obj)\noutput = BytesIO()\nwriter = pd.ExcelWriter(output, engine='xlsxwriter')\ndf.to_excel(writer, sheet_name='data', index = False)\nwriter.sav... | [
0
] | [] | [] | [
"pysmb",
"python",
"samba",
"temporary_files"
] | stackoverflow_0074224799_pysmb_python_samba_temporary_files.txt |
Q:
Django change upgrade MSSQL database
I have a Django app that was running without any problem with SQL server 2008,
I have an issue like this after I upgraded the MS SQL server 2008 into 2019.
I didn't change anything in the code but when I'm calling the DB, I face this error:
42000', '[42000] [Microsoft][ODBC Dr... | Django change upgrade MSSQL database | I have a Django app that was running without any problem with SQL server 2008,
I have an issue like this after I upgraded the MS SQL server 2008 into 2019.
I didn't change anything in the code but when I'm calling the DB, I face this error:
42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot ... | [
"SQL Server never had a REGEXP_LIKE function. It doesn't have any regular expression functions. It seems someone created a custom method with that name in SQL Server 2008 which wasn't migrated to the new database.\nThe SQL Server backend is provided by the mssql-django package. The source shows that the module inst... | [
0,
0
] | [] | [] | [
"python",
"sql_server"
] | stackoverflow_0074193324_python_sql_server.txt |
Q:
PyDrive: Invalid client secrets file
I am trying to use PyDrive to get a list of all files in my Google Drive. I have read through the docs and completed all steps. I have client secrets.json saved down, but I continue to get the following error. The code I am using is:
from pydrive.auth import GoogleAuth
from pyd... | PyDrive: Invalid client secrets file | I am trying to use PyDrive to get a list of all files in my Google Drive. I have read through the docs and completed all steps. I have client secrets.json saved down, but I continue to get the following error. The code I am using is:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = Goo... | [
"Based on the error log, your program cannot find the file: 'client_secrets.json'. This file is essential as it helps identify your program to the Google API.\nSteps to get the authentication going:\n\nRequest Google Drive API access through Google Cloud Console\nSteps explained at: https://pythonhosted.org/PyDriv... | [
16,
3,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"pydrive",
"python",
"python_2.7"
] | stackoverflow_0028184419_pydrive_python_python_2.7.txt |
Q:
Trying to list the 1st and second column but all text are indexed as one
Im trying to put into list two seperate column from an input file but they are all indexed the same how do i fix this.
name = []
income = []
with open('region-income.dat') as f:
parse = f.readlines()[8:]
for x in parse:
name.a... | Trying to list the 1st and second column but all text are indexed as one | Im trying to put into list two seperate column from an input file but they are all indexed the same how do i fix this.
name = []
income = []
with open('region-income.dat') as f:
parse = f.readlines()[8:]
for x in parse:
name.append(x.split(' ')[0])
print (name)
this code produces this outcome... | [
"That should do it ?\nname = []\nincome = []\n\nwith open('region-income.dat') as f:\n parse = f.readlines()[8:]\n for x in parse:\n row = x.split()\n name.append(row[0])\n income.append(row[1])\n\nprint(name)\nprint(income)\n\nIt seems the XIII line is separated with tabs (\\t) instead of s... | [
0
] | [] | [] | [
"arrays",
"python",
"python_3.x",
"string"
] | stackoverflow_0074232564_arrays_python_python_3.x_string.txt |
Q:
Is it possible to specify your own distance function using scikit-learn K-Means Clustering?
Is it possible to specify your own distance function using scikit-learn K-Means Clustering?
A:
Here's a small kmeans that uses any of the 20-odd distances in
scipy.spatial.distance, or a user function.
Comments would be w... | Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | Is it possible to specify your own distance function using scikit-learn K-Means Clustering?
| [
"Here's a small kmeans that uses any of the 20-odd distances in\nscipy.spatial.distance, or a user function.\nComments would be welcome (this has had only one user so far, not enough);\nin particular, what are your N, dim, k, metric ?\n#!/usr/bin/env python\n# kmeans.py using any of the 20-odd metrics in scipy.spat... | [
89,
63,
34,
17,
10,
5,
4,
0
] | [
"def distance_metrics(dist_metrics):\n kmeans_instance = kmeans(trs_data, initial_centers, metric=dist_metrics)\n\n label = np.zeros(210, dtype=int)\n for i in range(0, len(clusters)):\n for index, j in enumerate(clusters[i]):\n label[j] = i\n\n"
] | [
-2
] | [
"cluster_analysis",
"k_means",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0005529625_cluster_analysis_k_means_machine_learning_python_scikit_learn.txt |
Q:
What are the differences between strings 'True','False' and boolean True,False in Python
sorted_varieties = price_extremes.sort_values(by =['min','max'], ascending = ['False','False'])
variety
min
max
Pinot Grigio
4.0
70.0
Malbec-Syrah
4.0
78.0
White Blend
4.0
375.0
Tempranillo
4.0
600.0
sorted_varieties = p... | What are the differences between strings 'True','False' and boolean True,False in Python | sorted_varieties = price_extremes.sort_values(by =['min','max'], ascending = ['False','False'])
variety
min
max
Pinot Grigio
4.0
70.0
Malbec-Syrah
4.0
78.0
White Blend
4.0
375.0
Tempranillo
4.0
600.0
sorted_varieties = price_extremes.sort_values(by =['min','max'], ascending = [False,False])
vari... | [
"A non-empty string evaluates as True, so in your case it is similar to running:\nsorted_varieties = price_extremes.sort_values(by=['min','max'],\n ascending=[True, True])\n\n"
] | [
4
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074232562_group_by_pandas_python.txt |
Q:
How to plot 1 dimensional data inside the 2 dimensional triangular coordinates with colorbar in python?
I have closed triangle data coordinates a1 (size 10x1) and b1 (10x1), which creates the 3 closed triangles. I have another c1 data (size 3x1). I want to plot the c1 data over the triangle with colorbar. The imag... | How to plot 1 dimensional data inside the 2 dimensional triangular coordinates with colorbar in python? | I have closed triangle data coordinates a1 (size 10x1) and b1 (10x1), which creates the 3 closed triangles. I have another c1 data (size 3x1). I want to plot the c1 data over the triangle with colorbar. The image I'm attempting to create is similar to the matlab function patch(x,y,c). But I am unable to find a similar ... | [
"I propose the following solution, you can edit the colormap label if you prefer. By the way, I used the following method to display triangles as it was simpler than yours.\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\na1=[0.90899658,1.10720062,1.47019958,0.90899658,1.47019958,3.... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074231981_matplotlib_python.txt |
Q:
1D plot python colored by class
I used PCA and did dimensionality reduction to 1D for the iris dataset using the below code.
I have checked the question
1D plot matplotlib.
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
import matplotlib.cm as ... | 1D plot python colored by class | I used PCA and did dimensionality reduction to 1D for the iris dataset using the below code.
I have checked the question
1D plot matplotlib.
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
import matplotlib.cm as cm
# dataset
iris = datasets.load_ir... | [
"It's not exactly clear what kind of output you want but you could simply use seaborn and pass class for the hue argument. Read the documentation.\nsns.scatterplot(data=tips, x=\"total_bill\", y=\"tip\", hue=\"time\")\n\nFor your case data = iris and hue = class\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pca",
"python",
"seaborn"
] | stackoverflow_0074229408_matplotlib_pca_python_seaborn.txt |
Q:
Polars equivalent of pandas expression df.groupby['col1','col2']['col3'].sum().unstack()
pandasdf=pd.DataFrame(
{
"A": [1, 2, 3, 4, 5],
"fruits": ["banana", "banana", "apple", "apple", "banana"],
"B": [5, 4, 3, 2, 1],
"cars": ["beetle", "audi", "beetle", "beetle", "beetle"],
... | Polars equivalent of pandas expression df.groupby['col1','col2']['col3'].sum().unstack() | pandasdf=pd.DataFrame(
{
"A": [1, 2, 3, 4, 5],
"fruits": ["banana", "banana", "apple", "apple", "banana"],
"B": [5, 4, 3, 2, 1],
"cars": ["beetle", "audi", "beetle", "beetle", "beetle"],
"optional": [28, 300, None, 2, -30],
}
)
pandasdf.groupby(["fruits","cars"])['B'].sum... | [
"It seems like you want tot do a pivot.\ndf = pl.DataFrame(\n {\n \"A\": [1, 2, 3, 4, 5],\n \"fruits\": [\"banana\", \"banana\", \"apple\", \"apple\", \"banana\"],\n \"B\": [5, 4, 3, 2, 1],\n \"cars\": [\"beetle\", \"audi\", \"beetle\", \"beetle\", \"beetle\"],\n \"optional\": ... | [
2
] | [] | [] | [
"analytics",
"data_analysis",
"dataframe",
"python",
"python_polars"
] | stackoverflow_0074226602_analytics_data_analysis_dataframe_python_python_polars.txt |
Q:
How to add test data into django admin using a script
I am currently trying to create script where once the data has been deleted from django admin, we can add the data into database again for testing purposes.
In django when we are adding data, we need to fill every field in django admin but what i want is a scri... | How to add test data into django admin using a script | I am currently trying to create script where once the data has been deleted from django admin, we can add the data into database again for testing purposes.
In django when we are adding data, we need to fill every field in django admin but what i want is a script in which I have some test data and when I run, it automa... | [
"To fill up your target, you can use Faker. You need to create a python script corresponding to your model fields mapping and assign the fake values to your model (like creating a general model object). By this, you can create one object at a time. To create multiple objects at a time you can use for loop.\nExample... | [
3
] | [] | [] | [
"automated_tests",
"django",
"django_admin",
"python",
"testing"
] | stackoverflow_0074232238_automated_tests_django_django_admin_python_testing.txt |
Q:
How to filter empty values from a column of Python Polars Dataframe?
I have a python polars dataframe as-
df_pol = pl.DataFrame({'test_names':[['Mallesham','','Bhavik','Jagarini','Jose','Fernando'],
['','','','ABC','','XYZ']]})
I would like to get a count of elements from each ... | How to filter empty values from a column of Python Polars Dataframe? | I have a python polars dataframe as-
df_pol = pl.DataFrame({'test_names':[['Mallesham','','Bhavik','Jagarini','Jose','Fernando'],
['','','','ABC','','XYZ']]})
I would like to get a count of elements from each list in test_names field not considering the empty values.
df_pol.with_col... | [
"You can use arr.eval to run any polars expression on the list's elements. In an arr.eval expression, you can pl.element() to refer to the lists element and then apply an expression.\nNext we simply use a filter expression to prune the values we don't need.\ndf = pl.DataFrame({\n \"test_names\":[\n [\"Mal... | [
1,
0
] | [] | [] | [
"python",
"python_polars"
] | stackoverflow_0074231254_python_python_polars.txt |
Q:
Saving a dictionary to a JSON file in python
I am trying to save my objects created, stored in the __objects class attribute, and I am getting error:
Traceback (most recent call last):
File "/home/leuel/PycharmProjects/AirBnB_clone/./test_save_reload_base_model.py", line 2, in <module>
from models import sto... | Saving a dictionary to a JSON file in python | I am trying to save my objects created, stored in the __objects class attribute, and I am getting error:
Traceback (most recent call last):
File "/home/leuel/PycharmProjects/AirBnB_clone/./test_save_reload_base_model.py", line 2, in <module>
from models import storage
File "/home/leuel/PycharmProjects/AirBnB_cl... | [
"you already encoded your dictionary to a valid JSON data when you use json.dumps but when you try to dump it again with json.dump, python gives an error because json.dumps expects a valid python dictionary, not a valid JSON Data, and since you're trying to write to a file, use\nf.write(json_string)\n\ninstead of j... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074232861_json_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.