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: What is the time complexity of my algorithm using a for loop? I have trouble with that exercise, how can I write it in Python, and get time complexity? Should use a while loop? Write an algorithm that returns the smallest value in the array A[1 . . . n]. Use a while loop. What is the time complexity of your algor...
What is the time complexity of my algorithm using a for loop?
I have trouble with that exercise, how can I write it in Python, and get time complexity? Should use a while loop? Write an algorithm that returns the smallest value in the array A[1 . . . n]. Use a while loop. What is the time complexity of your algorithm? list1 = [] num = int(input("Enter number of elements in list...
[ "How to get the time complexity?\nMost of the time when someone is asking you for time complexity they aren't asking for exact time complexity, they are asking for an approximate estimate in terms of Big O Notation. I highly recommend you check out this wiki but in short, Big O Notation asks \"For 'n' elements how...
[ 2 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0074677687_algorithm_python.txt
Q: Further optimizing the ISING model I've implemented the 2D ISING model in Python, using NumPy and Numba's JIT: from timeit import default_timer as timer import matplotlib.pyplot as plt import numba as nb import numpy as np # TODO for Dict optimization. # from numba import types # from numba.typed import Dict @n...
Further optimizing the ISING model
I've implemented the 2D ISING model in Python, using NumPy and Numba's JIT: from timeit import default_timer as timer import matplotlib.pyplot as plt import numba as nb import numpy as np # TODO for Dict optimization. # from numba import types # from numba.typed import Dict @nb.njit(nogil=True) def initialstate(N): ...
[ "The computation of the exponential is not really an issue. The main issue is that generating random numbers is expensive and a huge number of random values are generated. Another issue is that the current computation is intrinsically sequential.\nIndeed, for N=32, mcmove tends to generate about 3000 random values,...
[ 1, 1 ]
[]
[]
[ "montecarlo", "numba", "numpy", "performance", "python" ]
stackoverflow_0074660595_montecarlo_numba_numpy_performance_python.txt
Q: How to get data from django orm inside an asynchronous function? I need to retrieve data from the database inside an asynchronous function. If I retrieve only one object by executing e.g: users = await sync_to_async(Creators.objects.first)() everything works as it should. But if the response contains multiple obj...
How to get data from django orm inside an asynchronous function?
I need to retrieve data from the database inside an asynchronous function. If I retrieve only one object by executing e.g: users = await sync_to_async(Creators.objects.first)() everything works as it should. But if the response contains multiple objects, I get an error. @sync_to_async def get_creators(): return Cr...
[ "You may try wrap get_creators response into list:\n@sync_to_async\ndef get_creators():\n return list(Creators.objects.all())\n\n", "Since Django 4.1 you can do the following:\nasync for creator in Creators.objects.all():\n print(creator)\n\nAnd you can replace this with filter and the like as long as the ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0071489479_django_python.txt
Q: Kernel died with rasterio.open().read() on geo tiff images When I tried to open and read a certain geo tiff image with gdal and rasterio, I can read and do things like img.meta and img.descriptions. But when I tried to do img.read() with rasterio or img.GetRasterBand(1).ReadAsArray() with gdal the kernel always di...
Kernel died with rasterio.open().read() on geo tiff images
When I tried to open and read a certain geo tiff image with gdal and rasterio, I can read and do things like img.meta and img.descriptions. But when I tried to do img.read() with rasterio or img.GetRasterBand(1).ReadAsArray() with gdal the kernel always died after a certain runtime. It's not happening to all geo tiff i...
[ "I had the same problem when reading large .tiff files.\nFollowing what @Val said in the comments I checked for how much free RAM memory I had as described here:\nimport psutil\npsutil.virtual_memory()\n\nAnd indeed my issue was that I was running out of RAM. You may try to use del arr once you're done with some ar...
[ 0 ]
[]
[]
[ "gdal", "gis", "kernel", "python", "rasterio" ]
stackoverflow_0068667679_gdal_gis_kernel_python_rasterio.txt
Q: Tools for automating windows applications (preferably in Python)? I have a legacy Windows application which performs a critical business function. It has no API or official support for automation. This program requires a human to perform a sequence of actions in order to convert files in a particular input format ...
Tools for automating windows applications (preferably in Python)?
I have a legacy Windows application which performs a critical business function. It has no API or official support for automation. This program requires a human to perform a sequence of actions in order to convert files in a particular input format into a PDF, from which we can scrape content and then process the data ...
[ "You have multiple options:\n1. winshell: A light wrapper around the Windows shell functionality\n2. Automa: Utilty to automate repetitive and/or complex task \n3: PyAutoGUI is a Python module for programmatically controlling the\nmouse and keyboard.\n4. Sikuli automates anything you see on the screen http://www.si...
[ 3, 3, 1, 0 ]
[]
[]
[ "automation", "python", "windows" ]
stackoverflow_0052832504_automation_python_windows.txt
Q: TypeError: is_legacy_optimizer is not a valid argument, kwargs should be empty for `optimizer_experimental.Optimizer` Please help me Code: from tensorflow.keras.models import load_model model_path = "model/classifier.h5" model = load_model(model_path) Error: TypeError: is_legacy_optimizer is not a valid argument,...
TypeError: is_legacy_optimizer is not a valid argument, kwargs should be empty for `optimizer_experimental.Optimizer`
Please help me Code: from tensorflow.keras.models import load_model model_path = "model/classifier.h5" model = load_model(model_path) Error: TypeError: is_legacy_optimizer is not a valid argument, kwargs should be empty for optimizer_experimental.Optimizer.
[ "It's possible that the model was trained using a different version of tf.\nTry confirming if the environment where you trained and are loading have the same tf version.\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0073538911_keras_python_tensorflow.txt
Q: Checking the type of variable in Jinja2 I want to check the type of variable in Jinja2. If it is type of variable is dictionary then I have to print some text in the paragraph and if it's not dict then I have to print some other values. What I tried here is {% if {{result}} is dict %} <tr> <td> <p> The details are...
Checking the type of variable in Jinja2
I want to check the type of variable in Jinja2. If it is type of variable is dictionary then I have to print some text in the paragraph and if it's not dict then I have to print some other values. What I tried here is {% if {{result}} is dict %} <tr> <td> <p> The details are not here </p> </td> </tr> {% else %} {% for ...
[ "You should replace {% if {{result}} is dict %} with {% if result is mapping %}.\nReference\n", "Alternative, and possibly better solutions:\n{% if result.__class__.__name__ == \"dict\" %}\nor add isinstance to Jinja context, and then\n{% if isinstance(result, dict) %}\n" ]
[ 1, 0 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0058264079_jinja2_python.txt
Q: I'm doing some basis conditional exercises, and I don't know what the % numbers mean in this code currentYear = int(input('Enter the year: ')) month = int(input('Enter the month: ')) if ((currentYear % 4) == 0 and (currentYear % 100) != 0 or (currentYear % 400) ==0): print('Leap Year') I have no idea what ...
I'm doing some basis conditional exercises, and I don't know what the % numbers mean in this code
currentYear = int(input('Enter the year: ')) month = int(input('Enter the month: ')) if ((currentYear % 4) == 0 and (currentYear % 100) != 0 or (currentYear % 400) ==0): print('Leap Year') I have no idea what the % numbers in the brackets with the currentYear means. I gather it has something to do with leap yea...
[ "The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.\nSo 100 % 5 == 0\nor\n100 % 3 == 1 ---> Remainder equals 1\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074677867_python.txt
Q: Render markdown files contain mermaid diagrams to a combined PDF file using mkdocs Currently, I'm using mkdocs-materialto use mermaid diagrams, configured as follows (in mkdocs.yml): ... markdown_extensions: - pymdownx.superfences: custom_fences: - name: mermaid class: mermaid ... However, I enc...
Render markdown files contain mermaid diagrams to a combined PDF file using mkdocs
Currently, I'm using mkdocs-materialto use mermaid diagrams, configured as follows (in mkdocs.yml): ... markdown_extensions: - pymdownx.superfences: custom_fences: - name: mermaid class: mermaid ... However, I encounter troubles with PDF exporting. I have tried several plugins. Most of them depend on...
[ "My current workaround\nRun: ENABLE_PDF_EXPORT=1 mkdocs build. Each markdown file will be exported to a PDF file.\nThen, I will define the order of all PDFs when merging into one unique file by putting the PDF name from top to bottom:\nIn chapters.txt:\nA.pdf\nB.pdf\nC.pdf\n...\n\nThen run the following script. Rem...
[ 0 ]
[]
[]
[ "mermaid", "mkdocs", "pdf", "python" ]
stackoverflow_0074602739_mermaid_mkdocs_pdf_python.txt
Q: How to drop rows of a column having float datatype and are values less than 1 I am new to pandas and I have just started to learn how to analyze a data. In order to explain y problem, Consider this table as df.csv Name Age Height A 2 5.7 B 4 5.4 C 8 5.9 D 4 0.6 From this file, I want to drop the row that has...
How to drop rows of a column having float datatype and are values less than 1
I am new to pandas and I have just started to learn how to analyze a data. In order to explain y problem, Consider this table as df.csv Name Age Height A 2 5.7 B 4 5.4 C 8 5.9 D 4 0.6 From this file, I want to drop the row that has Height less than 1 so that when i pass this command, it would delete t...
[ "dec = df[df['Height'] < 1.0].index\ndf.drop(dec, inplace=True)\n\nTrue and False are written in capital letters and the check is needed for 1 and not for 0.\n" ]
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074664750_csv_dataframe_pandas_python.txt
Q: Avro, Hive or HBASE - What to use for 10 mio. records daily? I have the following requirements: i need to process per day around 20.000 elements (lets call them baskets) which generate each between 100 and 1.000 records (lets call them products in basket). A single record has about 10 columns, each row has about 5...
Avro, Hive or HBASE - What to use for 10 mio. records daily?
I have the following requirements: i need to process per day around 20.000 elements (lets call them baskets) which generate each between 100 and 1.000 records (lets call them products in basket). A single record has about 10 columns, each row has about 500B - 1KB size (in total). That means, that i produce around 5 to ...
[ "If you want to analyze data based on columns and aggregates, ORC or Parquet are better. If you don't plan on managing Hadoop infrastructure, then Hive or HBase wouldn't be acceptable. I agree a SQL Server might struggle with large queries... Out of the options listed, that narrows it down to BigQuery.\nIf you want...
[ 0 ]
[]
[]
[ "avro", "hbase", "hive", "parquet", "python" ]
stackoverflow_0074655522_avro_hbase_hive_parquet_python.txt
Q: Circularity Calculation with Perimeter & Area of a Simple Circle Circularity signifies the comparability of the shape to a circle. A measure of circularity is the shape area to the circle area ratio having an identical perimeter (we denote it as Circle Area) as represented in equation below. Sample Circularity = S...
Circularity Calculation with Perimeter & Area of a Simple Circle
Circularity signifies the comparability of the shape to a circle. A measure of circularity is the shape area to the circle area ratio having an identical perimeter (we denote it as Circle Area) as represented in equation below. Sample Circularity = Sample Area / Circle Area Let the perimeter of shape be P, so P = 2 * p...
[ "As I mentioned in this recent answer to a related question, OpenCV's perimeter estimate is not good enough to compute the circularity feature. OpenCV computes the perimeter by adding up all the distances between vertices of the polygon built from the edge pixels of the image. This length is typically larger than t...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074580811_image_processing_opencv_python.txt
Q: updating options in optionmenu Tkinter I am currently writing on a small hobby projekt and i have a problem concerning my list "dice" while using the dropdown menu it only ever shows the first itteration of the list (the single 0) but it is sopposed to be updated in the dropdown menue after each press of the "rol...
updating options in optionmenu Tkinter
I am currently writing on a small hobby projekt and i have a problem concerning my list "dice" while using the dropdown menu it only ever shows the first itteration of the list (the single 0) but it is sopposed to be updated in the dropdown menue after each press of the "roll the dice" button. How do i do that? from r...
[ "Is this is what you want? I moved optionmenu into roll() function\nfrom random import randint\nfrom tkinter import *\n\nroot = Tk()\nroot.title('Hobbyprojekt')\n\ncount = -1\n#global dice\ndice = [0]\nprpp= IntVar() \ndiceshow=Label()\n#defining funtions for buttons \ndef roll():\n global count\n global dice...
[ 0 ]
[]
[]
[ "optionmenu", "python", "tkinter", "updating" ]
stackoverflow_0074625320_optionmenu_python_tkinter_updating.txt
Q: Python 3.11 base64 error " a bytes-like object is required, not 'list' " Im tryna make a very basic password manager kinda program that's about as basic as it gets and am using base64 to encode the passwords that are getting saved , but using ` encode = base64.b64encode(read_output).encode("utf-8") print("...
Python 3.11 base64 error " a bytes-like object is required, not 'list' "
Im tryna make a very basic password manager kinda program that's about as basic as it gets and am using base64 to encode the passwords that are getting saved , but using ` encode = base64.b64encode(read_output).encode("utf-8") print("Encrypted key: ",encode) decode = base64.b64decode(encode).decode("utf...
[ "You should first encode, then pass it to the function:\n(assuming read_output is of type list. It will also work with all of the basic types objects)\nencode = base64.b64encode(str(read_output).encode(\"utf-8\"))\nprint(\"Encrypted key: \",encode)\ndecode = base64.b64decode(encode).decode(\"utf-8\")\nprint(decode)...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074677941_python_python_3.x.txt
Q: How to view Gekko variables/parameters for debug purposes? I have a fitting task where I am using GEKKO. There are a lot of variables, arrays of variables, some variables that must contain arrays, and so on. I didn't have success with the fitting, so I need to do step-by-step verification of all parameters that I ...
How to view Gekko variables/parameters for debug purposes?
I have a fitting task where I am using GEKKO. There are a lot of variables, arrays of variables, some variables that must contain arrays, and so on. I didn't have success with the fitting, so I need to do step-by-step verification of all parameters that I am providing for GEKKO and all the calculated intermediate value...
[ "Turn up the DIAGLEVEL to 2 or higher to produce diagnostic files in the run directory m.path.\nfrom gekko import GEKKO\nm = GEKKO(remote=False)\nc = 2\nx = m.Param(3,name='x')\nro = m.Var(value=4,lb=0,ub=10,name='ro')\ny = m.Var()\nphi = m.Intermediate(c*ro,name='phi')\nm.Equation(y==phi**2+x)\nm.Maximize(y)\nm.op...
[ 1 ]
[]
[]
[ "gekko", "optimization", "python" ]
stackoverflow_0074677526_gekko_optimization_python.txt
Q: Assign group number for each row, based on columns value ranges I have some data, that needs to be clusterised into groups. That should be done by a few predifined conditions. Suppose we have the following table: d = {'ID': [100, 101, 102, 103, 104, 105], 'col_1': [12, 3, 7, 13, 19, 25], 'col_2': [3, 1, ...
Assign group number for each row, based on columns value ranges
I have some data, that needs to be clusterised into groups. That should be done by a few predifined conditions. Suppose we have the following table: d = {'ID': [100, 101, 102, 103, 104, 105], 'col_1': [12, 3, 7, 13, 19, 25], 'col_2': [3, 1, 3, 3, 2, 4] } df = pd.DataFrame(data=d) df.head() Here, I wan...
[ "Not sure I understand the full logic, can't you use pandas.cut:\nbins = [0, 10, 15, 20, np.inf]\ndf['group_num'] = pd.cut(df['col_1'], bins=bins,\n labels=range(1, len(bins)))\n\nOutput:\n ID col_1 col_2 group_num\n0 100 12 3 2\n1 101 3 1 1\n2 102 ...
[ 2, 2 ]
[]
[]
[ "group_by", "grouping", "lambda", "pandas", "python" ]
stackoverflow_0074677294_group_by_grouping_lambda_pandas_python.txt
Q: print contents of remaining tags after a tag beautifulsoup i just printed all the contents of li using .find_all('li') and i want to continue printing 'p' tags after li tag ends, like not 'p' tags in the beginning of html or inbetween. 'p' tags or remaining tags at the end. please help. Basically need everything a...
print contents of remaining tags after a tag beautifulsoup
i just printed all the contents of li using .find_all('li') and i want to continue printing 'p' tags after li tag ends, like not 'p' tags in the beginning of html or inbetween. 'p' tags or remaining tags at the end. please help. Basically need everything after final list-end tag. from bs4 import BeautifulSoup html_doc...
[ "You can try this:\nfor li in soup.select(\"li:not(li li)\"): \n print(\" \".join([\n d.get_text().strip() for d in li.descendants \n if 'NavigableString' in str(type(d)) and \n d.parent.name == 'li' and d.get_text().strip()\n ])) \n print(\"--sep--\")\n\n# for the p tags after ANY of ...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_3.x" ]
stackoverflow_0074677516_beautifulsoup_html_python_python_3.x.txt
Q: Python: Scheduling cron jobs with time limit? I have been using apscheduler. A recurring problem regarding the package is that if for any reason, a running job hangs indefinitely (for example if you create an infinite while loop inside of it) it will stop the whole process forever as there is no time limit option ...
Python: Scheduling cron jobs with time limit?
I have been using apscheduler. A recurring problem regarding the package is that if for any reason, a running job hangs indefinitely (for example if you create an infinite while loop inside of it) it will stop the whole process forever as there is no time limit option for the added jobs. Apscheduler has stated multiple...
[ "Based on the number of answers and my own research this is not currently possible with apscheduler. I have written my own quick implementation. The syntax is very similar to apscheduler, you just need to create a similar Scheduler object and add jobs to it with add_job, then use start. For my needs this has solved...
[ 0 ]
[]
[]
[ "apscheduler", "cron", "jobs", "multithreading", "python" ]
stackoverflow_0074524160_apscheduler_cron_jobs_multithreading_python.txt
Q: Tkinter canvas growing out of screen because of labels on canvas I have a tkinter canvas where I put labels on. When too much labels are added to the canvas it grows out of the screen. How do I set a max size on the canvas? middleCanvas = Canvas(window, bg="red", width=300, height=400) middleCanvas.grid(column=1,...
Tkinter canvas growing out of screen because of labels on canvas
I have a tkinter canvas where I put labels on. When too much labels are added to the canvas it grows out of the screen. How do I set a max size on the canvas? middleCanvas = Canvas(window, bg="red", width=300, height=400) middleCanvas.grid(column=1, row=3, sticky="N") scroll_y.grid(column=2, row=3, sticky="NS") midd...
[ "This also happened to me with buttons.\nYou can fix it by defining a WIDTH variable and set it to the size you want. Then set the Label width to the WIDTH variable.\nFor example:\nWIDTH = 5\nmessagelabel = Label(middleCanvas, text=\"A very, very, very very, very long string. \", width=WIDTH)\nmessagelabel.grid(co...
[ 1 ]
[]
[]
[ "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0074678075_python_tkinter_tkinter_canvas.txt
Q: Multiple URLs in multiple browsers in selenium (local) python I have a test script that I want to be run for multiple URLs on multiple browsers (Chrome and Firefox) locally on my machine. Every browser has to open all the URLs for the test script. I have run the test script for multiple URLs for multiple browsers....
Multiple URLs in multiple browsers in selenium (local) python
I have a test script that I want to be run for multiple URLs on multiple browsers (Chrome and Firefox) locally on my machine. Every browser has to open all the URLs for the test script. I have run the test script for multiple URLs for multiple browsers. I have the following code which do the task. Is there any better w...
[ "Here is one possible way to improve the code.\nimport time\nfrom selenium import webdriver\n\n\ndriver_array = [webdriver.Firefox(), webdriver.Chrome()]\nsites = [ \"http://www.github.com\", \"https://tribune.com.pk\"]\n\n\ndef get_storage_items(driver, storage_type):\n items = driver.execute_script(\n ...
[ 0 ]
[]
[]
[ "browser_automation", "cross_browser", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074678060_browser_automation_cross_browser_python_selenium_selenium_webdriver.txt
Q: Is it possible to create muti thread in a flask server? I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am trying to figure out a way to run the function in server in different threads. Here's my code sample: from flask_restx import Api,fields,Resource fro...
Is it possible to create muti thread in a flask server?
I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am trying to figure out a way to run the function in server in different threads. Here's my code sample: from flask_restx import Api,fields,Resource from flask import Flask app = Flask(__name__) api = Api(app) pa...
[ "I have the answer for you. to run a process in the background with flask, schedule it to run using another process using APScheduler. A very simple package that helps you schedule tasks to run functions at an interval, in your case one time at utcnow().\nhere is the link to Flask-APScheduler.\njob = scheduler.add_...
[ 0 ]
[]
[]
[ "flask", "flask_restx", "multithreading", "python", "threadpoolexecutor" ]
stackoverflow_0074672488_flask_flask_restx_multithreading_python_threadpoolexecutor.txt
Q: How to launch a project correctly? There is such a project https://github.com/WentianZhang-ML/FRT-PAD , I want to run it locally. At the very end it says that you can run as python train_main.py \ --train_data [om/ci] --test_data [ci/om] --downstream [FE/FR/FA] --graph_type [direct/dense] I try to run this file i...
How to launch a project correctly?
There is such a project https://github.com/WentianZhang-ML/FRT-PAD , I want to run it locally. At the very end it says that you can run as python train_main.py \ --train_data [om/ci] --test_data [ci/om] --downstream [FE/FR/FA] --graph_type [direct/dense] I try to run this file in juputer, but I get SystemExit: 2
[ "Some simple options for running a python script in jupyter:\nOption 1: Open a terminal in Jupyter, and run your Python scripts in the terminal like you would in your local terminal.\nOption 2: Make a notebook, and use %run <name of script.py> as an entry in a cell. This is more fully featured than using !python <n...
[ 0 ]
[]
[]
[ "machine_learning", "python" ]
stackoverflow_0074678074_machine_learning_python.txt
Q: Cannot run python program in Vs code you just know it by seeing the picture I don't know what to do... I tried many things from google tried putting the same file path to launcher.json but nothing worked even tried reinstalling the whole visual studio code As asked adding launch.json file code: launch.json code A...
Cannot run python program in Vs code
you just know it by seeing the picture I don't know what to do... I tried many things from google tried putting the same file path to launcher.json but nothing worked even tried reinstalling the whole visual studio code As asked adding launch.json file code: launch.json code
[ "Have you tried using the generic configuration for running a currently open file?\n \"configurations\": [\n {\n \"name\": \"Python: Current File\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${file}\",\n \"console\": \"integr...
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074677714_python_visual_studio_code.txt
Q: Plotly timeline with objects In the below example, I would like to group the elements of y axis by continent, and to display the name of the continent at the top of each group. I can't figure out in the layout where we can set it. the example come from this plotly page import pandas as pd import plotly.graph_objec...
Plotly timeline with objects
In the below example, I would like to group the elements of y axis by continent, and to display the name of the continent at the top of each group. I can't figure out in the layout where we can set it. the example come from this plotly page import pandas as pd import plotly.graph_objects as go from plotly import data ...
[ "To show grouping by continent instead of the code you showed would require looping through the data structure from dictionary format to data frame. y-axis by continent by specifying a multi-index for the y-axis.\nI have limited myself to the top 5 countries by continent because the large number of categorical vari...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074677111_plotly_python.txt
Q: What does print()'s `flush` do? There is a boolean optional argument to the print() function flush which defaults to False. The documentation says it is to forcibly flush the stream. I don't understand the concept of flushing. What is flushing here? What is flushing of stream? A: Normally output to a file or the...
What does print()'s `flush` do?
There is a boolean optional argument to the print() function flush which defaults to False. The documentation says it is to forcibly flush the stream. I don't understand the concept of flushing. What is flushing here? What is flushing of stream?
[ "Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.\nI do use it e.g. when I make a user prompt like Do you want to continue (Y/n):, before getting the input.\nThis can be simulated...
[ 43, 40, 6, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0015608229_python_python_3.x.txt
Q: Changing multiple while statements using defined functions? Python code where user inputs surname, forename that must be certain length and wont accept numeric values. I'm creating code for a website to get a user to input various questions like name, address, phone number etc. my code is working currently for eac...
Changing multiple while statements using defined functions?
Python code where user inputs surname, forename that must be certain length and wont accept numeric values. I'm creating code for a website to get a user to input various questions like name, address, phone number etc. my code is working currently for each question, but every question is a while statement and I wanted ...
[ "You can modify the function like this:\ndef name_check(name):\n while True:\n if len(name) < 15 and name.isalpha():\n break\n else:\n print('invalid')\n name = input(\"First Name:\\t\")\n continue\n return name\n\nresult = name_check(input(\"First Nam...
[ 0 ]
[]
[]
[ "python", "python_3.x", "user_defined_functions", "while_loop" ]
stackoverflow_0074678022_python_python_3.x_user_defined_functions_while_loop.txt
Q: Have you ever get RuntimeError: await wasn't used with future? trying to extract data from a website by using asyncio and aiohttp, and AWAIT problem occur in for loop function. here my script : async def get_page(session,x): async with session.get(f'https://disclosure.bursamalaysia.com/FileAccess/viewHtml?e={x...
Have you ever get RuntimeError: await wasn't used with future?
trying to extract data from a website by using asyncio and aiohttp, and AWAIT problem occur in for loop function. here my script : async def get_page(session,x): async with session.get(f'https://disclosure.bursamalaysia.com/FileAccess/viewHtml?e={x}') as r: return await r.text() async def get_all(sessi...
[ "You can use multiprocessing to scrape multiple link simultaneously(parallelly):\nfrom multiprocessing import Pool\n \ndef scrape(url):\n #Scraper script\n\np = Pool(10)\n# This “10” means that 10 URLs will be processed at the same time.\np.map(scrape, list_of_all_urls)\np.terminate()\np.join()\n\n\nHere we m...
[ 0, 0 ]
[]
[]
[ "async_await", "asynchronous", "python" ]
stackoverflow_0068563801_async_await_asynchronous_python.txt
Q: How to run two processes with dockerfile? I need to run uvicorn server process and my python script (which is another process). Since uvicorn start a process that doesn't end, the second command will not start. So i ask you if you know some workaround to overcome this problem. I tried to do this command: CMD cd Ma...
How to run two processes with dockerfile?
I need to run uvicorn server process and my python script (which is another process). Since uvicorn start a process that doesn't end, the second command will not start. So i ask you if you know some workaround to overcome this problem. I tried to do this command: CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 -...
[ "Create a wrapper script, e.g. run.sh:\n#!/bin/bash\n\n# Start the first process\nuvicorn ManagerBot:app --host 0.0.0.0 --port 8000 &\n \n# Start the second process\npython ManagerBot.py &\n \n# Wait for any process to exit\nwait -n\n \n# Exit with status of process that exited first\nexit $?\n\nThen, in Dockerf...
[ 1 ]
[]
[]
[ "command", "docker", "dockerfile", "python", "server" ]
stackoverflow_0074678353_command_docker_dockerfile_python_server.txt
Q: Converting list of dictionary and dictionay data to a dataframe in python I am trying to send a SOAP request and iteratively and the response captured for each iteration is as follows. df = {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO...
Converting list of dictionary and dictionay data to a dataframe in python
I am trying to send a SOAP request and iteratively and the response captured for each iteration is as follows. df = {'@diffgr:id': 'Table1', '@msdata:rowOrder': '0', 'NVIC_CUR': '0BQU22', 'NVIC_MODEL': '0BQU', 'ModelName': 'DIESEL TWIN TURBO 4 1996 cc BTCDI 10 SP AUTOMATIC'} {'@diffgr:id': 'Table1', '@msdata:rowOrder':...
[ "You can do it by this three-step-\n\nYou can append each SOAP API response to either its dictionary or a list to a new python list, let's say its called - list_of_dict, and\n\nThen iterate it and append it to a new list let's call it final_list_of_dict if it's a dictionary else iterate it again if a listlike below...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074678229_dictionary_list_python.txt
Q: Error When Trying to Calculate FLOPS for Complex TF2 Keras Models I want to calculate the FLOPS in the ML models used. I get an error when I tried to calculate for much complex models. I get this Error for Efficientnet Models: ValueError: Unknown layer: FixedDropout. Please ensure this object is passed to the `cus...
Error When Trying to Calculate FLOPS for Complex TF2 Keras Models
I want to calculate the FLOPS in the ML models used. I get an error when I tried to calculate for much complex models. I get this Error for Efficientnet Models: ValueError: Unknown layer: FixedDropout. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_...
[ "In the first function, you are using the convert_variables_to_constants_v2_as_graph function from TensorFlow to convert the model to a graph. This function has a custom_objects parameter that you can use to pass the custom layers that the model uses. You can add the FixedDropout layer to this parameter to fix the ...
[ 0 ]
[]
[]
[ "computer_vision", "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074675233_computer_vision_keras_machine_learning_python_tensorflow.txt
Q: Unable to install discord py with pip i have python 3.11 downloaded, and i installed pip with it. however, i can't install discord py with py -3 -m pip install -U discord.py i've tried a few other ways, still didn't work. in the end it says: note: This error originates from a subprocess, and is likely not a prob...
Unable to install discord py with pip
i have python 3.11 downloaded, and i installed pip with it. however, i can't install discord py with py -3 -m pip install -U discord.py i've tried a few other ways, still didn't work. in the end it says: note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building whee...
[ "Hmmm, it seems it might be a problem due to dependencies to yarl and multidict (happens). I've had the same problem with itertools, and even opencv taking extremely long to build with a non-upgraded pip version!\nHave you tried upgrading pip? Same problem with those libraries' dependencies.\npip3 install --upgrade...
[ 1, 1, 0, 0 ]
[]
[]
[ "cmd", "discord", "discord.py", "installation", "python" ]
stackoverflow_0074617360_cmd_discord_discord.py_installation_python.txt
Q: Imported module not found in PyInstaller I'm working in Windows, using PyInstaller to package a python file. But some error is occuring: Traceback (most recent call last): File "<string>", line 2, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 386, in importHook mod = _sel...
Imported module not found in PyInstaller
I'm working in Windows, using PyInstaller to package a python file. But some error is occuring: Traceback (most recent call last): File "<string>", line 2, in <module> File "D:\Useful Apps\pyinstaller-2.0\PyInstaller\loader\iu.py", line 386, in importHook mod = _self_doimport(nm, ctx, fqname) File "D:\Useful ...
[ "If you are using virtualenv you should use the \"-p\" or \"--path='D:...'\" option. Like this:\npyinstaller.exe --onefile --paths=D:\\env\\Lib\\site-packages .\\foo.py\n\nWhat this does is generates foo.spec file with this pathex path\n", "This sounds like a job for hidden imports (only available in the latest ...
[ 19, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "exe", "pyinstaller", "python", "sockets", "windows" ]
stackoverflow_0015114695_exe_pyinstaller_python_sockets_windows.txt
Q: How to extract certain letters from a string using Python I have a string 'A1T1730' From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python. I have the following right now which extracts every char...
How to extract certain letters from a string using Python
I have a string 'A1T1730' From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python. I have the following right now which extracts every character from the string separately so can someone please help me ...
[ "my_string = \"A1T1730\"\nmy_string = my_string[1] + my_string[-4:]\nprint my_string\n\nOutput\n11730\n\nIf you want to extract them to different variables, you can just do\nfirst, last = my_string[1], my_string[-4:]\nprint first, last\n\nOutput\n1 1730\n\n", "Using filter with str.isdigit (as unbound method form...
[ 5, 4, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0021187124_list_python.txt
Q: Pandas: sort_index - help understanding 'key' argument I am trying to sort a complex index (weird strings, with a custom order). I originally tried to do this, but its messing up the index (because its overwriting, not actually sorting) df.index = list(sorted(df.index, key=Delta_Sorter.sort)) # <--Delta_Sorter.sor...
Pandas: sort_index - help understanding 'key' argument
I am trying to sort a complex index (weird strings, with a custom order). I originally tried to do this, but its messing up the index (because its overwriting, not actually sorting) df.index = list(sorted(df.index, key=Delta_Sorter.sort)) # <--Delta_Sorter.sort is a classmethod Instead, I should probably be using Pand...
[]
[]
[ "Syntax: DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, sort_remaining=True, by=None)\nParameters :\naxis : index, columns to direct sorting\nlevel : if not None, sort on values in specified index level(s)\nascending : Sort ascending vs. descending\ninp...
[ -2 ]
[ "pandas", "python" ]
stackoverflow_0074678401_pandas_python.txt
Q: TypeError:run() missing 1 required positional argument: 'self' I wrote a simple program in pycharm on Windows, then it ran. In order to get the apk file, I installed ubuntu on a virtual machine. Then I installed pip, paycharm, kivy. Qivy installed through the terminal according to the instructions with their site....
TypeError:run() missing 1 required positional argument: 'self'
I wrote a simple program in pycharm on Windows, then it ran. In order to get the apk file, I installed ubuntu on a virtual machine. Then I installed pip, paycharm, kivy. Qivy installed through the terminal according to the instructions with their site. I typed the code and got an error:run() missing 1 required position...
[ "the .kv file does not support multi-line entries so far as I know. The method on_release needs to reference a function and you would normally put that in the widget (root.your_function) or app (app.your_function). I changed the answer to use build_string only for convenience; it is a good idea to use a separate ...
[ 0 ]
[]
[]
[ "kivy", "python", "ubuntu" ]
stackoverflow_0074673204_kivy_python_ubuntu.txt
Q: pickle data was truncated i created a corpus file then stored in a pickle file. my messages file is a collection of different news articles dataframe. from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer import re ps = PorterStemmer() corpus = [] for i in range(0, len(messages)): review...
pickle data was truncated
i created a corpus file then stored in a pickle file. my messages file is a collection of different news articles dataframe. from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer import re ps = PorterStemmer() corpus = [] for i in range(0, len(messages)): review = re.sub('[^a-zA-Z]', ' ', mes...
[ "i would use pickle file created by my local machine only, that works properly\n", "problem occurs due to partial download of glove vectors i have uploaded the data\nthrough colab upload to session storage and after that simply write this command\nit works very well.\nwith open('/content/glove_vectors', 'rb') as ...
[ 0, 0 ]
[]
[]
[ "data_science", "data_science_experience", "pickle", "python" ]
stackoverflow_0061718355_data_science_data_science_experience_pickle_python.txt
Q: Creating threaded popups in PySimpleGUI I have trouble creating either multiple windows or popups using PySimpleGUI. Each window/popup is supposed to be called from a seperate thread and timeout after 2 seconds. Using following implementation results in (as expected) this error: main thread is not in main loop. Ho...
Creating threaded popups in PySimpleGUI
I have trouble creating either multiple windows or popups using PySimpleGUI. Each window/popup is supposed to be called from a seperate thread and timeout after 2 seconds. Using following implementation results in (as expected) this error: main thread is not in main loop. How do I fix that? def get_info(): while Tr...
[ "This isn't possible because PySimpleGUI is not thread-safe. This means that you can only use it in the main thread of your program.\nTo fix this error, you can use a queue to communicate between the main thread and the other threads. Each thread can add an event to the queue, and the main thread can read from the ...
[ 1 ]
[]
[]
[ "multithreading", "pysimplegui", "python", "user_interface" ]
stackoverflow_0074678475_multithreading_pysimplegui_python_user_interface.txt
Q: How can I write this sql query in django orm? I have a sql query that works like this, but I couldn't figure out how to write this query in django. Can you help me ? select datetime, array_to_json(array_agg(json_build_object(parameter, raw))) as parameters from dbp_istasyondata group by 1 order by 1; ...
How can I write this sql query in django orm?
I have a sql query that works like this, but I couldn't figure out how to write this query in django. Can you help me ? select datetime, array_to_json(array_agg(json_build_object(parameter, raw))) as parameters from dbp_istasyondata group by 1 order by 1;
[ "You can use raw function of django orm. You can write your query like this:\nYourModel.objects.raw('select * from your table'): #---> Change the model name and query\n\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0074678065_django_django_models_django_orm_python.txt
Q: How to make a movie out of images in python I currently try to make a movie out of images, but i could not find anything helpful . Here is my code so far: import time from PIL import ImageGrab x =0 while True: try: x+= 1 ImageGrab().grab().save('img{}.png'.format(str(x)) except: ...
How to make a movie out of images in python
I currently try to make a movie out of images, but i could not find anything helpful . Here is my code so far: import time from PIL import ImageGrab x =0 while True: try: x+= 1 ImageGrab().grab().save('img{}.png'.format(str(x)) except: movie = #Idontknow for _ in range(x): ...
[ "You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.\nI'm attaching below a code snipped I used to combine all png files from a folder called \"images\" into a video.\nimport...
[ 147, 54, 29, 16, 1, 0, 0 ]
[]
[]
[ "image", "python", "screenshot", "video" ]
stackoverflow_0044947505_image_python_screenshot_video.txt
Q: How to store data in seperate memory mdoules I'm working on an image processing pipeline in Python and I'm using Cython for the main computation so that it can run really fast. From early benchmarks, I found a memory bottleneck where the code would not scale at all using multiple threads. I revised the algorithm a...
How to store data in seperate memory mdoules
I'm working on an image processing pipeline in Python and I'm using Cython for the main computation so that it can run really fast. From early benchmarks, I found a memory bottleneck where the code would not scale at all using multiple threads. I revised the algorithm a bit to reduce the bandwidth required and now it s...
[ "The OS manages splitting the program virtual address space to the different physical addresses (Ram sticks, pagefile, etc) this is transparent to python or any programming language, all systems were already using both sticks for read and write.\nThe fact that both float64 and float32 have the same performance mean...
[ 2 ]
[]
[]
[ "memory", "memory_management", "multithreading", "python" ]
stackoverflow_0074678047_memory_memory_management_multithreading_python.txt
Q: use Elasticsearch, for h in one['hits']['hits']: KeyError: 'hits' the es codeenter image description here wrong error I use above code to do elasticsearch, but meet the wrong error, for h in one['hits']['hits']: KeyError: 'hits' A: It looks like you are trying to iterate through the hits returned by an Elasticse...
use Elasticsearch, for h in one['hits']['hits']: KeyError: 'hits'
the es codeenter image description here wrong error I use above code to do elasticsearch, but meet the wrong error, for h in one['hits']['hits']: KeyError: 'hits'
[ "It looks like you are trying to iterate through the hits returned by an Elasticsearch query, but the hits key is not present in the one dictionary. This is likely because your Elasticsearch query did not return any results, or because there was an error in the query itself.\nIf you want to iterate through the hits...
[ 0 ]
[]
[]
[ "data_retrieval", "elasticsearch", "http", "information_retrieval", "python" ]
stackoverflow_0074665990_data_retrieval_elasticsearch_http_information_retrieval_python.txt
Q: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed Complete Error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers...
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed
Complete Error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'webservice_again.CustomUser' that has not been installed model.py from builtins import ValueError from datetime import date imp...
[ "By default django looks for models in models.py. Try changing model.py file to models.py. If you somehow have a models folder which houses all your model files, then import the CustomUser model in __init__.py file located within the models folder. This should solve it!\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_users", "python" ]
stackoverflow_0055203871_django_django_models_django_users_python.txt
Q: Celery worker running tensorflow unable to create CUDA event I am loading tensorflow model to the celery worker but when I try to run a task on the worker, it shows the following error: [2018-09-19 10:29:39,753: INFO/MainProcess] Received task: analyze_atom[f6bb76cc-aa16-4761-a7cf-0ed111886ff8] [2018-09-19 10:29...
Celery worker running tensorflow unable to create CUDA event
I am loading tensorflow model to the celery worker but when I try to run a task on the worker, it shows the following error: [2018-09-19 10:29:39,753: INFO/MainProcess] Received task: analyze_atom[f6bb76cc-aa16-4761-a7cf-0ed111886ff8] [2018-09-19 10:29:41,198: WARNING/ForkPoolWorker-2] paper checkpoint1 takes 1.43330...
[ "Changing things to single-threaded is an easy fix. You can resolve this issue by adding -P solo to your celery command\ni.e:\ncelery -app APP worker -P solo --loglelvel=info\n\nNote: APP is your app name.\n" ]
[ 0 ]
[]
[]
[ "celery", "python", "tensorflow" ]
stackoverflow_0052397450_celery_python_tensorflow.txt
Q: How to send json formatted messages to Slack through Cloud functions? I am trying to send a json formatted message to Slack through a Cloud function using slack_sdk, if I send it like this (not formatted) it works. client = WebClient(token='xoxb-25.......') try: response = client.chat_postMessage(chann...
How to send json formatted messages to Slack through Cloud functions?
I am trying to send a json formatted message to Slack through a Cloud function using slack_sdk, if I send it like this (not formatted) it works. client = WebClient(token='xoxb-25.......') try: response = client.chat_postMessage(channel='#random', text=DICTIONARY) I found the documentation on Slack that cha...
[ "Bit late, but I hope this can help others who stumble upon this issue in the future.\nI think that you've misunderstood the documentation. The JSON support allows for accepting POST message bodies in JSON format, as only application/x-www-form-urlencoded format was supported earlier. Read more here.\nTo answer you...
[ 0 ]
[]
[]
[ "google_cloud_functions", "python", "slack", "slack_api" ]
stackoverflow_0073580490_google_cloud_functions_python_slack_slack_api.txt
Q: open cv can't open/read file: check file path/integrity I am creating a face detection algorithm which should take in images from a folder as input but I get this error: import dlib import argparse import cv2 import sys import time import process_dlib_boxes # construct the argument parser parser = argparse.Argum...
open cv can't open/read file: check file path/integrity
I am creating a face detection algorithm which should take in images from a folder as input but I get this error: import dlib import argparse import cv2 import sys import time import process_dlib_boxes # construct the argument parser parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', default=r"C:...
[ "I assume the problem is that cv2.imread is returning None because it is unable to read the input image. This can happen if the file path provided to cv2.imread is incorrect or if the file does not exist.\nYou can try printing the value of args['input'] to make sure it is correct and points to a valid image file. Y...
[ 0, 0 ]
[]
[]
[ "cv2", "file", "path", "python" ]
stackoverflow_0074677763_cv2_file_path_python.txt
Q: Create a nested list object with an arbitrary depth I want to create a nested list object. In this way, the user enters a positive integer, then add empty lists to the initial list, equal to the number entered by the user. The second list should be added to the first list, the third list should be added to the sec...
Create a nested list object with an arbitrary depth
I want to create a nested list object. In this way, the user enters a positive integer, then add empty lists to the initial list, equal to the number entered by the user. The second list should be added to the first list, the third list should be added to the second list, the fourth list should be added to the third li...
[ "a = []\nfor _ in range(x):\n a = [a]\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074678460_python.txt
Q: Rollback to specific version of a python package in Goolge Colab I've read that rolling back rpy2 version to v3.4.2 fixed the problem (in this case Rpy2 Error depends on execution method: NotImplementedError: Conversion "rpy2py" not defined, but it could be any problem) How can I change the installed version of ...
Rollback to specific version of a python package in Goolge Colab
I've read that rolling back rpy2 version to v3.4.2 fixed the problem (in this case Rpy2 Error depends on execution method: NotImplementedError: Conversion "rpy2py" not defined, but it could be any problem) How can I change the installed version of the python package rpy2 to version v3.4.2 in Google Colab? I know the ...
[ "!pip install -Iv rpy2==3.4.2\n\nworked for me as explained in https://stackoverflow.com/a/5226504/7735095\n" ]
[ 0 ]
[]
[]
[ "google_colaboratory", "python", "version" ]
stackoverflow_0074678556_google_colaboratory_python_version.txt
Q: Mypy is not able to find an attribute defined in the parent NamedTuple In my project I'm using Fava. Fava, is using Beancount. I have configured Mypy to read the stubs locally by setting mypy_path in mypy.ini. Mypy is able to read the config. So far so good. Consider this function of mine 1 def get_units(postings:...
Mypy is not able to find an attribute defined in the parent NamedTuple
In my project I'm using Fava. Fava, is using Beancount. I have configured Mypy to read the stubs locally by setting mypy_path in mypy.ini. Mypy is able to read the config. So far so good. Consider this function of mine 1 def get_units(postings: list[Posting]): 2 numbers = [] 3 for posting in postings: 4 nu...
[ "The type of units isn't Amount:\nclass Posting(NamedTuple):\n account: Account\n units: Union[Amount, Type[MISSING]]\n\nIt's Union[Amount, Type[MISSING]], exactly like the error message says. And if it's Type[MISSING] there is no number attribute, exactly like the error message says. If you were to run thi...
[ 3 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0074678602_mypy_python.txt
Q: How to assign dynamic variables calling from a function in python I have a function which does a bunch of stuff and returns pandas dataframes. The dataframe is extracted from a dynamic list and hence I'm using the below method to return these dataframes. As soon as I call the function (code in 2nd block), my jupyt...
How to assign dynamic variables calling from a function in python
I have a function which does a bunch of stuff and returns pandas dataframes. The dataframe is extracted from a dynamic list and hence I'm using the below method to return these dataframes. As soon as I call the function (code in 2nd block), my jupyter notebook just runs the cell infinitely like some infinity loop. Any ...
[ "for each dataframe object your code is creating you can simply add it to a dictionary and set the key from your dynamic list.\nHere is a simple example:\nimport pandas as pd\n\ntest_data = {\"key1\":[1, 2, 3], \"key2\":[1, 2, 3], \"key3\":[1, 2, 3]}\ndf = pd.DataFrame.from_dict(test_data)\n\ndataframe example:\n ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074672341_pandas_python.txt
Q: How to perform a mathematical operation on two instances of object in Django? I want to add two numbers from two different objects. Here is a simplified version. I have two integers and I multiply those to get multiplied . models.py: class ModelA(models.Model): number_a = models.IntegerField(default=1, null=Tr...
How to perform a mathematical operation on two instances of object in Django?
I want to add two numbers from two different objects. Here is a simplified version. I have two integers and I multiply those to get multiplied . models.py: class ModelA(models.Model): number_a = models.IntegerField(default=1, null=True, blank=True) number_b = models.IntegerField(default=1, null=True, blank=True...
[ "In your template, when you do a forloop over the numbers variable, you can directly access properties, functions and attributes.\nSo to access the value you want I guess it would look something like this, simplified:\n{% for number in numbers %}\n {{ number.multiplied }}\n{% endfor %}\n\nHope that makes sense?\...
[ 2, 1, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074678108_django_django_templates_python.txt
Q: File is not showing when applying rasterio.open() Here is my code refPath = '/Users/admin/Downloads/Landsat8/' ext = '_NDWI.tif' for file in sorted(os.listdir(refPath)): if file.endswith(ext): print(file) ndwiopen = rs.open(file) ndwiread = ndwiopen.read(1) Here is the error 2014_NDW...
File is not showing when applying rasterio.open()
Here is my code refPath = '/Users/admin/Downloads/Landsat8/' ext = '_NDWI.tif' for file in sorted(os.listdir(refPath)): if file.endswith(ext): print(file) ndwiopen = rs.open(file) ndwiread = ndwiopen.read(1) Here is the error 2014_NDWI.tif -------------------------------------------------...
[ "Unsure if this is your exact problem, but I rammed my head against this same exact error for 5-10 hours before I realized that the '.tif' file I was trying to read had an extension in all caps, as in '.TIF'. This is apparently the default for the Landsat 8 image bands that I was working with.\nI was doing similar ...
[ 0 ]
[]
[]
[ "image", "python", "rasterio" ]
stackoverflow_0073506395_image_python_rasterio.txt
Q: Deleting a key in a dictionary submission How would I go about in deleting a specified key within a Dictionary based on the following condition?[enter image description here Deleting a key in a dictionary
Deleting a key in a dictionary submission
How would I go about in deleting a specified key within a Dictionary based on the following condition?[enter image description here Deleting a key in a dictionary
[]
[]
[ "thisdict = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\ndel thisdict[\"model\"]\nprint(thisdict)\n\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0074678640_python.txt
Q: FLL Python - running two commands at once I am helping coach First Lego League (FLL) and this year with the SPIKE robot they allow us to use Python to command the robot. We used to be able (using Scratch style coding) to have the robot do two things at once, like drive forward and raise attachement. But with Pytho...
FLL Python - running two commands at once
I am helping coach First Lego League (FLL) and this year with the SPIKE robot they allow us to use Python to command the robot. We used to be able (using Scratch style coding) to have the robot do two things at once, like drive forward and raise attachement. But with Python everything is sequential. How could we have i...
[ "To run two processes at once in python, you can use the multiprocessing module to create separate processes for each command and run them simultaneously.\nimport multiprocessing\n\ndef run_command1():\n # code for command1\n\ndef run_command2():\n # code for command2\n\nif __name__ == '__main__':\n p1 = m...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074678613_python.txt
Q: when I go to scrapy to convert my web scraping data to csv! No matter how many rows I have. In just one row, the data of all rows is being inserted import scrapy from ..items import AmazondawinItem class AmazonspiderSpider(scrapy.Spider): name = 'amazon' pagenumber = 3 allowed_domains = ['amazon.com']...
when I go to scrapy to convert my web scraping data to csv! No matter how many rows I have. In just one row, the data of all rows is being inserted
import scrapy from ..items import AmazondawinItem class AmazonspiderSpider(scrapy.Spider): name = 'amazon' pagenumber = 3 allowed_domains = ['amazon.com'] start_urls = [ 'https://www.amazon.com/s?k=laptop&i=computers&crid=27GFGJVF4KNRP&sprefix=%2Ccomputers%2C725&ref=nb_sb_ss_recent_1_0_recent' ...
[ "It's because you're yielding all the items instead of yielding each item separately.\nA not so nice solution:\nimport scrapy\n# from ..items import AmazondawinItem\n\n\nclass AmazonspiderSpider(scrapy.Spider):\n name = 'amazon'\n pagenumber = 3\n allowed_domains = ['amazon.com']\n start_urls = [\n ...
[ 0 ]
[]
[]
[ "python", "scrapy", "web_crawler", "web_scraping" ]
stackoverflow_0074671535_python_scrapy_web_crawler_web_scraping.txt
Q: How to disable Neptune callback in transformers trainer runs? After installing Neptune.ai for occasional ML experiments logging, it became included by default into the list of callbacks in all transformers.trainer runs. As a result, it requires proper initialisation with token or else throws NeptuneMissingConfigur...
How to disable Neptune callback in transformers trainer runs?
After installing Neptune.ai for occasional ML experiments logging, it became included by default into the list of callbacks in all transformers.trainer runs. As a result, it requires proper initialisation with token or else throws NeptuneMissingConfiguration error, demanding token and project name. This is really annoy...
[ "To disable Neptune callback in transformers trainer runs, you can pass the --no-neptune flag to the trainer.train() function.\ntrainer = Trainer(\n model=model,\n args=args,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n no_neptune=True\n)\ntrainer.train()\n\n", "Apparently this pie...
[ 0, 0 ]
[]
[]
[ "callback", "huggingface_transformers", "neptune", "python", "pytorch" ]
stackoverflow_0074678703_callback_huggingface_transformers_neptune_python_pytorch.txt
Q: Tkinter - How to disable button when window opened I'm new to the 'Tkinter' library and I wanted to know how to disable a button when a new window has been opened. For example, if a button on the main window is clicked, a new window will open, and all buttons on the main window will be disabled. After the window i...
Tkinter - How to disable button when window opened
I'm new to the 'Tkinter' library and I wanted to know how to disable a button when a new window has been opened. For example, if a button on the main window is clicked, a new window will open, and all buttons on the main window will be disabled. After the window is closed, the buttons should be re-enabled again. Here's...
[ "You can hide window\nroot.withdraw()\n\n# or \n\nroot.iconify()\n\nand show again\nroot.deiconify()\n\n\nTo disable button \nb['state'] = 'disabled' \n\nTo enable button \nb['state'] = 'normal'\n\n\nEDIT: as @acw1668 noted in comment it needs win.protocol() to run close_second when user used closing button [X] on ...
[ 1, 0 ]
[ "Welcome to Tkinter Library.\nI done why you are using that 'w' you can just use root and it work.\nfrom tkinter import *\nroot = Tk()\n\ndef z():\n\n bu = Button(root, text = \"Click!\", font = 'bold')\n bu.pack()\n\nb = Button(root, text = \"Click!\", command = z)\nb.pack()\n\nroot.mainloop()\n\nAsk me if y...
[ -3 ]
[ "python", "python_3.x", "tk_toolkit", "tkinter" ]
stackoverflow_0060470329_python_python_3.x_tk_toolkit_tkinter.txt
Q: How to animate object color changing with Manim? I want to animate Dot object to periodically change its color. Something like this: I've only found AnimatedBoundary class but it changes only the object's boundary (as the name says ofc). Is there any way to achieve that with already existing tools? A: Maybe som...
How to animate object color changing with Manim?
I want to animate Dot object to periodically change its color. Something like this: I've only found AnimatedBoundary class but it changes only the object's boundary (as the name says ofc). Is there any way to achieve that with already existing tools?
[ "Maybe something like this could work for you\nclass ColoredDot(Scene):\n def construct(self):\n \n tracker = ValueTracker(0)\n \n def update_color(obj):\n T=tracker.get_value()\n rgbcolor=[1,1-T,0+T]\n m_color=rgb_to_color(rgbcolor)\n upd_dot=Dot(c...
[ 2, 0 ]
[]
[]
[ "colors", "manim", "python" ]
stackoverflow_0067693569_colors_manim_python.txt
Q: How to assign a "null" value from another column? I would like to create a new column called "season_new", where I want to maintain the non-null season and extract the season for null values from the programme name. My dataframe is something like this: programme season grey's anatomy s1 null friends season 1 1 ...
How to assign a "null" value from another column?
I would like to create a new column called "season_new", where I want to maintain the non-null season and extract the season for null values from the programme name. My dataframe is something like this: programme season grey's anatomy s1 null friends season 1 1 grey's anatomy s2 null big bang theory s2 2 ...
[ "When trying your code, for some reason the regex didn't return only the integers:\n0 grey's anatomy s1 NaN s1\n1 friends season 1 1.0 season 1\n2 grey's anatomy s2 NaN s2\n3 big bang theory s2 2.0 s2\n4 big bang theory 1.0 NaN\n5 peaky blinders ...
[ 0, 0 ]
[ "You can use pandas.Series.fillna since this one accepts Series as a value.\n\nvalue: scalar, dict, Series, or DataFrame\n\nTry this :\ndt['season_new'] = (\n dt['programme']\n .str.extract(r'[season\\s?|s](\\d+)', expand=False)\n .fillna(dt['season']...
[ -1, -1 ]
[ "pandas", "python", "regex" ]
stackoverflow_0074677738_pandas_python_regex.txt
Q: how to apply Slack app_home_opened event in Python Flask Slack App I am currently working on Slack Event API to show the Home tab in the existed Slack App. So, I am struggling to implement app_home_opened from the Slack Event API to the app. The app is developed by Python Flask. And when I tried to show home tab i...
how to apply Slack app_home_opened event in Python Flask Slack App
I am currently working on Slack Event API to show the Home tab in the existed Slack App. So, I am struggling to implement app_home_opened from the Slack Event API to the app. The app is developed by Python Flask. And when I tried to show home tab in the dummy app which is not using flask, it was succeed. But I want to ...
[ "Something like this should work.\nimport os\nfrom slack_bolt import App\n\n...\n\napp = App(token=os.environ.get(\"SLACK_BOT_TOKEN\"))\n\n...\n\n@app.event(\"app_home_opened\")\ndef update_home_tab(client, event, logger):\n try:\n client.views_publish(\n user_id=event[\"user\"],\n view={\n \"t...
[ 0 ]
[]
[]
[ "flask", "python", "slack", "slack_api", "slack_block_kit" ]
stackoverflow_0073482118_flask_python_slack_slack_api_slack_block_kit.txt
Q: NonUniformImage: numpy example gives 'cannot unpack non-iterable NoneType object' error 2D-Histogram I'm trying to run this very simple example from numpy page regarding histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html. from matplotlib.image import NonUniformImage import matplot...
NonUniformImage: numpy example gives 'cannot unpack non-iterable NoneType object' error 2D-Histogram
I'm trying to run this very simple example from numpy page regarding histogram2d: https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html. from matplotlib.image import NonUniformImage import matplotlib.pyplot as plt xedges = [0, 1, 3, 5] yedges = [0, 2, 3, 4, 6] x = np.random.normal(2, 1, 100) y = np.r...
[ "The full error message is:\nTypeError Traceback (most recent call last)\nFile ~\\anaconda3\\lib\\site-packages\\IPython\\core\\formatters.py:339, in BaseFormatter.__call__(self, obj)\n 337 pass\n 338 else:\n--> 339 return printer(obj)\n 340 # Finally look for specia...
[ 0 ]
[]
[]
[ "histogram2d", "numpy", "python" ]
stackoverflow_0074677859_histogram2d_numpy_python.txt
Q: Pyinstaller - Error loading Python DLL - FormatMessageW failed I compiled my .py file running following commands: pyinstaller myfile.py --onefile. When i run it on my pc(Windows 10) everything works just fine. When i try to run it on my `virtual machine(Windows 8). I get the following error: Error loading Pytho...
Pyinstaller - Error loading Python DLL - FormatMessageW failed
I compiled my .py file running following commands: pyinstaller myfile.py --onefile. When i run it on my pc(Windows 10) everything works just fine. When i try to run it on my `virtual machine(Windows 8). I get the following error: Error loading Python DLL 'C:\Users\MyUsername\Appdata\Local\Temp\NUMBERS\python36.dll...
[ "I had a similar problem trying to run a python-based program (aws cli) and getting the \"Error loading Python DLL ... LoadLibrary: The specified module could not be found.\" on Windows Server 2008 R2. \nI solved this issue by installing the Visual C++ Redistributable for Visual Studio 2015 run-time components. htt...
[ 3, 0, 0 ]
[ "You can use auto-py-to-exe instead:\npython -m pip install auto-py-to-exe\nAnd then wait for it to download and then write in then cmd (or terminal):\nauto-py-to-exe\nA screen will appear:\n\nAnd just make as I made in the screenshot, then press \"convert .py to .exe\" and then press \"show output folder\".\n" ]
[ -1 ]
[ "pyinstaller", "python" ]
stackoverflow_0054214600_pyinstaller_python.txt
Q: How Do I Check RegEx In Integer Form I am trying to do the Advent Of Code 2022, 1st problem. (DONT TELL THE ANSWER). What i am doing is reading the file and taking each number and adding it to a sum value. What happens is, when I come across the "\n", it doesn't understand it and I am having trouble trying to crea...
How Do I Check RegEx In Integer Form
I am trying to do the Advent Of Code 2022, 1st problem. (DONT TELL THE ANSWER). What i am doing is reading the file and taking each number and adding it to a sum value. What happens is, when I come across the "\n", it doesn't understand it and I am having trouble trying to create the array of sums. Can anyone help? ` w...
[ "Instead of checking for i == \"\\n\", you should check i == ''. As the split based on \\n will remove all the \\n but left empty strings ''\nAnd for the line sum += int(str(i)), it should be applied when i != '' only.\nSo the modified code should be:\nwith open(\"input.txt\") as f:\n list_array = f.read().split(\...
[ 0 ]
[]
[]
[ "integer", "python", "validation" ]
stackoverflow_0074678597_integer_python_validation.txt
Q: User Defined function problem (Language:Python) Write the definition of a user defined function PushA(N) which accepts a list of names in N and pushes all those names which have letter 'A' present in it ,into a list named OnlyA. Write a program in python to input 5 names and push them one by one into a list named ...
User Defined function problem (Language:Python)
Write the definition of a user defined function PushA(N) which accepts a list of names in N and pushes all those names which have letter 'A' present in it ,into a list named OnlyA. Write a program in python to input 5 names and push them one by one into a list named AllNames. The program should then use the function Pu...
[]
[]
[ "# Function to push names with 'A' into a list named OnlyA\n\ndef PushA(N):\n\n OnlyA = []\n\n for name in N:\n\n if 'A' in name.upper():\n\n OnlyA.append(name)\n\n return OnlyA\n\n# Main program\n\nAllNames = []\n\n" ]
[ -2 ]
[ "list", "python", "stack", "user_defined_functions" ]
stackoverflow_0074678774_list_python_stack_user_defined_functions.txt
Q: Python Flask Apache wsgi Not Wrking EDIT-1 - I was having import issues running the app with mod_wsgi and the command line, but I have resolved those. I still can't get the mod_wsgi part to work, as detailed below. EDIT-2 Now the mod_wsgi is loading the login page, but the sqlite db is complaining. And one import ...
Python Flask Apache wsgi Not Wrking
EDIT-1 - I was having import issues running the app with mod_wsgi and the command line, but I have resolved those. I still can't get the mod_wsgi part to work, as detailed below. EDIT-2 Now the mod_wsgi is loading the login page, but the sqlite db is complaining. And one import either works for mod_wsgi, or the command...
[ "I am not sure this is the answer, but it is a workable solution.\nI changed the name of the the file rocket_launcher.py to controller.py and changed the appropriate references to rocket_launcher in the code to controller.\nI then changed the import in __init__.py to `import controller'.\nAnd voila, it works for bo...
[ 0 ]
[]
[]
[ "flask", "mod_wsgi", "python" ]
stackoverflow_0074668973_flask_mod_wsgi_python.txt
Q: When I swap two values in my list it is not a permanent swap in the list? I'm new to Python, and I have an assignment where I have a frogs vs. toads game. They are in a list and they need to swap places one step at a time. the list looks like this: ["F","F","F"," ","T","T","T"] and should look like ["T","T","T"," ...
When I swap two values in my list it is not a permanent swap in the list?
I'm new to Python, and I have an assignment where I have a frogs vs. toads game. They are in a list and they need to swap places one step at a time. the list looks like this: ["F","F","F"," ","T","T","T"] and should look like ["T","T","T"," ","F","F","F"] to win the game. The user inputs From and To and they swap. But ...
[ "So you want it such that the lilypad list does not revert back to ['F', 'F', 'F', ' ', 'T', 'T', 'T'] and that the position list also won't revert back to ['1', '2', '3', '4', '5', '6', '7']?\nThe problem in your code is that you reset the variables here:\n position= [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]\...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074672043_list_python.txt
Q: Select, move and deselect a card from Solitaire game pygame I want to select a card with the mouse (the card changes to another image of a card with orange edges), move it (or not) and later deselect the card clicking again, returning it to the original image of the card (without orange edges). I made the two firs...
Select, move and deselect a card from Solitaire game pygame
I want to select a card with the mouse (the card changes to another image of a card with orange edges), move it (or not) and later deselect the card clicking again, returning it to the original image of the card (without orange edges). I made the two first steps, but I can't find a way to deselect the card. for event i...
[ "Do not load the images in the application loop. Load the images before the application loop. Use a Boolean variable (card_selected) to indicate if the map is selected. Invert the state when clicking on the card (card_selected = not card_selected):\ncard_1 = pygame.image.load(\"1c.png\").convert_alpha()\ncard_1 = ...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074678805_pygame_python.txt
Q: Python interact with OS cmd I would like to know if it was possible via the OS module to iterate on several lines with the command prompt Here is an example of what I would have liked to do but which does not work (non-persistent session): from os import popen, system, getlogin system(f'cd C:/Users/{getlogin()}')...
Python interact with OS cmd
I would like to know if it was possible via the OS module to iterate on several lines with the command prompt Here is an example of what I would have liked to do but which does not work (non-persistent session): from os import popen, system, getlogin system(f'cd C:/Users/{getlogin()}') print(popen('pip freeze'))
[ "I tested this on Windows and it worked with check_output from subprocess, using cmd /C to execute both commands and exit\nfrom os import getlogin\nfrom subprocess import check_output\n\ncmd_str = fr'cmd.exe /C \"cd C:\\Users\\{getlogin()} && pip freeze\"'\n\noutput = check_output(cmd_str, shell=True).decode()\nfor...
[ 1, 0 ]
[]
[]
[ "cmd", "python", "python_os" ]
stackoverflow_0074677640_cmd_python_python_os.txt
Q: Does sonar cloud support decorative messages for Python in a GitHub PR with workflow? I used the generic workflow https://github.com/SonarSource/sonarcloud-github-action-samples/blob/generic/.github/workflows/build.yml as suggested in the docs. But I'm not receiving the message from the bot in the repository, code...
Does sonar cloud support decorative messages for Python in a GitHub PR with workflow?
I used the generic workflow https://github.com/SonarSource/sonarcloud-github-action-samples/blob/generic/.github/workflows/build.yml as suggested in the docs. But I'm not receiving the message from the bot in the repository, code is analyzed just fine and I can see it in the website. workflow name: CI on: push: ...
[ "Yes, SonarCloud does support decorating pull requests with analysis results for Python projects. In order for this to work, your GitHub workflow needs to include the pull-requests permission and use the SonarSource/sonarcloud-github-action action to run the SonarCloud analysis.\nBased on the information you provid...
[ 1, 0 ]
[]
[]
[ "github", "github_actions", "python", "sonarcloud", "workflow" ]
stackoverflow_0074559957_github_github_actions_python_sonarcloud_workflow.txt
Q: Django waitress- How to run it in Daemon Mode I've a django application with waitress (gunicorn doesn't work on windows) to serve it. Because its production code and its based on windows 2012 server. But I want the django application to run in daemon mode is it possible? Daemon mode - app running without command p...
Django waitress- How to run it in Daemon Mode
I've a django application with waitress (gunicorn doesn't work on windows) to serve it. Because its production code and its based on windows 2012 server. But I want the django application to run in daemon mode is it possible? Daemon mode - app running without command prompt visible also I'll be helpful to open shell wi...
[ "For production:\ncreate a file server.py at same level as manage.py and add following:\nfrom waitress import serve\n \nfrom myapp.wsgi import application\n \nif __name__ == '__main__':\n serve(application, port='8000')\n\nStart-Process python -NoNewWindow -ArgumentList \"server.py\"\nYou can close the ter...
[ 2, 0, 0, 0 ]
[]
[]
[ "daemon", "django", "python", "waitress", "windows" ]
stackoverflow_0074574627_daemon_django_python_waitress_windows.txt
Q: Apache Beam Python SDK on Flink Runner to use Snowflake IO I have an existing Flink cluster in k8s. I am using Flink's session mode. I want to set up a periodic ETL job from Snowflake using Apache Beam. Thus, I have tried to use from apache_beam.io.snowflake import ReadFromSnowflake. I am aware that an expansion s...
Apache Beam Python SDK on Flink Runner to use Snowflake IO
I have an existing Flink cluster in k8s. I am using Flink's session mode. I want to set up a periodic ETL job from Snowflake using Apache Beam. Thus, I have tried to use from apache_beam.io.snowflake import ReadFromSnowflake. I am aware that an expansion service is required, but here is where I am struggling. I have se...
[ "It seems that you are using FlinkRunner, and it means that it will use non-portable Flink.\nI have checked with a committer that works on portability (@chamikara) and he suggested using the PortableRunner if you need portability.\n" ]
[ 0 ]
[]
[]
[ "apache_beam", "apache_flink", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074666364_apache_beam_apache_flink_python_snowflake_cloud_data_platform.txt
Q: Cloud Computing Heuristic (Greedy) and Genetic algorithms for task scheduling Hello Everyone if somebody give me a hand by solving this coding (C++, Python) problem for cloud computing task scheduling by Heuristic (Greedy) and Genetic algorithms I have no clue how to write the code I have surfed through Google to...
Cloud Computing Heuristic (Greedy) and Genetic algorithms for task scheduling
Hello Everyone if somebody give me a hand by solving this coding (C++, Python) problem for cloud computing task scheduling by Heuristic (Greedy) and Genetic algorithms I have no clue how to write the code I have surfed through Google to find a code inspire me tackle the problem: the proble is: Problem: Task Scheduling...
[ "Here is a simple outline for implementing the task scheduling problem using heuristic and genetic algorithms in C++ and Python.\nFor the heuristic algorithm, you can start by creating a class or struct to represent each task and VM. This class or struct should have fields for the task size, deadline, and processin...
[ 0 ]
[]
[]
[ "c++", "cloud", "genetic_algorithm", "greedy", "python" ]
stackoverflow_0074678875_c++_cloud_genetic_algorithm_greedy_python.txt
Q: How to generate arbitrary high dimensional connectivity structures for scipy.ndimage.label I have some high dimensional boolean data, in this example an array with 4 dimensions, but this is arbitrary: X.shape (3, 2, 66, 241) I want to group the dataset into connected regions of True values, which can be done wit...
How to generate arbitrary high dimensional connectivity structures for scipy.ndimage.label
I have some high dimensional boolean data, in this example an array with 4 dimensions, but this is arbitrary: X.shape (3, 2, 66, 241) I want to group the dataset into connected regions of True values, which can be done with scipy.ndimage.label, with the aid of a connectivity structure which says which points in the a...
[ "The key to constructing an arbitrary structure for scipy.ndimage.label is to understand the concept of a neighborhood. A neighborhood is a set of points in the data that are considered to be connected. For example, in a 2D array, the neighborhood of a point (x,y) is the set of points {(x-1,y-1), (x-1,y), (x-1,y+1)...
[ 0, 0, 0 ]
[]
[]
[ "image_processing", "ndimage", "python", "scipy" ]
stackoverflow_0074564292_image_processing_ndimage_python_scipy.txt
Q: PyQt5: How to install/run Qt Designer Feeling really stupid, right now, but the title says it all: How do you start the QtDesigner? I've installed PyQt5 via pip and I believe to have identified the directory it's been installed in as C:\Users\%username%\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt...
PyQt5: How to install/run Qt Designer
Feeling really stupid, right now, but the title says it all: How do you start the QtDesigner? I've installed PyQt5 via pip and I believe to have identified the directory it's been installed in as C:\Users\%username%\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt5 Now what? There are a lot of .pyd files,...
[ "I struggled with this as well. The pyqt5-tools approach is cumbersome so I created a standalone installer for Qt Designer. It's only 40 MB. Maybe you will find it useful!\n", "If you are working in python virtual environment, in the command window\n>>qt5-tools designer\n\ncan open designer window.\n", "The Qt ...
[ 36, 32, 22, 20, 19, 7, 5, 5, 4, 4, 4, 2, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "pyqt5", "python", "qt", "qt_designer" ]
stackoverflow_0042090739_pyqt5_python_qt_qt_designer.txt
Q: Selenium (Python) (Firefox) is unable to write Firefox profile. Permission denied (os error 13) When I run my Python code using Selenium to open (and scrape) a website, using a profile parameter, I get the following error message: selenium.common.exceptions.SessionNotCreatedException: Message: Failed to set pr...
Selenium (Python) (Firefox) is unable to write Firefox profile. Permission denied (os error 13)
When I run my Python code using Selenium to open (and scrape) a website, using a profile parameter, I get the following error message: selenium.common.exceptions.SessionNotCreatedException: Message: Failed to set preferences: Unable to write Firefox profile: Permission denied (os error 13) I use the following code...
[ "This error message is telling you that your Python script is unable to write to the Firefox profile that you specified. This could be because the permissions on the profile directory are not set correctly, or because your script is running as a different user than the one who owns the Firefox profile.\nOne way to ...
[ 0 ]
[]
[]
[ "firefox", "linux", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074651572_firefox_linux_python_selenium_selenium_webdriver.txt
Q: AttributeErrors: undesired interaction between @property and __getattr__ I have a problem with AttributeErrors raised in a @property in combination with __getattr__() in python: Example code: >>> def deeply_nested_factory_fn(): ... a = 2 ... return a.invalid_attr ... >>> class Test(object): ... def __g...
AttributeErrors: undesired interaction between @property and __getattr__
I have a problem with AttributeErrors raised in a @property in combination with __getattr__() in python: Example code: >>> def deeply_nested_factory_fn(): ... a = 2 ... return a.invalid_attr ... >>> class Test(object): ... def __getattr__(self, name): ... if name == 'abc': ... return 'ab...
[ "If you're willing to exclusively use new-style classes, you could overload __getattribute__ instead of __getattr__:\nclass Test(object):\n def __getattribute__(self, name):\n if name == 'abc':\n return 'abc'\n else:\n return object.__getattribute__(self, name)\n @property\...
[ 3, 1, 0 ]
[]
[]
[ "attributeerror", "getattr", "properties", "python" ]
stackoverflow_0036575068_attributeerror_getattr_properties_python.txt
Q: Doing operations inside millions of csv files with python script csv format screenshot of my csv So, as shown in the attached file (one among the millions of csv files I have), they are in one line with 13890 columns. I had to convert them into two columns only with several lines instead the actual form in order...
Doing operations inside millions of csv files with python script
csv format screenshot of my csv So, as shown in the attached file (one among the millions of csv files I have), they are in one line with 13890 columns. I had to convert them into two columns only with several lines instead the actual form in order to have the date and its parameter only. The applied operations to co...
[ "So, there are a couple of ways to parse the file better:\nFirst up you can use enumerate when you want access to the index as well as the value in an array.\nSecond there's no need to check every index because you already know which ones contain the data you need.\nAnd for optimisation the biggest mistake was open...
[ 1 ]
[]
[]
[ "csv", "database", "pyarrow", "pycharm", "python" ]
stackoverflow_0074678238_csv_database_pyarrow_pycharm_python.txt
Q: Outer minimum vectorization in numpy Given an NxM matrix A, I want to efficiently obtain the NxMxN tensor whose ith layer is the application of np.minimum between A and the ith row of A. Using a for loop: > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0], A.shape[1], A.shape[0])) > for ...
Outer minimum vectorization in numpy
Given an NxM matrix A, I want to efficiently obtain the NxMxN tensor whose ith layer is the application of np.minimum between A and the ith row of A. Using a for loop: > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0], A.shape[1], A.shape[0])) > for i in range(a.shape[0]): output[:, :,...
[ "With broadcasting we can make a (3,3,2) result:\nIn [153]: np.minimum(A[:,None,:],A[None,:,:])\nOut[153]: \narray([[[1, 2],\n [1, 2],\n [1, 2]],\n\n [[1, 2],\n [3, 4],\n [3, 4]],\n\n [[1, 2],\n [3, 4],\n [5, 6]]])\n\nand then switch the last 2 dimensions to get...
[ 1, 0 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074678481_numpy_python_vectorization.txt
Q: Python Threading vs Multiprocessing to improve REST API responsiveness "fire and forget" tasks I am somewhat new to both threading and multiprocessing in Python, as well as dealing with the concept of the GIL. I have a situation where I have time consuming fire and forget tasks that I need the server to run, but t...
Python Threading vs Multiprocessing to improve REST API responsiveness "fire and forget" tasks
I am somewhat new to both threading and multiprocessing in Python, as well as dealing with the concept of the GIL. I have a situation where I have time consuming fire and forget tasks that I need the server to run, but the server should immediately reply to the client and basically be like "okay, your thing was submitt...
[ "I suggest using Advance Python Scheduler.\nInstead of running your function in a thread, schedule it to run and immediately return to client.\nAfter setting up your flask app, setup Flask-APScheduler and then schedule your function to run in the background.\nfrom apscheduler.schedulers.background import Background...
[ 1 ]
[]
[]
[ "flask", "multiprocessing", "multithreading", "optimization", "python" ]
stackoverflow_0074663169_flask_multiprocessing_multithreading_optimization_python.txt
Q: how to tell if a button hasnt been pressed button = Button(style = discord.ButtonStyle.green, emoji = ":arrow_backward:", custom_id = "button1") view = View() view.add_item(button) async def button_callback(interaction): await message.edit(content="**response 1**") button.callback = button_callback a...
how to tell if a button hasnt been pressed
button = Button(style = discord.ButtonStyle.green, emoji = ":arrow_backward:", custom_id = "button1") view = View() view.add_item(button) async def button_callback(interaction): await message.edit(content="**response 1**") button.callback = button_callback await message.edit(content="⠀⠀:watermelon:⠀⠀⠀⠀⠀:w...
[ "Try this solution\n\n# Set a timer to check if the button has not been pressed\nimport asyncio\n\ntime_limit = 15 # Set the amount of time to wait before checking\n\nasync def check_button():\n await asyncio.sleep(time_limit) # Wait the designated amount of time\n if not button.pressed: # Check if the button...
[ 0 ]
[]
[]
[ "discord", "pycord", "python" ]
stackoverflow_0074678952_discord_pycord_python.txt
Q: Turn values from string to integers in JSON file python I'm trying to change values in a JSON file from strings to integers, my issue is that the keys are row numbers so I can't call by key name (as they will change consistently). The values that need changing are within the "sharesTraded" object. Below is my JSON...
Turn values from string to integers in JSON file python
I'm trying to change values in a JSON file from strings to integers, my issue is that the keys are row numbers so I can't call by key name (as they will change consistently). The values that need changing are within the "sharesTraded" object. Below is my JSON file: { "lastDate": { "30": "04/04/2022", ...
[ "You have a couple of problems. First, since you only convert the values to a list, you loose the information about which key is associated with the values. Second, you write that list back to the file, loosing all of the other data too.\nYou could create a new dictionary with the modified values and assign that ba...
[ 2, 1 ]
[]
[]
[ "integer", "json", "python", "string" ]
stackoverflow_0074678918_integer_json_python_string.txt
Q: Converting TIFF images to NumPy format I would need help to create a code that would convert my tiff images to .npy format so I can save it as .npy file. I haven't found a good solution anywhere on this platform. Thank you in advance! A: Here is a code snippet that you can use to convert your TIFF images to .npy...
Converting TIFF images to NumPy format
I would need help to create a code that would convert my tiff images to .npy format so I can save it as .npy file. I haven't found a good solution anywhere on this platform. Thank you in advance!
[ "Here is a code snippet that you can use to convert your TIFF images to .npy format in Python:\nimport numpy as np\nfrom PIL import Image\n\n# Load the TIFF image\nim = Image.open('my_image.tiff')\n\n# Convert the image to a numpy array\nim_array = np.array(im)\n\n# Save the array to a .npy file\nnp.save('my_image....
[ 0 ]
[]
[]
[ "numpy", "python", "tiff" ]
stackoverflow_0074678997_numpy_python_tiff.txt
Q: Is there a function that makes python read only some parts of a string and execute an operation I'm trying to make my Python read only the first 3 digits of a string and print an answer based on the first three digits of the string. I tried: if str[1,2,3] = 080: print(...) elif str[123] =090: print(,,,) A: ...
Is there a function that makes python read only some parts of a string and execute an operation
I'm trying to make my Python read only the first 3 digits of a string and print an answer based on the first three digits of the string. I tried: if str[1,2,3] = 080: print(...) elif str[123] =090: print(,,,)
[ "Here is how you can achieve this in Python:\n# Store the string in a variable\nstring = \"Hello world\"\n\n# Get the first three characters of the string\nfirst_three_chars = string[:3]\n\n# Check if the first three characters are \"080\"\nif first_three_chars == \"080\":\n print(\"The first three characters ar...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679053_python.txt
Q: Unable to complete operation on element with key none I'm practicing with an algorithm that generates a random number that the user needs, then keeps trying until it hits. But PySimpleGUI produces an error saying: Unable to complete operation on element with key None. import randomimport PySimpleGUI as sg class C...
Unable to complete operation on element with key none
I'm practicing with an algorithm that generates a random number that the user needs, then keeps trying until it hits. But PySimpleGUI produces an error saying: Unable to complete operation on element with key None. import randomimport PySimpleGUI as sg class ChuteONumero: def init(self): self.valor_aleator...
[ "Revised your code ...\nimport random\nimport PySimpleGUI as sg\n\nclass ChuteONumero:\n\n def __init__(self):\n self.valor_aleatorio = 0\n self.valor_minimo = 1\n self.valor_maximo = 100\n self.tentar_novamente = True\n\n def Iniciar(self):\n # Layout\n layout = [\n ...
[ 0 ]
[]
[]
[ "pysimplegui", "python" ]
stackoverflow_0074678831_pysimplegui_python.txt
Q: How do I copy all folder contents from one location to another - Python? I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL contents, images, videos, etc. I have tried using this shutil code I...
How do I copy all folder contents from one location to another - Python?
I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL contents, images, videos, etc. I have tried using this shutil code I found online, however it has not worked and shows the message:* Error occurre...
[ "To copy all the contents of a folder, you can use the shutil.copytree method instead of shutil.copy. This method will copy all the contents of the source folder, including any sub-folders and files, to the destination folder.\nHere is an example of how you can use shutil.copytree to copy the contents of a folder:\...
[ 0 ]
[]
[]
[ "copy", "copy_paste", "python", "shutil", "windows" ]
stackoverflow_0074679048_copy_copy_paste_python_shutil_windows.txt
Q: Last iteration of loop not completely executed I am currently writing a short script to scrape all outlets from a retailer in my home country. I first scrape all possible postal codes from the website of the postal service, after which I enter these one by one automatically with Selenium in their location finder. ...
Last iteration of loop not completely executed
I am currently writing a short script to scrape all outlets from a retailer in my home country. I first scrape all possible postal codes from the website of the postal service, after which I enter these one by one automatically with Selenium in their location finder. After this, I check whether the found locations are ...
[ "import requests\nimport pandas as pd\n\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n with requests.Session() as req:\n req.headers.update(headers)\n params = {\n 'q': '9000',\n 'fi...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074678059_beautifulsoup_python_selenium_selenium_chromedriver_web_scraping.txt
Q: I'm getting an "Execution Timed Out" error? I'm trying to improve my algorithm skills. When I run my code, I get an "Execution Timed Out" error. Pseudocode [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 My Code def hotpo(n): calculator = 0 wh...
I'm getting an "Execution Timed Out" error?
I'm trying to improve my algorithm skills. When I run my code, I get an "Execution Timed Out" error. Pseudocode [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 My Code def hotpo(n): calculator = 0 while n >= 1: if n % 2 == 0: n ...
[ "you are dividing number by 2 if number is even but multiplying it by 3 and adding 1 into it.\nso for any number it will keep doing this\n2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,.....\nyou just have to change condition to n>1 in while loop\nbecause at last 2 will come and it got divided by 2, then n becomes 1 then again it w...
[ 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0074678975_algorithm_python.txt
Q: Selenium with python : failed to click on the button to switch the language of a website I am trying to go to the french version of this website : https://ciqual.anses.fr/. I tried to click on the button 'FR' but nothing happens, I am still on the english page. Here is my code : from selenium import webdriver from...
Selenium with python : failed to click on the button to switch the language of a website
I am trying to go to the french version of this website : https://ciqual.anses.fr/. I tried to click on the button 'FR' but nothing happens, I am still on the english page. Here is my code : from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains impor...
[ "Try this:\nswitch_to_french = driver.find_element(By.XPATH, \"//a[@id='fr-switch']\")\ndriver.execute_script(\"arguments[0].click();\", switch_to_french)\n\n" ]
[ 0 ]
[]
[]
[ "click", "python", "selenium" ]
stackoverflow_0074678963_click_python_selenium.txt
Q: Convert all images in a pandas dataframe column to grayscale I have a column of a pandas dataframe with 25 thousand images, and I want to convert the color of all of them to grayscale. What would be the simplest way to do this? I know how to convert the color, which I must use a loop and do the conversion with num...
Convert all images in a pandas dataframe column to grayscale
I have a column of a pandas dataframe with 25 thousand images, and I want to convert the color of all of them to grayscale. What would be the simplest way to do this? I know how to convert the color, which I must use a loop and do the conversion with numpy or opencv, but I don't know how to do this loop with a column o...
[ "One way to convert the color of images in a pandas dataframe is to use the apply method on the column containing the image data. This method allows you to apply a custom function to each element of the column.\nFor example, if your dataframe has a column called 'images' containing the image data, you could convert...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074679121_pandas_python.txt
Q: parsing email threads in python tl;dr questions: how to parse MIME content into threads (thus lists of individual replies & forwards) any libraries that do that? Does Mime-Version: 1.0 standardize the way threads are represented? I'm analyzing enron dataset (https://www.cs.cmu.edu/~./enron/, you can also browse ...
parsing email threads in python
tl;dr questions: how to parse MIME content into threads (thus lists of individual replies & forwards) any libraries that do that? Does Mime-Version: 1.0 standardize the way threads are represented? I'm analyzing enron dataset (https://www.cs.cmu.edu/~./enron/, you can also browse the documents here: http://www.enron-...
[ "Here are a code sample hope it will be usefull\nimport email\n\nemail_message: email.message.Message = email.message_from_bytes(raw_email_body)\n# or as in your example\n# email.message_from_string(open(filename, 'r').read(), policy=email.policy.default)\n\nmessage_parts = list(message.walk())\nfor part in message...
[ 0, 0 ]
[]
[]
[ "email", "email_parsing", "mime", "parsing", "python" ]
stackoverflow_0074568352_email_email_parsing_mime_parsing_python.txt
Q: I can't install matplotlib using pip I am totally new to the Python and I wanted to use a matplotlib for my school project. I tried to install it using pip (pip install matplotlib), but I got a really long and bad-looking error and I don't know what to do... I was trying to upgrade pip and setuptools, but i didn't...
I can't install matplotlib using pip
I am totally new to the Python and I wanted to use a matplotlib for my school project. I tried to install it using pip (pip install matplotlib), but I got a really long and bad-looking error and I don't know what to do... I was trying to upgrade pip and setuptools, but i didn't help. I don't understand this issue, beca...
[ "Add your python to path and try running command in command prompt.\n", "try to run\npython -m pip install -U pip\npython -m pip install -U matplotlib\nwhile installing Matplotlib !\n" ]
[ 0, 0 ]
[]
[]
[ "matplotlib", "pip", "python", "python_3.x" ]
stackoverflow_0058582126_matplotlib_pip_python_python_3.x.txt
Q: How to emit data from python socket.io server to angular socket.io client I need to get real time data in my angular project from a python server (no chat). I have the angular side setup, but I don't know how to get the python backend working. angular: import { Injectable } from '@angular/core'; import { Observabl...
How to emit data from python socket.io server to angular socket.io client
I need to get real time data in my angular project from a python server (no chat). I have the angular side setup, but I don't know how to get the python backend working. angular: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import {io} from 'socket.io-client'; @Injectable({ provided...
[ "You can use the send method provided by SocketManager to send messages to the client.\nHere is an example of how you can modify your code to send random numbers to the client:\nfrom fastapi import FastAPI\nfrom fastapi_socketio import SocketManager\nimport uvicorn\nimport random\n\napp = FastAPI()\nsio = SocketMan...
[ 0 ]
[]
[]
[ "angular", "python", "socket.io" ]
stackoverflow_0074679118_angular_python_socket.io.txt
Q: Filter QuerySet from a given list of indexs I have a list of index i want to extract from another queryset. >>> allLocation = loc.objects.all() >>> allLocation <QuerySet [<loc: loc object (1)>, <loc: loc object (2)>, <loc: loc object (3)>, <loc: loc object (4)>, <loc: loc object (5)>]> >>> UserIndex = [0,3,4] >>>...
Filter QuerySet from a given list of indexs
I have a list of index i want to extract from another queryset. >>> allLocation = loc.objects.all() >>> allLocation <QuerySet [<loc: loc object (1)>, <loc: loc object (2)>, <loc: loc object (3)>, <loc: loc object (4)>, <loc: loc object (5)>]> >>> UserIndex = [0,3,4] >>> >>> allLocation[UserIndex[1]] <loc: loc object ...
[ "So using chatGPT I found the ans I was looking for\nfilteredUser = allLocation.filter(id__in=[allLocation[i].id for i in UserIndex]) \n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0074348329_django_django_models_django_queryset_python.txt
Q: python - Run indented code through keyboard shortcuts in Spyder as in RStudio I would like to be able to run an indented block of code in python in the same way I do in R. In particular, if in RStudio I have the following indented block of code: print(seq(from = 1, to = 10, by = 1)) I can plac...
python - Run indented code through keyboard shortcuts in Spyder as in RStudio
I would like to be able to run an indented block of code in python in the same way I do in R. In particular, if in RStudio I have the following indented block of code: print(seq(from = 1, to = 10, by = 1)) I can place the cursor everywhere (at the beginning of the code, in the middle, at the end) e...
[ "(Spyder maintainer here) You said\n\nAny advice on how to run such code without selecting it first?\n\nYes, you need to use cells for that. You can create a cell by inserting a comment that starts with # %%, like this\nimport pandas as pd\n\n# %%\ncars = {'Brand': ['Honda', 'Ford','Audi'],\n 'Price': [20000...
[ 1, 0 ]
[]
[]
[ "keyboard_shortcuts", "python", "r", "spyder" ]
stackoverflow_0067314850_keyboard_shortcuts_python_r_spyder.txt
Q: How to extract exactly the same word with regexp_extract_all in pyspark I am having some issues in finding the correct regular expression lets say I have this list of keywords: keywords = [' b.o.o', ' a.b.a', ' titi'] (please keep in mind that there is a blank space before any keyword and this list can contain up ...
How to extract exactly the same word with regexp_extract_all in pyspark
I am having some issues in finding the correct regular expression lets say I have this list of keywords: keywords = [' b.o.o', ' a.b.a', ' titi'] (please keep in mind that there is a blank space before any keyword and this list can contain up to 100keywords so I can't to it without a function) and my dataframe df: ente...
[ "I think you need to add a backslash before the dot in your regular expression pattern to escape it, so it's treated as a literal dot and not a special character that matches any character.\nIn your code, you can try using the re.escape() method from the re module to escape all special characters in the keywords li...
[ 0, 0, 0 ]
[]
[]
[ "apache_spark", "extract", "pyspark", "python", "regex" ]
stackoverflow_0074671615_apache_spark_extract_pyspark_python_regex.txt
Q: My discord bot is not responding to my commands import discord import os client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print("We have logged in as {0.user}".format(client)) @client.event async def on_message(message): if message.author == client.user: ret...
My discord bot is not responding to my commands
import discord import os client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print("We have logged in as {0.user}".format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): ...
[ "You seem to have an indentation error:\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if message.content.startswith('$hello'):\n channel = message.channel\n await channel.send('Hello!')\n\nThe last if-statement is never going to be executed. Instead, move it one i...
[ 0, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074679033_discord.py_python.txt
Q: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu When I go to run a python code directly through the terminal it gives me this error, I've already tried to reinstall numpy and it didn't work! And I tried to install ml...
mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu
When I go to run a python code directly through the terminal it gives me this error, I've already tried to reinstall numpy and it didn't work! And I tried to install mlk service returns the same error. Can someone help me ? UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensurin...
[ "Can be solved by resetting package configuration by force reinstall of numpy.\nconda install numpy --force-reinstall\n\n", "I was able to fix it by running the following commands to uninstall and reinstall the packages\npip uninstall matplotlib\npip uninstall pillow\npip uninstall numpy\npip install matplotlib\n...
[ 4, 3, 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0072858984_jupyter_notebook_python.txt
Q: Gtts library error. I don't know why this error are happening or how to fix them I am tried to convert pdf to an audio file but when ever I run my code I get a bunch error from the gtts liberary. If there is a better liberary to use that does not sound like a robot please let me know the errors are https://pastebi...
Gtts library error. I don't know why this error are happening or how to fix them
I am tried to convert pdf to an audio file but when ever I run my code I get a bunch error from the gtts liberary. If there is a better liberary to use that does not sound like a robot please let me know the errors are https://pastebin.com/Uwnq1MgS and my code is #Importing Libraries #Importing Google Text to Speech li...
[ "It looks like the issue is with the PyPDF2 library. The getPage() method is not able to extract the text from some pages in the PDF file, resulting in an error.\nOne solution could be to use the PyMuPDF library instead, which is a more powerful PDF manipulation library. You can install it using the following comma...
[ 0 ]
[]
[]
[ "gtts", "python" ]
stackoverflow_0074679139_gtts_python.txt
Q: NotImplementedError: Conversion 'rpy2py' not defined for objects of type '' only after I run the code twice If I run the following code once it works. import numpy as np import rpy2.robjects as robjects x = np.linspace(0, 1, num = 11, endpoint=True) y = np.array([-1,1,1, -1,1,0, .5,.5,.4, .5, -1]) r_x = robj...
NotImplementedError: Conversion 'rpy2py' not defined for objects of type '' only after I run the code twice
If I run the following code once it works. import numpy as np import rpy2.robjects as robjects x = np.linspace(0, 1, num = 11, endpoint=True) y = np.array([-1,1,1, -1,1,0, .5,.5,.4, .5, -1]) r_x = robjects.FloatVector(x) r_y = robjects.FloatVector(y) r_smooth_spline = robjects.r['smooth.spline'] #extract R functi...
[ "The easiest fix is to run once:\n!pip install -Iv rpy2==3.4.2\n\nat the start of the Jupyter-notebook in order to rollback to version 3.4.2, where this problem did not occur (see Rpy2 Error depends on execution method: NotImplementedError: Conversion \"rpy2py\" not defined). For more information how to cahge the v...
[ 0, 0 ]
[]
[]
[ "jupyter_notebook", "python", "rpy2" ]
stackoverflow_0074678378_jupyter_notebook_python_rpy2.txt
Q: Cannot able to run cqlsh due to python attribute error Cannot able to execute the command cqlsh in mac m1 based system. % bin/cqlsh Traceback (most recent call last): File "/Users/avinashkasukurthi/devtools/apache-cassandra-4.0.7/bin/cqlsh.py", line 159, in <module> from cqlshlib import cql3handling, cqlhand...
Cannot able to run cqlsh due to python attribute error
Cannot able to execute the command cqlsh in mac m1 based system. % bin/cqlsh Traceback (most recent call last): File "/Users/avinashkasukurthi/devtools/apache-cassandra-4.0.7/bin/cqlsh.py", line 159, in <module> from cqlshlib import cql3handling, cqlhandling, pylexotron, sslhandling, cqlshhandling File "/Users/...
[ "Looks like there may have been a breaking change introduced to Python's synchronized regex engine (SRE) with Python 3.11. I have created a ticket for this on the Cassandra project (CASSANDRA-18088).\nIn the interim, downgrade your local Python to 3.10, and you should be fine.\n" ]
[ 0 ]
[]
[]
[ "cassandra", "cassandra_4.0", "cqlsh", "python" ]
stackoverflow_0074673247_cassandra_cassandra_4.0_cqlsh_python.txt
Q: Add a column in my dataframe based on the name of Excel file I want to import many excel files into one single dataframe and I want a column where all the rows are the same as the original excel file name in python this is what i have tried df_final=df_final.assign(Année='2021') df_final=df_final.assign(Mois='Octo...
Add a column in my dataframe based on the name of Excel file
I want to import many excel files into one single dataframe and I want a column where all the rows are the same as the original excel file name in python this is what i have tried df_final=df_final.assign(Année='2021') df_final=df_final.assign(Mois='Octobre') But I am obliged each time to imort a single excel file add...
[ "in order to add a value to each dataframe based on the filename you need to create a list of values equal to the number of rows. Below is a simple example assuming the dataframes are the same.\nEach sample file I have created looks like this:\nfile1.xlsx\n Some Data\n0 5\n1 3\n2 2\n3 ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074677969_python.txt