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:
(Python , OpenCV) Extract picture from picture
I want to extract each sticker 5x6 and to total 30 sticker
like below , how do I do so
(expect pic ) https://imgur.com/a/C5CiSxM
(original picture) https://imgur.com/a/V0lvqU3
from below link I come up my code
How extract pictures from an big image in python
follo... | (Python , OpenCV) Extract picture from picture | I want to extract each sticker 5x6 and to total 30 sticker
like below , how do I do so
(expect pic ) https://imgur.com/a/C5CiSxM
(original picture) https://imgur.com/a/V0lvqU3
from below link I come up my code
How extract pictures from an big image in python
following the suggestion:
The black pixels along the to... | [
"The black pixels along the top are a distraction, so are the black pixels of the QR codes. You are only interested in the white stickers.\nSo, take a copy of your image and threshold at a high value to give you pure white stickers surrounded by black and with black QR codes within each sticker. Now find white cont... | [
1
] | [] | [] | [
"contour",
"image",
"opencv",
"python",
"python_tesseract"
] | stackoverflow_0074299517_contour_image_opencv_python_python_tesseract.txt |
Q:
Python: How to replace every space in a dictionary to an underscore?
Im still a beginner so maybe the answer is very easy, but I could not find a solution (at least one I could understand) online.
Currently I am learning famous works of art through the app "Anki". So I imported a deck for it online containing over... | Python: How to replace every space in a dictionary to an underscore? | Im still a beginner so maybe the answer is very easy, but I could not find a solution (at least one I could understand) online.
Currently I am learning famous works of art through the app "Anki". So I imported a deck for it online containing over 700 pieces.
Sadly the names of the pieces are in english and I would like... | [
"You can use dictionary comprehension with the replace method to update all the values (names of art pieces in this case) of the dictionary.\nart_dictionary = {\n \"Wassily Kandinsky\": \"Composition VIII\",\n \"Zhou Fang\": \"Ladies Wearing Flowers in Their Hair\",\n }\n \nart_dictionary = {key:value.replace... | [
2
] | [] | [] | [
"anki",
"dictionary",
"python",
"web_scraping"
] | stackoverflow_0074301695_anki_dictionary_python_web_scraping.txt |
Q:
ModuleNotFoundError: No module named 'setup_logger' with non root user
I have a module setup_logger.py with below contents:
import logging
import os
base_dir = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(format='[%(asctime)s]:[%(levelname)s]:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', file... | ModuleNotFoundError: No module named 'setup_logger' with non root user | I have a module setup_logger.py with below contents:
import logging
import os
base_dir = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(format='[%(asctime)s]:[%(levelname)s]:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename=os.path.join(base_dir, 'dummy.log'), filemode='w',level=logging.DEBUG)
... | [
"What you can do is making the file a pip package.\nFirst thing you have to do is put it in a folder called setup_logger wich is in a folder named src.\nThen in the top folder you can make a file called pyproject.toml with the following contents :\n[build-system]\nrequires = [\"setuptools>=61.0\"]\nbuild-backend = ... | [
0
] | [] | [] | [
"linux",
"python",
"python_3.x"
] | stackoverflow_0074301452_linux_python_python_3.x.txt |
Q:
How to check when was last time the User logged in?
I would like to update my model if the user did not logged in the day before .
@receiver(post_save, sender=user_logged_in)
def user_logged_in_streak(sender, instance, *args, **kwargs):
today: date = timezone.now().date()
class_completed = Cla... | How to check when was last time the User logged in? | I would like to update my model if the user did not logged in the day before .
@receiver(post_save, sender=user_logged_in)
def user_logged_in_streak(sender, instance, *args, **kwargs):
today: date = timezone.now().date()
class_completed = ClassAttempt.objects.filter(user=instance.user,
... | [
"Create a condition on the basis of instance.user.last_login and current timestamp - timedelta(1). Use python datetime.\n",
"This was the solution, instance will no work, pass request as an argument to get the user informations\n\n @receiver(user_logged_in, sender=User)\n def user_logged_in(sender, request,... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074275856_django_python.txt |
Q:
I get a 404 error when passing as a parameter to the path an int that is a foreign key
This is the url i am trying:
http://localhost:8000/blog/categoria/1/
The foreign key is categoria_id that comes from relationship many to many of Post and Categoria.
I am using Sqlite3.
This file is the models.py
from django.db ... | I get a 404 error when passing as a parameter to the path an int that is a foreign key | This is the url i am trying:
http://localhost:8000/blog/categoria/1/
The foreign key is categoria_id that comes from relationship many to many of Post and Categoria.
I am using Sqlite3.
This file is the models.py
from django.db import models
from django.contrib.auth.models import User
class Categoria(models.Model):
... | [
"I change the database to postgresql and I added a / before categoria in the file urls.py. For now it works. It’s strange, because I’ve made these changes before and it didn't work.\nDespite this I would appreciate any suggestion. Thank you.\nThis file is the urls.py after the change:\nfrom django.urls import path\... | [
0
] | [] | [] | [
"django",
"django_models",
"django_urls",
"django_views",
"python"
] | stackoverflow_0074294862_django_django_models_django_urls_django_views_python.txt |
Q:
Slicing a multi-index dataframe
I have a "pandas.MultiIndex.from_product" data-frame from which I want to slice some data.
For these slices I know the (multi-) index.
The known index does not necessarily exist in the data-frame, it might be lower for the start-index (b1) or higher for the end-index (b2), see code ... | Slicing a multi-index dataframe | I have a "pandas.MultiIndex.from_product" data-frame from which I want to slice some data.
For these slices I know the (multi-) index.
The known index does not necessarily exist in the data-frame, it might be lower for the start-index (b1) or higher for the end-index (b2), see code slice1.
Here is a minimal example of ... | [
"Answering my own question. I tried it way too complicated, this is the answer:\nslice2 = df.loc[(0,1):(2,0),:]\n\n",
"Even shorter:\nslice2 = df[(0,1):(2,0)]\n\n"
] | [
1,
1
] | [] | [] | [
"dataframe",
"multi_index",
"pandas",
"python",
"slice"
] | stackoverflow_0074301148_dataframe_multi_index_pandas_python_slice.txt |
Q:
python - Compare MIDI files
I want to compare two midi files in python, one file is original, and another is automatically generated.
Is there a function in python that will compare two audio files in MID format and return the percentage of similarity between the two?
Sorry for my bad english.
A:
Midi, can be op... | python - Compare MIDI files | I want to compare two midi files in python, one file is original, and another is automatically generated.
Is there a function in python that will compare two audio files in MID format and return the percentage of similarity between the two?
Sorry for my bad english.
| [
"Midi, can be opened as text, so\nfrom difflib import SequenceMatcher\n#get content of each midi file\nwith open(\"file1.midi\",'r') as f:\n content=f.read()\nwith open(\"file2.midi\",'r') as f2:\n content2=f2.read()\n#compare them with sequence matcher\nm = SequenceMatcher(None, content1, content2)\nprint(m.rati... | [
1
] | [] | [] | [
"audio",
"midi",
"python"
] | stackoverflow_0074301750_audio_midi_python.txt |
Q:
try: except: clauses not working with elif statements?
I am working through the Automate the Boring Stuff with Python course, and one of the lessons has me stumped, regarding the use of the try: and except: clauses.
When I run the code as described in the course below, using if/else statements it works, as the exc... | try: except: clauses not working with elif statements? | I am working through the Automate the Boring Stuff with Python course, and one of the lessons has me stumped, regarding the use of the try: and except: clauses.
When I run the code as described in the course below, using if/else statements it works, as the except clause is executed and python prints ' you did not enter... | [
"The thing that produces a ValueError is the conversion of the input to integer (int(numcats) and int(input())). In the first example, you do it inside of the try block in the second before try, hence the error is not caught.\nMove numcats=int(input()) inside the try block and this should work fine.\n",
"You need... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074301916_python.txt |
Q:
cpp vector erase by indices too slower than python
I want to delete items in vector by indices in cpp code. However it is too slow
cpp version
long remove_cnt = 0;
for (auto &remove_idx : remove_index) {
mylist.erase(mylist.begin() + (long) remove_idx - remove_cnt);
remove_cnt++;
}
python version
new_m... | cpp vector erase by indices too slower than python | I want to delete items in vector by indices in cpp code. However it is too slow
cpp version
long remove_cnt = 0;
for (auto &remove_idx : remove_index) {
mylist.erase(mylist.begin() + (long) remove_idx - remove_cnt);
remove_cnt++;
}
python version
new_mylist = [item for i, item in enumerate(mylist) if i not... | [
"Your question is a good example of why a 1-1 translation between languages usually doesn't work.\nTo efficiently erase items from a vector you don't do it by index.\nAssuming you got your indices in python by evaluating some condition (a predicate). You can directly use this predicate in C++.\nSay you want to remo... | [
3
] | [] | [] | [
"c++",
"python",
"stl",
"vector"
] | stackoverflow_0074301738_c++_python_stl_vector.txt |
Q:
Azure Functions App works with direct input url which under "Function App", but doesn't work with url under "Function", neither work with Code + Test
I am trying to extract data from Azure SQL with Azure Function.
I created a function with Python code using flask to fetch the data from database.
I have three route... | Azure Functions App works with direct input url which under "Function App", but doesn't work with url under "Function", neither work with Code + Test | I am trying to extract data from Azure SQL with Azure Function.
I created a function with Python code using flask to fetch the data from database.
I have three routes to request:
@app.route('/')
def root():
return 'root'
@app.route("/datatable", methods=['GET'])
def get_table():
out = ''
query = ''
try:
... | [
"I have used github sample azure function using fast Api. I have deployed in azure. I can be able to get the same response as you got.\n\nFunction response which contains api url\n\nAfter I changed the function.json file route has \"route\": \"{/api/*route}\" I can be able to see the results of Api URL.\n{\n\"scrip... | [
0
] | [] | [] | [
"api",
"azure",
"azure_functions",
"python"
] | stackoverflow_0073939490_api_azure_azure_functions_python.txt |
Q:
How to build PyQt6 app designed as MVC with pyinstaller?
I recently coded a program to extract subtitles from video and audio files. The interface is written with PyQt6 and I have problems with the compilation. I can't use fbs because I'm on Python 3.10. I get a TypeError 'bytes' object cannot be interpreted as an... | How to build PyQt6 app designed as MVC with pyinstaller? | I recently coded a program to extract subtitles from video and audio files. The interface is written with PyQt6 and I have problems with the compilation. I can't use fbs because I'm on Python 3.10. I get a TypeError 'bytes' object cannot be interpreted as an integer using pyinstaller traditionally but everything works ... | [
"Thanks everyone. Sorry, I finally found. I was using pyinstaller-3 while current version is pyinstaller-5. Everything is working fine now.\n"
] | [
0
] | [] | [] | [
"pyinstaller",
"pyqt",
"pyqt6",
"python"
] | stackoverflow_0074293946_pyinstaller_pyqt_pyqt6_python.txt |
Q:
Scrape allAmazon product names using selenium and python python
I am trying to scrape product names from https://www.amazon.com/Best-Sellers-Electronics-Televisions/zgbs/electronics/172659 this url, using selenium and python .
I used css selectors and xpath, Although there are 50 products in the page around 30 pro... | Scrape allAmazon product names using selenium and python python | I am trying to scrape product names from https://www.amazon.com/Best-Sellers-Electronics-Televisions/zgbs/electronics/172659 this url, using selenium and python .
I used css selectors and xpath, Although there are 50 products in the page around 30 product names are getting scraped after that I'm receiving the error,no ... | [
"I think its because the initial load has only the 30 products.\nThe other 20 are loaded only when the page is scrolled to the bottom.\ndriver.execute_script(\"window.scrollTo(0,Math.max(document.documentElement.scrollHeight,\" + \"document.body.scrollHeight,document.documentElement.clientHeight));\");\nitems = dri... | [
1
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074299101_python_selenium_web_scraping.txt |
Q:
Comparing Pandas Dataframe column with List
I am trying to compare a Pandas Dataframe with a List. I have extracted IDs to a list, called list_x;
Since I have several rows with the same ID, this is reflected on the list. i.e list_x = [1,1,1,1,2,3, etc.]
I am trying to drop all dataframe entries that have an ID tha... | Comparing Pandas Dataframe column with List | I am trying to compare a Pandas Dataframe with a List. I have extracted IDs to a list, called list_x;
Since I have several rows with the same ID, this is reflected on the list. i.e list_x = [1,1,1,1,2,3, etc.]
I am trying to drop all dataframe entries that have an ID that is also in the list
what I have been trying are... | [
"You want to get the dataframe without rows associated to IDs in list_x.\nSo you can go for this :\n# your df (2 columns : ID and value)\ndf = pd.DataFrame({'ID': [1,3,5,6,7], 'value' : ['red', 'blue', 'green', 'orange', 'purple']})\n\n# the list of IDs you don't want in your the dataframe\nlist_x = [1,1,2,3,5]\n\n... | [
1
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074301610_dataframe_list_pandas_python.txt |
Q:
How to define enum values that are functions?
I have a situation where I need to enforce and give the user the option of one of a number of select functions, to be passed in as an argument to another function:
I really want to achieve something like the following:
from enum import Enum
#Trivial Function 1
def fun... | How to define enum values that are functions? | I have a situation where I need to enforce and give the user the option of one of a number of select functions, to be passed in as an argument to another function:
I really want to achieve something like the following:
from enum import Enum
#Trivial Function 1
def functionA():
pass
#Trivial Function 2
def functio... | [
"Your assumption is wrong. Values can be arbitrary, they are not limited to integers. From the documentation:\n\nThe examples above use integers for enumeration values. Using integers\n is short and handy (and provided by default by the Functional API),\n but not strictly enforced. In the vast majority of use-cas... | [
48,
2,
2,
2,
0
] | [] | [] | [
"enums",
"function",
"python"
] | stackoverflow_0040338652_enums_function_python.txt |
Q:
Concatenate columns at the end of a MultiIndex columns DataFrame
Consider the following DataFrames df :
df =
kind A B
names u1 u2 u3 y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.8421 0.2670
... | Concatenate columns at the end of a MultiIndex columns DataFrame | Consider the following DataFrames df :
df =
kind A B
names u1 u2 u3 y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.8421 0.2670
0.2 0.1753 0.1013 0.5231 0.8060 0.0040
0.3 0.5953 0... | [
"Add parameter sort_remaining=False in DataFrame.sort_index:\ndf = pd.concat([df1, df2], axis=1).sort_index(level=\"kind\", axis=1, sort_remaining=False)\nprint (df)\nkind A B \nnames u1 u2 u3 potato y1 y2\nTime ... | [
3,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074301497_pandas_python.txt |
Q:
How to remove first or last few characters from a string?
I have only ever written a few lines and don´t really understand what I´m doing. So could any one please explain to me why this doesn´t work for "end = 0" and how could I make it work?
Thank you kindly :)
start = rs.GetInteger
end = rs.GetInteger
end = -end... | How to remove first or last few characters from a string? | I have only ever written a few lines and don´t really understand what I´m doing. So could any one please explain to me why this doesn´t work for "end = 0" and how could I make it work?
Thank you kindly :)
start = rs.GetInteger
end = rs.GetInteger
end = -end
objectIDs = rs.GetObjects("Pick some object")
for singleID i... | [
"-0 is 0. So, when you have\n123456789\nas input and 5 as start, 0 as end, then it will be the very first. So, you sliced the first 5 characters.\nWith 0 and 4, -4 means that except the last 4 four characters, so you get 12345.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074302025_python.txt |
Q:
function which purpose is to print lowercase symbols with some conditions
My task "For this challenge, define a function called quieter_please that takes in one string argument and checks if the string is all uppercase. If it is all upper case, convert the string to all lowercase and return this lowercased string.... | function which purpose is to print lowercase symbols with some conditions | My task "For this challenge, define a function called quieter_please that takes in one string argument and checks if the string is all uppercase. If it is all upper case, convert the string to all lowercase and return this lowercased string. If the argument string is not all uppercase, return this same string, unmodifi... | [
"You need to add () after islower and isupper functions it would be islower() and isupper()\nstr=\"Hello\"\ndef quieter_please(str):\n if str.islower()==False and str.isupper()==False:\n c=str\n return c\n elif str.islower()==True and str.isupper()==False:\n b=str\n return b \n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074302057_python.txt |
Q:
How can I access Github user ID from Python having only email or name?
I need to get Github user ids by their names or emails. How can I do that?
Thanks :)
I was trying to use pygithub but that doesnt seem to help much.
A:
Try using the Github user search API
https://api.github.com/search/users?q=EnterEmailHere
... | How can I access Github user ID from Python having only email or name? | I need to get Github user ids by their names or emails. How can I do that?
Thanks :)
I was trying to use pygithub but that doesnt seem to help much.
| [
"Try using the Github user search API\nhttps://api.github.com/search/users?q=EnterEmailHere\n"
] | [
0
] | [] | [] | [
"github",
"python"
] | stackoverflow_0074301230_github_python.txt |
Q:
How to space overlapping annotations
I want to annotate the bars in a graph with some text but if the bars are close together and have comparable height, the annotations are above ea. other and thus hard to read (the coordinates for the annotations were taken from the bar position and height).
Is there a way to sh... | How to space overlapping annotations | I want to annotate the bars in a graph with some text but if the bars are close together and have comparable height, the annotations are above ea. other and thus hard to read (the coordinates for the annotations were taken from the bar position and height).
Is there a way to shift one of them if there is a collision?
E... | [
"I've written a quick solution, which checks each annotation position against default bounding boxes for all the other annotations. If there is a collision it changes its position to the next available collision free place. It also puts in nice arrows.\nFor a fairly extreme example, it will produce this (none of th... | [
57,
12,
9,
1
] | [] | [] | [
"matplotlib",
"plot_annotations",
"python"
] | stackoverflow_0008850142_matplotlib_plot_annotations_python.txt |
Q:
Multiple period persistence, vectorization, time series python
I have a DataFrame with daily values and I am building out a forecast using various methods predicting the values for the next two weeks.
As a base, naive, forecast I want to simply say the value today is the best forcast for the next two weeks e.g.:
... | Multiple period persistence, vectorization, time series python | I have a DataFrame with daily values and I am building out a forecast using various methods predicting the values for the next two weeks.
As a base, naive, forecast I want to simply say the value today is the best forcast for the next two weeks e.g.:
the value on 01-Jan-2012 is 100, then I would like the forecast for ... | [
"General principles\nHere my shot at it.\nI use a function that does almost that: np.lib.stride_tricks.sliding_window.\nExcept that it shows forward values, when what you want to do is backward values (at t, you want to see value at t-1 as \"prediction J+1\", value at t-2 as \"prediction J+2\", etc. And more genera... | [
3,
0,
0
] | [] | [] | [
"apply",
"numpy",
"pandas",
"python",
"time_series"
] | stackoverflow_0074172129_apply_numpy_pandas_python_time_series.txt |
Q:
Is there a function in google.colab module to close the runtime
Sometimes when I give run in google.colab I cant stay infront of the computer to manually disconnect from the server when the run is complete and the connection stays on even when my run is complete occupying the node for no reason.
Is there a functio... | Is there a function in google.colab module to close the runtime | Sometimes when I give run in google.colab I cant stay infront of the computer to manually disconnect from the server when the run is complete and the connection stays on even when my run is complete occupying the node for no reason.
Is there a function in google.colab so that say I can insert the function to close the ... | [
"quit() and exit() are not executed in google colab (18 Aug 2019). Just type the following:\n!kill -9 -1\n\n",
"import sys\nsys.exit()\n\nThis will end the runtime, freeing up the GPU.\nEDIT: Apparently my last answer doesn't work any more.\nThe thing to do now is !kill -9 -1.\n",
"Since September 2022, it is n... | [
6,
3,
2
] | [] | [] | [
"google_colaboratory",
"python",
"pytorch"
] | stackoverflow_0050541851_google_colaboratory_python_pytorch.txt |
Q:
Connection denied with flask_socketio when using CORS on client side
I want to connect from a client to a server using websockets (both on my machine, localhost). I have this simple client side code using flask and I use flask_cors to allow for the client to get data from any domain.
from flask import Flask
from f... | Connection denied with flask_socketio when using CORS on client side | I want to connect from a client to a server using websockets (both on my machine, localhost). I have this simple client side code using flask and I use flask_cors to allow for the client to get data from any domain.
from flask import Flask
from flask import render_template
from flask_cors import CORS
app = Flask(__nam... | [
"Flask-CORS is an extension that works on Flask routes. This extension has no knowledge of Socket.IO.\nFlask-SocketIO provides its own CORS configuration options. In your case, you should initialize your SocketIO object as follows:\nsocketio = SocketIO(app, cors_allowed_origins='http://localhost:8080')\n\n"
] | [
0
] | [] | [] | [
"cors",
"flask_socketio",
"javascript",
"python",
"socket.io"
] | stackoverflow_0074296460_cors_flask_socketio_javascript_python_socket.io.txt |
Q:
Sklearn Mean Absolute Error with X and Y From Rows
I tried to do Mean Absolute Error from Sklearn with this dataset
Name
Jan Qty
Feb Qty
Mar Qty
Jan Fcst
Feb Fcst
Mar Fcst
Banana
10
5
23
7
4
24
Apple
5
3
32
8
7
17
I want to create New Column named MAE with sklearn.metrics.mean_absolute_error in it with
y_true ... | Sklearn Mean Absolute Error with X and Y From Rows | I tried to do Mean Absolute Error from Sklearn with this dataset
Name
Jan Qty
Feb Qty
Mar Qty
Jan Fcst
Feb Fcst
Mar Fcst
Banana
10
5
23
7
4
24
Apple
5
3
32
8
7
17
I want to create New Column named MAE with sklearn.metrics.mean_absolute_error in it with
y_true = Jan Qty, Feb Qty, and Mar Qty
y_pred = Jan F... | [
"Try:\ndf.apply(lambda x: mean_absolute_error(x.filter(regex='Qty'), x.filter(regex='Fcst')), axis=1)\n\nResult:\n0 1.666667\n1 7.333333\ndtype: float64\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"scikit_learn",
"statistics"
] | stackoverflow_0074302207_pandas_python_scikit_learn_statistics.txt |
Q:
How to find who's Next Birthdate given CSV file of Names and Birthdays?
We are given a CSV file containing names and birthdays, we have to output who's birthday is next in function.
kept getting a local unbound error, not sure how to fix it, basically trying to read the file, check the dates, find which date is ne... | How to find who's Next Birthdate given CSV file of Names and Birthdays? | We are given a CSV file containing names and birthdays, we have to output who's birthday is next in function.
kept getting a local unbound error, not sure how to fix it, basically trying to read the file, check the dates, find which date is next, then return the name connected with that date
birthdates.csv:
Draven Broc... | [
"Welcome to stack overflow.\nThe way to do this is\n\nRead in your CSV data\n\nConvert the data to e.g. a pandas DataFrame\n2a. I suggest you convert the dates to e.g. pd.Timestamp and not keep them as strings to avoid bad things happening when comparing\n\nSort the DataFrame based on dates, or find the row with th... | [
0,
0
] | [] | [] | [
"csv",
"dictionary",
"list",
"python"
] | stackoverflow_0074301677_csv_dictionary_list_python.txt |
Q:
Import Error partially initialized from imported file
i dont know how i can call function from the file who import.
toolkit.py:
from utilities import bcolors, utility
from backups import backups
import os
version = "1.0"
utility.UpdateNeeded()
class main():
def main():
print( bcolors.BOLD + "Toolkit"... | Import Error partially initialized from imported file | i dont know how i can call function from the file who import.
toolkit.py:
from utilities import bcolors, utility
from backups import backups
import os
version = "1.0"
utility.UpdateNeeded()
class main():
def main():
print( bcolors.BOLD + "Toolkit" + bcolors.ENDC)
print("")
choose = int(in... | [
"In toolkit.py you are trying to import something from backups.py, but in backups.py you are trying to import something from toolkit.py. Python can't import the one without the other so it goes into a loop, detects it and gives you this error. You need to separate the two components so that they are not dependent o... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074302118_python_python_3.x.txt |
Q:
Python Permutations unexpected behavior?
Given the sample below:
from itertools import permutations
p=permutations("abc", 2)
def func():
for i in p:
print("values=", i)
print("First use case:")
func()
print("Second use case:")
func()
print("The End!")
Output:
First use case:
values= ('a', '... | Python Permutations unexpected behavior? | Given the sample below:
from itertools import permutations
p=permutations("abc", 2)
def func():
for i in p:
print("values=", i)
print("First use case:")
func()
print("Second use case:")
func()
print("The End!")
Output:
First use case:
values= ('a', 'b')
values= ('a', 'c')
values= ('b', 'a')
valu... | [
"p is and iterator which means once you finish iterating through it there are no more elements in it. You will have to regenerate the iterator.\nLike:\ndef func():\n p=permutations(\"abc\", 2)\n for i in p:\n print(\"values=\", i)\n\nIf you have situation where the iterator is generated randomly and you want... | [
1
] | [] | [] | [
"permutation",
"python"
] | stackoverflow_0074302277_permutation_python.txt |
Q:
How to upload a numpy.ndarray image into Azure Storage Blob
I would like to upload an image numpy.ndarray data into Azure Storage Blob. I am using the BlobServiceClient. But I cannot find a way for upload_blob to accept a numpy.ndarray. How can I upload it?
blob_client = blob_service_client.get_blob_client(
... | How to upload a numpy.ndarray image into Azure Storage Blob | I would like to upload an image numpy.ndarray data into Azure Storage Blob. I am using the BlobServiceClient. But I cannot find a way for upload_blob to accept a numpy.ndarray. How can I upload it?
blob_client = blob_service_client.get_blob_client(
container=CONTAINER, blob=filename)
blob_client.upl... | [
"You should encode your np.ndarray into bytes first.\nimport numpy as np\nfrom azure.storage.blob import BlockBlobService\nfrom PIL import Image\naccount_name = '<your account name>'\naccount_key = '<your account key>'\ncontainer_name = '<your container name>'\nblob_name = 'image.jpg' # my test image name\nimg: np... | [
1
] | [] | [] | [
"azure_blob_storage",
"azure_functions",
"numpy_ndarray",
"python"
] | stackoverflow_0073714036_azure_blob_storage_azure_functions_numpy_ndarray_python.txt |
Q:
convert list to lowercase in python
I have a list in python, which contains alphanumeric elements. I would like to convert all elements to lowercase.
Is it the only way to create a Dataframe using the list and use the lower function?
Here is the example:
l = ['abc123']
l.lower()
Error:
AttributeError: 'list' obje... | convert list to lowercase in python | I have a list in python, which contains alphanumeric elements. I would like to convert all elements to lowercase.
Is it the only way to create a Dataframe using the list and use the lower function?
Here is the example:
l = ['abc123']
l.lower()
Error:
AttributeError: 'list' object has not attribute 'lower'
| [
"You have one string element in a list. List doesn't understand string functions. You need to call .lower() on string.\nThere are several solutions. Use which is best for your use case.\nl = ['ABC123']\n\n[s.lower() for s in l] # ['abc123']\n\nlist(map(str.lower, l)) # ['abc123']\n\nl[0].lower() # 'abc1... | [
1,
0,
0
] | [
"l = [char.lower() for char in l ]\nprint(l)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074301583_python.txt |
Q:
how to set dictionary if select key is repeats with python?
I'm using python 3 and I have a dictionary containing some scheduler data. Now I want to set that if a day name repeats in the data list.
here is the case and code :
data = [
{'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, ... | how to set dictionary if select key is repeats with python? | I'm using python 3 and I have a dictionary containing some scheduler data. Now I want to set that if a day name repeats in the data list.
here is the case and code :
data = [
{'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Tuesday', 'full_day': True, 'cl... | [
"You can use a dictionary with day as the key for this (using dictionary comprehension):\ndata = list({d['day']: d for d in data}.values())\n\nThis will keep only the last occurrence of each day.\nThe above is equivalent to:\n'''\ndata_dict will be:\n{\n 'Monday': {'day': 'Monday', 'full_day': True, 'close_day': ... | [
2,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074301968_python_python_3.x.txt |
Q:
ModuleNotFoundError: No module named 'word2number' Error
While installed 'word2number' using command
from word2number import w2n
I am getting this error while using Google Colab:
ModuleNotFoundError: No module named 'word2number' Error
May I know how do I solve the error?
A:
You probably need to run
!pip insta... | ModuleNotFoundError: No module named 'word2number' Error | While installed 'word2number' using command
from word2number import w2n
I am getting this error while using Google Colab:
ModuleNotFoundError: No module named 'word2number' Error
May I know how do I solve the error?
| [
"You probably need to run\n!pip install word2number\n\nto install the library to Google colab. import statements don't install libraries, they load libraries that are already installed (a lot of libraries come pre installed).\n",
"While trying to install word2number same error is coming\n!pip install word2number\... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0073432779_python.txt |
Q:
Python Pandas Replace multiple values in one column with dict
I have the below df as an example
Product Code
Product Type
Price
01478
ELC
£119.00
01479
GRN
£159.00
01514
PWR
£100.00
01617
ELC
£119.00
01819
ELC - GRN - PWR
£300.00
01819
ELC - GRN - PWR
£300.00
I am trying to change multiple values in the 'P... | Python Pandas Replace multiple values in one column with dict | I have the below df as an example
Product Code
Product Type
Price
01478
ELC
£119.00
01479
GRN
£159.00
01514
PWR
£100.00
01617
ELC
£119.00
01819
ELC - GRN - PWR
£300.00
01819
ELC - GRN - PWR
£300.00
I am trying to change multiple values in the 'Product Type' column using a dict
This is my code:
df[... | [
"you can use regex inside df.Series.replace (without str):\ndf['Product Type'] = df['Product Type'].replace(dict, regex=True)\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"multivalue",
"pandas",
"python",
"replace"
] | stackoverflow_0074302179_dataframe_multivalue_pandas_python_replace.txt |
Q:
Creating csv from json data
I have a json file from a twitter api that has tweet.fields as well as user.fields but the tweet and the user data are linked using author_id in json equivalent of foriegn key relations. I need to display the username, name, and id along with the rest of tweet details in the same csv ta... | Creating csv from json data | I have a json file from a twitter api that has tweet.fields as well as user.fields but the tweet and the user data are linked using author_id in json equivalent of foriegn key relations. I need to display the username, name, and id along with the rest of tweet details in the same csv table.
"data": [
{
... | [
"https://datatofish.com/json-string-to-csv-python/\nTry to walk through it step-by-step.\nGood luck :)\n"
] | [
0
] | [] | [] | [
"csv",
"json",
"python",
"twitter"
] | stackoverflow_0074302278_csv_json_python_twitter.txt |
Q:
APScheduler Get next_run_time
I am looking to get the next_run_time of a scheduled job but I receive an AttributeError when on that. How do I properly access it:
sched.add_job(myFunc, 'cron', minute='*', start_date=datetime(2023,1,1), end_date=datetime(2023,1,3))
for job in sched.get_jobs():
print(job.next_run... | APScheduler Get next_run_time | I am looking to get the next_run_time of a scheduled job but I receive an AttributeError when on that. How do I properly access it:
sched.add_job(myFunc, 'cron', minute='*', start_date=datetime(2023,1,1), end_date=datetime(2023,1,3))
for job in sched.get_jobs():
print(job.next_run_time)
sched.start()
Am I accessin... | [
"You need to call sched.start() first before job.next_run_time\n"
] | [
1
] | [] | [] | [
"apscheduler",
"python"
] | stackoverflow_0074295164_apscheduler_python.txt |
Q:
Get dataframe cell value based on substring
I am trying to search for a substring across my dataframe (no specific column) and get in return the value of the cell.
For example:
Column A
Column B
Red apple
carrots
Blue Car
Banana
I’d like to search the cell which contains “Apple” and i should get in return “Red... | Get dataframe cell value based on substring | I am trying to search for a substring across my dataframe (no specific column) and get in return the value of the cell.
For example:
Column A
Column B
Red apple
carrots
Blue Car
Banana
I’d like to search the cell which contains “Apple” and i should get in return “Red apple”.
i have been successful returni... | [
"One option is to stack and use boolean indexing:\ns = df.stack()\n\nout = s[s.str.contains('apple')]\n\noutput:\n0 Column A Red apple\ndtype: object\n\nIf you expect a single match:\nout = s[s.str.contains('apple')].squeeze()\n\noutput: 'Red apple'\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302460_dataframe_pandas_python.txt |
Q:
Delete entire dataframe rows based on condition and stack remaining rows
I have the following dataframe:
Date Name Grade Hobby
01/01/2005 Albert 4 Drawing
08/04/1996 Martha 6 Horseback riding
03/03/2003 Jack 5 Singing
07/01/2001 Millie 5 ... | Delete entire dataframe rows based on condition and stack remaining rows | I have the following dataframe:
Date Name Grade Hobby
01/01/2005 Albert 4 Drawing
08/04/1996 Martha 6 Horseback riding
03/03/2003 Jack 5 Singing
07/01/2001 Millie 5 Netflix
24/09/2000 Julie 7 Sleeping
...
I want to f... | [
"Think this should do the job\ndf['Date'] = pd.to_datetime(df['Date'], dayfirst=True)\n\ndf_new = df[df['Date'].duplicated(keep=False)].sort_values('Date')\n\n",
"Convert Date to datetimes by to_datetime, then filter rows in boolean indexing and last sorting by DataFrame.sort_values:\ndf['Date'] = pd.to_datetime(... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302487_dataframe_pandas_python.txt |
Q:
ImportError: No module named crispy-forms
I'm working on some django apps, pretty noob still. Would like to use crispy-forms, but eclipse and django doesnt recognize it.
Trying to runserver or shell:
$ python manage.py runserver
this happens:
Traceback (most recent call last):
File "manage.py", line 10, in <mod... | ImportError: No module named crispy-forms | I'm working on some django apps, pretty noob still. Would like to use crispy-forms, but eclipse and django doesnt recognize it.
Trying to runserver or shell:
$ python manage.py runserver
this happens:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
... | [
"I solved this problem right now, I realized that the crispy-form installed version was the python 2.7 version, but I'm using Django-1.10 with Python 3.5, and I think this is your problem too.\nTry: pip3 install --user django-crispy-forms\n",
"You have to make sure that you install crispy-forms into the virtualen... | [
30,
19,
12,
6,
3,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0
] | [
"I had this same error and all I had to do was runserver using\npython3 manage.py runserver. I'm not sure how it works but I think some modules need you to explicitly call python3 and not just the alias.\n"
] | [
-1
] | [
"django",
"django_crispy_forms",
"python"
] | stackoverflow_0028560968_django_django_crispy_forms_python.txt |
Q:
"end" parameter in "print" function not working in python
I'm wondering why end =" " is not working here. Could you help me?
import sys
num1 = int(input())
num2 = int(input())
sum_even_pos = 0
sum_odd_pos = 0
for n in range (num1, num2 + 1):
n = str(n)
for i in range(0, 6):
if i % 2 == 0:
... | "end" parameter in "print" function not working in python | I'm wondering why end =" " is not working here. Could you help me?
import sys
num1 = int(input())
num2 = int(input())
sum_even_pos = 0
sum_odd_pos = 0
for n in range (num1, num2 + 1):
n = str(n)
for i in range(0, 6):
if i % 2 == 0:
sum_odd_pos = int(n[0]) + int(n[2]) + int(n[4])
els... | [
"A blank print() statement (last line) would bring a newline anyway\n"
] | [
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074302537_loops_python.txt |
Q:
Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1129)'))
I am using requests python library to access an internal api -
x1 = requests.post(url, json = data, headers = headers)
But got this error message -
HTTPSConnectionPo... | Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1129)')) | I am using requests python library to access an internal api -
x1 = requests.post(url, json = data, headers = headers)
But got this error message -
HTTPSConnectionPool(host='url', port=443): Max retries exceeded with url: '' (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate ... | [
"I found the solution later.\nI just edited the host entry in the server for the url to make the post request.\nYou can edit your host file at server/system -\nvi /etc/hosts \n\nThere I added, eg -\nIP Url\n0.0.0.0 google.com \n1.1.1.1 abc.com\n\nThis solves my error.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_requests",
"python_requests_html"
] | stackoverflow_0074299580_python_python_3.x_python_requests_python_requests_html.txt |
Q:
How can i update my website when i post a message in my discord server?
How can i update my website when i post a message in my discord server? I would like to know how to collect the messages in javascript because im using discord.py so its difficult
Havent tried anyything yet
A:
You could use an api managed by... | How can i update my website when i post a message in my discord server? | How can i update my website when i post a message in my discord server? I would like to know how to collect the messages in javascript because im using discord.py so its difficult
Havent tried anyything yet
| [
"You could use an api managed by the discord.py code that updates the data on each message send and access it in js on the client side?\nPython api:\nhttps://www.dataquest.io/blog/python-api-tutorial/\nJs accessing the api:\nhttps://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\nDiscord.js which mi... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074302547_discord_discord.py_python.txt |
Q:
Scrape a webpage and save as static page
I am trying to save the static version of a loaded webpage contents.
So, for doing that I am using kora.selenium in Colab. The code is,
#!pip install kora
from kora.selenium import wd
wd.get("https://www.cnbc.com/2022/01/03/5-ways-to-reset-your-retirement-savings-and-save-m... | Scrape a webpage and save as static page | I am trying to save the static version of a loaded webpage contents.
So, for doing that I am using kora.selenium in Colab. The code is,
#!pip install kora
from kora.selenium import wd
wd.get("https://www.cnbc.com/2022/01/03/5-ways-to-reset-your-retirement-savings-and-save-more-money-in-2022.html")
page_source = wd.page... | [
"Please see https://pypi.org/project/pywebcopy/\nIt uses lxml to parse the elements and requests to fetch the content. You can do the same with BeautifulSoup (Which has lxml as one of its parsers) but it is a lot of job to check for all meta contents and download it.\nYour example downloads 17MB into /dist/cnbc-cop... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x",
"selenium",
"web_scraping"
] | stackoverflow_0074299375_beautifulsoup_python_python_3.x_selenium_web_scraping.txt |
Q:
How to generate exponentially increasing range in Python
I want to test the performance of some code using an exponentially increasing value. So that as an extra digit is added to the numbers_size the increment is multiplied by 10. This is how I'm doing it so far but it looks a bit hacky. Suggestions for improv... | How to generate exponentially increasing range in Python | I want to test the performance of some code using an exponentially increasing value. So that as an extra digit is added to the numbers_size the increment is multiplied by 10. This is how I'm doing it so far but it looks a bit hacky. Suggestions for improvements without introducing non-standard libraries?
numbers_siz... | [
"If you consider numpy as one of the standards ;), you may use numpy.logspace since that is what it is supposed to do.... (note: 100=10^2, 1000000000=10^9)\nfor n in numpy.logspace(2,9,num=9-2, endpoint=False):\n test(n)\n\nexample 2 (note: 100=10^2, 1000000000=10^9, want to go at a step 10x, it is 9-2+1 points... | [
23,
17,
14,
5,
5,
1,
0,
0
] | [
"example of 'NOT reading the question properly' and 'NOT how to do it'\nfor i in xrange(100, 1000000000, 100):\n # timer\n test(i)\n # whatever\n\nIs about as simple as it gets... adjust xrange accordingly\n"
] | [
-2
] | [
"python"
] | stackoverflow_0011443737_python.txt |
Q:
Is there a way to pass a string which contain muliple delimiter in Django?
Info: I want to make a queryset where i have pass a string. A string contain multiple delimiter , like a separator. I just want to know it is possible to pass a string with muliple delimiter and filter out the video which are match with the... | Is there a way to pass a string which contain muliple delimiter in Django? | Info: I want to make a queryset where i have pass a string. A string contain multiple delimiter , like a separator. I just want to know it is possible to pass a string with muliple delimiter and filter out the video which are match with the strings?
def videosfilter(request):
''' videos filter '''
videos = Vid... | [
"You can use reduce an operator:\nfrom functools import reduce\nimport operator\nfrom django.db.models import Q\n....\n\ndef videosfilter(request): \n my_string = 'python programming,django framework'\n custom_filter = reduce(operator.or_, (Q(title__icontains=x) for x in my_string.split(,)))\n videos = ... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074302558_django_django_models_python.txt |
Q:
Delete repeated vowels in string
Here is my code:
def del_rep_vow(s):
'''
>>> del_rep_vow('adaptation')
'adpttion'
>>> del_rep_vow('repetitions')
'reptitons'
>>> del_rep_vow('kingkong')
'kingkong'
>>> del_rep_vow('aeiouaeiou')
'aeiou'
'''
final_list = []
for i in s:
... | Delete repeated vowels in string | Here is my code:
def del_rep_vow(s):
'''
>>> del_rep_vow('adaptation')
'adpttion'
>>> del_rep_vow('repetitions')
'reptitons'
>>> del_rep_vow('kingkong')
'kingkong'
>>> del_rep_vow('aeiouaeiou')
'aeiou'
'''
final_list = []
for i in s:
if i not in final_list:
... | [
"You should maintain a Python set of vowel characters already seen. For each new encountered letter as you walk down the string, only append a vowel if it is not in the set.\ndef del_rep_vow(s):\n vowels_seen = set()\n final_list = []\n for i in s:\n if i in ['a', 'e', 'i', 'o', 'u']:\n ... | [
3,
2,
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074296722_python_python_3.x.txt |
Q:
Why does my list have extra double brackets?
arr_list = []
arr = ['5', '6', '2', '4', '+']
arr_list.append([''.join(arr[0:4])])
print(arr_list)
Ouput: [['5624']]
Why does the output have 2 sets of square brackets? I only want one.
Thanks in advnace.
A:
arr_list = []
arr = ['5', '6', '2', '4', '+']
arr_list.app... | Why does my list have extra double brackets? | arr_list = []
arr = ['5', '6', '2', '4', '+']
arr_list.append([''.join(arr[0:4])])
print(arr_list)
Ouput: [['5624']]
Why does the output have 2 sets of square brackets? I only want one.
Thanks in advnace.
| [
"arr_list = []\narr = ['5', '6', '2', '4', '+']\narr_list.append(''.join(arr[0:4]))\nprint(arr_list)\n\nsimply remove the brackets from the third row\n",
"Use:\narr_list.append(''.join(arr[0:4]))\n\n",
"You're appending a list to arr_list.\nUse this instead:\narr_list.append(''.join(arr[0:4]))\n\n",
"Remove t... | [
2,
0,
0,
0,
0
] | [] | [] | [
"append",
"arrays",
"join",
"list",
"python"
] | stackoverflow_0074302569_append_arrays_join_list_python.txt |
Q:
How to convert back a ragged tensor with nested ragged dimension that was previously converted into a standard tensor
RaggedTensor has methods to_tensor() and from_tensor(). However it seems that applying tf.RaggedTensor.from_tensor(ragged_tensor.to_tensor(), padding=0) fails if ragged_tensor has nested dimensions... | How to convert back a ragged tensor with nested ragged dimension that was previously converted into a standard tensor | RaggedTensor has methods to_tensor() and from_tensor(). However it seems that applying tf.RaggedTensor.from_tensor(ragged_tensor.to_tensor(), padding=0) fails if ragged_tensor has nested dimensions
Example:
data = tf.ragged.constant([
[[4,35,6,33], [7,2], [89,56,12]],
[[2,11], [9]]
])
tf.RaggedTensor.from_... | [
"I may have found an answer myself. Posting in case is useful to someone:\nInstead of using the padding parameter, pass the nested row lengths of the original tensor\ntf.RaggedTensor.from_tensor(data.to_tensor(), lengths=data.nested_row_lengths())\n\ndata = tf.ragged.constant([\n [[4,35,6,33], [7,2], [89,56,12]]... | [
1
] | [] | [] | [
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0074295538_python_tensorflow_tensorflow2.0.txt |
Q:
Run External Python script outside the Django project through html button
I am trying to run python script through html button but I am getting the following error. I don't know why. kindly help to get rid off it. The error is:
module 'sys' has no attribute 'execute'
views.py:
from subprocess import run, PIPE
from... | Run External Python script outside the Django project through html button | I am trying to run python script through html button but I am getting the following error. I don't know why. kindly help to get rid off it. The error is:
module 'sys' has no attribute 'execute'
views.py:
from subprocess import run, PIPE
from django.shortcuts import render
import requests
import sys
def external(request... | [
"Try to use subprocess library like\nimport subprocess\nsubprocess.run([\"ls\", \"-l\", \"/dev/null\"], capture_output=True)\n\n"
] | [
0
] | [] | [] | [
"django",
"html",
"javascript",
"python"
] | stackoverflow_0074301619_django_html_javascript_python.txt |
Q:
fig-width has no effect in a quarto document
Consider the following code:
---
title: "Untitled"
format: pdf
---
```{python}
#| echo: false
#| fig-align: center
#| fig-width: 1cm
import matplotlib.pyplot as plt
x = [1, 2]
y = [2, 3]
plt.plot(x,y)
```
The parameter fig-width has no effect whatever the chosen wi... | fig-width has no effect in a quarto document | Consider the following code:
---
title: "Untitled"
format: pdf
---
```{python}
#| echo: false
#| fig-align: center
#| fig-width: 1cm
import matplotlib.pyplot as plt
x = [1, 2]
y = [2, 3]
plt.plot(x,y)
```
The parameter fig-width has no effect whatever the chosen width.
Could someone please help me?
| [
"Edit\nYou can also use set_figwidth from matplotlib to control the plot figure sizes generated by matplotlib.\n---\ntitle: \"Untitled\"\nformat: pdf\nengine: jupyter\n---\n\n```{python}\n#| echo: false\n#| fig-align: center\n\nimport matplotlib.pyplot as plt\n\nplot = plt.figure()\nplot.set_figwidth(2)\nplot.set_f... | [
1
] | [] | [] | [
"python",
"quarto"
] | stackoverflow_0074302660_python_quarto.txt |
Q:
dataframe index: 'int' object is not subscriptable error
I am trying to calculate the difference between two index values for a dataframe (number of days between first and last index values in dataframe).
I have the following error (below). I was wondering if there is a workaround for this (it seems the below code... | dataframe index: 'int' object is not subscriptable error | I am trying to calculate the difference between two index values for a dataframe (number of days between first and last index values in dataframe).
I have the following error (below). I was wondering if there is a workaround for this (it seems the below code was working OK for a small dataframe..)? Thanks
type(data1.in... | [
"Use only Timedelta.days, because subtract scalars to scalar Timedelta:\nout = (d1-d3).days\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302801_dataframe_pandas_python.txt |
Q:
Checking a large list of permutations. Any advice to get it to run faster?
I have about 95,000,000 permutations to check.
I have 8 lists of varying length, each string identifies properties (a-k) defined in an excel sheet.
e.g
bcdgj
has properties b, c, d, g and j
I need to find just one permutation that contains... | Checking a large list of permutations. Any advice to get it to run faster? | I have about 95,000,000 permutations to check.
I have 8 lists of varying length, each string identifies properties (a-k) defined in an excel sheet.
e.g
bcdgj
has properties b, c, d, g and j
I need to find just one permutation that contains at least 3 of every property and then match those properties to the data in the... | [
"Python is not designed to write computationally-intensive pure-Python codes. It is meant to be used as glue code. The intensive part should be vectorized, that is, optimized in compiled native languages like C. This is especially true with the default implementation of CPython which is an interpreter. Any call to ... | [
1,
0
] | [] | [] | [
"bigdata",
"optimization",
"permutation",
"python"
] | stackoverflow_0074300536_bigdata_optimization_permutation_python.txt |
Q:
Why are values from a dict not being returned even if keys are present when passing a function as default?
I'm a bit puzzled by the following behaviour. I am retrieving values from a dict such that if a key does not exist I call a function which creates the value and inserts it into the dict. I do this through the... | Why are values from a dict not being returned even if keys are present when passing a function as default? | I'm a bit puzzled by the following behaviour. I am retrieving values from a dict such that if a key does not exist I call a function which creates the value and inserts it into the dict. I do this through the default parameter of the dictionary.get method. The problem is that the default function keeps being called EVE... | [
"In the given example, I would expect the dictionary to return the value world WITHOUT calling the load_default function.\nWhen executing dictionary.get(\"hello\", load_default(\"hello\")) Python evaluates the expressions passed to .get() method as parameter first and then calls the method with values obtained from... | [
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074302654_dictionary_python.txt |
Q:
invoking AWS lambda python function from an existing lambda function gives error
can anyone help me to troubleshoot below error while invoking child lambda function from parent function in same region. I have referred online for this received error 'Database' object is not callable and no help found related to thi... | invoking AWS lambda python function from an existing lambda function gives error | can anyone help me to troubleshoot below error while invoking child lambda function from parent function in same region. I have referred online for this received error 'Database' object is not callable and no help found related to this error.
import certifi
import os, sys
from pymongo import MongoClient
... | [
"The issue is that you accidentally have two client objects:\nclient = boto3.client('lambda')\n...\nclient = MongoClient(\"mongodb+...\", tlsCAFile=ca)\n\nThe latter replaces the former, so when you subsequently make a call to the AWS Lambda SDK via client, that object is of type Database rather than being an actua... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python",
"python_3.x"
] | stackoverflow_0074301443_amazon_web_services_aws_lambda_python_python_3.x.txt |
Q:
How to apply a function in a pairwise fashion in python with one argument and a list of arguments
What is the best and fastest way to apply a function in python when:
A function takes two arguments
Argument #1 is a predefined value
Argument #2 is a list of values
I need to apply the function with Argument #1 and ... | How to apply a function in a pairwise fashion in python with one argument and a list of arguments | What is the best and fastest way to apply a function in python when:
A function takes two arguments
Argument #1 is a predefined value
Argument #2 is a list of values
I need to apply the function with Argument #1 and every element from Argument #2 list
I can do something like this:
result = []
for argument_from_list i... | [
"As a list comprehension:\nresult = [my_func(predefined_value, argument_from_list) for argument_from_list in arguments_list]\n\nIf you want to use map, it takes a function that takes a single argument, so either you'll have to get a function that takes a single argument.\nUsing map and lambda:\nresult = list(map(la... | [
2
] | [] | [] | [
"list_comprehension",
"python",
"python_3.x"
] | stackoverflow_0074302733_list_comprehension_python_python_3.x.txt |
Q:
uplad file to google drive with progress bar with python requests
This is my code for uploading to google drive with python requests using google-drive-api.
import sys
import json
import requests
from tqdm import tqdm
import requests_toolbelt
from requests.exceptions import JSONDecodeError
class ProgressBar(tqdm)... | uplad file to google drive with progress bar with python requests | This is my code for uploading to google drive with python requests using google-drive-api.
import sys
import json
import requests
from tqdm import tqdm
import requests_toolbelt
from requests.exceptions import JSONDecodeError
class ProgressBar(tqdm):
def update_to(self, n: int) -> None:
self.update(n - self... | [
"When I saw your script, I thought that the content type is not included in the request header. In this case, I think that the request body is directly shown in the uploaded file. I thought that this might be the reason for your current issue. In order to remove this issue, how about the following modification?\nFr... | [
2,
0
] | [] | [] | [
"google_drive_api",
"python",
"python_3.x",
"python_requests"
] | stackoverflow_0074300051_google_drive_api_python_python_3.x_python_requests.txt |
Q:
How to correctly write @vectorize decorator's signatures with numba
I want to add a decorator to the function which requires 7 arguments such as:
n = 1000000
greyscales = np.floor(np.random.uniform(0, 255, n).astype(np.float32))
weights = np.random.normal(.5, .1, n).astype(np.float32)
exp
@vectorize('float32(... | How to correctly write @vectorize decorator's signatures with numba | I want to add a decorator to the function which requires 7 arguments such as:
n = 1000000
greyscales = np.floor(np.random.uniform(0, 255, n).astype(np.float32))
weights = np.random.normal(.5, .1, n).astype(np.float32)
exp
@vectorize('float32(float32)', target = 'cuda')
def normalize(greyscales):
return greysc... | [
"As Rutger Kassies has also said, there does not seem to be a good reason why the create_hidden_layer function has to take the other functions as an input. So you can simply remove that part to make it work,also you should note a couple of other things:\n\nnumba can infer which types a function accepts/outputs, so ... | [
1
] | [] | [] | [
"decorator",
"deep_learning",
"numba",
"python"
] | stackoverflow_0074294713_decorator_deep_learning_numba_python.txt |
Q:
Contour plot of a multivariate function
I have a multivariate function
X is (2, 1), A(100, 2), and b is (100, 1).
How can I plot the contour plot of it in python? for a simple case like Z = X^2 + Y^2 I have this code, but I don't think it can work for my problem.
x, y = np.linspace(-3, 3, 400), np.linspace(-3, 3,... | Contour plot of a multivariate function | I have a multivariate function
X is (2, 1), A(100, 2), and b is (100, 1).
How can I plot the contour plot of it in python? for a simple case like Z = X^2 + Y^2 I have this code, but I don't think it can work for my problem.
x, y = np.linspace(-3, 3, 400), np.linspace(-3, 3, 400)
XX, YY = np.meshgrid(x, y)
Z = (XX **... | [
"I assumed that in the pictured formula x is the same as X, which represents the coordinates of a point in a 2D plane.\nThen, with np.meshgrid you create the usual grid of coordinates over which evaluating the function, xx and yy. At this points, you need to combine them into a matrix X of 2 rows (representing x an... | [
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074300202_matplotlib_numpy_python.txt |
Q:
Cannot download datasets from tfds
I cannot download the Celeb_A dataset for StarGAN. I got an error:
/usr/local/lib/python3.7/dist-packages/tensorflow_datasets/core/download/downloader.py
in _assert_status(response)
305 if response.status_code != 200:
306 raise DownloadError('Failed to get url {}. HTTP cod... | Cannot download datasets from tfds | I cannot download the Celeb_A dataset for StarGAN. I got an error:
/usr/local/lib/python3.7/dist-packages/tensorflow_datasets/core/download/downloader.py
in _assert_status(response)
305 if response.status_code != 200:
306 raise DownloadError('Failed to get url {}. HTTP code: {}.'.format(
--> 307 response... | [
"I have experienced the same issue (http code: 429) with download of celeba dataset when I called\ntfds.load('celeb_a', data_dir='./', as_supervised=True, with_info=True)\n\nI just found working solution to download data here.\ntfds.builder('celeb_a', data_dir='./', version='2.0.1')\nceleb_a_builder = celeb_a_build... | [
1
] | [] | [] | [
"generative_adversarial_network",
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0073812531_generative_adversarial_network_python_tensorflow_tensorflow_datasets.txt |
Q:
List iteration using multiple lists
I've got two lists
All_Teams = [a,b,c,d,e...] #has 30 items
Players = [p1, p2, p3, p4, p5, p6] #has 6 items currently, but this will be varied
In this example I want to assign x number of random teams to each player, where x = All_Teams/Players (5 in this example). But once a t... | List iteration using multiple lists | I've got two lists
All_Teams = [a,b,c,d,e...] #has 30 items
Players = [p1, p2, p3, p4, p5, p6] #has 6 items currently, but this will be varied
In this example I want to assign x number of random teams to each player, where x = All_Teams/Players (5 in this example). But once a team has be assigned to a player it can't ... | [
"Shuffle the All_Teams list, split in it into x parts and there you have it, groups for each player:\nimport random\n\nAll_Teams = [i for i in range(30)]\nPlayers = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'] \n\nassert len(All_Teams) % len(Players) == 0\nx = int(len(All_Teams) / len(Players))\n\nrandom.shuffle(All_Teams)... | [
0
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0074302584_list_loops_python.txt |
Q:
Issue deploying Python Flask Package, more specifically unable to open database file
The Error message that shows up is sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8)
And the Traceback stated the error as fighter... | Issue deploying Python Flask Package, more specifically unable to open database file | The Error message that shows up is sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8)
And the Traceback stated the error as fighters = Fighter.query.all()
I have tried different methods of `
fighters.query.get(Fighter)
`
... | [
"try this\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'\n\ninstead of this\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///tmp/test.db')\n\n"
] | [
0
] | [] | [] | [
"flask_sqlalchemy",
"operationalerror",
"python"
] | stackoverflow_0074302915_flask_sqlalchemy_operationalerror_python.txt |
Q:
How to use xlwings to run a macro from one excel onto another excel?
I searched on google and find out how to excute a macro by xlwings in python. However, now I have two excels, A with a macro but no data, B with data but no macro. Then how to excute the macro in A onto B? You can understand that I wanna write a ... | How to use xlwings to run a macro from one excel onto another excel? | I searched on google and find out how to excute a macro by xlwings in python. However, now I have two excels, A with a macro but no data, B with data but no macro. Then how to excute the macro in A onto B? You can understand that I wanna write a macro script and then use it to process many excels in python. How should ... | [
"If you want execute macro, but get data from many files, then you must in VBA use Workbooks object. Its possible in different way:\nWorkbooks(\"B.xlsx\").Worksheets(\"test3\").Range(\"A1\", \"D5\").Value = Null\n\nand you can use\nWindows(\"B.xlsx\").Activate\nActiveWorkbook.Sheets(\"test5\").Range(\"C4\").Select\... | [
0
] | [] | [] | [
"excel",
"python",
"xlwings"
] | stackoverflow_0074302747_excel_python_xlwings.txt |
Q:
Copy files to a new folder based on file name, and then name the new folder based on the file name
I'm trying to use python to automate the very manual process of moving test result files to a newly created folder.
Simply put, each part we test spits out 5 files, 3x .txt files, 1x .PDF and 1x .ZMP file. We have a ... | Copy files to a new folder based on file name, and then name the new folder based on the file name | I'm trying to use python to automate the very manual process of moving test result files to a newly created folder.
Simply put, each part we test spits out 5 files, 3x .txt files, 1x .PDF and 1x .ZMP file. We have a growing folder consisting of hundreds of these files.
All of these files end in a serial no which is TSS... | [
"This code will go through all the files in SRC and if the file name contains TSS it will extarct the TSS-XXXX-XXXX and then it will check if the TSS-XXXX-XXXX folder exist in the DST folder (if not it will create the folder) and then it will move the file from SRC\\ to DST\\TSS-XXXX-XXXX\\\n\nskip file if already ... | [
0
] | [] | [] | [
"copy",
"directory",
"file",
"move",
"python"
] | stackoverflow_0074302734_copy_directory_file_move_python.txt |
Q:
How to do similar to conditional countifs on a dataframe
I am trying to replicate countifs in excel to get a rank between two unique values that are listed in my dataframe. I have attached the expected output calculated in excel using countif and let/rank functions.
I am trying to generate "average rank of gas and... | How to do similar to conditional countifs on a dataframe | I am trying to replicate countifs in excel to get a rank between two unique values that are listed in my dataframe. I have attached the expected output calculated in excel using countif and let/rank functions.
I am trying to generate "average rank of gas and coal plants" that takes the number from the "average rank col... | [
"import pandas as pd\ndf = pd.read_csv(\"gas.csv\")\ndisplay(df['Technology'].value_counts())\nprint('------')\ndisplay(df['Technology'].value_counts()[0]) # This is how you access count of CCGT\ndisplay(df['Technology'].value_counts()[1])\n\nOutput:\nCCGT 47\nCOAL 2\nName: Technology, dtype: int64\n\n------... | [
2
] | [] | [] | [
"excel",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074302838_excel_jupyter_notebook_pandas_python.txt |
Q:
Scikit Learn Pipeline with SMOTE
I would like to create a Pipeline with SMOTE() inside, but I can't figure out where to implement it.
My target value is imbalanced. Without SMOTE I have very bad results.
My code:
df_n = df[['user_id','signup_day', 'signup_month', 'signup_year',
'purchase_day', 'purchase_month... | Scikit Learn Pipeline with SMOTE | I would like to create a Pipeline with SMOTE() inside, but I can't figure out where to implement it.
My target value is imbalanced. Without SMOTE I have very bad results.
My code:
df_n = df[['user_id','signup_day', 'signup_month', 'signup_year',
'purchase_day', 'purchase_month', 'purchase_year','purchase_value',
... | [
"from imblearn.over_sampling import SMOTEN\nsampler = SMOTEN(random_state=0)\nXsm,ysm = sampler.fit_resample(X, y)\n\n",
"You can use below code for adding SMOTE in pipeline (need some tweaking though)\nfrom imblearn.pipeline import Pipeline\n\n# define pipeline\nmodel = DecisionTreeClassifier()\nover = SMOTE(sam... | [
2,
1,
1
] | [] | [] | [
"pipeline",
"python",
"regression",
"scikit_learn",
"smote"
] | stackoverflow_0072749144_pipeline_python_regression_scikit_learn_smote.txt |
Q:
How to convert data into time series
I have : (dateTime is in string format)
df
dateTime level
2020-10-31T23:18:00.000 slow
2020-10-31T23:25:00.000 moderate
I want to convert this to time series in 1min level by replicating the 'level' for every minute until the next instance where the... | How to convert data into time series | I have : (dateTime is in string format)
df
dateTime level
2020-10-31T23:18:00.000 slow
2020-10-31T23:25:00.000 moderate
I want to convert this to time series in 1min level by replicating the 'level' for every minute until the next instance where there is a change:
df
dateTime ... | [
"Create DatetimeIndex and use DataFrame.asfreq:\ndf['dateTime'] = pd.to_datetime(df['dateTime'])\ndf = df.set_index('dateTime').asfreq('1Min', method='ffill')\nprint (df)\n level\ndateTime \n2020-10-31 23:18:00 slow\n2020-10-31 23:19:00 slow\n2020-10-31 23:20:00 ... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302888_dataframe_pandas_python.txt |
Q:
(eval):10: unmatched | conda active error on iTerm, Mac M1 Big Sur
fellows,
I just changed to MAC AIR M1 from windows so I've been suffering from getting used to use it and build development envs.
while the process I tried about dozen ways to install tensorflow for M1, I installed and deleted anaconda3 several tim... | (eval):10: unmatched | conda active error on iTerm, Mac M1 Big Sur | fellows,
I just changed to MAC AIR M1 from windows so I've been suffering from getting used to use it and build development envs.
while the process I tried about dozen ways to install tensorflow for M1, I installed and deleted anaconda3 several times and install miniforge by brew and additionally installed miniforge3(I... | [
"I have met same error, but I found the problem solved when I comment the prefix lines in my ~/.zshrc file. The actual mistake is yarn path config line, I‘m not sure is yarn error or my previouse incorrect edit.\nexport YARN_GLOBAL_PATH=$(yarn global bin)\nexport PATH=\"'$YARN_GLOBAL_PATH:$PATH\"\n\nthere's a \"'\"... | [
1,
0
] | [] | [] | [
"apple_m1",
"conda",
"python",
"terminal",
"zsh"
] | stackoverflow_0067973151_apple_m1_conda_python_terminal_zsh.txt |
Q:
Exit codes in Python
I got a message saying script xyz.py returned exit code 0. What does this mean?
What do the exit codes in Python mean? How many are there? Which ones are important?
A:
You're looking for calls to sys.exit() in the script. The argument to that method is returned to the environment as the exit... | Exit codes in Python | I got a message saying script xyz.py returned exit code 0. What does this mean?
What do the exit codes in Python mean? How many are there? Which ones are important?
| [
"You're looking for calls to sys.exit() in the script. The argument to that method is returned to the environment as the exit code.\nIt's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.\n",
"From the documentation for sys.exit:\n\nThe optional argument arg can ... | [
308,
131,
48,
22,
17,
14,
13,
8,
6,
6,
6,
3,
0
] | [
"To allow exception handlers and other things execute I recommend a clean shutdown with the exit(0) builtin rather than using sys.exit() which terminates the process abruptly.\n"
] | [
-3
] | [
"exit_code",
"python"
] | stackoverflow_0000285289_exit_code_python.txt |
Q:
Compare quantity of each item in dataframe in pandas
I fairly new to programming in python and using the pandas library
and I am having problems with comparing 2 dataframes with different quantities
i want to see if the quantity in data_1 is less than the quantity in data_2 for each item
import pandas as pd
data_... | Compare quantity of each item in dataframe in pandas | I fairly new to programming in python and using the pandas library
and I am having problems with comparing 2 dataframes with different quantities
i want to see if the quantity in data_1 is less than the quantity in data_2 for each item
import pandas as pd
data_1 = [['banana',10],['orange',2],['strawberry',3]]
data_2 =... | [
"For such comparison item should be index and then you might concat quantity columns and compute desired column following way\nimport pandas as pd\n\ndata_1 = [['banana',10],['orange',2],['strawberry',3]]\ndata_2 = [['banana',1],['orange',2],['strawberry',5],['melon',8]]\n\ndf_1 = pd.DataFrame(data_1,columns = ['it... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302956_dataframe_pandas_python.txt |
Q:
Combining multiple CSVs in pandas
I have multiple csv files (which I've moved into pandas dataframes) in a folder, each of which holds monthly website data
January.csv:
URL Value
page1 10
page2 52
page3 17
February.csv:
URL Value
page1 20
page2 7
page3 15
March.csv:
URL Value
page1 7
pag... | Combining multiple CSVs in pandas | I have multiple csv files (which I've moved into pandas dataframes) in a folder, each of which holds monthly website data
January.csv:
URL Value
page1 10
page2 52
page3 17
February.csv:
URL Value
page1 20
page2 7
page3 15
March.csv:
URL Value
page1 7
page2 15
page3 23
and need to combin... | [
"While @robinood's answer is correct, I think it's more efficient to use generator expression (in round brackets):\nall_filenames = [i for i in glob.glob('*.{}'.format('csv'))]\nresult = pd.concat((pd.read_csv(f, index_col='URL', usecols=['URL', 'Value']) for f in all_filenames), axis=1)\n\nNote that the above snip... | [
3,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302969_dataframe_pandas_python.txt |
Q:
Move multiple object
All,
I am writing a code to move multiple balls in a Tkinter window, I know we can easily do this using oops/classes, but I am wondering if we can do this without classes. My current code kind of works but since I use for loops after every iteration one of the balls disappears. can you suggest... | Move multiple object | All,
I am writing a code to move multiple balls in a Tkinter window, I know we can easily do this using oops/classes, but I am wondering if we can do this without classes. My current code kind of works but since I use for loops after every iteration one of the balls disappears. can you suggest what's wrong here? and ho... | [
"Your code is working. Unfortunately, you didn't mention bouncing balls. The HEIGHT and WIDTH don't help with offset screen. By using winfo_height() and winfo_width() will solve the problem. As for me, I used a bouncing ball using class instantiate module. And canvas.move(b,x,y) is always placed after if/else condi... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074295477_python_tkinter.txt |
Q:
txt to pandas df python
I am trying to extract the information from the following text file and convert it to a pandas dataframe, the text file looks like:
disp alarm active
1:Critical 2:Major 3:Minor 4:Warning
--------------------------------------------------------------------------------
Sequence AlarmId ... | txt to pandas df python | I am trying to extract the information from the following text file and convert it to a pandas dataframe, the text file looks like:
disp alarm active
1:Critical 2:Major 3:Minor 4:Warning
--------------------------------------------------------------------------------
Sequence AlarmId Level Date Time Descripti... | [
"from io import StringIO\n\nimport pandas as pd\n\nbuf = StringIO()\n\nwith open(\"log.log\") as f:\n for i, line in enumerate(f.readlines()):\n if (i in [0, 1, 2, 4, 14, 15]) or (line.strip() == \"\"):\n continue\n buf.write(\n \"|\".join([line[:10], line[10:20], line[20:27],... | [
2
] | [] | [] | [
"pandas",
"parsing",
"python",
"text"
] | stackoverflow_0074302296_pandas_parsing_python_text.txt |
Q:
Heatmap plot of array of arrays
I have a numpy array composed of the following arrays (as example):
my_array = [[10,12,0],[10,13,1],[11,12,1],[11,13,0],[12,12,1],[12,13,0]]
Where items are [x,y,value]
I want to plot a heatmap or similar with x values in X, y values i Y, and color depending on value (0 or 1). I wan... | Heatmap plot of array of arrays | I have a numpy array composed of the following arrays (as example):
my_array = [[10,12,0],[10,13,1],[11,12,1],[11,13,0],[12,12,1],[12,13,0]]
Where items are [x,y,value]
I want to plot a heatmap or similar with x values in X, y values i Y, and color depending on value (0 or 1). I want also label color for 0 as 'A points... | [
"you could create a 2d list or numpy 2d array and plt that.\nimport matplotlib.pyplot as plt\nxvals = [10,11,12]\nyvals = [12,13]\nzvals = [[10,12,0],[10,13,1],[11,12,1],[11,13,0],[12,12,1],[12,13,0]]\n\nim = [[0 for j in range(len(xvals))] for i in range(len(yvals))]\n\nfor val in zvals:\n im[val[1] - yvals[0]]... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074301472_numpy_python.txt |
Q:
How to reorder the columns of a MultiIndex columns pandas DataFrame?
After having read the pandas reindex docs, it is still not clear to me how to re-arrange the order of the columns in a MultiIndex DataFrame and re-assign it to the original DataFrame.
For example, say that I have the following DataFrame
df =
kin... | How to reorder the columns of a MultiIndex columns pandas DataFrame? | After having read the pandas reindex docs, it is still not clear to me how to re-arrange the order of the columns in a MultiIndex DataFrame and re-assign it to the original DataFrame.
For example, say that I have the following DataFrame
df =
kind A B
names u1 u2 ... | [
"Here is solution for recreate MultiIndex with expected ordering:\nprint (df)\nkind C A B\nnames d1 u2 u3 u1 y2\n0.0 0.5083 0.1007 0.8001 0.7373 0.1387\n0.1 0.6748 0.0354 0.0076 0.8421 0.2670\n0.2 0.1753 0.1013 0.5231 0.8060 0.0040\n\n... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074302318_dataframe_pandas_python.txt |
Q:
How do i remove the unnecessary text in the terminal in vscode?
Hi i'm new into vscode and when i run a program there is some text that i want to get rid of.
i mainly want to remove the first two paragraphs, but also removing the path would be ideal
i tried code runner but thats not the solution i'm looking for
i... | How do i remove the unnecessary text in the terminal in vscode? | Hi i'm new into vscode and when i run a program there is some text that i want to get rid of.
i mainly want to remove the first two paragraphs, but also removing the path would be ideal
i tried code runner but thats not the solution i'm looking for
i also tried changing the color to black but i reckon there is a way t... | [
"Adding the \"-NoLogo\" start parameter will remove the paragraph of text; If you open your settings file (Ctrl+Shift+P and then type \"Settings\" -> User Settings JSON), you can use the following bit of configuration:\n// should go in the main JSON object with the other keys\n\"terminal.integrated.profiles.windows... | [
3,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"terminal",
"visual_studio_code"
] | stackoverflow_0074303133_python_python_3.x_terminal_visual_studio_code.txt |
Q:
Convert spaCy `Doc` into CoNLL 2003 sample
I was planning to train a Spark NLP custom NER model, which uses the CoNLL 2003 format to do so (this blog even leaves some traning sample data to speed-up the follow-up). This "sample data" is NOT useful for me, as I have my own training data to train a model with; this ... | Convert spaCy `Doc` into CoNLL 2003 sample | I was planning to train a Spark NLP custom NER model, which uses the CoNLL 2003 format to do so (this blog even leaves some traning sample data to speed-up the follow-up). This "sample data" is NOT useful for me, as I have my own training data to train a model with; this data however, consists of a list of spaCy Doc ob... | [
"If you look at a sample CoNLL file, you'll see they just separate entries with one blank line between them. So you just use a for loop.\nfor doc in docs:\n for sent in doc.sents:\n print(\"#\", doc) # optional but makes it easier to read\n print(sent._.conll_str)\n print()\n\nCoNLL files ar... | [
1,
1,
0
] | [] | [] | [
"conll",
"nlp",
"python",
"spacy_3"
] | stackoverflow_0074212658_conll_nlp_python_spacy_3.txt |
Q:
Keras functional API Model with String Input
I am using tensorflow==2.9.1 an i am trying to use tf.keras.Model? to build a model with partially numerical and partially categorical data.
Here a short example of what i would like to do:
import tensorflow==2.9.1
input_layer = tf.keras.layers.InputLayer(input_shape=(... | Keras functional API Model with String Input | I am using tensorflow==2.9.1 an i am trying to use tf.keras.Model? to build a model with partially numerical and partially categorical data.
Here a short example of what i would like to do:
import tensorflow==2.9.1
input_layer = tf.keras.layers.InputLayer(input_shape=(1,), dtype=tf.string)
string_lookup_layer = tf.ker... | [
"Use tf.keras.layers.Input instead of tf.keras.layers.InputLayer and initialize your StringLookup layer first:\nimport tensorflow as tf\n\ninputs = tf.keras.layers.Input(shape=(1,), dtype=tf.string)\nstring_lookup_layer = tf.keras.layers.StringLookup(vocabulary=[\"a\", \"b\"], output_mode=\"one_hot\")\noutputs = st... | [
2
] | [] | [] | [
"deep_learning",
"keras",
"python",
"string",
"tensorflow"
] | stackoverflow_0074303461_deep_learning_keras_python_string_tensorflow.txt |
Q:
SyntaxError: positional argument follows keyword argument - Plotly
I have checked several article to help me correct the following codes but despite changes I don't know how to fix it.
thank you for your help
import plotly.graph_objects as px
import plotly.graph_objs as go
x = ['18-25', '25-35', '35-45','45-55',... | SyntaxError: positional argument follows keyword argument - Plotly | I have checked several article to help me correct the following codes but despite changes I don't know how to fix it.
thank you for your help
import plotly.graph_objects as px
import plotly.graph_objs as go
x = ['18-25', '25-35', '35-45','45-55','55-65']
plot = px.Figure(data=[go.Bar(
name = 'Bulle de Babel',
... | [
"Here's what you currently have, with only the indentation and whitespace adjusted to something more conventional\nplot = px.Figure(data=[\n go.Bar(\n name='Bulle de Babel',\n x=x,\n y=[97, 204, 192, 145, 96]\n ),\n go.Bar(\n name... | [
1
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0074303301_python_syntax_error.txt |
Q:
how can I approach scraping a real estate website with BeautifulSoup4
(new to this, so apologies if the question is stupid, I don't need a solution but just a push in the right direction)
I am trying to scrape a real estate website using bs4, problem is I can't find data I am looking for. when I parse the html I c... | how can I approach scraping a real estate website with BeautifulSoup4 | (new to this, so apologies if the question is stupid, I don't need a solution but just a push in the right direction)
I am trying to scrape a real estate website using bs4, problem is I can't find data I am looking for. when I parse the html I can't see the information I need from the website. Is it even possible to sc... | [
"@baduker already has stated about it's dynamic nature and the way of the possible solution. The website is very lazy load and dynamic. So I use selenium with bs4.\nWorking code as an examole:\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import ... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074301517_beautifulsoup_python_web_scraping.txt |
Q:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 355: invalid start byte
I've been trying to iterate through a csv file with the following code:
`
import csv
import os, sys
directory = "/Users/aliharam/Desktop/Lamis File"
files = []
for filename in os.listdir(directory):
f = os.path.join(d... | UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 355: invalid start byte | I've been trying to iterate through a csv file with the following code:
`
import csv
import os, sys
directory = "/Users/aliharam/Desktop/Lamis File"
files = []
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
# checking if it is a file
if os.path.isfile(f):
files.append(... | [] | [] | [
"The file your program reads contains character(at position 355) which does not belong to Unicode.\nIf we assume you are reading a Unicode encoded file, then there is an error in your data file. First you need to make sure the file your program reads is encoded in Unicode or not.\n"
] | [
-1
] | [
"python",
"read.csv"
] | stackoverflow_0074303487_python_read.csv.txt |
Q:
Python sends bulk mail from [BCC] insted of [TO], why?
I am writing a python script that sends every day a bulk email (connected to an outlook.com account) with the body of a news website as an ebook to multiple kindle accounts (that have already whitelisted this outlook account).
This was working so far, but sinc... | Python sends bulk mail from [BCC] insted of [TO], why? | I am writing a python script that sends every day a bulk email (connected to an outlook.com account) with the body of a news website as an ebook to multiple kindle accounts (that have already whitelisted this outlook account).
This was working so far, but since yesterday the kindle devices couldn't get the ebooks. I've... | [
"Your code seems to be written for Python 3.5 or earlier. The email library was overhauled in 3.6 and is now quite a bit more versatile and logical. Probably throw away what you have and start over with the examples from the email documentation.\nThe simple and obvious solution is to put all the recipients in msg[\... | [
2
] | [] | [] | [
"email",
"email_attachments",
"html_email",
"python"
] | stackoverflow_0074302670_email_email_attachments_html_email_python.txt |
Q:
Converting a for loop to a while loop ( with a range involved)
Converting this to a while loop is turning out to be more trouble than initially thought.
Any tips or tricks on how to solve this would be appreciated
sum = 0
for i in range (10,0,-1):
sum = sum +1
print(i,sum)
this is as close as i can get -
... | Converting a for loop to a while loop ( with a range involved) | Converting this to a while loop is turning out to be more trouble than initially thought.
Any tips or tricks on how to solve this would be appreciated
sum = 0
for i in range (10,0,-1):
sum = sum +1
print(i,sum)
this is as close as i can get -
i=1
while i in range(10,0,-1):
print(i)
print(i, end=' ')
... | [
"Your guess was too close to get the same result using while loop.\nUse two , len() and list() function , to get the same outputs.\ni=1\nwhile i in range(10,0,-1):\nprint(len(list(range(10,0,-1)))-i+1,i)\ni=i+1\n\nThankyou hope it helps\n",
"I think this code will do what you expect\ns = i = 10\nwhile i > 0:\n ... | [
1,
0
] | [] | [] | [
"for_loop",
"loops",
"python",
"while_loop"
] | stackoverflow_0074298544_for_loop_loops_python_while_loop.txt |
Q:
How do I change the size of figures drawn with Matplotlib?
How do I change the size of figure drawn with Matplotlib?
A:
figure tells you the call signature:
from matplotlib.pyplot import figure
figure(figsize=(8, 6), dpi=80)
figure(figsize=(1,1)) would create an inch-by-inch image, which would be 80-by-80 pixe... | How do I change the size of figures drawn with Matplotlib? | How do I change the size of figure drawn with Matplotlib?
| [
"figure tells you the call signature:\nfrom matplotlib.pyplot import figure\n\nfigure(figsize=(8, 6), dpi=80)\n\nfigure(figsize=(1,1)) would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument.\n",
"If you've already got the figure created, you can use figure... | [
1762,
1082,
698,
426,
185,
85,
60,
50,
42,
33,
20,
17,
16,
15,
14,
12,
10,
8,
6,
4,
2,
1
] | [] | [] | [
"figsize",
"matplotlib",
"pandas",
"python",
"seaborn"
] | stackoverflow_0000332289_figsize_matplotlib_pandas_python_seaborn.txt |
Q:
How to use pipenv on server
I try to use pipenv on server
task :migrate do on roles(:app) do
execute "cd #{release_path} && /home/ubuntu/.pyenv/shims/pipenv install"
execute "cd #{release_path} && /home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py makemigrations"
execute "cd #{rele... | How to use pipenv on server | I try to use pipenv on server
task :migrate do on roles(:app) do
execute "cd #{release_path} && /home/ubuntu/.pyenv/shims/pipenv install"
execute "cd #{release_path} && /home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py makemigrations"
execute "cd #{release_path} && /home/ubuntu/.pyenv/... | [
"Use pipenv as a development environment.\n\nInstall pipenv via pip\npip3 install --user pipenv\n\nRun pipenv shell\npipenv shell\n\nInstall django and packages you need\npipenv install django\npipenv install django-crispy-forms\n\nRun your server\npipenv run python3 manage.py runserver\n\n\n"
] | [
0
] | [] | [] | [
"pipenv",
"python",
"server"
] | stackoverflow_0073827810_pipenv_python_server.txt |
Q:
2nd Reaction not being added to a cog command
I lately switched to cogs in nextcord.
I added a poll command, a simple one where you just have to react.
@commands.command()
@commands.has_permissions(moderate_members=True)
async def poll(self, ctx, *, content:str=None):
if content == None:
... | 2nd Reaction not being added to a cog command | I lately switched to cogs in nextcord.
I added a poll command, a simple one where you just have to react.
@commands.command()
@commands.has_permissions(moderate_members=True)
async def poll(self, ctx, *, content:str=None):
if content == None:
content = "Lorem Ipsum"
embed=nextcor... | [] | [] | [
"embed=discord.Embed uh???\nyo gotta change that\n"
] | [
-1
] | [
"discord.py",
"nextcord",
"python"
] | stackoverflow_0074303622_discord.py_nextcord_python.txt |
Q:
Unable to run python files in terminal on Mac
I create a file and try run it in my terminal and get this error "/Library/Developer/CommandLineTools/usr/bin/python3: can't open file '/Users/dcg/pb': [Errno 2] No such file or directory"
I'm not sure why, as when I Cd and I'm in the correct directory. This is a my fi... | Unable to run python files in terminal on Mac | I create a file and try run it in my terminal and get this error "/Library/Developer/CommandLineTools/usr/bin/python3: can't open file '/Users/dcg/pb': [Errno 2] No such file or directory"
I'm not sure why, as when I Cd and I'm in the correct directory. This is a my first time coding in python on this laptop. Any help ... | [
"Are you sure to point to the python file you created ?\n/Users/dcg/pb isn't a python file, you may be missing the .py extension in your command line prompt.\n"
] | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0074303524_macos_python.txt |
Q:
How can I repeatedly play a sound sample, allowing the next loop to overlap the previous
Not sure if this isn't a dupe, but the posts I found so far didn't solve my issue.
A while ago, I wrote a (music) metronome for Ubuntu. The metronome is written in python3/Gtk
To repeatedly play the metronome- tick (a recorde... | How can I repeatedly play a sound sample, allowing the next loop to overlap the previous | Not sure if this isn't a dupe, but the posts I found so far didn't solve my issue.
A while ago, I wrote a (music) metronome for Ubuntu. The metronome is written in python3/Gtk
To repeatedly play the metronome- tick (a recorded sound sample), I used subprocess.Popen() to play the sound, using ogg123 as a cli tool:
subp... | [
"You can use pydub for audio manipulation , including playing repetedly.\nHere is an example. You can develop this further using examples from pydub site.\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\nn = 2\n\naudio = AudioSegment.from_file(\"sound.wav\") #your audio file\nplay(audio * n) #Pl... | [
1,
0
] | [] | [] | [
"audio",
"python",
"python_3.x",
"windows"
] | stackoverflow_0039647440_audio_python_python_3.x_windows.txt |
Q:
Join values into one line with specific separator
Noob here...
I'm trying to develop a handful of python tools in my new role. I'm not a developer, but want/need to learn some handy coding.
Background:
Sometimes we're provided with a CSV and some populated columns. The values of one of these columns are reference ... | Join values into one line with specific separator | Noob here...
I'm trying to develop a handful of python tools in my new role. I'm not a developer, but want/need to learn some handy coding.
Background:
Sometimes we're provided with a CSV and some populated columns. The values of one of these columns are reference IDs that we will need to perform DB searches on. Someti... | [
"You can just create a new string and assign it to your current string with comma's at the beginning and end like this:\nReplace the target string\nfiledata = filedata.replace(\"\\n\", \"','\")\n\nnewfiledata = \",\" + filedata + \",\"\n\nprint(newfiledata)\n\n\nNote: If you use this approach, every time you now me... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074301015_dataframe_pandas_python.txt |
Q:
Repeatedly sample and combine elements of a list
Suppose we have a list L = ['a', 'b', 'c'], I would like to perform a group sampling of L to generate an expected result:
[['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
We can see, in this final output, a list of lists, its each element,... | Repeatedly sample and combine elements of a list | Suppose we have a list L = ['a', 'b', 'c'], I would like to perform a group sampling of L to generate an expected result:
[['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
We can see, in this final output, a list of lists, its each element, there are no repeated elements without considering th... | [
"One way of doing it is using combinations from itertools module. Do it in a for loop and change its r= parameter every time. r=1, r=2, until r=len(L):\nfrom itertools import combinations\n\nlst = [\"a\", \"b\", \"c\"]\nprint([list(item) for i in range(1, len(lst) + 1) for item in combinations(lst, i)])\n\noutput:\... | [
1
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074303493_list_python_python_3.x.txt |
Q:
How to reference a single column in a def function
First off I know using regular expression is not the best email validation but this is a preliminary step, a better validation comes later.
I want to create a function that validates whether or not an email address is valid but i am not sure how to reference only ... | How to reference a single column in a def function | First off I know using regular expression is not the best email validation but this is a preliminary step, a better validation comes later.
I want to create a function that validates whether or not an email address is valid but i am not sure how to reference only one column in a data frame.
import pandas as pd
d=[['Au... | [
"I believe you might want:\ndef Prospect(colname, errors, df=df):\n \n m = df[colname].str.match(r\"^.+@.+\\..{2,}$\")\n \n if m.all():\n pass\n else:\n error='this is an invalid email'\n errors.append(error)\n \nerrors = []\nProspect('email', errors, df=df)\n\nprint(errors)\n... | [
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074303234_pandas_python.txt |
Q:
Pandas - match column from two df and return value from another columnl
I have a csv of transactions from my bank, and another csv that I have created where I have categorized the most frequently occurring transactions. I want to classify the bank csv with a category by matching the Descriptions between both dataf... | Pandas - match column from two df and return value from another columnl | I have a csv of transactions from my bank, and another csv that I have created where I have categorized the most frequently occurring transactions. I want to classify the bank csv with a category by matching the Descriptions between both dataframes. Not all will be classified/have a match.
df1 ~2.5k rows:
Description, ... | [
"You could use pandas' join, but you need to set the 'Descritpion' as the index:\nimport pandas as pd\n\ndata1 = {'Description':['Corner Store','Cinema','Trampoline Store'],\n 'Amount':[30,10,20]}\ndf1 = pd.DataFrame(data1)\n\ndata2 = {'Description':['Corner Store','Cinema', 'The Pub'],\n 'Category'... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074302610_pandas_python.txt |
Q:
Python: how parse this dict recursively?
I've a flat dict with entities. Each entity can have a parent. I'd like to recursively build each entity, considering the parent values.
Logic:
Each entity inherits defaults from its parent (e.g. is_mammal)
Each entity can overwrite the defaults of its parent (e.g. age)
Ea... | Python: how parse this dict recursively? | I've a flat dict with entities. Each entity can have a parent. I'd like to recursively build each entity, considering the parent values.
Logic:
Each entity inherits defaults from its parent (e.g. is_mammal)
Each entity can overwrite the defaults of its parent (e.g. age)
Each entity can add new attributes (e.g. hobby)
... | [
"def get_character(entities, key):\n try:\n entity = get_character(entities, entities[key]['parent'])\n except KeyError:\n entity = {}\n entity.update(entities[key])\n return entity\n\n",
"This solution is using recursion and a Python quirk where mutables (here it's a dictionary {}), are... | [
2,
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074303332_python_recursion.txt |
Q:
Bubble Sort using a while loop in Python
I've been set a bubble sort for homework, and I've been trying to use a while loop. I know that it's possible with a for loop, but I don't really understand them and I'd like to write something that I understand.
unsorted = True
numbers = []
unsortchecker = 0
start = 0
maxl... | Bubble Sort using a while loop in Python | I've been set a bubble sort for homework, and I've been trying to use a while loop. I know that it's possible with a for loop, but I don't really understand them and I'd like to write something that I understand.
unsorted = True
numbers = []
unsortchecker = 0
start = 0
maxlist = int(input("How many numbers should be so... | [
"The bubble sort algorithm works in O(n*n) time by repeatedly swapping adjacent elements with each other to ensure sort order. Its popular publicized form with two for loops can easily be modified to replace with while loops as expressed below:\ndef bubbleSort(l):\n i = 0\n while i<len(l):\n j = 0\n ... | [
1,
0,
0,
0
] | [
"Using a for loop with a definite number of iteration(s) is potentially wasteful. It fails to accommodate the scenario where a already sorted array is given. The for loop would blindly iterate regardless of whether the array is sorted or not. \nInstead, we should introduce a flag and use a while loop. As soon as it... | [
-1
] | [
"bubble_sort",
"python"
] | stackoverflow_0041600327_bubble_sort_python.txt |
Q:
Reading "a flat, binary array of 16-bit signed, little-endian (LSB) integers" from file in python
I'm trying to read a old file of snow data from here, but I'm having a ton of trouble just opening a single file and getting data out. In the user guide, it says "Each monthly binary data file with the file extension ... | Reading "a flat, binary array of 16-bit signed, little-endian (LSB) integers" from file in python | I'm trying to read a old file of snow data from here, but I'm having a ton of trouble just opening a single file and getting data out. In the user guide, it says "Each monthly binary data file with the file extension ".NSIDC8" contains a flat, binary array of 16-bit signed, little-endian (LSB) integers, 721 columns by ... | [
"You can unpack the data 16 bits at a time and specify this in your unpack format string. You're using <i, which wants 4 bytes. The data is in 16 bit numbers, which wants 2 bytes. Instead, use <h.\nFor example,\n# I chose a random file from their setup\nwith open(\"NL198303.v01.NSIDC8\", \"rb\") as dfile:\n prin... | [
1,
0
] | [] | [] | [
"binary",
"python",
"struct"
] | stackoverflow_0074303547_binary_python_struct.txt |
Q:
array to image using np.full in opencv?
I am new to opencv and I was just wondering if I can make a image using numpy array.
First I just made a simple black image using np.zeroes ->
import numpy as np
img = np.zeros([512,512,3])
cv.imwrite('color_img.jpg', img)
cv.imshow("image", img)
cv.waitKey(0)
This display... | array to image using np.full in opencv? | I am new to opencv and I was just wondering if I can make a image using numpy array.
First I just made a simple black image using np.zeroes ->
import numpy as np
img = np.zeros([512,512,3])
cv.imwrite('color_img.jpg', img)
cv.imshow("image", img)
cv.waitKey(0)
This displays a black image.
So I wanted to try out this ... | [
"The problem was in the data type of both the arrays. (As pointed out in comments.)\nThe dtype of np.zeros() is float64 while the dtype of np.full() is int32.\nSo, it's better to specify dtype while doing such things.\neg->\n(array of zeros using np.full())\nimport numpy as np\nimg = np.full([512,512,3], 0, dtype=n... | [
1
] | [] | [] | [
"numpy",
"opencv",
"python"
] | stackoverflow_0074303515_numpy_opencv_python.txt |
Q:
List to csv without commas in Python
I have a following problem.
I would like to save a list into a csv (in the first column).
See example here:
import csv
mylist = ["Hallo", "der Pixer", "Glas", "Telefon", "Der Kühlschrank brach kaputt."]
def list_na_csv(file, mylist):
with open(file, "w", newline="") as c... | List to csv without commas in Python | I have a following problem.
I would like to save a list into a csv (in the first column).
See example here:
import csv
mylist = ["Hallo", "der Pixer", "Glas", "Telefon", "Der Kühlschrank brach kaputt."]
def list_na_csv(file, mylist):
with open(file, "w", newline="") as csv_file:
csv_writer = csv.writer(... | [
"You have two problems here.\n\nwriterows expects a list of rows, said differently a list of iterables. As a string is iterable, you write each word in a different row, one character per field. If you want one row with one word per field, you should use writerow\n csv_writer.writerow(mylist)\n\n\nby default, the cs... | [
3,
1,
0,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0066354890_csv_python.txt |
Q:
How to create a dynamic filter?
I have a table with equipment and each of them has dates for level of maintenance. The user can select the maintenance level. So, I should adjust my SQLAlchemy for each combination of maintenance level chosen. For example:
SELECT * WHERE (equipment IN []) AND m_level1 = DATE AND m_l... | How to create a dynamic filter? | I have a table with equipment and each of them has dates for level of maintenance. The user can select the maintenance level. So, I should adjust my SQLAlchemy for each combination of maintenance level chosen. For example:
SELECT * WHERE (equipment IN []) AND m_level1 = DATE AND m_level2 = DATE ....)
So it is possible... | [
"I assume you are using the ORM.\nin that case, the filter function returns a query object. You can conditionaly build the query by doing something like\nquery = Session.query(schema.Object).filter_by(attribute=value)\nif condition:\n query = query.filter_by(condition_attr=condition_val)\nif another_condition:\n... | [
36,
22,
15,
2,
0
] | [] | [] | [
"dynamic",
"filter",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0037336520_dynamic_filter_python_sqlalchemy_sqlite.txt |
Q:
How to transform a 2d array in to two different 1d array in python
I'm trying to transform one 2d array:
{4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
in to 2 different 1d arrays, like this:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = [2, 3, 7, 6, 4, 2, 2, 1, 1]
To plot, using matplotlib, arr1 as y and a... | How to transform a 2d array in to two different 1d array in python | I'm trying to transform one 2d array:
{4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}
in to 2 different 1d arrays, like this:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = [2, 3, 7, 6, 4, 2, 2, 1, 1]
To plot, using matplotlib, arr1 as y and arr2 as x.
How can I do this?
PS: Sorry for the bad English. (;
| [
"here is what you can do:\nimport matplotlib.pylab as plt\nd = {4: 6, 6: 2, 1: 2, 3: 7, 5: 4, 9: 1, 2: 3, 7: 2, 8: 1}\nsorted_list = sorted(d.items()) # sorted by key, return a list of tuples\nx, y = zip(*sorted_list) # unpack a list of pairs into two tuples\n\nplt.plot(x, y)\nplt.show()\n\noutput :\n\n",
"You ca... | [
2,
2
] | [] | [] | [
"arrays",
"matplotlib",
"python"
] | stackoverflow_0074303815_arrays_matplotlib_python.txt |
Q:
want to make python function a tv_turn_on_or_Off() to print on for first time then off if called again
make a function named tv_turn_on_or_Off() ,it will take no parameter. if called for the first time it will print tv is on. if called again it will print tv is off. Then,if called again will print tv is on
class a... | want to make python function a tv_turn_on_or_Off() to print on for first time then off if called again | make a function named tv_turn_on_or_Off() ,it will take no parameter. if called for the first time it will print tv is on. if called again it will print tv is off. Then,if called again will print tv is on
class abcTv:
def __init__(self):
pass
def tv_turn_on_or_of(self):
pass
a=abcTv()
a.tv_... | [
"Just have a simple flag as your instance variable. By each call you should toggle it:\nclass abcTv:\n def __init__(self):\n self._is_on = False\n\n def tv_turn_on_or_of(self):\n if not self._is_on:\n print(\"tv is on\")\n self._is_on = True\n else:\n prin... | [
0
] | [] | [] | [
"function",
"if_statement",
"oop",
"python"
] | stackoverflow_0074303810_function_if_statement_oop_python.txt |
Q:
using ajax in flask to load live logs
I am looking for some help, regarding my web server. I have a flask web server, designed to search in log files, and it does the job, but I need something else. To access the live data, to see the logs live.
It's an internal application, so the security is not a concern. The m... | using ajax in flask to load live logs | I am looking for some help, regarding my web server. I have a flask web server, designed to search in log files, and it does the job, but I need something else. To access the live data, to see the logs live.
It's an internal application, so the security is not a concern. The main thing it should do, is to open a file a... | [
"So, in short terms in case of anyone else needs something like this, the solutin is :\n@login_required\ndef live():\n return render_template('live.html',user=current_user)\n \n@views.route('/live_logs', methods=['GET', 'POST'])\ndef live_logs():\n if request.method == 'GET':\n def generate():\n ... | [
0
] | [] | [] | [
"flask",
"html",
"javascript",
"python"
] | stackoverflow_0072477949_flask_html_javascript_python.txt |
Q:
Print side by side .describe() in pandas
Hello so i have two columns that im using describe() and im getting their stats. I have something like this
x=pd.Series([1,3,4,6,7])
y=pd.Series([75,324,234,42])
desk1=x.describe()
desk2=y.describe()
I want to print desk1 and desk2 below of each category.I am doing... | Print side by side .describe() in pandas | Hello so i have two columns that im using describe() and im getting their stats. I have something like this
x=pd.Series([1,3,4,6,7])
y=pd.Series([75,324,234,42])
desk1=x.describe()
desk2=y.describe()
I want to print desk1 and desk2 below of each category.I am doing this:
print("desk1 stats",end="\t\t")
print("... | [
"What about using:\nprint(pd.concat([desk1, desk2],\n keys=['desk1 description', 'desk2 description'],\n axis=1))\n\noutput:\n desk1 description desk2 description\ncount 5.000000 4.000000\nmean 4.200000 168.750000\nstd 2.38746... | [
2,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074303646_numpy_pandas_python.txt |
Q:
Interpolation between two datetimes
I have a time series dataset and I'm getting some events. These events are when I get a specific error from my system. Now I wanted to plot a graph from the dataset and place markers from the events on the graph of my time series. So I have to interpolate between two timestamps ... | Interpolation between two datetimes | I have a time series dataset and I'm getting some events. These events are when I get a specific error from my system. Now I wanted to plot a graph from the dataset and place markers from the events on the graph of my time series. So I have to interpolate between two timestamps to get the exact y value. My problem is n... | [
"use a numeric representation of datetime, e.g. Unix time you get from .timestamp(). Ex:\nfrom datetime import datetime\nimport numpy as np\n\ntest=np.interp(\n datetime(2022, 10, 11, 12, 24, 5, 922000).timestamp(),\n [datetime(2022, 10, 11, 12, 6, 40, 480000).timestamp(), datetime(2022, 10, 11, 12, 52, 51, 4... | [
1
] | [] | [] | [
"datetime",
"interpolation",
"numpy",
"python"
] | stackoverflow_0074302903_datetime_interpolation_numpy_python.txt |
Q:
Google Colab: Call a function from another python file
I want to run a function DataProcesser from a load_data.py python file, which can be found in my google drive path gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/.
from google.colab import drive
drive.mount('/content/gdrive')
# Custom functions/classes
path_t... | Google Colab: Call a function from another python file | I want to run a function DataProcesser from a load_data.py python file, which can be found in my google drive path gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/.
from google.colab import drive
drive.mount('/content/gdrive')
# Custom functions/classes
path_to_module = 'gdrive/My\ Drive/Colab\ Notebooks/CODEX/source/'... | [
"You probably don't need to escape the spaces in your string path_to_module but it might be that the path Colab sees is different. If you expand the files tab in Colab you can navigate to the files in Google Drive. Then you can right click on the file or folder you want and do Copy path. You can then paste this int... | [
2,
1
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0069371228_google_colaboratory_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.