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: In Django how to convert an uploaded pdf file to an image file and save to the corresponding column in database? I am creating an HTML template to show the cover of a pdf file(first page or user can choose one). I want Django to create the cover image automatically without extra upload. The pdf file is uploaded us...
In Django how to convert an uploaded pdf file to an image file and save to the corresponding column in database?
I am creating an HTML template to show the cover of a pdf file(first page or user can choose one). I want Django to create the cover image automatically without extra upload. The pdf file is uploaded using Django Modelform. Here is the structure of my code models.py class Pdffile(models.Model): pdf = models.FileFie...
[ "In the pdf2image package there is a function called convert_from_path.\nThis is the description inside the package of what each of the parameters of the function does.\nParameters:\n pdf_path -> Path to the PDF that you want to convert\n dpi -> Image quality in DPI (default 200)\n ...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0066069902_django_python.txt
Q: can i use prometheus without docker and kuber? I was wondering if there is any way to use Prometheus (as a playground, to see how it works) without needing to dockerize the app and deploy it on kuber (kind or minikube)? A: You don't need to dockerize the Prometheus just to try it out. Regarding trying it on non ...
can i use prometheus without docker and kuber?
I was wondering if there is any way to use Prometheus (as a playground, to see how it works) without needing to dockerize the app and deploy it on kuber (kind or minikube)?
[ "You don't need to dockerize the Prometheus just to try it out.\nRegarding trying it on non containerized environment, there are multiple options.\n\nUse the demo(hosted) Prometheus to check its features, query the data etc :\nhttps://prometheus.demo.do.prometheus.io/graph\nYou can simple download the binary and ru...
[ 1 ]
[]
[]
[ "docker", "monitoring", "prometheus", "python" ]
stackoverflow_0074328274_docker_monitoring_prometheus_python.txt
Q: Scraping Issue - Python, Selenium- NoSuchElementException: Unable to locate element: / **How can I click a non-button for refresh page - ** I'm trying to web scraping with selenium but I cant click a spesific area. Here is my code and ERROR message. from selenium import webdriver from selenium.webdriver.common.key...
Scraping Issue - Python, Selenium- NoSuchElementException: Unable to locate element: /
**How can I click a non-button for refresh page - ** I'm trying to web scraping with selenium but I cant click a spesific area. Here is my code and ERROR message. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.common.act...
[ "As stated in the comments, sometimes elements take some time to load if they are built through JS therefore including some explicit wait can help:\nelement = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"<your_xpath>\")\n ) \n)\n\nWhere 10 is the number of seconds you a...
[ 0 ]
[]
[]
[ "issuu", "python", "selenium_firefoxdriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074320211_issuu_python_selenium_firefoxdriver_selenium_webdriver_web_scraping.txt
Q: How should I structure a config file to accept mutually exclusive parameters? I'm writing a Python program that should accept input data from either a CSV file or a database. The structure of the data will be identical, it's just the method of getting the data. I'd like to put the configuration for getting that da...
How should I structure a config file to accept mutually exclusive parameters?
I'm writing a Python program that should accept input data from either a CSV file or a database. The structure of the data will be identical, it's just the method of getting the data. I'd like to put the configuration for getting that data into a config file (along with other options), and then ideally have that config...
[ "I suppose the answers to your question will be rather subjective either way.\nWith all due respect, the dataclasses module is very weak IMHO compared to other projects out there that do similar things. I personally like Pydantic very much, but there are other options as well. One reason is the fact that dataclasse...
[ 0 ]
[]
[]
[ "configparser", "configuration", "python", "type_hinting" ]
stackoverflow_0074322459_configparser_configuration_python_type_hinting.txt
Q: Identify forks of a python package from within I have a Python package (a PyQt GUI app) on Github, published via PyPI. It has a crash reporting facility. Ever once in a while, I receive crashes that are subtly, but unmistakably inconsistent with my code. Examples: a "class X not found in module Y" error, where dep...
Identify forks of a python package from within
I have a Python package (a PyQt GUI app) on Github, published via PyPI. It has a crash reporting facility. Ever once in a while, I receive crashes that are subtly, but unmistakably inconsistent with my code. Examples: a "class X not found in module Y" error, where dependency module Y was recently updated by adding clas...
[ "Here's what I've come up with. I've introduced a Python file cookie.py with a placeholder variable:\ncookie=False\n\nAnd placed it into source control as it is, with a False cookie value. During the build process, I place the latest commit hash into the cookie file, like this:\ngit log --pretty=format:%%H -n 1 >ha...
[ 1 ]
[]
[]
[ "pip", "pypi", "python", "setuptools" ]
stackoverflow_0074318065_pip_pypi_python_setuptools.txt
Q: Incrementing and showing number on click in Turtle This is the code: def money(): money += 1 t.write('Money: ' + str(money)) player.onclick(money, 1) What shows up on turtle is: Money: <function money at 0x00000249BA69B010> I tried changing format and string but it just won't show anything different I'm look...
Incrementing and showing number on click in Turtle
This is the code: def money(): money += 1 t.write('Money: ' + str(money)) player.onclick(money, 1) What shows up on turtle is: Money: <function money at 0x00000249BA69B010> I tried changing format and string but it just won't show anything different I'm looking for: Money: 0
[ "There are a few issues here. For starters, you can't use a variable money to represent two things at once. There should be separate variable names for the function that runs on click and the integer that represents how much money the player has. Since functions are usually actions, let's call it add_money, and cal...
[ 2 ]
[]
[]
[ "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074325680_python_python_turtle_turtle_graphics.txt
Q: Options for linting Cython code I have a Cython module that I would like to lint PEP8 style, however pylint syntax errors on Cython cdef syntax. Does anyone have a suggestion about how to maintain Python coding standards for Cython code? A: Although not command-line based, PyCharm claims to have Cython support....
Options for linting Cython code
I have a Cython module that I would like to lint PEP8 style, however pylint syntax errors on Cython cdef syntax. Does anyone have a suggestion about how to maintain Python coding standards for Cython code?
[ "Although not command-line based, PyCharm claims to have Cython support. Unfortunately, it's only available on the paid-version \"Professional Edition\".\n", "I use Sublime Text editor with SublimeLinter Flake8 package.\nMy Flake8 config is:\n\"flake8\": {\n \"@disable\": false,\n \"args\": ...
[ 5, 3, 0, 0 ]
[]
[]
[ "cython", "pylint", "python" ]
stackoverflow_0025535599_cython_pylint_python.txt
Q: Replacing Consonants and Vowels in a String - Python/PySimpleGUI Dears, I want to write a function in Python, given a string, returns a new string in which the vowel will remain as it is and the consonants will be replaced with grec alphabet : α, β, γ, δ, ε, ...., Ω ω. And once there is a duplicate consanant, same...
Replacing Consonants and Vowels in a String - Python/PySimpleGUI
Dears, I want to write a function in Python, given a string, returns a new string in which the vowel will remain as it is and the consonants will be replaced with grec alphabet : α, β, γ, δ, ε, ...., Ω ω. And once there is a duplicate consanant, same letter will be used : Let me clarify this by examples : String "Bette...
[ "This should work:\na = \"αβγ\" # replace with the complete greek alphabet\ns = \"Better\"\nvovels = \"AEIOUaeiou\"\nalready_replaced = {}\nnew_string = \"\"\ncounter = 0\nfor c in s:\n if c in vovels:\n new_string += c\n elif c in already_replaced.keys():\n new_string += already_replaced[c]...
[ 1 ]
[]
[]
[ "alphabetical", "pysimplegui", "python", "replace", "string" ]
stackoverflow_0074328723_alphabetical_pysimplegui_python_replace_string.txt
Q: How to load the latest checkpoint and save it as a model in Tensorflow? So, I was wondering how to load the latest checkpoint in Tensorflow having its path/directory and continue the training where I left off. And also how to load the latest checkpoint and save it as a complete model. Please help me My code: ...
How to load the latest checkpoint and save it as a model in Tensorflow?
So, I was wondering how to load the latest checkpoint in Tensorflow having its path/directory and continue the training where I left off. And also how to load the latest checkpoint and save it as a complete model. Please help me My code: cp_callback = tf.keras.callbacks.ModelCheckpoint( filepath=che...
[ "The simplest solution to your problem would be to save the entire model with the ModelCheckpoint callback.\nYou only have to remove the save_weights_only argument for it to work.\ncp_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_path, \n verbose=1,\n save_fre...
[ 0 ]
[]
[]
[ "deep_learning", "keras", "pickle", "python", "tensorflow" ]
stackoverflow_0074328165_deep_learning_keras_pickle_python_tensorflow.txt
Q: running a command as a super user from a python script So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, ...
running a command as a super user from a python script
So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ...
[ "Try:\nsubprocess.call(['sudo', 'apach2ctl', 'restart'])\nThe subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.\nIf you don't define them, then it grabs sys.stdout, etc...\...
[ 29, 22, 16, 13, 6, 5, 4, 3, 0 ]
[]
[]
[ "python", "subprocess", "sudo" ]
stackoverflow_0000567542_python_subprocess_sudo.txt
Q: How to change tkinter geometry values in regard to (for example) a scrolled text height? I was wondering how do the geometry() function values in tkinter come to play with the height value of for example a scrolled text? How can I convert the units to work with each other? For example: If I want to open a scrolled...
How to change tkinter geometry values in regard to (for example) a scrolled text height?
I was wondering how do the geometry() function values in tkinter come to play with the height value of for example a scrolled text? How can I convert the units to work with each other? For example: If I want to open a scrolled text box underneath my tkinter window with a click of a button, I know I need then to change ...
[ "Widgets that contains text usually provide their width and height in character space. This means tkinter takes the average width and height of your font and multiplies it with the given number in width and height.\nThere are mainly two ways to deal with that, either tk.Font.measure or metrics, if you want to conve...
[ 1 ]
[]
[]
[ "python", "tkinter", "tkinter_scrolledtext" ]
stackoverflow_0074328563_python_tkinter_tkinter_scrolledtext.txt
Q: Filtering large vcf file I have a VCF file with following format: #CHROM POS ID REF ALT QUAL FILTER. INFO chr1 10061 . A T 77.1 AC0 AC=2;AN=53780 chr1 10162 . A GC 81.0. AC0;AS_VQSR AC=1;AN=3615 I want to apply couple of filters: Retain only those rows where length of REF and ALT column is exactly 1. After fi...
Filtering large vcf file
I have a VCF file with following format: #CHROM POS ID REF ALT QUAL FILTER. INFO chr1 10061 . A T 77.1 AC0 AC=2;AN=53780 chr1 10162 . A GC 81.0. AC0;AS_VQSR AC=1;AN=3615 I want to apply couple of filters: Retain only those rows where length of REF and ALT column is exactly 1. After first filter I want to...
[ "With the following toy dataframe mimicking yours:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"#CHROM\": [\"chr1\", \"chr1\", \"chr2\", \"chr1\"],\n \"POS\": [10061, 10162, 10163, 10061],\n \"ID\": [\".\", \".\", \".\", \".\"],\n \"REF\": [\"A\", \"A\", \"AA\", \"A\"],\n ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074300975_pandas_python.txt
Q: How to reference (and modify) a slice of a scipy sparse matrix? I'm trying to get a reference to a column-wise slice of a scipy sparse matrix, and modify it. I tried the following but the slice seems to be returning a copy instead of a reference (as is the numpy behaviour), so the original matrix is not modified. ...
How to reference (and modify) a slice of a scipy sparse matrix?
I'm trying to get a reference to a column-wise slice of a scipy sparse matrix, and modify it. I tried the following but the slice seems to be returning a copy instead of a reference (as is the numpy behaviour), so the original matrix is not modified. >>> import scipy.sparse as sp >>> A=sp.csc_matrix((10, 100)) >>> B=A[...
[]
[]
[ "I think you need to change the dtype to ndarray first. Try this:\nimport numpy as np\nimport scipy.sparse as sp\nA=sp.csc_matrix((10, 100), dtype=np.int8).toarray()\nB=A[:, 0:1]\nB[:,0]=1\nB\narray([[1],\n [1],\n [1],\n [1],\n [1],\n [1],\n [1],\n [1],\n [1],\n [1]], dtype=int8)\n\n" ]
[ -1 ]
[ "matrix", "numpy", "python", "scipy" ]
stackoverflow_0074323869_matrix_numpy_python_scipy.txt
Q: Get the depth of a node in a Ternary Tree Using The Indexes in Array Implementation of Trees Let's assume we create a Ternary tree using an array implementation. The root is stored in the index 1, the left child is stored in index = 3(index)-1, middle child is stored in 3(index), and right child is stored in 3(ind...
Get the depth of a node in a Ternary Tree Using The Indexes in Array Implementation of Trees
Let's assume we create a Ternary tree using an array implementation. The root is stored in the index 1, the left child is stored in index = 3(index)-1, middle child is stored in 3(index), and right child is stored in 3(index)+1. So for example. Assume the following Ternary Tree. A ...
[ "The number of nodes in level k is 3**k, for level 0 it's 1, for level 1 it's 3, for level 2 it's 9, and so on.\nThe total number of nodes in k levels is the sum of arithmetic progression:\nsum(i in [0;k], 3**i) = (1 + 3**k)*(k+1) / 2\n\nFor a node index N you need to find such k that:\n(1 + 3**k)*(k+1)/2 <= N < (1...
[ 0, 0 ]
[]
[]
[ "data_structures", "python", "ternary_tree", "tree" ]
stackoverflow_0074328544_data_structures_python_ternary_tree_tree.txt
Q: How to rename subfolders by numerical pattern and order based on theirs parent in python I have a folder with many sub-folders, and each sub-folder also has two sub-folders. The structure looks like this: --folder --sub-f1 --1-1000 --1-1050 --sub-f2 --1-1030 --1-1060 --sub-f3 --1-1040 --1-1...
How to rename subfolders by numerical pattern and order based on theirs parent in python
I have a folder with many sub-folders, and each sub-folder also has two sub-folders. The structure looks like this: --folder --sub-f1 --1-1000 --1-1050 --sub-f2 --1-1030 --1-1060 --sub-f3 --1-1040 --1-1070 What I want to achieve is extract the folder with smaller number in name(in the above exa...
[ "I have written a fairly verbose algorithm to explain step by step how it works:\nfrom glob import glob\nimport os\n\nroot_dir = 'folder' # specify here your root dir, in your example is \"folder\"\nparent_dirs = glob(f\"{root_dir}/*\", recursive=True) # detect all first level subdirs\n\nfor parent in parent_dirs...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074328639_python.txt
Q: How to move domain code if eventsourcing library records aggregate class path? I am exploring the eventsourcing library and wonder how to deal with source code structure changes, especially with renames and moves of aggregate classes in the domain. By default, the library uses a fully qualified class name includin...
How to move domain code if eventsourcing library records aggregate class path?
I am exploring the eventsourcing library and wonder how to deal with source code structure changes, especially with renames and moves of aggregate classes in the domain. By default, the library uses a fully qualified class name including package and module name for the topic of stored events, e.g., event_sourcing_test....
[ "Registering Old Topics\nThe eventsourcing docs provide a helpful example on registering old topics which now need to resolve to a new location. I've pasted part of their example here for convenience:\nfrom eventsourcing.utils import register_topic\n\n\nclass MyAggregate(Aggregate):\n class Started(Aggregate.Cre...
[ 0 ]
[]
[]
[ "event_sourcing", "python" ]
stackoverflow_0073640959_event_sourcing_python.txt
Q: How to extract first two characters of a string in openpyxl Python? I am trying to assign cell value in python openpxl by referencing the first 2nd characters of a string in another cell eg say the content of cell "A2" is the string "Random", I am trying to extract the first two characters Ra The codes I tried so ...
How to extract first two characters of a string in openpyxl Python?
I am trying to assign cell value in python openpxl by referencing the first 2nd characters of a string in another cell eg say the content of cell "A2" is the string "Random", I am trying to extract the first two characters Ra The codes I tried so far: import openpyxl from openpyxl import Workbook, load_workbook wb = o...
[ "You have to use the cell.value property to return a string and after that, you can slice it.\nTry this :\nws[\"A4\"].value = ws[\"A3\"].value[:2]\n\n" ]
[ 1 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0074328780_openpyxl_python.txt
Q: Pygame on two different python versions I'd like to install pygame on the newest python 3.11.0 version: if i use pip command it just keeps telling me that pygame is already installed... that is true because it is on python 3.10.8, but I want to install it on 3.11.0 too... How to install it also in the other versio...
Pygame on two different python versions
I'd like to install pygame on the newest python 3.11.0 version: if i use pip command it just keeps telling me that pygame is already installed... that is true because it is on python 3.10.8, but I want to install it on 3.11.0 too... How to install it also in the other version? Thanks ;) I tried some suggestions found o...
[ "Type out the full path to the 3.11 binary and use pip as a python module for that python binary, for example:\nC:\\some\\path\\to\\python311\\python.exe -m pip install pygame\n\nThe more complicated method, but definitely the more recommended way if you are using multiple different versions often and you wish to s...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.10", "python_3.11", "windows" ]
stackoverflow_0074329063_pygame_python_python_3.10_python_3.11_windows.txt
Q: pandas groupby converts dtype of grouped columns from string to object I am facing an issue with the fact that pandas groupby is coercing a string column into an object column for no good reason. >>> df = pd.DataFrame({"x":["a", "b"], "y":[1, 2]}) >>> df = df.astype({"x":"string", "y":"Int64"}) >>> df.dtypes x ...
pandas groupby converts dtype of grouped columns from string to object
I am facing an issue with the fact that pandas groupby is coercing a string column into an object column for no good reason. >>> df = pd.DataFrame({"x":["a", "b"], "y":[1, 2]}) >>> df = df.astype({"x":"string", "y":"Int64"}) >>> df.dtypes x string y Int64 dtype: object >>> df.groupby(["x"], as_index=False).sum()...
[ "It is not a bug. string will be consider as object class in pandas while calculation. You can also check the type of each cell\ndf.applymap(type)\nOut[72]: \n x y\n0 <class 'str'> <class 'int'>\n1 <class 'str'> <class 'int'>\ndf.groupby([\"x\"], as_index=False).sum().applymap(type)\n...
[ 0 ]
[]
[]
[ "dtype", "group_by", "pandas", "python" ]
stackoverflow_0074328889_dtype_group_by_pandas_python.txt
Q: How to create PayPal payment requests via python I am looking for a way to create payment requests via a Python desktop application. Just found out about the PayPal REST SDK but it seems not to provide a way to create standard requests like the ones every personal user can create in the webinterface. Is there anot...
How to create PayPal payment requests via python
I am looking for a way to create payment requests via a Python desktop application. Just found out about the PayPal REST SDK but it seems not to provide a way to create standard requests like the ones every personal user can create in the webinterface. Is there another way to create a request and track the progress?
[ "Simple money requests can only be sent via the web interface, but invoices can be created and sent programmatically via the Invoicing API.\n" ]
[ 0 ]
[]
[]
[ "paypal", "paypal_rest_sdk", "python" ]
stackoverflow_0074329105_paypal_paypal_rest_sdk_python.txt
Q: How do I obtain an intermediate solution using the pydrake interface to Gurobi I'm using pydrake to interface with Gurobi and solve a second-order cone program. I am hoping to get the solution at each iterate so I can see how the solution evolves. Whenever termination is due to number of iterates, the early termin...
How do I obtain an intermediate solution using the pydrake interface to Gurobi
I'm using pydrake to interface with Gurobi and solve a second-order cone program. I am hoping to get the solution at each iterate so I can see how the solution evolves. Whenever termination is due to number of iterates, the early termination appears to return the variable solutions as NaNs, regardless of the number of ...
[ "Have you looked at the \"debug mathematical program\" tutorial? https://deepnote.com/workspace/Drake-0b3b2c53-a7ad-441b-80f8-bf8350752305/project/Tutorials-2b4fc509-aef2-417d-a40d-6071dfed9199/notebook/debug_mathematical_program-9acce39e5eb642e392d86d0809fa5c76\nIn particular, for gurobi we often turn on the solv...
[ 0 ]
[]
[]
[ "drake", "python" ]
stackoverflow_0074320174_drake_python.txt
Q: How to scrape an API response that is requested by the target website? I'd like to scrape content of a website that is requested asynchronous and not visible in the source code. How can I await the website's request? I need to sniff its traffic somehow, but couldn't find anything yet. I'm looking something like th...
How to scrape an API response that is requested by the target website?
I'd like to scrape content of a website that is requested asynchronous and not visible in the source code. How can I await the website's request? I need to sniff its traffic somehow, but couldn't find anything yet. I'm looking something like that (pseudo code): import requests from bs4 import BeautifulSoup page = requ...
[ "You can't do that with BeautifulSoup, you need to use something which mimics a web browser, such as Selenium with Geckodriver.\n" ]
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074329133_python_web_scraping.txt
Q: Why some .xlsx files are successfully open with openpyxl, but others cannot be open? I am using Python 2.7 & openpyxl==2.5.11. I want to read .xlsx files using openpyxl. Initially I was testing with files downloaded from Google Drive and everything worked nice. Now, I tried to load some files generated with Micros...
Why some .xlsx files are successfully open with openpyxl, but others cannot be open?
I am using Python 2.7 & openpyxl==2.5.11. I want to read .xlsx files using openpyxl. Initially I was testing with files downloaded from Google Drive and everything worked nice. Now, I tried to load some files generated with Microsoft Excel, but I see this error: raise IOError("File contains no valid workbook part") I...
[ "this worked for me\ndf = pd.read_excel(\"Set.xlsb\", sheet_name='Dataset', engine='pyxlsb')\n\nCredits to the answer here: Using Pandas with XLSB File\n" ]
[ 0 ]
[ "probably because you didn't save those .xlsx correctly, such as simply change the files suffix to xlsx.\nHere's a solution that works for me:\nre-save the fail-to-open files to .xlsx, even if those files already have .xlsx suffix.\nif you don't know which of the files need to be resaved, start with the files with ...
[ -1 ]
[ "excel", "openpyxl", "python", "python_2.7", "xlsx" ]
stackoverflow_0053422596_excel_openpyxl_python_python_2.7_xlsx.txt
Q: Python : class definition with **kwargs When trying to instantiate the following class I am getting the following error : "TypeError: __init__() takes exactly 2 arguments (3 given)" Do you know what would be the issue ? Here is the class definition : class db_create_table(): ''' doc here ...
Python : class definition with **kwargs
When trying to instantiate the following class I am getting the following error : "TypeError: __init__() takes exactly 2 arguments (3 given)" Do you know what would be the issue ? Here is the class definition : class db_create_table(): ''' doc here ''' def __init__(self,TableName, *...
[ "In order to pass schema and to unpack it into **kwargs, you have to use **schema:\ndb_create_table('Table1', **schema)\n\nExplanation:\nThe single asterisk form (*args) unpacks a sequence to form an argument list, while the double asterisk form (**kwargs) unpacks a dict-like object to a keyworded argument list.\nW...
[ 6, 3, 0, 0 ]
[]
[]
[ "instance", "oop", "python" ]
stackoverflow_0046213381_instance_oop_python.txt
Q: Python script creates conda env inside the current conda env Following these suggestions and these instructions I want to create a conda environment bar from within a Python script. My problem is that I run the script while activated another env foo. As in the examples from the docs - the commands work, however my...
Python script creates conda env inside the current conda env
Following these suggestions and these instructions I want to create a conda environment bar from within a Python script. My problem is that I run the script while activated another env foo. As in the examples from the docs - the commands work, however my new env is created under the current one, like here: base ...
[ "This is not really a matter of conda.cli. As discussed in another question: the issue was that foo env contained conda itself inside it and while building the environment from within the script the interpreter called that \"internal\" conda, thus thinking that foo is base.\n" ]
[ 0 ]
[]
[]
[ "anaconda", "conda", "python" ]
stackoverflow_0074308690_anaconda_conda_python.txt
Q: How to add empty sub-columns to a multi-index dataframe? I'm working with a multiindex - multicolumns DataFrame in Pandas. I have 16 main columns (level 0), such as Climate Change, Ozone Depletion,etc; and each of them contains 2 subcolumns (level 1): Agriculture and Transformation. I want to create a new subcolu...
How to add empty sub-columns to a multi-index dataframe?
I'm working with a multiindex - multicolumns DataFrame in Pandas. I have 16 main columns (level 0), such as Climate Change, Ozone Depletion,etc; and each of them contains 2 subcolumns (level 1): Agriculture and Transformation. I want to create a new subcolumn (Transport) to each main column, that I will fill later wit...
[ "With the following toy dataframe as an example:\nimport pandas as pd\n\ndf = pd.DataFrame(\n [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],\n columns=pd.MultiIndex.from_product([(\"col1\", \"col2\"), (\"sub_col1\", \"sub_col2\")]),\n index=[0, 1, 2],\n)\n\nprint(df)\n# Output\n col1 col2...
[ 1 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "python" ]
stackoverflow_0074304099_dataframe_multi_index_pandas_python.txt
Q: Appending python lists into list issue I am trying to do something but having trouble with lists. I tried the following : list1=[] list2=[] for _ in range(int(input())): name = input() score = float(input()) list1.append(name) list1.append(score) list2.append(list1) list1.clear() print(li...
Appending python lists into list issue
I am trying to do something but having trouble with lists. I tried the following : list1=[] list2=[] for _ in range(int(input())): name = input() score = float(input()) list1.append(name) list1.append(score) list2.append(list1) list1.clear() print(list2) If I input something like : 2 a 1 b 2 ...
[ "The problem is in these two lines:\n list2.append(list1)\n list1.clear()\n\nlist1 in the second line refers to the same object as the list1 in the first line. You're clearing the list that you just added to list2.\nInstead do:\n list2.append(list1)\n list1 = []\n\nto create a new list....
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074329271_list_python.txt
Q: Automatically open a file send via email I am currently in the position where one of my home devices sends the data of each day in form of a .csv file via email. Thereby I can tell the device to whatever email (also multiple) it should send this file at the end of the day. The email only contains this one file att...
Automatically open a file send via email
I am currently in the position where one of my home devices sends the data of each day in form of a .csv file via email. Thereby I can tell the device to whatever email (also multiple) it should send this file at the end of the day. The email only contains this one file attached to it. So, this is what I am working wit...
[ "Here is a link to medium article that has instructions how to download attachments that came with the email\nThe program could read the csv file with Pandas library. You can do all sorts of data manipulation and also some plotting with pandas. But If you want to have really good plots you could use matplotlib and ...
[ 1 ]
[]
[]
[ "download", "email", "python" ]
stackoverflow_0074329278_download_email_python.txt
Q: How to mulitiply two arrays of different shape in numpy to get a matrix I have for example two arrays, a and b. Array a has a length of 3. Array b an arbitrary length. I would like to do the following with a numpy approach: temp_res = 0 for i in range(3): tem_res += a[i] * b a can be treated as a vector o...
How to mulitiply two arrays of different shape in numpy to get a matrix
I have for example two arrays, a and b. Array a has a length of 3. Array b an arbitrary length. I would like to do the following with a numpy approach: temp_res = 0 for i in range(3): tem_res += a[i] * b a can be treated as a vector of scalar values for multiplication. Basically I want to have a Matrix with 3 ...
[ "you need to read about numpy broadcasting, putting 1 in the first dimension of b will force broadcasting on it, a reshape only changes the stride but doesn't make a copy of the data.\ntem_res = a * b.reshape([1,-1])\n\nthis can also be written this way in case b was larger than 2D\ntem_res = a * b[None,:]\n\nExamp...
[ 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074329362_arrays_numpy_python.txt
Q: How to use modulo in if-statement to execute some functions? I have a simulation time, starting from zero and counting upwards. Then I have some if-statements, in which I set the speed of a motor to a specific value. I want to execute different stuff depending on the simulation time. E.g., if simulation_time % 500...
How to use modulo in if-statement to execute some functions?
I have a simulation time, starting from zero and counting upwards. Then I have some if-statements, in which I set the speed of a motor to a specific value. I want to execute different stuff depending on the simulation time. E.g., if simulation_time % 5000 <= 0: motorSpeed = actionList[choice1] elif simulation_time ...
[ "I might do:\nmotor_speed_cycle = (simulation_time // 5000) % 3\ncycle_list = [actionList[choice] for choice in (choice1, choice2, choice3)]\nmotorSpeed = cycle_list[motor_speed_cycle]\n\n\nThe first line sets motor_speed_cycle to a value from 0 to 2. The // 5000 breaks simulation_time into the increments of 5000 ...
[ 0 ]
[ "You can create a different variable to track this cycle and reset it when the timer exceeds specific threshold\nmotor_speed_cycle = simulation_time\n\nif motor_speed_cycle % 5000 <= 0:\n motorSpeed = actionList[choice1]\nelif motor_speed_cycle % 10000 <= 0:\n motorSpeed = actionList[choice2]\nelif motor_spee...
[ -1 ]
[ "if_statement", "modulo", "python" ]
stackoverflow_0074329322_if_statement_modulo_python.txt
Q: Find the median of a column based on criteria within dataframe and insert this as a new column I'm trying to look in a dataframe, and find the median of data within a column based on another column. I have a dataframe with 'zipcode' data and 'price' data. I want to find the median of the 'price' based on the 'zip...
Find the median of a column based on criteria within dataframe and insert this as a new column
I'm trying to look in a dataframe, and find the median of data within a column based on another column. I have a dataframe with 'zipcode' data and 'price' data. I want to find the median of the 'price' based on the 'zipcode', and report it in a new column. When I run the program as is, I get a column that reports the...
[ "You should groupby with zip code only\ndf['median_cal'] = df.groupby('zipcode')['price'].transform('median')\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074329382_dataframe_pandas_python.txt
Q: Nested function doesn't read Combobox values from outer function when changed (tkinter) In the following code, I'm facing the problem that after I choose a text from the second menu then change the color in the first menu, the background changes but the label background doesn't change, how can I fix this? For exam...
Nested function doesn't read Combobox values from outer function when changed (tkinter)
In the following code, I'm facing the problem that after I choose a text from the second menu then change the color in the first menu, the background changes but the label background doesn't change, how can I fix this? For example, if I first choose "red" and "Hi" then choose "yellow", "Hi"'s background will still be r...
[ "Since just changing color will not execute the nested function show_text() and so the text background will not be updated.\nTo fix it, bind the two comboboxes to same function which update the text based on the selections of both the comboboxes:\nfrom tkinter import *\nfrom tkinter import ttk\n\ndef show_text(even...
[ 0 ]
[]
[]
[ "combobox", "python", "tkinter" ]
stackoverflow_0074329296_combobox_python_tkinter.txt
Q: Why selenium is not starting next url after quiting the previous url Actully I'm working on some URLs. URLs are store in my database while picking one by one and looking for it resources and storing that resources in a database. if I do this with out using driver.quit() somehow for everyurl it store information fr...
Why selenium is not starting next url after quiting the previous url
Actully I'm working on some URLs. URLs are store in my database while picking one by one and looking for it resources and storing that resources in a database. if I do this with out using driver.quit() somehow for everyurl it store information from the beginning so I decide to use driver.quit now it work only for the f...
[ "You need to put the line driver = webdriver.Chrome() into the loop. That's the line that actually opens chrome. So, at the end of the loop you do driver.quit(). That closes the browser. And at the beginning of each loop you need to open it again. So place driver = webdriver.Chrome() before driver.get(full_url) ins...
[ 1 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0074328472_python_python_3.x_selenium_selenium_webdriver.txt
Q: How to link elements from a string with numbers in Python? I'd like to link elements from a string with numbers in Python. Users need to give an input string (one word such as "world") and then the elements of that string (here the letters of the word "world") needs to be linked to numbers starting from 0. Then, w...
How to link elements from a string with numbers in Python?
I'd like to link elements from a string with numbers in Python. Users need to give an input string (one word such as "world") and then the elements of that string (here the letters of the word "world") needs to be linked to numbers starting from 0. Then, when you give another string as an input, the corresponding numbe...
[ "a = \"world\"\n\ntracker = dict()\nfor index, value in enumerate(a):\n tracker[value] = index\n\nb = \"lord\"\nresult = \"\"\nfor str_char in b:\n result += str(tracker[str_char])\n\nprint(result)\n\n", "There is built-in data structure that can store key value pairs and it is called\ndictionary\nYou can make ...
[ 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074329372_python_string.txt
Q: How to get location of label in list in dataframe in pandas I want to get the uid using name for eg: someFunctionToFindUidOfName('Akt') //should return uid = 0, but don't know how to get that i am new to dataFrames please explain the answer I also want to checkif dataFrame has username and password if it has it w...
How to get location of label in list in dataframe in pandas
I want to get the uid using name for eg: someFunctionToFindUidOfName('Akt') //should return uid = 0, but don't know how to get that i am new to dataFrames please explain the answer I also want to checkif dataFrame has username and password if it has it will print "user found!" please answer in 1 and 2 differently ...
[ "\nTo get the uid from the name just simply use that:\n dataFrame[dataFrame['name'] == 'Akt']['uid']\n\n\nDo you mean if name and password columns exist?\n if 'name' in dataFrame.keys() and 'password' in dataFrame.keys():\n print('user found')\n\n\n\nHope it helps\n", "I think this is what you are looking for...
[ 0, 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074328510_dataframe_list_pandas_python.txt
Q: How do you save a Tensorflow dataset to a file? There are at least two more questions like this on SO but not a single one has been answered. I have a dataset of the form: <TensorSliceDataset shapes: ((512,), (512,), (512,), ()), types: (tf.int32, tf.int32, tf.int32, tf.int32)> and another of the form: <BatchData...
How do you save a Tensorflow dataset to a file?
There are at least two more questions like this on SO but not a single one has been answered. I have a dataset of the form: <TensorSliceDataset shapes: ((512,), (512,), (512,), ()), types: (tf.int32, tf.int32, tf.int32, tf.int32)> and another of the form: <BatchDataset shapes: ((None, 512), (None, 512), (None, 512), (...
[ "An incident was open on GitHUb and it appears there's a new feature available in TF 2.3 to write to disk :\nhttps://www.tensorflow.org/api_docs/python/tf/data/experimental/save\nhttps://www.tensorflow.org/api_docs/python/tf/data/experimental/load\nI haven't tested this features yet but it seems to be doing what yo...
[ 10, 9, 7, 2, 1, 1 ]
[]
[]
[ "python", "serialization", "tensorflow", "tensorflow_datasets" ]
stackoverflow_0061720708_python_serialization_tensorflow_tensorflow_datasets.txt
Q: Find keys of dictionary that sum to 6 I'm having trouble accessing multiple values in a dictionary. Let's say I have this dictionary: {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5} I want to find two keys that sum to 6 and display their values. Here, the keys 4 and 2 add to 6, so the 2 values are 3 and 1. Where...
Find keys of dictionary that sum to 6
I'm having trouble accessing multiple values in a dictionary. Let's say I have this dictionary: {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5} I want to find two keys that sum to 6 and display their values. Here, the keys 4 and 2 add to 6, so the 2 values are 3 and 1. Where do I start? This is the code I have so far...
[ "No need for extra loops (or itertools), they will only slow your program down. You already know what the other index needs to be (because you can subtract the index from 6), so just check if that index exists:\ndct = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}\n\nfor i, key in enumerate(dct):\n if i + 2 > ...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0074329403_dictionary_key_python.txt
Q: Pygame mouse position not precise enough to rotate the 3D scene I need to rotate a 3D scene or a character using the mouse position: for example, if I move the mouse to the right, I want to turn to the right / the character should turn right. I've seen lots of games place the mouse in the center of the screen, the...
Pygame mouse position not precise enough to rotate the 3D scene
I need to rotate a 3D scene or a character using the mouse position: for example, if I move the mouse to the right, I want to turn to the right / the character should turn right. I've seen lots of games place the mouse in the center of the screen, then get its position relatively to the previous frame, update the game ...
[ "You get the position of the mouse with pygame.mouse.get_pos() and you reset the position with pygame.mouse.set_pos(). What if there was an event between pygame.mouse.get_pos() and pygame.mouse.set_pos()? Also pygame.mouse.get_pos() only tells you the current position of the mouse curosr, but it does not tell you h...
[ 0 ]
[]
[]
[ "3d", "mouse", "pygame", "python", "rotation" ]
stackoverflow_0071593670_3d_mouse_pygame_python_rotation.txt
Q: Compound interest with adding money each year I am trying to figure out this question in python, I found the compound interest rate formula however, for me the biggest problem is how to add 50 dollars after each year after my money increased by interest rate Principal(Starting amount) is: 100 USD Yearly Interest r...
Compound interest with adding money each year
I am trying to figure out this question in python, I found the compound interest rate formula however, for me the biggest problem is how to add 50 dollars after each year after my money increased by interest rate Principal(Starting amount) is: 100 USD Yearly Interest rate: 10 percent after each year-end, we add 50 USD....
[ "capital = 100\nir = 0.1\nbonus = 50\n\ndef compound_interest(year, capital, ir, bonus):\n if year == 0:\n return capital\n \n investment_return = (capital * ir) + bonus\n\n return compound_interest(year - 1, capital + investment_return, ir, bonus)\n\nprint(compound_interest(0, capital, ir, bonus))\nprint(co...
[ 1 ]
[]
[]
[ "finance", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074329371_finance_python_python_2.7_python_3.x.txt
Q: Pycharm - unable to use fixutures or other resources from parrent directories when running pytest Pycharm version: 2022.2.3 (Professional Edition) Framework: FastAPI Tests: pytest 6.1.0 OS: macOS Monterey 12.4 There are a few posts about this with a few suggested solutions but from what I see it mainly comes down ...
Pycharm - unable to use fixutures or other resources from parrent directories when running pytest
Pycharm version: 2022.2.3 (Professional Edition) Framework: FastAPI Tests: pytest 6.1.0 OS: macOS Monterey 12.4 There are a few posts about this with a few suggested solutions but from what I see it mainly comes down to improper configuration. This could be the case here as well but none of the previous solutions look ...
[ "How do you get this file in the code?\nLooks like you are doing something like: my_json = 'tests/fixtures/some_files/datafile.json'.\nMy suggestion is that when you run it with poetry, it \"knows\" where the project root is and finds the file without problems. But when you run it using Pycharm it tries to find 'te...
[ 0 ]
[]
[]
[ "path", "pycharm", "pytest", "python", "testing" ]
stackoverflow_0074327384_path_pycharm_pytest_python_testing.txt
Q: WinError 10057 - Python TCP Server is not receiving client connections from localhost I have this python server code here, which is waiting to receive a message digest and an encrypted message from a python client. Clientside socket: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s=socket.socket(...
WinError 10057 - Python TCP Server is not receiving client connections from localhost
I have this python server code here, which is waiting to receive a message digest and an encrypted message from a python client. Clientside socket: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s=socket.socket() s.connect((HOST, PORT)) s.sendall(transmit) Server Side: with socket.socket(sock...
[ " s.bind((HOST, PORT))\n s.listen()\n conn, addr = s.accept()\n\nconn is the connected socket, s is the listener socket.\n chunk = s.recv(4096)\n\nThe error you get is because you are trying to read from the listener socket s, not from the connected socket conn:\n\nline 23, in chunk = s.recv(4096) ... A requ...
[ 0, 0 ]
[]
[]
[ "python", "sockets", "tcp", "tcpserver" ]
stackoverflow_0074329387_python_sockets_tcp_tcpserver.txt
Q: how to convert lmd file to csv? [Flow Cytometry data] lmd file extension is often used for generating flow cytometry data. But this couldn't be directly used for processing either in R or Python. Is there a way to somehow convert it to csv or some renowned format? A: This is a bit tricky. So far I haven't come a...
how to convert lmd file to csv? [Flow Cytometry data]
lmd file extension is often used for generating flow cytometry data. But this couldn't be directly used for processing either in R or Python. Is there a way to somehow convert it to csv or some renowned format?
[ "This is a bit tricky. So far I haven't come across any such direct conversion function. Perhaps, fcs is a more common format for flow-cytometry. Hence, we will first need to convert lmd to fcs and then to csv format.\nStep 1: lmd to fcs [Using R]\n# install\nsource(\"http://bioconductor.org/biocLite.R\")\nbiocLite...
[ 0, 0, 0 ]
[]
[]
[ "csv", "export_to_csv", "file_extension", "python", "r" ]
stackoverflow_0070348405_csv_export_to_csv_file_extension_python_r.txt
Q: Scrape websites with python I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and scrapy. My question is that is there any way to scrape a website without using any libra...
Scrape websites with python
I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and scrapy. My question is that is there any way to scrape a website without using any library? If there is a way to scrape a...
[ "Instead of using scrapy you can use urllib.\nInstead of beautifulsoup you can use regex.\nBut scrapy and beautifulsoup do your life easier.\nScrapy, not easy library so you can use requests or urllib.\n", "i think the best, popular and easy to learn and use libraries in python web scraping are requests, lxml and...
[ 2, 0 ]
[ "I think it's not possible to scrap websites without using any library. You can refer bellow the blog to learn more about web scraping using python. here explain how anyone can scrap websites using python in an easy manner.\nhttps://spurqlabs.com/how-to-do-web-scraping-crawling-using-python-with-selenium/\n" ]
[ -1 ]
[ "beautifulsoup", "libraries", "python", "scrapy", "web_scraping" ]
stackoverflow_0062287967_beautifulsoup_libraries_python_scrapy_web_scraping.txt
Q: Using Mechanicalsoup to navigate multiple pages / forms I've had success using mechanicalsoup with single pages / single forms, but am having difficulty with a multistep problem. The pages I am attempting to navigate start here: https://webapps2.ncua.gov/CustomQuery/CUSelect.aspx I get through the first page/form,...
Using Mechanicalsoup to navigate multiple pages / forms
I've had success using mechanicalsoup with single pages / single forms, but am having difficulty with a multistep problem. The pages I am attempting to navigate start here: https://webapps2.ncua.gov/CustomQuery/CUSelect.aspx I get through the first page/form, but then I am not sure how to deal with the second page/form...
[ "I was solving a similar issue, following the advice in MechanicalSoup follow a link without inside a button I switched to selenium\n" ]
[ 0 ]
[]
[]
[ "api", "json", "mechanicalsoup", "python", "web_scraping" ]
stackoverflow_0058153250_api_json_mechanicalsoup_python_web_scraping.txt
Q: SQLAlchemy cannot find a class name Simplified, I have the following class structure (in a single file): Base = declarative_base() class Item(Base): __tablename__ = 'item' id = Column(BigInteger, primary_key=True) # ... skip other attrs ... class Auction(Base): __tablename__ = 'auction' id...
SQLAlchemy cannot find a class name
Simplified, I have the following class structure (in a single file): Base = declarative_base() class Item(Base): __tablename__ = 'item' id = Column(BigInteger, primary_key=True) # ... skip other attrs ... class Auction(Base): __tablename__ = 'auction' id = Column(BigInteger, primary_key=True) ...
[ "This all turned out to be because of the way I've set SQLAlchemy up in Pyramid. Essentially you need to follow this section to the letter and make sure you use the same declarative_base instance as the base class for each model.\nI was also not binding a database engine to my DBSession which doesn't bother you unt...
[ 38, 20, 16, 5, 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "pyramid", "python", "relationships", "sqlalchemy" ]
stackoverflow_0009088957_pyramid_python_relationships_sqlalchemy.txt
Q: Read parquet files from S3 bucket in a for loop I want to read parquet files from an AWS S3 bucket in a for loop. Here's my code (that doesn't work): session = boto3.Session( aws_access_key_id=key, aws_secret_access_key=secret, region_name=region_name) ...
Read parquet files from S3 bucket in a for loop
I want to read parquet files from an AWS S3 bucket in a for loop. Here's my code (that doesn't work): session = boto3.Session( aws_access_key_id=key, aws_secret_access_key=secret, region_name=region_name) s3 = session.resource('s3') bucke...
[ "pandas.read_parquet() expects a a reference to the file to read, not the file contents itself as you provide it.\nFrom the documentation:\n\npath : str, path object or file-like object\nString, path object (implementing os.PathLike[str]), or file-like object implementing a binary read() function. The string could ...
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "pandas", "python" ]
stackoverflow_0074319534_amazon_s3_amazon_web_services_boto3_pandas_python.txt
Q: Button with label is not visible when system calls a funtion from another python file i have 2 python file TestBtnImage1.py and TestBtnImage2.py I am trying to call display() fucntion of TestBtnImage2 on button click of TestBtnImage1.py, button without image displying in frame, however button with image is not dis...
Button with label is not visible when system calls a funtion from another python file
i have 2 python file TestBtnImage1.py and TestBtnImage2.py I am trying to call display() fucntion of TestBtnImage2 on button click of TestBtnImage1.py, button without image displying in frame, however button with image is not displying. thanks in advance TestBtnImage1.py from tkinter import * from TestBtnImage1 import ...
[ "There are a few problems in your code.\nIn TestBtnImage1.py\n\nYou are importing itself, which will cause a NameError.\nfrom TestBtnImage1 import *\nand you just need to change it to TestBtnImage2\n\nThe geometry specifier should be 'x'\nIf you use frame.geometry('200*200'), it will cause tkinter bad geometry spec...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074326464_python_tkinter.txt
Q: Python - Shapes (None, 1) and (None, 25) are incompatible of CNN model I'm trying to train the model but I am stuck with this error ValueError: Shapes (None, 1) and (None, 24) are incompatible My code model = models.Sequential() model.add(layers.Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=(28, 28,...
Python - Shapes (None, 1) and (None, 25) are incompatible of CNN model
I'm trying to train the model but I am stuck with this error ValueError: Shapes (None, 1) and (None, 24) are incompatible My code model = models.Sequential() model.add(layers.Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=(28, 28, 1))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(laye...
[ "The problem comes from a mismatch of the last layer of your model (None, 25) and the labels (None, 1).\nThis can be fixed by changing the loss function to \"sparse_categorical_crossentropy\"\nSee What is the difference between sparse_categorical_crossentropy and categorical_crossentropy? for more details.\n" ]
[ 0 ]
[]
[]
[ "conv_neural_network", "deep_learning", "keras", "python", "tensorflow" ]
stackoverflow_0074063351_conv_neural_network_deep_learning_keras_python_tensorflow.txt
Q: Is there a way to process point in area faster in Python? shapely implementation I have attempted to try in Python the same thing I achieve in a GIS Software. I have 51 centroids to compare to 90,000+ parcels and find the overlap. It seems that my script is working (which I am happy to have been able and write) bu...
Is there a way to process point in area faster in Python? shapely implementation
I have attempted to try in Python the same thing I achieve in a GIS Software. I have 51 centroids to compare to 90,000+ parcels and find the overlap. It seems that my script is working (which I am happy to have been able and write) but I was curious if there is a way to speed this up? it takes around 5mins. I appreciat...
[ "Parse your GeoJSON file only once, not for each point you read from the CSV.\nYou can also use csv.DictReader to make your code a bit shorter.\nimport json, csv, time\nfrom shapely.geometry import Point, Polygon\n\n\ndef parse_parcel(feature: dict):\n geometry_dict = feature[\"geometry\"]\n coordinates = geo...
[ 1, 1 ]
[]
[]
[ "coordinates", "python", "shapely" ]
stackoverflow_0074315545_coordinates_python_shapely.txt
Q: How to mask inputs with variable size in transformer model when the batches needs to be masked differently? I'm making a transformer using tensorflow.keras and having issues understanding how the attention_mask works for a MultiHeadAttention layer. My input is 3-dimensional data. For example, let's assume my whole...
How to mask inputs with variable size in transformer model when the batches needs to be masked differently?
I'm making a transformer using tensorflow.keras and having issues understanding how the attention_mask works for a MultiHeadAttention layer. My input is 3-dimensional data. For example, let's assume my whole dataset has 10 elements, each one with length no more than 4: # whole data [ # first item [ [ 1, ...
[ "\nFirst, a simpler example to understand MultiHeadAttention mask.\n\n#Crude Self attention implementation\nquery = tf.constant([[1], [2], [3], [4]], dtype=tf.float32) #Shape([4, 1])\n\nscores = tf.matmul(query, query, transpose_b=True) #Shape([4, 4])\n#unnormalized, presoftmax score\n\nThe above is the attention ...
[ 1, 0 ]
[]
[]
[ "keras", "numpy", "python", "tensorflow", "transformer_model" ]
stackoverflow_0074278898_keras_numpy_python_tensorflow_transformer_model.txt
Q: pandas calculate mean of column that has lists instead of single value I have a pandas dataframe that has one column and it has a list of values in each row. I need to calculate the mean using the corresponding values from each row. That is I need the mean for eight values in the list. each element in the list is ...
pandas calculate mean of column that has lists instead of single value
I have a pandas dataframe that has one column and it has a list of values in each row. I need to calculate the mean using the corresponding values from each row. That is I need the mean for eight values in the list. each element in the list is the value of a variable >>> df_ex 0 [1, 2, 3, 4, 5, 6, 7, 8] 1 [2, 3, ...
[ "You can convert to nested lists first and then to array and then calculate the mean:\na = np.array(df_ex.tolist())\nprint (a)\n[[1 2 3 4 5 6 7 8]\n [2 3 4 5 6 7 8 1]]\n \n# Mean of all values\nprint (a.mean())\n4.5\n\n# Specify row-wise mean\nprint (a.mean(axis=1))\n[ 4.5 4.5]\n\n# Specify column-wise mean\nprint...
[ 7, 1, 0, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0047428781_dataframe_numpy_pandas_python.txt
Q: Heapsort Implementation Python I'm having some issues implementing HeapSort in python. Input sequence does not get properly sorted... The implementation looks like this: class Heap: def __init__(self, S, heapsize): self.S = S self.heapsize = heapsize def shiftdown(H, i): siftkey = H.S[i] pa...
Heapsort Implementation Python
I'm having some issues implementing HeapSort in python. Input sequence does not get properly sorted... The implementation looks like this: class Heap: def __init__(self, S, heapsize): self.S = S self.heapsize = heapsize def shiftdown(H, i): siftkey = H.S[i] parent = i spotfound = False ...
[ "There are a few issues:\n\nFirst and foremost, the algorithm states that \"S is indexed from 1 to N\". This is not how Python lists are indexed, since they start at index 0. So either you must translate the code so that all indexing is made one less, or (probably less work) you could add a dummy value at index 0 t...
[ 0, 0 ]
[]
[]
[ "algorithm", "heapsort", "python", "sorting" ]
stackoverflow_0074328017_algorithm_heapsort_python_sorting.txt
Q: Run Score in a python quiz game I was writing my first project in python : a quiz with questions, answers and final score question1 = 'When python was created?: ' question2 = 'Who wrote python?: ' question3 = 'How we call an anonymous functions in python?: ' answer1 = '1991' answer2 = 'Guido van Rossum' answer3 =...
Run Score in a python quiz game
I was writing my first project in python : a quiz with questions, answers and final score question1 = 'When python was created?: ' question2 = 'Who wrote python?: ' question3 = 'How we call an anonymous functions in python?: ' answer1 = '1991' answer2 = 'Guido van Rossum' answer3 = 'lambda' score1 = '10' score2 = '20...
[ "question1 = 'When python was created?: '\nquestion2 = 'Who wrote python?: '\nquestion3 = 'How we call an anonymous functions in python?: '\n\nanswer1 = '1991'\nanswer2 = 'Guido van Rossum'\nanswer3 = 'lambda'\n\nscore1 = 10\nscore2 = 20\nscore3 = 30\n\nresult1 = score1\nresult2 = score2\nresult3 = score3\n\n# Ques...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074329721_python.txt
Q: Best way to vectorize appending mis-matched rows into pandas dataframe from list looking for assistance in speeding up this operation. I am trying to insert list elements as rows into a pandas df where the number of list elements can be less than (but will never exceed) the number of columns. I am currently doing ...
Best way to vectorize appending mis-matched rows into pandas dataframe from list
looking for assistance in speeding up this operation. I am trying to insert list elements as rows into a pandas df where the number of list elements can be less than (but will never exceed) the number of columns. I am currently doing this in a loop, and that takes a very long time at scale. Any ideas as to how I can ve...
[ "Here is an easier and more efficient way to do that with Pandas from_records:\nimport pandas as pd\n\nmyList = [\"a/b/c\", \"a/b\", \"a\", \"a/b/c\"]\n\ndf = pd.DataFrame.from_records(\n [x.split(\"/\") for x in myList], columns=[\"col1\", \"col2\", \"col3\"]\n)\n\nThen:\nprint(df)\n# Output\n col1 col2 col3...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074292388_pandas_python.txt
Q: ERROR: No matching distribution found for torch==1.2.0 I'm checking this repo and it says it requires torch==1.2.0 in its requirements.txt. So tried install them, but I got the error. The full error: > pip install torch==1.2.0 ERROR: Could not find a version that satisfies the requirement torch==1.2.0 (from versio...
ERROR: No matching distribution found for torch==1.2.0
I'm checking this repo and it says it requires torch==1.2.0 in its requirements.txt. So tried install them, but I got the error. The full error: > pip install torch==1.2.0 ERROR: Could not find a version that satisfies the requirement torch==1.2.0 (from versions: 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 1.10.0, 1.10.1...
[ "I had the same issue with a different senario, in my case, I just downgraded the python version to 3.7.13 and torch installation was successful.\nYou may try to create a new conda environment with that version.\nThe torch installation command was conda install pytorch==1.2.0 torchvision==0.4.0 cudatoolkit=10.0 -c ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0070911456_python.txt
Q: I wanted to make a function of pangram i coded this def panagram(sen): sen= sen.replace(" ","") alphabets = ["a","b","c","d","e","f","g","h","i",'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',1] for words in sen: for letter in words: if letter.lower() in alphabe...
I wanted to make a function of pangram
i coded this def panagram(sen): sen= sen.replace(" ","") alphabets = ["a","b","c","d","e","f","g","h","i",'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',1] for words in sen: for letter in words: if letter.lower() in alphabets: alphabets.remove(letter...
[ "The problem is that you removed the spaces from the string.\nWhen the first loop is run it, as there are no spaces in the string, it instead of considering words directly takes up the letters.\nFor eg. if\nsen = \"The quick brown fox jumps over the lazy dog\"\nwhen you remove spaces, it becomes\n\"Thequickbrownfox...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074329822_python.txt
Q: Error when clicking a button using selenium I'm trying to click on a button using the selenium, but I'm getting an error. This is the error: this is the fragment of the accessed html page: This is my code: from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--he...
Error when clicking a button using selenium
I'm trying to click on a button using the selenium, but I'm getting an error. This is the error: this is the fragment of the accessed html page: This is my code: from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbo...
[ "This is (mostly) caused by element not being loaded and you're trying to perform click on it before...\nTry with this:\nWebDriverWait(wd, 2).until(EC.visibility_of_element_located((By.CLASS_NAME, 'VfPpkd-LgbsSe.VfPpkd-LgbsSe-OWXEXe-dgl2Hf.ksBjEc.lKxP2d.LQeN7.x0t5t'))).click()\n\nDon't forget to import WebDriverWai...
[ 0, 0 ]
[]
[]
[ "html", "python", "selenium" ]
stackoverflow_0074323693_html_python_selenium.txt
Q: ModuleNotFoundError: No module named 'pyomo' I am trying to run a jupyter notebook with pyomo, but get this error when trying to import from pyomo.environ. !sapt-get install -y -qq coinor-cbc from pyomo.environ import * E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied) E: Un...
ModuleNotFoundError: No module named 'pyomo'
I am trying to run a jupyter notebook with pyomo, but get this error when trying to import from pyomo.environ. !sapt-get install -y -qq coinor-cbc from pyomo.environ import * E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied) E: Unable to acquire the dpkg frontend lock (/var/lib/d...
[ "First step: If you have recently installed or updated versions, etc., log out completely and log back in to ensure you are using current environment variables. Then...\nIt is likely that your jupyter module is running inside a different python framework than the one you installed pyomo in.\nCheck it within the n...
[ 1 ]
[]
[]
[ "jupyter_notebook", "pyomo", "python", "ubuntu", "windows_subsystem_for_linux" ]
stackoverflow_0074329575_jupyter_notebook_pyomo_python_ubuntu_windows_subsystem_for_linux.txt
Q: How to get wifi snr with python? I want to get the snr(signal to noise ratio) of wifi with python. Actually, I try to set network adapter(0bda:b711) into monitor mode, then I use sniff(from scapy.all import sniff) to get some packages. But, the dBm_AntNoise is None type here from scapy.all import sniff from scapy...
How to get wifi snr with python?
I want to get the snr(signal to noise ratio) of wifi with python. Actually, I try to set network adapter(0bda:b711) into monitor mode, then I use sniff(from scapy.all import sniff) to get some packages. But, the dBm_AntNoise is None type here from scapy.all import sniff from scapy.layers.dot11 import Dot11 import time...
[ "hope this helps. I was able to produce these results.\nsudo python3 wifi.py\ndBm_AntSignal -87\ndBm_AntNoise= -89\ndBm_AntSignal -83\ndBm_AntNoise= -89\n\nUsing code based on what you provided.\n\n# FILE: wifi.py\nfrom scapy.all import *\n\nconf.use_pcap=True\n\ndef callBack(pkg):\n if pkg.haslayer(Dot11):\n ...
[ 0 ]
[]
[]
[ "linux", "python", "wifi" ]
stackoverflow_0074328963_linux_python_wifi.txt
Q: How can I clean this code ? (rock paper scissors) I made rock paper scissors game with score counter. Although it works well, I realized that the code is too heavy. import random game = 3 userScore = 0 computerScore = 0 while game != 0: print(f"game left : {game}") user = input("'r' for rock, 'p' for pap...
How can I clean this code ? (rock paper scissors)
I made rock paper scissors game with score counter. Although it works well, I realized that the code is too heavy. import random game = 3 userScore = 0 computerScore = 0 while game != 0: print(f"game left : {game}") user = input("'r' for rock, 'p' for paper and 's' for scissors : ") computer = random.choi...
[ "A few changes you can make to the main loop that make it a little simpler:\n# use 'for' and 'range' to iterate over a sequence of numbers\nfor game in range(3, 0, -1):\n\n print(f\"game left : {game}\")\n user = input(\"'r' for rock, 'p' for paper and 's' for scissors : \")\n # an iterable of single-chara...
[ 1, 0 ]
[]
[]
[ "coding_style", "list", "python" ]
stackoverflow_0074328834_coding_style_list_python.txt
Q: How to merge multiple data frames? I'm looking to merge multiple data frames. The main data frame consist of list of postal codes, and looks like so: Then I have multiple csv files with all post codes with its areas, which named subsequently (area0.csv, area1.csv, and etc. up to area26.csv) and each file looks li...
How to merge multiple data frames?
I'm looking to merge multiple data frames. The main data frame consist of list of postal codes, and looks like so: Then I have multiple csv files with all post codes with its areas, which named subsequently (area0.csv, area1.csv, and etc. up to area26.csv) and each file looks like so: I'm aiming to build a new data f...
[ "Aren't you just looking for merge?\nExample\nmaindf=pd.DataFrame({'LocationPostCode':['BB2 6PS', 'LE11 2ER', 'H91 WR26']})\ncsv1=pd.DataFrame({'pcd':['WV3 0ZQ', 'LE11 2ER'], 'ru11ind':['A1', 'A1']}) # I assume you know how to read a csv, but this dataframe is reproducible\ncsv2=pd.DataFrame({'pcd':['A21 CV51', 'H9...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074329414_dataframe_pandas_python.txt
Q: Instagram Web automation I want to get the text of the sender in my console. Here's the current code, from selenium.webdriver.chrome.options import Options from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys opt = Options() opt.add_experimenta...
Instagram Web automation
I want to get the text of the sender in my console. Here's the current code, from selenium.webdriver.chrome.options import Options from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys opt = Options() opt.add_experimental_option("debuggerAddress","lo...
[ "The search by CLASS_NAME needs one class name to find an element. But here you are giving it many class names. Class names in the \"class\" attribute are separated by spaces. So \"_ab8w _ab94 _ab97 _ab9f _ab9k _ab9p ab9 _aba8 _abcm\" is not a class name but a list of classes separated by spaces.\nBy.CLASS_NAME wil...
[ 0 ]
[]
[]
[ "automation", "python", "selenium", "web" ]
stackoverflow_0074322810_automation_python_selenium_web.txt
Q: Merging dataframe with "in" operator like approach I want to merge two dataframes. One consists of a "hit" dataframe where I have a number of protein ids. The second is a database dataframe, which contains all known proteins and their functions. See examples below. The goal is to associate my protein hits with the...
Merging dataframe with "in" operator like approach
I want to merge two dataframes. One consists of a "hit" dataframe where I have a number of protein ids. The second is a database dataframe, which contains all known proteins and their functions. See examples below. The goal is to associate my protein hits with the respective row in the database dataframe. What complica...
[ "First split each expression according to the ; symbol on a new row.\nhit_df= hit_df[\"Hits\"].str.split(\"; \", expand = False).explode().to_frame()\nprint(hit_df) \n Hits\n0 Protein_1\n1 Protein_2\n2 Protein_3A\n2 Protein_3B\n3 Protein_8\n4 Protein_5\n\n\nthen use isin function and get only matchin...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074329948_dataframe_pandas_python.txt
Q: Python simple loop of averages only returns first item I wrote a code to calculate an average, but it takes only the first item in the list. I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the average. def average_price_petrol(**args): result...
Python simple loop of averages only returns first item
I wrote a code to calculate an average, but it takes only the first item in the list. I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the average. def average_price_petrol(**args): result = 0 total = 0 for key,value in args.items(): result...
[ "In addition to the already mentioned indentation issue for return which causes the function to return on the very first loop iteration, you do not need to iterate over args.items() as you don't care about the keys.\ndef average_price_petrol(**args):\n result = 0\n total = 0\n for value in args.values():\n...
[ 3, 2 ]
[]
[]
[ "control_flow", "python" ]
stackoverflow_0074329922_control_flow_python.txt
Q: Finding non-intersection of two pytorch tensors Thanks everyone in advance for your help! What I'm trying to do in PyTorch is something like numpy's setdiff1d. For example given the below two tensors: t1 = torch.tensor([1, 9, 12, 5, 24]).to('cuda:0') t2 = torch.tensor([1, 24]).to('cuda:0') The expected output sho...
Finding non-intersection of two pytorch tensors
Thanks everyone in advance for your help! What I'm trying to do in PyTorch is something like numpy's setdiff1d. For example given the below two tensors: t1 = torch.tensor([1, 9, 12, 5, 24]).to('cuda:0') t2 = torch.tensor([1, 24]).to('cuda:0') The expected output should be (sorted or unsorted): torch.tensor([9, 12, 5])...
[ "I came across the same problem but the proposed solutions were far too slow when using larger arrays. The following simple solution works on CPU and GPU and is significantly faster than the other proposed solutions:\ncombined = torch.cat((t1, t2))\nuniques, counts = combined.unique(return_counts=True)\ndifference ...
[ 20, 3, 3, 2, 1, 1 ]
[]
[]
[ "numpy", "python", "pytorch" ]
stackoverflow_0055110047_numpy_python_pytorch.txt
Q: How can I access a fixture in a decorator? I have a fixture, let's call it myfixture, being declared using conftest.py. I'm trying to streamline a large number of tests to follow the following pattern of using decorators: @pytest.fixture def myfixture(): return True def cleanup(myfixture_value): def wrapp...
How can I access a fixture in a decorator?
I have a fixture, let's call it myfixture, being declared using conftest.py. I'm trying to streamline a large number of tests to follow the following pattern of using decorators: @pytest.fixture def myfixture(): return True def cleanup(myfixture_value): def wrapper(func): def wrapped(*args, **kwargs):...
[ "Ok so this worked. The problem is that the fixture is only really created when pytest calls the testing method, which doesn't occur before the decorators are run (AFAICT, I'm not a python expert). The workaround I had is to see if the test function had the fixture provided in its kwargs from within the decorator, ...
[ 0 ]
[]
[]
[ "fixtures", "pytest", "python", "python_decorators" ]
stackoverflow_0074328662_fixtures_pytest_python_python_decorators.txt
Q: can't get ROUGE score with pyrouge I was carrying out an experiment on text summarization. After getting the decoded sentences and reference sentences, I used pyrouge to obtain the ROUGE score, the python code is as follows: from pyrouge import Rouge155 r=Rouge155() r.model_filename_pattern = '#ID#——reference.txt'...
can't get ROUGE score with pyrouge
I was carrying out an experiment on text summarization. After getting the decoded sentences and reference sentences, I used pyrouge to obtain the ROUGE score, the python code is as follows: from pyrouge import Rouge155 r=Rouge155() r.model_filename_pattern = '#ID#——reference.txt' r.system_filename_pattern = '(\d+)_deco...
[ "I found that this issue was caused by the <s>and </s>in the reference sentences. I deleted these symbols and got the ROUGE score in the end.\n", "In general I found you have to remove from your summaries all the tags are like: <something>. In my case I used the following instruction to remove <n>:\nsummary.repla...
[ 0, 0, 0 ]
[]
[]
[ "python", "summarization", "text" ]
stackoverflow_0050386640_python_summarization_text.txt
Q: I am trying to download attachments from Outlook using Python by specifying subject line. But the code does not download any attachment Below is my code: import win32com.client import os outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers ...
I am trying to download attachments from Outlook using Python by specifying subject line. But the code does not download any attachment
Below is my code: import win32com.client import os outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case the inbox. You can change that number to reference messages = inbox.Items message = messages.GetFirst...
[ "First, the subject line may contain forbidden symbols for file names. Make sure the file name string is safe. The file will not be saved if the string contains any forbidden symbols.\nSecond, it makes sense to check the Attachment.Type property which returns an OlAttachmentType constant indicating the type of the ...
[ 1, 0 ]
[]
[]
[ "email", "office_automation", "outlook", "python", "win32com" ]
stackoverflow_0074326468_email_office_automation_outlook_python_win32com.txt
Q: Add button components to a message (discord.py) I was wondering after seeing this (message components) on discord's API reference if there was any way to implement it using python ? I tried making a json array and passing it in my message but couldn't make it work. I also tried looking on the reference for python...
Add button components to a message (discord.py)
I was wondering after seeing this (message components) on discord's API reference if there was any way to implement it using python ? I tried making a json array and passing it in my message but couldn't make it work. I also tried looking on the reference for python but couldn't find anything. Here's my code componen...
[ "New Answer\n\nDiscord.py 2.0 Allows for use of Buttons and Dropdowns, and has new added support for Slash Commands. A 3rd party repository is no longer necessary. However, if you don't want to use the default one for some reason, you can checkout discord_slash.\nTo upgrade to Discord.py 2.0:\nWindows:\npip install...
[ 16, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "api", "discord.py", "python" ]
stackoverflow_0067722188_api_discord.py_python.txt
Q: Formating user input into a txt file I am trying to format these 2 user inputs into a file on seperate lines I know I have to us the \n to use a new line but I keep getting errors with where I put it, is there another way to get each user input on a new line? ''' def userfile(): text = [] text.append(input(...
Formating user input into a txt file
I am trying to format these 2 user inputs into a file on seperate lines I know I have to us the \n to use a new line but I keep getting errors with where I put it, is there another way to get each user input on a new line? ''' def userfile(): text = [] text.append(input("Enter sentence 1: ")) text.append(inpu...
[ "You have to append it at the end of user input:\ntext.append(input(\"Enter sentence 1: \") + \"\\n\")\ntext.append(input(\"Enter sentence 2: \") + \"\\n\")\n\n", "There are several ways of doing this.\nExplictly Looping\ndef userfile():\n text = []\n\n text.append(input(\"Enter sentence 1: \"))\n text.a...
[ 0, 0 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0074330041_formatting_python.txt
Q: Given a two-digit integer, swap its digits and print the result python Is there a way to swap the digits of a 2-digit integer without converting to string and back? number = int(input()) digit_1 = number // 10 digit_2 = number % 10 swapped_number = (digit_2 * 10)+ digit_1 print(swapped_number) so this is what i ...
Given a two-digit integer, swap its digits and print the result python
Is there a way to swap the digits of a 2-digit integer without converting to string and back? number = int(input()) digit_1 = number // 10 digit_2 = number % 10 swapped_number = (digit_2 * 10)+ digit_1 print(swapped_number) so this is what i have so far and it works beside for the fact that 10 will be outputed to jus...
[ "Convert the integer to string. Then you can swap it like so:\nnumber = input()\nprint(number[::-1])\n\n", "As per my comment:\nTo reverse the digits of a 2-digit integer (assuming 10 <= x < 100):\ny = (10 * x - 1) % 99 + 1\n\nTo print a leading 0:\nf'{x:02d}'\n\nVerification\nfor x in range(1, 100):\n truth =...
[ 1, 1, 0 ]
[]
[]
[ "python", "swap" ]
stackoverflow_0074311104_python_swap.txt
Q: Thread Safety in Python's dictionary I have a class which holds a dictionary class OrderBook: orders = {'Restaurant1': None, 'Restaurant2': None, 'Restaurant3': None, 'Restaurant4': None} @staticmethod def addOrder(restaurant_name, orders): OrderBook.o...
Thread Safety in Python's dictionary
I have a class which holds a dictionary class OrderBook: orders = {'Restaurant1': None, 'Restaurant2': None, 'Restaurant3': None, 'Restaurant4': None} @staticmethod def addOrder(restaurant_name, orders): OrderBook.orders[restaurant_name] = orders And I am ...
[ "Python's built-in structures are thread-safe for single operations, but it can sometimes be hard to see where a statement really becomes multiple operations.\nYour code should be safe. Keep in mind: a lock here will add almost no overhead, and will give you peace of mind.\nhttps://web.archive.org/web/202011080912...
[ 121, 40, 28, 1 ]
[ "dict() is not thread-safe. You just need to execute the following code to see a runtime error.\nimport threading\n\ndic = dict()\n\ndef producer():\n for i in range(1000000):\n dic[i] = i\n\ndef consumer():\n for key, value in dic.items():\n print(key, value)\n\nth1 = threading.Thread(target=pr...
[ -1 ]
[ "dictionary", "multithreading", "python", "thread_safety" ]
stackoverflow_0006953351_dictionary_multithreading_python_thread_safety.txt
Q: Selenium: Loop through a list of XPATH variables and compare strings I'm writing a bot in Python that uses Selenium to play a web-based of Tic Tac Toe. I want to loop through an array of XPATHs that represent the game grid and check each square for the presence of the 'O' character. If the square is marked by an...
Selenium: Loop through a list of XPATH variables and compare strings
I'm writing a bot in Python that uses Selenium to play a web-based of Tic Tac Toe. I want to loop through an array of XPATHs that represent the game grid and check each square for the presence of the 'O' character. If the square is marked by an O, the number of that square should be appended to another list of marked...
[ "You have to loop through the length of the 'Board.squares' list, like this:\nfor i in range(len(Board.squares)):\n text = driver.find_element(By.XPATH, Board.squares[i]).text\n\nOutput:\n(//div[contains(@class, 'board-row')]//button[contains(@class, 'square')])[1]\n(//div[contains(@class, 'board-row')]//button[...
[ 1, 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074319605_python_selenium_selenium_webdriver.txt
Q: I am getting an error "Fatal error no such file or directory #include 'Python.h'" while building wheel for cytoolz I tried to install tronpy module in Pydroid 3, but it failed with an error FileNotFound. I used this command: pip3 install tronpy And got this error message: /storage/emulated/0 $ pip3 install tronpy...
I am getting an error "Fatal error no such file or directory #include 'Python.h'" while building wheel for cytoolz
I tried to install tronpy module in Pydroid 3, but it failed with an error FileNotFound. I used this command: pip3 install tronpy And got this error message: /storage/emulated/0 $ pip3 install tronpy Collecting tronpy Using cached tronpy-0.2.6-py3-none-any.whl (34 kB) Collecting base58<3.0.0,>=2.0.0 Using cached b...
[ "I used Termux and wrote apt install python-dev and then I installed tronpy and started my code by typing python and then my code.\nThanks for comment.\n" ]
[ 0 ]
[]
[]
[ "c", "python", "python_3.x", "tron" ]
stackoverflow_0074328752_c_python_python_3.x_tron.txt
Q: Resizing PIL Image gives a completely black image I have a dataset of grayscale images, like this one below: Now, I open my dataset with the following class: """Tabular and Image dataset.""" def __init__(self, excel_file, image_dir): self.image_dir = image_dir self.excel_file = excel_file...
Resizing PIL Image gives a completely black image
I have a dataset of grayscale images, like this one below: Now, I open my dataset with the following class: """Tabular and Image dataset.""" def __init__(self, excel_file, image_dir): self.image_dir = image_dir self.excel_file = excel_file self.tabular = pd.read_excel(excel_file) ...
[ "You have either shared a different file from the one your code opens, or imgur has changed your file. In any case, the most expedient way to examine the content of your file on Linux/Unix/macOS without installing any software is to use the file command. So, checking your file we can see that it is an 8-bit PNG wit...
[ 1 ]
[]
[]
[ "image_classification", "image_size", "python", "python_imaging_library", "pytorch" ]
stackoverflow_0074327197_image_classification_image_size_python_python_imaging_library_pytorch.txt
Q: While loop only takes one condition The while loop command only takes one condition or it'll ignore them entirely. The script ends up running the program infinitely. I've tried running the keyboard condition as a variable. I've also tried a variable counter (while i < 4) as one of the conditions with the same res...
While loop only takes one condition
The while loop command only takes one condition or it'll ignore them entirely. The script ends up running the program infinitely. I've tried running the keyboard condition as a variable. I've also tried a variable counter (while i < 4) as one of the conditions with the same results. Switching the conditions and putti...
[ "If one of the 2 conditions is true then it keeps on looping.\nIn order to exit the loop both conditions MUST be false.\nMeaning :\n\nblue must be true\nq must be pressed\n\nDon't know pyautogui and its is_pressed() behaviour. May be you've to keep the finger on the q key to satisfy the 2nd condition ?\n" ]
[ 0 ]
[]
[]
[ "infinite_loop", "python", "while_loop" ]
stackoverflow_0074330013_infinite_loop_python_while_loop.txt
Q: Count of uninterrupted loop iterations In Python, I often find myself implementing the same pattern: count the number of "valid" iterations while processing within a loop, where an "invalid" iteration is skipped over with a continue statement. I use the continue statement instead of if-else blocks to improve reada...
Count of uninterrupted loop iterations
In Python, I often find myself implementing the same pattern: count the number of "valid" iterations while processing within a loop, where an "invalid" iteration is skipped over with a continue statement. I use the continue statement instead of if-else blocks to improve readability. Essentially, I do the following: cou...
[ "No, I think the very first version:\ncount = 0\nfor item in collection:\n do_something_1(item)\n if not evaluate_some_condition(item):\n continue\n count += 1\n do_something_2(item)\nreturn count\n\nis pretty much how it is done and it very obvious (i.e. readable) what is happening. If you compa...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074318261_python_python_3.x.txt
Q: access json file error - string indices must be integers I have the following problem, and I am not sure how to access the item from a nested json file. Could anyone help me out here, please! intents = {"intents": [ {"tag": "greeting", "patterns": ["Hi", "Hey", "Is anyone there?", "Hello", "Hay"], "r...
access json file error - string indices must be integers
I have the following problem, and I am not sure how to access the item from a nested json file. Could anyone help me out here, please! intents = {"intents": [ {"tag": "greeting", "patterns": ["Hi", "Hey", "Is anyone there?", "Hello", "Hay"], "responses": ["Hello", "Hi", "Hi there"] }, {"tag": "goo...
[ "You're double-encoding the Json. Drop the first new_intents = json.dumps(intents, indent=4) and it should work:\n# remove this line:\n# new_intents = json.dumps(intents, indent=4)\n\nwith open('json_data.json', 'w') as outfile:\n json.dump(intents, outfile, indent=4) # <-- change new_intents to intents\n\nwit...
[ 1, 0 ]
[]
[]
[ "json", "nlp", "python", "typeerror" ]
stackoverflow_0074330055_json_nlp_python_typeerror.txt
Q: print a dictionary adding a blank space between each blocks New to python. Here's a nested dictionary with two books each having 8 attributes. book_collection ={17104: {'Title': 'A River', 'Author': 'Elisha Mitchell', 'Publisher': 'FPG Publishing', 'Pages': '345', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID':...
print a dictionary adding a blank space between each blocks
New to python. Here's a nested dictionary with two books each having 8 attributes. book_collection ={17104: {'Title': 'A River', 'Author': 'Elisha Mitchell', 'Publisher': 'FPG Publishing', 'Pages': '345', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID': 17104}, 37115: {'Title': 'Aim High', 'Author': 'George Tayloe Wi...
[ "Use this:\n for id, book in book_collection.items():\n for book_attribute, attribute_value in book.items():\n print(book_attribute, ': ', attribute_value, sep='')\n print()\n\nYou can just use the index() function to check if the index is 9 then ask like this\nfor id, book in book_collecti...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074329940_dictionary_python.txt
Q: How do I create a random VECTOR I'm completely new to Python, in fact the last time I knew any programming it was commodor-64 basic (apologies). I'm trying to create random vectors in PYHON. The vector is 52 digits bit only containing 0 - 12 and the vector itself must not repeat. I tried this... from random impor...
How do I create a random VECTOR
I'm completely new to Python, in fact the last time I knew any programming it was commodor-64 basic (apologies). I'm trying to create random vectors in PYHON. The vector is 52 digits bit only containing 0 - 12 and the vector itself must not repeat. I tried this... from random import randint vector = [randint(0...
[ "Your question is a little difficult to parse, but with less than 52 values trying to fill 52 indicies, you fundamentally want more degrees than you have!\nInstead of trying to make a list from random elements, you could create a collection indexing each card and shuffle or take without replacement from it!\ncard_i...
[ 0 ]
[]
[]
[ "python", "random", "vector" ]
stackoverflow_0074327322_python_random_vector.txt
Q: Pandas split and replace string value in a column and create binary encoded columns I have the following list of values per row. I would like to split these values into separate categories and create separate columns. Some of these values belong to the same category. So I need to categorise them in columns 0, Body...
Pandas split and replace string value in a column and create binary encoded columns
I have the following list of values per row. I would like to split these values into separate categories and create separate columns. Some of these values belong to the same category. So I need to categorise them in columns 0, Body;TSS1500 1, TSS200 2, 3, 1stExon;3'UTR 4, 5, TSS200;TSS200;TSS200 6, 1stExon;3'UTR 7, TSS...
[ "With the dataframe you provided:\n\ndf = pd.DataFrame(\n {\n \"Values\": [\n \"Body;TSS1500\",\n \"TSS200\",\n \"1stExon;3'UTR\",\n \"TSS200;TSS200;TSS200\",\n \"1stExon;3'UTR\",\n \"TSS1500\",\n \"1stExon;5'UTR\",\n ...
[ 0 ]
[]
[]
[ "binary", "dataframe", "pandas", "python", "replace" ]
stackoverflow_0074270758_binary_dataframe_pandas_python_replace.txt
Q: Vscode keras intellisense(suggestion) not working properly Intellisense works fine on importing phrase But when it comes with chaining method, it shows different suggestions Python & Pylance extensions are installed. A: From this issue on github try adding this to the bottom of your tensorflow/__init__.py (in ...
Vscode keras intellisense(suggestion) not working properly
Intellisense works fine on importing phrase But when it comes with chaining method, it shows different suggestions Python & Pylance extensions are installed.
[ "From this issue on github\ntry adding this to the bottom of your tensorflow/__init__.py (in .venv/Lib/site-packages/tensorflow for me)\n# Explicitly import lazy-loaded modules to support autocompletion.\n# pylint: disable=g-import-not-at-top\nif _typing.TYPE_CHECKING:\n from tensorflow_estimator.python.estimator....
[ 10, 0, 0, 0 ]
[]
[]
[ "autocomplete", "python", "visual_studio_code" ]
stackoverflow_0068860879_autocomplete_python_visual_studio_code.txt
Q: Template matching with multiple objects in OpenCV Python I'm trying to find multiple templates in an image using opencv python, according to this link. But the problem is that multiple points returned for a single object with a slightly difference in position. Something like this: I dont want to use cv2.minMaxLoc...
Template matching with multiple objects in OpenCV Python
I'm trying to find multiple templates in an image using opencv python, according to this link. But the problem is that multiple points returned for a single object with a slightly difference in position. Something like this: I dont want to use cv2.minMaxLoc() because there is multiple templates in image. I wrote a fun...
[ "One way to find multiple matches is to write over the found matches and run the match again. Edit: A better way to find multiple matches is to write over the results. In the first example we fill the matched part of results with zeroes (use ones for SQDIFF or CCORR_NORMED) , and then look for the next match in a l...
[ 7, 2, 1 ]
[]
[]
[ "computer_vision", "image_processing", "opencv", "python", "template_matching" ]
stackoverflow_0050579050_computer_vision_image_processing_opencv_python_template_matching.txt
Q: Should I scale datetime variables? I have a dataframe with different weather variables and datetime variables (month, day, hour). I'm going to use the variables to predict number of cyclist. I want to scale the variables with StandardScaler, but should I include the datetime variables as well, or just scale the we...
Should I scale datetime variables?
I have a dataframe with different weather variables and datetime variables (month, day, hour). I'm going to use the variables to predict number of cyclist. I want to scale the variables with StandardScaler, but should I include the datetime variables as well, or just scale the weather variables? It just feels wrong to ...
[ "You should not scale datetime values cause its just the track of features and not features it self\n" ]
[ 0 ]
[]
[]
[ "data_science", "python" ]
stackoverflow_0074330003_data_science_python.txt
Q: Converting a file into a list and then into a dictionary I'm working with a file right now where every line of data is sorted like " Dog 15 28 0 58 79 01" and I'm trying to convert it to a dictionary where Dog is the key and the others are the values. Because its not split by comma's I've figured out that I should...
Converting a file into a list and then into a dictionary
I'm working with a file right now where every line of data is sorted like " Dog 15 28 0 58 79 01" and I'm trying to convert it to a dictionary where Dog is the key and the others are the values. Because its not split by comma's I've figured out that I should probably .split it to convert it to a list then use a for eac...
[ "You can't have multiple values for a single a key. There is always a key-value pair. A single key can only have a single value.\nEdit:\nAccording to the comment, you can do it like this\ndata = \"Dog 15 28 0 58 79 01\"\n\nd = {}\nd[data.split(\" \")[0]] = data.split(\" \")[1:]\n\nEdit:\nFor every line in the file ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074330092_python.txt
Q: assertDictEqual with pandas DF I need to combine assertDictEqual with pandas.testing.assert_frame_equal. let's assume I have the following functions: def function_to_test(): data = {'Name': ['Tom', 'Joseph'], 'Age': [20, 21]} df = pd.DataFrame(data) return {"key_first_level": {"key_second_level": df}} ...
assertDictEqual with pandas DF
I need to combine assertDictEqual with pandas.testing.assert_frame_equal. let's assume I have the following functions: def function_to_test(): data = {'Name': ['Tom', 'Joseph'], 'Age': [20, 21]} df = pd.DataFrame(data) return {"key_first_level": {"key_second_level": df}} def test_function_to_test(): ...
[ "The assertDictEqual method is comparing the 2 dicts using the != operator. While the dict type returns a single True/False for the != and == operations, DataFrame returns True/False for every value in the table and that is what actually causing the error ValueError: The truth value of a DataFrame is ambiguous. Use...
[ 0 ]
[]
[]
[ "assert", "python", "python_unittest" ]
stackoverflow_0074322841_assert_python_python_unittest.txt
Q: trying to extract month but got an error integer argument expected, got float data.info() data['Timestamp']=pd.to_datetime(data['Timestamp'], errors='coerce') import datetime as dt #function for month def get_month(x): return dt.datetime(x.year, x.month,1) #apply the function data['get_Timestamp'] = data['Ti...
trying to extract month but got an error integer argument expected, got float
data.info() data['Timestamp']=pd.to_datetime(data['Timestamp'], errors='coerce') import datetime as dt #function for month def get_month(x): return dt.datetime(x.year, x.month,1) #apply the function data['get_Timestamp'] = data['Timestamp'].apply(get_month) data.tail() i want get my timestamp month like 2022-1...
[ "To extract month usually you can extract via the below snippet\ndf['get_Timestamp'] = df['ArrivalDate'].dt.month\n\n", "You use errors='coerce'. This means that there can be Nat values ​​in the dataset. You may be getting an error because the function you are using is trying to convert the Nat value. You can set...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074330058_pandas_python.txt
Q: SytanxError with sg. argument from PySimpleGUI in Python I want to make a widget window, but the Bottom and Text part aren't working properly and it keps getting sintax errors at the same part: import PySimpleGUI as sg layout = [ [sg.Text("Hello from PySimpleGUI")], [sg.Button("Close")] window = sg.W...
SytanxError with sg. argument from PySimpleGUI in Python
I want to make a widget window, but the Bottom and Text part aren't working properly and it keps getting sintax errors at the same part: import PySimpleGUI as sg layout = [ [sg.Text("Hello from PySimpleGUI")], [sg.Button("Close")] window = sg.Window("Demo, layout") ] while true: event, values = window...
[ "This:\nlayout = [\n [sg.Text(\"Hello from PySimpleGUI\")], \n [sg.Button(\"Close\")]\n window = sg.Window(\"Demo, layout\")\n]\n\nisn't a valid list, because you can't include an assignment like that, and there should be a comma after the second element. Also, the call to sg.Window() doesn't look right, b...
[ 0, 0 ]
[]
[]
[ "pysimplegui", "python", "syntax_error" ]
stackoverflow_0074330244_pysimplegui_python_syntax_error.txt
Q: Append values with different lengths from one dictionary to another I have a dictionary with list values of a different length. I'm needed to get the values that are in the same position associated to the same key in a new dictionary. Original Dictionay {A: [1,2] , B: [3,4,5]} New Dictionary: {A: [1,3], B: [2,4], ...
Append values with different lengths from one dictionary to another
I have a dictionary with list values of a different length. I'm needed to get the values that are in the same position associated to the same key in a new dictionary. Original Dictionay {A: [1,2] , B: [3,4,5]} New Dictionary: {A: [1,3], B: [2,4], C: [5]} I tried a for loop and wrapping my values in zip_longest, but am ...
[ "I would add a condition when looping through the values of the dict sub_folder_notebooks to make sure that you can access elem[x]. not the nicest way but should do the trick:\nfor x in range(0, max([len(v) for v in sub_folder_notebooks.values()])):\nnotebook_step[x] = zip_longest([elem[x] for elem in sub_folder_no...
[ 0 ]
[]
[]
[ "dictionary", "for_loop", "python" ]
stackoverflow_0074330175_dictionary_for_loop_python.txt
Q: How to see the attributes of argparse.NameSpace Python object? For a project involving multiple scripts (data processing, model tuning, model training, testing, etc.) I may keep all my <class 'argparse.ArgumentParser'> objects as the return value of functions for each script task in a module I name cli.py. However...
How to see the attributes of argparse.NameSpace Python object?
For a project involving multiple scripts (data processing, model tuning, model training, testing, etc.) I may keep all my <class 'argparse.ArgumentParser'> objects as the return value of functions for each script task in a module I name cli.py. However, in the calling script itself (__main__), after calling args = pars...
[ "I don't know about VSCode, in an ipython session, the tab complete does show the available attributes of Namespace. argparse.Namespace is a relatively simple object class. What you want, I think, are just the attributes of this object.\nIn [238]: args = argparse.Namespace(test='one', foo='three', bar=3)\nIn [239...
[ 1, 0 ]
[]
[]
[ "argparse", "python", "visual_studio_code" ]
stackoverflow_0069982081_argparse_python_visual_studio_code.txt
Q: How can I remove the last 20 % of a dataset? I have a dataset and want to remove the last 20 % of the rows I have a dataset and want to remove the last 20 % of the rows A: After loading the dataset if you are using pandas and python You can do something like that. df = df.iloc[: -int(df.shape[0] * 0.2), :] # 0.2...
How can I remove the last 20 % of a dataset?
I have a dataset and want to remove the last 20 % of the rows I have a dataset and want to remove the last 20 % of the rows
[ "After loading the dataset if you are using pandas and python\nYou can do something like that.\ndf = df.iloc[: -int(df.shape[0] * 0.2), :] # 0.2 is 20 % of the rows\n\niloc is used to select rows by number (integer location)\n" ]
[ 0 ]
[]
[]
[ "data_cleaning", "dataset", "python" ]
stackoverflow_0074330320_data_cleaning_dataset_python.txt
Q: Indexing numpy arrays only if within bounds I have a 2d numpy array psi with shape (nx,ny). I want to create a new array phi of the same shape where for each element phi[i][j] I need to evaluate an expression containing psi[i][j] and neighboring elements psi[i-1][j],psi[i+1][j],psi[i][j+1] and psi[i][j-1],except f...
Indexing numpy arrays only if within bounds
I have a 2d numpy array psi with shape (nx,ny). I want to create a new array phi of the same shape where for each element phi[i][j] I need to evaluate an expression containing psi[i][j] and neighboring elements psi[i-1][j],psi[i+1][j],psi[i][j+1] and psi[i][j-1],except for edge cases where any of these neighbors are no...
[ "This problem smells like finite differences. Your best bet is to write a (fast, possibly recursive) loop for the inner points, and then loop over the boundary points separately, imposing the desired boundary conditions there. Obviously, the other way around also works: start by assigning boundary points, then loop...
[ 0, 0 ]
[]
[]
[ "arrays", "conditional_statements", "indexing", "numpy", "python" ]
stackoverflow_0074186157_arrays_conditional_statements_indexing_numpy_python.txt
Q: Empty list of ids in a Kivy GridLayout I am trying to develop a toy app with Kivy. So far I have a grid of 9 x 9 TextInput widgets that have been added programmatically to a GridLayout (I refer to it by the id "grid" in my kv file). For some reason, although I am assigning an id to each of the TextInput widgets, t...
Empty list of ids in a Kivy GridLayout
I am trying to develop a toy app with Kivy. So far I have a grid of 9 x 9 TextInput widgets that have been added programmatically to a GridLayout (I refer to it by the id "grid" in my kv file). For some reason, although I am assigning an id to each of the TextInput widgets, the ids dictionary that I get in the get_widg...
[ "The ids dict is populated only from kv ids. The Kivy property that widgets have is actually unrelated, and I'm not sure if it's used for anything.\n", "Sticking this in there might fix your problems\nself.ids = {child.id:child for child in self.children}\n\n", "Answer from Lawrence DU did not solve my problem,...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0035150338_kivy_python.txt
Q: How to iterate through items in a list that have commas in them? I have a class instance: self.robots = ROBOT() And I want to run my code such that I will have the following arguments passed into it: bestBrains[overallChampionIndex],-8,0 bestBrains[overallChampionIndex],-4,-4 bestBrains[overallChampionIndex],-4,4...
How to iterate through items in a list that have commas in them?
I have a class instance: self.robots = ROBOT() And I want to run my code such that I will have the following arguments passed into it: bestBrains[overallChampionIndex],-8,0 bestBrains[overallChampionIndex],-4,-4 bestBrains[overallChampionIndex],-4,4 In successive iterations. So the first iteration will be: self.robot...
[ "as suggested in the comment you can use the asterisk operator this way:\nself.robots[*self.position[i]]\n\nor simply by accessing the elements of your tuple this way:\nself.robots[self.position[i][0], self.position[i][1], self.position[i][2]]\n\n" ]
[ 1 ]
[]
[]
[ "arguments", "list", "python" ]
stackoverflow_0074330269_arguments_list_python.txt
Q: How to pipe the result of "ngrok http 8000" to another file? I use ngrok for testing webhooks, and I find myself constantly copy/pasting the newly generated ngrok host into several places, so I decided to automate this process, but can't seem to find a clean way to extract the url from the ngrok process. I expecte...
How to pipe the result of "ngrok http 8000" to another file?
I use ngrok for testing webhooks, and I find myself constantly copy/pasting the newly generated ngrok host into several places, so I decided to automate this process, but can't seem to find a clean way to extract the url from the ngrok process. I expected to be able to pipe the output to a file, then extract it using r...
[ "Instead of get result output from ngrok http <port>, you can use agent api.\nLike screenshot in your question, when you execute ngrok http proxy, ngrok serves Web Interface (http://127.0.0.1:4040 in this case.)\nThis, Web Interface also support some APIs including able to retrieve public url (this is what you want...
[ 1 ]
[]
[]
[ "bash", "ngrok", "python", "sh" ]
stackoverflow_0063492743_bash_ngrok_python_sh.txt
Q: How to limit list of string is pattern with regex? I tried to compose patten with regex, and tried to validate multiple strings. However, seems my patterns fine according to regex documentation, but some reason, some invalid string is not validated correctly. Can anyone point me out what is my mistakes here? test ...
How to limit list of string is pattern with regex?
I tried to compose patten with regex, and tried to validate multiple strings. However, seems my patterns fine according to regex documentation, but some reason, some invalid string is not validated correctly. Can anyone point me out what is my mistakes here? test use case this is test use case for one input string: imp...
[ "The \\w character class also matches underscores and numbers:\n\nMatches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.\n\n(https://docs.python.org/3/library/re.html#r...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074324330_python_regex.txt
Q: I need help witht this python code its being annoying it gives me a error Code : from sys import exit didlogcorrect = 1 Minecraft = 'Minecraft' Roblox = 'Roblox' Exit = 'Exit' chrome = 'chrome' print('Welcome To PotatOS') user_input = input("What would you like to do on PotatOS: ") if user_input == Roblox: ...
I need help witht this python code its being annoying it gives me a error
Code : from sys import exit didlogcorrect = 1 Minecraft = 'Minecraft' Roblox = 'Roblox' Exit = 'Exit' chrome = 'chrome' print('Welcome To PotatOS') user_input = input("What would you like to do on PotatOS: ") if user_input == Roblox: print('Unable to connect to wifi Now terminating process') elif user_input ...
[ "Functionalities:\nThe built-in input function writes a prompt to standard output without a trailing newline and then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.\nAs you want to compare values, you need to check the user input like this using if/elif/else state...
[ 2, 1 ]
[ "I suggest doing\nuser_input = input(\"What would you like to do on PotatOS\")\n\nThen doing something with user_input. The key here is to keep each line of code as simple as possible. As you learn more about python, you will discover when it is appropriate to chain two method calls together, but until then, don't....
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0074330301_python_python_3.x.txt
Q: Use value of primary key in FileField upload_to function Given the following model I am attempting to use the models ID field (a UUID) in the upload_to path but its defined as None, presumably as it hasn't been generated at that point. If I use a UUID field that isn't defined as the primary key it works OK. How do...
Use value of primary key in FileField upload_to function
Given the following model I am attempting to use the models ID field (a UUID) in the upload_to path but its defined as None, presumably as it hasn't been generated at that point. If I use a UUID field that isn't defined as the primary key it works OK. How do I get the value of the id field at the point picture_path is ...
[ "Since in your example primary key is generated as uuid4 and does not depend on DB counter - you can safely generate it upfront.\nIn other words - you don't have to wait for DB insert to get primary key - you can make it yourself and then insert into DB (being pretty sure that it's unique - because it's uuid4)\nSo,...
[ 1 ]
[]
[]
[ "django", "django_file_upload", "django_models", "python" ]
stackoverflow_0074327498_django_django_file_upload_django_models_python.txt
Q: Python-No such file or directory getAttribute.js I had a Python selenium program working a week or so ago. Now selenium fails on the import: from selenium import webdriver The IDLE ouput: Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "lice...
Python-No such file or directory getAttribute.js
I had a Python selenium program working a week or so ago. Now selenium fails on the import: from selenium import webdriver The IDLE ouput: Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> RESTART: C:\Users\M...
[ "The error does gives us some hint on whats wrong happening as follows :\nFileNotFoundError: [Errno 2] No such file or directory: 'C:\\\\Users\\\\Mike\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36-32\\\\lib\\\\site-packages\\\\selenium\\\\webdriver\\\\remote\\\\getAttribute.js'\n\nWhich essentially means ge...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0048859312_python_selenium_selenium_webdriver.txt
Q: How to read a file but only the context after the = in python Hello i am creating a web browser and i want to have a config file. My config file goes like this # (a commend to help with editing the config file) default-webpage = google.com dark-mode = true and many more things and i want to put the context befor...
How to read a file but only the context after the = in python
Hello i am creating a web browser and i want to have a config file. My config file goes like this # (a commend to help with editing the config file) default-webpage = google.com dark-mode = true and many more things and i want to put the context before and after the = on a dictionary when i can access and take the va...
[ "If you want to code a solution manually, you can try the following to split each line into a key-value pair and store it in a config dictionary:\nconfig = open(\"config.cfg\", \"r\")\ncontext = config.readlines()\nconfig_dict = {}\nfor line in context:\n split_line = line.split('=')\n key, value = split_line...
[ 0 ]
[]
[]
[ "config", "dictionary", "file", "python" ]
stackoverflow_0074330369_config_dictionary_file_python.txt