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: How to get difference between current timestamp and a different timestamp? I am trying get difference between two timestamps and check if its greater than 30 mins timestamp1 = 1668027512 now = datetime.now(tz) And this is what i am trying to do from datetime import datetime import pytz as tz tz = tz.timezone('UTC...
How to get difference between current timestamp and a different timestamp?
I am trying get difference between two timestamps and check if its greater than 30 mins timestamp1 = 1668027512 now = datetime.now(tz) And this is what i am trying to do from datetime import datetime import pytz as tz tz = tz.timezone('UTC') import time timestamp1 = 1668027512 timestamp1 = datetime.utcfromtimestamp(i...
[ "from datetime import datetime\n\n# 30 minutes times 60 seconds\nthirty_minutes = 30 * 60\n\npast_timestamp = 1668027512\nnow_timestamp = datetime.now().timestamp()\n\nif (now_timestamp - past_timestamp) > thirty_minutes:\n # do your thing\n\n", "The problem you are facing is that when you use .strftime(\"%Y-...
[ 1, 0, 0 ]
[]
[]
[ "datetime", "python", "unix_timestamp" ]
stackoverflow_0074605684_datetime_python_unix_timestamp.txt
Q: Malformed query in elasticsearch search = { "from": str(start), "size": str(size), "query": { "bool": { "must": { "multi_match": { "query":query, "fields":["name","description","tags","comments","created","creator","transaction","walle...
Malformed query in elasticsearch
search = { "from": str(start), "size": str(size), "query": { "bool": { "must": { "multi_match": { "query":query, "fields":["name","description","tags","comments","created","creator","transaction","wallet"], "operator":"or"} ...
[ "So the issue is some of those fields are arrays and need [] inside them. Specifically must and filter. Adding appropriate braces solved the issue. Here's the new format:\nsearch = {\n \"from\": start,\n \"query\": {\n \"bool\": {\n \"must\": [\n { \"multi_match\": {\n \"query\": query,...
[ 0 ]
[]
[]
[ "elasticsearch", "python" ]
stackoverflow_0074540296_elasticsearch_python.txt
Q: PySpark: create column based on value and dictionary in columns I have a PySpark dataframe with values and dictionaries that provide a textual mapping for the values. Not every row has the same dictionary and the values can vary too. | value | dict | | -------- | -----...
PySpark: create column based on value and dictionary in columns
I have a PySpark dataframe with values and dictionaries that provide a textual mapping for the values. Not every row has the same dictionary and the values can vary too. | value | dict | | -------- | ---------------------------------------------- | | 1 | {"1": "Text ...
[ "Hope this helps.\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nimport json\n\n\nif __name__ == '__main__':\n spark = SparkSession.builder.appName('Medium').master('local[1]').getOrCreate()\n df = spark.read.format('csv').option(\"header\",\"true\...
[ 1, 1 ]
[]
[]
[ "apache_spark_sql", "dictionary", "mapping", "pyspark", "python" ]
stackoverflow_0074599729_apache_spark_sql_dictionary_mapping_pyspark_python.txt
Q: Safely and Asynchronously Interrupt an Infinite-Loop Python Script started by a BASH script via SSH My Setup: I have a Python script that I'd like to run on a remote host. I'm running a BASH script on my local machine that SSH's into my remote server, runs yet another BASH script, which then kicks off the Python s...
Safely and Asynchronously Interrupt an Infinite-Loop Python Script started by a BASH script via SSH
My Setup: I have a Python script that I'd like to run on a remote host. I'm running a BASH script on my local machine that SSH's into my remote server, runs yet another BASH script, which then kicks off the Python script: Local BASH script --> SSH --> Remote BASH script --> Remote Python script The Python script config...
[ "In combining the suggestions from the comments (and lots of help from a buddy), I've got something that works for me:\n\nSolution 1:\nIn summary, I made my remote BASH script record its Group Process ID (GPID; that which is also assigned to the Python script that is spawned by the remote BASH script) to a file, an...
[ 0 ]
[]
[]
[ "bash", "python", "ssh" ]
stackoverflow_0074527122_bash_python_ssh.txt
Q: Python subprocess.run() batch file with updating variables I want to ask how can I run an external batch file while updating the variable before I run the process. The detail for my question is following: I have a batch file right now, while it performs a simulation process. I want to write a module that I can upd...
Python subprocess.run() batch file with updating variables
I want to ask how can I run an external batch file while updating the variable before I run the process. The detail for my question is following: I have a batch file right now, while it performs a simulation process. I want to write a module that I can update the variable first without manually updating the batch files...
[ "\nCan someone give ... any possible solution ...?\n\n\nin a loop\n\nopen and read the batch file (--> results in a string)\nuse pattern matching to find then replace the relevant parts of that string with your data\nwrite the modified string to the batch file\nrun the batch file with subprocess and get its results...
[ 0, 0 ]
[]
[]
[ "batch_file", "python", "subprocess" ]
stackoverflow_0074605590_batch_file_python_subprocess.txt
Q: How to convert a sympy decimal number to a Python decimal? In sympy I can for example do: from sympy import EulerGamma EulerGamma.n(60) 0.577215664901532860606512090082402431042159335939923598805767 I would like to convert that into a Decimal number without losing any precision. from decimal import Decimal as D i...
How to convert a sympy decimal number to a Python decimal?
In sympy I can for example do: from sympy import EulerGamma EulerGamma.n(60) 0.577215664901532860606512090082402431042159335939923598805767 I would like to convert that into a Decimal number without losing any precision. from decimal import Decimal as D import decimal decimal.getcontext().prec = 100 D(EulerGamma.n(60)...
[ "Try doing D(str(EulerGamma.n(60))). This will construct a Decimal from the object's string representation.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074606080_python.txt
Q: installing python packages without internet and using source code as .tar.gz and .whl we are trying to install couple of python packages without internet. For ex : python-keystoneclient For that we have the packages downloaded from https://pypi.python.org/pypi/python-keystoneclient/1.7.1 and kept it in server. Ho...
installing python packages without internet and using source code as .tar.gz and .whl
we are trying to install couple of python packages without internet. For ex : python-keystoneclient For that we have the packages downloaded from https://pypi.python.org/pypi/python-keystoneclient/1.7.1 and kept it in server. However, while installing tar.gz and .whl packages , the installation is looking for dependen...
[ "This is how I handle this case:\nOn the machine where I have access to Internet:\nmkdir keystone-deps\npip download python-keystoneclient -d \"/home/aviuser/keystone-deps\"\ntar cvfz keystone-deps.tgz keystone-deps\n\nThen move the tar file to the destination machine that does not have Internet access and perform ...
[ 138, 49, 10, 0, 0 ]
[ "This isn't an answer. I was struggling but then realized that my install was trying to connect to internet to download dependencies.\nSo, I downloaded and installed dependencies first and then installed with below command. It worked\npython -m pip install filename.tar.gz\n\n", "You can manually download the 'whl...
[ -1, -1 ]
[ "openstack", "pip", "python" ]
stackoverflow_0036725843_openstack_pip_python.txt
Q: cx_oracle and sqlalchemy performance comparison I am working oracle database and wanted to know which toolkit (sqlalchemy or cx_Oracle) is better in performance as I can't see any comparisons online I hope someone can help me. I have listed the key performance indicators that I need to be addressed. Bulk insertion...
cx_oracle and sqlalchemy performance comparison
I am working oracle database and wanted to know which toolkit (sqlalchemy or cx_Oracle) is better in performance as I can't see any comparisons online I hope someone can help me. I have listed the key performance indicators that I need to be addressed. Bulk insertion and single line insertion connections complexity whi...
[ "SQLAlchemy is a layer on top of cx_Oracle so it will always have more overhead.\nWhen looking for performance, you should evaluate the latest cx_Oracle release (now called python-oracledb) since the new Thin mode has some advantages (e.g with DB Object types). See the release announcement for information about py...
[ 1 ]
[]
[]
[ "database", "oracle", "performance", "python", "sqlalchemy" ]
stackoverflow_0074597303_database_oracle_performance_python_sqlalchemy.txt
Q: Parse HTML to find titles with Python and BeautifulSoup This is the code I'm currently using... import requests from bs4 import BeautifulSoup headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-A...
Parse HTML to find titles with Python and BeautifulSoup
This is the code I'm currently using... import requests from bs4 import BeautifulSoup headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Li...
[ "If I understand you correctly you want to get text from the parameter title=:\ntitles = soup.select(\"a.title\")\n\nfor a in titles:\n print(a[\"title\"])\n\n\nIf you want the text inside <a>:\ntitles = soup.select(\"a.title\")\n\nfor a in titles:\n print(a.text)\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "parsing", "python" ]
stackoverflow_0074606128_beautifulsoup_parsing_python.txt
Q: Writing interpolated grib2 data with pygrib leads to unusable grib file I'm trying to use pygrib to read data from a grib2 file, interpolate it using python, and write it to another file. I've tried both pygrib and eccodes and both produce the same problem. The output file size increased by a factor of 3, but when...
Writing interpolated grib2 data with pygrib leads to unusable grib file
I'm trying to use pygrib to read data from a grib2 file, interpolate it using python, and write it to another file. I've tried both pygrib and eccodes and both produce the same problem. The output file size increased by a factor of 3, but when I try to view the data in applications like Weather and Climate Toolkit it h...
[ "Table 5.6 for GRIB2 (https://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_doc/) is related to \"ORDER OF SPATIAL DIFFERENCING\".\nFor some reason, when you modify grb['values'], it sets grb['orderOfSpatialDifferencing'] = 0, which \"wgrib2 -V\" doesn't like. So, after changing 'values', change 'orderOfSpatialDiffer...
[ 0 ]
[]
[]
[ "pygrib", "python" ]
stackoverflow_0066552793_pygrib_python.txt
Q: Python for i in range loop as argument a variable The problem is that I try to apply the reeks of fibonacci with a startValue that is an input. And how many terms there is in the reeks.My problem is that when I enter my variable n (the number that gets added to the start value, its 1 more than the number it was ge...
Python for i in range loop as argument a variable
The problem is that I try to apply the reeks of fibonacci with a startValue that is an input. And how many terms there is in the reeks.My problem is that when I enter my variable n (the number that gets added to the start value, its 1 more than the number it was getting added on one loop before. I tried chaning the loo...
[ "It's not very clear what your for loop is trying to do here.\n\nMy problem is that when I enter my variable n (the number that gets added to the start value, its 1 more than the number it was getting added on one loop before.\n\nWell, all you're doing in the loop is incrementing your variable by 1 each iteration a...
[ 0 ]
[]
[]
[ "fibonacci", "python" ]
stackoverflow_0074606167_fibonacci_python.txt
Q: Python object of type has no len() I tried to solve an easy problem in leetcode. Here is the source: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ I almost solved it with for loop, but i get an error Python object of type ListNode has no len(). I have tried to use call() or len(), but i have n...
Python object of type has no len()
I tried to solve an easy problem in leetcode. Here is the source: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ I almost solved it with for loop, but i get an error Python object of type ListNode has no len(). I have tried to use call() or len(), but i have no knowledge or understanding how does th...
[]
[]
[ "I can't really decipher how your ListNode class is designed to work, but the answer to how to be able to call len on an instance of your own class is to define the __len__ dunder method for the class. As others have pointed out in the comments, you'll also need to define the __getitem__ method in order to be able ...
[ -1 ]
[ "object", "python" ]
stackoverflow_0074606115_object_python.txt
Q: Celery task not working in Django framework I tried code to send_email 5 times to user as Asynchronous task using Celery and Redis Broker in Django Framework. My Celery server is working and it is responding to the celery cli interface even it is receiving task from Django but after that I am getting Error like: T...
Celery task not working in Django framework
I tried code to send_email 5 times to user as Asynchronous task using Celery and Redis Broker in Django Framework. My Celery server is working and it is responding to the celery cli interface even it is receiving task from Django but after that I am getting Error like: Traceback (most recent call last): File "c:\user...
[ "This is an issue when you running Python over Windows 7/10.\nThere are a workaround, you just need to use the module eventlet that you can install using pip:\n\npip install eventlet\n\nAfter that execute your worker with -P eventlet at the end of the command:\n\ncelery -A MyWorker worker -l info -P eventlet\n\n", ...
[ 0, 0 ]
[]
[]
[ "celery", "django", "python", "python_3.x", "redis" ]
stackoverflow_0056205396_celery_django_python_python_3.x_redis.txt
Q: How convert user inputted constant (pi,e) to float in python? I'm writing a code which must compute definite integral of a function. I'll provide code in the below. How can I urge computer to understand user input "pi" or "e" for constant numbers? Problem is that I must convert the type of input to float, for foll...
How convert user inputted constant (pi,e) to float in python?
I'm writing a code which must compute definite integral of a function. I'll provide code in the below. How can I urge computer to understand user input "pi" or "e" for constant numbers? Problem is that I must convert the type of input to float, for following calculations. So when user inputs pi it's raising ValueError...
[ "You can write a function that recognizes certain names before calling float() to parse it normally.\ndef my_float(s):\n constants = {\"pi\": 3.14159, \"e\": 2.71928}\n if s in constants:\n return constants[s]\n else:\n return float(s)\n\nThen you can read write:\nprint(\"Enter lower bound: \...
[ 1, 1 ]
[]
[]
[ "constants", "pi", "python", "sympy", "user_input" ]
stackoverflow_0052820034_constants_pi_python_sympy_user_input.txt
Q: How to append/concat dataframes from within a function to a global dataframe I have a scraping function that returns a dataframe as such: enter image description here How can i add this dataframe to a global dataframe as to keep extending my dataframe like so: enter image description here The result should be a fu...
How to append/concat dataframes from within a function to a global dataframe
I have a scraping function that returns a dataframe as such: enter image description here How can i add this dataframe to a global dataframe as to keep extending my dataframe like so: enter image description here The result should be a function i can run again and again with different arguments to compile data into my ...
[ "You can use concat:\nappended_df = pd.DataFrame() # Initilize\nappended_df = pd.concat([appended_df, new_df], axis=1)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074606230_dataframe_pandas_python.txt
Q: Open the same excel file in different windows with python I am very new to python. I'm currently trying to open the same instances of one excel-file (Excel 2013) and move opened windows using python, but can't find any info on how to do it. Manually i would just click on "New Window" on "View" tab. If I'll try ope...
Open the same excel file in different windows with python
I am very new to python. I'm currently trying to open the same instances of one excel-file (Excel 2013) and move opened windows using python, but can't find any info on how to do it. Manually i would just click on "New Window" on "View" tab. If I'll try open it with subprocess, it'll successively open and close windows...
[ "I don't know python, so likely to be garbage code!\nUsing the Excel COM object you get programmatic access to the \"new window\" (among other things).\nThe Window object that is returned from Workbook.NewWindow has a hWnd property (which might be what you need for the MoveWindow) and/or there is also a Top and Lef...
[ 0 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0074605764_excel_python.txt
Q: Base 64 decode with Python on XAMPP I'm trying to bring on my local server (XAMPP), a script that's working on my VPS server (Linux CentOS7). On XAMPP, I call the Python script wit PHP, something like: $hotel = array("Name"=>$_POST["NAME"] ,.. ); $param = escapeshellcmd(base64_enc...
Base 64 decode with Python on XAMPP
I'm trying to bring on my local server (XAMPP), a script that's working on my VPS server (Linux CentOS7). On XAMPP, I call the Python script wit PHP, something like: $hotel = array("Name"=>$_POST["NAME"] ,.. ); $param = escapeshellcmd(base64_encode(json_encode($hotel))); $result = shel...
[ "If the problem is caused by not reading the \"$param\" variable due to single quotes, replacing the line of\n$result = shell_exec('python C:\\xampp\\htdocs\\bounce.py $param');\n\nwith\n$result = shell_exec(\"python C:\\\\xampp\\\\htdocs\\\\bounce.py $param\");\n\ncould help. worth a try.\n" ]
[ 0 ]
[]
[]
[ "base64", "php", "python" ]
stackoverflow_0074065117_base64_php_python.txt
Q: How to format textual output with whitespace like tabs or newline? I am somewhat experienced in python, but i have never really had to format my return of a function. This is my desired format: This is what my output is currently looking like: I have been researching how to use escaped whitespace-chars like \t, ...
How to format textual output with whitespace like tabs or newline?
I am somewhat experienced in python, but i have never really had to format my return of a function. This is my desired format: This is what my output is currently looking like: I have been researching how to use escaped whitespace-chars like \t, and I know about \n from C++, but I am unsure how to implement these fun...
[ "Something like this should work:\nwords = [\n ('THE', 30062),\n ('AND', 28379),\n ('I', 22307),\n ('THAT', 11924),\n]\n\ndef print_words(all_words, limit=19):\n totwords = sum([y for x,y in all_words])\n print(\"Total words:\", totwords)\n print()\n print(\"Top\", limit, \"words:\")\n\n ...
[ 0 ]
[]
[]
[ "python", "string_formatting", "whitespace" ]
stackoverflow_0074606251_python_string_formatting_whitespace.txt
Q: How to read a jpg. from google storage as a path or file type As the topic indicates... I have try two ways and none of them work: First: I want to programmatically talk to GCS in Python. such as reading gs://{bucketname}/{blobname} as a path or a file. The only thing I can find is a gsutil module, however it seem...
How to read a jpg. from google storage as a path or file type
As the topic indicates... I have try two ways and none of them work: First: I want to programmatically talk to GCS in Python. such as reading gs://{bucketname}/{blobname} as a path or a file. The only thing I can find is a gsutil module, however it seems used in a commend line instead of a python application. i find a ...
[ "I'd be using fsspec's GCS filesystem implementation instead.\nhttps://github.com/fsspec/gcsfs/\n>>> import gcsfs\n>>> fs = gcsfs.GCSFileSystem(project='my-google-project')\n>>> fs.ls('my-bucket')\n['my-file.txt']\n>>> with fs.open('my-bucket/my-file.txt', 'rb') as f:\n... print(f.read())\nb'Hello, world'\n\nht...
[ 0, 0 ]
[]
[]
[ "google_cloud_storage", "python" ]
stackoverflow_0074605414_google_cloud_storage_python.txt
Q: How to print all rows containing a part of input? I have a csv file that contains sequence and gene name. I want to take an input from user and print all the rows that contains user input as a part. As an example my data is; Gene 1 ATGCGGTCTA Gene 2 ACGCCCATGA Gene 3 TCGAC When user enters GC the outcome...
How to print all rows containing a part of input?
I have a csv file that contains sequence and gene name. I want to take an input from user and print all the rows that contains user input as a part. As an example my data is; Gene 1 ATGCGGTCTA Gene 2 ACGCCCATGA Gene 3 TCGAC When user enters GC the outcome must be Gene 1 ATGCGGTCTA Gene 2 ACGCCCATGA sinc...
[ "Using pandas and assuming the column of your dataframe with the sequences is called sequences, you can do :\nfiltered_df = df[df['sequences'].str.contains(s)]\n" ]
[ 0 ]
[]
[]
[ "input", "list", "python", "python_3.x", "sequence" ]
stackoverflow_0074606197_input_list_python_python_3.x_sequence.txt
Q: How to use functools.partial for a class method? I'd like to apply partial from functools to a class method. from functools import partial class A: def __init__(self, i): self.i = i def process(self, constant): self.result = self.i * constant CONST = 2 FUNC = partial(A.process, CONST) W...
How to use functools.partial for a class method?
I'd like to apply partial from functools to a class method. from functools import partial class A: def __init__(self, i): self.i = i def process(self, constant): self.result = self.i * constant CONST = 2 FUNC = partial(A.process, CONST) When I try: FUNC(A(4)) I got this error: 'int' object ...
[ "You're binding one positional argument with partial which will go to the first argument of process, self. When you then call it you're passing A(4) as the second positional argument, constant. In other words, the order of arguments is messed up. You need to bind CONST to constant explicitly:\nFUNC = partial(A.proc...
[ 4, 0 ]
[]
[]
[ "class", "functools", "object", "partial", "python" ]
stackoverflow_0060756161_class_functools_object_partial_python.txt
Q: YOLOv7 --save-txt Argument Path Change I do object detection with YOLOv7 ready model. I'm running detect.py like this "python detect.py --source human.jpg --save-txt" The --save-txt argument gives me the coordinates in the form of .txt and it saves to 'runs/detect/exp/labels' but I want it to save in 'runs/data/tr...
YOLOv7 --save-txt Argument Path Change
I do object detection with YOLOv7 ready model. I'm running detect.py like this "python detect.py --source human.jpg --save-txt" The --save-txt argument gives me the coordinates in the form of .txt and it saves to 'runs/detect/exp/labels' but I want it to save in 'runs/data/train' I think the relevant code is on line 10...
[ "not a very professional solution but it worked\nimg_name = p.name.split(\".\")\ntxt_path = f'runs/data/train/{img_name[0]}' # img.txt\n\n" ]
[ 0 ]
[]
[]
[ "path", "python", "python_3.x", "yolo" ]
stackoverflow_0074594411_path_python_python_3.x_yolo.txt
Q: HTTP status code is not handled using scrapy and selenium I am facing the error HTTP status code is not handled or not allowed how to solve these error I am using the selenium and scrapy together I am also using the user agent in setting but the HTTP error will not solve kindly recommend any solution this is pa...
HTTP status code is not handled using scrapy and selenium
I am facing the error HTTP status code is not handled or not allowed how to solve these error I am using the selenium and scrapy together I am also using the user agent in setting but the HTTP error will not solve kindly recommend any solution this is page link https://www.askgamblers.com/online-casinos/countries/uk...
[ "You are getting such error because the website is under cloudflare protection.\nhttps://www.askgamblers.com/online-casinos/countries/uk is using Cloudflare CDN/Proxy!\n\nhttps://www.askgamblers.com/online-casinos/countries/uk is NOT using Cloudflare SSL\n\nAnd Scrapy with Selenium/scrapy can't handle(I tested) clo...
[ 0 ]
[]
[]
[ "python", "scrapy", "selenium", "web_scraping" ]
stackoverflow_0074605560_python_scrapy_selenium_web_scraping.txt
Q: I need a bit of lead with solving this fish detector problem by using a for loop A fish-finder is a device used by anglers to find fish in a lake. If the fish-finder finds a fish, it will sound an alarm. It uses depth readings to determine whether to sound an alarm. For our purposes, the fish-finder will decide th...
I need a bit of lead with solving this fish detector problem by using a for loop
A fish-finder is a device used by anglers to find fish in a lake. If the fish-finder finds a fish, it will sound an alarm. It uses depth readings to determine whether to sound an alarm. For our purposes, the fish-finder will decide that a fish is swimming past if: there are four consecutive depth readings which form a ...
[ "The advantage of the for loop is that you can handle an arbitrary number of fish.\ndef fishies( depths ):\n # This could be done easier with zip, but that's an advanced topic.\n ups = 0\n downs = 0\n for i in range(len(depths)-1):\n if depths[i] < depths[i+1]:\n ups += 1\n elif...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074606389_python_python_3.x.txt
Q: snake game will fail when rapidly press three buttons once Currently I'm using pygame to create my first snake game, but there is a weird bug exist. When I press three bottoms, such as up+left+right, simultaneously, my game will automatically be stopped. Python might think the snake collide its own body, so it let...
snake game will fail when rapidly press three buttons once
Currently I'm using pygame to create my first snake game, but there is a weird bug exist. When I press three bottoms, such as up+left+right, simultaneously, my game will automatically be stopped. Python might think the snake collide its own body, so it lets the game stop, but actually the snake doesn't. I don't know ho...
[ "The problem is that more than on KEYDOWN has be handled in on frame. Do not change interaction.snake.direction in the event loop, but set a local variable with the new direction and update interaction.snake.direction after the event loop:\nnew_direction = interaction.snake.direction\n\nfor event in pygame.event.ge...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074606448_pygame_python.txt
Q: Tweepy.errors.NotFound: 404 Not Found 50 - User not found I am trying to make a twitter bot in python using tweepy, when running the below code I get error: tweepy.errors.NotFound: 404 Not Found 50 - User not found. My code: import tweepy import logging from config import create_api import json logging.basicCon...
Tweepy.errors.NotFound: 404 Not Found 50 - User not found
I am trying to make a twitter bot in python using tweepy, when running the below code I get error: tweepy.errors.NotFound: 404 Not Found 50 - User not found. My code: import tweepy import logging from config import create_api import json logging.basicConfig(level=logging.INFO) logger = logging.getLogger() class Fav...
[ "The user does not exist anymore in Twitter.\nYou must catch the error with an except statement in python.\nYou did not provide the exact line where the error happen but you should try to catch it with something like this:\ntry:\n api.get_user()\nexcept tweepy.error.NotFound:\n print(\"user not found\")\n\n" ...
[ 0 ]
[]
[]
[ "bots", "python", "python_3.x", "tweepy", "twitter" ]
stackoverflow_0072015504_bots_python_python_3.x_tweepy_twitter.txt
Q: cx_Oracle for Oracle Linux 7 not working after install For the last week I have been trying to get cx_oracle installed and working. I started with an Oracle 19 appliance which is on Oracle Linux 7. I used the official oracle site to install cx_oracle as listed below. The install seems to have worked fine, but when...
cx_Oracle for Oracle Linux 7 not working after install
For the last week I have been trying to get cx_oracle installed and working. I started with an Oracle 19 appliance which is on Oracle Linux 7. I used the official oracle site to install cx_oracle as listed below. The install seems to have worked fine, but when I try to import the module, it is not found. I checked all ...
[ "You now seem to have multiple cx_Oracle packages installed, which isn't helping untangle your problems (and not something I want to replicate).\nTo start from scratch with a clean OL7 image, follow the \"Installing Python 3 from the Oracle Linux 7 Latest Repository\" section of https://yum.oracle.com/oracle-linux-...
[ 1, 0 ]
[]
[]
[ "cx_oracle", "oracle19c", "oraclelinux", "python", "rhel7" ]
stackoverflow_0074605940_cx_oracle_oracle19c_oraclelinux_python_rhel7.txt
Q: Creating functions (or lambdas) in a loop (or comprehension) I'm trying to create functions inside of a loop: functions = [] for i in range(3): def f(): return i # alternatively: f = lambda: i functions.append(f) The problem is that all functions end up being the same. Instead of returning ...
Creating functions (or lambdas) in a loop (or comprehension)
I'm trying to create functions inside of a loop: functions = [] for i in range(3): def f(): return i # alternatively: f = lambda: i functions.append(f) The problem is that all functions end up being the same. Instead of returning 0, 1, and 2, all three functions return 2: print([f() for f in fun...
[ "You're running into a problem with late binding -- each function looks up i as late as possible (thus, when called after the end of the loop, i will be set to 2). \nEasily fixed by forcing early binding: change def f(): to def f(i=i): like this:\ndef f(i=i):\n return i\n\nDefault values (the right-hand i in i=...
[ 235, 49, 0, 0 ]
[ "You can try like this:\nl=[]\nfor t in range(10):\n def up(y):\n print(y)\n l.append(up)\nl[5]('printing in 5th function')\n\n", "just modify the last line for\nfunctions.append(f())\n\nEdit: This is because f is a function - python treats functions as first-class citizens and you can pass them arou...
[ -1, -2 ]
[ "python" ]
stackoverflow_0003431676_python.txt
Q: How do I make theses values next to each other with commas in between theme I want these format theses to be 1girl, belt, etc.. what can I do to achieve this? 1girl belt breasts gloves long_hair long_sleeves medium_breasts military solo uniform white_gloves Here's what I have I want them side by side with commas I...
How do I make theses values next to each other with commas in between theme
I want these format theses to be 1girl, belt, etc.. what can I do to achieve this? 1girl belt breasts gloves long_hair long_sleeves medium_breasts military solo uniform white_gloves Here's what I have I want them side by side with commas I don't know what to do to get what I want. It's probably something either really ...
[ "You can try either of these, depending on what you need:\nnewstr = ', '.join(str.split(' ')) ## if you want the separator to be an empty space\nprint(newstr)\n\nor\nimport re\nnewstr = ', '.join(re.split('\\s|_', str)) ## if you want the separator to be an empty space or _\nprint(newstr)\n\n're' is a module made t...
[ 0 ]
[]
[]
[ "format", "python" ]
stackoverflow_0074606210_format_python.txt
Q: Building a "half" polar diagram using matplotlib I would like to draw this using matplotlib and for now I have this using this code : fig = plt.figure() ax = fig.add_subplot(111, projection='polar', xlim=(-90, 90)) ax.set_thetamin(-90) # set the limits ax.set_thetamax(90) ax.set_theta_offset(.5*np.pi) # point the ...
Building a "half" polar diagram using matplotlib
I would like to draw this using matplotlib and for now I have this using this code : fig = plt.figure() ax = fig.add_subplot(111, projection='polar', xlim=(-90, 90)) ax.set_thetamin(-90) # set the limits ax.set_thetamax(90) ax.set_theta_offset(.5*np.pi) # point the origin towards the top ax.set_thetagrids(range(-90, 10...
[ "You need to change the values of angles:\nplt.plot(angle / np.pi * 2,valeurs,\"o \")\n\n\n" ]
[ 0 ]
[]
[]
[ "diagram", "matplotlib", "polar_coordinates", "python" ]
stackoverflow_0074606531_diagram_matplotlib_polar_coordinates_python.txt
Q: Embedding a custom widget into a stacked widget page WITHOUT using qtdesigner I am trying to embed two custom widgets into the pages of a stacked widget on a dialog page. I have mocked up my problem using the main script dialog.py which has a stacked widget with two pages promoting widget_1_UI from widget_1.py and...
Embedding a custom widget into a stacked widget page WITHOUT using qtdesigner
I am trying to embed two custom widgets into the pages of a stacked widget on a dialog page. I have mocked up my problem using the main script dialog.py which has a stacked widget with two pages promoting widget_1_UI from widget_1.py and widget_2_UI from widget_2.py to each page, respectively. It doesn't throw any erro...
[ "Figured it out! In dialog.py widget_1_UI() is set as the promoted widget for the first page of the stacked widget but there is nothing to tell it what should be inside it. Adding self.page_1.setupUi(self.page_1) does just that.\nself.page_1 = widget_1_UI()\nself.page_1.setupUi(self.page_1)\nself.stackedWidget.addW...
[ 0 ]
[]
[]
[ "embed", "python", "qstackedwidget" ]
stackoverflow_0074602812_embed_python_qstackedwidget.txt
Q: Selenium doesn't open the specified URL and shows data:, I am trying to open the URL using selenium in chrome. I have chromedriver available with me. following is the code I want to execute. from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-infobars")...
Selenium doesn't open the specified URL and shows data:,
I am trying to open the URL using selenium in chrome. I have chromedriver available with me. following is the code I want to execute. from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-infobars") driver = webdriver.Chrome(executable_path="./chromedriver", ...
[ "This error message...\nselenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally\n (chrome not reachable)\n (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)\n\n...impli...
[ 4, 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0052760842_google_chrome_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How do I create a drop down menu inside of a command with discord.py I was going to make a rock paper scissors game with discord.py and I first defaulted to using select menus in messages, that would work if I could find a way to do it, so then I decided to just make it use a string object, but then I thought to...
How do I create a drop down menu inside of a command with discord.py
I was going to make a rock paper scissors game with discord.py and I first defaulted to using select menus in messages, that would work if I could find a way to do it, so then I decided to just make it use a string object, but then I thought to myself it would not be easy if the user had to guess what the choices whe...
[ "There are three ways to do this:\n\nchoices\nLiteral\nEnum\n\nThe docs page for choices shows an example for all three of them. The one you decide to go for depends on your use case. For example, Choices have a value attribute that you can use to make them easier to work with internally (like attaching an id to th...
[ 1 ]
[]
[]
[ "discord", "discord.py", "menu", "python", "python_3.x" ]
stackoverflow_0074606436_discord_discord.py_menu_python_python_3.x.txt
Q: How to get the numerical value for each matching value in a row in a csv file I have a csv file with "years" in row[0] and I need to get a count of how many times each year occurs and pair it with that year in a dictionary. To be clear, the year is the key and the amount of times it occurs in the csv is the value....
How to get the numerical value for each matching value in a row in a csv file
I have a csv file with "years" in row[0] and I need to get a count of how many times each year occurs and pair it with that year in a dictionary. To be clear, the year is the key and the amount of times it occurs in the csv is the value. Here's what I have, but I am missing something. I just can't figure out how to get...
[ "You are using the count variable wrong, try this:\ndef incidents_per_year():\n dict = {}\n with open(\"saved_data.csv\") as f:\n reader = csv.reader(f)\n next(reader)\n for row in reader:\n year = row[0]\n dict[year] = (dict.get(year) or 0) + 1\n return dict\n\nFor every year in the file it wi...
[ 0, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074601906_csv_python.txt
Q: Creating a Protobuf file from CSV Good day everyone. I need to create a simple file in Protobuf (proto) format, preferably using Python (I'm currently using PyCharm). It should be very simple and resemble the following CSV structure: header = ['Surname', 'Name'] data = ['John', 'Doe'] If anyone knows how to do it,...
Creating a Protobuf file from CSV
Good day everyone. I need to create a simple file in Protobuf (proto) format, preferably using Python (I'm currently using PyCharm). It should be very simple and resemble the following CSV structure: header = ['Surname', 'Name'] data = ['John', 'Doe'] If anyone knows how to do it, it would help me a lot. Thanks! I have...
[ "What issues have you faced?\nsyntax=\"proto3\";\n\nmessage Data {\n string surname = 1;\n string name = 2;\n}\n\nmessage CSV {\n repeated Data data = 1;\n}\n\nor\nsyntax=\"proto3\";\n\nmessage Data {\n string data1 = 1;\n string data2 = 2;\n}\n\nmessage CSV {\n string header1 = 1;\n string header2 = 2;\n r...
[ 0 ]
[]
[]
[ "csv", "protocol_buffers", "python" ]
stackoverflow_0074604304_csv_protocol_buffers_python.txt
Q: Python Canvas bind and resize When the window is resized, I want the height to be set equal to the width so the windows always is a square. In the code below print(event.width) does print the new window width, but canvas.configure(height=event.width) doesn't change the canvas height. What am I doing wrong? EDIT: ...
Python Canvas bind and resize
When the window is resized, I want the height to be set equal to the width so the windows always is a square. In the code below print(event.width) does print the new window width, but canvas.configure(height=event.width) doesn't change the canvas height. What am I doing wrong? EDIT: I want the whole window to stay squ...
[ "Changing the size of the canvas won't override the size created by the user. If you're wanting the whole window to remain square you must explicitly set the size of the window.\nFor example:\ndef resize(event):\n width = root.winfo_width()\n root.wm_geometry(f\"{width}x{width}\")\n\n", "I'm not sure if thi...
[ 1, 0 ]
[]
[]
[ "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0074606422_python_tkinter_tkinter_canvas.txt
Q: A variable updating every time it is changed i'm trying to create a variable that, everytimes it is changed, checks if the value is a certain amount and updates itself. I have something like this max = 10 min = 0 var = 1 And then some code updating it. Is it any way to keep it updating? It is in a class if it can...
A variable updating every time it is changed
i'm trying to create a variable that, everytimes it is changed, checks if the value is a certain amount and updates itself. I have something like this max = 10 min = 0 var = 1 And then some code updating it. Is it any way to keep it updating? It is in a class if it can in some way help. I tried to put something like i...
[ "Here's how you might approach doing something like this. Although you cannot mess with assignment directly, you can change how properties are set and accessed:\nclass LimitedValue:\n def __init__(self, min, max):\n self.min = min\n self.max = max\n self._value = None\n\n @property\n d...
[ 1 ]
[]
[]
[ "class", "python", "python_3.x", "variables" ]
stackoverflow_0074606553_class_python_python_3.x_variables.txt
Q: how to add double quotes to a string in text file I have a file with words that are each in a separate line. I want to read each word and add quotes around it, and a comma after the word. After that I want the words back into a new text file with the added symbols. Example, this as input file: ram shyam raja I w...
how to add double quotes to a string in text file
I have a file with words that are each in a separate line. I want to read each word and add quotes around it, and a comma after the word. After that I want the words back into a new text file with the added symbols. Example, this as input file: ram shyam raja I want this to be in the output file: "ram", "shyam", "raj...
[ "If each word is on the same line of the input file, separated by spaces. Then you could approach it like this:\n# read lines from file\ntext = \"\"\nwith open('filename.txt', 'r') as ifile:\n text = ifile.readline()\n\n# get all sepearte string split by space\ndata = text.split(\" \")\n\n# add quotes to each on...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074601508_python_python_3.x.txt
Q: How to create a new column in a dataframe based on the values of multiple columns in a different dataframe? Let's say I have the two data frames below: data = { 'Part' : ['part1', 'part2', 'part3', 'part4', 'part5'], 'Number' : ['123', '234', '345', '456', '567'], 'Code' : ['R2', 'R2', 'R4', 'R5', 'R5'] } ...
How to create a new column in a dataframe based on the values of multiple columns in a different dataframe?
Let's say I have the two data frames below: data = { 'Part' : ['part1', 'part2', 'part3', 'part4', 'part5'], 'Number' : ['123', '234', '345', '456', '567'], 'Code' : ['R2', 'R2', 'R4', 'R5', 'R5'] } df = pd.DataFrame(data, dtype = object) data2 = { 'Part' : ['part1', 'part2', 'part6', 'part4'], 'Number' : ...
[ "Here are two ways to do what you've asked:\n# First way\ndf = df.set_index(['Part','Number']).assign(Old_code=df2.set_index(['Part','Number']).Code).reset_index()\n\n# Second way\ndf = df.merge(df2.rename(columns={'Code':'Old_code'}), how='left', on=['Part','Number'])\n\nOutput:\n Part Number Code Old_code\n0 ...
[ 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074606446_dataframe_pandas_python.txt
Q: Create multiple for i in X depending on a given number I want to create a class in python that contains variables and a domain for each variable to generate a list of dictionary containing all the possible solutions for variables assignments for exemple: x='x' y='y' domainx=[1,2] domainy=[3,4] def solutions(elt,e...
Create multiple for i in X depending on a given number
I want to create a class in python that contains variables and a domain for each variable to generate a list of dictionary containing all the possible solutions for variables assignments for exemple: x='x' y='y' domainx=[1,2] domainy=[3,4] def solutions(elt,elt2,domainx,domainy): for i in domainx: for j in ...
[ "Try using itertools!\nEssentially, itertools.product does what you want. As explained in the docs, this function takes the Cartesian product of input iterables. So, list(itertools.product([0, 1], [2, 3])) produces [(0, 2), (0, 3), (1, 2), (1, 3)], which is basically all you want.\nAll that's left is converting tha...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074606461_python.txt
Q: Pandas read_pickle, UnpicklingError: invalid load key, '\xfd' I am trying to read in my pickle file , however I am getting the following error UnpicklingError: invalid load key, '\xfd'. Does anyone know how to solve this? import pandas as pd file = r"O:\Stack\Over\Flow\202210_Other.pkl" test = pd.read_pickle(file...
Pandas read_pickle, UnpicklingError: invalid load key, '\xfd'
I am trying to read in my pickle file , however I am getting the following error UnpicklingError: invalid load key, '\xfd'. Does anyone know how to solve this? import pandas as pd file = r"O:\Stack\Over\Flow\202210_Other.pkl" test = pd.read_pickle(file) print(test) Any advice would be appeciated.
[ "Was able to figure it out, it was\npd.read_pickle(file, compression=\"xz\")\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074606016_pandas_python.txt
Q: How can I add labels to a distance matrix used to make a dendrogram and have the labels also show on the dendrogram I have a distance matrix: array('d', [188.61516889752, 226.68716730362135, 188.96015266132167]) I would like to add labels to the matrix before performing hierarchical cluster using scipy. I produce...
How can I add labels to a distance matrix used to make a dendrogram and have the labels also show on the dendrogram
I have a distance matrix: array('d', [188.61516889752, 226.68716730362135, 188.96015266132167]) I would like to add labels to the matrix before performing hierarchical cluster using scipy. I produce a UPGMA dendrogram from the distance matrix using: from scipy.cluster.hierarchy import average, fcluster #from scipy.spa...
[ "It looks like you're missing a couple steps between \"create the distance matrix\" and \"create the dendrogram\".\nSee this other StackOverflow question for several worked examples.\nIn general, scipy and the underlying numpy tend not to include labels in their data structures. (Unlike, say pandas, which does trac...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python", "scikit_learn", "scipy" ]
stackoverflow_0074606336_arrays_numpy_python_scikit_learn_scipy.txt
Q: auto detect face only when the human is in motion and take a snapshot with opencv I'm working on Face recognition project in python, trying to take a snapshot of a human face from an IP cam whenever a human comes in the cam steam. Here is the code: import numpy as np import cv2 import time #import the cascade for...
auto detect face only when the human is in motion and take a snapshot with opencv
I'm working on Face recognition project in python, trying to take a snapshot of a human face from an IP cam whenever a human comes in the cam steam. Here is the code: import numpy as np import cv2 import time #import the cascade for face detection face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcasca...
[ "I guess you need to modify your code to make a cropped image for every facebox and then write the cropped image, not a basic frame:\nfor (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\n roi_gray = gray[y:y + h, x:x + w]\n roi_color = frame[y:y + h, x:x + ...
[ 0 ]
[]
[]
[ "face_recognition", "opencv", "python" ]
stackoverflow_0074600768_face_recognition_opencv_python.txt
Q: Horizontal concatenating dataframes without taking into account the index I'm stucked with womething chich looks super easy: I have a dafatframe df1 df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)), index=["1", "2", "3", "4"], columns=["A", "B", "C", "D"]) enter image de...
Horizontal concatenating dataframes without taking into account the index
I'm stucked with womething chich looks super easy: I have a dafatframe df1 df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)), index=["1", "2", "3", "4"], columns=["A", "B", "C", "D"]) enter image description here I have another dafatframe df2: df2 = pd.DataFrame(np.random.rand...
[ "Unfortunately ignore_index only works on the axis you are trying to concat (which should be axis 1). You could remove the index before the concat:\npd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis=1)\n\n" ]
[ 0 ]
[]
[]
[ "concatenation", "dataframe", "python" ]
stackoverflow_0074606611_concatenation_dataframe_python.txt
Q: Order a list of ip,domain and url i have a txt with some IPs,domains and urls but the list is not organized. I want to divide the IP, domain and url like that: List before: 1.1.1.1 domain.com 2.2.2.2 https://url.com/test 3.3.3.3 domain2.com List after: IP 1.1.1.1 2.2.2.2 3.3.3.3 DOMAIN domain.com domain2.com UR...
Order a list of ip,domain and url
i have a txt with some IPs,domains and urls but the list is not organized. I want to divide the IP, domain and url like that: List before: 1.1.1.1 domain.com 2.2.2.2 https://url.com/test 3.3.3.3 domain2.com List after: IP 1.1.1.1 2.2.2.2 3.3.3.3 DOMAIN domain.com domain2.com URL https://url.com/test How can i do it...
[ "I think thats what you need, you must install validators with the following command pip install validators. Hope this helps\nCode:\nimport validators\nimport re\n\nmy_dict = dict()\nwith open('config.txt') as f:\n for line in f:\n if bool(re.match(r\"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\", l...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074606365_python_python_3.x.txt
Q: Find the width of tree at each level/height (non-binary tree) Dear experienced friends, I am looking for an algorithm (Python) that outputs the width of a tree at each level. Here are the input and expected outputs. (I have updated the problem with a more complex edge list. The original question with sorted edge l...
Find the width of tree at each level/height (non-binary tree)
Dear experienced friends, I am looking for an algorithm (Python) that outputs the width of a tree at each level. Here are the input and expected outputs. (I have updated the problem with a more complex edge list. The original question with sorted edge list can be elegantly solved by @Samwise answer.) Input (Edge List:...
[ "Build a dictionary of the \"level\" of each node, and then count the number of nodes at each level:\n>>> from collections import Counter\n>>> def tree_width(edges):\n... levels = {} # {node: level}\n... for [p, c] in edges:\n... levels[c] = levels.setdefault(p, 0) + 1\n... widths = Counter(lev...
[ 2, 1 ]
[]
[]
[ "algorithm", "python", "python_3.x" ]
stackoverflow_0074604676_algorithm_python_python_3.x.txt
Q: Can't get href from Selenium webdriver scraping youtube I am trying to scrape youtube videos from a channel by doing the following code below however, it seems that my element_titles don't have a href attribute. This worked about a year ago and I am unsure why it doesn't work now? Did youtube change the way we can...
Can't get href from Selenium webdriver scraping youtube
I am trying to scrape youtube videos from a channel by doing the following code below however, it seems that my element_titles don't have a href attribute. This worked about a year ago and I am unsure why it doesn't work now? Did youtube change the way we can get href? #Scrape for videos # WARNING: Takes very long HO...
[ "The below full working code will pull the required data here all the video links smoothly.\nExample:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\nimport pandas as pd\nfrom selenium.webdriver.support.wait import We...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_requests", "selenium" ]
stackoverflow_0074606385_beautifulsoup_python_python_requests_selenium.txt
Q: Efficient way to get counts from a query I am trying to find the occupancy of a parking lot for every time a vehicle exits. I have a data frame where each row corresponds to a parking entry and exit timestamp. The dataset is quite large and the solution I have currently takes a bit of time to process. I am able to...
Efficient way to get counts from a query
I am trying to find the occupancy of a parking lot for every time a vehicle exits. I have a data frame where each row corresponds to a parking entry and exit timestamp. The dataset is quite large and the solution I have currently takes a bit of time to process. I am able to find the occupancy by performing the followin...
[ "Here's what I was suggesting. I print out the combined dataframe so you can see what it looks like.\nimport pandas as pd\n\ndata = [\n [1, \"2022-11-01 08:00:00\", \"2022-11-01 17:00:00\"],\n [2, \"2022-11-01 09:00:00\", \"2022-11-01 13:00:00\"],\n [3, \"2022-11-01 10:00:00\", \"2022-11-01 16:00:00\"],\n...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074605690_python.txt
Q: How to use type hints in python 3.6? I noticed Python 3.5 and Python 3.6 added a lot of features about static type checking, so I tried with the following code (in python 3.6, stable version). from typing import List a: List[str] = [] a.append('a') a.append(1) print(a) What surprised me was that, Python didn't g...
How to use type hints in python 3.6?
I noticed Python 3.5 and Python 3.6 added a lot of features about static type checking, so I tried with the following code (in python 3.6, stable version). from typing import List a: List[str] = [] a.append('a') a.append(1) print(a) What surprised me was that, Python didn't give me an error or warning, although 1 was...
[ "Type hints are entirely meant to be ignored by the Python runtime, and are checked only by 3rd party tools like mypy and Pycharm's integrated checker. There are also a variety of lesser known 3rd party tools that do typechecking at either compile time or runtime using type annotations, but most people use mypy or ...
[ 42, 24, 11, 0 ]
[]
[]
[ "mypy", "python", "python_3.x", "python_typing", "type_hinting" ]
stackoverflow_0041356784_mypy_python_python_3.x_python_typing_type_hinting.txt
Q: AttributeError at /social-auth/complete/google-oauth2/ 'Request' object has no attribute 'login' I had written a REST API service on python using django rest framework to which I wanted to attach authentication from authorizations using OAuth2 (Google). I used to social django lib, however when I was starting my s...
AttributeError at /social-auth/complete/google-oauth2/ 'Request' object has no attribute 'login'
I had written a REST API service on python using django rest framework to which I wanted to attach authentication from authorizations using OAuth2 (Google). I used to social django lib, however when I was starting my service locally and putting my credentials in google form to auth I keep getting this error (look at i...
[ "I reinstalled the entire virtual environment, as well as all the places in the settings.py file that were responsible for auth. It helped me.\nAlso you can check URLs and Redirect URLs on console.cloud.google.com where you have registered your web app.\n" ]
[ 0 ]
[]
[]
[ "authentication", "django", "django_socialauth", "oauth_2.0", "python" ]
stackoverflow_0074606805_authentication_django_django_socialauth_oauth_2.0_python.txt
Q: Make directed graph run clockwise and change its orientation The following code generates a circular directed graph with networkx. from matplotlib import pyplot as plt import networkx as nx def make_cyclic_edge(lst): cyclic = [] for i, elem in enumerate(lst): if i+1 < len(lst): cyclic....
Make directed graph run clockwise and change its orientation
The following code generates a circular directed graph with networkx. from matplotlib import pyplot as plt import networkx as nx def make_cyclic_edge(lst): cyclic = [] for i, elem in enumerate(lst): if i+1 < len(lst): cyclic.append((elem, lst[i+1])) else: cyclic.append((...
[ "It's not the most elegant, but here's one approach that works. I made the following changes to your cycle_diagram function. I added optional arguments top (to specify the top node) and flip (to specify whether to flip coordinates horizontally). Within the code, I added the following in after the layout pos is defi...
[ 2 ]
[]
[]
[ "matplotlib", "networkx", "python", "rotation" ]
stackoverflow_0074602010_matplotlib_networkx_python_rotation.txt
Q: how to do less than django queryset with column parameter I want to count my stock as this sql code: SELECT COUNT(*) FROM management_stock WHERE stockCount < minStock How to do that query in django queryset? I got error in my this query: Stock.objects.all().filter(stockCount__lt=minStock).count() my table is lik...
how to do less than django queryset with column parameter
I want to count my stock as this sql code: SELECT COUNT(*) FROM management_stock WHERE stockCount < minStock How to do that query in django queryset? I got error in my this query: Stock.objects.all().filter(stockCount__lt=minStock).count() my table is like this: class Stock(models.Model): product = models.OneToOn...
[ "You can use an F-expression [Django-doc] to reference a field, so:\nfrom django.db.models import F\n\nStock.objects.filter(stockCount__lt=F('minStock')).count()\n" ]
[ 1 ]
[]
[]
[ "django", "django_filter", "django_models", "python" ]
stackoverflow_0074606678_django_django_filter_django_models_python.txt
Q: Python & Regex: Simple findall issue Can someone please help me understand why the last result isn't returning [+50, -50] and is capturing that annoying "/". To be clear, I am trying to match on "-" or "+/-". thats why I'm confused as to why "/-50" is catching. a = ['a+/-50', 'a +50', 'a', '+50,+100', '+50/-50']...
Python & Regex: Simple findall issue
Can someone please help me understand why the last result isn't returning [+50, -50] and is capturing that annoying "/". To be clear, I am trying to match on "-" or "+/-". thats why I'm confused as to why "/-50" is catching. a = ['a+/-50', 'a +50', 'a', '+50,+100', '+50/-50'] pattern = r'[-|+/-]*\d+' for x in a: ...
[ "There seems to be a misunderstanding of character classes here: they match one character, and the | symbol is not a special operator but a literal character option when appearing in such character class.\nYou'll want to change your regex to this:\nr'(?:-|\\+/-)?\\d+'\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074606792_python_regex.txt
Q: Loop through multiple html tables looking for specific values I'm trying to find an account number in a table (it can be in many multiple tables) along with the status of the account. I'm trying to utilize find_element using the Xpath and the odd thing is that it is saying it cannot find it. You can see in the ht...
Loop through multiple html tables looking for specific values
I'm trying to find an account number in a table (it can be in many multiple tables) along with the status of the account. I'm trying to utilize find_element using the Xpath and the odd thing is that it is saying it cannot find it. You can see in the html that the id exists yet it is defaulting to my except saying table...
[ "DataTables are dynamic elements - the actual info they hold is being hydrated by javascript on an empty table skeleton, after page loads. Therefore, you need to wait for the table to fully load, then look up the information it holds:\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui ...
[ 1 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0074606694_python_selenium_xpath.txt
Q: Dask object memory size larger than the file size? I have a csv file that is 15Gb in size according to du -sh filename.txt. However, when I load the file to dask, the dask array is almost 4 times larger at 55Gb. Is this normal? Here is how I am loading the file. cluster = LocalCluster() # Launches a scheduler and...
Dask object memory size larger than the file size?
I have a csv file that is 15Gb in size according to du -sh filename.txt. However, when I load the file to dask, the dask array is almost 4 times larger at 55Gb. Is this normal? Here is how I am loading the file. cluster = LocalCluster() # Launches a scheduler and workers locally client = Client(cluster) # Connect to ...
[ "Found the answer- it was right there on the output of arr where it says the Type -> 'object'. Looks like converting from dask dataframe to array using arr = ddf.to_dask_array(lengths=True) does not preserve the bool object type. I was able to reduce the memory load significantly by explicitly casting it as bool ty...
[ 0 ]
[]
[]
[ "bigdata", "csv", "dask", "python" ]
stackoverflow_0074597754_bigdata_csv_dask_python.txt
Q: Setting group order on pySankey sankey chart I'm trying to use a sankey chart to show some user segmentation change using PySankey but the class order is the opposite to what I want. Is there a way for me to specify the order in which each class is posted? Here is the code I'm using (a dummy version): test_df = pd...
Setting group order on pySankey sankey chart
I'm trying to use a sankey chart to show some user segmentation change using PySankey but the class order is the opposite to what I want. Is there a way for me to specify the order in which each class is posted? Here is the code I'm using (a dummy version): test_df = pd.DataFrame({ 'curr_seg':np.repeat(['A','B','C'...
[ "There is a bug in the first line of check_data_matches_labels function, you need to change to the following:\nif len(labels) > 0:\nThen you can use leftLabels and rightLabels to control order.\n" ]
[ 0 ]
[]
[]
[ "charts", "python", "sankey_diagram" ]
stackoverflow_0070986564_charts_python_sankey_diagram.txt
Q: pyMongo MongoDB Query for all databases I want to run the same query for all databases ` for example import pymongo db = pymongo.MongoClient("localhost") db["*"]["test"].find() or import pymongo db = pymongo.MongoClient("localhost") db["db1","db2","db3"]["test"].find() To put it bluntly, how to run this logi...
pyMongo MongoDB Query for all databases
I want to run the same query for all databases ` for example import pymongo db = pymongo.MongoClient("localhost") db["*"]["test"].find() or import pymongo db = pymongo.MongoClient("localhost") db["db1","db2","db3"]["test"].find() To put it bluntly, how to run this logic in mongodb import pymongo db = pymongo.Mon...
[ "There are no commands to run the same query on multiple databases in a single command.\nYou can get the list of databases and repeat the same command by iterating the list_database_names() method which you can run against the MongoClient instance, e.g.\nimport pymongo\n\nclient = pymongo.MongoClient()\ncollection ...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074606515_mongodb_pymongo_python.txt
Q: UnicodeEncodeError: 'charmap' codec can't encode characters/ writing in txt file i'm parcing a text file that has text in xml like configuration and the code i tried is this file_handle_tester = open("C:/Users/pc/Desktop/talabat yarmook.txt","r", encoding="utf8") sec_file = open("C:/Users/pc/Desktop/parced_text.t...
UnicodeEncodeError: 'charmap' codec can't encode characters/ writing in txt file
i'm parcing a text file that has text in xml like configuration and the code i tried is this file_handle_tester = open("C:/Users/pc/Desktop/talabat yarmook.txt","r", encoding="utf8") sec_file = open("C:/Users/pc/Desktop/parced_text.txt","w") a='com.talabat:id/textView_restaurantName' menu = list() for line in file_h...
[ "Simply change sec_file = open(\"C:/Users/pc/Desktop/parced_text.txt\",\"w\") to\nsec_file = open(\"C:/Users/pc/Desktop/parced_text.txt\",\"w\", encoding='utf-8')\n" ]
[ 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0074606785_python_unicode.txt
Q: Dash app not rendering design/ taking into account color etc I am trying to add a navigation bar on a new Dash app. If I run the code straight from dash website the output does not render properly. What it is supposed to look like: What I get locally (Dash 2.7.0 + chrome + dbc 1.2.1): I have seen other strange b...
Dash app not rendering design/ taking into account color etc
I am trying to add a navigation bar on a new Dash app. If I run the code straight from dash website the output does not render properly. What it is supposed to look like: What I get locally (Dash 2.7.0 + chrome + dbc 1.2.1): I have seen other strange behavior such as text in two dbc.col on the same dbc.row not showin...
[ "You'll need to define a stylesheet in order for your className references to take effect:\napp = dash.Dash(external_stylesheets=[dbc.themes.SLATE])\n\nResult:\n\nComplete code:\nimport dash\nfrom dash import html\nfrom dash.dependencies import Input, Output, State\nimport dash_bootstrap_components as dbc\n\n\napp ...
[ 1 ]
[]
[]
[ "frontend", "plotly", "plotly_dash", "python" ]
stackoverflow_0074601707_frontend_plotly_plotly_dash_python.txt
Q: Inserting csv file into a database using Python In Python I've connected to a Postgres database using the following code: conn = psycopg2.connect( host = "localhost", port = "5432", database = "postgres", user = "postgres", password = "123" ) cur = conn.cursor() I have created a table called d...
Inserting csv file into a database using Python
In Python I've connected to a Postgres database using the following code: conn = psycopg2.connect( host = "localhost", port = "5432", database = "postgres", user = "postgres", password = "123" ) cur = conn.cursor() I have created a table called departments and want to insert data into the database ...
[ "You have to pass the row information as a tuple. Try this instead:\nfor row in departments.itertuples():\n cur.execute('''\n INSERT INTO departments VALUES (%s, %s, %s)\n ''',\n (row.id, row.department_name, row.annual_budget))\nconn.commit()\n\nSee the docs for more ...
[ 0 ]
[]
[]
[ "psycopg2", "python", "sql" ]
stackoverflow_0074606989_psycopg2_python_sql.txt
Q: Extract data from string object with regex into Python I have this string: a = '91:99 OT (87:87)' I would like to split it into: ['91', '99', '87', '87'] In my case numerical values can vary from 01 to 999 so that I have to use regex module. I am working with Python. A: Sorry I found a simple solution : re.fi...
Extract data from string object with regex into Python
I have this string: a = '91:99 OT (87:87)' I would like to split it into: ['91', '99', '87', '87'] In my case numerical values can vary from 01 to 999 so that I have to use regex module. I am working with Python.
[ "Sorry I found a simple solution :\nre.findall('[0-9]+', a)\nI will return :\n['91', '99', '87', '87']\n", "regex is a pretty complicated topic. This site can help a lot https://regex101.com/\nhttps://cheatography.com/davechild/cheat-sheets/regular-expressions/\nI hope this is the answer you are looking for\n(\\d...
[ 0, 0 ]
[]
[]
[ "extract", "python", "string" ]
stackoverflow_0074606882_extract_python_string.txt
Q: comparing values from dictionary with same key python Below is a dictionary called total_per_person that maps total spent by a person in one week {'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Frank': 66.6, 'Alice': 64.10, 'Ingrid': 59.45, 'Bob': 103.50, 'Gertrude': 107.45, 'Dave': 62.24} Below is another di...
comparing values from dictionary with same key python
Below is a dictionary called total_per_person that maps total spent by a person in one week {'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Frank': 66.6, 'Alice': 64.10, 'Ingrid': 59.45, 'Bob': 103.50, 'Gertrude': 107.45, 'Dave': 62.24} Below is another dictionary called name_to_budget that maps the weekly budget ...
[ "You need to iterate over the keys and compare each one on the two dicts.\ndict.keys() return a list with all the keys.\nThis code snippets also consider corresponding budget and make sure the key is in the second dict with the in operator.\ntotal_per_person = {'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Fr...
[ 1 ]
[]
[]
[ "compare", "dictionary", "python" ]
stackoverflow_0074606823_compare_dictionary_python.txt
Q: requirments.txt with actual dependencies Is there a way to create a requirements.txt file that only contains the modules that my script actually needs? I usually just do a pip freeze and then remove unused modules. A: You can use pipreqs to analyze your project files, and automatically generate a requirements.tx...
requirments.txt with actual dependencies
Is there a way to create a requirements.txt file that only contains the modules that my script actually needs? I usually just do a pip freeze and then remove unused modules.
[ "You can use pipreqs to analyze your project files, and automatically generate a requirements.txt for you.\nFirst step is to install pipreqs. You can do so, by executing the following command in your console:\npip install pipreqs\n\nThen, the only thing you need to do is to execute the command pipreqs, specifying t...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074606944_python.txt
Q: How to display a list of children objects on detail view for Django Admin? I have two models: Setting and SettingsGroup. When someone clicks on a specific SettingsGroup in the Django Admin and the edit/detail page appears I'd like for the child Setting objects to be displayed but as a list not a form. I know that ...
How to display a list of children objects on detail view for Django Admin?
I have two models: Setting and SettingsGroup. When someone clicks on a specific SettingsGroup in the Django Admin and the edit/detail page appears I'd like for the child Setting objects to be displayed but as a list not a form. I know that Django has InlineModelAdmin but this displays the children as editable forms. My...
[ "Why can't you just access the children using something like Setting.objects.filter(group=SettingsGroup.objects.get(name={name}))\nIf being presented in a template you could pass the SettingsGroup name to the context and iterate over the children and present them however you like.\nI may not understand your questio...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0074606999_django_django_admin_django_models_python.txt
Q: How to print highest score from an external text file Help! I'm a starter coder and I am trying to build a top trumps game. I have created an external CSV file that stores the scores of the game. I am trying to get the game to print the highest score recorded but I am running in to a lot of errors. SOMEONE PLEASE ...
How to print highest score from an external text file
Help! I'm a starter coder and I am trying to build a top trumps game. I have created an external CSV file that stores the scores of the game. I am trying to get the game to print the highest score recorded but I am running in to a lot of errors. SOMEONE PLEASE HELP :(. I've been working on this for days now and the cod...
[ "Here is a way to manage the score database. There's a \"reader\" that translates from CSV and returns a dictionary, and a \"writer\" that accepts a dictionary and writes it to file. This is called \"serialization\" and \"deserialization\".\nimport random\nimport requests\nimport csv\n\ndef readscores(filename):\...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074606831_csv_python.txt
Q: using regex to split TM symbol from string? As the title states, I am trying to use regex to split the trademark ™ symbol from a string. I am looking for two possible patterns: string™ --> expected result: string ™ or string™2 --> expected result: string ™ 2 I came up with the below pattern to check whether a...
using regex to split TM symbol from string?
As the title states, I am trying to use regex to split the trademark ™ symbol from a string. I am looking for two possible patterns: string™ --> expected result: string ™ or string™2 --> expected result: string ™ 2 I came up with the below pattern to check whether a string contains either potential option: pattern...
[ "I'd do it with re.sub in two steps. First add space from the left side where necessary and then from the right side:\nimport re\n\ns = \"\"\"\\\nstring™\nstring™2\nstring©2\ntest test string™9 test test test\"\"\"\n\n\ns = re.sub(r\"([a-zA-Z0-9])([™©])\", r\"\\1 \\2\", s)\ns = re.sub(r\"([™©])([0-9])\", r\"\\1 \\2...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex", "superscript" ]
stackoverflow_0074606033_python_regex_superscript.txt
Q: get specific number of data from values ​in a column in pandas In order to prevent my machine learning algorithm from tending to a certain data, I want to reduce the frequency differences in my dataset, which is a pandas table, for example, in column X; A value is 1500 times B value is 3000 times C value is 1300 ...
get specific number of data from values ​in a column in pandas
In order to prevent my machine learning algorithm from tending to a certain data, I want to reduce the frequency differences in my dataset, which is a pandas table, for example, in column X; A value is 1500 times B value is 3000 times C value is 1300 times Is there a way to get 1250 of them all?
[ "can you try this:\ndf2=pd.concat(df[df['X']=='A'][:1250],df[df['X']=='B'][:1250],df[df['X']=='C'][:1250])\n\n", "You can group the table according to the column you want to set the frequency of (\"X\" for your example) and get as many data as you want with the head function (if there is less of a value than the ...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074578055_pandas_python.txt
Q: Replace value in rows (does not meet condition) with next closest row (meets condition) I have a dataframe as shown below. They are ordered Ascendingly by Column A and B. Only Occurrences >= 10 are valid, thus for rows with occurrences with less than 10, I want to replace their values with the next/closest valid r...
Replace value in rows (does not meet condition) with next closest row (meets condition)
I have a dataframe as shown below. They are ordered Ascendingly by Column A and B. Only Occurrences >= 10 are valid, thus for rows with occurrences with less than 10, I want to replace their values with the next/closest valid row. Column A Column B Occurrences Value Cell 1 Cell 2 1 0 Cell 1 Cell 3 2 0 Cell ...
[ "Something like this should work in Python:\nimport pandas as pd\nimport numpy as np\n\n# example dataframe\ndict = {'Column A': ['Cell 1', 'Cell 1', 'Cell 1', 'Cell 1', 'Cell 1', 'Cell 2'],\n 'Column B': ['Cell 2', 'Cell 3', 'Cell 4', 'Cell 5', 'Cell 6', 'Cell 1'],\n 'Occurrences': [1, 2, 10, 1, 12, 1],\...
[ 0, 0 ]
[]
[]
[ "google_bigquery", "python", "sql" ]
stackoverflow_0074604707_google_bigquery_python_sql.txt
Q: how to use fstring in a complex json object Is there a way to use fstring to change variable dynamically in a complex json object like this: payload = json.dumps({ "query": "query ($network: EthereumNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) {\n ethereum(network: $network) ...
how to use fstring in a complex json object
Is there a way to use fstring to change variable dynamically in a complex json object like this: payload = json.dumps({ "query": "query ($network: EthereumNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) {\n ethereum(network: $network) {\n transactions(options: {asc: \"date.date\"}...
[ "As I suggested, just convert the nested JSON to a dict and manipulate it:\nimport json\n\npayload = {\n \"query\": \"query ($network: EthereumNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) {\\n ethereum(network: $network) {\\n transactions(options: {asc: \\\"date.date\\\"}, d...
[ 1 ]
[]
[]
[ "f_string", "json", "python", "variables" ]
stackoverflow_0074607184_f_string_json_python_variables.txt
Q: How to pip install tkinter I use pip install python-tk but have an error ERROR: Could not find a version that satisfies the requirement python-tk (from versions: none) ERROR: No matching distribution found for python-tk A: Tkinter isn't distributed through pip; if it didn't come pre-packaged with Python, you hav...
How to pip install tkinter
I use pip install python-tk but have an error ERROR: Could not find a version that satisfies the requirement python-tk (from versions: none) ERROR: No matching distribution found for python-tk
[ "Tkinter isn't distributed through pip; if it didn't come pre-packaged with Python, you have to get it from elsewhere:\n\nUbuntu\n\nsudo apt-get install python3-tk \n\n\nFedora\n\nsudo dnf install python3-tkinter\n\n\nMacOS\n\nbrew install python-tk\n\n" ]
[ 1 ]
[ "It seems like you are trying to install tkinter but using a package name that is not supported.\nEdit this may help\n", "Firstly Make sure Python and pip is preinstalled on your system.\nType the following commands in command prompt to check is python and pip is installed on your system.\nTo check Python:\npytho...
[ -3, -3 ]
[ "python" ]
stackoverflow_0069603788_python.txt
Q: Numpy how to handle a number larger than int64 max? I am working a database that is very poorly organized. There are CustomerIds that are somehow bigger than int64. Here is an example: 88168142359034442077.0 In order to be able to use this ID, I need to turn it into a string and remove the decimal. I have tried to...
Numpy how to handle a number larger than int64 max?
I am working a database that is very poorly organized. There are CustomerIds that are somehow bigger than int64. Here is an example: 88168142359034442077.0 In order to be able to use this ID, I need to turn it into a string and remove the decimal. I have tried to use the following code: testdf = pd.DataFrame({'CUSTID':...
[ "Posting as an Answer because this became too large and I believe has further value\nI'd be very surprised if those values are the real and expected IDs and not an erroneous artifact of importing some text or binary format\nSpecifically, the authoring program(s) and database itself are almost-certainly not using so...
[ 2, 0, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074606765_numpy_pandas_python.txt
Q: Python: How can I pass this return value from one method to another? So I have a class which helps me to get past dates and parse them in a specific format. I know datetime has some functionality around this but I am trying to get a wide different array of formats for my use-case. Here is my setup so you can see w...
Python: How can I pass this return value from one method to another?
So I have a class which helps me to get past dates and parse them in a specific format. I know datetime has some functionality around this but I am trying to get a wide different array of formats for my use-case. Here is my setup so you can see where I am coming from. I have an engine class which houses all my classes ...
[ "I found the solution. So, I set my class structure up like this to clean up my file system and keep my classes clean.\nimport datetime\nfrom ._get_past_date import get_past_date\nfrom ._format_date import format_date\n\n\nclass date:\n\n def __init__(self):\n self.days_of_week = ['Monday', 'Tuesday', 'We...
[ 0 ]
[]
[]
[ "automation", "python", "return", "scripting" ]
stackoverflow_0074607212_automation_python_return_scripting.txt
Q: Multiple class inheritance TypeError with one grandparent, two parents, one child class I'm practicing OOP and keep running into this issue. Here's one example. Take a diamond-shaped multiple class inheritance arrangement, with Weapon feeding Edge and Long, both of which are inherited by Zweihander. If I code Edge...
Multiple class inheritance TypeError with one grandparent, two parents, one child class
I'm practicing OOP and keep running into this issue. Here's one example. Take a diamond-shaped multiple class inheritance arrangement, with Weapon feeding Edge and Long, both of which are inherited by Zweihander. If I code Edge without inheriting Weapon, the code works fine. But as soon as I make Weapon its parent, Edg...
[ "You only need to make a few small changes to each class's __init__ method to properly support cooperative multiple inheritance, per https://rhettinger.wordpress.com/2011/05/26/super-considered-super/\nclass Weapon:\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.does_damage = \...
[ 2 ]
[]
[]
[ "multiple_inheritance", "oop", "python" ]
stackoverflow_0074607049_multiple_inheritance_oop_python.txt
Q: Runtime error: Attempt to start new process before current process finished in python simple LDA implementation I tried running Latent Dirichlet Allocation on a very large dataset using simple LDA and LDAMulticore. But getting the below error after two days of execution "An attempt has been made to start a new pro...
Runtime error: Attempt to start new process before current process finished in python simple LDA implementation
I tried running Latent Dirichlet Allocation on a very large dataset using simple LDA and LDAMulticore. But getting the below error after two days of execution "An attempt has been made to start a new process before the current process has finished its bootstrapping phase. from gensim.models.coherencemodel import Cohere...
[ "It is caused by get_coherence() function, you need to wrap the whole code into main() function and add __name__ == \"__main__\" structure, see:\nhttps://github.com/RaRe-Technologies/gensim/issues/2291#issuecomment-447269158\n(You can also try it first on some very simple text sample, like this one: https://radimre...
[ 0 ]
[]
[]
[ "large_data", "latentdirichletallocation", "process", "python", "runtime_error" ]
stackoverflow_0073263582_large_data_latentdirichletallocation_process_python_runtime_error.txt
Q: Moving widgets in Canvas Tkinter I have a canvas with a little oval in it. It moves throughout the widget using the arrow keys but when it's on the edge of the canvas if I move it beyond that, the oval just disappears. I want the oval stays on any edge of the canvas no matter if I continue pressing the arrow key c...
Moving widgets in Canvas Tkinter
I have a canvas with a little oval in it. It moves throughout the widget using the arrow keys but when it's on the edge of the canvas if I move it beyond that, the oval just disappears. I want the oval stays on any edge of the canvas no matter if I continue pressing the arrow key corresponding to that edge without disa...
[ "You could test the current coordinates and compare them to your canvas size.\nI created a function to get the current x1, y1, x2, y2 from your oval. This way you have the coordiantes of the borders of your oval.\nSo all I do is testing if the oval is touching a border.\nfrom tkinter import *\n\nroot = Tk()\nroot.t...
[ 1, 1 ]
[]
[]
[ "canvas", "python", "tkinter" ]
stackoverflow_0074606986_canvas_python_tkinter.txt
Q: How to iterate throughout the column by comparing two row values in one iteration in python? Here in this excel analysis, there is a condition that was used, Excel formula=(=IF(AND(B2<1;B3>5);1;0)),please refer the image below. (https://i.stack.imgur.com/FpPIK.png) if compressor-1 first-row value is less than 1 (<...
How to iterate throughout the column by comparing two row values in one iteration in python?
Here in this excel analysis, there is a condition that was used, Excel formula=(=IF(AND(B2<1;B3>5);1;0)),please refer the image below. (https://i.stack.imgur.com/FpPIK.png) if compressor-1 first-row value is less than 1 (<1) and the second-row value is greater than 5 (>5) then it will return value '1', if the condition...
[ "You can check the current Compressor 1 row using .lt(...)\ndf[\"Compressor 1\"].lt(1)\n\nAnd the next row using .shift(-1) and .gt(...)\ndf[\"Compressor 1\"].shift(-1).gt(5)\n\nPut them together with & and convert to int\ndf[\"Frequency Cycle Comp 1\"] = (df[\"Compressor 1\"].lt(1) & df[\"Compressor 1\"].shift(-1)...
[ 0 ]
[]
[]
[ "data_analysis", "dataframe", "excel", "pandas", "python" ]
stackoverflow_0074606900_data_analysis_dataframe_excel_pandas_python.txt
Q: If a user enters an invalid string option in python how should I handle the exception? I'm writing a rock, paper, scissors, game for a user and computer and I want the user to type in one of the three options i.e "rock" but I'm not sure what kind of exception to use if the user enters say "monkey." class RockPaper...
If a user enters an invalid string option in python how should I handle the exception?
I'm writing a rock, paper, scissors, game for a user and computer and I want the user to type in one of the three options i.e "rock" but I'm not sure what kind of exception to use if the user enters say "monkey." class RockPaperScissors: def getUserChoice(userchoice): while True: try: ...
[ "It's very helpful to use a sentinel value like None, if you want to remind the user of the input choices after each failed attempt:\nclass RockPaperScissors:\n\n def getUserChoice(self):\n choice = None\n while choice not in ('rock', 'paper', 'scissors'):\n if choice is not None:\n ...
[ 0, 0, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074606911_function_python.txt
Q: How to write a Python program which sums up all the given numbers in a date within a given range? I have written a Python program that prints out all the dates in yyy-mm-dd format within the year 2020. And now i try to write a program which loops/iterate through the year 2020 and prints out the sum of all the give...
How to write a Python program which sums up all the given numbers in a date within a given range?
I have written a Python program that prints out all the dates in yyy-mm-dd format within the year 2020. And now i try to write a program which loops/iterate through the year 2020 and prints out the sum of all the given numbers for each date. For ex: the sum of the date 2020-01-01 is 6 (2+0+2+0+0+1+0+1), the sum of the ...
[ "[int(x) for x in \"2020-01-02\" if x!='-']\n\nis\n[2, 0, 2, 0, 0, 1, 0, 2]\n\nSo, from there\nsum(int(x) for x in \"2020-01-02\" if x!='-')\n# 7\n\nAnd you can go further\n[(ed,sum(int(x) for x in ed.strftime(\"%Y-%m-%d\") if x!='-')) for ed in date_range(start, end)]\n# [(datetime.date(2020, 1, 1), 6), (datetime....
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074607268_python_python_3.x.txt
Q: Assuming the structure of the json string does not change, is the order of a jsonpath match value result stable? Assuming the structure of the json string does not change, is the order of a jsonpath match value result stable? import jsonpath_ng response = json.loads(response) jsonpath_expression_name = jsonpath_...
Assuming the structure of the json string does not change, is the order of a jsonpath match value result stable?
Assuming the structure of the json string does not change, is the order of a jsonpath match value result stable? import jsonpath_ng response = json.loads(response) jsonpath_expression_name = jsonpath_ng.parse("$[forms][0][questionGroups][*][questions]..[name]") match_name = [match.value for match in jsonpath_expressi...
[ "Yes, the order of a jsonpath match value result is stable as long as the structure of the json string does not change. This is because jsonpath expressions are evaluated in a deterministic manner, meaning that the same expression will always return the same result.\n" ]
[ 3 ]
[]
[]
[ "dictionary_comprehension", "json", "jsonpath", "python" ]
stackoverflow_0074497071_dictionary_comprehension_json_jsonpath_python.txt
Q: How to render a Django Serializer Template with React Js? I've set up my api for a basic model in my Django project. I've defined my post and get methods and everything is working correctly. Now, I'm wondering how I can render my Django model using react js. Essentially, I'm wondering how I can use react js to ass...
How to render a Django Serializer Template with React Js?
I've set up my api for a basic model in my Django project. I've defined my post and get methods and everything is working correctly. Now, I'm wondering how I can render my Django model using react js. Essentially, I'm wondering how I can use react js to assign my django model values that were inserted using reactjs ins...
[ "Instead of thinking how to render your django model in react, i think it is easier to understand when you think in the server-client model.\nBasically you want to get you data from your django server and then show it in the client, using react.\nTo do this with Django rest framework, the best way is to make HTTP r...
[ 0 ]
[]
[]
[ "django", "javascript", "python", "reactjs" ]
stackoverflow_0074606323_django_javascript_python_reactjs.txt
Q: How to change the value of a python variable from a .kv file I am new fairly new to python and have just started using the kivy library. I am trying to change the value of a variable in the .py file when a button from the .kv file is pressed. I am unsure how to instigate this. The code I currently have is: python ...
How to change the value of a python variable from a .kv file
I am new fairly new to python and have just started using the kivy library. I am trying to change the value of a variable in the .py file when a button from the .kv file is pressed. I am unsure how to instigate this. The code I currently have is: python file: from kivy.app import App from kivy.uix.widget import Widget ...
[ "The on_press item needs to be connected to a method (function) in your code. One can use root.something to reach the widget or app.something to reach a method in the app object.\nKivy file\n<experienceScreen>:\n FloatLayout:\n pos:0,0\n size: root.width, root.height\n Label:\n text: 'What...
[ 0 ]
[]
[]
[ "kivy", "kivy_language", "python" ]
stackoverflow_0074605282_kivy_kivy_language_python.txt
Q: Cannot import pycaret in google colab I cant import pycaret in a google colab Here are all the steps I had taken: Change python version to 3.8 Installed pip I then ran !pip install pycaret import pycaret the install works, but then ModuleNotFoundError Traceback (most recent call last) <ipyt...
Cannot import pycaret in google colab
I cant import pycaret in a google colab Here are all the steps I had taken: Change python version to 3.8 Installed pip I then ran !pip install pycaret import pycaret the install works, but then ModuleNotFoundError Traceback (most recent call last) <ipython-input-27-fdea18e6876c> in <module> ...
[ "!pip install pycaret\n\nshould work without any issues. I have used it multiple times on Google Colab. Alternately, you can use\npip install --pre pycaret\n\n", "For importing use this, this is one is for classification:\nfrom pycaret.classification import *\n\nAnd for regression:\nfrom pycaret.regression import...
[ 0, 0 ]
[]
[]
[ "google_colaboratory", "import", "pip", "pycaret", "python" ]
stackoverflow_0074295700_google_colaboratory_import_pip_pycaret_python.txt
Q: How to produce correct endless socket connection? I need to produce endless socket connections, which can be broke only with 1KeyboardInterupt1 or special word. When I start both programs in different IDEs, the sender asks to input the message. But only the first message sends to the server and all the others don'...
How to produce correct endless socket connection?
I need to produce endless socket connections, which can be broke only with 1KeyboardInterupt1 or special word. When I start both programs in different IDEs, the sender asks to input the message. But only the first message sends to the server and all the others don't. I need to produce an endless cycle, where all inputs...
[ "The s.close() must be out of the while loop.\n" ]
[ 0 ]
[]
[]
[ "cycle", "python", "sockets" ]
stackoverflow_0074606513_cycle_python_sockets.txt
Q: Python - Grouping by multiple columns (Categorical dtype vs numeric dtype)- why are the results so different? I have a question about grouping pandas DataFrames by multiple columns. I am looking at some data for a TV show and trying to ensure that no season has two contestants with the same name. Series Name 1 D...
Python - Grouping by multiple columns (Categorical dtype vs numeric dtype)- why are the results so different?
I have a question about grouping pandas DataFrames by multiple columns. I am looking at some data for a TV show and trying to ensure that no season has two contestants with the same name. Series Name 1 David 1 Edward 1 Jasmine 2 Lea 2 Jonathan 2 Louise I want a unique count for groupings of Series...
[ "Actually, this is the default behaviour of Pandas when grouping categorical value, it adds missing categories (checkout this thread).\nTo group only the observed categories on the dataframe you can use:\ndf.groupby(['Series','Name'],observed=True)['Name'].count()\n\n" ]
[ 0 ]
[]
[]
[ "group_by", "multiple_columns", "pandas", "python" ]
stackoverflow_0074607271_group_by_multiple_columns_pandas_python.txt
Q: Type Error, Need a Y/N user confirmation. Python I am working on a function that will delete records of individuals but before doing so, it will display: Are you sure you want to delete record with Last Name: Apple, First Name: Amy ? Enter Y or N I got through most of my function. I am having difficulty with this...
Type Error, Need a Y/N user confirmation. Python
I am working on a function that will delete records of individuals but before doing so, it will display: Are you sure you want to delete record with Last Name: Apple, First Name: Amy ? Enter Y or N I got through most of my function. I am having difficulty with this Yes or No part. The code I have for the delete functi...
[ "input takes a single string as a parameter, but you've provided three. Construct a single string:\nif input(f\"Are you sure you want to delete record {roll} (y/n)? \") != \"y\":\n\n" ]
[ 0 ]
[]
[]
[ "python", "typeerror", "types" ]
stackoverflow_0074607473_python_typeerror_types.txt
Q: Is there a way to send query params for tests? I am trying to make some tests in which asks for ads of a particular type for instance: http://127.0.0.1:8000/ads/?type=normal should return the normal ads and http://127.0.0.1:8000/ads/?type=premium should return the premium ads the tests ask for the ads like thi...
Is there a way to send query params for tests?
I am trying to make some tests in which asks for ads of a particular type for instance: http://127.0.0.1:8000/ads/?type=normal should return the normal ads and http://127.0.0.1:8000/ads/?type=premium should return the premium ads the tests ask for the ads like this response = self.client.get(reverse("ads")) self.cl...
[ "When a URL is like domain/search/?q=haha, you would use request.GET.get('q', '').\nq is the parameter you want, and '' is the default value if q isn't found.\nHowever, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments)....
[ 0 ]
[]
[]
[ "django", "python", "testing" ]
stackoverflow_0074606501_django_python_testing.txt
Q: Keras Invalid argument: required broadcastable shapes at loc(unknown) I have been training my model by feeding the fit() method with train and test generators from the data that is stored away in hdf5 files (approx. 25,000 images and labels). I have recently processed negative cases into a new hdf5 file with a sim...
Keras Invalid argument: required broadcastable shapes at loc(unknown)
I have been training my model by feeding the fit() method with train and test generators from the data that is stored away in hdf5 files (approx. 25,000 images and labels). I have recently processed negative cases into a new hdf5 file with a similar amount of images, however, after updating the generator to read from b...
[ "After some debugging, the error lied in one of the output shapes from the generator.\nI was always guaranteeing that neg_labels to have the same shape as labels even though neg_images might not on the zeroth axis.\nThe fix was to set the shape of neg_labels to neg_images's shape on the first three axes and labels ...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074595310_keras_python_tensorflow.txt
Q: Python - split string without inner string I wanted to ask. if there is an efficient way to split a string and ignore inner strings of is Example: I get a string in this format: s = 'name,12345,Hello,\"12,34,56\",World' and the output I want, is: ['name', '12345', 'Hello', "12,34,56", 'World'] by splitting at th...
Python - split string without inner string
I wanted to ask. if there is an efficient way to split a string and ignore inner strings of is Example: I get a string in this format: s = 'name,12345,Hello,\"12,34,56\",World' and the output I want, is: ['name', '12345', 'Hello', "12,34,56", 'World'] by splitting at the "," the numbers become separated: ['name', '12...
[ "This job belongs to the csv module:\nimport csv\n\nout = next(csv.reader([s], skipinitialspace=True))\n# out is\n# ['name', '12345', 'Hello', '12,34,56', 'World']\n\nNotes\n\nThe csv library deals with comma-separated values, perfect for this job\nIt understands quotes, which your input calls for\nThe csv.reader t...
[ 3, 2, 1 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0074607505_python_split_string.txt
Q: Plotly: How to plot a tetrahedron volume I have a set of xyz points and a set of tetrahedrons. Where each node of the tetrahedron points to an index in the points table. I need to plot the tetrahedrons with a corresponding color based on the tag attribute. points Index x y z 0 x_1 y_1 z_1 1 x_2 y_2 z_2 ... ......
Plotly: How to plot a tetrahedron volume
I have a set of xyz points and a set of tetrahedrons. Where each node of the tetrahedron points to an index in the points table. I need to plot the tetrahedrons with a corresponding color based on the tag attribute. points Index x y z 0 x_1 y_1 z_1 1 x_2 y_2 z_2 ... ... ... ... tetrahedrons Index a ...
[ "I can't hide the fact that, a few minutes ago, I wasn't even aware of i,j,k parameters. But, still, I know that Mesh3D draws triangles, not tetrahedron. You need to take advantage of those i,j,k parameters to control which triangles are drawn. But it is still your job to tell which triangles need to be drawn to th...
[ 1, 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074607379_plotly_python.txt
Q: Improve the implementation of worldquant 101 alpha factors using numpy I was trying to implement 101 quant trading factors that were published by WorldQuant (https://arxiv.org/pdf/1601.00991.pdf). A typical factor is about processing stocks' price and volume information along with both time dimension and stock dim...
Improve the implementation of worldquant 101 alpha factors using numpy
I was trying to implement 101 quant trading factors that were published by WorldQuant (https://arxiv.org/pdf/1601.00991.pdf). A typical factor is about processing stocks' price and volume information along with both time dimension and stock dimension. Take the example of alpha factor #4: (-1 * Ts_Rank(rank(low), 9)). ...
[ "This part of the code:\nreturn np.apply_along_axis(rankdata, axis, a, method)\n\n...is going to be quite slow. Function application like this means more of the computation runs in Python, and relatively little of it runs in C.\nThere's a much faster solution available here, if you're okay with a slight change in h...
[ 1 ]
[]
[]
[ "dolphindb", "numpy", "pandas", "python", "quantitative_finance" ]
stackoverflow_0073694527_dolphindb_numpy_pandas_python_quantitative_finance.txt
Q: How to click a word on screen with pyutogui The error I am getting is: OSError: Failed to read Ok because file is missing, has improper permissions or is an unsupported or invalid format. Can someone help me? I’m using the command: pyautogui.click(‘Ok’) I was expecting this to click Ok on the screen when it pops u...
How to click a word on screen with pyutogui
The error I am getting is: OSError: Failed to read Ok because file is missing, has improper permissions or is an unsupported or invalid format. Can someone help me? I’m using the command: pyautogui.click(‘Ok’) I was expecting this to click Ok on the screen when it pops up. My code is: from pyvirtualdisplay import Displ...
[ "pyautogui.leftClick('OK') will do nothing since pyautogui.click() will take x and y coordinates for example:\npyautogui.click(100,100) #will click at the coordinates x 100 and y 100 \n\nWe can use locateOnScreen to get x,y coordinates of a image and then click it with pyautogui.click\nIn your case:\ntime.sleep(2)\...
[ 0 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0074607144_pyautogui_python.txt
Q: Python selenium gets stuck on site loading screen First of all, this is the website I use. The code block I used: from selenium import webdriver browserProfile = webdriver.ChromeOptions() browserProfile.add_argument("start-maximized") browserProfile.add_argument('--disable-blink-features=AutomationControlled') bro...
Python selenium gets stuck on site loading screen
First of all, this is the website I use. The code block I used: from selenium import webdriver browserProfile = webdriver.ChromeOptions() browserProfile.add_argument("start-maximized") browserProfile.add_argument('--disable-blink-features=AutomationControlled') browserProfile.add_argument('--user-agent=Mozilla/5.0 (Win...
[ "I would suggest you explore the following code:\nimport time\ntime.sleep(1) #sleep for 1 sec\ntime.sleep(0.25) #sleep for 250 milliseconds\n\n", "Make sure your chromedriver is up-to-date.\nIn your browser goto help -> about Google Chrome\nand check your version and then get the latest chromedriver\nfrom chromed...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0072622791_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Azure functions app keeps returning 401 unauthorized I have created an Azure Function base on a custom image (docker) using VS Code. I used the deployment feature of VS code to deploy it to azure and everything was fine. My function.json file specifies anonymous auth level: { "scriptFile": "__init__.py", "bind...
Azure functions app keeps returning 401 unauthorized
I have created an Azure Function base on a custom image (docker) using VS Code. I used the deployment feature of VS code to deploy it to azure and everything was fine. My function.json file specifies anonymous auth level: { "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type...
[ "Below methods can fix 4XX errors in our function app:\n\nMake sure you add all the values from Local.Settings.json file to Application settings (FunctionApp -> Configuration -> Application Settings)\n\nCheck for CORS in your function app. Try adding “*” and saving it.. reload the function app and try to run it.\n(...
[ 0, 0, 0 ]
[]
[]
[ "azure_functions", "docker", "python" ]
stackoverflow_0069188433_azure_functions_docker_python.txt
Q: Creating a day of year column overriding the leap day in a leap year I have a large database of climate variables - daily values of temp, humidity etc. I have a timestamp column %Y%m%d. I have removed leap days, as I need uniform 365 days for each of my years. I want to add a new column called 'day_of_year' with 1...
Creating a day of year column overriding the leap day in a leap year
I have a large database of climate variables - daily values of temp, humidity etc. I have a timestamp column %Y%m%d. I have removed leap days, as I need uniform 365 days for each of my years. I want to add a new column called 'day_of_year' with 1 to 365 for each year for as many years as I have in my database. How can ...
[ "Use pandas' day of year function, but instead of giving it the real timestamp, e.g. \"2022-11-27\", give it \"2021-\" + timestamp[-5:]. This will give you the altered number as if the timestamp was not a leap year.\n" ]
[ 0 ]
[]
[]
[ "arrays", "for_loop", "numpy", "pandas", "python" ]
stackoverflow_0074607654_arrays_for_loop_numpy_pandas_python.txt
Q: Selenium-webdriver script breaks loop I had been tasked with fixing a digital sign loop running off python in the office. The original script was lost due to a OS crash and I had to recreate it. I am at my python limits on fixing what I had been able to create using selenium. I wrote the below script and it functi...
Selenium-webdriver script breaks loop
I had been tasked with fixing a digital sign loop running off python in the office. The original script was lost due to a OS crash and I had to recreate it. I am at my python limits on fixing what I had been able to create using selenium. I wrote the below script and it functions for random periods of time before the l...
[ "At the bottom of this, python thinks there isn't a fourth window open. So first, let's put in some error handling, something like this:\nwhile True:\n try:\n if \"FireEye\" in driver.title:\n time.sleep(20)\n driver.switch_to.window(driver.window_handles[1])\n \n elif...
[ 0 ]
[]
[]
[ "python", "selenium_webdriver", "while_loop" ]
stackoverflow_0074604780_python_selenium_webdriver_while_loop.txt
Q: Generate pairs of users from list trying to create a function which generates pairs of users from list. Everyone have to get a pair. Example list of user IDs: list = [123, 456, 789] ...smth... result = {123:456, 456:789, 789:123} — OK list = [123, 456, 789] ...smth... result = {123:456, 456:123, 789:789} — BAD ...
Generate pairs of users from list
trying to create a function which generates pairs of users from list. Everyone have to get a pair. Example list of user IDs: list = [123, 456, 789] ...smth... result = {123:456, 456:789, 789:123} — OK list = [123, 456, 789] ...smth... result = {123:456, 456:123, 789:789} — BAD list = [123, 456, 789, 234, 678] ...sm...
[ "Assuming the pairs to be tuples, you can use itertools.combinations.\nFrom the docs (table on top of the page):\n\nr-length tuples, in sorted order, no repeated elements\n\nAnd:\n\nElements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repe...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x", "shuffle" ]
stackoverflow_0074607587_dictionary_list_python_python_3.x_shuffle.txt
Q: Where to store cross-testrun state in pytest (binary files)? I have a session-level fixture in pytest that downloads several binary files that I use throughout my test suite. The current fixture looks something like the following: @pytest.fixture(scope="session") def image_cache(pytestconfig, tmp_path_factory): ...
Where to store cross-testrun state in pytest (binary files)?
I have a session-level fixture in pytest that downloads several binary files that I use throughout my test suite. The current fixture looks something like the following: @pytest.fixture(scope="session") def image_cache(pytestconfig, tmp_path_factory): # A temporary directory loaded with the test image files downloa...
[ "A bit late here, but maybe I can still offer a helpful suggestion. You have at least two options, I think:\n\nuse pytest's caching solution on its own. Yes, it expects JSON-serializable data, so you'll need to convert your \"binary\" into strings. You can use base64 to safely encode arbitrary binary into letters...
[ 0 ]
[]
[]
[ "caching", "pytest", "python", "state" ]
stackoverflow_0070711084_caching_pytest_python_state.txt
Q: Convert directed graph to horizontal data format in pandas python I just started with python and know almost nothing about pandas. so now I have a directed graph which look like this: from ID to ID 13 22 13 56 14 10 14 15 14 16 now I need to transform it to horizontal data format like this: from ID To 0 To...
Convert directed graph to horizontal data format in pandas python
I just started with python and know almost nothing about pandas. so now I have a directed graph which look like this: from ID to ID 13 22 13 56 14 10 14 15 14 16 now I need to transform it to horizontal data format like this: from ID To 0 To 1 To 2 13 22 56 NAN 14 10 15 16 I find somet...
[ "You can do something like this to transform your dataframe, pandas will automatically add NaN values for any number of columns you have with this solution.\ndf = df.groupby('from')['to'].apply(list)\n\n## create the desired df from the lists\ndf = pd.DataFrame(df.tolist(),index=df.index).reset_index()\n\n\n## Rena...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074607584_pandas_python.txt
Q: Problem in debugging django project using VS code I have a problem while debugging a django project using VS code, the problem that nothing happened when I click to debug button, I can launch my script just by tapping in terminal python manage.py runserver. Here is my launch.json file, and note please that I tried...
Problem in debugging django project using VS code
I have a problem while debugging a django project using VS code, the problem that nothing happened when I click to debug button, I can launch my script just by tapping in terminal python manage.py runserver. Here is my launch.json file, and note please that I tried a lot of examples, and still the same problem: { "...
[ "I find a solution to solve this problem by upgrade the python version to 3.7, I don't have any idea about the problem happened in version 3.6, by the way, the upgrade python version is the solution.\n" ]
[ 0 ]
[]
[]
[ "debugging", "django", "python", "visual_studio_code" ]
stackoverflow_0074594548_debugging_django_python_visual_studio_code.txt
Q: How to scroll an element to exactly the middle of a screen using Selenium with Python I'm automating a webpage using Robot Framework, Selenium and python. There are several clicks on different elements of the page, and I want to first scroll the element exactly to the middle of the screen, and then click on it. I ...
How to scroll an element to exactly the middle of a screen using Selenium with Python
I'm automating a webpage using Robot Framework, Selenium and python. There are several clicks on different elements of the page, and I want to first scroll the element exactly to the middle of the screen, and then click on it. I have already used this: self.seleniumlibrary.scroll_element_into_view(element) but it does...
[ "There are several steps you can take:\n\nTry to maximize the browser screen with the command\n\n\nmaximize browser window\n\n\nDo a web page scroll\n\n\nexecute javascript window.scrollTo(0,2500)\n\n\n0 = start condition for scrolling page\n\n\n2500 = how far to scroll the webpage\n\nor you can do :\n\nscroll elem...
[ 1 ]
[]
[]
[ "javascript", "python", "robotframework", "screen", "selenium" ]
stackoverflow_0074592595_javascript_python_robotframework_screen_selenium.txt