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: I cannot install Django, And give "Installation failled" I want to install Django,But when I run pipenv install django it create virtual environment and then give Installation Failed. Before try below codes I run pip install django to install Django. And there is no issue with internet connection. How do I fix t...
I cannot install Django, And give "Installation failled"
I want to install Django,But when I run pipenv install django it create virtual environment and then give Installation Failed. Before try below codes I run pip install django to install Django. And there is no issue with internet connection. How do I fix this? I tried pip install django , pipenv install django
[ "Navigate to your desired folder, then:\n# Creates the virtual environment\npython -m venv venv\n\n# Activate your venv\nMac/Linux: source venv/bin/activate\nWindows: .\\venv\\Scripts\\activate\n\n# Update pip and install django\npip install --upgrade pip\npip install Django\n\nRemember that virual environment is a...
[ 0 ]
[]
[]
[ "backend", "django", "python" ]
stackoverflow_0074555783_backend_django_python.txt
Q: can you explain this logic explain this logic input:ABDEF output:GFECB input:ZZZ output:AAA write a program this logic A: A B D E F 1 2 4 5 6 G F E C B 7 6 5 3 2 Z Z Z 26 26 26 A A A 1 1 1 Basically its just reversing and adding 1 .Or Right shift by 1 all letters. You can use ord for implementing this. ...
can you explain this logic
explain this logic input:ABDEF output:GFECB input:ZZZ output:AAA write a program this logic
[ "A B D E F\n1 2 4 5 6\n\nG F E C B\n7 6 5 3 2\n\nZ Z Z \n26 26 26\n\nA A A\n1 1 1\n\nBasically its just reversing and adding 1 .Or Right shift by 1 all letters.\nYou can use ord for implementing this.\nSample code:\nx='A'\nb=ord(x)+1\nprint(chr(b))\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074555827_python.txt
Q: Print a dictionary into a table I have a dictionary: dic={'Tim':3, 'Kate':2} I would like to output it as: Name Age Tim 3 Kate 2 Is it a good way to first convert them into a list of dictionaries, lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}] and then write them into a table, by the method in https...
Print a dictionary into a table
I have a dictionary: dic={'Tim':3, 'Kate':2} I would like to output it as: Name Age Tim 3 Kate 2 Is it a good way to first convert them into a list of dictionaries, lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}] and then write them into a table, by the method in https://stackoverflow.com/a/10373268/15645...
[ "Rather than convert to a list of dictionaries, directly use the .items of the dict to get the values to display on each line:\nprint('Name Age')\nfor name, age in dic.items():\n print(f'{name} {age}')\n\nIn versions before 3.6 (lacking f-string support), we can do:\nprint('Name Age')\nfor name, age in dic.items...
[ 11, 11, 4, 4, 1, 1, 0 ]
[ "To improve upon Francis Colas's answer, you can make it simpler by using f strings:\nprint('Name Age')\nfor name, age in dic.items():\n print(f'{name} {age}')\n\n" ]
[ -1 ]
[ "dictionary", "python", "python_2.7" ]
stackoverflow_0029265002_dictionary_python_python_2.7.txt
Q: How to add element from last loop iteration to list in python? I have this list: t=['a','b','c'] and want to create the output such as: ['a'] ['a','b'] ['a','b','c'] I am not sure how to adjust this loop: for i in t: print(i) I am not sure how to write the loop to create this appending effect from the last it...
How to add element from last loop iteration to list in python?
I have this list: t=['a','b','c'] and want to create the output such as: ['a'] ['a','b'] ['a','b','c'] I am not sure how to adjust this loop: for i in t: print(i) I am not sure how to write the loop to create this appending effect from the last iteration and the current iteration. I hope someone can assist. Thanks...
[ "For beginners I think this is the simple approach..!\nCode:-\nlis=['a','b','c']\nres=[]\nfor i in range(len(lis)):\n temp=[]\n for j in range(i+1):\n temp.append(lis[j])\n res.append(temp)\nprint(res)\n\nOutput:-\n[['a'], ['a', 'b'], ['a', 'b', 'c']]\n\n", "Solution without nested loop:\nl = ['a'...
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074555146_python.txt
Q: Why am I getting a "TypeError: object of type 'NoneType' has no len()" for this using the len function on a set? I'm getting an error for a piece of python code I wrote that shouldn't This is the function I wrote and the input I gave it. #turn list of ints into set, remove val from set, and return the length of th...
Why am I getting a "TypeError: object of type 'NoneType' has no len()" for this using the len function on a set?
I'm getting an error for a piece of python code I wrote that shouldn't This is the function I wrote and the input I gave it. #turn list of ints into set, remove val from set, and return the length of the set without val. def foo(nums,val): sett = set(nums) sett_without_val = sett.remove(val) return len(sett...
[ "remove() method of set is changing it in-place, so\nsett_without_val = sett.remove(val)\n\nreturns None and assign it to the variable,\nworking code is\ndef foo(nums,val):\n sett = set(nums)\n sett.remove(val)\n return len(sett)\n\n\nprint(foo([3,2,2,3],3))\n\noutput:\n1\n\nExplanation:\n1. [3, 2, 2, 3] \...
[ 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0074555956_python_set.txt
Q: Access custom module in Azure ML subprocess / Edit PYTHONPATH inside of Azure ML pipeline I have the following project structure: . β”œβ”€β”€ my_custom_module β”‚ └── __init__.py β”‚ └── ... β”œβ”€β”€ scripts β”‚ β”œβ”€β”€ start_script.py β”‚ └── example.py I am running start_script.py inside of Azure M...
Access custom module in Azure ML subprocess / Edit PYTHONPATH inside of Azure ML pipeline
I have the following project structure: . β”œβ”€β”€ my_custom_module β”‚ └── __init__.py β”‚ └── ... β”œβ”€β”€ scripts β”‚ β”œβ”€β”€ start_script.py β”‚ └── example.py I am running start_script.py inside of Azure ML studio pipeline. Inside of start_script.py I need to run example.py by using: subprocess.run(...
[ "we cannot edit the PYTHONPATH inside the default pipeline. Instead, we can create the Data Science VM using the ARM template and make the custom modifications inside the current working directory.\nUbuntu Based:\n# create a Ubuntu Data Science VM in your resource group\naz vm create --resource-group YOUR-RESOURCE-...
[ 1 ]
[]
[]
[ "azure", "azure_machine_learning_service", "azure_ml_pipelines", "python" ]
stackoverflow_0074519733_azure_azure_machine_learning_service_azure_ml_pipelines_python.txt
Q: 'WebDriver' object has no attribute 'find_element_by_name' Whenever I run the code it brings up the instagram page for about two seconds until it closes and then it gives me this error: 'WebDriver' object has no attribute 'find_element_by_name' Whenever I run the code it brings up the instagram page for about two ...
'WebDriver' object has no attribute 'find_element_by_name'
Whenever I run the code it brings up the instagram page for about two seconds until it closes and then it gives me this error: 'WebDriver' object has no attribute 'find_element_by_name' Whenever I run the code it brings up the instagram page for about two seconds until it closes and then it gives me this error: 'WebDri...
[ "find_element_by_name, and other methods starting with find_element_by, were deprecated in Selenium 4.0.0 with this commit and have been removed from Selenium as of version 4.3 with this pull request. The aforementioned PR has a comment saying how to update your code to use the find_element() method instead of find...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074555404_python_selenium_selenium_webdriver.txt
Q: I activate venv in vscode but it doesnt appear in terminal I have no idea whats going on but I activated venv by using Scripts/activate and it doesnt working yet, the (venv) isnt appearing please someone could help me? I tried everything I could find lol A: It looks like you are using Git Bash or a similar bash-...
I activate venv in vscode but it doesnt appear in terminal
I have no idea whats going on but I activated venv by using Scripts/activate and it doesnt working yet, the (venv) isnt appearing please someone could help me? I tried everything I could find lol
[ "It looks like you are using Git Bash or a similar bash-like system for Windows. You need to run Scripts/activate.sh in this environment.\nFor PowerShell, use Scripts/activate.ps1, and for cmd use Scripts/activate.bat.\n", "What terminal are you using? Please create a new powershell or cmd terminal. Also you shou...
[ 0, 0 ]
[]
[]
[ "python", "python_venv", "visual_studio_code" ]
stackoverflow_0074550767_python_python_venv_visual_studio_code.txt
Q: Removing a node from a linked list I would like to create a delete_node function that deletes the node at the location in the list as a count from the first node. So far this is the code I have: class node: def __init__(self): self.data = None # contains the data self.next = None # contains the...
Removing a node from a linked list
I would like to create a delete_node function that deletes the node at the location in the list as a count from the first node. So far this is the code I have: class node: def __init__(self): self.data = None # contains the data self.next = None # contains the reference to the next node class linke...
[ "You shouldn't literally delete a node in Python. If nothing points to the node (or more precisely in Python, nothing references it) it will be eventually destroyed by the virtual machine anyway.\nIf n is a node and it has a .next field, then:\nn.next = n.next.next \n\nEffectively discards n.next, making the .next ...
[ 19, 6, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0004654953_linked_list_python.txt
Q: how to reinstall a python environment offline? I have server without Internet connection. I would to copy the current python environment from another machine (installed by pip and conda) to this server by disk. That is I need to know which packages are installed, download these package and reinstall these package...
how to reinstall a python environment offline?
I have server without Internet connection. I would to copy the current python environment from another machine (installed by pip and conda) to this server by disk. That is I need to know which packages are installed, download these package and reinstall these package in the server. Is there any way to manage the whole...
[ "Use pip freeze to create a list of installed packages and pip download to download them. Move them to your offline location and install them all with pip install:\n$ pip freeze > requirements.txt\n$ pip download -r ../requirements.txt -d packages\n$ # move packages/* to offline host\n\noffline_host$ pip install pa...
[ 2 ]
[]
[]
[ "conda", "pip", "python" ]
stackoverflow_0074555903_conda_pip_python.txt
Q: How to calculate peaks and valleys with first and last element using Numpy in performant way? I want to find peaks and valleys in a single array and I have achieved this using the link. However, pv does not include the first element and the last element. How can I do it? import numpy as np import matplotlib.pyplot...
How to calculate peaks and valleys with first and last element using Numpy in performant way?
I want to find peaks and valleys in a single array and I have achieved this using the link. However, pv does not include the first element and the last element. How can I do it? import numpy as np import matplotlib.pyplot as plt %matplotlib inline # example data with peaks: x = np.linspace(-1,3,1000) data = -0.1*np.co...
[ "Here is how you can do this:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# example data with peaks:\nx = np.linspace(-1, 3, 1000)\ndata = -0.1 * np.cos(12 * x) + np.exp(-((1 - x) ** 2))\n\n# ___ detection of local minimums and maximums ___\n\npv = np.diff(np.sign(np.diff(data))).nonzero()[0] + 1\np...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074555806_numpy_python.txt
Q: regex to add space b/w alphabet and number I have a string that has characters and numbers string is like iPhone8s i want the output to be iPhone 8s I have written this code s = 'iPhone8s' re.sub('(\d+(\.\d+)?)', r' \1 ', s).strip() but it outputs iPhone 8 s how can i make the output to be iPhone 8s i only want ...
regex to add space b/w alphabet and number
I have a string that has characters and numbers string is like iPhone8s i want the output to be iPhone 8s I have written this code s = 'iPhone8s' re.sub('(\d+(\.\d+)?)', r' \1 ', s).strip() but it outputs iPhone 8 s how can i make the output to be iPhone 8s i only want it for string that contains iPhone in it, i dont...
[ "\ni only want it for string that contains iPhone\n\nthen you have to put the iPhone into the regex\nimport re\n\ns = 'iphone8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # iPhone 8s\n\ns = 'random8s'\ns = re.sub('iPhone(\\d+)', r'iPhone \\1', s, 0, re.IGNORECASE)\nprint(s) # random8...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074555621_python_regex.txt
Q: What if we put zero at the place of negative index in a string? name = "Deepesh" print(name[0:0]) # this does not print anything Q1. Why the above statement is not printing anything print(name[-5:0]) # this also does not print anything Q2. Why the given statement is not printing the value present from index -5 ...
What if we put zero at the place of negative index in a string?
name = "Deepesh" print(name[0:0]) # this does not print anything Q1. Why the above statement is not printing anything print(name[-5:0]) # this also does not print anything Q2. Why the given statement is not printing the value present from index -5 to -1? Thanks for reading! I have tried all the patterns similar to t...
[ "The first reason why it cannot be printed is that the slice is a left-closed-right intercept, that is, the right index is not included, so the result of [0:0] is the element that does not contain index 0.\nThe second slicing method is because the default way of slicing is to start slicing from left to right, [-5:0...
[ 0 ]
[]
[]
[ "arrays", "indexing", "python", "string" ]
stackoverflow_0074555940_arrays_indexing_python_string.txt
Q: How can we "associate" a Python context manager to the variables appearing in its block? As I understand it, context managers are used in Python for defining initializing and finalizing pieces of code (__enter__ and __exit__) for an object. However, in the tutorial for PyMC3 they show the following context manager...
How can we "associate" a Python context manager to the variables appearing in its block?
As I understand it, context managers are used in Python for defining initializing and finalizing pieces of code (__enter__ and __exit__) for an object. However, in the tutorial for PyMC3 they show the following context manager example: basic_model = pm.Model() with basic_model: # Priors for unknown model paramete...
[ "PyMC3 does this by maintaining a thread local variable as a class variable inside the Context class. Models inherit from Context.\nEach time you call with on a model, the current model gets pushed onto the thread-specific context stack. The top of the stack thus always refers to the innermost (most recent) model u...
[ 7, 4, 1 ]
[]
[]
[ "contextmanager", "pymc3", "python" ]
stackoverflow_0051849395_contextmanager_pymc3_python.txt
Q: Get input from the terminal, and send it into a channel in discord.py I have spent a decent amount of time trying to found some solution to this, as far as I am aware, no one has asked or done this online. So what I want is to get user input FROM THE TERMINAL, and then send in into a channel I specify(I don't need...
Get input from the terminal, and send it into a channel in discord.py
I have spent a decent amount of time trying to found some solution to this, as far as I am aware, no one has asked or done this online. So what I want is to get user input FROM THE TERMINAL, and then send in into a channel I specify(I don't need to change channels), and for getting the chat, I don't know how to print w...
[ "This can be achieved by creating a function to handle messages from the console:\n@client.event\nasync def sendFromConsole():\n run = True\n while run:\n message = input('Enter message: ')\n channel = client.get_channel(CHANNEL_ID)\n await channel.send(message)\n\nThis repeatedly asks for your...
[ 1 ]
[]
[]
[ "discord.py", "input", "python" ]
stackoverflow_0074478106_discord.py_input_python.txt
Q: python Gtk3 - Set label of button to default value of None I am trying to reset a label of a button to its initial (default) value of None, which does not work as expected. Here's the minimal example: from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk class GUI(Gtk.Window):...
python Gtk3 - Set label of button to default value of None
I am trying to reset a label of a button to its initial (default) value of None, which does not work as expected. Here's the minimal example: from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk class GUI(Gtk.Window): def __init__(self): super().__init__() se...
[ "I'm not sure what your use case is, but you can try adding a GtkLabel child and set the string there:\nfrom gi import require_version\nrequire_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\n\nclass GUI(Gtk.Window):\n\n def __init__(self):\n super().__init__()\n self.connect('destroy', Gtk...
[ 1 ]
[]
[]
[ "gtk", "gtk3", "pygtk", "python", "python_3.x" ]
stackoverflow_0074547290_gtk_gtk3_pygtk_python_python_3.x.txt
Q: Building basic terminal with Python and change directory function isn't changing directory cd function isn't changing directory for some reason! Whenever I use is on my terminal, it temporarly changes the directory, when i move to next command, action gets to be undone. import os import pathlib from os.path import...
Building basic terminal with Python and change directory function isn't changing directory
cd function isn't changing directory for some reason! Whenever I use is on my terminal, it temporarly changes the directory, when i move to next command, action gets to be undone. import os import pathlib from os.path import join path = os.getcwd() # DONE def ls(): os.listdir(path) print(os.listdir(path)) ...
[ "Notice how you set the initial value of path to os.getcwd and then you use it in the cd function.\nThis won't work like the cd command for every input because you can only access files and folders inside path.\nWhat inputs have you tried?\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074555861_python.txt
Q: Why do I get "RuntimeError: This event loop is already running"? I am running the following code that tries to get some information from https://cdn.ime.co.ir but it gives me this error: RuntimeError: This event loop is already running My code is: import requests import json import asyncio import websockets impo...
Why do I get "RuntimeError: This event loop is already running"?
I am running the following code that tries to get some information from https://cdn.ime.co.ir but it gives me this error: RuntimeError: This event loop is already running My code is: import requests import json import asyncio import websockets import urllib import random from threading import Thread connectionData =...
[ "You're in an IPython kernel. Don't run this in an IPython kernel. They changed their async handling a while back in a way that breaks this kind of thing; the kernel itself is running in the event loop already. (Terminal IPython works a bit differently, so this might still work in IPython in a terminal, but I'd sti...
[ 2, 0 ]
[]
[]
[ "asynchronous", "event_loop", "python", "runtime_error" ]
stackoverflow_0060926440_asynchronous_event_loop_python_runtime_error.txt
Q: Unable to get kafka connect redshift connector working Following the question and suggestions here: Kafka JDBCSinkConnector Schema exception: JsonConverter with schemas.enable requires "schema" and "payload", I am trying to sink records into redshift using redshift connector and a producer written in python. Here ...
Unable to get kafka connect redshift connector working
Following the question and suggestions here: Kafka JDBCSinkConnector Schema exception: JsonConverter with schemas.enable requires "schema" and "payload", I am trying to sink records into redshift using redshift connector and a producer written in python. Here is the connector config: connector.class=io.confluent.connec...
[ "As suggested by @OneCricketeer and confirmed, encoding was done twice, causing it to fail.\nSolution: Only encode the string read from the JSON file\nvalue_serializer=lambda v: v.encode('utf-8')\n\n" ]
[ 2 ]
[]
[]
[ "apache_kafka", "apache_kafka_connect", "confluent_kafka_python", "python" ]
stackoverflow_0074552956_apache_kafka_apache_kafka_connect_confluent_kafka_python_python.txt
Q: tensorflow.linalg.eig throwing error UnboundLocalError: local variable 'out_dtype' referenced before assignment I have below code import tensorflow as tf X_tf = tf.Variable([[25, 2, 9], [5, 26, -5], [3, 7, -1]]) lambdas_X_tf, V_X_tf = tf.linalg.eig(X_tf) when I execute it I get below error File "C:\Users\u1.conda...
tensorflow.linalg.eig throwing error UnboundLocalError: local variable 'out_dtype' referenced before assignment
I have below code import tensorflow as tf X_tf = tf.Variable([[25, 2, 9], [5, 26, -5], [3, 7, -1]]) lambdas_X_tf, V_X_tf = tf.linalg.eig(X_tf) when I execute it I get below error File "C:\Users\u1.conda\envs\py39\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 153, in error_handler raise e.with_trac...
[ "You need to set dtype as float32:\nX_tf = tf.Variable([[25, 2, 9], [5, 26, -5], [3, 7, -1]], dtype=tf.float32) \n\n" ]
[ 0 ]
[]
[]
[ "eigenvalue", "eigenvector", "linear_algebra", "python", "tensorflow" ]
stackoverflow_0074556086_eigenvalue_eigenvector_linear_algebra_python_tensorflow.txt
Q: Matplotlib bbox_inches issue I have this very simple code: import math import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*math.pi) fig, ax = plt.subplots() ax.plot(x,np.sin(x)) plt.savefig('sinwave.png', bbox_inches='tight') plt.show() So what I would expect is that there is white backgroun...
Matplotlib bbox_inches issue
I have this very simple code: import math import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*math.pi) fig, ax = plt.subplots() ax.plot(x,np.sin(x)) plt.savefig('sinwave.png', bbox_inches='tight') plt.show() So what I would expect is that there is white background inside my plotting area, but no ...
[ "fig = plt.figure()\nfig.patch.set_facecolor('white')\nfig.patch.set_alpha(0.6) #play with the alpha value\n\nax = fig.add_subplot(111)\nax.patch.set_facecolor('white')\nax.patch.set_alpha(0.0) #play with the alpha value\n\nThen simply plot here\nPlt.scatter(x,y)\nPlt.show()\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074556178_matplotlib_python.txt
Q: Is there a simple way to remove multiple spaces in a string? Suppose this string: The fox jumped over the log. Turning into: The fox jumped over the log. What is the simplest (1-2 lines) to achieve this, without splitting and going into lists? A: >>> import re >>> re.sub(' +', ' ', 'The quick brown ...
Is there a simple way to remove multiple spaces in a string?
Suppose this string: The fox jumped over the log. Turning into: The fox jumped over the log. What is the simplest (1-2 lines) to achieve this, without splitting and going into lists?
[ ">>> import re\n>>> re.sub(' +', ' ', 'The quick brown fox')\n'The quick brown fox'\n\n", "foo is your string:\n\" \".join(foo.split())\n\nBe warned though this removes \"all whitespace characters (space, tab, newline, return, formfeed)\" (thanks to hhsaffar, see comments). I.e., \"this is \\t a test\\n\"...
[ 826, 772, 127, 65, 57, 21, 19, 16, 15, 11, 10, 8, 4, 4, 4, 3, 3, 3, 3, 3, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0001546226_python_regex_string.txt
Q: List comprehension in nested ifs I am a newbie trying to understand list comprehensions in python. My question is different from another posts. I was asked to write list comprehension code to get the following output: All odd numbers from 1 to 30 (both inclusive). Those that are multiples of 5 will be marked with ...
List comprehension in nested ifs
I am a newbie trying to understand list comprehensions in python. My question is different from another posts. I was asked to write list comprehension code to get the following output: All odd numbers from 1 to 30 (both inclusive). Those that are multiples of 5 will be marked with an 'x'. [1, 3, '5x', 7, 9, 11, 13, '1...
[ "You cannot solve this problem in one line using list comprehension alone. You need the ternary operator (enclosed in the parentheses).\n[(n if n%5 else f'{n}x') for n in range(1,31) if n%2]\n\n", "If you don't care about the order of the items, you can avoid needing the ternary operator (conditional expression) ...
[ 3, 3, 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0074555777_list_comprehension_python.txt
Q: How to pass a custom equality_check function into perfplot I'm working with the perfplot library to compare the performance of three functions f1, f2 and f3. The functions are supposed to return the same values, so I want to do equality checks. However, all other examples of perfplot I can find on the internet use...
How to pass a custom equality_check function into perfplot
I'm working with the perfplot library to compare the performance of three functions f1, f2 and f3. The functions are supposed to return the same values, so I want to do equality checks. However, all other examples of perfplot I can find on the internet use pd.DataFrame.equals or np.allclose as an equality checker but t...
[ "If we inspect the source code, the way the equality check works is that it takes the output of the first function passed to kernels as reference and compares it to the output of the subsequent functions passed to kernels in a loop.\nFor some reason, the equality check is different depending on if the first functio...
[ 0 ]
[]
[]
[ "equality", "performance", "perfplot", "python" ]
stackoverflow_0074556381_equality_performance_perfplot_python.txt
Q: Unzip file in blob storage with blob storage trigger I have a task where I need to take a zipped file from an Azure Storage Container and spit back out the unzipped contents into said container... I've created a blob trigger with python to try and accomplish this task. From what I can tell, usually people who use ...
Unzip file in blob storage with blob storage trigger
I have a task where I need to take a zipped file from an Azure Storage Container and spit back out the unzipped contents into said container... I've created a blob trigger with python to try and accomplish this task. From what I can tell, usually people who use python unzip files using this method import zipfile with z...
[ "After reproducing from my end, I could able to achieve using the below code.\nimport logging\nimport azure.functions as func\nfrom azure.storage.blob import BlobServiceClient\nimport zipfile\nimport os\n\nblob_service_client = BlobServiceClient.from_connection_string(\"<YOUR_CONNECTION_STRING>\")\ndir_path = r'<PA...
[ 1 ]
[]
[]
[ "azure", "azure_blob_trigger", "azure_functions", "python", "unzip" ]
stackoverflow_0074395710_azure_azure_blob_trigger_azure_functions_python_unzip.txt
Q: Using parameters to return table column values? I want to be able to use a parameter to determine which columns value to return. But, since 'owner' is a model, the 'assetType' in 'owner.assetType' is treated as an attribute and not as the parameter. This is just an example of the code I'm working on. # Owner, by d...
Using parameters to return table column values?
I want to be able to use a parameter to determine which columns value to return. But, since 'owner' is a model, the 'assetType' in 'owner.assetType' is treated as an attribute and not as the parameter. This is just an example of the code I'm working on. # Owner, by default, owns 1 home, 2 boats, and 3 cars class Owner(...
[ "We can optimize the solution by directly calling getattr\ntry:\n print(f\"Owned {House1Type.title()}: {getattr(owner, House1Type)}\")\nexcept:pass\n\nWe can achieve GOAL by using same getattr\ndef findValue(assetType):\n return getattr(owner, str(assetType), None)\n\n\n# GOAL: return '1'\nval = findValue(Hou...
[ 0 ]
[]
[]
[ "peewee", "postgresql", "python" ]
stackoverflow_0074556386_peewee_postgresql_python.txt
Q: Calculate the maximum number of consecutive digits in a string of discontinuous digits My dataframe inside a column data is [1,1,2,3,4,7,8,8,15,19,20,21]. I want to get the most contiguous data segments in this column: [1,2,3,4]. How to calculate it? A: You can create groups by consecutive values by compare diff...
Calculate the maximum number of consecutive digits in a string of discontinuous digits
My dataframe inside a column data is [1,1,2,3,4,7,8,8,15,19,20,21]. I want to get the most contiguous data segments in this column: [1,2,3,4]. How to calculate it?
[ "You can create groups by consecutive values by compare difference with cumulative sum, get counts by GroupBy.transform and last filter maximal counts of original column col - output are all consecutive values with maximal counts:\ns = df['col'].groupby(df['col'].diff().ne(1).cumsum()).transform('size')\n\nout = df...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074556466_numpy_pandas_python.txt
Q: When transforming a list of integers (that contain nans) into dataframes they convert to floats If I have a list and I convert it to dataframes I have lista=[1,2,3] print(pd.DataFrame(lista) #Got a dataframe of ints but if I have listb=[1,2,3,np.nan] print(pd.DataFrame(listb) #Got a dataframe of floats This does...
When transforming a list of integers (that contain nans) into dataframes they convert to floats
If I have a list and I convert it to dataframes I have lista=[1,2,3] print(pd.DataFrame(lista) #Got a dataframe of ints but if I have listb=[1,2,3,np.nan] print(pd.DataFrame(listb) #Got a dataframe of floats This does not change if I specify dtype='int64' Is there a way that I can get a dataframe with ints?
[ "Use Int64 for integers with missing values:\nlistb=[1,2,3,np.nan]\nprint(pd.DataFrame(listb, dtype='Int64'))\n \n 0\n0 1\n1 2\n2 3\n3 <NA>\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074556525_pandas_python.txt
Q: matplotlib event doesn't work when I use button clicked connect in pyqt5 I have 2 class, one (Plot) is for plot matplotlib figure, another (Widget) is for pyqt5. When I create a button in pyqt5 and clicked_connect to class Plot to create figure, the button_press_event in Plot doesn't work. import pandas as pd imp...
matplotlib event doesn't work when I use button clicked connect in pyqt5
I have 2 class, one (Plot) is for plot matplotlib figure, another (Widget) is for pyqt5. When I create a button in pyqt5 and clicked_connect to class Plot to create figure, the button_press_event in Plot doesn't work. import pandas as pd import numpy as np from PyQt5.QtWidgets import * import matplotlib.pyplot as pl...
[ "for plotting a graph with PyQt you need an element to render it. This is the Figure Canvas. Using layout options and properties you can customize it to be full screen. I created an example where you can click on the button to get a plot in fullscreen. If you need the navigation toolbar you have to decide yourself....
[ 0 ]
[]
[]
[ "matplotlib", "pyqt5", "python" ]
stackoverflow_0074555885_matplotlib_pyqt5_python.txt
Q: How to I extract int value in string value and put it in int column? I have a dataframe with over 100,000 rows and 200 columns there are some nan values in FALLDOWN_FLOOR column so I would like to extract int value out of FALLDOWN_LOCATION and fill nan values in FALLDOWN_FLOOR. here is the example of FALLDOWN_LOCA...
How to I extract int value in string value and put it in int column?
I have a dataframe with over 100,000 rows and 200 columns there are some nan values in FALLDOWN_FLOOR column so I would like to extract int value out of FALLDOWN_LOCATION and fill nan values in FALLDOWN_FLOOR. here is the example of FALLDOWN_LOCATION COLUMN 9 λ„λ‘œμ˜† 옹벽/10μΈ΅ 10...
[ "Use Series.str.extract with digits before μΈ΅:\ndf['FALLDOWN_FLOOR'] = df['FALLDOWN_LOCATION'].str.extract(r'(\\d+)μΈ΅', expand=False)\nprint (df[['FALLDOWN_FLOOR','FALLDOWN_LOCATION']])\n FALLDOWN_FLOOR FALLDOWN_LOCATION\ni \n9 10 ...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074556563_numpy_pandas_python.txt
Q: Python/Selenium - Clear the cache and cookies in my chrome webdriver? I'm trying to clear the cache and cookies in my chrome browser (webdriver from selenium) but I can't find any solutions for specifically the chrome driver. How do I clear the cache and cookies in Python? Thanks! A: Taken from this post: For co...
Python/Selenium - Clear the cache and cookies in my chrome webdriver?
I'm trying to clear the cache and cookies in my chrome browser (webdriver from selenium) but I can't find any solutions for specifically the chrome driver. How do I clear the cache and cookies in Python? Thanks!
[ "Taken from this post:\nFor cookies, you can use the delete_all_cookies function: \ndriver.delete_all_cookies()\n\nFor cache, there isn't a direct way to do this through Selenium. If you are trying to make sure everything is cleared at the beginning of starting a Chrome driver, or when you are done, then you don't ...
[ 30, 8, 2, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriver" ]
stackoverflow_0050456783_python_selenium_selenium_chromedriver_selenium_webdriver_webdriver.txt
Q: How to find the count of same values in a row in a dataframe? The dataframe is as follows: a | b | c | d ------------------------------- TRUE FALSE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE I need to find the count of the TRUE...
How to find the count of same values in a row in a dataframe?
The dataframe is as follows: a | b | c | d ------------------------------- TRUE FALSE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE I need to find the count of the TRUE's in each column. The last row should contain the count as follows...
[ "Because Trues are processing like 1 you can use sum:\ndf['count'] = df.sum(axis=1)\n\nIf TRUEs are strings:\ndf['count'] = df.eq('TRUE').sum(axis=1)\n\n" ]
[ 1 ]
[]
[]
[ "count", "dataframe", "pandas", "python" ]
stackoverflow_0074556629_count_dataframe_pandas_python.txt
Q: How to merge two dataframes with different variations of a column values? I have two data frames that I want to merge on a same column name but the values can have different variations of a values. Examples. Variations of a value : Variations USA US United States United States of America The United States of...
How to merge two dataframes with different variations of a column values?
I have two data frames that I want to merge on a same column name but the values can have different variations of a values. Examples. Variations of a value : Variations USA US United States United States of America The United States of America And let's suppose the data frames as below: df1 = co...
[ "You simply create a reftable then merge\nYour data:\ndf = pd.DataFrame({'name':['USA', 'US', 'United States', 'FR', 'France'],\n 'val':[1,2,3,4,5]})\ndf\n\n name val\n0 USA 1\n1 US 2\n2 United States 3\n3 FR 4\n4 France 5\n\nY...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074555443_dataframe_pandas_python.txt
Q: Market Basket Association Analysis python or SQL I am using a dataset as below. Rows show invoice numbers, columns show products. I want to show the number of products on the same invoice as a matrix (i.e. there will be products in both rows and columns, the intersection of the row and column will show how many ti...
Market Basket Association Analysis python or SQL
I am using a dataset as below. Rows show invoice numbers, columns show products. I want to show the number of products on the same invoice as a matrix (i.e. there will be products in both rows and columns, the intersection of the row and column will show how many times those 2 products are on the same invoice. How can ...
[ "The OP made two mistakes here. The first one is the input to generate the intended Table 1 should be:\nimport pandas as pd\n\nids = ['invoice_1', 'invoice_2', 'invoice_3', 'invoice_4', 'invoice_5', 'invoice_6', 'invoice_7']\nA = [0, 0, 1, 0, 1, 1, 1]\nB = [0, 1, 1, 0, 1, 1, 1]\nC = [1, 1, 1, 0, 1, 0, 0]\nD = [1, 0...
[ 1 ]
[]
[]
[ "market_basket_analysis", "pandas", "python" ]
stackoverflow_0074551290_market_basket_analysis_pandas_python.txt
Q: When transforming a list of tuples to dataframes is there a way to keep the integers integers? If I have a list like this lista=[(0.11838, 0.1926, 0.12071, 0.27438, -0.0253, -0.18799, 0.01544, 0.24514, 0.19905, 0.18563, 0.19999, 0.25336, 783, 783, 783, 783), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, ...
When transforming a list of tuples to dataframes is there a way to keep the integers integers?
If I have a list like this lista=[(0.11838, 0.1926, 0.12071, 0.27438, -0.0253, -0.18799, 0.01544, 0.24514, 0.19905, 0.18563, 0.19999, 0.25336, 783, 783, 783, 783), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan), (nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan...
[ "Not during the DataFrame creation. Since np.nan is a float Dtype, the entire column is transformed into floats. The individual Dtypes will have to be transformed after the DataFrame is created.\nUse DataFrame.convert_dtypes:\ndf = pd.DataFrame(lista).convert_dtypes()\nprint (df)\n 0 1 2 ...
[ 2, 0 ]
[]
[]
[ "dataframe", "nan", "pandas", "python" ]
stackoverflow_0074556638_dataframe_nan_pandas_python.txt
Q: how to check every dictionary is perfect in list , python I have a data set as below tmp_dict = { 'a': ?, 'b': ?, 'c': ?, } and I have a data is a list of dictionaries like tmp_list = [tmp_dict1, tmp_dict2, tmp_dict3....] and I found some of dictionaries are not perfectly have keys about 'a','b','c'. How do I c...
how to check every dictionary is perfect in list , python
I have a data set as below tmp_dict = { 'a': ?, 'b': ?, 'c': ?, } and I have a data is a list of dictionaries like tmp_list = [tmp_dict1, tmp_dict2, tmp_dict3....] and I found some of dictionaries are not perfectly have keys about 'a','b','c'. How do I check and fill the key is not existing
[ "You could try something like this:\n# List of keys to look for in each dictionary\ndict_keys = ['a','b','c']\n\n# Generate the dictionaries for demonstration purposes only\ntmp_dict1 = {'a':[1,2,3], 'b':[4,5,6]}\ntmp_dict2 = {'a':[7,8,9], 'b':[10,11,12], 'c':[13,14,15]}\ntmp_dict3 = {'a':[16,17,18], 'c':[19,20,21]...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "fill", "list", "python" ]
stackoverflow_0074556605_dictionary_fill_list_python.txt
Q: backend_youtube_dl.py", line 54, in _fetch_basic self._dislikes = self._ydl_info['dislike_count'] KeyError: 'dislike_count' I have the below code that has been used to download youtube videos. I automatically detect if it's a playlist or single video. However all the sudden it is giving the above error. What can b...
backend_youtube_dl.py", line 54, in _fetch_basic self._dislikes = self._ydl_info['dislike_count'] KeyError: 'dislike_count'
I have the below code that has been used to download youtube videos. I automatically detect if it's a playlist or single video. However all the sudden it is giving the above error. What can be the problem? import pafy from log import * import tkinter.filedialog import pytube url = input("Enter url :") directory = tki...
[ "Your issue doesn't have anything to do with your code.\nYoutube does no longer have a dislike count, they simply removed it.\nYou just have to wait for the pafy package to be updated accordingly, or patch the package locally and remove that part by yourself.\nKeep in mind there are at least 5 different pull reques...
[ 5, 4, 4, 1, 1, 1, 0 ]
[]
[]
[ "pafy", "python" ]
stackoverflow_0070344739_pafy_python.txt
Q: Load facenet model I have tried almost all the answers on stackoverflow but nothing worked. Here is my code. from keras.models import load_model load_model('facenet_keras.h5') It is giving me this error ValueError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_577...
Load facenet model
I have tried almost all the answers on stackoverflow but nothing worked. Here is my code. from keras.models import load_model load_model('facenet_keras.h5') It is giving me this error ValueError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_5776\2622147163.py in ----...
[ "If you can recreate the architecture, in this case from [keras_facenet/inception_resnet_v1][1], then you can do:\nmodel = InceptionResNetV1(\n input_shape=(None, None, 3),\n classes=512,\n )\nmodel.load_weights('model.h5')\n\n" ]
[ 0 ]
[]
[]
[ "facenet", "keras", "python", "tensorflow" ]
stackoverflow_0074556149_facenet_keras_python_tensorflow.txt
Q: I want to save the output text as it is code import csv import pandas as pd data = [] with open("book1.csv", "r") as f: reader =csv.reader(f) next(reader) for row in reader: data.append(row[0]) print(data) df = pd.DataFrame(data) df.to_csv('save.csv', mode='a', header=True, index=False...
I want to save the output text as it is
code import csv import pandas as pd data = [] with open("book1.csv", "r") as f: reader =csv.reader(f) next(reader) for row in reader: data.append(row[0]) print(data) df = pd.DataFrame(data) df.to_csv('save.csv', mode='a', header=True, index=False) output (https://i.stack.imgur.com/8JSZL.pn...
[ "I was running through something similar to this and I do not remember that I could figure it out so I came up with a workaround.\n#replace '\\n' with '\\\\n'\ndf.replace('\\n', '\\\\n', inplace= True)\n# export normally\ndf.to_csv('path')\n\nwhenever you want to open it back, just read the file and again replace a...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074556687_python.txt
Q: What is the difference between torch.nn.functional.grid_sample and torch.nn.functional.interpolate? Let's say I have an image I want to downsample to half its resolution via either grid_sample or interpolate from the torch.nn.functional library. I select mode ='bilinear' for both cases. For grid_sample, I'd do the...
What is the difference between torch.nn.functional.grid_sample and torch.nn.functional.interpolate?
Let's say I have an image I want to downsample to half its resolution via either grid_sample or interpolate from the torch.nn.functional library. I select mode ='bilinear' for both cases. For grid_sample, I'd do the following: dh = torch.linspace(-1,1, h/2) dw = torch.linspace(-1,1, w/2) mesh, meshy = torch.meshgrid((d...
[ "Second for brevity. Grid_sample is more suitable for non-uniform interpolation.\n" ]
[ 0 ]
[]
[]
[ "bilinear_interpolation", "interpolation", "python", "python_3.x", "torch" ]
stackoverflow_0072373545_bilinear_interpolation_interpolation_python_python_3.x_torch.txt
Q: .txt file opened in python won't iterate properly The following contains abridged version of the code for a text card game I am trying to run. It should get a random string for a card from a random line in "cards.txt", and add it to a user's collection at "user.txt" (user would be the name of the user). A sample l...
.txt file opened in python won't iterate properly
The following contains abridged version of the code for a text card game I am trying to run. It should get a random string for a card from a random line in "cards.txt", and add it to a user's collection at "user.txt" (user would be the name of the user). A sample line from "users.txt" should look like: X* NameOfCard I...
[ "open(collectionPath, \"w+\") Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning.\nSo essentially you are erasing the contents of your file, and thus cannot read anything from it. You probab...
[ 1 ]
[]
[]
[ "file", "for_loop", "python", "txt" ]
stackoverflow_0074556826_file_for_loop_python_txt.txt
Q: How to convert number to words I'm beginner, i have homework that requires the user to input a number and it convert it to words.For example: 15342 to one five three four two this's my code, but it only work with a number: def convert_text(): arr = ['zero','one','two','three','four','five','six','seven','eig...
How to convert number to words
I'm beginner, i have homework that requires the user to input a number and it convert it to words.For example: 15342 to one five three four two this's my code, but it only work with a number: def convert_text(): arr = ['zero','one','two','three','four','five','six','seven','eight','nine'] word = arr[n] ...
[ "Keep the value you pas being a string, then you can iterate over its chars\narr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\n\ndef convert_text(value):\n result = []\n for char in value:\n result.append(arr[int(char)])\n return \" \".join(result)\n\nprint(conv...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074556778_python.txt
Q: Elasticsearch - How to create buckets by using information from two fields at the same time? My documents are like this: {'start': 0, 'stop': 3, 'val': 3} {'start': 2, 'stop': 4, 'val': 1} {'start': 5, 'stop': 6, 'val': 4} We can imagine that each document occupies the x-coordinates from 'start' to 'stop', and ha...
Elasticsearch - How to create buckets by using information from two fields at the same time?
My documents are like this: {'start': 0, 'stop': 3, 'val': 3} {'start': 2, 'stop': 4, 'val': 1} {'start': 5, 'stop': 6, 'val': 4} We can imagine that each document occupies the x-coordinates from 'start' to 'stop', and has a certain value 'val' ('start' < 'stop' is guaranteed). The goal is to plot a line showing the s...
[ "The right way to do this in one single query is to use the range field type (available since 5.2) instead of using two fields start and stop and reimplementing the same logic. Like this:\nPUT test \n{\n \"mappings\": {\n \"properties\": {\n \"range\": {\n \"type\": \"integer_range\"\n },\n ...
[ 1 ]
[]
[]
[ "elasticsearch", "python" ]
stackoverflow_0074554278_elasticsearch_python.txt
Q: Forwarding FastAPI requests to another server I have a FastAPI application for testing/development purposes. What I want is that any request that gets to my app will automatically be sent, as is, to another app on another server, with exactly the same parameters and same endpoint. This is not a redirect, because ...
Forwarding FastAPI requests to another server
I have a FastAPI application for testing/development purposes. What I want is that any request that gets to my app will automatically be sent, as is, to another app on another server, with exactly the same parameters and same endpoint. This is not a redirect, because I still want the app to process the request and ret...
[ "You can use the AsyncClient() from the httpx library, as described in this answer, as well as this and this answer (have a look at those for more details on the approach). You can spawn a Client in the startup event handler, store it on the app instanceβ€”as described here, as well as here and hereβ€”and reuse it ever...
[ 0 ]
[]
[]
[ "fastapi", "forward", "python", "request", "rest" ]
stackoverflow_0074555102_fastapi_forward_python_request_rest.txt
Q: Kernel keeps dying what function do you use in Jupyter notebook in place of quit() because the quit() function keeps killing my kernel but it works perfectly in the pycharm and VS code I wrote the quit function under an if statement. And the quit() function instead of ending the program when the condition is met, ...
Kernel keeps dying
what function do you use in Jupyter notebook in place of quit() because the quit() function keeps killing my kernel but it works perfectly in the pycharm and VS code I wrote the quit function under an if statement. And the quit() function instead of ending the program when the condition is met, it rather kills my kerne...
[]
[]
[ "I think raising an error when your if statement is verified can be a good solution.\nFor example :\nraise KeyboardInterrupt\n\nHaving a look at https://docs.python.org/3/tutorial/errors.html may help you.\n" ]
[ -1 ]
[ "function", "if_statement", "jupyter", "python" ]
stackoverflow_0074556816_function_if_statement_jupyter_python.txt
Q: How do I combine one input to a list of another input in order? Say I had an input of: john bob alex liam # names 15 17 16 19 # age 70 92 70 100 # iq How do I make it so that john is assigned to age 15 and iq of 70, bob is assigned to age 17 and iq of 92, alex is assigned to age 16 and iq of 70, and liam is assig...
How do I combine one input to a list of another input in order?
Say I had an input of: john bob alex liam # names 15 17 16 19 # age 70 92 70 100 # iq How do I make it so that john is assigned to age 15 and iq of 70, bob is assigned to age 17 and iq of 92, alex is assigned to age 16 and iq of 70, and liam is assigned to age 19 and iq of 100? Right now I have: names = input().split...
[ "We can form 3 lists and then zip them together:\nnames = \"john bob alex liam\"\nages = \"15 17 16 19\"\niq = \"70 92 70 100\"\nlist_a = names.split()\nlist_b = ages.split()\nlist_c = iq.split()\nzipped = zip(list_a, list_b, list_c)\nzipped_list = list(zipped) \n\nprint(zipped_list)\n\nThis prints:\n[('john', '15...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074556969_python_python_3.x.txt
Q: A certain regular expression that should match does not match in Python I am working with determining if certain regular expressions apply to some specified text, and for this I wrote a short Python script. I am having trouble with a certain regular expression because I tested it in an app on my iPhone designed t...
A certain regular expression that should match does not match in Python
I am working with determining if certain regular expressions apply to some specified text, and for this I wrote a short Python script. I am having trouble with a certain regular expression because I tested it in an app on my iPhone designed to test regular expressions on specified text, and the regular expression matc...
[ "\nWhat I would like, if possible, is to get an explanation as to why the regular expression does not match the text in Python\n\nThe problem is that the [[:punct:]] character class appears inside a character class. You need to stick to the brackets that [[:punct:]] already has, and add the other characters inside ...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074554306_python_regex.txt
Q: Memory Error when parsing a large number of files I am parsing 6k csv files to merge them into one. I need this for their joint analysis and training of the ML model. There are too many files and my computer ran out of memory by simply concatenating them. S = β€˜β€™ for f in csv_files: # read the csv file #df = df.a...
Memory Error when parsing a large number of files
I am parsing 6k csv files to merge them into one. I need this for their joint analysis and training of the ML model. There are too many files and my computer ran out of memory by simply concatenating them. S = β€˜β€™ for f in csv_files: # read the csv file #df = df.append(pd.read_csv(f)) s = s + open(f, mode ='r').read...
[ "I believe this may help:\nfile = open('bigdata.csv', mode = 'w')\n\nfor f in csv_files:\n s = open(f, mode='r').read()[32:]\n file.write(s)\n\nfile.close()\n\nIn contrast, your origin code need at least the same memory as the size of the output file, which is 60gb and maybe larger than the memory of your com...
[ 0 ]
[]
[]
[ "bigdata", "data_processing", "machine_learning", "python" ]
stackoverflow_0074556994_bigdata_data_processing_machine_learning_python.txt
Q: Why can't I "deactivate" pyenv / virtualenv? How to "fix" installation I am on a freshly installed Ubuntu 16.04 and in view of developing with recent versions of pandas I installed Python 3.6.0 using a virtual environment. A reason for choosing 3.6.0 was because I read somewhere that this version of Python could d...
Why can't I "deactivate" pyenv / virtualenv? How to "fix" installation
I am on a freshly installed Ubuntu 16.04 and in view of developing with recent versions of pandas I installed Python 3.6.0 using a virtual environment. A reason for choosing 3.6.0 was because I read somewhere that this version of Python could deal with virtual environments natively, i.e. without installing anything els...
[ "It was deactivated when I used this command: pyenv shell .\n", "EDIT-[22/11/22]---> BELOW ANSWER IS FROM 2018 - maybe i never got to DEACTIVATE and did only manage to UN-INSTALL\nThe way to DEACTIVATE the default PyEnv General is --pyenv uninstall 3.6.0/envs/general\npyenv-virtualenv: remove /home/dhankar/.pyenv...
[ 1, 0, 0 ]
[]
[]
[ "pyenv", "python", "ubuntu", "virtualenv" ]
stackoverflow_0043935610_pyenv_python_ubuntu_virtualenv.txt
Q: ValueError: Length of values does not match length of index | Pandas DataFrame.unique() I am trying to get a new dataset, or change the value of the current dataset columns to their unique values. Here is an example of what I am trying to get : A B ----- 0| 1 1 1| 2 5 2| 1 5 3| 7 9 4| 7 9 5| 8 9 Wanted Result...
ValueError: Length of values does not match length of index | Pandas DataFrame.unique()
I am trying to get a new dataset, or change the value of the current dataset columns to their unique values. Here is an example of what I am trying to get : A B ----- 0| 1 1 1| 2 5 2| 1 5 3| 7 9 4| 7 9 5| 8 9 Wanted Result Not Wanted Result A B A B ----- ----- 0| 1 1 ...
[ "The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:\nA data frame of four rows:\ndf = pd.DataFrame({'A': [1,2,3,4]})\n\nNow trying to assign a list/array of two elements to it:\ndf['B'] = [3,4] # or df['B'] = np.array([3...
[ 125, 2, 0 ]
[]
[]
[ "dataframe", "duplicates", "pandas", "python" ]
stackoverflow_0042382263_dataframe_duplicates_pandas_python.txt
Q: Different result when i switch positions of my two different functions Note - I am using VSCode Sample 1: In this example my function nextSquare() is been executed, but aFunc() is not been executed, as in, i get no output for my 2nd function def nextSquare(): i = 1 while True: yield i*i i +...
Different result when i switch positions of my two different functions
Note - I am using VSCode Sample 1: In this example my function nextSquare() is been executed, but aFunc() is not been executed, as in, i get no output for my 2nd function def nextSquare(): i = 1 while True: yield i*i i += 1 for num in nextSquare(): if num<100: print(num) def aFunc()...
[ "The for loop never ends, so nothing after it is executed. When num is more than 100 it stops printing, but it keeps looping. You need to stop the loop.\nfor num in nextSquare():\n if num<100:\n print(num)\n else:\n break\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.11" ]
stackoverflow_0074556876_python_python_3.11.txt
Q: How to generate the csv file with the Number field but None value I got a requirement to get data from database and write them into file with CSV format. and the further requirement is the field needs to be sepread by the comma char, and the String value needs to be enclosed with double quota char, and other filed...
How to generate the csv file with the Number field but None value
I got a requirement to get data from database and write them into file with CSV format. and the further requirement is the field needs to be sepread by the comma char, and the String value needs to be enclosed with double quota char, and other fileds no need. but when write them into csv, the number field with Null val...
[ "Setting quoting to csv.QUOTE_NONNUMERIC means to quote all non-numeric values, and since None (or '') is not a numeric type, its output gets quoted.\nA workaround is to create a subclass of a numeric type and force its string conversion to be '', so that it passes csv's numeric type check and gets a non-quoted emp...
[ 1 ]
[]
[]
[ "csv", "format", "python" ]
stackoverflow_0074556908_csv_format_python.txt
Q: Reshaping a Dataframe with a column having numeric and non-numeric value stored as Object Datatype I want to reshape the input dataframe to output dataframe shape as mentioned below. Input Dataframe ID Parameter Value 0 1001 Name Peter 1 1001 Name Pete 2 1001 Name ...
Reshaping a Dataframe with a column having numeric and non-numeric value stored as Object Datatype
I want to reshape the input dataframe to output dataframe shape as mentioned below. Input Dataframe ID Parameter Value 0 1001 Name Peter 1 1001 Name Pete 2 1001 Name J. Pete 3 1001 ShoeSize A 4 1001 ShoeSize A 5 1001 BrainSize 32 6 1001 ...
[ "Use:\njoin = lambda x: ','.join(x.dropna())\n(df.assign(idx2=lambda d: d.groupby(['ID', 'Parameter']).cumcount())\n .pivot(index=['ID', 'idx2'], columns='Parameter', values='Value')\n .astype({'BrainSize': float})\n .groupby(level=0).agg({'BrainSize': 'mean', 'Name': join, 'ShoeSize': join})\n)\n\noutput:\nP...
[ 1 ]
[]
[]
[ "data_transform", "pivot_table", "python" ]
stackoverflow_0074557126_data_transform_pivot_table_python.txt
Q: Python - How to sort a 2d array by different order for each element? I just want to clear out that I am new to coding. I am trying to solve a problem set that counts the occurrence of characters in a string and prints out the 3 most reoccurring characters Heres the code I wrote s = input().lower() b = [] ...
Python - How to sort a 2d array by different order for each element?
I just want to clear out that I am new to coding. I am trying to solve a problem set that counts the occurrence of characters in a string and prints out the 3 most reoccurring characters Heres the code I wrote s = input().lower() b = [] for i in s: templst = [] templst.append(i) tem...
[ "you need to specify multiple conditions for the sort\nfinal= Sorted(b, key = lambda e: (-e[1], e[0]))\n\nThe negative sign here makes larger numbers first (as if we are sorting in reverse order)\n", "Since pythons sort is stable you could do two sort passes:\nb.sort(key=lambda x: x[0])\nb.sort(key=lambda x: x[1]...
[ 1, 0 ]
[]
[]
[ "arrays", "list", "python", "sorting", "string" ]
stackoverflow_0074556864_arrays_list_python_sorting_string.txt
Q: sum in list of dictionaries python with exception how do I get the sum of money and spent from a list of dictionaries where sum of money = (sum of money of shirt color blue and red) and (sum of money of shirt color yellow and green) sum of spent = (sum of spent of shirt color blue and red) and (sum of spent of shi...
sum in list of dictionaries python with exception
how do I get the sum of money and spent from a list of dictionaries where sum of money = (sum of money of shirt color blue and red) and (sum of money of shirt color yellow and green) sum of spent = (sum of spent of shirt color blue and red) and (sum of spent of shirt color yellow and green) should i make new dictionary...
[ "The data is\npeople = [{'name': 'A', 'shirtcolor': 'blue', 'money': '100', 'spent': '50'},\n {'name': 'B', 'shirtcolor': 'red', 'money': '70', 'spent': '50'},\n {'name': 'C', 'shirtcolor': 'yellow', 'money': '100', 'spent': '70'},\n {'name': 'D', 'shirtcolor': 'blue', 'money': '200', 'sp...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x" ]
stackoverflow_0074556828_dictionary_list_python_python_3.x.txt
Q: How to convert a three digit integer (xxx) with a 1 decimal place float (xx.x)? Currently I'm getting data from some sensors with voltage(V) and current(C) values which is decoded into text as V040038038039C125067 to be stored in MYSQL DB table. The voltage contains 4 different voltage values combined while the cu...
How to convert a three digit integer (xxx) with a 1 decimal place float (xx.x)?
Currently I'm getting data from some sensors with voltage(V) and current(C) values which is decoded into text as V040038038039C125067 to be stored in MYSQL DB table. The voltage contains 4 different voltage values combined while the current contains 2 different current values combined where each value represented by 3 ...
[ "Which version of Python are you using? int should convert strings such as '040' just fine.\nPython 3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:56:21) \nType 'copyright', 'credits' or 'license' for more information\nIPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.\n\nIn [1]: int('04...
[ 0, 0 ]
[ "This is a Very Simple Problem\nWhat you have to do is just divide the number by 10 and convert it into float with float inbuilt function in python.\na = int(input(\"Enter a random number: \"))\nprint(float(a/10))\n\nnow apply it in your problem.\nvolt_1 = float(int(v1)/10)\nvolt_2 = float(int(v2)/10)\nvolt_3 = flo...
[ -2 ]
[ "mysql", "python", "syntax_error" ]
stackoverflow_0074555970_mysql_python_syntax_error.txt
Q: Speed up groupby rolling apply utilising multiple columns I'm trying to create a Brier Score for a grouped rolling window. As the function that calculates the Brier Score utilises multiple columns in the grouped rolling window I've had to use the answer here as the basis for a rather hacky solution: import pandas ...
Speed up groupby rolling apply utilising multiple columns
I'm trying to create a Brier Score for a grouped rolling window. As the function that calculates the Brier Score utilises multiple columns in the grouped rolling window I've had to use the answer here as the basis for a rather hacky solution: import pandas as pd import numpy as np from pandas._libs.tslibs.timestamps im...
[ "You can easily achieve fast execution with parallel-pandas.\nIn your example, I increased the number of groups from 2 to 100. Initialize parallel-pandas and use p_apply the parallel analog of the apply method\nimport time\n\nfrom pandas._libs.tslibs.timestamps import Timestamp\nimport random\nimport pandas as pd\n...
[ 1 ]
[]
[]
[ "group_by", "pandas", "pandas_apply", "pandas_rolling", "python" ]
stackoverflow_0074083218_group_by_pandas_pandas_apply_pandas_rolling_python.txt
Q: f-string with percent and fixed decimals? I know that I can to the following. But is it possible to combine them to give me a percent with fixed decimal? >>> print(f'{0.123:%}') 12.300000% >>> print(f'{0.123:.2f}') 0.12 But what I want is this output: 12.30% A: You can specify the number of decimal places befor...
f-string with percent and fixed decimals?
I know that I can to the following. But is it possible to combine them to give me a percent with fixed decimal? >>> print(f'{0.123:%}') 12.300000% >>> print(f'{0.123:.2f}') 0.12 But what I want is this output: 12.30%
[ "You can specify the number of decimal places before %:\n>>> f'{0.123:.2%}' \n'12.30%'\n\n" ]
[ 2 ]
[]
[]
[ "f_string", "python" ]
stackoverflow_0074557297_f_string_python.txt
Q: Hashing the content of a method in Python I am looking for a robust way to hash/serialize the content of a method in Python. Use-case: We are doing some file caching the result of a transformation function, and it would be great if it was possible to automatically refresh if transformation function has changed: ca...
Hashing the content of a method in Python
I am looking for a robust way to hash/serialize the content of a method in Python. Use-case: We are doing some file caching the result of a transformation function, and it would be great if it was possible to automatically refresh if transformation function has changed: cached_file = get_cached_filename( data_versi...
[ "Good question. Not sure if it is the best approach, but you can get the function source code using inspect module, like this:\ninspect.getsource(foo)\n\nThat will return the source as a string, so you can then get the hash to get a cache key by running some hashing function.\n" ]
[ 2 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0074557272_hash_python.txt
Q: Add multiple recipient while sending mail throws error - python I have a code that should send mail to multiple recipient , but it throws me error when i use multiple recipients. The error am getting - {'error': {'code': 'RequestBodyRead', 'message': "The property 'Email Address' does not exist on type 'microsoft....
Add multiple recipient while sending mail throws error - python
I have a code that should send mail to multiple recipient , but it throws me error when i use multiple recipients. The error am getting - {'error': {'code': 'RequestBodyRead', 'message': "The property 'Email Address' does not exist on type 'microsoft.graph.recipient'. Make sure to only use property names that are defin...
[ "The name of the property inside toRecipients is emailAddress not Email Address.\nSimply remove the space.\nrecipient_list = [{'emailAddress': {'Address': address}} for address in recipients]\n\nAlso in attachments you have some spaces: '@odata. type': '#microsoft. graph. fi LeAttachment'.\nRemove those spaces\natt...
[ 0 ]
[]
[]
[ "email", "microsoft_graph_api", "microsoft_graph_mail", "office365", "python" ]
stackoverflow_0074557328_email_microsoft_graph_api_microsoft_graph_mail_office365_python.txt
Q: Multiprocessing starmap creates duplicate objects I am trying to use multiprocessing to (i) read in data, (ii) do some analyses, and (iii) save the output/results of those analyses as an instance of custom class. My function that does the analyses inputs multiple arguments, indicating that starmap from the multip...
Multiprocessing starmap creates duplicate objects
I am trying to use multiprocessing to (i) read in data, (ii) do some analyses, and (iii) save the output/results of those analyses as an instance of custom class. My function that does the analyses inputs multiple arguments, indicating that starmap from the multiprocessing module should do the trick. However, even tho...
[ "let's first run this code serially without multiprocessing.\nfrom itertools import starmap\nresults = list(starmap(fun,inputs))\n# [11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11]\n\nnotice you only created one EgClass instance in your entire code, (you only called EgClass() once), np.repeat simply repeats the poi...
[ 1 ]
[]
[]
[ "multiprocessing", "pool", "python" ]
stackoverflow_0074552552_multiprocessing_pool_python.txt
Q: Indexed manageable attributes in Python I need to add a custom attributes to a class and make this attributes 'indexed'. This code fragment illustrates the issue: import numpy as np class Test: def __init__(self): self.arr = np.array([[100, 200, 300], [100, 155, 120], ...
Indexed manageable attributes in Python
I need to add a custom attributes to a class and make this attributes 'indexed'. This code fragment illustrates the issue: import numpy as np class Test: def __init__(self): self.arr = np.array([[100, 200, 300], [100, 155, 120], [300, 110, 333], ...
[ "There is a slightly hacky way to do what you want by piggybacking off __setitem__.\nimport numpy as np\n\nclass Test:\n def __init__(self):\n self.arr = np.array([[100, 200, 300],\n [100, 155, 120],\n [300, 110, 333],\n [...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074533621_numpy_python.txt
Q: Python Zybooks LAB 9.6 - Contact List Yet again, I do not understand an error I keep encountering. Here is my code: s = input() name = input() splits = s.split(" ") i = 0 for i in range(len(splits)): if(splits[i] == name): break print(splits[i+1]) Here is the error: Traceback (most recent call la...
Python Zybooks LAB 9.6 - Contact List
Yet again, I do not understand an error I keep encountering. Here is my code: s = input() name = input() splits = s.split(" ") i = 0 for i in range(len(splits)): if(splits[i] == name): break print(splits[i+1]) Here is the error: Traceback (most recent call last): File "main.py", line 15, in <module>...
[ "s = 'Hello'\nname = 'Goodbye'\nsplits = s.split() # default value is a single space ['Hello'] - notice the single value\n\nfor i in range(1): # because splits has a single item in the list\n if 'Hello' == 'Goodbye':\n break\n \nprint(splits[i+1]) # this will not work because splits has a single index ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074557361_python.txt
Q: Selenium Webdriver Xpath id random I have a problem, when I look for the id of an xpath it changes every time I enter the web how can i use selenium webdriver python browser.find_element(By.ID,) if the id changes every time I consult it first <span data-dojo-attach-point="containerNode,focusNode" class="tabLabel"...
Selenium Webdriver Xpath id random
I have a problem, when I look for the id of an xpath it changes every time I enter the web how can i use selenium webdriver python browser.find_element(By.ID,) if the id changes every time I consult it first <span data-dojo-attach-point="containerNode,focusNode" class="tabLabel" role="tab" tabindex="0" id="icm_widget...
[ "Try to use below xpath\nbrowser.find_element(By.XPATH(//span[contains(@id, 'icm_widget_SelectorTabContainer') and text()='Search']);\n\n", "In case the first part of the id is unique and stable as it seems to be, you can use XPath or CSS Selector to locate this element.\nXPath:\nbrowser.find_element(By.XPATH, \"...
[ 0, 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "webdriver" ]
stackoverflow_0074555529_google_chrome_python_selenium_webdriver.txt
Q: Crate new row depends on 2 columns After Year row need a new row as Year period if column 1 is year and column3< 2010 then columns values for year period is Below 2010 same as other rows Column1 Column2 ColumnX Column3 0 Year 1 A 2009 1 Date 1 A 12 2 Year 2 ...
Crate new row depends on 2 columns
After Year row need a new row as Year period if column 1 is year and column3< 2010 then columns values for year period is Below 2010 same as other rows Column1 Column2 ColumnX Column3 0 Year 1 A 2009 1 Date 1 A 12 2 Year 2 A 2021 3 Year 3 ...
[ "Filter rows first in boolean indexing for Year columns, replace Column3 in numpy.select and add substring to Column1, last join with original by concat and sort indices by DataFrame.sort_index:\n#necessary default RangeIndex\ndf = df.reset_index(drop=True)\n\ndf2 = df[df['Column1'].eq('Year')].copy()\ndf2['Column3...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074557375_pandas_python.txt
Q: How to associate subplots with a particular figure number? coming from MATLAB, I am trying to perform something like how subplots are associated with a figure number: figure(3) subplot(3,1,1) How would I do this in Python? Below is where I am stuck. plt.figure(3) fig, axs = plt.subplots(3) A: You have to add su...
How to associate subplots with a particular figure number?
coming from MATLAB, I am trying to perform something like how subplots are associated with a figure number: figure(3) subplot(3,1,1) How would I do this in Python? Below is where I am stuck. plt.figure(3) fig, axs = plt.subplots(3)
[ "You have to add subplots to the figure you created\nfig = plt.figure(3)\naxs = fig.add_subplot(3, 1, 1)\n\nor you can create both using subplots, so the previous call of figure is not needed\nfig, axs = plt.subplots(3, 1)\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074556278_matplotlib_python.txt
Q: login flow api server python Im kind fo new in this so any help will be highly appreciated. Im trying to write an API server that will contain simple request of user login. This is what i got so far, hashing: from flask import Flask, request, jsonify, Response import jwt app = Flask(__name__) @app.route('/login'...
login flow api server python
Im kind fo new in this so any help will be highly appreciated. Im trying to write an API server that will contain simple request of user login. This is what i got so far, hashing: from flask import Flask, request, jsonify, Response import jwt app = Flask(__name__) @app.route('/login', methods=['POST']) def login(): ...
[ "I normally use passlib to do this when I am building rest API using fastapi but I am not if it works with flask.\nTo Install\npip install \"passlib[bcrypt]\"\nOr\npip3 install \"passlib[bcrypt]\"\n\nUsage\nfrom passlib.context import CryptContext\n\npwd_context = CryptContext(schemes='bcrypt')\n\n\"\"\"\nCall this...
[ 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074557365_api_python.txt
Q: How to convert index of a pandas dataframe into a column This seems rather obvious, but I can't seem to figure out how to convert an index of data frame to a column? For example: df= gi ptt_loc 0 384444683 593 1 384444684 594 2 384444686 596 To, df= index1 gi p...
How to convert index of a pandas dataframe into a column
This seems rather obvious, but I can't seem to figure out how to convert an index of data frame to a column? For example: df= gi ptt_loc 0 384444683 593 1 384444684 594 2 384444686 596 To, df= index1 gi ptt_loc 0 0 384444683 593 1 1 384444684 ...
[ "either:\ndf['index1'] = df.index\n\nor, .reset_index:\ndf = df.reset_index(level=0)\n\n\nso, if you have a multi-index frame with 3 levels of index, like:\n>>> df\n val\ntick tag obs \n2016-02-26 C 2 0.0139\n2016-02-27 A 2 0.5577\n2016-02-28 C 6 0.0303\n\nand you w...
[ 1252, 56, 51, 42, 11, 11, 5, 2, 0 ]
[]
[]
[ "dataframe", "indexing", "pandas", "python", "series" ]
stackoverflow_0020461165_dataframe_indexing_pandas_python_series.txt
Q: Update row values where certain condition is met in pandas Say I have the following dataframe: What is the most efficient way to update the values of the columns feat and another_feat where the stream is number 2? Is this it? for index, row in df.iterrows(): if df1.loc[index,'stream'] == 2: # do someth...
Update row values where certain condition is met in pandas
Say I have the following dataframe: What is the most efficient way to update the values of the columns feat and another_feat where the stream is number 2? Is this it? for index, row in df.iterrows(): if df1.loc[index,'stream'] == 2: # do something How do I do it if there are more than 100 columns? I don't ...
[ "I think you can use loc if you need update two columns to same value:\ndf1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'\nprint df1\n stream feat another_feat\na 1 some_value some_value\nb 2 aaaa aaaa\nc 2 aaaa aaaa\nd 3 some_value so...
[ 305, 4, 0 ]
[]
[]
[ "indexing", "iterator", "mask", "pandas", "python" ]
stackoverflow_0036909977_indexing_iterator_mask_pandas_python.txt
Q: Streamlip app not searching files in the good directory I am trying to run a Streamlit app importing pickle files and a DataFrame. The pathfile for my script is : /Users/myname/Documents/Master2/Python/Final_Project/streamlit_app.py And the one for my DataFrame is: /Users/myname/Documents/Master2/Python/Final_P...
Streamlip app not searching files in the good directory
I am trying to run a Streamlit app importing pickle files and a DataFrame. The pathfile for my script is : /Users/myname/Documents/Master2/Python/Final_Project/streamlit_app.py And the one for my DataFrame is: /Users/myname/Documents/Master2/Python/Final_Project/data/metabolic_syndrome.csv One could reasonably argu...
[ "you can use os.getcwd() to get the Current Working Directory. Read up on what this means exactly, fe here\nSee the sample script below on how to use it. I'm using os.sep for OS agnostic filepath separators.\nimport os\n\n\nprint(os.getcwd())\n\nrelative_path = \"data\"\nfull_path = f\"{os.getcwd()}{os.sep}{relativ...
[ 0, 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074530787_python_streamlit.txt
Q: requests.Session with client certificates and own CA Here is my code os.environ['REQUESTS_CA_BUNDLE'] = os.path.join('/path/to/','ca-own.crt') s = requests.Session() s.cert = ('some.crt', 'some.key') s.get('https://some.site.com') Last instruction returns: requests.exceptions.SSLError: HTTPSConnectionPool(host='...
requests.Session with client certificates and own CA
Here is my code os.environ['REQUESTS_CA_BUNDLE'] = os.path.join('/path/to/','ca-own.crt') s = requests.Session() s.cert = ('some.crt', 'some.key') s.get('https://some.site.com') Last instruction returns: requests.exceptions.SSLError: HTTPSConnectionPool(host='some.site.com', port=443): Max retries exceeded with url: ...
[ "Above code will work if you put verify=False in the GET request, but it's not ideal security wise(Man in the middle attacks) thus you need to add the CA certificate(issuer's certificate) file to the verify parameter. More info here\nsession = requests.Session()\nsession.verify = \"/path/to/issuer's certificate\"(C...
[ 0, 0 ]
[]
[]
[ "ca", "client_certificates", "python", "python_3.x", "session" ]
stackoverflow_0071955825_ca_client_certificates_python_python_3.x_session.txt
Q: Computing the distance matrix from an adjacency matrix in python Write a code that produces the distance matrix from a graph (graph theory), the code should use the adjacency matrix and cannot use any functions from NetworkX module, apart from networkx.adjacency_matrix(). I understand the process of how the dista...
Computing the distance matrix from an adjacency matrix in python
Write a code that produces the distance matrix from a graph (graph theory), the code should use the adjacency matrix and cannot use any functions from NetworkX module, apart from networkx.adjacency_matrix(). I understand the process of how the distance matrix works. My theory of how the adjacency matrix is involved is...
[]
[]
[ "Check if the below code helps.\n#G is a networkX graph.\ndef get_actual_distance_between_two_nodes(G, i, j):\n pos=nx.spring_layout(G, seed=random_seed)\n sp = nx.shortest_path(G, i, j)\n edges_set = [[sp[i], sp[i+1]] for i in range(len(sp)-1)]\n\n distance_list = []\n for edge in edges_set:\n ...
[ -1 ]
[ "adjacency_matrix", "distance_matrix", "python" ]
stackoverflow_0055328620_adjacency_matrix_distance_matrix_python.txt
Q: Python type hints: How to use Literal with strings to conform with mypy? I want to restrict the possible input arguments by using typing.Literal. The following code works just fine, however, mypy is complaining. from typing import Literal def literal_func(string_input: Literal["best", "worst"]) -> int: if str...
Python type hints: How to use Literal with strings to conform with mypy?
I want to restrict the possible input arguments by using typing.Literal. The following code works just fine, however, mypy is complaining. from typing import Literal def literal_func(string_input: Literal["best", "worst"]) -> int: if string_input == "best": return 1 elif string_input == "worst": ...
[ "Unfortunately, mypy does not narrow the type of input_string to Literal[\"best\"]. You can help it with a proper type annotation:\ninput_string: Literal[\"best\"] = \"best\"\nliteral_func(string_input=input_string)\n\nPerhaps worth mentioning that pyright works just fine with your example.\n\nAlternatively, the sa...
[ 1 ]
[]
[]
[ "literals", "mypy", "python" ]
stackoverflow_0074557655_literals_mypy_python.txt
Q: pyautogui screenshot command is not working import pyautogui myScreenshot = pyautogui.screenshot() myScreenshot.save(r'C:\Users\"my user name"\PycharmProjects\"my project"\ name.png') I don't know what I did wrong but any similar command is not working (I have installed pyautogui). A: If you already have PIL...
pyautogui screenshot command is not working
import pyautogui myScreenshot = pyautogui.screenshot() myScreenshot.save(r'C:\Users\"my user name"\PycharmProjects\"my project"\ name.png') I don't know what I did wrong but any similar command is not working (I have installed pyautogui).
[ "If you already have PIL (Pillow) installed, you'll need to upgrade it via the command prompt command\npip install Pillow --upgrade\n\n", "Just install Pillow package using pip:\npip install Pillow\n\nor\npip3 install Pillow\n\n", "Try to upgrade your PyAutoGui module using the following command:\npip install p...
[ 1, 0, 0 ]
[]
[]
[ "pyautogui", "python", "screenshot" ]
stackoverflow_0069526177_pyautogui_python_screenshot.txt
Q: Can't connect to local MySQL server through socket '/tmp/mysql.sock When I attempted to connect to a local MySQL server during my test suite, it fails with the error: OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") However, I'm able to at all times, connect to ...
Can't connect to local MySQL server through socket '/tmp/mysql.sock
When I attempted to connect to a local MySQL server during my test suite, it fails with the error: OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") However, I'm able to at all times, connect to MySQL by running the command line mysql program. A ps aux | grep mysql sh...
[ "sudo /usr/local/mysql/support-files/mysql.server start \n\nThis worked for me. However, if this doesnt work then make sure that mysqld is running and try connecting.\n", "The relevant section of the MySQL manual is here. I'd start by going through the debugging steps listed there.\nAlso, remember that localhost ...
[ 175, 147, 145, 30, 29, 22, 15, 9, 9, 9, 7, 7, 7, 4, 4, 4, 3, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "Mac user here running mac os mojave 10.14. In my case what helped me was to uninstall MySQL from within the system preferences pane and then reinstalling and selecting the legacy password MySQL system during the installation wizard.\nI did this by going to apple menu > system preferences >> MySQL >> and then hitti...
[ -2 ]
[ "django", "mysql", "python" ]
stackoverflow_0016325607_django_mysql_python.txt
Q: Is there an easy way to convert ISO 8601 duration to timedelta? Given a ISO 8601 duration string, how do I convert it into a datetime.timedelta? This didn't work: timedelta("PT1H5M26S", "T%H%M%S") A timedelta object represents a duration, the difference between two dates or times (https://docs.python.org/3/librar...
Is there an easy way to convert ISO 8601 duration to timedelta?
Given a ISO 8601 duration string, how do I convert it into a datetime.timedelta? This didn't work: timedelta("PT1H5M26S", "T%H%M%S") A timedelta object represents a duration, the difference between two dates or times (https://docs.python.org/3/library/datetime.html#datetime.timedelta). ISO 8601 durations are described...
[ "I found isodate library to do exactly what I want\nisodate.parse_duration('PT1H5M26S')\n\n\nYou can read the source code for the function here\n\n", "If you're using Pandas, you could use pandas.Timedelta. The constructor accepts an ISO 8601 string, and pandas.Timedelta.isoformat you can format the instance back...
[ 59, 5, 4, 1, 1, 0 ]
[]
[]
[ "datetime", "python", "python_datetime", "timedelta" ]
stackoverflow_0036976138_datetime_python_python_datetime_timedelta.txt
Q: How to print whole number without zeros after decimal point? I'm trying to print a whole number (such as 39 for example) in the following format: 39. It must not be a str type object like '39.' for example, but a number e. g. n = 39.0 should be printed like 39. n = 39.0 #magic stuff with output 39. I tried using ...
How to print whole number without zeros after decimal point?
I'm trying to print a whole number (such as 39 for example) in the following format: 39. It must not be a str type object like '39.' for example, but a number e. g. n = 39.0 should be printed like 39. n = 39.0 #magic stuff with output 39. I tried using :.nf methods (:.0f apparently -- didn't work), print(float(39.)) o...
[ "From Format Specification Mini-Language (emphasis mine):\n\nThe '#' option causes the β€œalternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal outpu...
[ 8, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074425460_python.txt
Q: Exclude holidays between two selected dates in pyhton odoo How can I calculate total hours between two dates. here I have to select the start date and end date. and every day an employee works 8 hours per day. I calculate the total hours between these two dates. For example if I select two dates from: 11/21/2022 ...
Exclude holidays between two selected dates in pyhton odoo
How can I calculate total hours between two dates. here I have to select the start date and end date. and every day an employee works 8 hours per day. I calculate the total hours between these two dates. For example if I select two dates from: 11/21/2022 and date to:11/22/2022. These two dates total hours are 16 hours...
[ "You can simply use weekday function to find the weekday for that day. Then compare it with holidays.\nIn [1]: from datetime import date, timedelta \n ...: \n ...: start_date = date(2019, 1, 1) \n ...: end_date = date(2020, 1, 1) \n ...: delta = timedelta(days=1) \n ...: count = 0 \n ...: while ...
[ 0, 0 ]
[]
[]
[ "odoo", "python" ]
stackoverflow_0074545035_odoo_python.txt
Q: Why is the loop not calculating every lowercase letter from a string? I am trying to calculate every lowercase letter from a mixed uppercase and lowercase string and form a new string of only lowercase. For example I have a string named st="ABcASFatBD" and I expect an output of low= "cat" but I am getting only "c"...
Why is the loop not calculating every lowercase letter from a string?
I am trying to calculate every lowercase letter from a mixed uppercase and lowercase string and form a new string of only lowercase. For example I have a string named st="ABcASFatBD" and I expect an output of low= "cat" but I am getting only "c" as the output. Below is my code. class Solution(object): def find...
[ "The problem is that you have your script ending on the first time it finds a lowercase value, whereas your return lo should be outside of the for i in range(...):. But heres a simpler version of your code:\nclass Solution(object):\n\n def find_crowd(self, st):\n lo = \"\"\n lo = ''.join([char for ...
[ 0, 0, 0 ]
[]
[]
[ "loops", "python", "string" ]
stackoverflow_0074557249_loops_python_string.txt
Q: Welcome messages for different userNames I want a python code to print greeting messages for users when logged in: if the userName is admin then it should print "Hello admin you're welcome, would you want to see a status update?", and if the userName is other than admin then a different welcome message is printed:...
Welcome messages for different userNames
I want a python code to print greeting messages for users when logged in: if the userName is admin then it should print "Hello admin you're welcome, would you want to see a status update?", and if the userName is other than admin then a different welcome message is printed: I tried the code below but am not getting it ...
[ "The first prompt says to loop through the list of user names, and print a special message if the name is \"admin\":\ndef main():\n userNames = [\"jack2\", \"admin\", \"lucy21\", \"angeUt\", \"lacky53\"]\n for user in userNames:\n if user == \"admin\":\n print(\"Hello admin would you like to...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074504267_python.txt
Q: Python - Intersection of multiple lists taken two at a time In python, I am able to get intersection of multiple lists: arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] result = set.intersection(*map(set, arr)) Output: result = {3} Now, I want the result as intersection of all 3 nested lists taken 2 at a time: result = {...
Python - Intersection of multiple lists taken two at a time
In python, I am able to get intersection of multiple lists: arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]] result = set.intersection(*map(set, arr)) Output: result = {3} Now, I want the result as intersection of all 3 nested lists taken 2 at a time: result = {2, 3, 4} as [2, 3] is common between 1st and 2nd lists, [3, 4] i...
[ "You can take a union of the all pairs of intersections as follows;\nimport itertools as it\narr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\nres = set.union(*(set(i).intersection(set(j)) for i,j in it.combinations(arr,2)))\n# output {2, 3, 4}\n\n*edit as per @DanielHao's comment\n", "Try itertools.combinations\nfrom ite...
[ 1, 0 ]
[]
[]
[ "intersection", "list", "python", "set" ]
stackoverflow_0074557859_intersection_list_python_set.txt
Q: Pyspark Avoid Pivot Transformation To Dataframe - Pivot Alternative I have a datafrane to which I am applying a pivot transformation and I want to know if there is a way to have the same end result and avoid the pivot transformation. The dataframe looks like this: |gender| pro|week| share|forecast| ...
Pyspark Avoid Pivot Transformation To Dataframe - Pivot Alternative
I have a datafrane to which I am applying a pivot transformation and I want to know if there is a way to have the same end result and avoid the pivot transformation. The dataframe looks like this: |gender| pro|week| share|forecast| +------+------------+----+-------------+--------+ | Male| A| ...
[ "performances are poor because you do not provide values for the share column.\ncf. doc pivot(pivot_col, values=None)\nNot providing values is more concise but less efficient, because Spark needs to first compute the list of distinct values internally.\nI can insure you that the current official implementation of p...
[ 0 ]
[]
[]
[ "dataframe", "loops", "pivot", "pyspark", "python" ]
stackoverflow_0074521544_dataframe_loops_pivot_pyspark_python.txt
Q: How to map values from nested dict to Pydantic Model? I am trying to map a value from a nested dict/json to my Pydantic model. For me, this works well when my json/dict has a flat structure. However, I am struggling to map values from a nested structure to my Pydantic Model. Lets assume I have a json/dict in the f...
How to map values from nested dict to Pydantic Model?
I am trying to map a value from a nested dict/json to my Pydantic model. For me, this works well when my json/dict has a flat structure. However, I am struggling to map values from a nested structure to my Pydantic Model. Lets assume I have a json/dict in the following format: d = { "p_id": 1, "billing": { ...
[ "You can customize __init__ of your model class:\nfrom pydantic import BaseModel\n\nd = {\n \"p_id\": 1,\n \"billing\": {\n \"first_name\": \"test\"\n }\n}\n\n\nclass Order(BaseModel):\n p_id: int\n pre_name: str\n\n def __init__(self, **kwargs):\n kwargs[\"pre_name\"] = kwargs[\"bil...
[ 11, 0, 0 ]
[]
[]
[ "pydantic", "python" ]
stackoverflow_0066570894_pydantic_python.txt
Q: How do I get these outputs in 1 single list or dictionary from bs4 import BeautifulSoup import requests with open("htmlviewer.html") as fp: soup = BeautifulSoup(fp, "html.parser") gp = soup.find_all("a") for link in gp: bs = link.get('href') I am using this code to extract links from source code...
How do I get these outputs in 1 single list or dictionary
from bs4 import BeautifulSoup import requests with open("htmlviewer.html") as fp: soup = BeautifulSoup(fp, "html.parser") gp = soup.find_all("a") for link in gp: bs = link.get('href') I am using this code to extract links from source code and here is my output -| None https://support.google.com/web...
[ "First create an empty list outside the for loop, e.g. links = [] and then inside your for loop do links.append(link.get(\"href\"))\n" ]
[ 0 ]
[]
[]
[ "list", "python", "web_scraping" ]
stackoverflow_0074558002_list_python_web_scraping.txt
Q: Converting Flask form data to JSON only gets first value I want to take input from an HTML form and give the output in JSON format. When multiple values are selected they are not converted into JSON arrays, only the first value is used. @app.route('/form') def show_form(): return render_template('form.html') ...
Converting Flask form data to JSON only gets first value
I want to take input from an HTML form and give the output in JSON format. When multiple values are selected they are not converted into JSON arrays, only the first value is used. @app.route('/form') def show_form(): return render_template('form.html') @app.route("/result", methods=['POST']) def show_result(): ...
[ "request.form is a MultiDict. Iterating over a multidict only returns the first value for each key. To get a dictionary with lists of values, use to_dict(flat=False).\nresult = request.form.to_dict(flat=False)\n\nAll values will be lists, even if there's only one item, for consistency. If you want to flatten single...
[ 21 ]
[ "Difference in results when using the \"flat\" parameter:\nresult = request.form.to_dict(flat=True)\nResult: {'a': '6', 'b': '7', 'c': '8'}\nresult = request.form.to_dict(flat=False)\nResult: {'a': ['6'], 'b': ['7'], 'c': ['8']}\n" ]
[ -1 ]
[ "flask", "jinja2", "json", "python" ]
stackoverflow_0045590988_flask_jinja2_json_python.txt
Q: How to post Telegraph article? I want to post a Telegra.ph article using Python and Telegraph API. I tried modules telegraph and python-telegraphapi, but I cannot do it. I try to use example codes of the modules: from telegraph import Telegraph telegraph = Telegraph() telegraph.create_account(short_name='1337') ...
How to post Telegraph article?
I want to post a Telegra.ph article using Python and Telegraph API. I tried modules telegraph and python-telegraphapi, but I cannot do it. I try to use example codes of the modules: from telegraph import Telegraph telegraph = Telegraph() telegraph.create_account(short_name='1337') response = telegraph.create_page( ...
[ "I think you should replace short_name on yours when you create_account:\ntelegraph.create_account(short_name='<your_name>')\n", "There are 2 different solutions for using the API.\nimport json\nMAIN_URL = 'https://api.telegra.ph/'\n\nclass apiuz():\n def __init__(self):\n self.http = requests.Session()...
[ 0, 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0048823781_module_python.txt
Q: Identify if records exist in another dataframe, within the first dataframe I have two csv files, OrderOne (approx 105k records) & OrderTwo (approx 115k records) I want to add a column in OrderTwo which states "TRUE" if that record is found in OrderOne, and "FALSE" if not. The new column should be appended and the ...
Identify if records exist in another dataframe, within the first dataframe
I have two csv files, OrderOne (approx 105k records) & OrderTwo (approx 115k records) I want to add a column in OrderTwo which states "TRUE" if that record is found in OrderOne, and "FALSE" if not. The new column should be appended and the file output. There is no shared key, so I'm creating one. It will the concatena...
[ "As @Clegane identified, the issue here was not the code but the input data containing duplicate records. By including the original reference in the merge then dropping duplicates on OrderTwo['Supplier Reference'] I got the expected answer. Thanks!\n" ]
[ 0 ]
[]
[]
[ "dataframe", "merge", "python" ]
stackoverflow_0074550989_dataframe_merge_python.txt
Q: Single column fetch returning in list in python postgresql Database: id trade token 1 abc 5523 2 fdfd 5145 3 sdfd 2899 Code: def db_fetchquery(sql): conn = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432') cursor = conn.cursor() conn.autocommit ...
Single column fetch returning in list in python postgresql
Database: id trade token 1 abc 5523 2 fdfd 5145 3 sdfd 2899 Code: def db_fetchquery(sql): conn = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432') cursor = conn.cursor() conn.autocommit = True cursor.execute(sql) row = cursor.rowco...
[ "Not sure if you are able to do that without further processing but I would do it like this:\ndata = [x[0] for x in data]\n\nwhich convert the list of tuples to a 1D list\n", "To convert [(5523,),(5145,),(2899,)] to [5523, 5145, 2899] you can use lambda or list comprehension\nusing lambda\nres = [(5523,),(5145,),...
[ 3, 0 ]
[]
[]
[ "list", "postgresql", "python", "python_3.x", "sql" ]
stackoverflow_0068842475_list_postgresql_python_python_3.x_sql.txt
Q: Alternative methods to cartopy functions (manipulating shapely linestrings - Geodetic) Long story short I can't get cartopy to install in my environment so I'm looking for alternative ways of doing things it might be used for. I've recently been following this tutorial which uses cartopy to alter the path of shape...
Alternative methods to cartopy functions (manipulating shapely linestrings - Geodetic)
Long story short I can't get cartopy to install in my environment so I'm looking for alternative ways of doing things it might be used for. I've recently been following this tutorial which uses cartopy to alter the path of shapely linestrings to take into account the curvature of the earth: "Cartopy can be used to mani...
[ "It's probably feasible to implement the great circle algorithms yourself, but there are also other options. If you manage the install pyproj for example, you can use the example below, it samples a given amount of points between two locations on earth.\nNote that although I still use Cartopy to show the coastlines...
[ 1 ]
[]
[]
[ "cartopy", "gis", "python", "shapely" ]
stackoverflow_0074554773_cartopy_gis_python_shapely.txt
Q: Odoo t-field image is appearing empty to public I have a simple controller when shows the people comment in the website along with their pictures. Everything works fine except the image is not appearing when the user logout. here is my controller @http.route('/page/homepage', type='http', auth='public', websi...
Odoo t-field image is appearing empty to public
I have a simple controller when shows the people comment in the website along with their pictures. Everything works fine except the image is not appearing when the user logout. here is my controller @http.route('/page/homepage', type='http', auth='public', website=True) def comment_list(self): comments = reque...
[ "Use img tag.\nlike\n<span>\n <img t-att-src=\"'p.image'\" t-att-class=\"'img-rounded'\" t-att-widget=\"'image'\" />\n</span>\n\nHope it will help you.\n", "I found the problem, it was due to security reason, i add an open access rule of the module. and it worked!\n", "<img t-if=\"line.image_upload\"\n t-...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "odoo_8", "odoo_9", "openerp", "python" ]
stackoverflow_0038067886_odoo_8_odoo_9_openerp_python.txt
Q: How to get an individual row in Big Query? I want to get an individual row from the QueryJob in BQ. My query: select count(*) from ... returns a single row & I want to read the count value which is its first column. So if I can get the first row then I can do row[0] for the first column. I can iterate: row in quer...
How to get an individual row in Big Query?
I want to get an individual row from the QueryJob in BQ. My query: select count(*) from ... returns a single row & I want to read the count value which is its first column. So if I can get the first row then I can do row[0] for the first column. I can iterate: row in queryJob but since I require only the first row this...
[ "Just do:\nrow = self.client.query(count_query)\nresult = row.result().total_rows\n\nThis will give the count from the query\n", "you can use to_dataframe():\nresult = self.client.query(count_query).to_dataframe()\n\n#if you want to result as a integer:\nresult = self.client.query(count_query).to_dataframe()['fir...
[ 0, 0 ]
[]
[]
[ "google_bigquery", "pandas", "python", "sql" ]
stackoverflow_0074557942_google_bigquery_pandas_python_sql.txt
Q: Can't get table data from grid formatted website I am trying to extract data from https://www.lipidmaps.org/databases/lmsd/LMSL01010001. I usually use beautifulsoup or pandas to extract table data. But the tables in the website dont seem to have been made with the table class. For example, the Calculated Physicoch...
Can't get table data from grid formatted website
I am trying to extract data from https://www.lipidmaps.org/databases/lmsd/LMSL01010001. I usually use beautifulsoup or pandas to extract table data. But the tables in the website dont seem to have been made with the table class. For example, the Calculated Physicochemical Properties table has been made with "flex-grow ...
[ "Here is one way of getting that information, and displaying it into a dataframe format:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10...
[ 0 ]
[]
[]
[ "html", "python", "web_scraping" ]
stackoverflow_0074558011_html_python_web_scraping.txt
Q: Add a gaussian noise to a Tensorflow Dataset I have a CSVDataset which has around 6 million rows. For the purposes of this question I am making a TensorSliceDataset as following:- import tensorflow as tf import numpy as np datasetz = tf.data.Dataset.from_tensor_slices((np.random.randn(10, 5), np.random.randn(10,1...
Add a gaussian noise to a Tensorflow Dataset
I have a CSVDataset which has around 6 million rows. For the purposes of this question I am making a TensorSliceDataset as following:- import tensorflow as tf import numpy as np datasetz = tf.data.Dataset.from_tensor_slices((np.random.randn(10, 5), np.random.randn(10,1))) datasetz = datasetz.map(lambda x, y: (x, x)) d...
[ "This adds each row with random noise:\ndatasetz = tf.data.Dataset.from_tensor_slices((np.random.randn(10, 5), np.random.randn(10,1)))\ndatasetz = datasetz.map(lambda x, y: (x+corruption_level*tf.random.uniform(shape=(5,), dtype=tf.float64), y))\ndatasetz\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074558138_python_python_3.x_tensorflow_tensorflow2.0.txt
Q: Translating from Python to C++ I'm struggling to try and convert this from python into c++, please if anyone could help it would be greatly appreciated. Assume that the timern and Day variables are already given so no need for the time.ctime(thing) if Day!=4: timeschedule=["08:30","09:20","10:10","11:00","11:3...
Translating from Python to C++
I'm struggling to try and convert this from python into c++, please if anyone could help it would be greatly appreciated. Assume that the timern and Day variables are already given so no need for the time.ctime(thing) if Day!=4: timeschedule=["08:30","09:20","10:10","11:00","11:30","12:20","13:10","14:00","14:45"] ...
[ "Only focusing on the problem that you're asking about, a possible solution could be (assuming by reading the code snippet provided that we're inside another kind of loop):\nstd::vector<std::string> data = {};\n \nif (getCurrentDOWAsString==\"Saturday\" || getCurrentDOWAsString==\"Sunday\")\n break;\nelse if ...
[ 0 ]
[]
[]
[ "c++", "python", "python_3.x", "time", "translate" ]
stackoverflow_0074555818_c++_python_python_3.x_time_translate.txt
Q: "10.9.8.5", port 5433 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? I am trying to tunnel to my database using python, but crashes with a warning: "10.9.8.5", port 5433 failed: Connection timed out (0x0000274C/10060) Is the server runni...
"10.9.8.5", port 5433 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?
I am trying to tunnel to my database using python, but crashes with a warning: "10.9.8.5", port 5433 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? My python settings: ` with SSHTunnelForwarder( ('10.132.230.2', 22), ...
[ "You're telling your database client to connect directly to 10.9.8.5:5433. That's not how tunneling works.\nThe SSHTunnelForwarder opens a port on your local machine, which it then forwards to the given remote_bind_address through the intermediate ssh server. It doesn't let you magically access the remote server un...
[ 0 ]
[]
[]
[ "postgresql", "python", "ubuntu" ]
stackoverflow_0074557998_postgresql_python_ubuntu.txt
Q: How to apply Video augmentation with keras preprocessing layers uniformly for all frames in the video? I'm trying to apply data augmentation to a video dataset wherein each video is applied with the different augmentations. For example, all frames in video 1 are flipped horizontally and rotated by 10Β°. All frames ...
How to apply Video augmentation with keras preprocessing layers uniformly for all frames in the video?
I'm trying to apply data augmentation to a video dataset wherein each video is applied with the different augmentations. For example, all frames in video 1 are flipped horizontally and rotated by 10Β°. All frames in video 2 on the other hand, are not flipped and rotated by -5Β°. I passed a seed in the preprocessing layer...
[ "Video Augmentation:: For videos, combine time and channel axis and treat it as an image augmentation problem. And reshape the end result to get videos augmented same for all frames.\n#input dimension:\nBATCH, TIME,WIDTH, HEIGHT,_= tf.shape(videos)\n\nStep1: change input shape-(batch, time, width, height, 3) to (b...
[ 1 ]
[]
[]
[ "data_augmentation", "keras", "python", "tensorflow" ]
stackoverflow_0074508852_data_augmentation_keras_python_tensorflow.txt
Q: How to make debug window expressions always stick as watches in PyCharm? I recently updated PyCharm to 2022.2.4 (Professional Edition), and now the debug window looks like so Before updating, The debug window had a "+" icon in which I could add a watch expression. Now, I can type the expression in the top line, b...
How to make debug window expressions always stick as watches in PyCharm?
I recently updated PyCharm to 2022.2.4 (Professional Edition), and now the debug window looks like so Before updating, The debug window had a "+" icon in which I could add a watch expression. Now, I can type the expression in the top line, but a watch is not added and I have to go all the way to the right and click th...
[ "While writing the question, I found the answer. Thought I'd save someone the hassle by posting anyway:\nIn the expression line, notice the text\n\n\"Evaluate expression (Enter) or add a watch (Ctrl + Shift + Enter)\n\nSo just (Ctrl + Shift + Enter) would create a watch.\n\n" ]
[ 0 ]
[]
[]
[ "debugging", "pycahrm", "python", "watch" ]
stackoverflow_0074558534_debugging_pycahrm_python_watch.txt
Q: Optimizing python loop & function I'm looking for some optimization on the below code. I've measured the time of various parts of it, which prompted me to few optimization areas: scores.append(...)) seems to be taking a lot of time, compared to just running the function for the result. Any way to improve the effi...
Optimizing python loop & function
I'm looking for some optimization on the below code. I've measured the time of various parts of it, which prompted me to few optimization areas: scores.append(...)) seems to be taking a lot of time, compared to just running the function for the result. Any way to improve the efficiency of collecting the results? At th...
[ "While testing, I've noticed that\nscores.append(match_simulation(teamHstats.iloc[0], teamAstats.iloc[0], stats, JTimer))\n\nis very inefficient due to teamHstats.iloc[0]. So instead of doing that, I've changed to teamHstat = teamHstats.iloc[0] and match_simulation(teamHstat, ...) which improved speed significantly...
[ 0 ]
[]
[]
[ "dictionary", "list", "loops", "optimization", "python" ]
stackoverflow_0074552971_dictionary_list_loops_optimization_python.txt
Q: NotImplementedError: 'split_respect_sentence_boundary=True' is only compatible with split_by='word' I have the following lines of code from haystack.document_stores import InMemoryDocumentStore, SQLDocumentStore from haystack.nodes import TextConverter, PDFToTextConverter,PreProcessor from haystack.utils import cl...
NotImplementedError: 'split_respect_sentence_boundary=True' is only compatible with split_by='word'
I have the following lines of code from haystack.document_stores import InMemoryDocumentStore, SQLDocumentStore from haystack.nodes import TextConverter, PDFToTextConverter,PreProcessor from haystack.utils import clean_wiki_text, convert_files_to_docs, fetch_archive_from_http, print_answers doc_dir = "C:\\Users\\abcd\...
[ "As you can see in the PreProcessor API docs, the default value for split_respect_sentence_boundary is True.\nIn order to make your code work, you should specify split_respect_sentence_boundary=False:\npreprocessor = PreProcessor(\n clean_empty_lines=True,\n clean_whitespace=True,\n clean_header_footer=Tru...
[ 0 ]
[]
[]
[ "haystack", "preprocessor", "python" ]
stackoverflow_0074557335_haystack_preprocessor_python.txt
Q: How to use map function to save a list of dataframes to the desired path using python I have a code written using for loop to save the dataframes present in a list (Date is the name of the list) to the specified path for Dates in Date: if Dates.empty: pass else: PATH = f'C:/Users/Desktop/' ...
How to use map function to save a list of dataframes to the desired path using python
I have a code written using for loop to save the dataframes present in a list (Date is the name of the list) to the specified path for Dates in Date: if Dates.empty: pass else: PATH = f'C:/Users/Desktop/' + Dates.iloc[0]['Col1'] + '/' + Dates.iloc[0]['Col2'] + '/' if not os.path.exists(P...
[ "Under the assumption that your for loop works correctly you could use a map function as follow:\nimport pandas as pd\n\ndef save_dataframe(Dates: pd.DataFrame):\n if not Dates.empty:\n PATH = f'C:/Users/Desktop/' + Dates.iloc[0]['Col1'] + '/' + Dates.iloc[0]['Col2'] + '/'\n if not os.path.exists(P...
[ 1 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074557880_dataframe_for_loop_pandas_python.txt