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: Why " NumExpr defaulting to 8 threads. " warning message shown in python? I am trying to use the lux library in python to get visualization recommendations. It shows warnings like NumExpr defaulting to 8 threads.. import pandas as pd import numpy as np import opendatasets as od pip install lux-api import lux impor...
Why " NumExpr defaulting to 8 threads. " warning message shown in python?
I am trying to use the lux library in python to get visualization recommendations. It shows warnings like NumExpr defaulting to 8 threads.. import pandas as pd import numpy as np import opendatasets as od pip install lux-api import lux import matplotlib And then: link = "https://www.kaggle.com/noordeen/insurance-premi...
[ "This is not really something to worry about in most cases. The warning comes from this function, here the most important part:\n...\n env_configured = False\n n_cores = detect_number_of_cores()\n if 'NUMEXPR_MAX_THREADS' in os.environ:\n # The user has configured NumExpr in the expected way, so sup...
[ 0 ]
[]
[]
[ "numexpr", "numpy", "python", "warnings" ]
stackoverflow_0071248521_numexpr_numpy_python_warnings.txt
Q: How to receive a num at each step and continue until zero is entered; then this program should print each entered num as its own num Here I have this code: N = int(input()) Tmp=n While tmp>0 : Print(n) Tmp-=1 But for ex: when I have: 3 2 1 0 As entered nums, it just prints: 3 3 3 But I need to print: 3 3 3 2 2 1 H...
How to receive a num at each step and continue until zero is entered; then this program should print each entered num as its own num
Here I have this code: N = int(input()) Tmp=n While tmp>0 : Print(n) Tmp-=1 But for ex: when I have: 3 2 1 0 As entered nums, it just prints: 3 3 3 But I need to print: 3 3 3 2 2 1 Here I have this code: N = int(input()) Tmp=n While tmp>0 : Print(n) Tmp-=1 But there is a problem!bc it just prints 3 3 3 Ins...
[ "you need to print(tmp) instead of print(n)\nthis will print 3 2 1.\nTo get 3 3 3 2 2 1 you need to change your code more:\nn = int(input())\n\ntmp=n\n\nwhile tmp > 0:\n for _ in range(tmp)\n print(tmp)\n tmp -= 1\n\n\n", "You need to add if statement when tmp equals 0 then subtract n by 1 and assign tmp bac...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074655549_python.txt
Q: Spreading out shift assignments in constraint solver (ortools) I used the Google OR-Tools Employee Scheduling script (thanks by the way) to make a on-call scheduler. Everything works fine and it is doing what it is supposed to. It makes sure each person works about the same amount of "shifts" (two week periods),...
Spreading out shift assignments in constraint solver (ortools)
I used the Google OR-Tools Employee Scheduling script (thanks by the way) to make a on-call scheduler. Everything works fine and it is doing what it is supposed to. It makes sure each person works about the same amount of "shifts" (two week periods), it lets certain shifts be requested and I added a constraint where ...
[ "There seem to be frequent complaints about lack of documentation, but there is some available on the Google OR-Tools site at https://developers.google.com/optimization .\nI learned a lot from the user manual from the old Google OR-Tools ConstraintSolver, to be found at https://www.scribd.com/document/482135694/use...
[ 1 ]
[]
[]
[ "constraint_programming", "cp_sat_solver", "or_tools", "python", "python_3.x" ]
stackoverflow_0074627968_constraint_programming_cp_sat_solver_or_tools_python_python_3.x.txt
Q: What is the meaning of reset_states() and update_state() in tf.keras metrics? I am checking very simple metrics objects in tensorflow.keras such as BinaryAccuracy or AUC. They all have reset_states() and update_state() arguments, but I found their documentation insufficient and unclear. Can you explain what they m...
What is the meaning of reset_states() and update_state() in tf.keras metrics?
I am checking very simple metrics objects in tensorflow.keras such as BinaryAccuracy or AUC. They all have reset_states() and update_state() arguments, but I found their documentation insufficient and unclear. Can you explain what they mean?
[ "update_state measures the metrics (mean, auc, accuracy), and stores them in the object, so it can later be retrieved with result:\nimport tensorflow as tf\n\nmean_object = tf.metrics.Mean()\n\nvalues = [1, 2, 3, 4, 5]\n\nfor ix, val in enumerate(values):\n mean_object.update_state(val)\n print(mean_object.re...
[ 4, 0 ]
[]
[]
[ "keras", "metrics", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0065722580_keras_metrics_python_tensorflow_tensorflow2.0.txt
Q: Using Selenium and Python, but Print function not working I am using selenium to write a test script to purchase a number of items automatically. However for some reason when I am asking python to print a certain elements text, nothing is appearing in the console for me to assert that my script has selected the co...
Using Selenium and Python, but Print function not working
I am using selenium to write a test script to purchase a number of items automatically. However for some reason when I am asking python to print a certain elements text, nothing is appearing in the console for me to assert that my script has selected the correct colour of the item. # Driver select the first trainer opt...
[ "If the text is not on the element and is on childrens of the element, change .text to .get_attribute(\"innerText\")\nOther solution could be accurate more on the element you want to extract, but sometimes you need this cause text is mixed on multiple elements\ntrainerColour1 = driver.find_element(By.XPATH,\"//span...
[ 0 ]
[]
[]
[ "console", "pycharm", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074654178_console_pycharm_python_selenium_selenium_webdriver.txt
Q: Can I setup a simple job queue with celery on a plotly dashboard? I have a dashboard very similar to this one- import datetime import dash from dash import dcc, html import plotly from dash.dependencies import Input, Output # pip install pyorbital from pyorbital.orbital import Orbital satellite = Orbital('TERRA')...
Can I setup a simple job queue with celery on a plotly dashboard?
I have a dashboard very similar to this one- import datetime import dash from dash import dcc, html import plotly from dash.dependencies import Input, Output # pip install pyorbital from pyorbital.orbital import Orbital satellite = Orbital('TERRA') external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']...
[ "Yes, you can achieve this with Celery. Celery is a task queue that allows you to schedule tasks to be executed at a later time. It is designed to be used in distributed systems and can be used to manage the execution of callbacks in your Dash application.\nA small working example of using Celery with Dash would lo...
[ 0, 0 ]
[]
[]
[ "celery", "plotly", "plotly_dash", "plotly_python", "python" ]
stackoverflow_0074533185_celery_plotly_plotly_dash_plotly_python_python.txt
Q: How do I use selenium ChromeDriver to scroll the sidebar on Google maps to load more results? I’ve run into a problem trying to use Selenium ChromeDriver to scroll down the sidebar of a google maps results page. I am trying to get to the 6th result down but the result does not fully load until you scroll down. Usi...
How do I use selenium ChromeDriver to scroll the sidebar on Google maps to load more results?
I’ve run into a problem trying to use Selenium ChromeDriver to scroll down the sidebar of a google maps results page. I am trying to get to the 6th result down but the result does not fully load until you scroll down. Using the find_element_by_xpath method, I am successfully able to access results 1-5 and click into th...
[ "I found a solution that works, it is to target the element in XPATH from the javascript interface of selenium. You must then execute two commands on an instruction (targeting and scroll)\ndriver.executeScript(\"var el = document.evaluate('/html/body/jsl/div[3]/div[10]/div[8]/div/div[1]/div/div/div[4]/div[1]', docu...
[ 1, 0, 0 ]
[]
[]
[ "html", "python", "scroll", "selenium", "selenium_webdriver" ]
stackoverflow_0067783868_html_python_scroll_selenium_selenium_webdriver.txt
Q: Distance from a point to a line I have created a class "Point" and i want to calculate the shortest distance between a given point and a line ( characterized by 2 other points ), all points are known. I tried to use this formula : |Ax+By+C| / sqrt(A^2+B^2) , but i messed up and got more confused by the minute (mo...
Distance from a point to a line
I have created a class "Point" and i want to calculate the shortest distance between a given point and a line ( characterized by 2 other points ), all points are known. I tried to use this formula : |Ax+By+C| / sqrt(A^2+B^2) , but i messed up and got more confused by the minute (mostly because of math formulas :( )......
[ "You should be able to use this formula from the points directly. So, you'd have something like:\nimport math\n\nclass Point:\n def distance_to_line(self, p1, p2):\n x_diff = p2.x - p1.x\n y_diff = p2.y - p1.y\n num = abs(y_diff*self.x - x_diff*self.y + p2.x*p1.y - p2.y*p1.x)\n den = ...
[ 6, 0, 0, 0 ]
[]
[]
[ "distance", "line", "point", "python", "python_3.x" ]
stackoverflow_0040970478_distance_line_point_python_python_3.x.txt
Q: Numpy/Scipy: Efficient Determinant of Gram Matrix I need to compute the (log of the) determinant of the Gram matrix of a matrix A and I was wondering if there is a way to compute this efficiently and in a stable way in Numpy/Scipy. import numpy as np m, n = 100, 150 J = np.random.randn(m, n) np.log(np.det(J.dot(J....
Numpy/Scipy: Efficient Determinant of Gram Matrix
I need to compute the (log of the) determinant of the Gram matrix of a matrix A and I was wondering if there is a way to compute this efficiently and in a stable way in Numpy/Scipy. import numpy as np m, n = 100, 150 J = np.random.randn(m, n) np.log(np.det(J.dot(J.T))) is there some LAPACK routine or some math trick I...
[ "For better numerical stability, I would suggest to use slogdet, which is your main aim in any case. There may also be a very minimal gain if you use np.inner(J, J) instead of J.dot(J.T). For really speeding things up, I would recommend using jax.numpy.\nimport numpy as np\nimport jax\nimport jax.numpy as jnp\n\nm,...
[ 2 ]
[]
[]
[ "determinants", "numpy", "python", "scipy" ]
stackoverflow_0074654414_determinants_numpy_python_scipy.txt
Q: Telethon async and await mess Here is my code as follows: import time import telethon import asyncio # Enter your API ID and API hash here api_id = 13****** api_hash = '8ba0a***********************' # Enter the name of the text file containing the messages message_file = 'messages.txt' async def main(): # C...
Telethon async and await mess
Here is my code as follows: import time import telethon import asyncio # Enter your API ID and API hash here api_id = 13****** api_hash = '8ba0a***********************' # Enter the name of the text file containing the messages message_file = 'messages.txt' async def main(): # Connect to the Telegram API using yo...
[ "Try changing your code to something like this:\nimport asyncio\nimport telethon\n\napi_id = 13******\napi_hash = '8ba0a***********************'\nmessage_file = 'messages.txt'\n\n# Better style would be to have these not initiated\n# at the top-level and instead behind the if name == main\n# guard, but lets keep it...
[ 0 ]
[]
[]
[ "async_await", "python", "telegram", "telethon" ]
stackoverflow_0074655509_async_await_python_telegram_telethon.txt
Q: Assigning to a subset of a Dataframe (with a selection or other method) in python Polars In Pandas I can do the following: data = pd.DataFrame( { "era": ["01", "01", "02", "02", "03", "10"], "pred1": [1, 2, 3, 4, 5,6], "pred2": [2,4,5,6,7,8], "pred3": [3,5,6,8,9,1], "something_else": [5,4,3,...
Assigning to a subset of a Dataframe (with a selection or other method) in python Polars
In Pandas I can do the following: data = pd.DataFrame( { "era": ["01", "01", "02", "02", "03", "10"], "pred1": [1, 2, 3, 4, 5,6], "pred2": [2,4,5,6,7,8], "pred3": [3,5,6,8,9,1], "something_else": [5,4,3,67,5,4], }) pred_cols = ["pred1", "pred2", "pred3"] ERA_COL = "era" DOWNSAMPLE_CROSS_VAL = 10 ...
[ "Let's see if I can help. It would appear that what you want to accomplish is to replace a subset/filtered portion of a column with values derived from other one or more other columns.\nFor example, if you are attempting to accomplish this:\nERA_COL = \"era\"\n\ntest_split = [\"01\", \"02\", \"10\"]\ntest_split_in...
[ 0, 0 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074645846_python_python_polars.txt
Q: convert flatten dict to nested dict I use this function to convert nested dict to flatten dict: make_flatten_dict = lambda d, sep: pd.json_normalize(d, sep=sep).to_dict(orient='records')[0] input: d = {'a': 1, 'c': {'a': '#a_val', 'b': {'x': '#x_value', 'y' : '#y'}}, 'd': [1, '#d_i1', 3]} output: {'a': 1, 'd': ...
convert flatten dict to nested dict
I use this function to convert nested dict to flatten dict: make_flatten_dict = lambda d, sep: pd.json_normalize(d, sep=sep).to_dict(orient='records')[0] input: d = {'a': 1, 'c': {'a': '#a_val', 'b': {'x': '#x_value', 'y' : '#y'}}, 'd': [1, '#d_i1', 3]} output: {'a': 1, 'd': [1, '#d_i1', 3], 'c.a': '#a_val', 'c.b.x'...
[ "For each multi-key you need to build the tree, add a {} for each one except the last, then use the last one to assign the value\nvalue = {'a': 1, 'd': [1, '#d_i1', 3], 'c.a': '#a_val', 'c.b.x': '#x_value', 'c.b.y': '#y'}\n\nresult = {}\nfor k, v in value.items():\n tmp = result\n *keys, last = k.split(\".\")...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074656144_python.txt
Q: Bitcoin Chart with log scale Python I'm using Python (beginner) and I want to plot the Bitcoin price in log scale but without seeing the log price, I want to see the linear price. import pandas as pd import matplotlib.pyplot as plt import numpy as np from cryptocmd import CmcScraper from math import e from matplo...
Bitcoin Chart with log scale Python
I'm using Python (beginner) and I want to plot the Bitcoin price in log scale but without seeing the log price, I want to see the linear price. import pandas as pd import matplotlib.pyplot as plt import numpy as np from cryptocmd import CmcScraper from math import e from matplotlib.ticker import ScalarFormatter # ---...
[ "Welcome to Stackoverflow!\nYou were getting there, the following code will yield what you want (I simply added some fake data + 1 line of code to your plotting code):\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\ny = [10**x for x in np.arange(0, 5, 0.1)]\nx = [x for x ...
[ 0 ]
[]
[]
[ "bitcoin", "price", "python", "scale" ]
stackoverflow_0074654327_bitcoin_price_python_scale.txt
Q: How to lookup in python between 2 dataframes with match mode -> an exact match or the next larger item? I'd like to create a lookup (similar to excel for example) with match mode -> an exact match or the next larger item. Let's say I have these 2 dataframes: seed(1) np.random.seed(1) Wins_Range = np.arange(1,101,...
How to lookup in python between 2 dataframes with match mode -> an exact match or the next larger item?
I'd like to create a lookup (similar to excel for example) with match mode -> an exact match or the next larger item. Let's say I have these 2 dataframes: seed(1) np.random.seed(1) Wins_Range = np.arange(1,101,1) Wins = pd.DataFrame({"Wins Needed": Wins_Range}) Wins Wins Needed 0 1 1 2 2 3 3 4 4 5 ......
[ "You need a merge_asof:\nout = pd.merge_asof(Wins, Levels, left_on='Wins Needed', right_on='Wins',\n direction='forward')[['Wins Needed', 'Level']]\n\nOr\nWins['Level'] = pd.merge_asof(Wins, Levels, left_on='Wins Needed', right_on='Wins',\n direction='forward')['Level...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074656342_dataframe_pandas_python.txt
Q: I am trying to make a simple gradient descent algorithm in python, but it goes back up after passing through the lowest point Problem I am trying to build a simple gradient descent algorithm and plot it on a heatmap. I assume there are better ways to do this, but I have to use this methodology. My professor and I ...
I am trying to make a simple gradient descent algorithm in python, but it goes back up after passing through the lowest point
Problem I am trying to build a simple gradient descent algorithm and plot it on a heatmap. I assume there are better ways to do this, but I have to use this methodology. My professor and I have very similar code but we cannot understand why mine behaves differently. Once the lowest point is reached, it should just turn...
[ "Solution\nThe problem was in effect with the grad function or rather with the ddx and ddy functions. These two functions were actually the same, except I was swapping x and y.\nIn other words, I wasn't computing the partial derivatives correctly which caused my gradient to be wrong and my algorithm to not work pro...
[ 0 ]
[]
[]
[ "algorithm", "gradient", "gradient_descent", "math", "python" ]
stackoverflow_0074646385_algorithm_gradient_gradient_descent_math_python.txt
Q: Does the preprocessing of one algorithm change the conditions of the experiment? As an example, We have two algorithms that utilize the same dataset and the same train and test data: 1 - uses k-NN and returns the accuracy; 2 -applies preprocessing before k-NN and adds a few more things, before returning the accura...
Does the preprocessing of one algorithm change the conditions of the experiment?
As an example, We have two algorithms that utilize the same dataset and the same train and test data: 1 - uses k-NN and returns the accuracy; 2 -applies preprocessing before k-NN and adds a few more things, before returning the accuracy. Although the preprocessing "is a part of" algorithm number 2, I've been told that ...
[ "It depends what you are comparing.\n\nif you compare the two methods \"with preprocessing allowed\", then you don't include the preprocessing in the experiment; and in principle you should test several (identical) queries;\n\nif you compare \"with no preprocessing allowed\", then include everything in the measurem...
[ 1 ]
[]
[]
[ "algorithm", "comparison", "machine_learning", "python", "theory" ]
stackoverflow_0074656128_algorithm_comparison_machine_learning_python_theory.txt
Q: Pytest mock fastapi.Depends upon direct function call How can we mock the fastapi.Depends function in a pytest? It works if we access the function via starlette.testclient.TestClient (see 1st example below). It fails if we call the method directly (see 2nd example). We know that we can override the Depends with a...
Pytest mock fastapi.Depends upon direct function call
How can we mock the fastapi.Depends function in a pytest? It works if we access the function via starlette.testclient.TestClient (see 1st example below). It fails if we call the method directly (see 2nd example). We know that we can override the Depends with app.dependency_overrides[get_user] = ... but same here, work...
[ "I am not sure if this is the correct approach to handle this, but I had a similar issue when trying to test a deeply nested function that was using Depends and thus was not willing to use the override approach.\nMy \"mock\" was pretty simple, instead of trying to mock fastapi.Depends I just passed in my desired re...
[ 0 ]
[]
[]
[ "fastapi", "mocking", "pytest", "python" ]
stackoverflow_0074630659_fastapi_mocking_pytest_python.txt
Q: group rows based on partial strings from two columns and sum values df = pd.DataFrame({'c1':['Ax','Ay','Bx','By'], 'c2':['Ay','Ax','By','Bx'], 'c3':[1,2,3,4]}) c1 c2 c3 0 Ax Ay 1 1 Ay Ax 2 2 Bx By 3 3 By Bx 4 I'd like to sum the c3 values by aggregating the same xy combinations from the c1 a...
group rows based on partial strings from two columns and sum values
df = pd.DataFrame({'c1':['Ax','Ay','Bx','By'], 'c2':['Ay','Ax','By','Bx'], 'c3':[1,2,3,4]}) c1 c2 c3 0 Ax Ay 1 1 Ay Ax 2 2 Bx By 3 3 By Bx 4 I'd like to sum the c3 values by aggregating the same xy combinations from the c1 and c2 columns. The expected output is c1 c2 c3 0 x y 4 #[Ax Ay...
[ "You can select values in c1 and c2 without first letters and aggregate sum:\ndf = df.groupby([df.c1.str[1:], df.c2.str[1:]]).sum().reset_index()\nprint (df)\n c1 c2 c3\n0 x y 4\n1 y x 6\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074656475_pandas_python.txt
Q: Use config and wildcards in snakemake rule output I have a list of fasta may be used, but some of them may also not be used, so I hope to use snakemake to index fastq if need I bulit a yaml file like this # config.yaml reference_genome: fa1: "path/to/genome" fa2: "..." fa3: "..." ... and I write a snakemake li...
Use config and wildcards in snakemake rule output
I have a list of fasta may be used, but some of them may also not be used, so I hope to use snakemake to index fastq if need I bulit a yaml file like this # config.yaml reference_genome: fa1: "path/to/genome" fa2: "..." fa3: "..." ... and I write a snakemake like this configfile: "config.yaml" rule all: input: ...
[ "My guess is that you want:\nrule all:\n input:\n expand('{reference_genome}.{type}', reference_genome=['fa1', 'fa2', 'fa3'], type=['amb', 'ann', 'pac'])\n\nrule index: \n input: \n #reference_genomeFile\n ref_genome=lambda wildcards:config['reference_genome'][wildcards.reference_genome]\...
[ 1, 1 ]
[]
[]
[ "bioinformatics", "pipeline", "python", "snakemake", "wildcard" ]
stackoverflow_0074652332_bioinformatics_pipeline_python_snakemake_wildcard.txt
Q: How to parse a string of multiple jsons without separators in python? Given a single-lined string of multiple, arbitrary nested json-files without separators, like for example: contents = r'{"payload":{"device":{"serial":213}}}{"payload":{"device":{"serial":123}}}' How can contents be parsed into an array of dict...
How to parse a string of multiple jsons without separators in python?
Given a single-lined string of multiple, arbitrary nested json-files without separators, like for example: contents = r'{"payload":{"device":{"serial":213}}}{"payload":{"device":{"serial":123}}}' How can contents be parsed into an array of dicts/jsons ? I tried df = pd.read_json(contents, lines=True) But only got a V...
[ "You can split the string, then parse each JSON string into a dictionary:\nimport json\n\ncontents = r'{\"payload\":{\"device\":{\"serial\":213}}}{\"payload\":{\"device\":{\"serial\":123}}}'\n\njson_strings = contents.replace('}{', '}|{').split('|')\njson_dicts = [json.loads(string) for string in json_strings]\n\nO...
[ 1 ]
[]
[]
[ "amazon_web_services", "arrays", "json", "ndjson", "python" ]
stackoverflow_0074656450_amazon_web_services_arrays_json_ndjson_python.txt
Q: Calculate average temperature in reducer I am trying to write a code that would calculate average temperature (reducer.py) based on ncdc weather. 0057011060999991928010112004+67500+012067FM-12+001199999V0202001N012319999999N0500001N9+00281+99999102171ADDAY181999GF108991999999999999001001MD1710261+9999MW1801 006201...
Calculate average temperature in reducer
I am trying to write a code that would calculate average temperature (reducer.py) based on ncdc weather. 0057011060999991928010112004+67500+012067FM-12+001199999V0202001N012319999999N0500001N9+00281+99999102171ADDAY181999GF108991999999999999001001MD1710261+9999MW1801 0062011060999991928010206004+67500+012067FM-12+00119...
[ "First of all, your shown data has no tabs, so it's not clear why you've shown code that splits lines on tabs and finds the max. Not an average.\nTo find an average, you'll need to collect all seen values into a list (values.append(int(val))), then you can from statistics import mean and call mean(values) at the en...
[ 0 ]
[]
[]
[ "hadoop", "hadoop_streaming", "mapreduce", "python" ]
stackoverflow_0074651008_hadoop_hadoop_streaming_mapreduce_python.txt
Q: Display a list of values from an array on a grid drawn using pygame I'm trying to create a small program that will draw a 6 x 6 grid. I have an array of values (36 elements) which I want to display in each box. I'm able to draw the grid using the below code, however I'm not able to figure out how to display the te...
Display a list of values from an array on a grid drawn using pygame
I'm trying to create a small program that will draw a 6 x 6 grid. I have an array of values (36 elements) which I want to display in each box. I'm able to draw the grid using the below code, however I'm not able to figure out how to display the text from the array in each box. Later I want to check where the current se...
[ "def print_matrix(matrix):\n for i in range(len(matrix)):\n if i % 6 == 0 and i != 0:\n print('')\n print(matrix[i], end = ' ')\n print('')\n\nprint_matrix(matrix)\n\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074642010_pygame_python.txt
Q: Spherical Graph Layout in Python Objective Display a 3D Sphere graph structure based on input edges & nodes using VTK for visualisation. As for example shown in https://epfl-lts2.github.io/gspbox-html/doc/graphs/gsp_sphere.html Target: State of work Input data as given factor NetworkX for position calculation ...
Spherical Graph Layout in Python
Objective Display a 3D Sphere graph structure based on input edges & nodes using VTK for visualisation. As for example shown in https://epfl-lts2.github.io/gspbox-html/doc/graphs/gsp_sphere.html Target: State of work Input data as given factor NetworkX for position calculation Handover to VTK methods for 3D visuali...
[ "Have you tried the python lib version of the GSPBOX?\nIf yes, why it does not work for you?\nhttps://pygsp.readthedocs.io/en/stable/reference/graphs.html\n", "To display a 3D Sphere graph structure using VTK, you can use the vtkSphereSource class to generate the sphere geometry, and the vtkGraphLayoutView class ...
[ 0, 0 ]
[]
[]
[ "3d", "graph", "python" ]
stackoverflow_0074164603_3d_graph_python.txt
Q: How to set this code to open at specific times of the day? SO basically how do i do to set this to run at a specific time of the day ? import winsound from win10toast import ToastNotifier def timer (reminder,seconds): notificator=ToastNotifier() notificator=ToastNotifier("Reminder",f"""Alarm will go off i...
How to set this code to open at specific times of the day?
SO basically how do i do to set this to run at a specific time of the day ? import winsound from win10toast import ToastNotifier def timer (reminder,seconds): notificator=ToastNotifier() notificator=ToastNotifier("Reminder",f"""Alarm will go off in (seconds) Seconds.""",duration=20 notificator.show_toast(f...
[ "Two possibilities from the top of my head:\n\n[Linux] Use cron job https://help.ubuntu.com/community/CronHowto\n[Any OS] Use scheduler https://schedule.readthedocs.io/en/stable/\n[Windows] Scheduling a .py file on Task Scheduler in Windows 10\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074656493_python.txt
Q: Reverse complement from a file The task is: Write a script (call it what you want) that that can analyze a fastafile (MySequences.fasta) by finding the reverse complement of the sequences. Using python. from itertools import repeat #opening file filename = "MySequences.fasta" file = open(filename, 'r') #reading...
Reverse complement from a file
The task is: Write a script (call it what you want) that that can analyze a fastafile (MySequences.fasta) by finding the reverse complement of the sequences. Using python. from itertools import repeat #opening file filename = "MySequences.fasta" file = open(filename, 'r') #reading the file for line in file: lin...
[ "You run your function in the wrong place.\nTo run your function for each iterator, run the function there.\n#reading the file\n\nfor line in file:\n line = line.strip()\n if \">\" in line:\n header = line\n elif (len(line) == 0):\n continue\n else:\n seq = line\n #run functi...
[ 0 ]
[]
[]
[ "bioinformatics", "python" ]
stackoverflow_0074656373_bioinformatics_python.txt
Q: Using a square matrix with Networkx but keep getting Adjacency matrix not square So I'm using Networkx to plot a cooc matrix. It works well with small samples but I keep getting this error when I run it with a big cooc matrix (reason why I can't share a minimum reproductible example): Traceback (most recent call l...
Using a square matrix with Networkx but keep getting Adjacency matrix not square
So I'm using Networkx to plot a cooc matrix. It works well with small samples but I keep getting this error when I run it with a big cooc matrix (reason why I can't share a minimum reproductible example): Traceback (most recent call last): File "", line 113, in <module> G = nx.from_pandas_adjacency(matrix) File...
[ "So I was able to fix my problem by first converting my matrix into a stack.\ncooc_matrix = matrix(matrixLabel, texts)\nmatrix = pd.DataFrame(cooc_matrix.todense(), index=matrixLabel, columns=matrixLabel)\nprint(matrix)\n\n#This fixed my problem\nstw = matrix.stack()\nstw = stw[stw >= 1].rename_axis(('source', 'tar...
[ 2, 0 ]
[]
[]
[ "matrix", "networkx", "python" ]
stackoverflow_0069349516_matrix_networkx_python.txt
Q: What is the best way to verify an email address if it actually exist? Is there any way to verify an email whether the email actually exist or no in python? Or is thee any platform offering such services? For Example: I have some emails email1@google.com email2@gmail.com asdasd@adasd.com asdasdasdasdasd@gmail.com H...
What is the best way to verify an email address if it actually exist?
Is there any way to verify an email whether the email actually exist or no in python? Or is thee any platform offering such services? For Example: I have some emails email1@google.com email2@gmail.com asdasd@adasd.com asdasdasdasdasd@gmail.com How can I be 100% sure which of the following email really exist on the inte...
[ "There are several tutorials on the internet. Here's what I found...\n\n\nFirst you need to check for the correct formatting and for this you can use regular expressions like this:\n import re\n \n addressToVerify ='info@scottbrady91.com'\n match = re.match('^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0...
[ 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069412522_python.txt
Q: Flask - show all data form Mongodb in html template I am using MongoDB as a database. I want to show all my data in the HTML template python code: from flask import Flask, render_template, request, url_for from flask_pymongo import PyMongo import os app = Flask(__name__) app.config['MONGO_DBNAME'] = 'flask_assignm...
Flask - show all data form Mongodb in html template
I am using MongoDB as a database. I want to show all my data in the HTML template python code: from flask import Flask, render_template, request, url_for from flask_pymongo import PyMongo import os app = Flask(__name__) app.config['MONGO_DBNAME'] = 'flask_assignment' app.config['MONGO_URI'] = 'mongodb://username:passwo...
[ "Maybe the issue is that the emp_list is very large, and it takes a long time to insert it in the template, see the page won't be shown. \nYou can limit the data to for example 10 documents, using:\nemp_list = mongo.db.employee_entry.find().limit(10)\n\nand see if it solves the problem.\n", "OK, I'm sorry for tha...
[ 0, 0 ]
[]
[]
[ "flask", "mongodb", "python" ]
stackoverflow_0048941101_flask_mongodb_python.txt
Q: How to make Django render URL dispatcher from HTML in Pandas column, instead of forwarding raw HTML? I want to render a pandas dataframe in HTML, in which 1 column has URL dispatched links to other pages. If I try to render this HTML, it just keeps raw HTML, instead of converting the URLS: utils.py import pandas a...
How to make Django render URL dispatcher from HTML in Pandas column, instead of forwarding raw HTML?
I want to render a pandas dataframe in HTML, in which 1 column has URL dispatched links to other pages. If I try to render this HTML, it just keeps raw HTML, instead of converting the URLS: utils.py import pandas as pd df = pd.DataFrame(["2022-007", "2022-008", "2022-111", "2022-222", "2022-555", "2022-151"], columns=[...
[ "In your view, you cannot use {% url '' %}.\nTo resolve a URL dynamically in your utils.py, use build_absolute_uri instead. You can also combine this with reverse() like so (note: you will have to pass your request object):\nrequest.build_absolute_uri(reverse('columndetails', args=('2022-007', )))\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_urls", "html", "python", "url" ]
stackoverflow_0074656451_django_django_urls_html_python_url.txt
Q: Saving changes to a dataframe after editing in a GUI I wrote a code, that extracts data from a csv file and displays it in a GUI (when data is already present). No i need to find a way, that if I change or edit Data in the GUI, the value should be replaced in the csv file as well. This part here is for extracting ...
Saving changes to a dataframe after editing in a GUI
I wrote a code, that extracts data from a csv file and displays it in a GUI (when data is already present). No i need to find a way, that if I change or edit Data in the GUI, the value should be replaced in the csv file as well. This part here is for extracting the data form the file (which works great): ` def updatete...
[ "I don't know if I understand exactly what you need, but I think after the modifications you should use the to_csv() function to export the changes to the CSV file, and connect it for example with a Button click.\nIn case you can not find the file after saving, you should note that the to_csv() function usually sav...
[ 0 ]
[]
[]
[ "csv", "pyqt5", "python" ]
stackoverflow_0074654646_csv_pyqt5_python.txt
Q: Python compute object property in separate task to improve performace I wonder if it's possible to compute an object property in a separate background thread when it's initialized to speed up my computation. I have this example code: class Element: def __init__(self): self.__area = -1 # cache the area va...
Python compute object property in separate task to improve performace
I wonder if it's possible to compute an object property in a separate background thread when it's initialized to speed up my computation. I have this example code: class Element: def __init__(self): self.__area = -1 # cache the area value @property def area(self) if self.__area < 0: ...
[ "The problem with Python and parallel computing is that there is that thing called GIL (Global Interpreter Lock). The GIL prevents a process to run multiple threads at the same time. So for that to work you would need to spawn a new process which has quiet some overhead. Furthermore it is cumbersome to exchange dat...
[ 0 ]
[]
[]
[ "background_process", "parallel_processing", "python", "python_multithreading" ]
stackoverflow_0074656410_background_process_parallel_processing_python_python_multithreading.txt
Q: Hidden Friend in Python I'm trying to create a hidden friend for my company. In this logic, they will fill out a google forms form and, at the end of the week, I will download it to my computer as a csv file. the data collected are: Full name, email address and desired gift. The idea is to automate the draw and ea...
Hidden Friend in Python
I'm trying to create a hidden friend for my company. In this logic, they will fill out a google forms form and, at the end of the week, I will download it to my computer as a csv file. the data collected are: Full name, email address and desired gift. The idea is to automate the draw and each member will receive a secr...
[ "It would be very helpful if you could attach some sample records from the input .csv file (anonymized if possible).\nWithout that, have you tried shuffling the original list instead of using the permutations?\nimport glob\nimport random\nimport csv\n\nall_list = []\nfor glob in glob.glob(\"random_friend/csv/*\"):\...
[ 1 ]
[]
[]
[ "python", "python_itertools", "random" ]
stackoverflow_0074656583_python_python_itertools_random.txt
Q: How to mock a function which makes a mutation on an argument that is necessary for the caller fuction logic I want to be able to mock a function that mutates an argument, and that it's mutation is relevant in order for the code to continue executing correctly. Consider the following code: def mutate_my_dict(mutabl...
How to mock a function which makes a mutation on an argument that is necessary for the caller fuction logic
I want to be able to mock a function that mutates an argument, and that it's mutation is relevant in order for the code to continue executing correctly. Consider the following code: def mutate_my_dict(mutable_dict): if os.path.exists("a.txt"): mutable_dict["new_key"] = "new_value" return True def ...
[ "With the help of Peter i managed to come up with this final test:\ndef mock_mutate_my_dict(my_dict):\n my_dict[\"new_key\"] = \"new_value\"\n return True\n\n\ndef test_function_under_test():\n with patch(\"stack_over_flow.mutate_my_dict\") as mutate_my_dict_mock:\n mutate_my_dict_mock.side_effect =...
[ 0 ]
[]
[]
[ "pytest", "python", "python_3.x", "python_unittest.mock", "unit_testing" ]
stackoverflow_0074643203_pytest_python_python_3.x_python_unittest.mock_unit_testing.txt
Q: Display MongoDB Documents data on a Webpage using Python Flask I wrote a code using Python and trying to display all the Documents from Mongodb on a web page. However, on webpage I see the Column names, but no data. And on the command, it does print all the data. Any help is greatly appreciated. import pymongo fro...
Display MongoDB Documents data on a Webpage using Python Flask
I wrote a code using Python and trying to display all the Documents from Mongodb on a web page. However, on webpage I see the Column names, but no data. And on the command, it does print all the data. Any help is greatly appreciated. import pymongo from pymongo import MongoClient import datetime import sys from flask i...
[ "Removed the for loop and rewrote the code as below:\n@app.route('/')\ndef Results():\n try:\n Project_List_Col = db.ppm_master_db_collection.find()\n return render_template('Results.html',tasks=Project_List_Col)\n except Exception as e:\n return dumps({'error': str(e)})\n\nif __name__ ==...
[ 0, 0 ]
[]
[]
[ "flask", "mongodb", "python" ]
stackoverflow_0057637088_flask_mongodb_python.txt
Q: Python: Move files from multiple folders in different locations into one folder I am able to move all files from one folder to another. I need help in order to move files to destination folder from multiple source folders. import os import shutil source1 = "C:\\Users\\user\\OneDrive\\Desktop\\1\\" source2 = "C:\\...
Python: Move files from multiple folders in different locations into one folder
I am able to move all files from one folder to another. I need help in order to move files to destination folder from multiple source folders. import os import shutil source1 = "C:\\Users\\user\\OneDrive\\Desktop\\1\\" source2 = "C:\\Users\\user\\OneDrive\\Desktop\\2\\" destination = "C:\\Users\\user\\OneDrive\\Deskto...
[ "This is the line interpreter is complaining about, you cannot pass two directories to os.listdir function\nfiles = os.listdir(source1, source2)\n\nYou have to have a nested loop (or list comprehension) to do what you want so:\nimport os\nsources = [source1, source2, ..., sourceN]\nfiles_to_move = []\nfor source in...
[ 1 ]
[]
[]
[ "directory", "file", "python", "shutil" ]
stackoverflow_0074656592_directory_file_python_shutil.txt
Q: Evaluating a Multiline Code Block (after an `if`) Without Indentation Is it possible to make Python3 see an unindented code chunk as a code block? If so how? This is more of a curiousity of how Python works. Typically if you want to run a code chunk after an if statement you need to indent what comes below: if T...
Evaluating a Multiline Code Block (after an `if`) Without Indentation
Is it possible to make Python3 see an unindented code chunk as a code block? If so how? This is more of a curiousity of how Python works. Typically if you want to run a code chunk after an if statement you need to indent what comes below: if True: x = 'hello' print(x) ## hello Is there a way to use the if a...
[ "This code should work:\nif True:(\nx:='hello_x',\nprint('hello'),\nprint(x)\n)\n\n## hello\n## hello_x\n\nIn your case, you are using a tuple to break python's indentation logic, so you need to separate each element with a comma. And since you are in a tuple, you need to use the Walrus Operator := to assign a valu...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074656650_python_python_3.x.txt
Q: Pandas development environment: pytest does not see changes after building edited .pyx file Q: Why is pytest not seeing changes when I edit a .pyx file and build? What step am I missing? I'm using Visuals Studio Code with remote containers as described at the end of this page. If I add changes to pandas/_libs/tsli...
Pandas development environment: pytest does not see changes after building edited .pyx file
Q: Why is pytest not seeing changes when I edit a .pyx file and build? What step am I missing? I'm using Visuals Studio Code with remote containers as described at the end of this page. If I add changes to pandas/_libs/tslibs/offsets.pyx, and then run (pandas-dev) root@60017c489843:/workspaces/pandas# python setup.py b...
[ "I'm pretty sure you need to install once the extensions are built (otherwise where are the built extension and how python/pytest should know where to look?). This is how my workflow looked some time ago (not sure it still applies but should be close enough):\npython setup.py build_ext --inplace -j 4\npython -m pip...
[ 1 ]
[]
[]
[ "cython", "pandas", "pytest", "python", "visual_studio_code" ]
stackoverflow_0074656048_cython_pandas_pytest_python_visual_studio_code.txt
Q: Square Every Digit of a Number in Python? Square Every Digit of a Number in Python? if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. write a code but this not working. def sq(num): words = num.split() # split the text for word in words: # for each word in the line: pri...
Square Every Digit of a Number in Python?
Square Every Digit of a Number in Python? if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. write a code but this not working. def sq(num): words = num.split() # split the text for word in words: # for each word in the line: print(word**2) # print the word num = 9119 sq(num...
[ "We can use list to split every character of a string, also we can use \"end\" in \"print\" to indicate the deliminter in the print out.\ndef sq(num):\n words = list(str(num)) # split the text\n for word in words: # for each word in the line:\n print(int(word)**2, end=\"\") # print the word\n\nnum = 9...
[ 3, 2, 1, 0, 0 ]
[ "def square_digits(num):\n num = str(num)\n result = ''\n for i in num:\n result += str(int(i)**2)\n return int(result)\nvar = square_digits(123)\nprint(var)\n\n" ]
[ -1 ]
[ "numbers", "python", "python_3.x" ]
stackoverflow_0049604549_numbers_python_python_3.x.txt
Q: looping through a data frame Python I have this data frame where I sliced columns from the original data frame: Type 1 Attack Grass 62 Grass 82 Dragon 100 Fire 52 Rock 100 I want to create each Pokemon’s adjusted attack attribute against grass Pokemon based on ‘Type 1’...
looping through a data frame Python
I have this data frame where I sliced columns from the original data frame: Type 1 Attack Grass 62 Grass 82 Dragon 100 Fire 52 Rock 100 I want to create each Pokemon’s adjusted attack attribute against grass Pokemon based on ‘Type 1’ where; the attack attribute is doubled ...
[ "There is some issues with your code as @azro pointed in the comments and there is no need for a loop here. You can simply use numpy.select to create a multi-conditionnal column.\nHere is an example to give you the general logic :\ndf[\"Attack\"] = df[\"Attack\"].astype(int)\n \nconditions = [df[\"Type 1\"].eq(\...
[ 1, 1 ]
[]
[]
[ "dataframe", "loops", "pandas", "python" ]
stackoverflow_0074656291_dataframe_loops_pandas_python.txt
Q: yfinance Crypto symbol list I am using yfinance in python to get crypto symbol pair prices. It gives real time data via its yf.download(tickers=tickers, period=period, interval=interval) function in a very nice format. I am wondering is there any function in yfinance to pull out all the supported crypto-pairs with...
yfinance Crypto symbol list
I am using yfinance in python to get crypto symbol pair prices. It gives real time data via its yf.download(tickers=tickers, period=period, interval=interval) function in a very nice format. I am wondering is there any function in yfinance to pull out all the supported crypto-pairs without doing any webscraping on this...
[ "To my knowledge YahooFinance uses CoinMarketCap to retrive crypto market information.\nCoinMarketCap offers the API you request here: (not free)\nhttps://pro-api.coinmarketcap.com/v1/exchange/market-pairs/latest\nI suggest you transfer to the Binance API. It includes the endpoint GET /api/v1/exchangeInfo as docume...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "cryptocurrency", "python", "yfinance" ]
stackoverflow_0067146805_cryptocurrency_python_yfinance.txt
Q: what is the fastest way to insert data into snowflake db table I have multiple .csv.gz files (each greater than 10GB) that need to be parsed - multiple rows are read to create one row insertion. The approach I'm taking is as follows: read .csv.gz file save soon-to-be-inserted rows into a buffer if there is enough...
what is the fastest way to insert data into snowflake db table
I have multiple .csv.gz files (each greater than 10GB) that need to be parsed - multiple rows are read to create one row insertion. The approach I'm taking is as follows: read .csv.gz file save soon-to-be-inserted rows into a buffer if there is enough data in the buffer, perform multirow insertion to database table N...
[ "Here is an article describing a Python multithreaded approach to bulk loading into Snowflake Zero to Snowflake: Multi-Threaded Bulk Loading with Python. Also note to optimize the number of parallel operations for a load, Snowflake recommends data files roughly 100-250 MB (or larger) in size compressed.\n" ]
[ 0 ]
[]
[]
[ "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074649452_python_snowflake_cloud_data_platform.txt
Q: how to efficiently and correctly overlay pngs taking into account transparency? when i was trying to overlay one image over the other one image had a transparent rounded rectangle filling and the other was just a normal image it looked either like this ( just putting the yellow over the pink without taking into a...
how to efficiently and correctly overlay pngs taking into account transparency?
when i was trying to overlay one image over the other one image had a transparent rounded rectangle filling and the other was just a normal image it looked either like this ( just putting the yellow over the pink without taking into account the rounded corners at all) or like this (looks just like the rounded rectang...
[ "It looks like you are setting the whole image as a mask, this is why the rounded corners have no effect at all from your pink background. I myself was struggling a lot with this task aswell and ended up using pillow instead of OpenCV. I don't know if it is more performant, but I got it running.\nHere the code that...
[ 1 ]
[]
[]
[ "alpha_transparency", "opencv", "python" ]
stackoverflow_0074654663_alpha_transparency_opencv_python.txt
Q: Count nodes sharing row or column with at least one other node I have a grid of nodes (represented by ones). I would like to quickly and simply (in a way that is both readable and fast) count the number of nodes that share a column or row with another node. Here is my solution (can it be improved?): grid=[[0,0,0,0...
Count nodes sharing row or column with at least one other node
I have a grid of nodes (represented by ones). I would like to quickly and simply (in a way that is both readable and fast) count the number of nodes that share a column or row with another node. Here is my solution (can it be improved?): grid=[[0,0,0,0],[1,1,1,1],[0,0,0,1],[0,0,1,1],[0,0,0,1]] rowlen=len(grid) collen=l...
[ "Sometimes fast and readable are the same, but more often they depend on your input and wishes. For example, what you are doing is still considered fast for most people, less than a second for a grid of 2500x2500 or 6.250.000 entries.\nNow for your question it is noticable, that if you know the row and column count...
[ 1 ]
[]
[]
[ "hash", "list", "optimization", "python", "python_3.x" ]
stackoverflow_0074647766_hash_list_optimization_python_python_3.x.txt
Q: What is a "Usage Error: --settings |--slot-settings" in the azure function CLI when setting the config? I was able to create a function app successfully through the cli but when I go to publish/create the function code, I get the error in the title. I will say I'm following this documentation to create a blob trig...
What is a "Usage Error: --settings |--slot-settings" in the azure function CLI when setting the config?
I was able to create a function app successfully through the cli but when I go to publish/create the function code, I get the error in the title. I will say I'm following this documentation to create a blob trigger function with prefect so that's why I have the two more config settings in my code - https://discourse.pr...
[ "You're spot on, it looks like just a formatting issue. Can you remove any back quotes and make everything into a single line?\n" ]
[ 0 ]
[]
[]
[ "azure_functions", "prefect", "python" ]
stackoverflow_0074647958_azure_functions_prefect_python.txt
Q: Scatter plot - how to do it I would like to reproduce this plot in Python: (https://i.stack.imgur.com/6CRfn.png) Any idea how to do this? I tried to do a normal plt.scatter() but I can't draw this axes on the zero, for example. A: That's a very general question... Using plt.scatter() is certainly a good option. ...
Scatter plot - how to do it
I would like to reproduce this plot in Python: (https://i.stack.imgur.com/6CRfn.png) Any idea how to do this? I tried to do a normal plt.scatter() but I can't draw this axes on the zero, for example.
[ "That's a very general question... Using plt.scatter() is certainly a good option. Then just add the two lines to the plot (e.g. using axhline and axvline).\nSlightly adapting this example:\nimport numpy as np\nimport matplotlib.pyplot as plt\n# don't show right and top axis[![enter image description here][1]][1]\n...
[ 0 ]
[]
[]
[ "plot", "python", "scatter_plot" ]
stackoverflow_0074650089_plot_python_scatter_plot.txt
Q: Adding subscription address to chainlink vrf v2 inside of the contract So I'm writing this lottery smart contract which is pretty straight forward, and since I want to test this on the goerli test net, I want to be able to add the contract as a subscriber to my VRF every time it's deployed. // SPDX-License-Identi...
Adding subscription address to chainlink vrf v2 inside of the contract
So I'm writing this lottery smart contract which is pretty straight forward, and since I want to test this on the goerli test net, I want to be able to add the contract as a subscriber to my VRF every time it's deployed. // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "node_modules/@chainlink/contracts...
[ "Using \"subscriber\" and \"consumer\" synonymously in regards to the contract using the subscription. Also, VRF v2 Mock can be found at Chainlink GitHub\nYou can add the contract as a subscriber upon deployment in two ways:\n\nset the contract as a subscriber within the .py file you're using for deployment\ninitia...
[ 0 ]
[]
[]
[ "brownie", "chainlink", "python", "solidity" ]
stackoverflow_0073788538_brownie_chainlink_python_solidity.txt
Q: AttributeError: 'str' object has no attribute 'numpy' My command Windows 11 PowerShell. !pip install tensorflow-datasets pip install tensorflow-datasets # pip install tfds-nightly import tensorflow_datasets as tfds datasets = tfds.load("imdb_reviews") train_set = tfds.load("imdb_reviews") # 25.000 reviews. tes...
AttributeError: 'str' object has no attribute 'numpy'
My command Windows 11 PowerShell. !pip install tensorflow-datasets pip install tensorflow-datasets # pip install tfds-nightly import tensorflow_datasets as tfds datasets = tfds.load("imdb_reviews") train_set = tfds.load("imdb_reviews") # 25.000 reviews. test_set = datasets["test"] # 25.000 reviews. train...
[ "You are trying to run python directly within powershell. But the powershell-interpreter speaks only powershell and cannot natively interprete python code.\nYou have to put the python code in a python file, e.g. my_code.py and call/execute it with python my_code.py from within powershell. Now the python interpreter...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074642430_python.txt
Q: How to find the numbers in the thousands, hundreds, tens, and ones place in PYTHON for an input number? For example: 256 has 6 ones, 5 tens, etc num = int(input("Please give me a number: ")) print(num) thou = int((num // 1000)) print(thou) hun = int((num // 100)) print(hun) ten =int((num // 10)) print(ten) one = i...
How to find the numbers in the thousands, hundreds, tens, and ones place in PYTHON for an input number? For example: 256 has 6 ones, 5 tens, etc
num = int(input("Please give me a number: ")) print(num) thou = int((num // 1000)) print(thou) hun = int((num // 100)) print(hun) ten =int((num // 10)) print(ten) one = int((num // 1)) print(one) I tried this but it does not work and I'm stuck.
[ "You might want to try something like following:\ndef get_pos_nums(num):\n pos_nums = []\n while num != 0:\n pos_nums.append(num % 10)\n num = num // 10\n return pos_nums\n\nAnd call this method as following.\n>>> get_pos_nums(9876)\n[6, 7, 8, 9]\n\nThe 0th index will contain the units, 1st i...
[ 14, 6, 4, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "In Python, you can try this method to print any position of a number.\nFor example, if you want to print the 10 the position of a number,\nMultiply the number position by 10, it will be 100,\nTake modulo of the input by 100 and then divide it by 10.\nNote: If the position get increased then the number of zeros in ...
[ -1, -1 ]
[ "numbers", "operators", "python" ]
stackoverflow_0032752750_numbers_operators_python.txt
Q: Why does patch.contains_point() behave differently from patch.get_path().contains_point() when checking if points are within a polygon? With matplotlib.patches, the patch.contains_point(xy) method seems to work differently from patch.get_path().contains_point(xy), at least after having added the patch to the axes....
Why does patch.contains_point() behave differently from patch.get_path().contains_point() when checking if points are within a polygon?
With matplotlib.patches, the patch.contains_point(xy) method seems to work differently from patch.get_path().contains_point(xy), at least after having added the patch to the axes. See difference True/True and True/False below. I can't find any documentation on this difference. Does anybody know? I also have difficulty ...
[ "Although this question is old, I just faced the same issue and solved it.\nThe issue is after adding patch to the axes, you need to give the coordinates/points in display reference frame. This can be performed with:\nax.transData.transform()\n\nI added one line to your code ignoring import statements. So the code ...
[ 0 ]
[]
[]
[ "matplotlib", "patch", "path", "python" ]
stackoverflow_0064454891_matplotlib_patch_path_python.txt
Q: django.template.exceptions.TemplateSyntaxError: Invalid block tag. Did you forget to register or load this tag? I have a view that has context data and it extends base.html but as I want the context data to be displayed in all templates that extend from base.html and not only the view with the context data I am do...
django.template.exceptions.TemplateSyntaxError: Invalid block tag. Did you forget to register or load this tag?
I have a view that has context data and it extends base.html but as I want the context data to be displayed in all templates that extend from base.html and not only the view with the context data I am doing custom template tags with the context inside but I get an error. view with and without context data: class HomeVi...
[ "Simple thing, you should load the template tag in news.html template which is registered.\nJust load the tag in news.html template:\n{% load tag_name %} #Add here tag name to load\n\nNote: Please ensure that template tag setting is added in settings.py file\n", "You need to define the python code containing your...
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074654931_django_django_templates_python.txt
Q: Printing Numbers in X Shape pattern in python in increasing to decreasing order I am solving a pattern problem in python, i need to print a pattern in such a way it consists of X and the numbers are filled first in increasing order and then after reaching mid number, they go to decreasing order, basically i did w...
Printing Numbers in X Shape pattern in python in increasing to decreasing order
I am solving a pattern problem in python, i need to print a pattern in such a way it consists of X and the numbers are filled first in increasing order and then after reaching mid number, they go to decreasing order, basically i did what, i find out the area where the X will display.,and fill the remaining matrix with...
[ "You can print the min(rows, n - rows - 1) instead of rows -\nn = 5\nfor rows in range(n):\n for cols in range(n):\n if((rows == cols) or (rows+cols)==n-1 ):\n print(min(rows, n - rows - 1),end=\"\")\n else:\n print(\" \",end=\"\")\n print()\n\nOutput:\n0 0\n 1 1 \n 2 \n 1 1 \n0 0\n\nFor n =...
[ 0, 0 ]
[]
[]
[ "matrix", "python", "python_3.x" ]
stackoverflow_0074656745_matrix_python_python_3.x.txt
Q: How can you create a sort of geometric sequence using numpy arrays? def nthgeo_function(nth): pow(2,nth) #arithmetic sequence code #make a list of values for n as n1,n2,n3... done list_nth = list(range(1,1000)) nth_array = np.array(list_nth) nthgeo = arr(np.typecodes, (nthgeo_function(nth) for nth in nth_arra...
How can you create a sort of geometric sequence using numpy arrays?
def nthgeo_function(nth): pow(2,nth) #arithmetic sequence code #make a list of values for n as n1,n2,n3... done list_nth = list(range(1,1000)) nth_array = np.array(list_nth) nthgeo = arr(np.typecodes, (nthgeo_function(nth) for nth in nth_array)) def m_function(nthgeo): print(nthgeo%m) m_function(nthgeo) ...
[ "It's not very clear what you are trying to do. Your line '[I] am trying to get multiple outputs from multiple inputs accordingly' sounds like you want to take an array as input and then perform your function on every element.\nI am not exactly clear on what your function is, because it sounds like you want to calc...
[ 0 ]
[]
[]
[ "arrays", "numpy_ndarray", "python" ]
stackoverflow_0074656446_arrays_numpy_ndarray_python.txt
Q: Why does importing from random in python give me back unused import statement? When I type for ex: from random import shuffle I get: Unused import statement 'from random import shuffle' in return and the letter go grey. Can anybody diagnose? I tried "from random import shuffle" and was expecting to be able to use...
Why does importing from random in python give me back unused import statement?
When I type for ex: from random import shuffle I get: Unused import statement 'from random import shuffle' in return and the letter go grey. Can anybody diagnose? I tried "from random import shuffle" and was expecting to be able to use shuffle
[ "Without seeing the rest of the code I think that the error description is correct. Your import is unused. That means that you imported it but in the actual script the shuffle function was never accessed.\nTry using it in your code:\nfrom random import shuffle\n\nmy_shuffled_number = shuffle([1, 2, 3, 4, 5])\n\npri...
[ 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0074656901_import_python.txt
Q: Percona Xtrabackup 8.0 failed and showed error "xtrabackup: Error: unknown argument: '/var/lib/mysql/data'" I'm using Openstack Trove to create and manage backup mysql8 with Percona Xtrabackup 8.0. When trying to create a backup for a DB, I encounter this problem: Backup failed because of Xtrabackup has an unknown...
Percona Xtrabackup 8.0 failed and showed error "xtrabackup: Error: unknown argument: '/var/lib/mysql/data'"
I'm using Openstack Trove to create and manage backup mysql8 with Percona Xtrabackup 8.0. When trying to create a backup for a DB, I encounter this problem: Backup failed because of Xtrabackup has an unknown argument. Everything else looks fine to me, so I couldn't understand what wrong. Anyone had this issue or can s...
[ "xtrabackup is not entirely helpful showing what it did recognise, it would help if it also showed the entire command line as received (especially if it turns out it read a defaults file which means the problem could be entirely elsewhere).\nIn the meantime, you need to see exactly what trove/guestagent/strategies/...
[ 0 ]
[]
[]
[ "backup", "mysql", "percona", "python" ]
stackoverflow_0059572759_backup_mysql_percona_python.txt
Q: Append values to lists after raster sampling, in a loop I have multiple rasters in a specific directory from which I need to extract band1 values (chlorophyll concentration) using a CSV containg the coordinates of the points of interest. This is the CSV (read as GeoDataFrame): point_id point_name latitude...
Append values to lists after raster sampling, in a loop
I have multiple rasters in a specific directory from which I need to extract band1 values (chlorophyll concentration) using a CSV containg the coordinates of the points of interest. This is the CSV (read as GeoDataFrame): point_id point_name latitude longitude geometry 0 1 'Forte de...
[ "Try this,\ndata = [[10.2427, 43.5703, 0.63],\n [10.2427, 43.5703, 0.94],\n [10.2427, 43.5703, 0.76],\n [10.2427, 43.5703, 0.76],\n [10.2427, 43.5703, 1.03],\n [10.2427, 43.5703, 0.86],\n [10.2427, 43.5703, 0.74],\n [10.2427, 43.5703, 1.71],\n [10.2427, 43.5703, 3.07],\n [12.199, 41.708, 0.96],\n [12.199, 41.708, 0...
[ 0 ]
[]
[]
[ "dataframe", "list", "loops", "pandas", "python" ]
stackoverflow_0074656778_dataframe_list_loops_pandas_python.txt
Q: Python how do i get out of the while loop I want to go back and forth between these two variables, but it ends the session with break. Can you be my assistant? login = """ (1) # basic Python Learnig (2) # JavaScrpit (3) # SQL (4) # C++ (0) # Exit. """ print(login) python = """ (1) # -getting started python (2)...
Python how do i get out of the while loop
I want to go back and forth between these two variables, but it ends the session with break. Can you be my assistant? login = """ (1) # basic Python Learnig (2) # JavaScrpit (3) # SQL (4) # C++ (0) # Exit. """ print(login) python = """ (1) # -getting started python (2) # -python syntax (3) # -python comment lines (...
[ "You need a specific condition in which to put the \"break\". Here, at every iteration you are breaking.\nBy looking at the code, i think you have to indent break another time and put it under \"print(\"Bad VOTE\", name)\". So in the case of a bad vote, the loop brakes.\n" ]
[ 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074656883_python_while_loop.txt
Q: python not recognized in Windows CMD even after adding to PATH I'm trying to -learn to write and- run Python scripts on my Windows 7 64 bit machine. I installed Python in C:/Python34, and I added this to my Windows' PATH variable : C:\Python34; C:\Python34\python.exe (the second one is probably meaningless but I ...
python not recognized in Windows CMD even after adding to PATH
I'm trying to -learn to write and- run Python scripts on my Windows 7 64 bit machine. I installed Python in C:/Python34, and I added this to my Windows' PATH variable : C:\Python34; C:\Python34\python.exe (the second one is probably meaningless but I tried) and still I get this error in Windows command line : C:\User...
[ "This might be trivial, but have you tried closing your command line window and opening a new one? This is supposed to reload all the environment variables.\nTry typing\necho %PATH%\n\ninto the command prompt and see if you can find your Python directory there.\nAlso, the second part of your addition to the PATH en...
[ 24, 22, 8, 6, 4, 2, 1, 1, 1, 0, 0 ]
[ "For me, installing the 'Windows x86-64 executable installer' from the official python portal did the trick.\nPython interpreter was not initially recognized, while i had installed 32 bit python.\nUninstalled python 32 bit and installed 64 bit.\nSo, if you are on a x-64 processor, install 64bit python.\n", "I tri...
[ -1, -1, -1, -1, -2 ]
[ "cmd", "command_line", "python", "python_3.x", "windows" ]
stackoverflow_0024186823_cmd_command_line_python_python_3.x_windows.txt
Q: How to convert YOLO format annotations to x1, y1, x2, y2 coordinates in Python? I would like to know how to convert annotations in YOLO format (e.g., center_X, center_y, width, height = 0.069824, 0.123535, 0.104492, 0.120117) to x1, y1, x2, y2 coordinates? A: If I recall correctly: x1 = (center_X-width/2)*image_...
How to convert YOLO format annotations to x1, y1, x2, y2 coordinates in Python?
I would like to know how to convert annotations in YOLO format (e.g., center_X, center_y, width, height = 0.069824, 0.123535, 0.104492, 0.120117) to x1, y1, x2, y2 coordinates?
[ "If I recall correctly:\nx1 = (center_X-width/2)*image_width\nx2 = (center_X+width/2)*image_width\ny1 = (center_y-height/2)*image_height\ny2 = (center_y+height/2)*image_height\n\n", "Given that the upper-left corner of the image is [0,0]: For the upper-left corner you have to do [x,y] = [center_X, center_Y] - 1/2...
[ 2, 1, 0 ]
[]
[]
[ "computer_vision", "python", "yolo" ]
stackoverflow_0066801530_computer_vision_python_yolo.txt
Q: Windows 11 pycocotools package installation error error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe' failed with exit code 2 I have installed C++ build tools and more. Install Visual C++ 2015 Build Tools from https://go.microsoft.com/fwl...
Windows 11 pycocotools package installation error
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe' failed with exit code 2 I have installed C++ build tools and more. Install Visual C++ 2015 Build Tools from https://go.microsoft.com/fwlink/?LinkId=691126 with default selection. This cannot ...
[ "I assume you have already installed Visual C++ Latest Build Tools\nfrom Visual Studio 2022 Build Tools: https://aka.ms/vs/17/release/vs_buildtools.exe\nNow, Check the Pycocotools/PythonAPI folder and modify the setup.py file\nchange these couple of lines as the following code and run this command again\nPreviously...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074596492_python.txt
Q: How to pick a random item from an input list? I am making a program that asks how many players are playing, and then asks to input the names of those players. Then, I want it to print a random player, but I can't figure it out how. The code right now prints a random letter from the last name given, I think: import...
How to pick a random item from an input list?
I am making a program that asks how many players are playing, and then asks to input the names of those players. Then, I want it to print a random player, but I can't figure it out how. The code right now prints a random letter from the last name given, I think: import random player_numberCount = input("How many playe...
[ "You need to add each player name entered to a list. Here is a starting point of what you need in your code:\nfrom random import choice\n\nnumber_of_players = int(input(\"How many players are there: \"))\nplayers = []\n\nfor _ in range(number_of_players):\n players.append(input(\"name the players: \"))\n\nprint(...
[ 2, 0, 0, 0 ]
[]
[]
[ "input", "python" ]
stackoverflow_0074651157_input_python.txt
Q: AttributeError: type Object 'Widget' has no attribute '_ipython_display_' In one of my python test case I have mockcomm object and in the mockcomm function I am using ipywidgets. Recently Upgraded ipywidgets version from 7 to 8. The code is working fine in version 7 of ipywidgets but when upgraded I am facing the ...
AttributeError: type Object 'Widget' has no attribute '_ipython_display_'
In one of my python test case I have mockcomm object and in the mockcomm function I am using ipywidgets. Recently Upgraded ipywidgets version from 7 to 8. The code is working fine in version 7 of ipywidgets but when upgraded I am facing the below error. Saying Object has not attribute defined. did any one faced the err...
[ "According to this issue, from ipywidgets 8, widgets uses _repr_mimebundle_ instead of _ipython_display_.\nSo _widget_attrs['_ipython_display_'] will raise KeyError. Use _repr_mimebundle_ as key will sovle problem.\n" ]
[ 0 ]
[]
[]
[ "ipywidgets", "jupyter_notebook", "python" ]
stackoverflow_0073578290_ipywidgets_jupyter_notebook_python.txt
Q: User Login Authentication using Django Model and form I am trying to setup user authentication for the login page using forms and comparing it to my database value but it does not work. I also tried using this particular questions User Login Authentication using forms and Django logic to solve my problem but it di...
User Login Authentication using Django Model and form
I am trying to setup user authentication for the login page using forms and comparing it to my database value but it does not work. I also tried using this particular questions User Login Authentication using forms and Django logic to solve my problem but it didn't help. Models.py from django.db import models from djan...
[ "Stop reinventing the wheel. Also, class names are supposed to be named with PascalCase.\nUse AbstractUser model:\nfrom django.contrib.auth.models import AbstractUser\n\nclass Student(AbstractUser):\n ...\n\nand in your main urls.py:\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n .....
[ 0, 0 ]
[]
[]
[ "authentication", "django", "django_forms", "django_models", "python" ]
stackoverflow_0073978305_authentication_django_django_forms_django_models_python.txt
Q: CUDA_HOME environment variable is not set I have a working environment for using pytorch deep learning with gpu, and i ran into a problem when i tried using mmcv.ops.point_sample, which returned : ModuleNotFoundError: No module named 'mmcv._ext' I have read that you should actually use mmcv-full to solve it, but ...
CUDA_HOME environment variable is not set
I have a working environment for using pytorch deep learning with gpu, and i ran into a problem when i tried using mmcv.ops.point_sample, which returned : ModuleNotFoundError: No module named 'mmcv._ext' I have read that you should actually use mmcv-full to solve it, but i got another error when i tried to install it:...
[ "you can chek it and check the paths with these commands :\n\nwhich nvidia-smi\nwhich nvcc\ncat /usr/local/cuda/version.txt\n\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074656874_python_pytorch.txt
Q: Python JSON serialize a Decimal object I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, an...
Python JSON serialize a Decimal object
I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'...
[ "Simplejson 2.1 and higher has native support for Decimal type:\n>>> json.dumps(Decimal('3.9'), use_decimal=True)\n'3.9'\n\nNote that use_decimal is True by default:\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,\n allow_nan=True, cls=None, indent=None, separators=None,\n encoding='ut...
[ 265, 239, 178, 64, 57, 38, 28, 14, 14, 13, 11, 7, 4, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "decimal", "floating_point", "json", "python" ]
stackoverflow_0001960516_decimal_floating_point_json_python.txt
Q: File "/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) I read previous answers but couldnt fix this. whenever I run the code, this error pops up at different epochs, sometimes the executu=ion goes till 50s and then sudden...
File "/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
I read previous answers but couldnt fix this. whenever I run the code, this error pops up at different epochs, sometimes the executu=ion goes till 50s and then suddenly this error appears and the execution stops. at some other times this error appears at epoch 16s and so on. 0it [00:00, ?it/s]/usr/local/lib/python3.8/d...
[ "x_out has a single dimension after the squeeze operation (I assume, hard to say from your code). Try printing x_out.shape to check. In this case, the solution would be torch.cat(x_out,dim = 0).\nYou may save yourself some code comprehension headaches by not performing the squeeze operation until the end. For insta...
[ 0 ]
[]
[]
[ "machine_learning", "python", "pytorch" ]
stackoverflow_0074656868_machine_learning_python_pytorch.txt
Q: code running fine on computer and on pydroid 3 it doesnt so i have made a script that when my phone connects to my wifi network it automatically turn on my computer and i downloaded pydroid on another phone to run it non stop and it outputs : ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface] ...
code running fine on computer and on pydroid 3 it doesnt
so i have made a script that when my phone connects to my wifi network it automatically turn on my computer and i downloaded pydroid on another phone to run it non stop and it outputs : ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface] [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern]...
[ "Try omitting the -t from ping when running the script on your phone.\nping works differently on your phone. On windows you have to add -t for it to ping nonstop, on other operating systems that is the default behaviour.\n" ]
[ 0 ]
[]
[]
[ "pydroid", "python" ]
stackoverflow_0074633484_pydroid_python.txt
Q: Prepare json file for GPT I would like to create a dataset to use it for fine-tuning GPT3. As I read from the following site https://beta.openai.com/docs/guides/fine-tuning, the dataset should look like this {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"prompt": "<prompt text>", "completion...
Prepare json file for GPT
I would like to create a dataset to use it for fine-tuning GPT3. As I read from the following site https://beta.openai.com/docs/guides/fine-tuning, the dataset should look like this {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"...
[ "it's more like, writing \\n a new line character after each json. so each line is JSON. somehow the link jsonlines throw server not found error on me.\nyou can have these options:\n\nwrite \\n after each line:\n\nimport json\nwith open(\"sample2_op1.json\", \"w\") as outfile:\n for e_json in dictionary:\n ...
[ 1 ]
[]
[]
[ "gpt_3", "nlp", "python" ]
stackoverflow_0074656790_gpt_3_nlp_python.txt
Q: Data in Pandas becomes NaN when I add it to another data frame I am trying to pull Worldwide data from a data set and add the column to another dataframe using pandas, but the data becomes NaN everytime I run the code. The same code works for when I try to pull US data. Code: fb_us_data = us_data[us_data.app_id ==...
Data in Pandas becomes NaN when I add it to another data frame
I am trying to pull Worldwide data from a data set and add the column to another dataframe using pandas, but the data becomes NaN everytime I run the code. The same code works for when I try to pull US data. Code: fb_us_data = us_data[us_data.app_id == fb_key] fb_ww_data = ww_data[ww_data.app_id == fb_key] fb_intl_data...
[ "the problem here come from indexes try reseting index before adding like this:\nfb_us_data = us_data[us_data.app_id == fb_key].copy()\nfb_ww_data = ww_data[ww_data.app_id == fb_key].copy()\nfb_us_data.reset_index(drop=True, inplace=True)\nfb_ww_data.reset_index(drop=True, inplace=True)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "typeerror" ]
stackoverflow_0074656491_dataframe_pandas_python_typeerror.txt
Q: Can I bulk gecode addresses from local OSM tile server to get lat/long? I need to geocode a few million addresses within a single country. I know that paid geocode APIs charge for bulk geocoding and/or place limits for queries. I downloaded a map tile server to run within a docker but would like to know how to get...
Can I bulk gecode addresses from local OSM tile server to get lat/long?
I need to geocode a few million addresses within a single country. I know that paid geocode APIs charge for bulk geocoding and/or place limits for queries. I downloaded a map tile server to run within a docker but would like to know how to get address lat/long. I used https://github.com/Overv/openstreetmap-tile-server ...
[ "You did set up a local tile server, not a geocoder. To perform local bulk geocoding you need a local geocoding server. For an OSM-based geocoder take a look at Nominatim.\n" ]
[ 0 ]
[]
[]
[ "docker", "geocode", "local", "openstreetmap", "python" ]
stackoverflow_0074657183_docker_geocode_local_openstreetmap_python.txt
Q: Remove specific things from string in Python I am struggling to remove some characters in a string. This is inside a loop. So if the string contains either of the below, then it needs to remove them and leave the rest behind. Characters to remove: "-" "1)", "2)" etc Here is the loop: for i in item: if i != "":...
Remove specific things from string in Python
I am struggling to remove some characters in a string. This is inside a loop. So if the string contains either of the below, then it needs to remove them and leave the rest behind. Characters to remove: "-" "1)", "2)" etc Here is the loop: for i in item: if i != "": items[heading].append(i) I am just wonde...
[ "Try this!\nbl = [\"-\", \"1)\", \"2)\"]\nstring = \"-2)Hello1) World!\"\n\nfor item in bl:\n string = string.replace(item, \"\")\n\nprint(string)\n\n" ]
[ -1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074657193_python_string.txt
Q: I use Django with PostgreSQL on docker compose, but django-test can't access database I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_se...
I use Django with PostgreSQL on docker compose, but django-test can't access database
I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_service.conf and .pgpass. docker-compose.yml version: "3.9" services: web: build: ...
[ "Using a service name for testing purposes is not supported at the moment.\nI suspect this is why python manage.py test does not work.\nSee the ticket here https://code.djangoproject.com/ticket/33685\nIf that is the cause of your issue, python manage.py runserver should work.\nIf you need to use tests, try the old ...
[ 0 ]
[]
[]
[ "django", "docker", "postgresql", "python", "python_3.x" ]
stackoverflow_0072122960_django_docker_postgresql_python_python_3.x.txt
Q: I dont want means in my pivot table. I want both data I had a big dataframe with training data: for each day and person the kind of training, and some data points per training. I pivot the table with this code trainingload = trainingload.pivot_table(index=('Date', 'About'), columns='NHV Training', values=['Duratio...
I dont want means in my pivot table. I want both data
I had a big dataframe with training data: for each day and person the kind of training, and some data points per training. I pivot the table with this code trainingload = trainingload.pivot_table(index=('Date', 'About'), columns='NHV Training', values=['Duration', 'sRPE Cardio', 'sRPE Biomechanical']) It works fine for...
[ "One solution would be to not use the pivot_table function and instead use the pivot function, which allows you to specify the aggregation function. Instead of using the default mean function, you can use the function that simply concatenates the values together, such as the sum function.\nHere is an example:\ntrai...
[ 0 ]
[]
[]
[ "dataframe", "pivot", "python" ]
stackoverflow_0074657259_dataframe_pivot_python.txt
Q: Match case statement with multiple 'or' conditions in each case Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists. a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] Then I want to check whether x is in each list. Something like ...
Match case statement with multiple 'or' conditions in each case
Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists. a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] Then I want to check whether x is in each list. Something like that (of course this is a Syntax Error but I hope you get the point)....
[ "As it seems cases accept a \"guard\" clause starting with Python 3.10, which you can use for this purpose:\nmatch x:\n case w if w in a:\n # this was the \"case in a\" in the question\n case w if w in b:\n # this was the \"case in b\" in the question\n ...\n\nthe w here actually captures the value of x, p...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074655787_python_python_3.x.txt
Q: Performing arithmetic calculations on all possible digit combinations in a list I create data in a format like this: initial_data = [ "518-2", '533-3', '534-0', '000-3', '000-4'] I need to perform several operations (add, sub, div, mult, factorial, power_to, root) on the part before the hyphen to see if there's a...
Performing arithmetic calculations on all possible digit combinations in a list
I create data in a format like this: initial_data = [ "518-2", '533-3', '534-0', '000-3', '000-4'] I need to perform several operations (add, sub, div, mult, factorial, power_to, root) on the part before the hyphen to see if there's an equation which equals the part after the hyphen. Like so: #5182 -5 - 1 + 8 = 2 or 5...
[ "I think this will help you a lot (tweaks are on you) but it doesn't write in a CSV, I leave that for you to try, just take into account that there are thousands of possible combinations and in some cases, the results are really huge (see comments in main()).\nI've added missing types in function declarations for c...
[ 0 ]
[]
[]
[ "functools", "numpy", "python" ]
stackoverflow_0074648564_functools_numpy_python.txt
Q: How to change the palette-legend in seaborn pairplot I've just learned that I can change axis-label font-size using sns.set_context. Is there an analogous way to change the content and size of the text in the 'palette-legend' on the right? I'd like to enlarge the text and relabel the '0' and '1', which were used ...
How to change the palette-legend in seaborn pairplot
I've just learned that I can change axis-label font-size using sns.set_context. Is there an analogous way to change the content and size of the text in the 'palette-legend' on the right? I'd like to enlarge the text and relabel the '0' and '1', which were used for matrix manipulation, back to descriptive text.
[ "You can use set_title() and set_text() to set the names of the legend title & labels. Similarly, use plt.setp() to change the font to the size you need it to be... an example is shown below.\npenguins = sns.load_dataset(\"penguins\")\ng=sns.pairplot(penguins, hue=\"species\")\n\ng._legend.set_title(\"New Title\") ...
[ 0 ]
[]
[]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0074656704_matplotlib_python_seaborn.txt
Q: Code giving NameError: name 'x' is not defined I am new to Python, and I am trying to make a numerical analysis model of differential equations. import sympy as sympy def picard_solver(y_0, x_0, rhs_expression, iteration_count:int = 5): x, phi = sympy.symbols("x phi") phi = x_0 for i in rang...
Code giving NameError: name 'x' is not defined
I am new to Python, and I am trying to make a numerical analysis model of differential equations. import sympy as sympy def picard_solver(y_0, x_0, rhs_expression, iteration_count:int = 5): x, phi = sympy.symbols("x phi") phi = x_0 for i in range(iteration_count + 1): phi = y_0 + sympy.i...
[ "I think that you need to pass a string in the y.evalf(subs={'x': x_i}) part of your code.\n" ]
[ 1 ]
[]
[]
[ "nameerror", "python" ]
stackoverflow_0074656877_nameerror_python.txt
Q: Python, reduce list of string doesn't work with newline? I try to combine a list of string to string using reduce function but it doesn't work. I prefer to use reduce function anyway how do I fix this? >> reduce(lambda x, y: x + y + "\n", ["dog", "cat"]) # this doesn't work # dogcat >> "\n".join(["dog", "cat"]) # ...
Python, reduce list of string doesn't work with newline?
I try to combine a list of string to string using reduce function but it doesn't work. I prefer to use reduce function anyway how do I fix this? >> reduce(lambda x, y: x + y + "\n", ["dog", "cat"]) # this doesn't work # dogcat >> "\n".join(["dog", "cat"]) # this works # dog # cat
[ "The purpose of join, is to put the element between each\nreduce(lambda x, y: x + \"\\n\" + y, [\"dog\", \"cat\"])\n\n", "###################### METHOD 1 ######################\n\nstrings = [\"This\", \"is\", \"a\", \"list\", \"of\", \"strings\"]\n\n# join the strings using lambda\njoined = lambda strings: \"\\n\...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074657363_python.txt
Q: pandas to_html: add attributes to table tag I'm using the pandas to_html() method to build a table for my website. I want to add some attributes to the <table> tag; however I'm not sure how to do this. my_table = Markup(df.to_html(classes="table")) Which produces: <table border="1" class="dataframe table"> I wan...
pandas to_html: add attributes to table tag
I'm using the pandas to_html() method to build a table for my website. I want to add some attributes to the <table> tag; however I'm not sure how to do this. my_table = Markup(df.to_html(classes="table")) Which produces: <table border="1" class="dataframe table"> I want to produce the following: <table border="1" cla...
[ "This can be achieved simply by manipulating the rendered html with a simple regular expression:\nimport re\n\ndf = pd.DataFrame(1, index=[1, 2], columns=list('AB'))\n\nhtml = df.to_html(classes=\"table\")\nhtml = re.sub(\n r'<table([^>]*)>',\n r'<table\\1 attribute=\"value\" attribute2=\"value2\">',\n htm...
[ 6, 0 ]
[]
[]
[ "html", "pandas", "python" ]
stackoverflow_0043312995_html_pandas_python.txt
Q: Why does changing the kernel_initializer lead to NaN loss? I am running an advantage actor-critic (A2C) reinforcement learning model, but when I change the kernel_initializer, it gives me an error where my state has value. Moreover, it works only when kernel_initializer=tf.zeros_initializer(). I have changed the...
Why does changing the kernel_initializer lead to NaN loss?
I am running an advantage actor-critic (A2C) reinforcement learning model, but when I change the kernel_initializer, it gives me an error where my state has value. Moreover, it works only when kernel_initializer=tf.zeros_initializer(). I have changed the model to this code, and I'm facing a different problem: repeati...
[ "Using a kernel_initializer of tf.zeros_initializer() for your dense layers in the actor and critic networks can lead to the issue you are experiencing, where the loss becomes NaN and the model repeats the same action. This is because using a kernel_initializer of tf.zeros_initializer() initializes all of the weigh...
[ 0 ]
[]
[]
[ "actor_critics", "python", "random", "tensorflow" ]
stackoverflow_0074612124_actor_critics_python_random_tensorflow.txt
Q: Python unittests used in a project structure with multiple directories I need to use unittest python library to execute tests about the 3 functions in src/arithmetics.py file. Here is my project structure. . ├── src │   └── arithmetics.py └── test └── lcm ├── __init__.py ├── test_lcm_exception....
Python unittests used in a project structure with multiple directories
I need to use unittest python library to execute tests about the 3 functions in src/arithmetics.py file. Here is my project structure. . ├── src │   └── arithmetics.py └── test └── lcm ├── __init__.py ├── test_lcm_exception.py └── test_lcm.py src/arithmetics.py def lcm(p, q): p, q = abs...
[ "Some files init.py are missing\nI think that the problem is the missing of file __init__.py in your subfolders. Try to add this empty file in all your subfolders as I show you below:\ntest_lcm\n├── __init__.py\n├── src\n| └── __init__py\n│ └── arithmetics.py\n└── test\n └── __init__py\n └── lcm\n ...
[ 1 ]
[]
[]
[ "python", "python_3.x", "python_unittest", "unit_testing" ]
stackoverflow_0074655669_python_python_3.x_python_unittest_unit_testing.txt
Q: Issue when reading csv file from url using pandas.read_csv I am trying to import a csv file from the following url "https://www.marketwatch.com/games/stackoverflowq/download?view=holdings&pub=4JwsLs_Gm4kj&isDownload=true" using the pandas read_csv function. However, I get the following error: StopIteration: The...
Issue when reading csv file from url using pandas.read_csv
I am trying to import a csv file from the following url "https://www.marketwatch.com/games/stackoverflowq/download?view=holdings&pub=4JwsLs_Gm4kj&isDownload=true" using the pandas read_csv function. However, I get the following error: StopIteration: The above exception was the direct cause of the following exception...
[ "The issue was indeed that the data could only be accessed after logging in.\nI have managed to resolve it using Selenium and this answer.\nfrom io import StringIO \nimport pandas as pd\nimport requests\nfrom selenium import webdriver\n\n#start requests session with login from selenium driver\ns = requests.Session(...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074605550_csv_pandas_python.txt
Q: discord.py how to make a command have a cooldown? want to have this command on cooldown for 30 seconds @client.command() @commands.cooldown(1,30,commands.BucketType.user) if message.content.startswith('!sg hunt') await message.channel.send('You hunted a...') @work.error async def work_error(ctx, erro...
discord.py how to make a command have a cooldown?
want to have this command on cooldown for 30 seconds @client.command() @commands.cooldown(1,30,commands.BucketType.user) if message.content.startswith('!sg hunt') await message.channel.send('You hunted a...') @work.error async def work_error(ctx, error): if isinstance(error, commands.CommandOnCooldown...
[ "Weidong Zhu Robot!\nYou probably forgot to make function definition. Also @client.command() returns context, not message, so don't forget about this too.\nThere's your quick fix\n@client.command()\n@commands.cooldown(1,30,commands.BucketType.user)\nasync def hunt_cmd(ctx):\n message = ctx.message\n if messag...
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074579743_bots_discord_discord.py_python.txt
Q: Open and close new tab with Selenium WebDriver in OS X I'm using the Firefox Webdriver in Python 2.7 on Windows to simulate opening (Ctrl+t) and closing (Ctrl + w) a new tab. Here's my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get(...
Open and close new tab with Selenium WebDriver in OS X
I'm using the Firefox Webdriver in Python 2.7 on Windows to simulate opening (Ctrl+t) and closing (Ctrl + w) a new tab. Here's my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('https://www.google.com') main_window = browser.current_wind...
[ "There's nothing easier and clearer than just running JavaScript.\nOpen new tab:\ndriver.execute_script(\"window.open('');\")\n", "open a new tab:\nbrowser.get('http://www.google.com')\n\nclose a tab:\nbrowser.close()\n\nswitch to a tab:\nbrowser.swith_to_window(window_name)\n\n", "You can choose which window y...
[ 14, 12, 11, 6, 2, 0 ]
[]
[]
[ "macos", "python", "selenium" ]
stackoverflow_0025951968_macos_python_selenium.txt
Q: Min and max values of an array in Python I want to calculate the minimum and maximum values of array A but I want to exclude all values less than 1e-12. I present the current and expected outputs. import numpy as np A=np.array([[9.49108487e-05], [1.05634586e-19], [5.68676707e-17], [1.02453254e...
Min and max values of an array in Python
I want to calculate the minimum and maximum values of array A but I want to exclude all values less than 1e-12. I present the current and expected outputs. import numpy as np A=np.array([[9.49108487e-05], [1.05634586e-19], [5.68676707e-17], [1.02453254e-06], [2.48792902e-16], [1.02453...
[ "Slice with boolean indexing before getting the min/max:\nB = A[A>1e-12]\nMin = np.min(B)\nMax = np.max(B)\nprint(Min, Max)\n\nOutput: 1.02453254e-06 9.49108487e-05\nB: array([9.49108487e-05, 1.02453254e-06, 1.02453254e-06])\n", "You can just select the values of the array greater than 1e-12 first and obtain the ...
[ 3, 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074657268_numpy_python.txt
Q: I keep getting name 'message' not defined in python even though I made it a global variable in the function and I'm calling it Code(python): import tkinter as tk root = tk.Tk() root.geometry("600x400") message_var2 = tk.StringVar() def page2(message): print(f'test\n{message}') def getInputtemp(): global ...
I keep getting name 'message' not defined in python even though I made it a global variable in the function and I'm calling it
Code(python): import tkinter as tk root = tk.Tk() root.geometry("600x400") message_var2 = tk.StringVar() def page2(message): print(f'test\n{message}') def getInputtemp(): global message message = message_var2.get() message_var2.set("") message_entryi = tk.Entry(root, textvariable=message_var2, fon...
[ "The issue you have here is that your function getInputtemp is not getting fired. It only gets fired when button save_btn2 is clicked. Also, the if statement where the error is occuring will only get fired once. To fix this, you can either do what @Tkirishima have suggested.\nOr just move the if statement inside th...
[ 2, 1 ]
[]
[]
[ "function", "global_variables", "python", "tkinter", "variables" ]
stackoverflow_0074657402_function_global_variables_python_tkinter_variables.txt
Q: Idiomatic way to drop Pandas DataFrame column in an idempotent fashion (without settings errors="ignore") Is there a more Pythonic or Pandas-idiomatic way to drop a DataFrame column without just setting errors="ignore"? Suppose I have the following DataFrame: import pandas as pd from pandas import DataFrame df_in...
Idiomatic way to drop Pandas DataFrame column in an idempotent fashion (without settings errors="ignore")
Is there a more Pythonic or Pandas-idiomatic way to drop a DataFrame column without just setting errors="ignore"? Suppose I have the following DataFrame: import pandas as pd from pandas import DataFrame df_initial: DataFrame = pd.DataFrame([ { "country": "DE", "price": 1, "quantity": 10 ...
[ "If you're trying to avoid the overhead of creating an additional function, I'd say that list comprehensions are a Pythonic way of achieving what you need.\nAn approach like this would be idempotent, and elegant enough:\ndf[[col for col in df.columns if col != 'country']]\n\nThe upside with this method is that it's...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074655572_dataframe_pandas_python.txt
Q: Python AND operator on two boolean lists - how? I have two boolean lists, e.g., x=[True,True,False,False] y=[True,False,True,False] I want to AND these lists together, with the expected output: xy=[True,False,False,False] I thought that expression x and y would work, but came to discover that it does not: in fac...
Python AND operator on two boolean lists - how?
I have two boolean lists, e.g., x=[True,True,False,False] y=[True,False,True,False] I want to AND these lists together, with the expected output: xy=[True,False,False,False] I thought that expression x and y would work, but came to discover that it does not: in fact, (x and y) != (y and x) Output of x and y: [True,Fa...
[ "and simply returns either the first or the second operand, based on their truth value. If the first operand is considered false, it is returned, otherwise the other operand is returned.\nLists are considered true when not empty, so both lists are considered true. Their contents don't play a role here.\nBecause bot...
[ 75, 20, 12, 7, 4, 2, 1, 0, 0, 0 ]
[ "The following works for me:\n([True,False,True]) and ([False,False,True])\n\noutput:\n[False, False, True]\n\n" ]
[ -1 ]
[ "boolean", "list", "operator_keyword", "python" ]
stackoverflow_0032192163_boolean_list_operator_keyword_python.txt
Q: how to get index of a giving string in liste python? my list is like this, in example the string is 'a' and 'b' ; i want to return the index of string 'a' and for 'b' then i want to calculate how many time is 'a' repeated in the list1 : list1=['a','a','b','a','a','b','a','a','b','a','b','a','a'] i want to return t...
how to get index of a giving string in liste python?
my list is like this, in example the string is 'a' and 'b' ; i want to return the index of string 'a' and for 'b' then i want to calculate how many time is 'a' repeated in the list1 : list1=['a','a','b','a','a','b','a','a','b','a','b','a','a'] i want to return the order of evry 'a' in list1 the result should be like th...
[ "You could do below:\na_positions = [idx + 1 for idx, el in enumerate(list1) if el == 'a']\na_repitition = len(a_positions)\n\nprint(a_positions):\n[1, 2, 4, 5, 7, 8, 10, 12, 13]\n\nprint(a_repitition):\n9\n\nIf you need repititions of each element you can also use collections.Counter\nfrom collections import Count...
[ 2, 1 ]
[]
[]
[ "indexing", "python" ]
stackoverflow_0074657346_indexing_python.txt
Q: Concatenate all 2 dimensional values in a dictionary. (Output is Torch tensor) I want to concatenate all 2 dimensional values in a dictionary. The number of rows of these values is always the same. D = {'a': [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'b': [[1, 1], [1...
Concatenate all 2 dimensional values in a dictionary. (Output is Torch tensor)
I want to concatenate all 2 dimensional values in a dictionary. The number of rows of these values is always the same. D = {'a': [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'b': [[1, 1], [1, 1], [1, 1]], 'c': [[2, 2, 2, 2], [2, 2, 2, 2], ...
[ "import torch\nprint(torch.cat(tuple([torch.tensor(D[name]) for name in D.keys()]), dim=1))\n\nOutput:\ntensor([[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],\n [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],\n [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]])\n\n", "from itertools import chain \nl = []\nfor i in range(len(D)):\n t...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "torch" ]
stackoverflow_0074656455_dictionary_python_torch.txt
Q: Jenkins groovy pipeline using try catch and variable from python exit I have a pipeline on jenkins that inside a stage it uses the try-catch framework to try to run a python script. once run, the python script either prints a good value or prints a bad value and exits, depending on the input. My goal is to later u...
Jenkins groovy pipeline using try catch and variable from python exit
I have a pipeline on jenkins that inside a stage it uses the try-catch framework to try to run a python script. once run, the python script either prints a good value or prints a bad value and exits, depending on the input. My goal is to later use this to make a test, so my requirement is that I need to be able to dife...
[ "This is the expected behavior I suppose. When the script exits with a non-zero exit code the StandardOut will not be returned. If you want to get the output irrespective of the status you can do something like this. The following will combine both STDOUT and STDERR and return while exiting the script with exit cod...
[ 0 ]
[]
[]
[ "groovy", "jenkins", "jenkins_pipeline", "python", "try_catch" ]
stackoverflow_0074651092_groovy_jenkins_jenkins_pipeline_python_try_catch.txt
Q: Can you set a condition for start and end dates in a month period? If a have a dataframe from which I get the total ocurrence of a value per year-month period, is there a way to change the month's start and end date? For example, let's take this: import pandas as pd data= { 'date': [ '2022-01-10',...
Can you set a condition for start and end dates in a month period?
If a have a dataframe from which I get the total ocurrence of a value per year-month period, is there a way to change the month's start and end date? For example, let's take this: import pandas as pd data= { 'date': [ '2022-01-10', '2022-01-24', '2022-02-08', '2022-02-23', '2022-03-10', '2022-03...
[ "An alternative approach is to make a dictionary or dataframe in a format like CustomMonth | StartMonth | StartDay | EndMonth | EndDay\nwith one row for each of your custom months\nFrom there you can query your data using this\n", "As an option, I can offer if there is data for each month. Let's transform the 'pe...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074646435_pandas_python.txt
Q: Pyspark: cast element array with nested struct I have pyspark dataframe with a column named received: "" how to access and convert the "size" element that is as a string into a float usando pyspark? root |-- title: string (nullable = true...
Pyspark: cast element array with nested struct
I have pyspark dataframe with a column named received: "" how to access and convert the "size" element that is as a string into a float usando pyspark? root |-- title: string (nullable = true) |-- received: array (nullable = true) | |-- e...
[ "I managed to solve it like this:\ndf = df.withColumn(\n \"received\",\n SF.expr(\"\"\"transform(\n received, \n x -> struct(x.col1, x.col2, x.col3, x.col4, float(x.delay) as delay, x.col6))\"\"\"\n )\n )\n\n" ]
[ 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074647610_pyspark_python.txt
Q: Import sklearn doesn’t exist on my replit For some odd reason when I do “import sklearn” it says ModuleNotFound or something like that. Can anyone please help? I tried going online and using bash to fix it but still didn’t work. A: open a shell in the workspace with ctrl-shift-s on mac command-shift-s command p...
Import sklearn doesn’t exist on my replit
For some odd reason when I do “import sklearn” it says ModuleNotFound or something like that. Can anyone please help? I tried going online and using bash to fix it but still didn’t work.
[ "open a shell in the workspace with ctrl-shift-s\non mac command-shift-s command prompt and run this command, it will install scikit\n\npip install scikit-learn\n\n" ]
[ 0 ]
[]
[]
[ "python", "replit", "replit_database" ]
stackoverflow_0074657703_python_replit_replit_database.txt
Q: How to check if two pandas dataframes have same values and concatenate those rows? I got a DF called "df" with 4 numerical columns [frame,id,x,y] I made a loop that creates two dataframes called df1 and df2. Both df1 and df2 are subseted of the original dataframe. What I want to do (and I am not understanding how ...
How to check if two pandas dataframes have same values and concatenate those rows?
I got a DF called "df" with 4 numerical columns [frame,id,x,y] I made a loop that creates two dataframes called df1 and df2. Both df1 and df2 are subseted of the original dataframe. What I want to do (and I am not understanding how to do it) is this: I want to CHECK if df1 and df2 have same VALUES in the column called ...
[ "df3 = pd.concat([df1, df2[df2.id.isin(df1.id)]], axis = 0)\n" ]
[ 0 ]
[]
[]
[ "loops", "pandas", "python" ]
stackoverflow_0074657688_loops_pandas_python.txt
Q: How to add dynamic arguments in slash commands [discord.py] The Question I'm trying to make a command that shows you the schedule of your class, for that, the user first introduces as an argument its degree and then the class, but every degree has a different number of classes, so I can't show a generic list for a...
How to add dynamic arguments in slash commands [discord.py]
The Question I'm trying to make a command that shows you the schedule of your class, for that, the user first introduces as an argument its degree and then the class, but every degree has a different number of classes, so I can't show a generic list for all the degrees. The actual code: class Ciclos(enum.Enum): ASI...
[ "Sry, I don't think dynamic choises are build into the discord api, but I usually use the following to add choises to a Slash command, maybee it can help you.\n@app_commands.choices(\nciclo=[\n app_commands.Choice(name=\"ASIX\", value=\"ASIX\"),\n app_commands.Choice(name=\"DAM\", value=\"DAM\")\n ],\nclas...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074647782_discord_discord.py_python.txt
Q: Deleting from file in python. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect Trying to delete a line from my file in python, and its throwing me this error. I have a student database, I want to delete a student/line that has the corresponding student id. E.g., line = 'San...
Deleting from file in python. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
Trying to delete a line from my file in python, and its throwing me this error. I have a student database, I want to delete a student/line that has the corresponding student id. E.g., line = 'SanVin22\tSanji\tVinsmoke\tWellington'. id is the inputted id. def DelStudent(self, data): self = id with open(dat...
[ "If the idea is to delete the line with the given id, then gather up all of the non-matching lines (i.e. those that we want to keep) and then write them back to the original file.\ndef DelStudent(self, data):\n new_lines = []\n with open(data, \"r+\") as datafile:\n for line in datafile:\n d...
[ 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074657721_file_python.txt
Q: Interaction followup only seems to send one embed I'm having issues sending multiple embeds in one response and I'm not entirely sure if it's my fault (mostly likely) or a bug with discord.py. I have a list of embeds I'm trying to follow up on an initial deferral. However, my bot only seems to ever send one embed,...
Interaction followup only seems to send one embed
I'm having issues sending multiple embeds in one response and I'm not entirely sure if it's my fault (mostly likely) or a bug with discord.py. I have a list of embeds I'm trying to follow up on an initial deferral. However, my bot only seems to ever send one embed, rather than sending the full list. The full code is he...
[ "Now resolved thanks to the owner of discord.py\n" ]
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074524899_bots_discord_discord.py_python.txt
Q: Convert multiple same Rows as Column headers This is my table: pivot_notNone = pivot[pivot['GHG'].notna()] pivot_notNone.head(10) UOM GHG Conversion Factor 2022 Unit GHG 1 tonnes 3029.260000 kg CO2 2 tonnes 2.250000 kg CH4 3 tonnes 1.800000 kg N2O 5 litres 1.742960 kg CO2 6 litres 0.001290 kg CH4 ... ... .....
Convert multiple same Rows as Column headers
This is my table: pivot_notNone = pivot[pivot['GHG'].notna()] pivot_notNone.head(10) UOM GHG Conversion Factor 2022 Unit GHG 1 tonnes 3029.260000 kg CO2 2 tonnes 2.250000 kg CH4 3 tonnes 1.800000 kg N2O 5 litres 1.742960 kg CO2 6 litres 0.001290 kg CH4 ... ... ... ... ... 8032 tonnes 105.669500 kg...
[ "Well, if we assume that your starting data has sort of groups of 3 rows of related data, we can maybe get away with adding a new grouping field to group them, and then we can pivot using that as well.\ndf['new_grouping_field'] = df.index // 3 # this gives the whole-number piece of the division,\n# so rows 0-2 will...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074638617_pandas_python.txt
Q: Write "null" if column doesn't exist with KeyError: "['Column'] not in index" in df.to_csv? I am getting KeyError: "['CashFinancial'] not in index" on the df.to_csv line because 'GOOG' doesn't have the CashFinancial column. How can I have it write in null for the CashFinancial value for 'GOOG'? import pandas as p...
Write "null" if column doesn't exist with KeyError: "['Column'] not in index" in df.to_csv?
I am getting KeyError: "['CashFinancial'] not in index" on the df.to_csv line because 'GOOG' doesn't have the CashFinancial column. How can I have it write in null for the CashFinancial value for 'GOOG'? import pandas as pd from yahooquery import Ticker symbols = ['AAPL','GOOG','MSFT'] #This will be 75,000 symbols. he...
[ "What about :\nif tick == \"GOOG\"\n df.loc[:,\"CashFinancial\"] = None\n\nTo set an entire CashFinancial column to \"None\" only if your \"tick\" was GOOG, before writing it to csv.\nThe full code from the example you posted would he something like :\nimport pandas as pd\nfrom yahooquery import Ticker\nsymbols ...
[ 1, 1 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074657789_csv_dataframe_pandas_python.txt
Q: Fatal Python error on Windows 10 when I try to access Python from command prompt I did everything from these answers on a previous thread and nothing changed. Even uninstalling Python did not improve the situation. Everything was working fine but all of a sudden it stopped working. Could not find platform inde...
Fatal Python error on Windows 10 when I try to access Python from command prompt
I did everything from these answers on a previous thread and nothing changed. Even uninstalling Python did not improve the situation. Everything was working fine but all of a sudden it stopped working. Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> C...
[ "I've just had the same problem.\nLooking back, the error is fairly clear: ModuleNotFoundError: No module named 'encodings' means Python is not able to find the encodings module, one of Python built-in modules. I had a look at my filesystem and found out that the encodings module is found at C:\\msys64\\mingw64\\li...
[ 0 ]
[]
[]
[ "msys", "python", "python_3.x", "windows" ]
stackoverflow_0071831380_msys_python_python_3.x_windows.txt