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 last output also varies in this block of python code? I can understand first output of first example, that is 2 as the i += 1 makes value to 2 than print calls, I also understand the second example's first output that is 1 because print calls i then increment begins. But, what about the end, as we have already...
why last output also varies in this block of python code?
I can understand first output of first example, that is 2 as the i += 1 makes value to 2 than print calls, I also understand the second example's first output that is 1 because print calls i then increment begins. But, what about the end, as we have already defined "while i < 6:" then why first example returns last out...
[ "The while condition is only checked before each iteration, not after every statement inside the loop body. So on the last iteration, i == 5 and the condition i < 6 succeeds. It goes into the loop body, increments i to 6, and then prints that value.\n", "i = 1\nwhile i < 6:# initially i value is 1.\n i += 1 # ...
[ 1, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074279870_python_while_loop.txt
Q: How to capture C++ operators and separators in regular expression? I am working on a project at university that attempts to create a JIT compiler in Python in C++. I am at the tokenisation step, and I managed to extract all strings and comments from the code. What I need is to divide the code into a flow of lexeme...
How to capture C++ operators and separators in regular expression?
I am working on a project at university that attempts to create a JIT compiler in Python in C++. I am at the tokenisation step, and I managed to extract all strings and comments from the code. What I need is to divide the code into a flow of lexemes divided by Python operators (+, -, /, etc.) and separators (commas, se...
[ "You need to escape the (, ), [, and the ]s that you want to match. This site should help you:\nhttps://regex101.com/\n" ]
[ 0 ]
[]
[]
[ "c++", "python", "regex", "split", "token" ]
stackoverflow_0074279837_c++_python_regex_split_token.txt
Q: name 'crs_matrix' is not defined Try to create new train matrix X_train_sparse_new = crs_matrix(hstack((X_train_sparse, new_feat_train['year_month_scaled'].values.reshape(-1,1)))) but get error name 'crs_matrix' is not defined. Anyway, I have imported it: from scipy.sparse import csr_matrix, hstack and want to r...
name 'crs_matrix' is not defined
Try to create new train matrix X_train_sparse_new = crs_matrix(hstack((X_train_sparse, new_feat_train['year_month_scaled'].values.reshape(-1,1)))) but get error name 'crs_matrix' is not defined. Anyway, I have imported it: from scipy.sparse import csr_matrix, hstack and want to ran my own class: def get_auc_lr_valid(...
[ "it's just because of a small spelling mistake in,\nX_train_sparse_new = crs_matrix(hstack((X_train_sparse, new_feat_train['year_month_scaled'].values.reshape(-1,1))))\n\nswap r and s in crs_matrix.\nCorrect code is\nX_train_sparse_new = csr_matrix(hstack((X_train_sparse, new_feat_train['year_month_scaled'].values....
[ 0 ]
[]
[]
[ "logistic_regression", "python" ]
stackoverflow_0074279648_logistic_regression_python.txt
Q: Python concurrency with concurrent.futures.ThreadPoolExecutor Consider the following snippet: import concurrent.futures import time from random import random class Test(object): def __init__(self): self.my_set = set() def worker(self, name): temp_set = set() temp_set.add(name) ...
Python concurrency with concurrent.futures.ThreadPoolExecutor
Consider the following snippet: import concurrent.futures import time from random import random class Test(object): def __init__(self): self.my_set = set() def worker(self, name): temp_set = set() temp_set.add(name) temp_set.add(name*10) time.sleep(random() * 5) ...
[ "Regarding question 1: Think about what's going on here:\nself.my_set = self.my_set.union(temp_set)\n\nThere's a sequence of at least three distinct steps\n\nThe worker call grabs a copy of self.my_set (a reference to Set object)\nThe union function constructs a new set.\nThe worker assigns self.my_set to refer to ...
[ 1 ]
[]
[]
[ "concurrency", "multithreading", "python", "thread_safety" ]
stackoverflow_0074278037_concurrency_multithreading_python_thread_safety.txt
Q: CSV Wildcard within string I am using a CSV file to read in terms that I am looking for in a text file. I would like to use a wildcard or 'Like' as a term. I am not looking for wildcard for text document name but for the terms I'm searching for found in the CSV file. For example: Terms in CSV file to search in Tex...
CSV Wildcard within string
I am using a CSV file to read in terms that I am looking for in a text file. I would like to use a wildcard or 'Like' as a term. I am not looking for wildcard for text document name but for the terms I'm searching for found in the CSV file. For example: Terms in CSV file to search in Text File, each term is in it's own...
[ "In your particular case (test, tests, testing), simple in operator might be sufficient, e.g.:\n\"test\" in line will evaluate to True for all three words and if \"test\" in line: would do the work.\nIn more complex cases, you might want to use regular expressions.\n", "In order to simplify the code flow without ...
[ 1, 1 ]
[]
[]
[ "csv", "python", "wildcard" ]
stackoverflow_0074279330_csv_python_wildcard.txt
Q: Create Chaikin Oscillator using Pandas I'm trying to implement Chaikin Oscillator from scratch but it gives me wrong results comparing to real one API (TradingView for example) Code: def exponential_moving_average_series(ts, n): """ :param df: pandas.DataFrame :param n: :return: pandas.DataFrame ...
Create Chaikin Oscillator using Pandas
I'm trying to implement Chaikin Oscillator from scratch but it gives me wrong results comparing to real one API (TradingView for example) Code: def exponential_moving_average_series(ts, n): """ :param df: pandas.DataFrame :param n: :return: pandas.DataFrame """ EMA = pd.Series(pd.ewma(ts, span =...
[ "Volume-based indicators are impractical to match TradingView because the reported volume data can often be different. With crypto the volume is also exchange-specific. With the Chaikin Oscillator, even more complications exist due to a seemingly undefined lookback length.\nAs of 2022, one article on Investopedia s...
[ 0 ]
[]
[]
[ "pandas", "python", "technical_indicator" ]
stackoverflow_0048722737_pandas_python_technical_indicator.txt
Q: Close all webdriver sessions using Python I am running a Flask server and I have the following problem. When an user login in, a Selenium webdriver is initialized and performs some task. It store some cookies and then it communicates with frontend (I can't control WHEN it will save the cookies and I cannot close i...
Close all webdriver sessions using Python
I am running a Flask server and I have the following problem. When an user login in, a Selenium webdriver is initialized and performs some task. It store some cookies and then it communicates with frontend (I can't control WHEN it will save the cookies and I cannot close it with driver.close(). After this I need to sta...
[ "Ideally, you want to driver.quit() to gracefully close all browser windows (note that driver.close() only closes the window in focus). If that's not possible, you can use psutil to kill the chromedriver processes:\nfor proc in psutil.process_iter():\n if 'chromedriver' in proc.name():\n proc.kill()\n\nA s...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074279938_python_selenium_selenium_webdriver.txt
Q: Django tests not isolated when testing authentication I am testing my authentication with the django.test.Client and two tests cases fail because once I test my test_login_success test case, the other tests fail because the user remains authenticated, even when I am instantiating a new client in the class setUp an...
Django tests not isolated when testing authentication
I am testing my authentication with the django.test.Client and two tests cases fail because once I test my test_login_success test case, the other tests fail because the user remains authenticated, even when I am instantiating a new client in the class setUp and even deleting the user in the tearDown. My code: from dja...
[ "Maybe you can use the method logout from Client class.\nthis method \"Log out the user by removing the cookies and session object.\"\nTell me if that works.\n", "The error: user.is_authenticated is not doing what is expected in this code. Since the user in request object in the view will be an AnonymousUser or a...
[ 1, 0 ]
[]
[]
[ "django", "django_tests", "python", "unit_testing" ]
stackoverflow_0074257790_django_django_tests_python_unit_testing.txt
Q: How to declare variables from an input() with different class ( int and str) iLig1, iCol1 , iLig2 , iCol2 , carac = map(int, input ().split ()) hello I try to get this ligne of input in my code right, I get 5 variables from an input that look like this: 1 12 7 14 u how can I declare the last one as a str properl...
How to declare variables from an input() with different class ( int and str)
iLig1, iCol1 , iLig2 , iCol2 , carac = map(int, input ().split ()) hello I try to get this ligne of input in my code right, I get 5 variables from an input that look like this: 1 12 7 14 u how can I declare the last one as a str properly, I tried to consider them all as str and convert the 4 first as int but I cannot...
[ "You can use the Iterable Unpacking : (*).\n# we suppose input is -> 1 2 3 4 u\n>>> *i, j = input().split()\n\n>>> print(i)\n['1', '2', '3', '4']\n\n>>> print(j)\nu\n\n>>> list(map(int, i))\n[1, 2, 3, 4]\n\n", "This should do the job:\niLig1, iCol1 , iLig2 , iCol2 , carac = [int(x) if i<4 else x for i,x in enumer...
[ 3, 2, 0 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0074280099_integer_python_string.txt
Q: How to split a list into multiple batches and assign each batch to a thread worker I want to split a bigger list (2000 items) into multiple batches, each going to run on a different thread in parallel. The text of the problem is this: We need to calculate the sum of squares for a list containing more than 2000 ite...
How to split a list into multiple batches and assign each batch to a thread worker
I want to split a bigger list (2000 items) into multiple batches, each going to run on a different thread in parallel. The text of the problem is this: We need to calculate the sum of squares for a list containing more than 2000 items. Ex: if the list was [1,2,3,4,5] -> result will be 55 Make sure to implement and time...
[ "I'm new to the ThreadPoolExecutor. After reading https://docs.python.org/3/library/concurrent.futures.html, I pulled out the ThreadPoolExecutor Example that utilizes the submit() method (as opposed to the map). My results are below. I've removed some of your code (like perf_counter) to get my code to work in a ...
[ 0 ]
[]
[]
[ "multithreading", "python", "python_multithreading", "threadpool" ]
stackoverflow_0074279478_multithreading_python_python_multithreading_threadpool.txt
Q: What is the purpose of sort_index of a Dataclass in Python? I am learning about Dataclasses but I am confused on the purpose of sort_index and how it actually works. I can't seem to find any valuable information on it. The official Python documentation doesn't mention it, which is mind boggling. Here is an example...
What is the purpose of sort_index of a Dataclass in Python?
I am learning about Dataclasses but I am confused on the purpose of sort_index and how it actually works. I can't seem to find any valuable information on it. The official Python documentation doesn't mention it, which is mind boggling. Here is an example: @dataclass(order=True) class Person: sort_index: int = fiel...
[ "Setting a sort_index attribute (or indeed, any identifier—the name is irrelevant) in the __post_init__ method appears to be the value on which comparisons are performed.\nThere is an implicit setting of the comparison methods (__lt__, __gt__, etc--read about dunder methods if unfamiliar), using the attributes prov...
[ 5, 0 ]
[]
[]
[ "data_class", "python", "python_3.x", "python_dataclasses" ]
stackoverflow_0068840767_data_class_python_python_3.x_python_dataclasses.txt
Q: i want to let the user input a number 3 times at most import random attempt =0 while attempt <=3: rand = random.randint(1,18) age = int(input(“please input your age:”)) if(int(age) == rand): print(“great”) elif age< rand: print (“smaller than the true value”) elif age > rand): print...
i want to let the user input a number 3 times at most
import random attempt =0 while attempt <=3: rand = random.randint(1,18) age = int(input(“please input your age:”)) if(int(age) == rand): print(“great”) elif age< rand: print (“smaller than the true value”) elif age > rand): print (“larger than the true value”) Generate a random age (1~1...
[ "You have to make sure you increase the value of attempt everytime you get an answer. Also, fix some indentation error:\nimport random\nattempt = 0\nwhile attempt < 3:\n rand = random.randint(1,18)\n age = int(input(\"Please enter your age\"))\n if(int(age) == rand):\n print(\"Great\")\n elif age...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074280078_python.txt
Q: Convert single-quoted string to double-quoted string I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote. A: There is no difference between "single quoted" and "double quoted" strings in Python: b...
Convert single-quoted string to double-quoted string
I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.
[ "There is no difference between \"single quoted\" and \"double quoted\" strings in Python:\nboth are parsed internally to string objects.\nI mean:\na = \"European Swallow\"\nb = 'African Swallow'\n\nAre internally string objects.\nHowever you might mean to add an extra quote inside an string object, so that the con...
[ 24, 20, 6, 5, 5, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001906991_python_string.txt
Q: How to get the transformation between two body frames in PyDrake I have two frames at different joint locations of IIWA arm, using f1 = plant.GetFrameByName("iiwa_link_0", kuka_model) f2 = plant.GetFrameByName("iiwa_link_2", kuka_model) I want to find the transformation between these two body frames(f1, f2). Getti...
How to get the transformation between two body frames in PyDrake
I have two frames at different joint locations of IIWA arm, using f1 = plant.GetFrameByName("iiwa_link_0", kuka_model) f2 = plant.GetFrameByName("iiwa_link_2", kuka_model) I want to find the transformation between these two body frames(f1, f2). Getting error when using f1.CalcPoseInBodyFrame() : TypeError: CalcPoseInBo...
[ "It would be helpful if you post the actual code giving you the error.\nWorst case, you can do this:\ncontext = ... # assuming you have a context where things are posed.\n\nf1 = plant.GetFrameByName(\"iiwa_link_0\", kuka_model)\nf2 = plant.GetFrameByName(\"iiwa_link_2\", kuka_model)\nX_F2F1 = f1.CalcPose(context, f...
[ 2 ]
[]
[]
[ "drake", "pose_estimation", "python", "robotics", "transformation" ]
stackoverflow_0074280132_drake_pose_estimation_python_robotics_transformation.txt
Q: How to summarise data to make a grouped bar chart in Altair / Streamlit In R I would code: library(tidyverse) library(lubridate) df<-data.frame(mydate=rep(as.Date("2022-01-01")+0:90, each=10), mygroup=sample(c("A", "B", "C"), size=910, replace=T)) df %>% mutate(mymonth=round_date(mydate, "month")...
How to summarise data to make a grouped bar chart in Altair / Streamlit
In R I would code: library(tidyverse) library(lubridate) df<-data.frame(mydate=rep(as.Date("2022-01-01")+0:90, each=10), mygroup=sample(c("A", "B", "C"), size=910, replace=T)) df %>% mutate(mymonth=round_date(mydate, "month")) %>% ggplot(aes(x=mymonth, fill=mygroup))+ geom_bar(position = "dodge")...
[ "Solution was multi-step. First, using dt.strftime('%Y-%m-15') to bring all the dates together per month (I choose the 15th, because the 1st was rounding down into the previous month. Bug?).\nThen groupby and count to summarize the data. .reset_index created a nice dataframe, and rename(columns= named the summary c...
[ 0 ]
[]
[]
[ "altair", "pandas", "python", "streamlit" ]
stackoverflow_0074271738_altair_pandas_python_streamlit.txt
Q: TypeError: unsupported operand type(s) for &: 'str' and 'bool' for DF filtering I am trying to filter my dataframe such that when I create a new columnoutput, it displays the "medium" rating. My dataframe has str values, so I convert them to numbers based on a ranking system I have and then I filter out the maximu...
TypeError: unsupported operand type(s) for &: 'str' and 'bool' for DF filtering
I am trying to filter my dataframe such that when I create a new columnoutput, it displays the "medium" rating. My dataframe has str values, so I convert them to numbers based on a ranking system I have and then I filter out the maximum and minimum rating per row. I am running into this error: TypeError: unsupported op...
[ "Took to sec to understand what you really meant by filter. Here is some code that should be self explanatory and should achieve what you're looking for:\n# Import pandas library\nimport pandas as pd\n \n# initialize list of lists\ndata = [['D', 'D', 'C'], ['C', 'B', 'A'], ['B', 'B', 'B']]\n \n# Create the pandas...
[ 1, 1 ]
[]
[]
[ "dataframe", "filter", "pandas", "python", "typeerror" ]
stackoverflow_0074279978_dataframe_filter_pandas_python_typeerror.txt
Q: Polars scan s3 multi-part parquet files I have a multipart partitioned parquet on s3. Each partition contains multiple parquet files. The below code narrows in on a single partition which may contain somewhere around 30 parquet files. When I use scan_parquet on a s3 address that includes *.parquet wildcard, it onl...
Polars scan s3 multi-part parquet files
I have a multipart partitioned parquet on s3. Each partition contains multiple parquet files. The below code narrows in on a single partition which may contain somewhere around 30 parquet files. When I use scan_parquet on a s3 address that includes *.parquet wildcard, it only looks at the first file in the partition. I...
[ "It looks like from the user guide on multiple files that to do so requires a loop creating many lazy dfs that you then combine together.\nAnother approach is to use the scan_ds function which takes a pyarrow dataset object.\nimport polars as pl\nimport s3fs\nimport pyarrow.dataset as ds\nfs = s3fs.S3FileSystem()\n...
[ 1 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074280212_python_python_polars.txt
Q: How to set up user input asking for a list one at a time? I am trying to replicate this python code but I am unsure how to go about asking for a user inputted list one at a time and then how to present the list in order and then randomly. If anyone could point me in the right direction I would appreciate it total ...
How to set up user input asking for a list one at a time?
I am trying to replicate this python code but I am unsure how to go about asking for a user inputted list one at a time and then how to present the list in order and then randomly. If anyone could point me in the right direction I would appreciate it total = 0 while True: List = input('Enter an item or "done" to s...
[ "Append the input on an array:\nall_values = []\nwhile True:\n value = input('Enter an item or \"done\" to stop entering items: ')\n if value == 'done':\n break\n all_values.append(value)\nprint(all_values)\n\n", "import random\n\nitems = []\nwhile True:\n x = input('Enter an item or \"done\" t...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074280358_python_python_3.x.txt
Q: Cannot find a module imported by another module I have a file structure like this └── myproject ├── src ├── a.py ├── b.py module a contains a class that is imported in by module b like this: from src.a import some_class when I try to import b from another class: from myproject.src import b I...
Cannot find a module imported by another module
I have a file structure like this └── myproject ├── src ├── a.py ├── b.py module a contains a class that is imported in by module b like this: from src.a import some_class when I try to import b from another class: from myproject.src import b I get this error: from src.a import some_class Modul...
[ "You can try this import in b.py\nfrom .a import some_class\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_import", "python_packaging" ]
stackoverflow_0074280474_python_python_import_python_packaging.txt
Q: Nested dictionary value acts as a counter I have the below code and am trying to generate a new dictionary of parameters. I would like the new dictionary to be a nested dictionary, and one of the nested keys be the most recent value, while the second nested key to be a counter that increases each time a value is u...
Nested dictionary value acts as a counter
I have the below code and am trying to generate a new dictionary of parameters. I would like the new dictionary to be a nested dictionary, and one of the nested keys be the most recent value, while the second nested key to be a counter that increases each time a value is updated. options = {'threads' : '1', 'tolerance'...
[ "over_params[k]['count'] += 1 won't work if over_params[k] isn't already a dict; you can fix this like follows:\noptions = {'threads' : '1', 'tolerance' : '1'}\noptions_2 = {'threads' : '2', 'timeout': True}\n\nover_params = {}\n\ndef overrides_tracker(options, over_params):\n print(options)\n for k, v in opt...
[ 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074280395_dictionary_python.txt
Q: Statsmodels state space representation of stochastic process with nonzero mean I would like to define a state space representation of a model with a nonzero drift term in statsmodels. The documentation for the state state representation framework appears to assume that the stochastic terms (epsilon and eta) have ...
Statsmodels state space representation of stochastic process with nonzero mean
I would like to define a state space representation of a model with a nonzero drift term in statsmodels. The documentation for the state state representation framework appears to assume that the stochastic terms (epsilon and eta) have zero mean: Is there a way to introduce (and then set as parameters) a mean drift te...
[ "Yes, you can add a constant term to either equation by placing values into obs_intercept or state_intercept.\nself.ssm['obs_intercept', 0] = 1.4\n\nIf the parameter is being estimated, then you would do this in the update method.\ndef update(self, params, **kwargs):\n params = super().update(params, **kwargs)\n...
[ 1 ]
[]
[]
[ "python", "state_space", "statsmodels" ]
stackoverflow_0074252913_python_state_space_statsmodels.txt
Q: Can someone point out where the error is happening when I call this variable outside the loop? Working on a weather generator that using terrain and month to randomize a weather effect for that scenario. Its extremely bloated because I could not get while loops or classes to work in previous iterations. I decided ...
Can someone point out where the error is happening when I call this variable outside the loop?
Working on a weather generator that using terrain and month to randomize a weather effect for that scenario. Its extremely bloated because I could not get while loops or classes to work in previous iterations. I decided to just to make a massive block of code that did the job and revisit later in my project. Using Pyth...
[ "You are approaching the code structure in a very \"abstract\" way.\nWhat makes a proper variable within a class is using the self \"prefix\" (trying to simplify terminology)\nfrom random import *\nimport random\n\nclass month:\n self.estimated_day = random.randint(1, 359)\n self.current_month = \"\"\n \n ...
[ 0, 0 ]
[]
[]
[ "class", "if_statement", "python", "random", "while_loop" ]
stackoverflow_0074280350_class_if_statement_python_random_while_loop.txt
Q: Cannot assign "1": "Refund.order" must be a "Order" instance So, this here is a dirty production-level code, and I am stuck at this. I am designing a Return API but I am not good at this, help is much appreciated. Traceback (most recent call last): File "C:\Users\Abdul\.virtualenvs\storefront\lib\site-packages\...
Cannot assign "1": "Refund.order" must be a "Order" instance
So, this here is a dirty production-level code, and I am stuck at this. I am designing a Return API but I am not good at this, help is much appreciated. Traceback (most recent call last): File "C:\Users\Abdul\.virtualenvs\storefront\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response...
[ "Assign an Order instance rather than the order ID to refund.order. You'll need to query for the matching order.\nThis is indicated in the Refund model by\norder = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='refunds')\n\nand in the error\n`ValueError: Cannot assign \"1\": \"Refund.order\" must ...
[ 1 ]
[]
[]
[ "api", "django", "django_rest_framework", "django_views", "python" ]
stackoverflow_0074279935_api_django_django_rest_framework_django_views_python.txt
Q: Why did a plawright-python app run in Docker failed? Headless=False? I have a small application that uses fast-api and playwright to scrape data and send it back to the client. The program is working properly when I'm running it locally, but when I try to run it as a Docker image it fails with the following error:...
Why did a plawright-python app run in Docker failed? Headless=False?
I have a small application that uses fast-api and playwright to scrape data and send it back to the client. The program is working properly when I'm running it locally, but when I try to run it as a Docker image it fails with the following error: Looks like you launched a headed browser without having a XServer running...
[ "After investigating and trying several things, looks like the problem is the user_agent of the browser when is in headless mode, for some reason the default user agent does not like to that page, try with:\ndef extract_html(self):\n with sync_playwright() as p:\n browser = p.chromium.launch(headless=True...
[ 1 ]
[]
[]
[ "docker", "playwright", "playwright_python", "python" ]
stackoverflow_0074266883_docker_playwright_playwright_python_python.txt
Q: How to make a copy of xml tree in python using ElementTree? I'm using xml.etree.ElementTree to parse xml file. I'm parsing xml file in the following way: import xml.etree.ElementTree as ET tree = ET.parse(options.xmlfile) root = tree.getroot() This is my xml file: <rootElement> <member> <member_id>43...
How to make a copy of xml tree in python using ElementTree?
I'm using xml.etree.ElementTree to parse xml file. I'm parsing xml file in the following way: import xml.etree.ElementTree as ET tree = ET.parse(options.xmlfile) root = tree.getroot() This is my xml file: <rootElement> <member> <member_id>439854395435</member_id> </member> </rootElement> Then I'm sav...
[ "You can create a copy of the member element and append it. Example:\nimport xml.etree.ElementTree as ET\nimport copy\n\ntree = ET.parse(\"test.xml\")\nroot = tree.getroot() \n\n# Find element to copy \nmember1 = tree.find(\"member\")\n\n# Create a copy\nmember2 = copy.deepcopy(member1)\n\n# Append the copy \nroot....
[ 15, 1 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0038906104_elementtree_python_xml.txt
Q: sqlalchemy.exc.InvalidRequestError: Row with identity key can't be loaded into an object; the polymorphic discriminator column refers to mapped class I have some legacy code that has a polymorphic base class definition and two sub classes. The entity definitions are below. class Field(Base): __tablename__ = "f...
sqlalchemy.exc.InvalidRequestError: Row with identity key can't be loaded into an object; the polymorphic discriminator column refers to mapped class
I have some legacy code that has a polymorphic base class definition and two sub classes. The entity definitions are below. class Field(Base): __tablename__ = "field" field_parent = Column(String(64), index=True) controller_id = Column(ForeignKey('controller.id')) controller = relationship("Controller"...
[ "I've come across the same stuff here, hence I'm going through your post ;) The obvious solution is to select a common ancestor class defining the concrete polymorphic identity via filter or smth.\n", "I just had the same issue as well and found a very simple solution: the base class needs also to have a polymorp...
[ 0, 0 ]
[]
[]
[ "polymorphic_relationship", "python", "sqlalchemy" ]
stackoverflow_0071013527_polymorphic_relationship_python_sqlalchemy.txt
Q: Error InvalidRequestError: SQL expression, column, or mapped entity expected using hybrid_property I have the following model class: class ArticleOptionSetModel(db.Model): __tablename__ = 'sdt_articles_options_sets' id = db.Column(db.Integer, db.Sequence("sdq_articles_options_sets"), primary_key=True) ...
Error InvalidRequestError: SQL expression, column, or mapped entity expected using hybrid_property
I have the following model class: class ArticleOptionSetModel(db.Model): __tablename__ = 'sdt_articles_options_sets' id = db.Column(db.Integer, db.Sequence("sdq_articles_options_sets"), primary_key=True) article_id = db.Column(db.Integer, db.ForeignKey('sdt_articles.id'), nullable=False) option_set_id ...
[ "You should return\nselect([1])\n\nor select([0]) \n\nto return as SQL entity.\n" ]
[ 0 ]
[]
[]
[ "hybrid", "orm", "properties", "python", "sqlalchemy" ]
stackoverflow_0063827481_hybrid_orm_properties_python_sqlalchemy.txt
Q: Python Type Hint Instances of class I'm unsure of the Python convention for type hinting for this situation I have a class class A(object): pass And a not defined number of subclasses of A, i.e.: class B(A): pass class C(A): pass class D(A): pass ..... If I want that a function, accepts onl...
Python Type Hint Instances of class
I'm unsure of the Python convention for type hinting for this situation I have a class class A(object): pass And a not defined number of subclasses of A, i.e.: class B(A): pass class C(A): pass class D(A): pass ..... If I want that a function, accepts only instances of B,C,D, and not instances ...
[ "Python hinting is just that (a hint that is a suggestion and therefore not enforceable).\nYou can hint which types a variable or argument should be, but cannot preclude a type.\nSo in the given example in the question, you can hint for B, C, and D as the arguments and just elect to omit A as an argument.\nSo it lo...
[ 1 ]
[]
[]
[ "python", "python_3.x", "python_typing", "type_hinting" ]
stackoverflow_0074280147_python_python_3.x_python_typing_type_hinting.txt
Q: Pandas list of JSON element to python array I have a dataframe like so: Store matches Murphy's [{'domain': 'murphyscolumbus.com', 'location': 'Columbus, OH'}, {'domain': 'murphystampa.com', 'location': 'Tampa, FL'}] Bill's [{'domain': 'billsdallas.com', 'location': 'Dallas, TX'}, {'domain': 'billsorlando.com', ...
Pandas list of JSON element to python array
I have a dataframe like so: Store matches Murphy's [{'domain': 'murphyscolumbus.com', 'location': 'Columbus, OH'}, {'domain': 'murphystampa.com', 'location': 'Tampa, FL'}] Bill's [{'domain': 'billsdallas.com', 'location': 'Dallas, TX'}, {'domain': 'billsorlando.com', 'location': 'Orlando, FL'}] What I wan...
[ "Try:\nfrom ast import literal_eval\n\n# apply literal_eval if necessary\ndf[\"matches\"] = df[\"matches\"].apply(literal_eval)\n\ndf[\"domains\"] = df.pop(\"matches\").apply(lambda x: [d[\"domain\"] for d in x])\nprint(df)\n\nPrints:\n Store domains\n0 Murphy's [murphyscolum...
[ 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074280710_dataframe_json_pandas_python.txt
Q: Nested tqdm progressbar not on same position during run My code consist of a double loop. I want to have a double tqdm progress bar, with the first keeping track of the outer loop, and the second keeping track of the inner loop. They should keep their position; only the inner loop progress bar should be cleared an...
Nested tqdm progressbar not on same position during run
My code consist of a double loop. I want to have a double tqdm progress bar, with the first keeping track of the outer loop, and the second keeping track of the inner loop. They should keep their position; only the inner loop progress bar should be cleared and start at zero at every outer iteration. The code I have now...
[ "Thanks to @Claudio I have solved it. I was running in PyCharm, whereas running in a terminal doesn't show this behavior.\nYou only should not close the second progress bar, and also to fix the initialization of the second bar it is better to do that outside of the loops.\nAnother cause of getting new lines is when...
[ 0 ]
[]
[]
[ "python", "tqdm" ]
stackoverflow_0074280549_python_tqdm.txt
Q: How to make the length of a nested list equal to the value of a number in a list, using list comprehension? I'm really new to Python, so forgive me if this is a ridiculously simple question. I have a given list x = [0,1,2,3,4,5,6,7,8,9] Now I want to make a list e, using list comprehension, that contains a list f...
How to make the length of a nested list equal to the value of a number in a list, using list comprehension?
I'm really new to Python, so forgive me if this is a ridiculously simple question. I have a given list x = [0,1,2,3,4,5,6,7,8,9] Now I want to make a list e, using list comprehension, that contains a list for each odd element of list x. All inner elements of this list should be true and the number of list elements is ...
[ "This code should do what you want:\n[[True for _ in range(z)] for z in x if z % 2 != 0]\n\nThe difference is in the inner comprehension, [True for _ in range(z)].\nPreviously, you were iterating over each z in x - so, for each iteration, z is an integer out of x. Then, for each unique z, you were iterating over th...
[ 3, 1, 1, 0 ]
[]
[]
[ "list", "list_comprehension", "nested", "python" ]
stackoverflow_0074280475_list_list_comprehension_nested_python.txt
Q: Equivalent of pandas merge_asof when joining spark dataframes, with merge nearest and tolerance I'm trying to replicate pandas's merge_asof behavior when joining Spark dataframes. Let's just say I have two dataframes, df1 and df2: import pandas as pd df1 = pd.DataFrame([{"timestamp": 0.5 * i, "a": i * 2} for i in ...
Equivalent of pandas merge_asof when joining spark dataframes, with merge nearest and tolerance
I'm trying to replicate pandas's merge_asof behavior when joining Spark dataframes. Let's just say I have two dataframes, df1 and df2: import pandas as pd df1 = pd.DataFrame([{"timestamp": 0.5 * i, "a": i * 2} for i in range(66)]) df2 = pd.DataFrame([{"timestamp": 0.33 * i, "b": i} for i in range(100)]) # use merge_as...
[ "The following provides configurable direction and tolerance arguments. Window functions are used (last for \"backward\", first for \"forward\" and both of them for \"nearest\").\nAlso, in my experience, the by argument of Pandas' merge_asof is often needed. So I have made an effort to add this argument to the func...
[ 3, 2, 2 ]
[]
[]
[ "apache_spark", "join", "pandas", "pyspark", "python" ]
stackoverflow_0069911136_apache_spark_join_pandas_pyspark_python.txt
Q: Pandas cumsum on a groupby object with a boolean condition For the given dataset below, I am able to calculate "distinct" visits to a hotel, which is defined as any visit where the traveler arrives at least one full calendar day (i.e., 2 or more days) since a previous departure. Any arrival that is less than one ...
Pandas cumsum on a groupby object with a boolean condition
For the given dataset below, I am able to calculate "distinct" visits to a hotel, which is defined as any visit where the traveler arrives at least one full calendar day (i.e., 2 or more days) since a previous departure. Any arrival that is less than one full calendar day since the previous visit will be merged with t...
[ "Let's do this piece by piece: (df[\"days_between_visits\"]>=2) returns a boolean series. We treat this series as an int64 because pandas allows for some integer operations to be performed on boolean series (with False == 0 and True == 1).\n\nWhen we perform the .cumsum() on the boolean series, we get the followin...
[ 0 ]
[]
[]
[ "cumsum", "group_by", "pandas", "python" ]
stackoverflow_0074103887_cumsum_group_by_pandas_python.txt
Q: How to print name under the column that has the max value? (pandas) (python) The data sheet I am working with is organized with the columns: 'Country', 'Internet Users', and 'Population'. I am able to work out and print the max percentage of population using internet, but how do I print the name of the country wit...
How to print name under the column that has the max value? (pandas) (python)
The data sheet I am working with is organized with the columns: 'Country', 'Internet Users', and 'Population'. I am able to work out and print the max percentage of population using internet, but how do I print the name of the country with that max percentage. For example, Indonesia will have the max with 94% but I am ...
[ "This should do it:\n# To get the country with max percentage\ncondition = pop.loc[pop['Percentage'] == pop['Percentage'].max(), 'Country']\n\nprint('Country with max percentage is: {} {:.0%}'.format(condition, pop['Percentage'].max()))\n\nOutput:\n'Country with max percentage is: Indonesia 94%'\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074280632_pandas_python.txt
Q: multithreading reading frames from opencv reducing latency Consider the below script: class VideoCaptureThreading: def __init__(self, src=0, width=640, height=480): self.src = src self.cap = cv2.VideoCapture(self.src) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) self.cap.set(cv...
multithreading reading frames from opencv reducing latency
Consider the below script: class VideoCaptureThreading: def __init__(self, src=0, width=640, height=480): self.src = src self.cap = cv2.VideoCapture(self.src) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) self.grabbed, self.fram...
[ "This approach makes sure the frame is the latest one in the stream in case the stream publishes faster than reading from the buffer. If there is an observable latency, it is most probably because of heavy publisher encoder options or unsuited listener configuration (e.g. realtime flag not set). Copy has a cost but...
[ 1 ]
[]
[]
[ "multithreading", "opencv", "python" ]
stackoverflow_0074280157_multithreading_opencv_python.txt
Q: Removing items from JSON using Python loop how do I iterate over the data and keep object keys that have the string "Java" in the value and remove keys with the string "Javascript" in the value? In addition to the iterations I already have in my code. For example: this key has the word 'Java' in the value. ...
Removing items from JSON using Python loop
how do I iterate over the data and keep object keys that have the string "Java" in the value and remove keys with the string "Javascript" in the value? In addition to the iterations I already have in my code. For example: this key has the word 'Java' in the value. "value" : "A vulnerability in the encryption ...
[ "Add this inside the for CVE_Item loop.\nCVE_Item['cve']['description']['description_data'] = [\n d for d in CVE_Item['cve']['description']['description_data'] \n if 'Java' in d['value'] and 'JavaScript' not in d['value']]\n\nThe modified loop looks like:\nfor CVE_Item in data['CVE_Items']:\n CVE_Item['cve...
[ 0 ]
[]
[]
[ "filter", "json", "loops", "python", "sorting" ]
stackoverflow_0074280635_filter_json_loops_python_sorting.txt
Q: Juypter will not launch from Anaconda When launching Juypter from Anaconda I receive the following error message: Traceback (most recent call last): File "C:\Users\ceo20\Anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\ceo20\Anacon...
Juypter will not launch from Anaconda
When launching Juypter from Anaconda I receive the following error message: Traceback (most recent call last): File "C:\Users\ceo20\Anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\ceo20\Anaconda3\lib\site-packages\notebook\notebookapp....
[ "Try this in Anaconda prompt\npip install --upgrade jupyter_client\n\n", "pip install --upgrade jupyter_client\n\nThis package provides the Python API for starting, managing and communicating with Jupyter kernels. The above code will upgrade jupyter client.\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0059559310_python.txt
Q: "duplicate key" error when adding a new ORM object with related (child) objects I have an association object defined using SQLAlchemy to represent a many-to-many relationship between 2 tables. The reason I am using the association object pattern is because the association table contains extra columns. I have a uni...
"duplicate key" error when adding a new ORM object with related (child) objects
I have an association object defined using SQLAlchemy to represent a many-to-many relationship between 2 tables. The reason I am using the association object pattern is because the association table contains extra columns. I have a unique constraint on the name column in the data_type table. When I try to insert data i...
[ "\nMy question is, how would I say, \"Get the ID if it exists and add to association table; otherwise, create the record in data_type, then add to association table\"?\n\nYour code needs to do exactly that. Let's look at a simplified example that uses an association table instead of an association object. To set up...
[ 0 ]
[]
[]
[ "many_to_many", "python", "sqlalchemy" ]
stackoverflow_0072221219_many_to_many_python_sqlalchemy.txt
Q: How can I install Detectplate Python package import numpy as np from skimage.transform import resize from skimage import measure from skimage.measure import regionprops import matplotlib.patches as patches import matplotlib.pyplot as plt import Detectplate # The invert was done so as to convert the black pixel to...
How can I install Detectplate Python package
import numpy as np from skimage.transform import resize from skimage import measure from skimage.measure import regionprops import matplotlib.patches as patches import matplotlib.pyplot as plt import Detectplate # The invert was done so as to convert the black pixel to white pixel and vice versa license_plate = np.inv...
[ "There is no package 'Detectplate' available on pip, so probably you are using someone else's code (https://pypi.org/search/?q=Detectplate&o=)\nThe best fit from searching through web is this script, in which there is also plate_like_objects variable: https://github.com/apoorva-dave/LicensePlateDetector/blob/master...
[ 0 ]
[]
[]
[ "package", "pip", "python" ]
stackoverflow_0074280470_package_pip_python.txt
Q: Taking user input into dataset, then check items in dataset and move to new dataset I want to get a user's input of ISBN-10/ISBN-13s and be able to check the length of each input after it's put into a dataset then convert the ISBN-13s to ISBN-10s. In the end it should be a list of ISBN-10s. I'm currently getting a...
Taking user input into dataset, then check items in dataset and move to new dataset
I want to get a user's input of ISBN-10/ISBN-13s and be able to check the length of each input after it's put into a dataset then convert the ISBN-13s to ISBN-10s. In the end it should be a list of ISBN-10s. I'm currently getting an empty list when I try and don't know where I went wrong with my code. import pyisbn al...
[ "I think your for loop is the problem. Try this:\nimport pyisbn\n\nalist = []\ndef get_dataset():\n while True:\n try:\n dataset = [str(_) for _ in input(\"\\nEnter Book ID(s): \").replace(',', ' ').split()]\n except ValueError:\n print(\"\\nInvalid Input\")\n continue\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074280826_python.txt
Q: How to execute a command prompt command from python I tried something like this, but with no effect: command = "cmd.exe" proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE) proc.stdin.write("dir c:\\") A: how about simply: import os os.system('dir c:\\') A: You probably want to ...
How to execute a command prompt command from python
I tried something like this, but with no effect: command = "cmd.exe" proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE) proc.stdin.write("dir c:\\")
[ "how about simply:\nimport os\nos.system('dir c:\\\\')\n\n", "You probably want to try something like this:\ncommand = \"cmd.exe /C dir C:\\\\\"\nI don't think you can pipe into cmd.exe... If you are coming from a unix background, well, cmd.exe has some ugly warts!\nEDIT: According to Sven Marnach, you can pipe t...
[ 86, 39, 23, 14, 7, 6, 3, 2, 2, 0 ]
[ "From Python you can do directly using below code\nimport subprocess\nproc = subprocess.check_output('C:\\Windows\\System32\\cmd.exe /k %windir%\\System32\\\\reg.exe ADD HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA /t REG_DWORD /d 0 /f' ,stderr=subprocess.STDOUT,shell=True)\n ...
[ -1 ]
[ "python", "windows" ]
stackoverflow_0005486725_python_windows.txt
Q: How to print each element of a list until a certain length Python How to print each element of my list to a defined length (5), so for example: myList = ["abcdefgh", "ijklmnop"] The output I'm looking for is: abcde ijklm I've tried this (printing dates from an excel sheet): i = 2 x =0 while i < maxR: valuesI...
How to print each element of a list until a certain length Python
How to print each element of my list to a defined length (5), so for example: myList = ["abcdefgh", "ijklmnop"] The output I'm looking for is: abcde ijklm I've tried this (printing dates from an excel sheet): i = 2 x =0 while i < maxR: valuesItems = wb0["C" + str(rowList[i])].value itemDate.append(valuesItem...
[ "for element in myList:\n print(element[:5])\n\n" ]
[ 4 ]
[]
[]
[ "element", "list", "printing", "python", "string_length" ]
stackoverflow_0074280892_element_list_printing_python_string_length.txt
Q: AWS Session/Credentials/Auth I'm following an AWS workshop for SaaS Serverless, however they wrote it with python code and i'm not very good at python so i'm trying to rewrite everything in javascript. It was doing ok until i get to the problem in title. They use this function to get authentication so i can regist...
AWS Session/Credentials/Auth
I'm following an AWS workshop for SaaS Serverless, however they wrote it with python code and i'm not very good at python so i'm trying to rewrite everything in javascript. It was doing ok until i get to the problem in title. They use this function to get authentication so i can register my tenant. import boto3 from aw...
[ "So I did a bit of digging through the source code and found the place where they declare the AWSRequestsAuth class here. TL;DR - it's a class that helps connect to AWS services via Amazon's signature version 4 signing process.\nFor your problem of getting credentials without hardcoding, I found this guide for Node...
[ 3, 2 ]
[]
[]
[ "amazon_web_services", "javascript", "python" ]
stackoverflow_0074280194_amazon_web_services_javascript_python.txt
Q: My code does not work on some cases. What is the problem? I'm having a problem here. This is a program finding the maximum and minimum value in a custom list. Some cases work while other cases don't work so well. #find the maximum and minimum number in an integer list def Custom_List(MyList): for i in range(l...
My code does not work on some cases. What is the problem?
I'm having a problem here. This is a program finding the maximum and minimum value in a custom list. Some cases work while other cases don't work so well. #find the maximum and minimum number in an integer list def Custom_List(MyList): for i in range(len(MyList)): if MyList[i] >= MyList[i-1]: ...
[ "try to start your loop from 1 so you can copare first and second element in the list at the first one instead of first one with the list index -1\n def Custom_List(MyList):\n for i in range(1,len(MyList)):\n if MyList[i] >= MyList[i-1]:\n myMax = MyList[i]\n if MyList[...
[ 0, 0 ]
[ "You forgot to end the string with quotes:\nlength = int(input(\"List length: )) #the length of a list\n\nTry this:\n#find the maximum and minimum number in an integer list\ndef Custom_List(MyList):\n for i in range(len(MyList)):\n if MyList[i] >= MyList[i-1]:\n myMax = MyList[i]\n ...
[ -2 ]
[ "list", "max", "python", "python_3.x" ]
stackoverflow_0074279181_list_max_python_python_3.x.txt
Q: Payload to scrape data not working anymore I'm creating a list called id by scraping from the url below, but the payload I use to extract (which I've used successfully before) is not responsive. I get JSONDecodeError: Expecting value: line 1 column 1 (char 0) in response to data = requests.post(url, json=payload)....
Payload to scrape data not working anymore
I'm creating a list called id by scraping from the url below, but the payload I use to extract (which I've used successfully before) is not responsive. I get JSONDecodeError: Expecting value: line 1 column 1 (char 0) in response to data = requests.post(url, json=payload).json(). I'm not familiar with the issue: if it's...
[ "The error just means that the response wasn't proper json format. You can check for it by splitting up that data = requests.post(url, json=payload).json() line to something like\nres = requests.post(url, json=payload)\n# res.raise_for_status() # just in case\n\nif 'application/json' in res.headers['Content-Type']:...
[ 0 ]
[]
[]
[ "beautifulsoup", "json", "payload", "python", "screen_scraping" ]
stackoverflow_0074280152_beautifulsoup_json_payload_python_screen_scraping.txt
Q: My scrapy code is not working but everything seems okey Hello i tried to scrape some info from www.soccerstats.com.My code below isnot scrape anything from that website.The output is: {'BOT_NAME': 'superlig', 'NEWSPIDER_MODULE': 'superlig.spiders', 'REQUEST_FINGERPRINTER_IMPLEMENTATION': '2.7', 'SPIDER_MODULES'...
My scrapy code is not working but everything seems okey
Hello i tried to scrape some info from www.soccerstats.com.My code below isnot scrape anything from that website.The output is: {'BOT_NAME': 'superlig', 'NEWSPIDER_MODULE': 'superlig.spiders', 'REQUEST_FINGERPRINTER_IMPLEMENTATION': '2.7', 'SPIDER_MODULES': ['superlig.spiders'], 'TWISTED_REACTOR': 'twisted.internet...
[ "The issue is in the LinkExtractor xpath selector. That xpath although highlights elements on the website. When I perform a scrapy shell command to get the resultant elements against that selector, I get nothing.\nYou could simplify the selector to something like the one below, which worked for me and scraped items...
[ 0 ]
[]
[]
[ "python", "scrape", "scrapy", "web_scraping" ]
stackoverflow_0074279316_python_scrape_scrapy_web_scraping.txt
Q: Cant figure out this error -> IndexError: list index out of range So i have been working on this code for a while and i cant fin a solution to this problem and i was wondering if anyone in here could help me solve this? The problem is supposed to be in the method "hent_celle" where it takes in a coordinate from a ...
Cant figure out this error -> IndexError: list index out of range
So i have been working on this code for a while and i cant fin a solution to this problem and i was wondering if anyone in here could help me solve this? The problem is supposed to be in the method "hent_celle" where it takes in a coordinate from a grid and returns the object that is in that position. The error is: Tra...
[ "Pyhton list indexes start at 0, which means a list with 10 elements will use indices 0-9. Assuming self._ant_rader and self._ant_kolonner are the number of rows and columns, then rad and kol would need to be less than those values and cannot be the same value, or you get an index out of bounds error.\nFixed versio...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074280953_python.txt
Q: Convert DataFrame column type from string to datetime How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetimes? A: The easiest way is to use to_datetime: df['col'] = pd.to_datetime(df['col']) It also offers a dayfirst argument for European times (but beware this isn't strict). Here it...
Convert DataFrame column type from string to datetime
How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetimes?
[ "The easiest way is to use to_datetime:\ndf['col'] = pd.to_datetime(df['col'])\n\nIt also offers a dayfirst argument for European times (but beware this isn't strict).\nHere it is in action:\nIn [11]: pd.to_datetime(pd.Series(['05/23/2005']))\nOut[11]:\n0 2005-05-23 00:00:00\ndtype: datetime64[ns]\n\nYou can pass...
[ 678, 62, 50, 18, 0 ]
[]
[]
[ "dataframe", "datetime_format", "pandas", "python", "python_datetime" ]
stackoverflow_0017134716_dataframe_datetime_format_pandas_python_python_datetime.txt
Q: Use sharedvar.dll from Python I used a sharedvar.dll with Multicharts without any issue, I try with Python 3.10 but get some error: here my script: from ctypes import * # DLL , RETURN VALUE , FUCTION NAME, PARAMS #DefineDLLFunc: "C:\Windows\SharedVar-a64.dll", int, "svInit", ...
Use sharedvar.dll from Python
I used a sharedvar.dll with Multicharts without any issue, I try with Python 3.10 but get some error: here my script: from ctypes import * # DLL , RETURN VALUE , FUCTION NAME, PARAMS #DefineDLLFunc: "C:\Windows\SharedVar-a64.dll", int, "svInit", string; #DefineDLLFunc: "C:\Win...
[ "Try replacing line c_lib = \"C:\\Windows\\SharedVar-a64.dll\" with c_lib = \"C:\\Windows\\SharedVar-w64.dll\"\n" ]
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0074119533_ctypes_python.txt
Q: GraphQL + SQLalchemy, nested types cannot be detected I'm working on small app using graphql and sqlalcehmy. Currently faced one issue and I cannot overcome it. I have a model of skill which looks like this: class Skill(Base): __tablename__ = "skills" id = Column(Integer, primary_key=True, index=True) ...
GraphQL + SQLalchemy, nested types cannot be detected
I'm working on small app using graphql and sqlalcehmy. Currently faced one issue and I cannot overcome it. I have a model of skill which looks like this: class Skill(Base): __tablename__ = "skills" id = Column(Integer, primary_key=True, index=True) category = Column(String) name = Column(String, unique...
[ "I found the problem. in get_all_skills I need to create list of instances of CategorizedSkill. I thought that pydantic would convert dict into this model but apparently not.\n" ]
[ 0 ]
[]
[]
[ "graphql", "python", "sqlalchemy" ]
stackoverflow_0074279615_graphql_python_sqlalchemy.txt
Q: Partially initializing object attributes using functools.partial in python I'm wondering whether it is a valid use case of functools.partial to partially initialize object attributes in python. Let's say I have some base class A that has three object-level attributes (attr1, attr2, attr3): class A: def __init_...
Partially initializing object attributes using functools.partial in python
I'm wondering whether it is a valid use case of functools.partial to partially initialize object attributes in python. Let's say I have some base class A that has three object-level attributes (attr1, attr2, attr3): class A: def __init__(self, attr1, attr2, attr3): self.attr1 = attr1 self.attr2 = at...
[ "In both cases, you are basically defining factory functions to create instances of A. I would take a third route, an alternate constructor implemented using a class method.\nclass A:\n def __init__(self, attr1, attr2, attr3):\n self.attr1 = attr1\n self.attr2 = attr2\n self.attr3 = attr3\n\...
[ 0 ]
[]
[]
[ "functools", "inheritance", "python", "python_3.x" ]
stackoverflow_0074280930_functools_inheritance_python_python_3.x.txt
Q: why WinError 10053 occur optionally? I'm creating a program that activates the timer after receiving the time, ID, and password through the socket. and when i input "minute" value, I have winError 10053. I can't understand, why name and hour can be sent, not minute? this is client code declStart = input("if you wa...
why WinError 10053 occur optionally?
I'm creating a program that activates the timer after receiving the time, ID, and password through the socket. and when i input "minute" value, I have winError 10053. I can't understand, why name and hour can be sent, not minute? this is client code declStart = input("if you want to login, enter "login" ") # GUI 생기면 버...
[ "Error 10053 is \"Connection reset\" (WSAECONNRESET). It means the server closed its socket.\nThat is probably because the client sends !enter and the server tries to read it as a number and crashes. If you looked at the terminal where the server was running, you would see it crash.\n" ]
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0074274760_python_sockets.txt
Q: Why does my variable suddenly stop counting after the first loop? I'm writing a program that counts the amount of letters in a word. Everything seems to work fine except for the fact that my variable used for counting the number of letters (numberOfLetters) suddenly stops counting after the first loop. Here is my ...
Why does my variable suddenly stop counting after the first loop?
I'm writing a program that counts the amount of letters in a word. Everything seems to work fine except for the fact that my variable used for counting the number of letters (numberOfLetters) suddenly stops counting after the first loop. Here is my code: import random # Choosing a random word with open("Random Words.tx...
[ "String indexing is 0-based. But your code is treating it as 1-based. Note how in your sample output the 'a' in the chosen word 'abundant' is never printed -- you started with index 1.\nchosenWord[numberOfLetters] will fail when numberOfLetters == len(chosenWord) -- which it will do in the final pass through the lo...
[ 0 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0074278500_for_loop_loops_python.txt
Q: How to listen to a TCP stream on my FastAPI server I am working on a project building an API that is able to send the live location of vehicles to a frontend. I get this location data by subscribing to a ZMQ stream by running a while loop. This is all working and if I just run my stream as a script I can print all...
How to listen to a TCP stream on my FastAPI server
I am working on a project building an API that is able to send the live location of vehicles to a frontend. I get this location data by subscribing to a ZMQ stream by running a while loop. This is all working and if I just run my stream as a script I can print all kinds of information to the terminal (I'll store those ...
[ "In the example below, the server and worker are started in separate processes because the While loop won't resolve. It seems that you were on the right track. In my example, I have these functions in one file, but there are no restrictions on someone breaking them out into their own files:\nimport uvicorn\nimport ...
[ 0 ]
[]
[]
[ "fastapi", "python", "pyzmq", "while_loop", "zeromq" ]
stackoverflow_0074280987_fastapi_python_pyzmq_while_loop_zeromq.txt
Q: for loop with while loop wont break # Initialized list of cities CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"] # Get user input inCity = input("Enter name of city: ") # Write your test statement here to see if t...
for loop with while loop wont break
# Initialized list of cities CitiesInMichigan = ["Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"] # Get user input inCity = input("Enter name of city: ") # Write your test statement here to see if there is a match. for i in range(len(Citie...
[ "Your while loop is unnecessary and your else clause should simply be moved outside of the loop. You also need to loop all the way back to your initial input if a city is not found.\ncityFound = False\nwhile not cityFound:\n inCity = input(\"Enter name of city: \")\n for i in range(len(CitiesInMichigan)):\n i...
[ 1, 1, 0 ]
[]
[]
[ "arraylist", "for_loop", "python", "while_loop" ]
stackoverflow_0074280849_arraylist_for_loop_python_while_loop.txt
Q: ModuleNotFound error only in Flask subfolders, not in root I am having a very annoying problem with module imports within a Flask app. This is my file structure: root > app > views > tests In the views folder, there is a file called data.py. I wish to import this into a file called test_data.py in tests: from app...
ModuleNotFound error only in Flask subfolders, not in root
I am having a very annoying problem with module imports within a Flask app. This is my file structure: root > app > views > tests In the views folder, there is a file called data.py. I wish to import this into a file called test_data.py in tests: from app.views import data This gives a ModuleNotFound error, saying th...
[ "So, if your test_data.py is inside tests, and you wish to import data.py from views folder, you need to tell python to look into the folder specifically. You can do this in your test_data.py using this:\nimport sys\nsys.path.insert(1, '/root/app/views')\n\nimport data\n\nremember that the path is the absolute path...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074281115_python.txt
Q: How to improve this loop to group objects based on one field I'm trying to improve my code a little bit but not sure if it is even possible. I have sqlalchemy model which contains fields like category, name, img_path. After I fetch all of the objects, I need to group them into categories to get the following resul...
How to improve this loop to group objects based on one field
I'm trying to improve my code a little bit but not sure if it is even possible. I have sqlalchemy model which contains fields like category, name, img_path. After I fetch all of the objects, I need to group them into categories to get the following result: [{"category":"some category", "skills":[{"name": "some name", "...
[ "Your starting code is already pretty good, one thing you could improve is using defaultdict(list) instead of plain dict, which will take care of initializing empty list for new categories, e.g.\nfrom collections import defaultdict \n\n_categories = defaultdict(list)\n\nfor skill in skills:\n _categories[skill.c...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074281107_python_sqlalchemy.txt
Q: Filter out tuples with only one element I have a tuple containing coordinates for a list of nodes. The process I am attempting to complete needs a tuple with only 2-tuple or 3-tuples. I am trying to filter out any 1-tuples. G=nx.read_shp(r'C:\TestData\tl_2019_36013_roads.shp') pos = {k: v for k,v in enumerate(G.no...
Filter out tuples with only one element
I have a tuple containing coordinates for a list of nodes. The process I am attempting to complete needs a tuple with only 2-tuple or 3-tuples. I am trying to filter out any 1-tuples. G=nx.read_shp(r'C:\TestData\tl_2019_36013_roads.shp') pos = {k: v for k,v in enumerate(G.nodes())} X=nx.Graph() #Empty graph X.add_nodes...
[ "I guess the fastest and most pythonic way to filter this input is to use filter :)\nfiltered = filter(lambda x: len(x) > 1, input_list)\n\n" ]
[ 1 ]
[ "tuplelist = (40,), (40,21), (532, 234)\nnewlist = []\nfor i in tuplelist:\n if len(i) != 1:\n newlist.append(i)\n\n\nusing the len function, you can check if the length is not 1\nyou can also do this:\ntuplelist = (40,), (40,21), (532, 234)\nnewlist = []\n[newlist.append(i) for i in tuplelist if len(i) !...
[ -3 ]
[ "networkx", "python", "tuples" ]
stackoverflow_0074280983_networkx_python_tuples.txt
Q: storing a few variables from the same input-how? I am a beginner to python and I encountered a problem. This is what I wanted to do: If I I have 1 line that contains an input statement. while repeating the same line a few times by a loop, I want to store the data from the input and saving it from every repetition ...
storing a few variables from the same input-how?
I am a beginner to python and I encountered a problem. This is what I wanted to do: If I I have 1 line that contains an input statement. while repeating the same line a few times by a loop, I want to store the data from the input and saving it from every repetition without loosing the previous data. after finishing the...
[ "U can use split:\n# we suppose input is -> 1 2 3 4 u\n>>> (*i, j) = input().split()\n\n>>> print(i)\n['1', '2', '3', '4']\n\nHow to declare variables from an input() with different class ( int and str)\n", "You can store using a list and add to that list and keep on comparing data to it:\n\n\nlistNumbers = []#Cr...
[ 1, 1, 0 ]
[]
[]
[ "input", "pickle", "python", "store" ]
stackoverflow_0074280428_input_pickle_python_store.txt
Q: How do I fill in this incomplete script to return the sum of all divisors that are given? def sum_divisors(n): sum = 0 # Return the sum of all divisors of n, not including n return sum print(sum_divisors(0)) # 0 print(sum_divisors(3)) # Should sum of 1 # 1 print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9...
How do I fill in this incomplete script to return the sum of all divisors that are given?
def sum_divisors(n): sum = 0 # Return the sum of all divisors of n, not including n return sum print(sum_divisors(0)) # 0 print(sum_divisors(3)) # Should sum of 1 # 1 print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 # 55 print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 # 114 I attempted to f...
[ "This should work:\ndef sum_divisors(n):\n sum = 0\n for i in range(1, int(n/2 + 1)):\n if (n % i) == 0:\n sum = sum + i\n\nreturn sum\n\nBe careful: xrange is used in Python 2 while range is Python 3, more info at this other question.\n", "Use the sum() function to add a sequence.\nAnd yo...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074280972_python.txt
Q: A program that creates a list of several files Data files: file.json - athletes with the indication of the chest number, first and last name result.txt - results of the first attempt The time comes in the format "breast_number start HH:MM:SS,dst" and "breast_number finish HH:MM: SS, dst". What should be display...
A program that creates a list of several files
Data files: file.json - athletes with the indication of the chest number, first and last name result.txt - results of the first attempt The time comes in the format "breast_number start HH:MM:SS,dst" and "breast_number finish HH:MM: SS, dst". What should be displayed as a list: Result Occupied place|Chest number|Fi...
[ "You will want to import the json module and use the json.loads function to convert the json into a dict. Use loops to parse the dict and look at using f-strings to print the data out to the file.\n" ]
[ 0 ]
[]
[]
[ "json", "list", "python" ]
stackoverflow_0074281092_json_list_python.txt
Q: Fastapi how to return one field from nested model I have a user model which is linked to a status model. How do I return only one field from the status model? what i get now: "status": { "name": "figmer", "id": "4" }, what I want "status": "figmer" My models class UserBase(BaseModel): ...
Fastapi how to return one field from nested model
I have a user model which is linked to a status model. How do I return only one field from the status model? what i get now: "status": { "name": "figmer", "id": "4" }, what I want "status": "figmer" My models class UserBase(BaseModel): status_id: int = Field(default=1, title="status id")...
[ "JSON serialiation can be customized via json_encoders:\n\nBy default, models are serialised as dictionaries. If you want to serialise them differently, you can add models_as_dict=False when calling json() method and add the classes of the model in json_encoders\n\nfrom pydantic import BaseModel, Field\n\n\nclass P...
[ 0 ]
[]
[]
[ "fastapi", "pydantic", "python" ]
stackoverflow_0074279759_fastapi_pydantic_python.txt
Q: How to use single loop to obtain the given sequence? I want to use just 1 loop in python to obtain the sequence like (likes counter in second and miliseconds) 0 0.033 0.066 0.1 0.133 0.166 0.2.... Currently, I have to use two loops to obtain it as follows miliseconds =[0 0.033 0.066 0.1 0.133 0.166 0.2 0.233 0....
How to use single loop to obtain the given sequence?
I want to use just 1 loop in python to obtain the sequence like (likes counter in second and miliseconds) 0 0.033 0.066 0.1 0.133 0.166 0.2.... Currently, I have to use two loops to obtain it as follows miliseconds =[0 0.033 0.066 0.1 0.133 0.166 0.2 0.233 0.266 0.3 0.333 0.366 0.4 0.433 0.466 0.5 0.533 0.566 0.6 0....
[ "Use mathematics:\n# You can change second to '100'\nsecond = 3\nfor i in range((30 * second)+1):\n print(round(i/30, 4))\n \n # If you want to get full precision -> uncomment below line\n # print(i/30)\n\nOutput:\n0.0\n0.0333\n0.0667\n0.1\n0.1333\n0.1667\n0.2\n0.2333\n...\n2.7333\n2.7667\n2.8\n2.8333\n...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074281215_python_python_3.x.txt
Q: Closing a QDialog window that has been opened by another widget I think I've run into a problem similar to [StackOverflow -- How to close a QDialog][1] but I'm not seeing a solution if one was given. I've mocked two scripts similar to what I am having troubles with below. mainWidget.py from PyQt5 import QtCore, Qt...
Closing a QDialog window that has been opened by another widget
I think I've run into a problem similar to [StackOverflow -- How to close a QDialog][1] but I'm not seeing a solution if one was given. I've mocked two scripts similar to what I am having troubles with below. mainWidget.py from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMessageBox import shelve ...
[ "Current work around: in method passString of script mainWidget.py\ndef passString(self):\n stringToPass = self.lineEdit.text()\n \n openingDialog = QMessageBox()\n openingDialog.setWindowTitle(\"Warning\")\n openingDialog.setText(\"Are sure you want to pass the string: {}?\".form...
[ 0 ]
[]
[]
[ "pyqt5", "python", "qdialog" ]
stackoverflow_0074279367_pyqt5_python_qdialog.txt
Q: Why do I get product details ONLY from the first web page instead of all the 25pages I have a python script I divided into different functions. My first function 'get_url' is supposed to get the product url after the user have inputted the required product name in the prompt. I want to get the product details in a...
Why do I get product details ONLY from the first web page instead of all the 25pages
I have a python script I divided into different functions. My first function 'get_url' is supposed to get the product url after the user have inputted the required product name in the prompt. I want to get the product details in all the pages of the site. Now when i run my code, I get product details ONLY from the firs...
[ "The function get_url() has a loop that ends with return. So the function stops working after the first cycle. It generates one URL, returns it and that's all it does.\nTo fix that you can collect all urls into a variable inside the function and return it or change return to yield. This yield will turn your functio...
[ 1 ]
[]
[]
[ "python", "selenium", "web_site_project" ]
stackoverflow_0074263454_python_selenium_web_site_project.txt
Q: getting the span text from bs4 I have a number of text items contained in span tags that i need to extract. I am able to do this in a list comp in the class table-main__odds as shown. I need to get the same info fronm the table-main__odds coloured tag. The logic below does not return any values. any help is apprec...
getting the span text from bs4
I have a number of text items contained in span tags that i need to extract. I am able to do this in a list comp in the class table-main__odds as shown. I need to get the same info fronm the table-main__odds coloured tag. The logic below does not return any values. any help is appreciated? import requests from bs4 impo...
[ "Try:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.betexplorer.com/soccer/england/premier-league/results/\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\n\ndef get_odd_or_text(td):\n if \"data-odd\" in td.attrs:\n return td[\"data-odd...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074281093_beautifulsoup_python_web_scraping.txt
Q: Python script to merge PDF files with a blank page I have the following script compiled from other's suggestions, but I can't seem to get it to run properly. I need to merge several 3 page bill files into a single file for printing while adding a blank page in between each bill file so that each bill prints prope...
Python script to merge PDF files with a blank page
I have the following script compiled from other's suggestions, but I can't seem to get it to run properly. I need to merge several 3 page bill files into a single file for printing while adding a blank page in between each bill file so that each bill prints properly (we don't want the first page of one bill printed on...
[ "# If the file errors with \"no module PyPDF2\" then from command line, run pip install PyPDF2\nimport os\nfrom os import listdir, mkdir, startfile\nfrom os.path import isfile, join, exists\nfrom PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter\n\n#Input file path and print the pdf files in that path\npath...
[ 1 ]
[]
[]
[ "pdf", "python" ]
stackoverflow_0074281106_pdf_python.txt
Q: 3 arguments turned into a 2-tuple Define a function named generate_point which takes 3 arguments (i.e. 2 numbers and a 6-tuple), and returns a 2-tuple. Ex. Given inputs: , and c0, 1, 2, 3, 4, 5 the function shall calculate and return 1 and 1 respectively as follows: 1 = 0 + 1 + 2 1 = 3 + 4 + 5 I was given the sh...
3 arguments turned into a 2-tuple
Define a function named generate_point which takes 3 arguments (i.e. 2 numbers and a 6-tuple), and returns a 2-tuple. Ex. Given inputs: , and c0, 1, 2, 3, 4, 5 the function shall calculate and return 1 and 1 respectively as follows: 1 = 0 + 1 + 2 1 = 3 + 4 + 5 I was given the shell for generate_point as def generate...
[ "You need to unpack your input tuple, and then just return exactly what the prompt says.\nYou can unpack your 6-tuple like this:\nc0, c1, c2, c3, c4, c5 = cff\n\n" ]
[ 0 ]
[]
[]
[ "arguments", "function", "python", "tuples" ]
stackoverflow_0074281297_arguments_function_python_tuples.txt
Q: How to run a function in python only first time the code is running? I have written a function that will install the Module required to run a script. My problem is that the function runs every time the script is running. I need to run the function only the first time the script is running so that after installing ...
How to run a function in python only first time the code is running?
I have written a function that will install the Module required to run a script. My problem is that the function runs every time the script is running. I need to run the function only the first time the script is running so that after installing the module the function does not run every time the script is running. My ...
[ "I am not sure what you mean by running the script only the first time the script is running?.\ndoes that mean you want to run the script only once per computer/VM?.\nby the looks of it, it seems that the script that you want to run is for handling dependencies and packaging management, if that is the case I would ...
[ 0, 0 ]
[]
[]
[ "function", "module", "python" ]
stackoverflow_0069389165_function_module_python.txt
Q: My for loop keyword "item" is greyed out, out of no where I have been trying to make a for loop assign values to 8 variables in a list but the for loop "item" keyword is greyed out, and I am 99.999% sure that I did it right please help. G1l1x = 0 G2l1x = 0 G3l1x = 0 G4l1x = 0 G5l1x = 0 G6l1x = 0 G7l1x = 0 G8l1x = ...
My for loop keyword "item" is greyed out, out of no where
I have been trying to make a for loop assign values to 8 variables in a list but the for loop "item" keyword is greyed out, and I am 99.999% sure that I did it right please help. G1l1x = 0 G2l1x = 0 G3l1x = 0 G4l1x = 0 G5l1x = 0 G6l1x = 0 G7l1x = 0 G8l1x = 0 Cx = [G1l1x,G2l1x,G3l1x,G4l1x,G5l1x,G6l1x,G7l1x,G8l1x] for ...
[ "You can't reassign the item variable within for loop because \"item\" isn't pointing to a certain element.\n for i in range(len(Cx)):\n Cx[i] = 1000\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074281301_python.txt
Q: Installation: Reportlab: "ImportError: No module named reportlab.lib" I've installed reportlab, via pip install reportlab (also tried via easy_install reportlab ) ..but I get the above error. There are other RL imports before that - it's the .lib that it's objecting to. I've had RL working great in the past, but...
Installation: Reportlab: "ImportError: No module named reportlab.lib"
I've installed reportlab, via pip install reportlab (also tried via easy_install reportlab ) ..but I get the above error. There are other RL imports before that - it's the .lib that it's objecting to. I've had RL working great in the past, but IT reimaged my computer, and I'm trying to rebuild it. The script works fi...
[ "Most of the times errors like this are caused by an broken package, either in the package it self or in one of it's dependencies. \nThe best way to resolve such a issue is to force-reinstall the package, it will reinstall the package and its dependencies potentially repairing the package. \nTo force-reinstall repo...
[ 28, 2, 0, 0 ]
[ "The best way to install ReportLab is use their .exe installer. They have installers for 32bit and 64bit.\nhttps://pypi.org/project/reportlab/2.7/\n", "may be you are missing the module try below command for the same:\npip install --upgrade --force-reinstall reportlab\n" ]
[ -1, -1 ]
[ "installation", "pip", "python", "reportlab" ]
stackoverflow_0038711221_installation_pip_python_reportlab.txt
Q: Python3.9 Module not found import error for local package ├── README.md ├── src/ │ └── ptmodeling │ ├── __init__.py │ ├── driver.py │ ├── features.py │ └── modeling.py └── tests/ When I run python3 driver.py from within the ptmodeling directory I get ModuleNotFoundError: No module named ...
Python3.9 Module not found import error for local package
├── README.md ├── src/ │ └── ptmodeling │ ├── __init__.py │ ├── driver.py │ ├── features.py │ └── modeling.py └── tests/ When I run python3 driver.py from within the ptmodeling directory I get ModuleNotFoundError: No module named 'ptmodeling' . I tried running from project root, adding everyt...
[ "I don't see any problem here? Your question itself has the answer. And to your doubt, your code where you get an error won't work because python is looking into the ptmodeling folder inside the current directory. This means you're surfing through src/ptmodeling/ptmodeling which doesn't exist.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.9", "python_3.x" ]
stackoverflow_0074281365_python_python_3.9_python_3.x.txt
Q: PySimpleGUI change cprint output destination with param:window Have 2 Multiline elements in my window, 1 has param: reroute_cprint=True. When "Add" button is pressed I want to print to the 2:nd Multiline. Want to change the output destination for sg.cprint() in its paramaters, something like this: if event == -B_...
PySimpleGUI change cprint output destination with param:window
Have 2 Multiline elements in my window, 1 has param: reroute_cprint=True. When "Add" button is pressed I want to print to the 2:nd Multiline. Want to change the output destination for sg.cprint() in its paramaters, something like this: if event == -B_ADD-': sg.cprint("Text to print", window=window['-ML_QUE-'])...
[ "the correct code should be\nif event == -B_ADD-':\n sg.cprint(\"Text to print\", key='-ML_QUE-')\n\nIts the 'key' param that overrides the prev set cprint output destination, not the window param\n" ]
[ 1 ]
[]
[]
[ "pysimplegui", "python" ]
stackoverflow_0074281318_pysimplegui_python.txt
Q: Capturing and Storing Request Data Using Playwright for Python I'm working with playwright in python (after giving up on a proxymob approach), and I'm trying to capture all the headers from a given request/response using the code: import asyncio from time import sleep from urllib import request from playwright.asy...
Capturing and Storing Request Data Using Playwright for Python
I'm working with playwright in python (after giving up on a proxymob approach), and I'm trying to capture all the headers from a given request/response using the code: import asyncio from time import sleep from urllib import request from playwright.async_api import async_playwright from playwright.sync_api import sync_...
[ "I am not used to use async and I am not sure of your question, but I think this is what you want:\nimport asyncio\nfrom playwright.async_api import async_playwright\n\n\nasync def main():\n async with async_playwright() as p:\n for browser_type in [p.chromium, p.firefox, p.webkit]:\n browser =...
[ 0 ]
[]
[]
[ "playwright", "python" ]
stackoverflow_0074280956_playwright_python.txt
Q: Starting interactive terminal in a Python image container I downloaded an image public.ecr.aws/lambda/python:3.6 from this link and I am trying to open an interactive terminal into this container image. I tried the following tree approaches and none of these opens up any interactive terminal: docker run -it publ...
Starting interactive terminal in a Python image container
I downloaded an image public.ecr.aws/lambda/python:3.6 from this link and I am trying to open an interactive terminal into this container image. I tried the following tree approaches and none of these opens up any interactive terminal: docker run -it public.ecr.aws/lambda/python:3.6 bash docker run -it public.ecr.aw...
[ "ok, here's the answer 1 year and 3 months late ;-) but hopefully will be useful for someone.\ndocker run -it --rm --entrypoint /bin/bash public.ecr.aws/lambda/python:3.9\n\nYou just need to overwrite entrypoint, which was set to a shell script in the base image:\nhttps://github.com/aws/aws-lambda-base-images/blob/...
[ 1, 0 ]
[]
[]
[ "amazon_ecr", "amazon_web_services", "aws_lambda", "docker", "python" ]
stackoverflow_0068618355_amazon_ecr_amazon_web_services_aws_lambda_docker_python.txt
Q: Filtering pandas dataframe on 2 columns I have the below dataframe. How can I filter it to find only unique emails that are in both event years (e.g. 2022 and 2023)? df_current = pd.DataFrame({'Email':['Bob_Jones@gmail.com', 'Mike_Smith@gmail.com', 'Mike_Smith@gmail.com', 'Bob_Jones@gmail.com'], 'Ti...
Filtering pandas dataframe on 2 columns
I have the below dataframe. How can I filter it to find only unique emails that are in both event years (e.g. 2022 and 2023)? df_current = pd.DataFrame({'Email':['Bob_Jones@gmail.com', 'Mike_Smith@gmail.com', 'Mike_Smith@gmail.com', 'Bob_Jones@gmail.com'], 'Tickets Sold':[1, 2, 1, 1], 'Year':['2022', '20...
[ "Try this out\nduplicates = df_current.duplicated(subset=['Email'], keep=False)\ndf_desired = df_current[duplicates]\n\n", "Here's another way you could use:\nimport pandas as pd\n\nresult = df_current.loc[df_current.groupby('Email')['Year'].transform('nunique') >= 2, :]\n\nprint(result)\n# Prints:\n# ...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074281319_pandas_python.txt
Q: How to delete lines which contains only numbers in python? I have a large text file in Python. Firstly, I want to read the text then, delete lines which have only numbers. Then, I open a new text file and write with my changes. If the line contains numbers and strings, I want to keep them. I tried with isdigit and...
How to delete lines which contains only numbers in python?
I have a large text file in Python. Firstly, I want to read the text then, delete lines which have only numbers. Then, I open a new text file and write with my changes. If the line contains numbers and strings, I want to keep them. I tried with isdigit and regex but I couldn't... e.g. I tried: but it deletes all lines ...
[ "Strip whitespace from the line before checking if it is all numbers.\nfor line in text_data:\n if line.strip().isdigit():\n # do what is required for a line with all numbers\n else:\n # do what is required for an alphanumeric line\n\n", "I think you just need to read the file, filter it if li...
[ 1, 0 ]
[]
[]
[ "file", "numbers", "python", "text_files" ]
stackoverflow_0074280704_file_numbers_python_text_files.txt
Q: Python Zero-Padding in Output Text File with "{0:+03f}".format() Not Working I have created a program that calculates a variable-coefficient regression, and am attempting to output those coefficients to a text file. I am trying to use string formatting to pad zeros in order to have the output file line up correctl...
Python Zero-Padding in Output Text File with "{0:+03f}".format() Not Working
I have created a program that calculates a variable-coefficient regression, and am attempting to output those coefficients to a text file. I am trying to use string formatting to pad zeros in order to have the output file line up correctly. The offending code is shown below: output.write("N = 1 Regression:\n") output.w...
[ "The first number in the format is the total number of digits (including decimal point and sign), not the number to the left of the decimal point. What you want is:\noutput.write(\"a = {0:+011.6f}\\n\".format(T_fit_N1params[0]))\n\nWhen the total width you specified isn't enough, it is automatically expanded to...
[ 1 ]
[]
[]
[ "python", "string_formatting", "text_files" ]
stackoverflow_0074281261_python_string_formatting_text_files.txt
Q: Program that calculates subtotal of prices is not functioning properly This code I have to write should display the subtotal, number of items, sales tax, and total cost When I run it, the program calculates the prices entered wrong, and only prompts me 2 times for a price, when it should prompt me until I tell it ...
Program that calculates subtotal of prices is not functioning properly
This code I have to write should display the subtotal, number of items, sales tax, and total cost When I run it, the program calculates the prices entered wrong, and only prompts me 2 times for a price, when it should prompt me until I tell it to stop. This program uses a while loop and sentinel to proccess the total o...
[ "I edited some lines:\n1 ) I take itemCost variable in while loop. Because loop will wants input one time.\n2 ) I changed your while condition and i added else condition. when itemCost == 0, loop will break.\nTAXRATE = 0.0625\nnumItems = 0\nsubTotal = 0\n\n\nwhile True:\n itemCost = float(input(\"Enter the price...
[ 0, 0 ]
[]
[]
[ "loops", "python", "while_loop" ]
stackoverflow_0074281205_loops_python_while_loop.txt
Q: Getting joint location(3D pose) w.r.t world of Kuka Iiwa arm in Drake I have a Kuka Iiwa 7 arm in the scene and I am interested in getting the current(real-time) 3D coordinates of the arm joints w.r.t world (or w.r.t robot base). I am able to get the current joint 1 DOF positions(thetas) but not the exact 3D coord...
Getting joint location(3D pose) w.r.t world of Kuka Iiwa arm in Drake
I have a Kuka Iiwa 7 arm in the scene and I am interested in getting the current(real-time) 3D coordinates of the arm joints w.r.t world (or w.r.t robot base). I am able to get the current joint 1 DOF positions(thetas) but not the exact 3D coordinate representing the position of the joint in some frame(world or base). ...
[ "When the parser creates a joint, it'll also crate a \"parent\" frame and a \"child\" frame. These two frames are then constrained by the joint such that in the \"zero configuration\" (say zero angle) the parent and child frames are coincident.\nIf you do happen to have the frame object, then you can call Frame::Ca...
[ 1 ]
[]
[]
[ "drake", "python", "robot", "transformation" ]
stackoverflow_0074279453_drake_python_robot_transformation.txt
Q: How do I check file modified in python as a boolean, so I can implement in IF Statement? Im trying to create a function where if file modified, then perform task. I am able to do this if a file exists by doing - import os file_path = 'C:/Hi/' if os.listdir(file_path): do xyz But how can i do xyz based on if a f...
How do I check file modified in python as a boolean, so I can implement in IF Statement?
Im trying to create a function where if file modified, then perform task. I am able to do this if a file exists by doing - import os file_path = 'C:/Hi/' if os.listdir(file_path): do xyz But how can i do xyz based on if a files date was modified? os.path.getmtime(file_path) Only gets the time but cant be used in my...
[ "Try:\nimport os \nimport time\nno_of_seconds_since_last_check = 30\nif time.time() - os.path.getmtime(file_path) < no_of_seconds_since_last_check : \n print(\"doing xyz\")\n\n\nThe if condition detects a file modification within the specified time span, preferably since the last check for modifications.\n", "...
[ 1, 0 ]
[]
[]
[ "if_statement", "listdir", "path", "python" ]
stackoverflow_0074281287_if_statement_listdir_path_python.txt
Q: JSONDecodeError: Expecting ',' delimiter: Error while trying to convert string to dictionary I have a txt file like this: text='{"id": "a364ebd4", "reason": "delay", "description": "I bought a tv. It's not working and the manager said it was "the best" "}' When I try to convert the string into a dict using json.lo...
JSONDecodeError: Expecting ',' delimiter: Error while trying to convert string to dictionary
I have a txt file like this: text='{"id": "a364ebd4", "reason": "delay", "description": "I bought a tv. It's not working and the manager said it was "the best" "}' When I try to convert the string into a dict using json.loads() textf = json.loads(text) textf I get the error JSONDecodeError: Expecting ',' delimiter: lin...
[ "If you look at the final value in the dict (ie. the value of the \"description\" key, you will see that it contains a single ' in the word it's which breaks the text string. And there are also double quotes \" inside double quotes which create errors.\nYou should use this: instead\n'{\"id\": \"a364ebd4\", \"reason...
[ 0 ]
[]
[]
[ "data_science", "nlp", "python" ]
stackoverflow_0074281224_data_science_nlp_python.txt
Q: How do I fix this error? (Python SQLITE3) from typing import NewType import sqlite3 connection = sqlite3.connect("uids.db") cursor = connection.cursor() table = """CREATE TABLE USERS ( UID INT USERNAME VARCHAR(25) NOT NULL );""" cursor.execute("DROP TABLE IF EXISTS USERS") cursor....
How do I fix this error? (Python SQLITE3)
from typing import NewType import sqlite3 connection = sqlite3.connect("uids.db") cursor = connection.cursor() table = """CREATE TABLE USERS ( UID INT USERNAME VARCHAR(25) NOT NULL );""" cursor.execute("DROP TABLE IF EXISTS USERS") cursor.execute(table) print("table ok") uid = N...
[ "uid is type name. If you want to use interpolation, should be\n cursor.execute(f\"\"\"INSERT INTO USERS VALUES ({idx}, ?)\"\"\", (usrname,))\n\n", "Use placeholders for both variables, not just usrname. And the correct variable is idx.\ndef ucreate(idx: uid, usrname: str):\n cursor.execute(f\"\"\"INSERT IN...
[ 0, 0 ]
[]
[]
[ "cpython", "python", "sql", "sqlite" ]
stackoverflow_0074281440_cpython_python_sql_sqlite.txt
Q: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OperationalError: near ",": syntax error when I'm trying to remove specific things from my Database (sqlite3) it's giving me error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Operation...
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OperationalError: near ",": syntax error
when I'm trying to remove specific things from my Database (sqlite3) it's giving me error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OperationalError: near ",": syntax error for some reasons, here's the needed code: c.execute("DELETE FROM accounts WHERE email=?, password=?",...
[ "You need to use AND so:\n\"DELETE FROM accounts WHERE email=? AND password=?\"\n\n" ]
[ 0 ]
[]
[]
[ "discord.py", "pycord", "python", "sqlite" ]
stackoverflow_0074281550_discord.py_pycord_python_sqlite.txt
Q: I can't seem to understand this error: Picture.GetFrameColour() missing 1 required positional argument: 'self' class Picture: # PRIVATE Pdescription : STRING # PRIVATE Pwidth : INTEGER # PRIVATE Pheight : INTEGER # PRIVATE Pframecolour : STRING def __init__(self, Pdescription, Pwidth, Pheight, ...
I can't seem to understand this error: Picture.GetFrameColour() missing 1 required positional argument: 'self'
class Picture: # PRIVATE Pdescription : STRING # PRIVATE Pwidth : INTEGER # PRIVATE Pheight : INTEGER # PRIVATE Pframecolour : STRING def __init__(self, Pdescription, Pwidth, Pheight, Pframecolour): self.__Description = Pdescription self.__Width = Pwidth self.__Height = Pheig...
[ "myArray = [Picture for i in range(100)] creates a list with 100 references to the Picture class. Later, you append instances to the array (myArray.append(item)) but those append after the 100 class references that you put at the front. You don't need to pre-initialize the array; just create an empty one\nmyArray =...
[ 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074281455_oop_python.txt
Q: add row to a csv file with python I have two csv files that each have 2 columns, one of them being the date. I want to add the second column of the second file to the first file, resulting a file with 3 columns. I did it by creating a new file and appending the data to it this way: import csv coinsfile = open('to...
add row to a csv file with python
I have two csv files that each have 2 columns, one of them being the date. I want to add the second column of the second file to the first file, resulting a file with 3 columns. I did it by creating a new file and appending the data to it this way: import csv coinsfile = open('total-bitcoins.csv', newline='') pricesfi...
[ "res is a file handle, so the append method doesn't apply to it. So there's an attribute error while the output file is opened, which results in an empty output file (or, yes, one of the input files is empty, ending zip immediately, but this answer explains how to fix the next issues)\nA quickfix would be:\nres.wri...
[ 1, 0 ]
[]
[]
[ "csv", "file", "python" ]
stackoverflow_0051584192_csv_file_python.txt
Q: MongoEngine cannot connect through Atlas Uri string. Tried everything I'm new to programming and am building my first app.. I'm building a kivy app trying to use mongoDB as the database. I can connect to a localhost to query and create documents. I cannot get it to connect to the atlas no matter what I try. I'm al...
MongoEngine cannot connect through Atlas Uri string. Tried everything
I'm new to programming and am building my first app.. I'm building a kivy app trying to use mongoDB as the database. I can connect to a localhost to query and create documents. I cannot get it to connect to the atlas no matter what I try. I'm also using Pycharm and a venv. Heres the basic info: import pymongo from pym...
[ "Have you tried using MongoClient(connection_string, tlsCAFile=certifi.where()) ?\n\nCertifi provides Mozilla’s carefully curated collection of Root\nCertificates for validating the trustworthiness of SSL certificates\nwhile verifying the identity of TLS hosts.\n\nBefore testing the new code remember to do \"pip in...
[ 1 ]
[]
[]
[ "kivy", "mongodb", "mongoengine", "python", "ssl" ]
stackoverflow_0074280604_kivy_mongodb_mongoengine_python_ssl.txt
Q: Kivy slider override on_touch_up I am trying to build my first kivy app and create a simple audio cutting tool. I am using the slider widget to show the position in a playing song (that works so far) but I would like to enable the user to move the slider to a desired position and play the song from that chosen pos...
Kivy slider override on_touch_up
I am trying to build my first kivy app and create a simple audio cutting tool. I am using the slider widget to show the position in a playing song (that works so far) but I would like to enable the user to move the slider to a desired position and play the song from that chosen position. Code I have so far: file main....
[ "If you want to use on_touch_up, just replace on_release in your .kv file with it, all events can be called like that. You don't actually need to inherit the slider class.\non_touch_up is an event that is shared by all widgets because it is implemented in the widget class itself.\n", "First you have to change on_...
[ 0, 0 ]
[]
[]
[ "kivy", "python", "slider" ]
stackoverflow_0044628177_kivy_python_slider.txt
Q: SQLAlchemy error: An attempt to complete a transaction has failed. No corresponding transaction found I have installed: Ubuntu (18.04) Python (3.6.8) msodbcsql17 (Microsoft ODBC Driver 17 for SQL Server) SQLAlchemy (1.3.5) Pandas (0.24.2) and I want to create just a proof of concept using SQLAlchemy with an Azur...
SQLAlchemy error: An attempt to complete a transaction has failed. No corresponding transaction found
I have installed: Ubuntu (18.04) Python (3.6.8) msodbcsql17 (Microsoft ODBC Driver 17 for SQL Server) SQLAlchemy (1.3.5) Pandas (0.24.2) and I want to create just a proof of concept using SQLAlchemy with an Azure SQL Data Warehouse. However, when I try to run a query on Customer model which is mapped to the customers...
[ "The SQLAlchemy documentation for mssql+pyodbc://… has just been updated to include the following (for SQLA 1.4/2.0):\n\nAzure SQL Data Warehouse does not support transactions,\nand that can cause problems with SQLAlchemy's \"autobegin\" (and implicit\ncommit/rollback) behavior. We can avoid these problems by enabl...
[ 9, 2, 1 ]
[]
[]
[ "azure_sql_data_warehouse", "msodbcsql17", "pyodbc", "python", "sqlalchemy" ]
stackoverflow_0057123667_azure_sql_data_warehouse_msodbcsql17_pyodbc_python_sqlalchemy.txt
Q: input() function prevents new multiprocessing process to start when run through PyCharm I have a simple program (below) which does not behave as I expected when I run it through PyCharm. It behaves as expected when run through command prompt. It is a program that spawns a new process, but after that, reads input ...
input() function prevents new multiprocessing process to start when run through PyCharm
I have a simple program (below) which does not behave as I expected when I run it through PyCharm. It behaves as expected when run through command prompt. It is a program that spawns a new process, but after that, reads input from user using input() function. The problem is that when I use this function, the process d...
[ "Not happening on Linux. Even changing the multiprocessing set_start_method to spawn.\nCan you paste some screenshots or logs?\n", "You can normally fix this by checking the \"Emulate terminal in output console\" option in the run configuration.\n" ]
[ 0, 0 ]
[]
[]
[ "input", "multiprocessing", "multithreading", "python" ]
stackoverflow_0056456695_input_multiprocessing_multithreading_python.txt
Q: How to use Pcollection List length & values to partition Pcollection? I have dynamically fetched the data list from BigQuery, and transformed it into a so-called beam list, using a map transform I have calculated its length, now I want to use this length and list to partition the larger PCollection and then run so...
How to use Pcollection List length & values to partition Pcollection?
I have dynamically fetched the data list from BigQuery, and transformed it into a so-called beam list, using a map transform I have calculated its length, now I want to use this length and list to partition the larger PCollection and then run some transformations on individual partitions fanning out the operation. I am...
[ "Like others pointed out, you need side inputs here. You'd do something like this:\nwith beam.Pipeline(options=pipeline_options) as pipeline:\n sites_list = beam.pvalue.AsList(\n pipeline\n | \"Get site_id from D_Sites Table\"\n >> beam.io.ReadFromBigQuery(\n q...
[ 0 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074074789_apache_beam_google_cloud_dataflow_python.txt
Q: how do I access this json data in python? hi I'm pretty new at coding and I was trying to create a program in python that reads and save in another file the data inside a json file (not everything, just what I want). I googled how to parse data but there's something I don't understand. that's a part of the json fi...
how do I access this json data in python?
hi I'm pretty new at coding and I was trying to create a program in python that reads and save in another file the data inside a json file (not everything, just what I want). I googled how to parse data but there's something I don't understand. that's a part of the json file: ` { "profileRevision": 548789, "profileId...
[ "Access to JSON or dict element is realized by list indexes, please look at below example:\na = [\n {\n \"friends\": [\n {\n \"id\": 0,\n \"name\": \"Reba May\"\n }\n ],\n \"greeting\": \"Hello, Doris Gallagher! You have 2 unread messages.\",\n \"favoriteFruit\": \"strawberry\"\...
[ 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074281186_json_python.txt
Q: Display image with a zoom = 1 with Matplotlib imshow() (how to?) I want to display an image (say 800x800) with Matplotlib.pyplot imshow() function but I want to display it so that one pixel of the image occupies one pixel on the screen (zoom factor = 1, no shrink, no stretch). I'm a beginner, so do you know how to...
Display image with a zoom = 1 with Matplotlib imshow() (how to?)
I want to display an image (say 800x800) with Matplotlib.pyplot imshow() function but I want to display it so that one pixel of the image occupies one pixel on the screen (zoom factor = 1, no shrink, no stretch). I'm a beginner, so do you know how to proceed?
[ "Matplotlib isn't optimized for this. You'd be a bit better off with simpler options if you just want to display an image at one-pixel-to-one-pixel. (Have a look at Tkinter, for example.)\nThat having been said:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# DPI, here, has _nothing_ to do with your scr...
[ 29, 7, 0, 0 ]
[ "If you are trying to zoom in your image, then:\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\ndpi = 80\nmargin = 0.01 # The smaller it is, the more zoom you have\nxpixels, ypixels = your_image.shape[0], your_image.shape[1] ## \n\nfigsize = (1 + margin) * ypixels / dpi, (1 + margin) * xpixels / dpi\n\nfi...
[ -2 ]
[ "matplotlib", "python" ]
stackoverflow_0008056458_matplotlib_python.txt
Q: Is there a way to remove the side navigation bar containing file names in the latest version of streamlit? I recently upgraded streamlit to version 1.10.0. After upgradation I ran streamlit only to find that there is a side navigation bar displaying python file names present in my directory. I have attached images...
Is there a way to remove the side navigation bar containing file names in the latest version of streamlit?
I recently upgraded streamlit to version 1.10.0. After upgradation I ran streamlit only to find that there is a side navigation bar displaying python file names present in my directory. I have attached images for the same. import streamlit as st import pandas as pd from services.multiapp import MultiApp from functools ...
[ "Streamlit sidebar picks everything up that is located in the \"pages\" folder (see here: Blog Streamlit)\nYou could either rename your pages folder to something else or if you like the side bar, you can just collapse it initially:\nimport streamlit as st\nst.set_page_config(initial_sidebar_state=\"collapsed\")\n\n...
[ 2, 0, 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0072543675_python_streamlit.txt
Q: Read floats from txt (that has special characters [ ] ) and store them into 2D array I have the following .txt file: [0.03932153 0.10188484 0.23541254 0.18962094 0.43376015] [0.0453733 0.13984493 0.62747017 0.15459015 0.03272145] [0.0299296 0.1038427 0.74556143 0.03760473 0.08306153] [0.14998161 0.2...
Read floats from txt (that has special characters [ ] ) and store them into 2D array
I have the following .txt file: [0.03932153 0.10188484 0.23541254 0.18962094 0.43376015] [0.0453733 0.13984493 0.62747017 0.15459015 0.03272145] [0.0299296 0.1038427 0.74556143 0.03760473 0.08306153] [0.14998161 0.22125856 0.00924835 0.01314869 0.60636278] [0.09769381 0.12554495 0.0330114 0.26816809...
[ "You could use a regex to extract the numbers, and then map those to float:\nwith open(\"test.txt\", \"r\") as f:\n result = [\n list(map(float, re.findall(r\"-?\\d+(\\.\\d+)?\", line)))\n for line in f.readlines() \n ]\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "python", "regex", "txt" ]
stackoverflow_0074281613_arrays_python_regex_txt.txt
Q: Parsing empty strings to 0 for numeric fields when parsing with Pydantic I have recently had to use Pydantic for parsing JSON documents, and given the nature of the project (which involves ingesting some old documents from crummy scans) it turns out that we will be implementing the module which generates the JSON ...
Parsing empty strings to 0 for numeric fields when parsing with Pydantic
I have recently had to use Pydantic for parsing JSON documents, and given the nature of the project (which involves ingesting some old documents from crummy scans) it turns out that we will be implementing the module which generates the JSON by analyzing the scans, and we are also the ones who are supposed to prepare t...
[ "It was a little hard to understand, what your actual setup is, but if I understood correctly, you define your own models. In that case, you just need to write a custom validator with the pre=True setting to turn any empty string into a numeric zero for fields with numeric types.\nIf you want a validator that is m...
[ 1 ]
[]
[]
[ "json", "parsing", "pydantic", "python" ]
stackoverflow_0074279037_json_parsing_pydantic_python.txt
Q: Python - Adding a digit to a integer how do i add a digit to an integer in python ? value = 9 #add a 9 to "value" to get 99 print(value) So i want the console to return : 99 I tryed to do value.append(9) but it didnt work A: I think you could convert your number to a string, add those together, and then con...
Python - Adding a digit to a integer
how do i add a digit to an integer in python ? value = 9 #add a 9 to "value" to get 99 print(value) So i want the console to return : 99 I tryed to do value.append(9) but it didnt work
[ "I think you could convert your number to a string, add those together, and then convert it back into an integer. Something like\nvar1 = \"9\"\nvar2 = var1 + var1\nconvertedAnswer = int(var2)\nprint(convertedAnswer)\ncould work?\n", "You can convert int to str, concatenate the strings, and the convert back to int...
[ 1, 0 ]
[]
[]
[ "integer", "python" ]
stackoverflow_0074281636_integer_python.txt
Q: Try send data to OpenCTI I am trying to send data to my server (Opencti). This data is a migration from one internal database to Opencti. Apparently, the OpenCTI is working well, and the portal web is working. This is my docker-compose.yml: enter version: '3' services: redis: ...
Try send data to OpenCTI
I am trying to send data to my server (Opencti). This data is a migration from one internal database to Opencti. Apparently, the OpenCTI is working well, and the portal web is working. This is my docker-compose.yml: enter version: '3' services: redis: image: redis:7...
[ "In the python script you must put the API Key that is provided from OpenCTI. The UUID generated for the .env file isn't correct. Please reference the documentation https://opencti-client-for-python.readthedocs.io/en/3.3.0/client_usage/getting_started.html\n # OpenCTI API client initialization\nopencti_api_clien...
[ 0 ]
[]
[]
[ "docker", "docker_compose", "python", "server" ]
stackoverflow_0073624409_docker_docker_compose_python_server.txt
Q: read excel file that need to skip row and footer with dataflow I need to read a high number of excel file into bigquery from google cloud storage. Each of these file needs to have the skiprows and skipfooter arguments. I am thinking about using DataFlow. However I have no idea how to proceed What I have attempted ...
read excel file that need to skip row and footer with dataflow
I need to read a high number of excel file into bigquery from google cloud storage. Each of these file needs to have the skiprows and skipfooter arguments. I am thinking about using DataFlow. However I have no idea how to proceed What I have attempted if __name__ == '__main__': parser = argparse.ArgumentParser(descr...
[ "You will need to implement a DoFn that consumes each individual excel file in Python. You can do something like this:\np\n| fileio.MatchFiles(options.input)\n| ParDo(ConsumeExcelFiles())\n\nWhere your DoFn is:\nclass ConsumeExcelFiles(beam.DoFn):\n def process(self, filename):\n import openpyxl\n local_file...
[ 0 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "google_cloud_storage", "python" ]
stackoverflow_0074136969_apache_beam_google_cloud_dataflow_google_cloud_storage_python.txt
Q: 'Image' object is not callable I've been playing around with stable diffusion on Google colab, and I've been having some trouble getting a grid to work. Every time I run my image generator block, it gets through the generation but can't display the images, it gives me the error stated in the title. def image_grid(...
'Image' object is not callable
I've been playing around with stable diffusion on Google colab, and I've been having some trouble getting a grid to work. Every time I run my image generator block, it gets through the generation but can't display the images, it gives me the error stated in the title. def image_grid(imgs, rows, cols): assert len(i...
[ "First, removed [0], then changed 'return grid()' to 'return grid'\nThanks, OneCricketeer.\n" ]
[ 0 ]
[]
[]
[ "python", "stable_diffusion" ]
stackoverflow_0074281508_python_stable_diffusion.txt