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:
Creating a plot with the most occurring combinations of two columns
For showing my data I want to create a frequency plot. This plot will be based on the number of times a combination between two columns occur. I have a two columns in a dataset (df):
acq_cc: [CN, IN, CN, CN, CN, IN, CN, CN, CN, ZA]
tar_cc: [GB, ZA... | Creating a plot with the most occurring combinations of two columns | For showing my data I want to create a frequency plot. This plot will be based on the number of times a combination between two columns occur. I have a two columns in a dataset (df):
acq_cc: [CN, IN, CN, CN, CN, IN, CN, CN, CN, ZA]
tar_cc: [GB, ZA, NO, AR, VG, JP, NL, PK, PK, SG]
The value of the columns needs to be co... | [
"Just do value_counts on multiple columns then use head to select top 10 most occurring combinations:\nc = ['acq_cc', 'tar_cc']\ndf[c].value_counts().head(10).plot(kind='bar')\n\n\n\n"
] | [
1
] | [] | [] | [
"list_comprehension",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074274321_list_comprehension_matplotlib_pandas_python.txt |
Q:
How to consistently get the python_type from SQLAlchemy for nonstandard types?
I'm trying to create a function to write a Python dict as a row to a Postgres table, via the SQLAlchemy expression language. I want to check that the values passed in that dictionary match the corresponding column types of the database ... | How to consistently get the python_type from SQLAlchemy for nonstandard types? | I'm trying to create a function to write a Python dict as a row to a Postgres table, via the SQLAlchemy expression language. I want to check that the values passed in that dictionary match the corresponding column types of the database table.
So far I have something like
import sqlalchemy
from sqlalchemy import MetaDat... | [
"I solved this by creating a custom IntRangeType and have my models use that for the column definition instead.\nimport intervals\nfrom sqlalchemy.dialects.postgresql import INT4RANGE\nfrom sqlalchemy_utils import IntRangeType as _IntRangeType\n\nclass IntRangeType(_IntRangeType):\n class INT4RANGE(INT4RANGE):\n... | [
0
] | [] | [] | [
"crud",
"postgresql",
"psycopg2",
"python",
"sqlalchemy"
] | stackoverflow_0061259440_crud_postgresql_psycopg2_python_sqlalchemy.txt |
Q:
DeprecationWarning: the formatter module is deprecated and empty log file is being created
I'm trying to test my understanding of logging in Python but seems I'm missing something. There are two questions I have.
First is when I start the program I get a message:
"DeprecationWarning: the formatter module is deprec... | DeprecationWarning: the formatter module is deprecated and empty log file is being created | I'm trying to test my understanding of logging in Python but seems I'm missing something. There are two questions I have.
First is when I start the program I get a message:
"DeprecationWarning: the formatter module is deprecated"
What does this mean? Is there a different way I'm supposed to set the formatting? Is my fo... | [
"I've figured it out. Seems that the logging.FileHandler is not generating any logs in the log file for some reason. I have substituted it with:\n\"logging.basicConfig(filename='log_to_file.log', level=logging.INFO, format='{asctime} {message} {levelname}', style='{')\"\nThis worked for me and I'm now able to see l... | [
0
] | [] | [] | [
"formatter",
"logging",
"python"
] | stackoverflow_0074273595_formatter_logging_python.txt |
Q:
Python dataframe: how to remove first column (row number)
I have manually constructed the dataframe (df1,code below).
For this dataframe df1, how could I remove the first column (row number)?
Many thanks in advance
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-4-7', '2021-4-18', '2021-5-12'],
"x": [3, 3, 3, 0 ]}... | Python dataframe: how to remove first column (row number) | I have manually constructed the dataframe (df1,code below).
For this dataframe df1, how could I remove the first column (row number)?
Many thanks in advance
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-4-7', '2021-4-18', '2021-5-12'],
"x": [3, 3, 3, 0 ]})
Output:
date x
0 2021-3-22 3
1 2021-4-7 3
2 20... | [
"Simply use set_index method.\nimport pandas as pd\n\ndf1 = pd.DataFrame({\"date\": ['2021-3-22', '2021-4-7', '2021-4-18', '2021-5-12'],\n\"x\": [3, 3, 3, 0 ]})\n\ndf1.set_index('date', inplace=True)\n\n",
"The default dataframe representation will display index numbers by default. If you want to see your datafra... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074274336_dataframe_pandas_python.txt |
Q:
PUT or PUSH for modifying the existing data?
I have viewset,
class CompanyViewSet(viewsets.ModelViewSet):
serializer_class = s.CompanySerializer
queryset = m.Company.objects.all()
Which shows the view on /api/companys
There is a button for POST
I can add the new data from this form.
Now I want to modi... | PUT or PUSH for modifying the existing data? | I have viewset,
class CompanyViewSet(viewsets.ModelViewSet):
serializer_class = s.CompanySerializer
queryset = m.Company.objects.all()
Which shows the view on /api/companys
There is a button for POST
I can add the new data from this form.
Now I want to modify the existing data.
I have basic questions.
PUS... | [
"Mainly for updating(modify) data using PATCH method, PUT for replace data\nDescription of methods:\nhttps://www.restapitutorial.com/lessons/httpmethods.html\nTo define PUT method you can use follow example:\n# define url\nurlpatterns = [\n url('api/mydata/<id>', views.data_put),\n]\n\n\n# views\n@api_view(['PUT... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074274370_django_django_rest_framework_python.txt |
Q:
django-simple-history, TemplateDoesNotExist at /admin/shared_models/mannedsetting/1/history/ simple_history/object_history.html
I am using django-history-admin
I have model class
class MannedSetting(BaseModel):
history = HistoricalRecords()
class Meta:
db_table = 't_manned_setting'
confirm_msg ... | django-simple-history, TemplateDoesNotExist at /admin/shared_models/mannedsetting/1/history/ simple_history/object_history.html | I am using django-history-admin
I have model class
class MannedSetting(BaseModel):
history = HistoricalRecords()
class Meta:
db_table = 't_manned_setting'
confirm_msg = m.CharField(max_length=400)
then in admin.py
from simple_history.admin import SimpleHistoryAdmin
class MannedSettingAdmin(SimpleHi... | [
"\nAdd simple_history to INSTALLED_APPS in the settings\n\n"
] | [
0
] | [] | [] | [
"django",
"django_simple_history",
"python"
] | stackoverflow_0071092319_django_django_simple_history_python.txt |
Q:
Trying to get DeepSpeech to work. SoX not found even though I pip installed it?
The error I'm getting is:
FileNotFoundError: [Errno 2] SoX not found, use 16000hz files or
install it: The system cannot find the file specified
My audio file is from an mp4 video file that was then converted to a WAV file from VLC. ... | Trying to get DeepSpeech to work. SoX not found even though I pip installed it? | The error I'm getting is:
FileNotFoundError: [Errno 2] SoX not found, use 16000hz files or
install it: The system cannot find the file specified
My audio file is from an mp4 video file that was then converted to a WAV file from VLC. The sampling rate is 8000 Hz by default, and it appears that DeepSpeech needs 16kHz f... | [
"I faced the same issue, Fix it by converting the audio rate to 16000hz.\nPlease try\n`ffmpeg -i input.wav -ar 16000 output.wav`\n\n",
"You should install sox from apt-get ubuntu, not from pip.\nsudo apt-get install sox \n\n"
] | [
4,
1
] | [] | [] | [
"mozilla_deepspeech",
"python"
] | stackoverflow_0069997918_mozilla_deepspeech_python.txt |
Q:
Not getting the correct result for my output in average function
I've been working on do loops for python although there isn't one for the language. I am trying to get the average of certain integers entered until a negative integer is entered. I was able to get the program working, instead it gives me the wrong r... | Not getting the correct result for my output in average function | I've been working on do loops for python although there isn't one for the language. I am trying to get the average of certain integers entered until a negative integer is entered. I was able to get the program working, instead it gives me the wrong results after entering the numbers and getting the average. For instanc... | [
"You're initializing the variable named average as below code\n{average = calculateAverage(totalTestScore, count)}\n\nBut you aren't overwriting it or saving any new value into it. At the end you're returning the value of that variable that has retained the same value since it was initialized.\n",
"def average(x)... | [
0,
0,
0
] | [] | [] | [
"average",
"division",
"flowchart",
"function",
"python"
] | stackoverflow_0074271300_average_division_flowchart_function_python.txt |
Q:
Checking if a folder is in the current directory
I want to check if there exist a folder in the current folder my code is in, how can this be done?
What I mean is, we have folder called code_folder, which has the python code, i want to check in this python code if in this code_folder we have another folder called ... | Checking if a folder is in the current directory | I want to check if there exist a folder in the current folder my code is in, how can this be done?
What I mean is, we have folder called code_folder, which has the python code, i want to check in this python code if in this code_folder we have another folder called folder_1, if is it exists we can store something in it... | [
"try this code\nimport os\npath = \"code_folder\"\n# Check whether the defined path exists or not\nif not os.path.exists(path):\n # Create a new directory\n os.makedirs(path)\n print(\"The new directory is created!\")\nelse:\n pass\n\n",
"You can use pathlib for this.\nif pathlib.Path(\"path/to/code_folde... | [
1,
0
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0074274459_directory_python.txt |
Q:
Aggregates in python
I have a txt file with the following content:
ID1;ID2;TIME;VALUE
1000;100;012021;12
1000;100;022021;4129
1000;100;032021;128
1000;100;042021;412
1000;100;052021;12818
1000;120;022021;4129
1000;100;062021;546
1000;100;072021;86
1000;120;052021;12818
1000;100;082021;754
1000;100;092021;2633
10... | Aggregates in python | I have a txt file with the following content:
ID1;ID2;TIME;VALUE
1000;100;012021;12
1000;100;022021;4129
1000;100;032021;128
1000;100;042021;412
1000;100;052021;12818
1000;120;022021;4129
1000;100;062021;546
1000;100;072021;86
1000;120;052021;12818
1000;100;082021;754
1000;100;092021;2633
1000;100;102021;571
1000;120... | [
"I'm far from being a Python expert but how about something like:\n dd = defaultdict(lambda: [])\n rows = [elems for elems in [line.strip().split(';') for line in data[1:]]]\n for row in rows:\n mm = row[2][:2]\n yy = row[2][2:]\n vv = int(row[3])\n key = (row[0], row[1], yy)\n ... | [
1,
0
] | [] | [] | [
"aggregate",
"database",
"grouping",
"python"
] | stackoverflow_0074273359_aggregate_database_grouping_python.txt |
Q:
While installing the xhtmlpdf in python I am facing the issue with insatlling reportlab package
pip install xhtml2pdf
I got the error below:
PS D:\pace_at\PACE-AT-NewTech> docker exec pace_at pip install xhtml2pdf
Collecting xhtml2pdf
Using cached xhtml2pdf-0.2.8-py3-none-any.whl (256 kB)
Collecting arabic-resh... | While installing the xhtmlpdf in python I am facing the issue with insatlling reportlab package | pip install xhtml2pdf
I got the error below:
PS D:\pace_at\PACE-AT-NewTech> docker exec pace_at pip install xhtml2pdf
Collecting xhtml2pdf
Using cached xhtml2pdf-0.2.8-py3-none-any.whl (256 kB)
Collecting arabic-reshaper>=2.1.0
Downloading arabic_reshaper-2.1.3-py3-none-any.whl (20 kB)
Collecting Pillow>=8.1.1
U... | [
"Adding freetype-dev to your Dockerfile will resolve this, eg.:\nRUN apk update \\\n && apk add postgresql-dev gcc python3-dev musl-dev freetype-dev\n\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"python_3.x"
] | stackoverflow_0072717141_django_django_rest_framework_python_python_3.x.txt |
Q:
Same Output - Hamming distance
No matter what i'm trying to change, my output is always "Sensor defect detected". At first i thought it is an indetation-problem, but still it doesn't work.
def hamming_dist(signal_1, signal_2):
result = []
if len(signal_1['times']) != len(signal_1['data']):
ret... | Same Output - Hamming distance | No matter what i'm trying to change, my output is always "Sensor defect detected". At first i thought it is an indetation-problem, but still it doesn't work.
def hamming_dist(signal_1, signal_2):
result = []
if len(signal_1['times']) != len(signal_1['data']):
return "Empty signal on at least one of... | [
" str1 = signal_1['data']\n str2 = signal_2[i]\n\nOne string value is an element from signal_sensor_2, e.g. in iteration 1 it is 00101110 for str2. str1 is always entry data in your sensor_1 dictionary, e.g. always [\"00101110\", \"11001011\", \"11110000\", \"01000011\", \"11001101\", \"000110... | [
0
] | [] | [] | [
"hamming_distance",
"python"
] | stackoverflow_0074274512_hamming_distance_python.txt |
Q:
SSL error using multiprocessing in Python with Google Cloud services
In my application on Flask I use multiprocessing in a batch of files - user uploads a .zip with many pdf files -, after the upload, a new entity is created on the database for each file, then a thread is started and call a multiprocessing pool so... | SSL error using multiprocessing in Python with Google Cloud services | In my application on Flask I use multiprocessing in a batch of files - user uploads a .zip with many pdf files -, after the upload, a new entity is created on the database for each file, then a thread is started and call a multiprocessing pool so each file starts a process which has interactions to Google Cloud service... | [
"I ended up exchanging mutiprocessing and threading operations to celery task queues as there were some concerns regarding thread safety when connecting to gcloud services that I couldn't overcome. Celery implementation has been a good solution for many multiple async tasks on my app.\n#Import celery instance with ... | [
0,
0
] | [] | [] | [
"google_cloud_datastore",
"google_cloud_storage",
"multiprocessing",
"python",
"ssl"
] | stackoverflow_0058241849_google_cloud_datastore_google_cloud_storage_multiprocessing_python_ssl.txt |
Q:
Python and ReportLab. How to change a font and a font size in a Table object?
I need to change text style in particular cells in Table object (ReportLab).
As far as I understand, it could be done via TableStayle class, but I can't find samples.
my_table = Table(data, colWidths=column_widths, rowHeights = row_heght... | Python and ReportLab. How to change a font and a font size in a Table object? | I need to change text style in particular cells in Table object (ReportLab).
As far as I understand, it could be done via TableStayle class, but I can't find samples.
my_table = Table(data, colWidths=column_widths, rowHeights = row_heghts)
my_colour_black = [0, 0, 0]
my_colour_ligt_gray = [0.8, 0.8, 0.8]
my_colour_gra... | [
"Finally, I have found an answer. The format is:\n('FONTNAME', (0,0), (-1,-1), 'Arial'),\n('FONTSIZE', (0,0), (-1,0), 10),\nFull listing of TableStyle :\n current_tab_style = TableStyle([\n('FONTNAME', (0,0), (-1,-1), 'Arial'), # font\n('FONTSIZE', (0,0), (-1,0), 12),\n('FONTSIZE', (0,1), (-1,-1), 10),\n('ALIGN'... | [
0
] | [] | [] | [
"python",
"reportlab"
] | stackoverflow_0074272597_python_reportlab.txt |
Q:
How to get self object name from self method in Python
I am trying to find a way to automatically print the object reference name with just a print object
To be more specific.
Lets say I have a class:
class A:
def __init__(self):
self.cards = []
def __str__(self):
# return a string represe... | How to get self object name from self method in Python | I am trying to find a way to automatically print the object reference name with just a print object
To be more specific.
Lets say I have a class:
class A:
def __init__(self):
self.cards = []
def __str__(self):
# return a string representation of A
return "A contains " ...
...
Now w... | [
"As the comments on your question have stated, it is not possible and also unwise, consider something along the lines of the following approach instead:\nclass A:\n def __init__(self, name):\n self.cards = []\n self.name = name\n\n def __str__(self):\n return '{} contains ...'.format(self... | [
2,
0
] | [] | [] | [
"class",
"python",
"python_2.7",
"self"
] | stackoverflow_0023580236_class_python_python_2.7_self.txt |
Q:
can't read csv file using pd.read_csv() method in test class
import sys
import numpy as np
import pandas as pd
sys.path.insert(0, sys.argv[2])
sys.path.insert(1, sys.argv[3])
from training import CustomerSegmentation
class TestCustomerSegmentation:
dataset = pd.read_csv(
sys.path.pop(1),
parse_date... | can't read csv file using pd.read_csv() method in test class | import sys
import numpy as np
import pandas as pd
sys.path.insert(0, sys.argv[2])
sys.path.insert(1, sys.argv[3])
from training import CustomerSegmentation
class TestCustomerSegmentation:
dataset = pd.read_csv(
sys.path.pop(1),
parse_dates=["InvoiceDate"],
)
then by giving command line arguments:
... | [
"How about creating a virtual environment for your project first and running the codes in the Virtual environment.\npy -m venv environment\nenvironment\\Scripts\\activate\n\nTry creating an environment and run your project inside the environment.\n",
"you must add the file into the same folder. or maybe this link... | [
0,
0
] | [] | [] | [
"pandas",
"pytest",
"python",
"python_3.x",
"sys.path"
] | stackoverflow_0074273109_pandas_pytest_python_python_3.x_sys.path.txt |
Q:
Accelerated matrix search in python
There is now a way to search the index of a submatrix in the main matrix, but both are slow, can anyone think of a faster way?
a=np.array([[5 4 5 9 3 4 6 2 5 3]
[8 3 5 4 3 4 5 8 4 4]
[5 7 8 5 2 3 3 6 8 8]
[4 5 6 2 6 5 6 7 9 3]
[3 6... | Accelerated matrix search in python | There is now a way to search the index of a submatrix in the main matrix, but both are slow, can anyone think of a faster way?
a=np.array([[5 4 5 9 3 4 6 2 5 3]
[8 3 5 4 3 4 5 8 4 4]
[5 7 8 5 2 3 3 6 8 8]
[4 5 6 2 6 5 6 7 9 3]
[3 6 8 2 8 7 3 8 8 8]])
b=np.array([[2 3 3]
... | [
"Assuming the component of the small matrix are not repeated a lot of time in the big matrix and the small matrix is far smaller than the big one, you can search the first item of the small matrix in the big one so to then search the actual small matrix at the target found locations. This should help to reduce the ... | [
1
] | [] | [] | [
"matrix",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0074260747_matrix_multidimensional_array_numpy_python.txt |
Q:
pandas profiling import error : not able to import pandas_profiling package
I cannot import name DataError from pandas.core.base
When I import package:
from pandas_profiling import ProfileReport
it shows error:
cannot import name 'DataError' from 'pandas.core.base'
A:
There is a typo in the import. Try this:
In... | pandas profiling import error : not able to import pandas_profiling package | I cannot import name DataError from pandas.core.base
When I import package:
from pandas_profiling import ProfileReport
it shows error:
cannot import name 'DataError' from 'pandas.core.base'
| [
"There is a typo in the import. Try this:\nIn pandas 0.23.0 the import path for DataError should be \"from pandas.core.base import DataError\". (Resource here)\nSo use Pandas version 0.23.0 and it will work\nfrom pandas_profiling import ProfileReport\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"exploratory_data_analysis",
"pandas",
"pandas_profiling",
"python"
] | stackoverflow_0074273171_dataframe_exploratory_data_analysis_pandas_pandas_profiling_python.txt |
Q:
Why use Django REST Framework instead of returning normal HttpResponse in views?
I'm new to Python and I've seen a lot of tutorials which jump into the Django REST Framework when discussing how to create REST APIs without explaining why they need this library. I don't see the purpose of using the Django Rest Frame... | Why use Django REST Framework instead of returning normal HttpResponse in views? | I'm new to Python and I've seen a lot of tutorials which jump into the Django REST Framework when discussing how to create REST APIs without explaining why they need this library. I don't see the purpose of using the Django Rest Framework when I can just define API endpoints in views and return a simple HttpResponse to... | [
"The DRF is a complete toolkit for building RESTful APIs in Django, including authentication, serialization, etc. You can do without it but, in the end of the day, the DRF will save you a lot of time.\nIt fits well with the Django architecture and it's also quite extensible, so you won't be locked-in to some obscur... | [
0,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074238430_django_django_rest_framework_python.txt |
Q:
Login using flask and MySQL
I am setting up signup and login for my website using flask with MySQL as my database but when I try to log in it is showing the error "Incorrect username and password " even though they are both correct.
Below is the login code
@app.route('/login', methods=["GET", "POST"])`your text`
d... | Login using flask and MySQL | I am setting up signup and login for my website using flask with MySQL as my database but when I try to log in it is showing the error "Incorrect username and password " even though they are both correct.
Below is the login code
@app.route('/login', methods=["GET", "POST"])`your text`
def login():
if request.method... | [
"bcrypt has an internal comparison method, ‘bcrypt.checkpw(password, hashed)‘ maybe use that instead of manually comparing the hashes.\nIf that don’t work make sure your password hash stored in the database is using the same hashing algorithm as the one you currently using for password hashing and than comparing.\n... | [
0
] | [] | [] | [
"bcrypt",
"python"
] | stackoverflow_0074274348_bcrypt_python.txt |
Q:
Make an enemy follow you
Im trying to make an enemy follow the player which is moved by the mouse. The player spawns in but does not move. Here is my (new & edited)code :
This is the player class (no problem with that):
class Player(pg.sprite.Sprite):
def __init__(self):
self.groups = all_sprites
pg.sprite... | Make an enemy follow you | Im trying to make an enemy follow the player which is moved by the mouse. The player spawns in but does not move. Here is my (new & edited)code :
This is the player class (no problem with that):
class Player(pg.sprite.Sprite):
def __init__(self):
self.groups = all_sprites
pg.sprite.Sprite.__init__(self, self.gr... | [
"An option is to compute the Euclidean distance form the position of the follower to the target. Use pygame.math.Vector2 for the computation. Compute the distance from between the follower and the sprite and the unit direction vector from (follower_x, follower_y) to (mainsprite_x, mainsprite_y). The Unit Vector can... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0066754437_pygame_python.txt |
Q:
Python - how to get access to SharePoint site without access to root
I'm trying to read data from an HTML table that on a site with a URL like https://mysharepoint.sharepoint.com/sites/mySite/sitepages/tables
And I only have access to the "mySite" site. I've tried using shareplum like their documentation:
from sha... | Python - how to get access to SharePoint site without access to root | I'm trying to read data from an HTML table that on a site with a URL like https://mysharepoint.sharepoint.com/sites/mySite/sitepages/tables
And I only have access to the "mySite" site. I've tried using shareplum like their documentation:
from shareplum import Site
from shareplum import Office365
authcookie = Office365... | [
"Issue #105 on the SharePlum GitHub repo suggests a workaround:\nin shareplum/request_helper.py, comment out the following line in the post function (ln.17 for v0.5.1): response.raise_for_status()\nThis results in accepting the 403 return status, which you get for not having access to the root site. For me this sol... | [
0
] | [] | [] | [
"python",
"shareplum",
"sharepoint",
"sharepoint_online"
] | stackoverflow_0070259002_python_shareplum_sharepoint_sharepoint_online.txt |
Q:
pygame cant stop the image from moving out of the screen when touching the bottom
I am attempting to create a window where a sprite is stopped if it tries to go past the edges.
This has worked for all of the sides of the window except for the bottom.
this is the function:
def barrier(self,width,height):
if se... | pygame cant stop the image from moving out of the screen when touching the bottom | I am attempting to create a window where a sprite is stopped if it tries to go past the edges.
This has worked for all of the sides of the window except for the bottom.
this is the function:
def barrier(self,width,height):
if self.rect.right >= width:
self.rect.right = width
if self.rect.left <= 0:
... | [
"Get the actual width and height of the display from the display surface:\nscreen = pygame.display.set_mode((1920, 1080), pygame.FULLSCREEN)\nscreenwidth = screen.get_width() \nscreenheight = screen.get_height()\n\n"
] | [
0
] | [] | [] | [
"pygame",
"python",
"python_3.x"
] | stackoverflow_0066621090_pygame_python_python_3.x.txt |
Q:
When is it acceptable to shadow a builtin?
We are often told not to shadow builtins like id, int, list and so on. Is it ever acceptable to break this rule?
A:
In general, you should not shadow builtins for several reasons:
doing so prevents you from using the builtin later by calling its common name
other peop... | When is it acceptable to shadow a builtin? | We are often told not to shadow builtins like id, int, list and so on. Is it ever acceptable to break this rule?
| [
"In general, you should not shadow builtins for several reasons:\n\ndoing so prevents you from using the builtin later by calling its common name\nother people reading your code will be confused, as they expect list to be the builtin list, and so on\nIDEs will (usually) compound this by highlighting your shadowed v... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074274877_python.txt |
Q:
How can I fetch the source code from a website that is blocking the requests when we use python bs4, selenium?
I want to scrape the data present in this website "https://www.findhelp.org/care/support-network--san-francisco-ca?postal=94105". I tried using beautiful soup and selenium,
The first approach:
import requ... | How can I fetch the source code from a website that is blocking the requests when we use python bs4, selenium? | I want to scrape the data present in this website "https://www.findhelp.org/care/support-network--san-francisco-ca?postal=94105". I tried using beautiful soup and selenium,
The first approach:
import requests as requests
from bs4 import BeautifulSoup
url="https://www.findhelp.org/care/support-network--san-francisco-ca?... | [
"You can use the page_source property of Selenium as follows:\nfrom selenium import webdriver\n\nbrowser = webdriver.Firefox()\nbrowser.get(\"http://example.com\")\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"web_scraping"
] | stackoverflow_0074272589_python_python_3.x_web_scraping.txt |
Q:
Why would a key double after a merge?
I merge two datasets using following code:
output1 = classen_gravity.merge(fdi, how= "left", right_on=["Country", "Year", "regime"],
left_on=["country", "regime", "year"])
"regime" is supposed to stay as one column but after a merge, it becomes ... | Why would a key double after a merge? | I merge two datasets using following code:
output1 = classen_gravity.merge(fdi, how= "left", right_on=["Country", "Year", "regime"],
left_on=["country", "regime", "year"])
"regime" is supposed to stay as one column but after a merge, it becomes regime_x and regime_y.
Why would it happen... | [
"Is regime in both dataframes? x and y columns are created when the same column is in both dataframes\n",
"Make sure that the order of the columns is the same:\noutput1 = classen_gravity.merge(\n fdi,\n how= \"left\",\n right_on=[\"Country\", \"Year\", \"regime\"],\n left_on=[\"country\", \"year\", \"regi... | [
0,
0
] | [] | [] | [
"dataframe",
"merge",
"pandas",
"pandas_merge",
"python"
] | stackoverflow_0074274245_dataframe_merge_pandas_pandas_merge_python.txt |
Q:
pygame screen loop not working correctly. loop keeps reshreshing unlike others
def selection():
global selectionLoop
selectionLoop = True
clock.tick(1)
while selectionLoop:
print("disspam")
window.blit(backgroundgame, (0,0))
text.title('CHOOSE A SUBJECT!')
button(... | pygame screen loop not working correctly. loop keeps reshreshing unlike others | def selection():
global selectionLoop
selectionLoop = True
clock.tick(1)
while selectionLoop:
print("disspam")
window.blit(backgroundgame, (0,0))
text.title('CHOOSE A SUBJECT!')
button(550, 500, 250, 100, rollover_menucolours, menucolours, 'MUSIC', 'music', black, smal... | [
"The typical PyGame application loop has to:\n\nlimit the frames per second to limit CPU usage with pygame.time.Clock.tick\nhandle the events by calling either pygame.event.pump() or pygame.event.get().\nupdate the game states and positions of objects dependent on the input events and time (respectively frames)\ncl... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0060300875_pygame_python.txt |
Q:
Using Pylint in Ipython (Jupyter-Notebook)
I want to run Pylint or any equivalent while using Jupyter-Notebook. Is there a way to install and run Pylint this way?
A:
pycodestyle is an equivalent of pylint for Jupyter Notebook which is able to check your code against the PEP8 style guide.
First, you need to insta... | Using Pylint in Ipython (Jupyter-Notebook) | I want to run Pylint or any equivalent while using Jupyter-Notebook. Is there a way to install and run Pylint this way?
| [
"pycodestyle is an equivalent of pylint for Jupyter Notebook which is able to check your code against the PEP8 style guide.\nFirst, you need to install the pycodestyle in jupyter notebook by typing this command,\n!pip install pycodestyle pycodestyle_magic\n\nRun this command in a cell of jupyter notebook.\nAfter su... | [
21,
12,
5,
2,
0
] | [] | [] | [
"flake8",
"jupyter_notebook",
"pylint",
"python",
"python_3.x"
] | stackoverflow_0050358327_flake8_jupyter_notebook_pylint_python_python_3.x.txt |
Q:
Image size is too large
I have data like this:
and then I want to create a visualization from the data
I'm using this code :
# create the visualization of the data
fig = plt.figure(figsize=(10, 5)) #to set the figure size
fig.suptitle('Number of Transaction per day', fontsize=20) # to set the chart title and its... | Image size is too large | I have data like this:
and then I want to create a visualization from the data
I'm using this code :
# create the visualization of the data
fig = plt.figure(figsize=(10, 5)) #to set the figure size
fig.suptitle('Number of Transaction per day', fontsize=20) # to set the chart title and its font size
plt.xlabel('Day',... | [
"Use bar_label function\nbars = plt.bar(x, y, color='green') # to plot and select the line colour\n# You may need to adjust the axis limits to fit the labels.\nplt.bar_label(bars, padding=5, fontsize=20)\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074272863_matplotlib_python.txt |
Q:
python program that takes input and print data as sequence of upper and lowercase
Write a python program that takes a string as an input from the user and then modifies the string in such a way that the string always starts with an uppercase letter and the case of each subsequent letter is the opposite of the prev... | python program that takes input and print data as sequence of upper and lowercase | Write a python program that takes a string as an input from the user and then modifies the string in such a way that the string always starts with an uppercase letter and the case of each subsequent letter is the opposite of the previous letter (uppercase character followed by a lowercase character followed by an upper... | [
"you can try to define \"lower\" and \"upper\" functions yourself\ndef isup(s):\n # return not islow(s) # uncomment if specials chars are considered as upper\n return ord(s) in range(ord('A'),ord('Z'))\n\ndef islow(s):\n # return ord(s) in range(ord('a'),ord('z')) # uncomment too\n return not isup(s)\n\... | [
2,
1,
1,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0073004314_loops_python.txt |
Q:
How to write the json for patch on Django REST Framework
I have PATCH button form on ModelViewSet
class CompanyViewSet(viewsets.ModelViewSet):
serializer_class = s.CompanySerializer
queryset = m.Company.objects.all()
def patch(self, request, id, format=None):
print(id)
Now I try to modify ... | How to write the json for patch on Django REST Framework | I have PATCH button form on ModelViewSet
class CompanyViewSet(viewsets.ModelViewSet):
serializer_class = s.CompanySerializer
queryset = m.Company.objects.all()
def patch(self, request, id, format=None):
print(id)
Now I try to modify the existing data id = 1
So I write this in textarea and push ... | [
"Use perform_update like this :\nclass CompanyViewSet(viewsets.ModelViewSet):\nserializer_class = s.CompanySerializer \nqueryset = m.Company.objects.all() \n\ndef perform_update(self, serializer):\n instance = serializer.instance\n request = self.request\n serializer.save(**modified_attrs)\n return Re... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"javascript",
"python"
] | stackoverflow_0074274753_django_django_rest_framework_javascript_python.txt |
Q:
How to put a parameter in the assign function of DataFrames?
I would like to iterate over the columns and change the content of the columns with the assign function.
Related to this problem
So in that example they show that you can use the assign function:
df = df.assign(industry='yyy')
To change the content of t... | How to put a parameter in the assign function of DataFrames? | I would like to iterate over the columns and change the content of the columns with the assign function.
Related to this problem
So in that example they show that you can use the assign function:
df = df.assign(industry='yyy')
To change the content of the column called industry.
I thought I could perform:
for column ... | [
"The following snippet will do what you expect :-)\n# Option 1\n\nfor col in df.columns:\n df.loc[:, col] = 'yyy'\n\n# Option 2 (with .assign())\n\ncols = {col: 'yyy' for col in df.columns}\ndf = df.assign(**cols)\n\nInput:\n\nOutput:\n\n"
] | [
2
] | [] | [] | [
"assign",
"dataframe",
"python"
] | stackoverflow_0074274689_assign_dataframe_python.txt |
Q:
How to display all data from a column
There is a database in it there are columns with names: bellang, bellit ... How can I display all the numbers from the bellang column
Need to output 9 5 7
I tried cursor.fetchall()[] but the output is [(9,),(5,),(7,)]
A:
Since you are using cursor, you need to do this way
r... | How to display all data from a column | There is a database in it there are columns with names: bellang, bellit ... How can I display all the numbers from the bellang column
Need to output 9 5 7
I tried cursor.fetchall()[] but the output is [(9,),(5,),(7,)]
| [
"Since you are using cursor, you need to do this way\nrec = []\nrecords = cursor.fetchall()\nfor row in records:\n rec.append(row[0])\n cursor.close()\n\nOr alternatively, using list comprehension\n_cursor = cursor.fetchall()\nrec = [row[0] for row in _cursor]\ncursor.close()\n\n"
] | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074274870_python_sqlite.txt |
Q:
get the path of the executed file once "compiled" with pyinstaller
I know there are a lot of answers on this subject, but no one works once you compile a script in an executable.
In my python script, I create a file within the same directory of the script.
to get the path of the current dir I use pathlib
basepath ... | get the path of the executed file once "compiled" with pyinstaller | I know there are a lot of answers on this subject, but no one works once you compile a script in an executable.
In my python script, I create a file within the same directory of the script.
to get the path of the current dir I use pathlib
basepath = Path(__file__).parent
filename='myfile'
filepath=os.path.join(basepath... | [
"When you compile an app using pyinstaller with the --onefile or -F flag, the file that it creates is actually an archive file, like a .zip file.\nWhen you execute that file it launches a process that extracts itself into a temporary folder somewhere in your OS filesystem. This is the path that is reported when you... | [
1
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0074274894_pyinstaller_python.txt |
Q:
How to convert string value like "4w 2d.." to timedelta?
I have incoming string data in format like "4w 2d 5h" (weeks(w), days(d), hours(h), minutes(m)), some it can have different number of parameters (from 1 to 4, e.g "1w", "2w 5h", "3w 1d 5h 3m", etc).
I need to convert it to timedelta (datetime) format.
The on... | How to convert string value like "4w 2d.." to timedelta? | I have incoming string data in format like "4w 2d 5h" (weeks(w), days(d), hours(h), minutes(m)), some it can have different number of parameters (from 1 to 4, e.g "1w", "2w 5h", "3w 1d 5h 3m", etc).
I need to convert it to timedelta (datetime) format.
The only way I know it is to split it and then use statements depend... | [
"If you're sure the strings are well formatted then you could try to use re:\nimport re\nfrom datetime import timedelta\n\nre_td = re.compile(r\"(\\d+)(w|d|h|m)\")\nunits = {\"w\": \"weeks\", \"d\": \"days\", \"h\": \"hours\", \"m\": \"minutes\"}\n\ndef to_timedelta(string):\n return timedelta(**{units[u]: int(v... | [
2
] | [] | [] | [
"datetime",
"python",
"timedelta"
] | stackoverflow_0074273708_datetime_python_timedelta.txt |
Q:
move folder from dbfs location to user workspace directory in azure databricks
I need to move group of files(python or scala file from)or folder from dbfs location to user workspace directory to do testing on file.
Its verify difficult to upload each file one by one into the user workspace directory, so is it poss... | move folder from dbfs location to user workspace directory in azure databricks | I need to move group of files(python or scala file from)or folder from dbfs location to user workspace directory to do testing on file.
Its verify difficult to upload each file one by one into the user workspace directory, so is it possible to move file from dbfs location to user workspace directory in azure databricks... | [
"You can upload folder in any Azure cloud storage resources using the Azure Storage Explorer application from Microsoft\n. You can download the application here.\nAfter you have downloaded the application, you can sign in your Azure account and select the storage you want folder to upload to.\nPlease see this offic... | [
0
] | [] | [] | [
"apache_spark",
"azure",
"azure_databricks",
"databricks",
"python"
] | stackoverflow_0074274460_apache_spark_azure_azure_databricks_databricks_python.txt |
Q:
problems with doing an API call
I want to do an API call using the Forecast air pollution data from this website
https://openweathermap.org/api/air-pollution
The API call of the website state that it is these:
http://api.openweathermap.org/data/2.5/air_pollution/forecast?lat={lat}&lon={lon}&appid={API key}
Now I ... | problems with doing an API call | I want to do an API call using the Forecast air pollution data from this website
https://openweathermap.org/api/air-pollution
The API call of the website state that it is these:
http://api.openweathermap.org/data/2.5/air_pollution/forecast?lat={lat}&lon={lon}&appid={API key}
Now I have a dataframe in pandas which has ... | [
"You are using Python's f-string in a bad way. The url should be constructed as follows:\nurl = f\"http://api.openweathermap.org/data/2.5/air_pollution/forecast?lat={lat}&lon={lon}&appid={appid}\"\n\nNote the f before the first quote sign and variables names inside the curly braces - {appid} instead of {<your-app-i... | [
1,
0
] | [] | [] | [
"api",
"openweathermap",
"python"
] | stackoverflow_0074274590_api_openweathermap_python.txt |
Q:
ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl
I am trying to run the below in order to create a df by reading an excel. However I receive the below error. (I pip installed the openpyxl but I am taking the same error. )
import pandas as pd
import numpy as np
... | ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl | I am trying to run the below in order to create a df by reading an excel. However I receive the below error. (I pip installed the openpyxl but I am taking the same error. )
import pandas as pd
import numpy as np
df = pd.read_excel("test.xlsx")
return _bootstrap._gcd_import(name[level:], package, le... | [
"pip install openpyxl --upgrade\nIf this doesn't work; Try this too pip install pandas --upgrade\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074275058_python.txt |
Q:
Pygame set window on top without changing it's position
As I found in the following topic : How to make python window run as "Always On Top"?
I know how to put a window on top. But I would like to keep it at the same position. The autor says that he found a work around to find the x and y values. I would like to k... | Pygame set window on top without changing it's position | As I found in the following topic : How to make python window run as "Always On Top"?
I know how to put a window on top. But I would like to keep it at the same position. The autor says that he found a work around to find the x and y values. I would like to know how I can achieve that !
How can I get the x, y values o... | [
"There's a shorter solution using the same function:\nfrom ctypes import windll\nSetWindowPos = windll.user32.SetWindowPos\n\nNOSIZE = 1\nNOMOVE = 2\nTOPMOST = -1\nNOT_TOPMOST = -2\n\ndef alwaysOnTop(yesOrNo):\n zorder = (NOT_TOPMOST, TOPMOST)[yesOrNo] # choose a flag according to bool\n hwnd = pygame.display... | [
5,
4,
1,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0025381589_pygame_python.txt |
Q:
Read and compare data from multiple files
I'm trying to make a function that will accept a list of filenames as parameter to access data from two files at a time and compare the values, if value matches it will be added to the set and then print set.
The problem is that files have some matching values but function... | Read and compare data from multiple files | I'm trying to make a function that will accept a list of filenames as parameter to access data from two files at a time and compare the values, if value matches it will be added to the set and then print set.
The problem is that files have some matching values but function prints an empty set at the end.
def cross_refe... | [
"One reason might be that you are not stripping the contents of each line. So one line could be '0724-87234\\n' and the other could be '0724-87234' without '\\n'.\nI would go for another approach like this:\ndef cross_reference(files):\n common_values = None\n for file in files:\n with open(file) as f:... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074274720_python.txt |
Q:
error while installing dj-rest-auth inside google cloud vm and i created a virtualenv
I am inside SSH window of VM
I created a virtal environment using command :virtualenv -p python3.8 venv
now i try to install dj-rest-auth using command pip install dj-rest-auth and i am receiving error
Building wheels for collect... | error while installing dj-rest-auth inside google cloud vm and i created a virtualenv | I am inside SSH window of VM
I created a virtal environment using command :virtualenv -p python3.8 venv
now i try to install dj-rest-auth using command pip install dj-rest-auth and i am receiving error
Building wheels for collected packages: dj-rest-auth
Building wheel for dj-rest-auth (setup.py) ... error
But it allow... | [
"if we create a virtual environment having python installed inside VM using command python3 -m venv myenv then no error reeceived and all librarie got installed\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074237395_django_django_rest_framework_python.txt |
Q:
iterate through a list and restart index_1 at 0 if list index is out of range
I am trying to make a program where I have a list my_list_1 = [1,2,3,...] and a second list `my_list_2 = [1,2,3,...] and len(my_list_1) < len(my_list_2). I want to iterate through the lists like this:
my_list_1 = [1,2,3]
my_list_2 = [5,6... | iterate through a list and restart index_1 at 0 if list index is out of range | I am trying to make a program where I have a list my_list_1 = [1,2,3,...] and a second list `my_list_2 = [1,2,3,...] and len(my_list_1) < len(my_list_2). I want to iterate through the lists like this:
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
result = []
for i in range(len(my_list_2)):
result.append(my_list_1[i]... | [
"You just need modulo for the first index:\nfor i in range(len(my_list_2)):\n x = i % len(my_list_1)\n result.append(my_list_1[x] + my_list_2[i])\n\n",
"You can also use itertools.cycle to create a cyclical list iterator, and use zip for the iterator and the other list.\nfrom itertools import cycle\n\nmy_li... | [
0,
0
] | [] | [] | [
"iteration",
"list",
"loops",
"python"
] | stackoverflow_0074274759_iteration_list_loops_python.txt |
Q:
How do I export a read_html df to Excel, when it related to table ID rather than data in the code?
I am experiencing this error with the code below:
File "\<stdin\>", line 1, in \<module\>
AttributeError: 'list' object has no attribute 'to_excel'
I want to save the table I am scraping from wikipedia to an Excel f... | How do I export a read_html df to Excel, when it related to table ID rather than data in the code? | I am experiencing this error with the code below:
File "\<stdin\>", line 1, in \<module\>
AttributeError: 'list' object has no attribute 'to_excel'
I want to save the table I am scraping from wikipedia to an Excel file - but I can't work out how to adjust the code to get the data list from the terminal to the Excel fi... | [
"pandas.read_html() creates a list of tables respectiv dataframe objects, so you have to pick one by index in your case [0] - You also do not need requests and BeautifulSoup, separatly, just go with pandas.read_html()\npd.read_html(wiki_url,attrs={'id': table_id})[0]\n\nExample\nimport pandas as pd\n\nwiki_url = 'h... | [
1
] | [] | [] | [
"beautifulsoup",
"dataframe",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074275191_beautifulsoup_dataframe_pandas_python_web_scraping.txt |
Q:
My html parser is not showing the entire HTML code that actually runs behind the webpage when I inspect the HTML code. Here's my code:
`
import requests
from bs4 import BeautifulSoup as bs
import html5lib
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(exec... | My html parser is not showing the entire HTML code that actually runs behind the webpage when I inspect the HTML code. Here's my code: | `
import requests
from bs4 import BeautifulSoup as bs
import html5lib
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path=r'D:\Web Scraping\chromedriver.exe')
url = "https://ibegin.tcs.com/iBegin/jobs/search"
req = driver.get(url)
soup = bs(driver... | [
"The data you see on the page is loaded from external source via JavaScript. beautifulsoup doesn't execute javascript, so you must use other methods to load the data. For example using their Api:\nimport requests\nimport pandas as pd\n\napi_url = \"https://ibegin.tcs.com/iBegin/api/v1/jobs/searchJ\"\npayload = {\n ... | [
2
] | [] | [] | [
"beautifulsoup",
"html",
"json",
"python",
"web_scraping"
] | stackoverflow_0074275018_beautifulsoup_html_json_python_web_scraping.txt |
Q:
How to receive data from a sensor at the same time that the data is sent to a website using Multiprocessing on the Raspberry Pi?
I'm using nrf24L01 to collect data from a sensor and send it to a Raspberry Pi, and then the data is sent to a website.
The sensor needs to send data non-stop (it uses a fixed sampling o... | How to receive data from a sensor at the same time that the data is sent to a website using Multiprocessing on the Raspberry Pi? | I'm using nrf24L01 to collect data from a sensor and send it to a Raspberry Pi, and then the data is sent to a website.
The sensor needs to send data non-stop (it uses a fixed sampling of 2kHz)
However, during the request made by raspberry with the server, there is a small delay. As a result, the data sent by the senso... | [
"Since the sensor is generating data faster (2K samplings per second) than the website can (currently) accept it, I would think that whatever \"buffering\" you use, such as the threading.Queue suggested by @MarkSetchell, you would be filling the queue faster than it can be emptied and eventually memory would be exh... | [
2
] | [] | [] | [
"multiprocessing",
"python",
"raspberry_pi"
] | stackoverflow_0074268363_multiprocessing_python_raspberry_pi.txt |
Q:
How to find and replace text in a single cell when using Jupyter extension inside Visual Studio Code
As the title says, how to find and replace text inside a single jupyter cell when using the jupyter extension in Visual Studio Code? I am familiar with ctr+h but that will replace all the occurrences in the entire ... | How to find and replace text in a single cell when using Jupyter extension inside Visual Studio Code | As the title says, how to find and replace text inside a single jupyter cell when using the jupyter extension in Visual Studio Code? I am familiar with ctr+h but that will replace all the occurrences in the entire jupyter notebook file. This is a really important feature for me, as I am using it a lot in jupyter on the... | [
"F3 do the trick. It first shows the \"Find\" widget for a single cell. Then click the triangle on the left and it will be expanded to a \"Replace\" widget.\n\n",
"You can select the first occurrence and then use Ctrl+D. It will select the next occurence in the cell. Repeat that until you go back to the first ocu... | [
7,
1,
0
] | [] | [] | [
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0071319929_jupyter_notebook_python_visual_studio_code.txt |
Q:
Download YouTube video using Python to a certain directory
I have tried the following code to download a video in YouTube and it is working, but I want to save the video at a particular location. Now it is saving the video in C:/Users/Download. If I want to save the video in the desktop, what changes do I need in... | Download YouTube video using Python to a certain directory | I have tried the following code to download a video in YouTube and it is working, but I want to save the video at a particular location. Now it is saving the video in C:/Users/Download. If I want to save the video in the desktop, what changes do I need in the code?
from __future__ import unicode_literals
import youtub... | [
"I found out a really cool python module that allows you to download videos from youtube easily. TO install it:\npip install pytube\n\nNow, You can download your video like this -\nfrom pytube import YouTube\nyt = YouTube(\"https://www.youtube.com/watch?v=n06H7OcPd-g\")\nyt = yt.get('mp4', '720p')\nyt.download('/pa... | [
87,
26,
11,
4,
4,
2,
2,
1,
1,
0,
0
] | [
"I guess you are a bit confused, try this code, end to end\n from __future__ import unicode_literals\n import youtube_dl\n import urllib\n import shutil\n ydl_opts = {}\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])\n\n #Movi... | [
-4
] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0040713268_python_python_2.7_python_3.x.txt |
Q:
Neat-python FeedForwordNetwork.activate takes 2 positional arguments but 7 were given even though config file shows 6
When I ran my neat code I got this error in FeedForwardNetwork.activate() :
output = nets[x - 2].activate(player_.red_x, player_.red_y, player_.blue_x, player_.blue_y, player_.catcher,
TypeError: ... | Neat-python FeedForwordNetwork.activate takes 2 positional arguments but 7 were given even though config file shows 6 | When I ran my neat code I got this error in FeedForwardNetwork.activate() :
output = nets[x - 2].activate(player_.red_x, player_.red_y, player_.blue_x, player_.blue_y, player_.catcher,
TypeError: FeedForwardNetwork.activate() takes 2 positional arguments but 7 were given
I am unable to load imgs as I don't have enoug... | [
"Put the items in a list.\n\noutput = nets[x - 2].activate([player_.red_x, player_.red_y, player_.blue_x, player_.blue_y, player_.catcher,last_parm])\n\n"
] | [
0
] | [] | [] | [
"neat",
"python"
] | stackoverflow_0074274085_neat_python.txt |
Q:
Creating a list given an equation with no spaces
I want to create a list given a string such as 'b123+xyz=1+z1$' so that the list equals ['b123', '+', 'xyz', '=', '1', '+', 'z1', '$']
Without spaces or a single repeating pattern, I do not know how to split the string into a list.
I tried creating if statements in ... | Creating a list given an equation with no spaces | I want to create a list given a string such as 'b123+xyz=1+z1$' so that the list equals ['b123', '+', 'xyz', '=', '1', '+', 'z1', '$']
Without spaces or a single repeating pattern, I do not know how to split the string into a list.
I tried creating if statements in a for loop to append the string when it reaches a char... | [
"You can use a regular expression to split your string. This works by using positive lookaheads and look behinds for none word chars.\nimport re\n\nsample = \"b123+xyz=1+z1$\"\nsplit_sample = re.split(\"(?=\\W)|(?:(?<=\\W)(?!$))\", sample)\nprint(split_sample)\n\nOUTPUT\n['b123', '+', 'xyz', '=', '1', '+', 'z1', '$... | [
2,
2,
0,
0,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074270174_list_python_string.txt |
Q:
How to play sound in an Android app created by BeeWare using Python?
I used the BeeWare environment to create a simple MahJong game (find & click pairs to remove them) using Python (with Toga as layout tool) for Android.
Now I would like to have some buttons give a "click sound" when pressed:
Anyone have a helping... | How to play sound in an Android app created by BeeWare using Python? | I used the BeeWare environment to create a simple MahJong game (find & click pairs to remove them) using Python (with Toga as layout tool) for Android.
Now I would like to have some buttons give a "click sound" when pressed:
Anyone have a helping hint (or even working example)?
| [
"If you're using Briefcase 0.3.10 or newer (which uses Chaquopy to support Python on Android), then you could use the Chaquopy Python API to play audio files using SoundPool.\nFor example, the code from this answer could be written in Python as follows:\nfrom android.media import AudioManager, SoundPool\nfrom os.pa... | [
1
] | [] | [] | [
"android",
"beeware",
"cross_platform",
"python"
] | stackoverflow_0074120614_android_beeware_cross_platform_python.txt |
Q:
Why converting float to float16 creates unnecessary values?
Why when I perform
g = np.float16([4.4,4.6])
I get something different
g = [4.3984..., 4.6015...].
Will it somehow affect calculations with the matrix? Can I change this behavior without changing dtype?
Thanks!
A:
First of all, you have to cast floa... | Why converting float to float16 creates unnecessary values? | Why when I perform
g = np.float16([4.4,4.6])
I get something different
g = [4.3984..., 4.6015...].
Will it somehow affect calculations with the matrix? Can I change this behavior without changing dtype?
Thanks!
| [
"First of all, you have to cast float16 back to a float to get that result. You aren't getting a different result though, that's the actual value.\nYou can't represent 4.4 or 0.3 and many other rational numbers with a floating point number, no matter the precision. Python itself doesn't store 4.4 :\n>>> f\"{4.4}\" ... | [
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"precision",
"python"
] | stackoverflow_0074275130_numpy_numpy_ndarray_precision_python.txt |
Q:
Python to control Arduino
I want to develop a machine learning algorithm that will control the traffic lights to optimize the traffic flow. For the DEMO, I'll like to figure out a way to control an Arduino with 4 Traffic Lights for cars and 4 Pedestrian Lights ( 20 LEDs in total ), but all the control must come fr... | Python to control Arduino | I want to develop a machine learning algorithm that will control the traffic lights to optimize the traffic flow. For the DEMO, I'll like to figure out a way to control an Arduino with 4 Traffic Lights for cars and 4 Pedestrian Lights ( 20 LEDs in total ), but all the control must come from a Python script that will de... | [
"You'll have to upload the StandardFirmata to your Arduino. From there on you'll be able to use the pyfirmata library to access the hardware.\nThis is example code from realpython.com\nimport pyfirmata\nimport time\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\n\nwhile True:\n board.digital[13].write(1)\n time... | [
1
] | [] | [] | [
"arduino",
"machine_learning",
"python"
] | stackoverflow_0074275253_arduino_machine_learning_python.txt |
Q:
How to execute raw SQL in Flask-SQLAlchemy app
How do you execute raw SQL in SQLAlchemy?
I have a python web app that runs on flask and interfaces to the database through SQLAlchemy.
I need a way to run the raw SQL. The query involves multiple table joins along with Inline views.
I've tried:
connection = db.sess... | How to execute raw SQL in Flask-SQLAlchemy app | How do you execute raw SQL in SQLAlchemy?
I have a python web app that runs on flask and interfaces to the database through SQLAlchemy.
I need a way to run the raw SQL. The query involves multiple table joins along with Inline views.
I've tried:
connection = db.session.connection()
connection.execute( <sql here> )
B... | [
"Have you tried:\nresult = db.engine.execute(\"<sql here>\")\n\nor:\nfrom sqlalchemy import text\n\nsql = text('select name from penguins')\nresult = db.engine.execute(sql)\nnames = [row[0] for row in result]\nprint names\n\nNote that db.engine.execute() is \"connectionless\", which is deprecated in SQLAlchemy 2.0.... | [
406,
266,
69,
64,
39,
14,
2,
0,
0
] | [
"If you want to avoid tuples, another way is by calling the first, one or all methods:\nquery = db.engine.execute(\"SELECT * FROM blogs \"\n \"WHERE id = 1 \")\n\nassert query.first().name == \"Welcome to my blog\"\n\n"
] | [
-1
] | [
"flask",
"flask_sqlalchemy",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0017972020_flask_flask_sqlalchemy_python_sql_sqlalchemy.txt |
Q:
Limit argument to specific values in python
If I have python function with a string argument which needs to be in a specific list of values, what's the best way to handle this? Is there a convention to expressing this in the docstrings or anything?
eg.
def makeShape(shape):
assert shape in ["circle", "square", ... | Limit argument to specific values in python | If I have python function with a string argument which needs to be in a specific list of values, what's the best way to handle this? Is there a convention to expressing this in the docstrings or anything?
eg.
def makeShape(shape):
assert shape in ["circle", "square", "triangle"]
Is there a nicer way to express that... | [
"You could use an enum for the correct sort of shapes:\nclass rightShape(Enum):\n circle = 1\n square = 2\n triangle = 3\n\ndef makeShape(rightShape):\n # code in function\n\nThis will throw an honest-to-goodness error if you try to pass the function anything but a circle, square, or triangle.\n",
"If... | [
13,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0022418088_python.txt |
Q:
ATBSWP Chapter 4 practice project: Comma Code
So the practice project is as follows:
Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted ... | ATBSWP Chapter 4 practice project: Comma Code | So the practice project is as follows:
Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the prev... | [
"This is how I solved the problem:\ndef commaCode(eggs):\n return ', '.join(map(str,eggs[:-1])) + ' and ' + str(eggs[-1])\nspam = ['apples', 'bananas', 'tofu', 'cats']\nprint(commaCode(spam))\n\nOutput:\n\napples, bananas, tofu and cats\n\njoin() and map() wasn't discussed in the chapter. I learnt them while goo... | [
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0036191668_list_python.txt |
Q:
Custom django permissions for group chats?
I have a custom group model like this:
class MyGroup(models.Model):
name = models.CharField(max_length=200,null=True,blank=False,default="Group name")
members = models.ManyToManyField(get_user_model(), blank=True, related_name="grpmembers")
created_by = models... | Custom django permissions for group chats? | I have a custom group model like this:
class MyGroup(models.Model):
name = models.CharField(max_length=200,null=True,blank=False,default="Group name")
members = models.ManyToManyField(get_user_model(), blank=True, related_name="grpmembers")
created_by = models.ForeignKey(get_user_model(), on_delete=models.D... | [
"The problem is doing all the logic in models.\nOver problem 1 you need to verify user is not owner before allow to leave in the views.py.\nOver the problem 2 are 2 solutions, or you move can_view_group to views.py, or you define that in models as:\ndef can_view_group(self, user):\n #all the logic\n\nAnd you pas... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074274323_django_python.txt |
Q:
Copying a list of custom class objects without using .deepcopy()
I am working on an inventory simulation model. I have this global list variable called current_batches which consists of objects of a custom class Batch and is used to keep track of the current inventory. While running the simulation, a number of fun... | Copying a list of custom class objects without using .deepcopy() | I am working on an inventory simulation model. I have this global list variable called current_batches which consists of objects of a custom class Batch and is used to keep track of the current inventory. While running the simulation, a number of functions use this current_batches variable and modify it following certa... | [
"If you need a full deepcopy which takes time because the copied object is large I see no way to avoid it.\nI suggest you speed things up creating a current_batches_update object where you save the modifications only and adjust the logic of the code to get values not present in current_batches_update object from th... | [
0
] | [] | [] | [
"class",
"copy",
"object",
"performance",
"python"
] | stackoverflow_0074275236_class_copy_object_performance_python.txt |
Q:
Encoding problem when I want to save a CSV in Python
I want to save this list in a CSV file in Python.
row = ['4CIIN', '04-11-2022', '00:00', '2022-11-05 00:00:00', '00:00', b'4CIIN Compiti Scrivi un programma C che, 3CIIN letto l\xe2\x80\x99anno di nascita di una persona e l\xe2\x80\x99anno attuale in input, calc... | Encoding problem when I want to save a CSV in Python | I want to save this list in a CSV file in Python.
row = ['4CIIN', '04-11-2022', '00:00', '2022-11-05 00:00:00', '00:00', b'4CIIN Compiti Scrivi un programma C che, 3CIIN letto l\xe2\x80\x99anno di nascita di una persona e l\xe2\x80\x99anno attuale in input, calcoli l\xe2\x80\x99et\xc3\xa0 della persona. Restituisci un ... | [
"One approach would be to first convert any bytes into utf-8. Then use .writerow() to write a single row.\nWhen using a csv.writer() you should use newline='' to avoid extra unwanted newlines (this is explained in the Python docs).\nFor example:\nimport csv\n\nrow = ['4CIIN', '04-11-2022', '00:00', '2022-11-05 00:0... | [
1
] | [] | [] | [
"csv",
"encoding",
"python"
] | stackoverflow_0074270443_csv_encoding_python.txt |
Q:
I'm having trouble drawing a maple leaf in python turtle
Hey So I am trying to draw a Canadian Flag with python turtle but I am a beginner and I am having trouble drawing a maple leaf. Here is my code for the rectangles which I managed to do but Im stuck on the leaf so I was wondering if anyone could explain it in... | I'm having trouble drawing a maple leaf in python turtle | Hey So I am trying to draw a Canadian Flag with python turtle but I am a beginner and I am having trouble drawing a maple leaf. Here is my code for the rectangles which I managed to do but Im stuck on the leaf so I was wondering if anyone could explain it in simple terms. Here is the code I have to draw the 2 red sides... | [
"#MapleLeaf-Modifiable by USA\n# This will do \"black\" & \"red\", plus \"white\" & \"blue\" for Toronto, may God bless you all.\n\nimport turtle\n\ndef MapleLeaf(x=None, y=None):\n if x == None:\n x=0\n if y == None:\n y=0\n\n\n s = float(input(\"Please enter scale factor ? \"))\n\n turtl... | [
1,
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0067758066_python_python_turtle_turtle_graphics.txt |
Q:
How to add generated image in embed | discord.py
i was generated an image with "easy_pil" libray and i need to paste this image in to my embed, how can i do this using embed.set_image?
Generated image code:
background = Editor('./assets/card_1.jpg').resize((900, 300))
background.rectangle((30,220), width=600, hei... | How to add generated image in embed | discord.py | i was generated an image with "easy_pil" libray and i need to paste this image in to my embed, how can i do this using embed.set_image?
Generated image code:
background = Editor('./assets/card_1.jpg').resize((900, 300))
background.rectangle((30,220), width=600, height=30, fill='#C0B6CC', radius=20)
background.bar((30,... | [
"You can use the following code:\nfile = File(fp=background.image_bytes, filename=\"card.png\")\nembed = discord.Embed()\nembed.set_image(url=\"attachment://card.png\")\nawait channel.send(file=file, embed=embed)\n\nSource: https://discordpy.rtfd.org/en/stable/faq.html#local-image\n"
] | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074266848_discord.py_python.txt |
Q:
How do i save one subscription pub/sub message to three different big query tables in apache beam in python?
I have created three process and want to save data but this is not working for me.
Below is my custom pardo:
subscription = "pub/sub/writeToBigquery"
dataset_table1="A"
dataset_table2="B"
dataset_table3="c... | How do i save one subscription pub/sub message to three different big query tables in apache beam in python? | I have created three process and want to save data but this is not working for me.
Below is my custom pardo:
subscription = "pub/sub/writeToBigquery"
dataset_table1="A"
dataset_table2="B"
dataset_table3="c"
Schema1="et:timestamp,name:string,Day:integer"
schema2="et:timestamp,Place:string,Month:integer"
schema3="et:tim... | [
"You can do that with 3 sinks, example :\ndef process1(self, element, timestamp=beam.DoFn.TimestampParam):\n parsed = dict()\n parsed = json.loads(element.decode(\"utf-8\"))\n parsed[\"et\"] = parsed.et,\n parsed[\"name\"] = parsed.name\n parsed[\"Day\"] = parsed.day\n yield parsed\n\ndef process2... | [
1
] | [] | [] | [
"apache_beam",
"google_bigquery",
"google_cloud_pubsub",
"pipeline",
"python"
] | stackoverflow_0074273677_apache_beam_google_bigquery_google_cloud_pubsub_pipeline_python.txt |
Q:
how to access and print the value of inner index in python list
I have a list of strings i will like to access and print its inner elements as shown below:
mylist = ['apple', 'balls', 'camera', 'dough', 'eleven']
specified_index = random.choices((range(len(mylist))), k=len(mylist))
print("specified_index =", speci... | how to access and print the value of inner index in python list | I have a list of strings i will like to access and print its inner elements as shown below:
mylist = ['apple', 'balls', 'camera', 'dough', 'eleven']
specified_index = random.choices((range(len(mylist))), k=len(mylist))
print("specified_index =", specified_index)
merged_index = [mylist[tt] for tt in specified_index]
pri... | [
"Assuming all the words in mylist are longer than or equal to the length of mylist a list comprehension could be used to achieve your desired result:\n>>> import random\n>>> mylist = ['apple', 'balls', 'camera', 'dough', 'eleven']\n>>> specified_index = random.choices((range(len(mylist))), k=len(mylist))\n>>> speci... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074275438_python.txt |
Q:
Python error intents missing how can i fix?
Hello Im having This Error and idk how can i fix it
Traceback (most recent call last):
File "main.py", line 11, in <module>
blox = commands.Bot(command_prefix='!')
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
And on Linke 11 my code wr... | Python error intents missing how can i fix? | Hello Im having This Error and idk how can i fix it
Traceback (most recent call last):
File "main.py", line 11, in <module>
blox = commands.Bot(command_prefix='!')
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
And on Linke 11 my code wrriten is -
blox = commands.Bot(command_prefix='!'... | [
"You should pass the keyword argument intents to the Bot constructor.\nblox = commands.Bot(command_prefix='!', intents=intents)\nBut first you have to initialize the intents variable. You can read more about intents here.\n"
] | [
0
] | [] | [] | [
"error_handling",
"python",
"roblox"
] | stackoverflow_0074275573_error_handling_python_roblox.txt |
Q:
count the arrays in a large array
I wrote the following code but when the rows are large it is slow
import numpy as np
array = np.array([
[1,2],[1,2],[2,3],
[1,2],[2,3],[5,2]])
d={}
for l in array:
t = tuple(l)
if t in d:
d[t]+=1
else:
d[t]=1
print... | count the arrays in a large array | I wrote the following code but when the rows are large it is slow
import numpy as np
array = np.array([
[1,2],[1,2],[2,3],
[1,2],[2,3],[5,2]])
d={}
for l in array:
t = tuple(l)
if t in d:
d[t]+=1
else:
d[t]=1
print(d)
result:
`{(1, 2): 3, (2, 3): 2, (... | [
"Use np.unique\nelements, counts = np.unique(array, axis=0, return_counts=True)\n\nIn your case, elements will be\n[[1, 2],\n [2, 3],\n [5, 2]]\n\nand counts will be\n[3, 2, 1]\n",
"Without numpy library be like\nfinal_count={}\nfor lst in [list(x) for x in set(tuple(x) for x in array)]:\n final_count[tuple(l... | [
4,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074275522_arrays_numpy_python.txt |
Q:
Create different list from value in column 2 based on value in column 1
I have a table with 2 columns. I want to add values from column 2 to a three differents lists depending to the values in the other column
this is exemple of the table :'
df = pd.DataFrame({'col1':['x', 'y', 'z', 'x', 'y', 'z'], 'col2':['owl', ... | Create different list from value in column 2 based on value in column 1 | I have a table with 2 columns. I want to add values from column 2 to a three differents lists depending to the values in the other column
this is exemple of the table :'
df = pd.DataFrame({'col1':['x', 'y', 'z', 'x', 'y', 'z'], 'col2':['owl', 'fox', 'horse', 'dog', 'lion', 'bird']})
Expected output :
list_x = ['owl', '... | [
"import numpy as np\nimport pandas as pd\n\nlist_x = df.loc[df['col1'] == 'x', 'col2'].values\nlist_y = df.loc[df['col1'] == 'y', 'col2'].values\nlist_z = np.flip(df.loc[df['col1'] == 'z', 'col2'].values)\n\nprint('list_x', list_x, 'list_y', list_y, 'list_z', list_z)\n\nOutput\nlist_x ['owl' 'dog'] list_y ['fox' 'l... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074267504_pandas_python.txt |
Q:
open cv warp transformation
ich have a script to transform and warp an Image with open cv.
unfortunatel i get an error. It seems that cv2.warpPerspective cannot read the image.
Do have an idea to solve the issue? You will find the code here:
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
... | open cv warp transformation | ich have a script to transform and warp an Image with open cv.
unfortunatel i get an error. It seems that cv2.warpPerspective cannot read the image.
Do have an idea to solve the issue? You will find the code here:
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
img = cv2.imread('path to jpeg')... | [
"The solution below doesn't use matplotlib but seems to give the desired output.\nNote that your 4th point, pt_D, was slightly off so I adjusted it to match with the actual court last corner.\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('./tennis_court.jpg')\n\npt_A =[162,83]\npt_B = [68,324]\npt_C = [542,32... | [
0
] | [] | [] | [
"opencv",
"python",
"transformation",
"warp"
] | stackoverflow_0074274343_opencv_python_transformation_warp.txt |
Q:
Advance a Interpolation
Note; No special knowledge of Pykrige is needed to answer the question, as I already mention examples in the question!
Hi I would like to use Universal Kriging in my code. For this I have data that is structured as follows:
Latitude Longitude Altitude H2 O18 ... | Advance a Interpolation | Note; No special knowledge of Pykrige is needed to answer the question, as I already mention examples in the question!
Hi I would like to use Universal Kriging in my code. For this I have data that is structured as follows:
Latitude Longitude Altitude H2 O18 Date Year month da... | [
"From the documentation of pykrige.uk.UniversalKriging (https://geostat-framework.readthedocs.io/projects/pykrige/en/stable/generated/pykrige.uk.UniversalKriging.html#pykrige.uk.UniversalKriging):\n\ndrift_terms (list of strings, optional) – List of drift terms to\ninclude in universal kriging. Supported drift term... | [
1,
0
] | [] | [] | [
"interpolation",
"kriging",
"mapping",
"numpy",
"python"
] | stackoverflow_0072631305_interpolation_kriging_mapping_numpy_python.txt |
Q:
How do I insert element reference in an xpath string?
Given a UI element reference, how do I "append" a string to it so that I can find its next sibling element of type XCUIElementTypeStaticText?
The framework I am using contains a driver_helper.py file.
Within that file are the find_element & find_elements method... | How do I insert element reference in an xpath string? | Given a UI element reference, how do I "append" a string to it so that I can find its next sibling element of type XCUIElementTypeStaticText?
The framework I am using contains a driver_helper.py file.
Within that file are the find_element & find_elements methods defined as:
def find_element(self, locator: tuple) -> Web... | [
"If you can add methods in the driver_helper.py, you can implement there a method using the solution provided in this answer\nBut if you can not do that, you need to change the code of your sibling variable. Now you are trying to put an element into XPATH and this can not work as you put an object into a string.\nS... | [
2,
1,
1
] | [] | [] | [
"automated_tests",
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074241538_automated_tests_python_selenium_selenium_webdriver_xpath.txt |
Q:
How do I add axis labels and a title to a matplotlib integrated into a tkinter window?
I have searched the docs and I cannot figure out how to label the axis and title of a plot.
This is my current code:
font = {'size' : 40}
plot.rc('font', **font)
fig = Figure(figsize=(32, 31), dpi=20)
plot.figure(facecolor='... | How do I add axis labels and a title to a matplotlib integrated into a tkinter window? | I have searched the docs and I cannot figure out how to label the axis and title of a plot.
This is my current code:
font = {'size' : 40}
plot.rc('font', **font)
fig = Figure(figsize=(32, 31), dpi=20)
plot.figure(facecolor='yellow')
canvas = FigureCanvasTkAgg(fig, master=graphFrame) # A tk.DrawingArea.
canvas.get... | [
"You'll want to use plot.title, axis.set_xlabel, and axis.set_ylabel\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0074269606_matplotlib_python_tkinter.txt |
Q:
Interpolating a 2D array given value of certain points
Let's say I have a 2D array of that represents the signal strength of a network, like so:
d = np.array([[ 0, 0, 0, 3],
[ 0, 2, 0, 3],
[ 0, 0, 0, 0],
[ 0, 0, 0, 3]])
I know the signal strength of specific t... | Interpolating a 2D array given value of certain points | Let's say I have a 2D array of that represents the signal strength of a network, like so:
d = np.array([[ 0, 0, 0, 3],
[ 0, 2, 0, 3],
[ 0, 0, 0, 0],
[ 0, 0, 0, 3]])
I know the signal strength of specific transmission nodes in the network, and the ones I don't know ... | [
"I suspect you're not interpolating, but instead applying a max of the effects from each station. Extend to a three dimensional matrix where the added dimension is the number of stations, and then do a max over that dimension. The following produces the same output (made non-square to avoid transposition errors):\n... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074259044_numpy_python.txt |
Q:
SNOWPARK - How to use a sql command returned in a dataframe in anoter sql command downstream
How do I return the sql command in sql_df1 and automate the use of this command in another sql command
sql_df1= test_session.sql("select get_ddl('TABLE', 'A.TEST')")
sql_df1.show()
---------------------------------
|"GET... | SNOWPARK - How to use a sql command returned in a dataframe in anoter sql command downstream | How do I return the sql command in sql_df1 and automate the use of this command in another sql command
sql_df1= test_session.sql("select get_ddl('TABLE', 'A.TEST')")
sql_df1.show()
---------------------------------
|"GET_DDL('TABLE', 'A.TEST')" |
---------------------------------
|create or replace TABLE TEST ( |
|... | [
"There a few ways to do it.\nIf you're importing pandas, then something like this would work:\ndf = session.sql(\"SELECT GET_DDL('table', 'CITIBIKE_TRIPS')\")\npdf = df.to_pandas()\nprint(pdf.values[:1][0][0])\n\nI get as output:\ncreate or replace TABLE CITIBIKE_TRIPS (\n RIDE_ID VARCHAR(16777216),\n RIDEABL... | [
1
] | [] | [] | [
"python",
"snowflake_cloud_data_platform",
"snowpark"
] | stackoverflow_0074274880_python_snowflake_cloud_data_platform_snowpark.txt |
Q:
Pyinstaller doesn't find hidden import configargparse
I am trying to compile a python program which imports configargparse, but pyinstaller doesn't find it, even if I specify it with hidden imports. I use following command: pyinstaller.exe --onefile --hidden-import=configargparse some_folder\viewer.py --log-level... | Pyinstaller doesn't find hidden import configargparse | I am trying to compile a python program which imports configargparse, but pyinstaller doesn't find it, even if I specify it with hidden imports. I use following command: pyinstaller.exe --onefile --hidden-import=configargparse some_folder\viewer.py --log-level=DEBUG --debug=imports but when running the exe I get:
# co... | [
"So I had to add my venv/lib/site-packages as an absolute path to pathex in the spec file.\n"
] | [
0
] | [] | [] | [
"exe",
"pyinstaller",
"python"
] | stackoverflow_0074273813_exe_pyinstaller_python.txt |
Q:
How to get unique sets of data in pandas
Imagine people were asked their favorite color and their answers stored in a DataFrame (Person - Color). Some people name only one color, some -- more. I need to find unique combinations (sets) of colors.
import pandas as pd
data_list=['black',
'red',
... | How to get unique sets of data in pandas | Imagine people were asked their favorite color and their answers stored in a DataFrame (Person - Color). Some people name only one color, some -- more. I need to find unique combinations (sets) of colors.
import pandas as pd
data_list=['black',
'red',
'red',
'black',
'red',
... | [
"You could make a new column with a joined string of all the colors:\ndf_grouped = df.groupby('Names').agg({'Colors': pd.unique})\ndf_grouped['Colors str'] = [''.join(sorted(color_list)) for color_list in df_grouped['Colors']]\n\n# drop duplicate color combinations: \ndf_grouped = df_grouped.drop_duplicates(subset=... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074275731_pandas_python.txt |
Q:
Reading A Rotary Encoder in pyfirmata
I am trying to get the data from an encoder with pyfirmata. But I couldn't find anything on this particular topic. If someone could help me I would be very grateful.
A:
Here
Pin
CLk -> D8
DT -> D7
from pyfirmata import Arduino, util
import pyfirmata.util
counter = 0
board ... | Reading A Rotary Encoder in pyfirmata | I am trying to get the data from an encoder with pyfirmata. But I couldn't find anything on this particular topic. If someone could help me I would be very grateful.
| [
"Here\nPin\nCLk -> D8\nDT -> D7\nfrom pyfirmata import Arduino, util\nimport pyfirmata.util\n\ncounter = 0\n\nboard = Arduino('COM3')\n\niterator = pyfirmata.util.Iterator(board)\niterator.start()\n\nboard.digital[9].mode = pyfirmata.INPUT\nboard.digital[8].mode = pyfirmata.INPUT\n\naLastState = board.digital[9].re... | [
0
] | [] | [] | [
"arduino",
"pyfirmata",
"python"
] | stackoverflow_0073754298_arduino_pyfirmata_python.txt |
Q:
How to display tabset again after .close()?
I am working on a small application on ipywidgets that has multiple frames. This means users can click a button, and then the original set of widgets will be closed and a new set of widgets will appear. The function which I am using has a simplified structure as below:
d... | How to display tabset again after .close()? | I am working on a small application on ipywidgets that has multiple frames. This means users can click a button, and then the original set of widgets will be closed and a new set of widgets will appear. The function which I am using has a simplified structure as below:
def to_next_page(x):
current_page.close()
... | [
"you cant use .close\nuse this\nout = Output()\ndef to_next_page(x):\n out.clear_output()\n with out:\n display(next_page)\n\nand for displaying everytime use:\nwith out:\n display(anything)\n\nand for closing use:\n out.clear_output()\n\n"
] | [
0
] | [] | [] | [
"ipywidgets",
"python"
] | stackoverflow_0074086941_ipywidgets_python.txt |
Q:
Chat server - can't receive message while getting input from user
Okay so I understood what I did wrong. But I have another problem now, where using multithreading doesn't work as intended. In the code below, in the main fucntion, I start the message_listener thread, which should work in the background while I get... | Chat server - can't receive message while getting input from user | Okay so I understood what I did wrong. But I have another problem now, where using multithreading doesn't work as intended. In the code below, in the main fucntion, I start the message_listener thread, which should work in the background while I get user input. But when I send something from another client, the message... | [
"This is because the program waits for input from the user before receiving new messages. Your actions do not work in parallel.\nI suggest making the following changes\nimport threading\n\n\ndef message_handler():\n while True:\n # open listening and print new msg\n \n\nif __name__ == \"__main__\":\n ... | [
0
] | [] | [] | [
"multithreading",
"networking",
"python",
"sockets"
] | stackoverflow_0074275750_multithreading_networking_python_sockets.txt |
Q:
FileNotFoundError: [WinError 2] The system cannot find the file specified while running fastapi project using manage-fastapi
I am getting the following error when I try to run my fastapi project
1491, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
^^^^^... | FileNotFoundError: [WinError 2] The system cannot find the file specified while running fastapi project using manage-fastapi | I am getting the following error when I try to run my fastapi project
1491, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [WinError 2] The system cannot find the file specified
I am using manage-fa... | [
"From the traceback it seems like manage-fastapi is trying to execute some external commands. The way to execute external commands in python is using subprocess module. So searching over the manage-fastapi repository finds only two instances of subprocess call. One is,\ndef validate_project(cls, values: dict):\n ... | [
2
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074275768_fastapi_python.txt |
Q:
Multiply 1 element of a row with 1 element of a column in pandas and sum the product
I very new in python and I'm trying to have a first approach in pandas.
I have two dataframes, two tabs, made in this way:
df1
index | value_1 | value_2 | value_3 | value_4
0 1 2.5 3 5.5
1 5 ... | Multiply 1 element of a row with 1 element of a column in pandas and sum the product | I very new in python and I'm trying to have a first approach in pandas.
I have two dataframes, two tabs, made in this way:
df1
index | value_1 | value_2 | value_3 | value_4
0 1 2.5 3 5.5
1 5 1 2 3
2 8.58 4 1.5 1
3 2 ... | [
"Here is one way you can do it:\nimport pandas as pd\n \n# initialize list of lists\ndata_row = [[1, 2], [3, 4]]\ndata_col = [[5, 6], [7, 8]]\n# Create the pandas DataFrame\ndf_row = pd.DataFrame(data_row)\ndf_col = pd.DataFrame(data_col)\n#Transpose the df_col\ndf_col = df_col.T\ndf_mul = df_row.multiply(df_col)\... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074275474_pandas_python.txt |
Q:
Can we use matplotlib.animation in kivy? If Yes,How?
Well this How to use matplotlib animation within kivy question is similar but the answer is just not at all valuable
Also as pointed by @ImportanceOfBeingErnest I edited the question to Can we actually do it?If Yes then proceed below.
So it was easy to add anima... | Can we use matplotlib.animation in kivy? If Yes,How? | Well this How to use matplotlib animation within kivy question is similar but the answer is just not at all valuable
Also as pointed by @ImportanceOfBeingErnest I edited the question to Can we actually do it?If Yes then proceed below.
So it was easy to add animation in tkinter according to the following tutorial Sentde... | [
"I think kivy is less used nowadays.Nobody answered So i somehow i figured out a alternative to what i wanted to achieve.\nI added a Refresh button which runs the whole fuction again which includes fetching of the values from a file and draws the graph again.Thus whenever the values are updated in the file we get a... | [
1,
0,
0
] | [] | [] | [
"animation",
"kivy",
"matplotlib",
"python"
] | stackoverflow_0053830982_animation_kivy_matplotlib_python.txt |
Q:
Convert MultiIndex to column suffixes in pandas
I have this single pd.DataFrame
pd.DataFrame(columns=pd.MultiIndex.from_product([['X', 'Y'], ['L', 'R']]),
data=[[1, 5, 2, 6],
[3, 7, 4, 8]])
which produces
X Y
L R L R
-----------------
0 1 5 2 6
1 3 ... | Convert MultiIndex to column suffixes in pandas | I have this single pd.DataFrame
pd.DataFrame(columns=pd.MultiIndex.from_product([['X', 'Y'], ['L', 'R']]),
data=[[1, 5, 2, 6],
[3, 7, 4, 8]])
which produces
X Y
L R L R
-----------------
0 1 5 2 6
1 3 7 4 8
I would like to add the upper index as a s... | [
"You can use map for this\ndf.columns = df.columns.map(lambda x: f\"{x[1]}_{x[0]}\")\n\n L_X R_X L_Y R_Y\n0 1 5 2 6\n1 3 7 4 8\n\n",
"df.columns=[col[1] + \"_\" + col[0] for col in df.columns]\ndf\n\n L_X R_X L_Y R_Y\n0 1 5 2 6\n1 3 7 ... | [
1,
1,
0
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074275372_multi_index_pandas_python.txt |
Q:
Python multiple x,y,z values - is there a way to write them in short?
!!! >> I'm a total newbie, I opened matplotlib like 3 hours ago and self-taught myself here. If you introduce any new commands/lines, please let me know what they're called so I can look up tutorials, thanks!
Attempting to: Make a 3d plot of tra... | Python multiple x,y,z values - is there a way to write them in short? | !!! >> I'm a total newbie, I opened matplotlib like 3 hours ago and self-taught myself here. If you introduce any new commands/lines, please let me know what they're called so I can look up tutorials, thanks!
Attempting to: Make a 3d plot of tracks/lines
Problem: I have a .csv files with 29 sets of x y z data points wi... | [
"Since it's a fixed number of rows you can iterate over a range to get values. If it weren't fixed, you could count rows and use that to set the range.\nfor idx in range(29):\n suffix = '' if idx == 0 else str(idx + 1) # ranges start at 0\n x = points[f\"x{suffix}\"].values \n y = points[f\"y{suffix}\"].valu... | [
1,
1
] | [] | [] | [
"3d",
"line_plot",
"matplotlib",
"python"
] | stackoverflow_0074275971_3d_line_plot_matplotlib_python.txt |
Q:
Django error while saving to database : IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id
I have two models with OneToMany relation between them. personelModel and arizaModel. When I click the save button, I get the following error:
"IntegrityError at / NOT NULL constraint failed: kullan... | Django error while saving to database : IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id | I have two models with OneToMany relation between them. personelModel and arizaModel. When I click the save button, I get the following error:
"IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id"
personelModel saved but arizaModel not saved in database table. I want both models to be saved in ... | [
"p_id = models.ForeignKey(personelModel, on_delete=models.CASCADE)\n\n# p_id is null when save form you must be pass personelModel instance at saving time of\n\nform2 = ArizaBilgileriForm(request.POST, prefix='ariza_bilgileri')\n\n-------- Hint ------\nif request.method == 'POST':\n if form1.is_valid() and form2... | [
0
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074275664_django_django_models_django_templates_django_views_python.txt |
Q:
GCP Cloud Function PubSub not passing message to topic
I am trying to write a GCP Cloud Function which collects some data from an API call then stores selected data points in Firestore. I also would like to pass the event IDs to PubSub topic so that I can use them in other Cloud Functions.
So far I have the follow... | GCP Cloud Function PubSub not passing message to topic | I am trying to write a GCP Cloud Function which collects some data from an API call then stores selected data points in Firestore. I also would like to pass the event IDs to PubSub topic so that I can use them in other Cloud Functions.
So far I have the following:
import base64
import os
import requests
import json
fro... | [
"Since you have written PubSub code below the return statement the code was not executing.After rearranging the code it should be working as expected.\nFrom the comments it is clear that after modifying the code it is working as intended.\n"
] | [
0
] | [] | [] | [
"google_cloud_functions",
"google_cloud_platform",
"google_cloud_pubsub",
"python"
] | stackoverflow_0074260324_google_cloud_functions_google_cloud_platform_google_cloud_pubsub_python.txt |
Q:
Why am I getting multiple curves instead of one in a pdf
I'm trying to plot a histogram and a pdf for a normal distribution function of data_2, but I'm getting multiple lines instead of one, like this
Here is my code
def normal_dist(data_list):
density_func = sps.norm.pdf(data_list, np.mean(data_list), np.std... | Why am I getting multiple curves instead of one in a pdf | I'm trying to plot a histogram and a pdf for a normal distribution function of data_2, but I'm getting multiple lines instead of one, like this
Here is my code
def normal_dist(data_list):
density_func = sps.norm.pdf(data_list, np.mean(data_list), np.std(data_list))
return density_func
def plot_histo(data_list... | [
"matplotlib.pyplot.plot will plot the points in the order provided. The weird plot you get is because your \"x-values\" in data_2 are not sorted. To solve that, do the following\ndef plot_histo(data_list, bin_count , pdf):\n plt.hist(data_list, bins=bin_count, density= True)\n # Get the indices of the element... | [
2
] | [] | [] | [
"distribution",
"numpy",
"python",
"scipy",
"statistics"
] | stackoverflow_0074275730_distribution_numpy_python_scipy_statistics.txt |
Q:
How to color given data with matplotlib python?
I took Machine Learning course but since I have no idea about ML, it is very hard for me to understand all concept. I have a homework and I have to plot data to be able to start homework but I couldn't even plot the data properly. For question, instructor sent us a c... | How to color given data with matplotlib python? | I took Machine Learning course but since I have no idea about ML, it is very hard for me to understand all concept. I have a homework and I have to plot data to be able to start homework but I couldn't even plot the data properly. For question, instructor sent us a csv data file which consists of 3 columns. 3rd column ... | [
"Your data looks very similar to the picture, so you're close :).\nWhat you can do, it to use pandas to filter the dots by their colour, and make two calls to plot. You can pass the color to plot with, so in the first call you'd pass 'blue' and in the second call, with the 2nd set of points, you'd use yellow for th... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074275244_matplotlib_python.txt |
Q:
Is there a way to screenshot instagram without making it logging in more than once in selenium?
Is there a way where every time selenium tries to screenshot an instagram account, it only needs to login once?
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from s... | Is there a way to screenshot instagram without making it logging in more than once in selenium? | Is there a way where every time selenium tries to screenshot an instagram account, it only needs to login once?
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
from time import sleep
from credentials import user... | [
"You can achieve this using profile - Chrome profile.\nI couldn't able to verify this code, because my instagram account has some problems, but this code should work.\nThere are some flaws in your code, I've modified it.\nfrom selenium.webdriver.chrome.service import Service\n\nchrome_options = Options()\n# path of... | [
1
] | [] | [] | [
"google_chrome",
"instagram",
"jupyter_notebook",
"python",
"selenium"
] | stackoverflow_0074271533_google_chrome_instagram_jupyter_notebook_python_selenium.txt |
Q:
How to get all the indexes of leading zeroes using regex in python
Using Regex in Python (library re (only)), I want to create a function that gives me the position of all leading 0s in a string.
For example, if the string was: My house has 01 garden and 003 rooms.
I would want me the function to return 13, 27 and... | How to get all the indexes of leading zeroes using regex in python | Using Regex in Python (library re (only)), I want to create a function that gives me the position of all leading 0s in a string.
For example, if the string was: My house has 01 garden and 003 rooms.
I would want me the function to return 13, 27 and 28.
I tried for example:
import re
string = "My house has 01 garden and... | [
"You can do the following:\nimport re\n\ntext = \"My house has 01 garden and 003 rooms.\"\npattern = re.compile(r\"\\b0+\")\n\n\ndef leading_zeros_index(s: str) -> list:\n return [i for m in pattern.finditer(s) for i in range(m.start(), m.end())]\n\n\nprint(leading_zeros_index(text))\n\noutput:\n[13, 27, 28]\n\n... | [
6
] | [] | [] | [
"python",
"python_re",
"regex"
] | stackoverflow_0074276093_python_python_re_regex.txt |
Q:
How to extract city from dataframe column (not same format)
i have this dataframe, and i want to extract cities in a separate column. You can also see, that the format is not same, and the city can be anywhere in the row. How can i extract only cities i a new column?
Prompt. Here we are talking about German cities... | How to extract city from dataframe column (not same format) | i have this dataframe, and i want to extract cities in a separate column. You can also see, that the format is not same, and the city can be anywhere in the row. How can i extract only cities i a new column?
Prompt. Here we are talking about German cities. May be to find a dictionary, that shows all German cities and s... | [
"You could extract in a list all the cities from the dictionary you provided ( I asssume it's the 'stadt' key ), and then use str.findall in your column:\ncities_ = [cities[n]['stadt'] for n in range(0,len(cities))]\ndf.Adresse.str.findall(r'|'.join(cities_))\n\n>>>\n0 [Karlstr, Hamburg]\n1 []... | [
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074275857_pandas_python.txt |
Q:
Separate csv file paths with specific seed and speed number using Python
I am facing a problem where I have a list of csv file paths. I need to separate CSV file paths on the basis of specific mode with different seed and same speed using Python.
Naming convention is something like this:
Absolute Path of CSV file/... | Separate csv file paths with specific seed and speed number using Python | I am facing a problem where I have a list of csv file paths. I need to separate CSV file paths on the basis of specific mode with different seed and same speed using Python.
Naming convention is something like this:
Absolute Path of CSV file/(mode)(seed)(speed).csv
csv_filepaths = ['C:/Users/DELL/Documents/abc/alpha_58... | [
"If the unique key identifing each list has to be the combination of mode and speed then I would suggest creating a dictionary using that as key and keep a list of all the paths that correspond to that key.\ncsv_filepaths = [\n \"C:/Users/DELL/Documents/abc/alpha_586893215_speed0.csv\",\n \"C:/Users/DELL/Docu... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074264004_python.txt |
Q:
Could not find a version that satisfies the requirement MetaTrader5 doesn't work on Windows
I want to try MetaTrader5 programming with python,
in python file i have import MetaTrader5. But it's not possible to download that packages.
I tried to run this command on windows.
python -m pip install MetaTrader5
But it... | Could not find a version that satisfies the requirement MetaTrader5 doesn't work on Windows | I want to try MetaTrader5 programming with python,
in python file i have import MetaTrader5. But it's not possible to download that packages.
I tried to run this command on windows.
python -m pip install MetaTrader5
But it's just doesn't work. I tried to search internet. Everywhere is mention about MetaTrader5 doesn't... | [
"Check yout python version, MetaTrader5 only work with Python >= 3.5 and <4.\nCheck Doc\nhttps://pypi.org/project/MetaTrader5/\n"
] | [
1
] | [] | [] | [
"algorithmic_trading",
"metatrader5",
"python",
"trading",
"windows"
] | stackoverflow_0074276031_algorithmic_trading_metatrader5_python_trading_windows.txt |
Q:
How to include string after number in IntSlider?
I wanted to increase the size of the description of my variables and also include the measurement units after the value as indicated in this figure.
My code:
%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
a ... | How to include string after number in IntSlider? | I wanted to increase the size of the description of my variables and also include the measurement units after the value as indicated in this figure.
My code:
%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
a = widgets.IntSlider(description='Força', value=500, mi... | [
"use this instead:\n%matplotlib inline\nfrom ipywidgets import *\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nN = widgets.Label(value = \"N\")\nawidget = widgets.IntSlider(description='Força', value=500, min=1, max=1e3, step=1)\na = HBox([awidget,N])\nm = widgets.Label(value = \"m\")\nbwidget = widgets.I... | [
-1
] | [] | [] | [
"ipywidgets",
"matplotlib",
"python",
"visualization",
"widget"
] | stackoverflow_0073881543_ipywidgets_matplotlib_python_visualization_widget.txt |
Q:
(GeometryTypeError: Unknown geometry type: featurecollection) How to extend a function to all values in a column dependent on another dataframe?
I have written a function to check if a point is within a polygon, and if it is to return "True,{branch_name}" where branch_name is the name of the polygon, and when tryi... | (GeometryTypeError: Unknown geometry type: featurecollection) How to extend a function to all values in a column dependent on another dataframe? | I have written a function to check if a point is within a polygon, and if it is to return "True,{branch_name}" where branch_name is the name of the polygon, and when trying to extend this function to the whole column, I keep encountering the "GeometryTypeError: Unknown geometry type: featurecollection" error.
The funct... | [
"A few points\n\nhave used geopandas sample geometry to simulate data you describe. Making columns of two data frames consistent with what your describe\nyour sample code uses a function shape() it's not clear what this is. Possibly takes a WKT string and converts it into a polygon. Have removed as a polygon is b... | [
0
] | [] | [] | [
"coordinates",
"geometry",
"geopandas",
"pandas",
"python"
] | stackoverflow_0074273090_coordinates_geometry_geopandas_pandas_python.txt |
Q:
Django project doesnt insert into Oracle table
I'm building a integration app that consumes data from a API and save the sensitive information into a table inside a oracle database. My models succesfully migrated and created the tables and I was able to also succesfully consume and filter the data I need from the... | Django project doesnt insert into Oracle table | I'm building a integration app that consumes data from a API and save the sensitive information into a table inside a oracle database. My models succesfully migrated and created the tables and I was able to also succesfully consume and filter the data I need from the API, so I proceeded to use objects.update_or_create... | [
"I was able to solve this. I added a sleep at the end of my loop so that django would wait for the database to end the insert before running the loop one more time. What I think was happening is that the db was not able to keep up with the update of the app and was blocking the insert while holding the session up.\... | [
0
] | [] | [] | [
"django",
"oracle",
"python"
] | stackoverflow_0074236929_django_oracle_python.txt |
Q:
Getting ValueError: Expected 2D array, got 1D array instead:
When I run this code I am getting an error. I am a newbie. Please help me. Thanks in advance.
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import pandas as pd
df_percentage = (pd.read_csv("Data.csv", sep=';'))... | Getting ValueError: Expected 2D array, got 1D array instead: | When I run this code I am getting an error. I am a newbie. Please help me. Thanks in advance.
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import pandas as pd
df_percentage = (pd.read_csv("Data.csv", sep=';'))
print(df_percentage)
x=df_percentage.Percentage
y=df_percentage.P... | [
"x = x.values.reshape(-1,1)\n\nwill fix it.\nsee: https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.reshape.html\n"
] | [
0
] | [] | [] | [
"linear_regression",
"machine_learning",
"python"
] | stackoverflow_0074275913_linear_regression_machine_learning_python.txt |
Q:
ValueError at / (Required parameter name not set)
I am trying to make a blog app using django and python. I am also trying to use s3 buckets for storage and heroku for deployment.I am follow a tutorial online by coreymschafer. I am doing everything exactly as the tutorial, yet i am getting that error. I have no id... | ValueError at / (Required parameter name not set) | I am trying to make a blog app using django and python. I am also trying to use s3 buckets for storage and heroku for deployment.I am follow a tutorial online by coreymschafer. I am doing everything exactly as the tutorial, yet i am getting that error. I have no idea what to do. Please help!
I have also installed boto3... | [
"Had the same issue.\nCommented out this line and the code was working fine again:\nDEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n\nFound out it was because, even if i had already restarted my PC, one of Environmental variable I was referencing was improperly set:\nAWS_ACCESS_KEY_ID = os.enviro... | [
9,
1,
1,
0,
0,
0,
0
] | [
"comment down the line\nSTATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n",
"I did have the same issue.\nTha way I solved it was this:\n\nGo to your AWS console\nChoose the name of your bucket\nChoose properties\nChoose Encryption\nClick on Read more.. (this will lead you to your permissions tab)... | [
-1,
-2
] | [
"amazon_s3",
"amazon_web_services",
"django",
"heroku",
"python"
] | stackoverflow_0059640100_amazon_s3_amazon_web_services_django_heroku_python.txt |
Q:
How to infer the type of last element passed to `*args` parameter in python?
I want to write a pipeline function which takes an abritrary number of functions and forwards the input of the first to the second and so on up until the last. The output of pipeline is a Callable. The input of that Callable matches the f... | How to infer the type of last element passed to `*args` parameter in python? | I want to write a pipeline function which takes an abritrary number of functions and forwards the input of the first to the second and so on up until the last. The output of pipeline is a Callable. The input of that Callable matches the first function given to pipeline. The output matches the last function given to pip... | [
"Actually found a way to solve this problem using TypeVarTuple and Unpack. PEP646 provides an example that shows how to unpack heterogenous parameters passed as *args. With this approach the example from the question could be typed as follows:\nfrom typing import TypeVar\nfrom typing_extension import TypeVarTuple, ... | [
2,
0
] | [] | [] | [
"python",
"python_typing",
"typing"
] | stackoverflow_0074173628_python_python_typing_typing.txt |
Q:
Read a tar.gz compressed file form a file stream, uncompress it and put it in another file stream without writing to disk
I have a big 1GB directory with multiple files that is stored in S3 in the format tar.gz and manipulated by a Lambda function.
The file system of the Lambda function is read only. So I would li... | Read a tar.gz compressed file form a file stream, uncompress it and put it in another file stream without writing to disk | I have a big 1GB directory with multiple files that is stored in S3 in the format tar.gz and manipulated by a Lambda function.
The file system of the Lambda function is read only. So I would like the operations to be done in memory.
I cannot include it in the image of the Lambda function itself, as GitHub won't accept ... | [
"I don't think you can work with 1Gb file from your lambda, because there is a 512 MB in its temp directory limitation (please check https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)\nPlease check for large file, mount an EFS to the lambda or change to logic (explore another possibility worke... | [
1,
1
] | [] | [] | [
"amazon_s3",
"aws_lambda",
"python",
"tar",
"tensorflow"
] | stackoverflow_0070309520_amazon_s3_aws_lambda_python_tar_tensorflow.txt |
Q:
Loop backwards starting in value (list)
If i have a list calle dates (for example) that goes like this:
[2022,2021,2020....]
Until 20 or 30 values. And I reverse it with
reversed(list)
So it looks like this now:
[1980.1981,1982...]
How can I make a loop that starts in value 2020 for example and goes till 2022?
So... | Loop backwards starting in value (list) | If i have a list calle dates (for example) that goes like this:
[2022,2021,2020....]
Until 20 or 30 values. And I reverse it with
reversed(list)
So it looks like this now:
[1980.1981,1982...]
How can I make a loop that starts in value 2020 for example and goes till 2022?
So far i tried in the loop something like this:... | [
"If you know the start index you need the loop to start with you can use slicing like:\nfor item in dates[2::-1]:\n\nwhich will loop backwards starting with the third item (with index 2) in the list down to its first element (with index 0) or\nfor item in reversed_dates[-3:]: \n\nwhich will loop starting with the t... | [
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074275220_loops_python.txt |
Q:
How do I can fix the error Use no-check-certificate
I'm trying to get access to the dataset using:
!wget https://liquidtelecom.dl.sourceforge.net/project/easc-corpus/EASC/EASC.zip
But I got the following error message
ERROR: cannot verify liquidtelecom.dl.sourceforge.net's certificate, issued by ‘CN=R3,O=Let's En... | How do I can fix the error Use no-check-certificate | I'm trying to get access to the dataset using:
!wget https://liquidtelecom.dl.sourceforge.net/project/easc-corpus/EASC/EASC.zip
But I got the following error message
ERROR: cannot verify liquidtelecom.dl.sourceforge.net's certificate, issued by ‘CN=R3,O=Let's Encrypt,C=US’:
Issued certificate has expired.
To connect... | [
"The problem is that liquidtelecom.dl.sourceforge.net does not have a valid https certificate and wget is refusing to connect\nIf you are sure you want to connect to it anyway then provide the --no-check-certificate flag to wget to make it skip certificate validation.\n!wget --no-check-certificate https://liquidtel... | [
1
] | [] | [] | [
"python",
"ssl_certificate"
] | stackoverflow_0074276253_python_ssl_certificate.txt |
Q:
Dictionary with dictionaries add numbering to value
I have a dictionary with dictionaries and I need to add numbers to the values 'plece'. Numbering according to the length of the main dictionary.
{'SVF': {'place': '', 'name': 'Sebastian Vettel', 'team': 'FERRARI', 'time': '1:04.415'}, 'VBM': {'place': '', 'name':... | Dictionary with dictionaries add numbering to value | I have a dictionary with dictionaries and I need to add numbers to the values 'plece'. Numbering according to the length of the main dictionary.
{'SVF': {'place': '', 'name': 'Sebastian Vettel', 'team': 'FERRARI', 'time': '1:04.415'}, 'VBM': {'place': '', 'name': 'Valtteri Bottas', 'team': 'MERCEDES', 'time': '1:12.434... | [
"You can simply iterate through the values of the outer dictionary(which are dictionaries themselves) and get the numbers from enumerate() object whose start= argument is set to 1:\nfrom pprint import pprint\n\nd = {\n \"SVF\": {\n \"place\": \"\",\n \"name\": \"Sebastian Vettel\",\n \"team\... | [
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074275960_dictionary_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.