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: Syntax error while using psycopg2.copy_expert I use psycopg2 to call PostgreSQL COPY command from my programs written in Python, and so far I have used copy_from function in that package to achieve this. As I understand, in recent versions qualified names for tables, that is, scheman_name.table_name are no more au...
Syntax error while using psycopg2.copy_expert
I use psycopg2 to call PostgreSQL COPY command from my programs written in Python, and so far I have used copy_from function in that package to achieve this. As I understand, in recent versions qualified names for tables, that is, scheman_name.table_name are no more authorized while using copy_from for security reasons...
[ "General tip. Assign a composed query to a variable and print it to see what is wrong.\n copy_cmd = sql.SQL(\n \"copy {} from stdin with ({})\"\n ).format(\n sql.Identifier(\"dev_schema\", \"testtab\"),\n copy_options\n )\n print(copy_cmd.as_string(connec...
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074331813_postgresql_psycopg2_python.txt
Q: I can't get the title to change on tkinter from tkinter import * win = Tk() win.title("Calculator") **Above is the code that I am using. It just doesn't seem to work for some reason. ** This seems to be the correct way as far as Google is concerned LOL. I need some expertise! A: Was unable to reproduce the err...
I can't get the title to change on tkinter
from tkinter import * win = Tk() win.title("Calculator") **Above is the code that I am using. It just doesn't seem to work for some reason. ** This seems to be the correct way as far as Google is concerned LOL. I need some expertise!
[ "Was unable to reproduce the error. \nFirst lets check that Tkinter is properly installed in your system if everything is working correctly a tkinter window show open.\npython -m tkinter\n\nSecond try the code bellow\nmain.py\nfrom tkinter import *\n\nwin = Tk()\nwin.title(\"Calculator\")\n\nwin.mainloop()\n\n\nFur...
[ 0 ]
[]
[]
[ "graphics", "python", "tkinter" ]
stackoverflow_0074331792_graphics_python_tkinter.txt
Q: Retrieving function arguments from *args and **kwargs Let's say I have a function f() which I know accepts 1 argument, action, followed by a variable number of arguments. Depending on the initial action value, the function expects a different set of following arguments, e.g. for action 1 we know we must have 3 ext...
Retrieving function arguments from *args and **kwargs
Let's say I have a function f() which I know accepts 1 argument, action, followed by a variable number of arguments. Depending on the initial action value, the function expects a different set of following arguments, e.g. for action 1 we know we must have 3 extra arguments p1, p2 and p3. Depending on how the function w...
[ "I would call a sub-function with a defined argument list within f:\ndef f(action, *args, **kwargs):\n if action == 1:\n f_1(*args, **kwargs)\n ...\n\ndef f_1(p1, p2, p3):\n # now you know the args\n\nOf course, this raises the question why you need the over-all function, but let's assume you have a...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074331939_python.txt
Q: How do I find the x and y values in an array where the array is divided equally in a cartesian orientation? What I'm trying to do is simply find and define an x and y coordinate for the highest number in the array. For example, 50000 would output: x = 2, y = 2. Is there an easy way to accomplish this? I created th...
How do I find the x and y values in an array where the array is divided equally in a cartesian orientation?
What I'm trying to do is simply find and define an x and y coordinate for the highest number in the array. For example, 50000 would output: x = 2, y = 2. Is there an easy way to accomplish this? I created this code below: data_array = [[0, 1, 2, 3, 50000], [5, 6, 7, 8, 9], [10, 11, 12, 13, 1...
[ "Modify 2 lines in your program:\nprint(\"x =\", x-2)\nprint(\"y =\", y+2)\n\n", "if you could use numpy do the argmax like this then find the coordinate (row col) and coordinate switch to chartersian (reverse y) then both subtracte the half , (considering it is even in both dimentions.\nidx = np.argmax(data_arra...
[ 0, 0 ]
[]
[]
[ "cartesian", "coordinates", "numpy", "output", "python" ]
stackoverflow_0074331883_cartesian_coordinates_numpy_output_python.txt
Q: module import : NameError (name 'A' is not defined ) I have created a module which calculates QR decomposition and tests .It contains several different functions. I have saved this file as Numla.py . I want to import these functions in Jupyter Notebook but I keep having this error . I have also tried other importi...
module import : NameError (name 'A' is not defined )
I have created a module which calculates QR decomposition and tests .It contains several different functions. I have saved this file as Numla.py . I want to import these functions in Jupyter Notebook but I keep having this error . I have also tried other importing methods e.g from Numla import qr , from Numla import * ...
[ "To import a function, just use the function name without the arguments:\nfrom Numla import qr\n\nYou can then use the function qr in your notebook.\nI've tested this locally and it works. It will work fine as long as Numla.py is in a directory in your Python path. If you continue having issues with Colab you might...
[ 0 ]
[]
[]
[ "import", "importerror", "module", "nameerror", "python" ]
stackoverflow_0074331982_import_importerror_module_nameerror_python.txt
Q: Why does the object have no Attribute 'privileges'? ` class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user (self): full_name = f"{self.first_name.title()} {self.last_name.titl...
Why does the object have no Attribute 'privileges'?
` class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user (self): full_name = f"{self.first_name.title()} {self.last_name.title()}" return full_name def greet_user (self):...
[ "The problem is your Admin class never initialized self.privileges, due to not having an init method. This was due to a typo.\nYou had\nclass Admin (User):\n def __ini__ (self, first_name, last_name):\n super().__init__(first_name, last_name)\n self.privileges = ['registrar authorization','content ...
[ 0 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0074324846_attributeerror_python.txt
Q: ImportError: cannot import name <...> (most likely due to a circular import) I have an issue with relative imports in python. (I really can't do these imports the other way...) Structure of my project is similar to this: app β”œβ”€β”€β”€schemas └───__init__.py └───a.py └───b.py └───c.p...
ImportError: cannot import name <...> (most likely due to a circular import)
I have an issue with relative imports in python. (I really can't do these imports the other way...) Structure of my project is similar to this: app β”œβ”€β”€β”€schemas └───__init__.py └───a.py └───b.py └───c.py └───d.py In file a.py are classes A, ABase. Files b.py, c.py, d.py are...
[ "Round Robin import or circular import only occurs when a imports b which imports a which etc.. I'm not sure why the above would cause this unless you've omitted something. However one thing you may be able to try is using the typing libraries TYPE_CHECK argument which is always False at runtime and True otherwise....
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_import" ]
stackoverflow_0074332091_python_python_3.x_python_import.txt
Q: Numpy: Boolean operation on np.array passed into function Numpy allows to pass a numpy.array as argument into a function and evaluate the function for every element of the array.: def f(n): return n**2 arr = np.array([1,2,3]) f(arr) outputs: >>>[1 4 9] This works fine, as long as f(n)doesn't perform boolean...
Numpy: Boolean operation on np.array passed into function
Numpy allows to pass a numpy.array as argument into a function and evaluate the function for every element of the array.: def f(n): return n**2 arr = np.array([1,2,3]) f(arr) outputs: >>>[1 4 9] This works fine, as long as f(n)doesn't perform boolean operations on n like this: def f(n): if n%2 == 0: ...
[ "do you want to try something like this? https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html\nimport numpy as np\n\narr = np.array([1,2,3])\n\ndef f(n):\n if n%2 == 0:\n print(n)\n return n**2\n\nvfunc = np.vectorize(f) \nvfunc(arr) \n\noutputs:\n2\narray([1, 4, 9])\n\nw...
[ 1, 0 ]
[]
[]
[ "boolean_operations", "numpy", "python" ]
stackoverflow_0074329696_boolean_operations_numpy_python.txt
Q: Converting a number to binary with a fixed length Say I get a random number between 1 and 127. I change the number to binary and remove the 0b from it with the following code: key_one= int(raw_input("Enter key (0 <= key <= 127): ")) if key_one in range(128): bin_key_one=bin(key_one)[2:] print bin_key_one else...
Converting a number to binary with a fixed length
Say I get a random number between 1 and 127. I change the number to binary and remove the 0b from it with the following code: key_one= int(raw_input("Enter key (0 <= key <= 127): ")) if key_one in range(128): bin_key_one=bin(key_one)[2:] print bin_key_one else: print "You have to enter key (0 <= key <= 127)" ...
[ "No you don't.\n>>> '{0:07b}'.format(12)\n'0001100'\n\n", "So it happens that Python has a string method .zfill() for that:\n>>> '1'.zfill(7)\n'0000001'\n>>> '10010'.zfill(7)\n'0010010'\n\n", "With Python 3.6's new f-strings, you can now do:\nkey_one = int(input(\"Enter key (0 <= key <= 127): \"))\n\nif key_one...
[ 92, 39, 6, 3, 2, 1, 1, 0 ]
[ "Try this:\nfor i in range(1, 127):\n'0'*(7-len(bin(i)[2:]))+bin(i)[2:]\n\n" ]
[ -2 ]
[ "for_loop", "python" ]
stackoverflow_0003252528_for_loop_python.txt
Q: Parsing with Python Help me How can I pull all coordinates value (56.10457, 47.211815,36.130162, 67.135758) from the entire text? <script> data = milestonesMap.getEmptyData(); data.points.push({ properties: { ...
Parsing with Python Help me
How can I pull all coordinates value (56.10457, 47.211815,36.130162, 67.135758) from the entire text? <script> data = milestonesMap.getEmptyData(); data.points.push({ properties: { balloonContentHeader:...
[ "user regex:\ncoord = re.findall(\"coordinates: \\[([0-9., ]*),([0-9., ]*)\\]\", soup)\n\noutput\n[('46.10457', ' 67.211815'), ('36.130162', ' 67.135758')]\n\nor just re.findall(\"coordinates: \\[([0-9., ]*)\\]\", soup) to have both long, lat as one tuple\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074332145_python.txt
Q: How can I seperate my one long column name into columns I have this CSV file and this column name ['school;sex;age;address;famsize;Pstatus;Medu;Fedu;Mjob;Fjob;reason;guardian;traveltime;studytime;failures;schoolsup;famsup;paid;activities;nursery;higher;internet;romantic;famrel;freetime;goout;Dalc;Walc;health;absen...
How can I seperate my one long column name into columns
I have this CSV file and this column name ['school;sex;age;address;famsize;Pstatus;Medu;Fedu;Mjob;Fjob;reason;guardian;traveltime;studytime;failures;schoolsup;famsup;paid;activities;nursery;higher;internet;romantic;famrel;freetime;goout;Dalc;Walc;health;absences;G1;G2;G3'] This includes only 1 column but I want to sep...
[ "if example.csv is mixing separators like\nID,Name,school;sex;age;address\n1,Bart,Springfield;M;10;123 terrace st\n1,Lisa,Springfield;M;8;123 terrace st\n\nyou can use the regexp [,;] to match either\nimport pandas as pd\npd.read_csv('example.csv', sep='[,;]')\n\n[if the csv file extension is misleading -- not actu...
[ 0 ]
[]
[]
[ "csv", "dataframe", "python" ]
stackoverflow_0074332162_csv_dataframe_python.txt
Q: How to compare letters from a input string to letters in a a different string from a given list? Hi I'm trying to make a word game, where the user guesses a word from a word in a given list, and the program tells the user what words they got wrong. The problem I'm having is that my program does not check for the w...
How to compare letters from a input string to letters in a a different string from a given list?
Hi I'm trying to make a word game, where the user guesses a word from a word in a given list, and the program tells the user what words they got wrong. The problem I'm having is that my program does not check for the words that the user inputs, but instead checks the validity of the word from the word list. How do I ch...
[ "This code will check letter by letter to see if user input matches random word from a given list:\ndef checkLetters(secretWord, userWord):\n print(f'Secret word: {secretWord}, user word: {userWord}')\n if len(secretWord) != len(userWord):\n return False\n\n for i, letter in enumerate(secretWord):\n...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074332150_list_python.txt
Q: How to read a file in Python written out by C++ I have one program written in C++ that outputs the data from several different types of arrays. For simplicity, I'm using ints and just writing them out one at a time to figure this out. I need to be able to read the file in on Python, but clearly am missing somethin...
How to read a file in Python written out by C++
I have one program written in C++ that outputs the data from several different types of arrays. For simplicity, I'm using ints and just writing them out one at a time to figure this out. I need to be able to read the file in on Python, but clearly am missing something. I'm having trouble translating the concepts from C...
[ "In the simple case you have provided, it is easy to write the Python code to read out 1234 and 5678 (assuming sizeof(int) is 4 bytes) by using int.from_bytes.\nAnd you should open the file in binary mode.\nimport sys\n\nwith open(\"out.txt\", \"rb\") as f:\n while (byte := f.read(4)):\n print(int.from_by...
[ 2 ]
[]
[]
[ "c++", "file_read", "file_writing", "python" ]
stackoverflow_0074332135_c++_file_read_file_writing_python.txt
Q: Converting audio files from .wav to mp3 using GNU Parallel I am trying to convert a full folder of audio files(.wav) to .mp3 by changing the bitrate. The problem is each audio file name consist of multiple '.' and ends with .wav. I am using gnu-parallel to convert the audio signals bitrate and save them as .mp3. M...
Converting audio files from .wav to mp3 using GNU Parallel
I am trying to convert a full folder of audio files(.wav) to .mp3 by changing the bitrate. The problem is each audio file name consist of multiple '.' and ends with .wav. I am using gnu-parallel to convert the audio signals bitrate and save them as .mp3. My command line: ls wavs | cut -d '.' -f 1 | parallel -I% ffmpeg ...
[ "I know 3 month ...\nReplace \"wavs/%.wav\" by {}\nand\nReplace \"wavs_2/%.mp3\" by {}.finalname.mp3\nA complete line working for me:\nparallel -a \"/dev/shm/findaudio.txt\" ffmpeg -i {} -codec:a libmp3lame -b:a 320k {}.320k.mp3\nI search files before and put in findaudio.txt\nFull batch here:\nhttps://github.com/L...
[ 0 ]
[]
[]
[ "audio", "bitrate", "lossy_compression", "python" ]
stackoverflow_0073112037_audio_bitrate_lossy_compression_python.txt
Q: pandas computing new column as a average of other two conditions So I have this dataset of temperatures. Each line describe the temperature in celsius measured by hour in a day. So, I need to compute a new variable called avg_temp_ar_mensal which representsthe average temperature of a city in a month. City in thi...
pandas computing new column as a average of other two conditions
So I have this dataset of temperatures. Each line describe the temperature in celsius measured by hour in a day. So, I need to compute a new variable called avg_temp_ar_mensal which representsthe average temperature of a city in a month. City in this dataset is represented as estacao and month as mes. I'm trying to do...
[ "You are calling a groupby on a single column when you are doing df2['temp_ar'].groupby(...). This doesn't make much sense since in a single column, there's nothing to group by.\nInstead, you have to perform the groupby on all the columns you need. Also, make sure that the final output is a series and not a datafra...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074331877_dataframe_pandas_python.txt
Q: TransportError: HTTPSConnectionPool error calling Google Cloud Speech API from Python 2.7 I downloaded Google Cloud SDK by following https://cloud.google.com/sdk/docs/quickstart-debian-ubuntu . And I downloaded Google Speech API by following https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/...
TransportError: HTTPSConnectionPool error calling Google Cloud Speech API from Python 2.7
I downloaded Google Cloud SDK by following https://cloud.google.com/sdk/docs/quickstart-debian-ubuntu . And I downloaded Google Speech API by following https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/speech/cloud-client . When I run python transcribe.py resources/audio.raw, the error happens....
[ "It looks a grpcio issue that's causing the error. I suggest installing the latest version the Cloud Speech API client library (which specifies its required version of grpcio) and try again. Rather than downloading it from GH, I suggest using pip install instead.\n\"Hello World\" s2t-demo.py example (Py2&3 compatib...
[ 0 ]
[]
[]
[ "google_cloud_platform", "google_speech_api", "oauth", "python", "python_2.7" ]
stackoverflow_0046832451_google_cloud_platform_google_speech_api_oauth_python_python_2.7.txt
Q: Can I define an action on file upload when using ipywidgets FileUpload widget I want to create an event off the uploading of a file with widgets.FileUpload same as I would do with an widgets.Button using the .on_click(some_function). Is there a way to do something like this import ipywidgets as widgets def do_so...
Can I define an action on file upload when using ipywidgets FileUpload widget
I want to create an event off the uploading of a file with widgets.FileUpload same as I would do with an widgets.Button using the .on_click(some_function). Is there a way to do something like this import ipywidgets as widgets def do_something_with_file(fu): content = fu.data[0].decode('utf-8') # doing somet...
[ "You can observe the change in _counter\nExample:\nfrom ipywidgets import widgets\nuploader = widgets.FileUpload()\ndisplay(uploader)\n\ndef on_upload_change(change):\n print(change)\n\nuploader.observe(on_upload_change, names='_counter')\n\n", "The above answer is not working anymore, with ipywidgets version ...
[ 8, 0 ]
[]
[]
[ "ipython", "jupyter", "jupyter_notebook", "python", "widget" ]
stackoverflow_0059259414_ipython_jupyter_jupyter_notebook_python_widget.txt
Q: Downloading all Images from a page with beautifulSoup not working I am trying to download the show images from this page with beautifulsoup. When I run the below code the only image that downloads is the spinning loading icon. When I check the requests tab on the page I can see requests for all the other images on...
Downloading all Images from a page with beautifulSoup not working
I am trying to download the show images from this page with beautifulsoup. When I run the below code the only image that downloads is the spinning loading icon. When I check the requests tab on the page I can see requests for all the other images on the page so assume they should be downloaded as well. I am not sure wh...
[ "You can try via the api they seem to be using to populate the page\napi_url = 'https://apis-edge-prod.tech.tvnz.co.nz/api/v1/web/play/page/categories/sci-fi-and-fantasy'\nr = requests.get(api_url)\ntry:\n embVals = r.json()['_embedded'].values() \nexcept Exception as e:\n embVals = []\n print('failed to g...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074294192_beautifulsoup_python.txt
Q: Syntax confusion over posting to database I am following a tutorial by Telusko. He switched to PostgreSQL but I decided to continue with SQLite. He showed this code to add a user to the database: def register(request): if request.method == "POST": firstname= request.POST['firstname'] lastname= request.P...
Syntax confusion over posting to database
I am following a tutorial by Telusko. He switched to PostgreSQL but I decided to continue with SQLite. He showed this code to add a user to the database: def register(request): if request.method == "POST": firstname= request.POST['firstname'] lastname= request.POST['lastname'] email= request.POST['email'...
[ "You must be using django's default ModelManager, which doesn't have the create_user method. You need to inherit from AbstractBaseUser class instead of models.Model in your User model and add objects = UserManager() to your model, like below:\nfrom django.contrib.auth.models import AbstractBaseUser, UserManager\n\...
[ 1 ]
[]
[]
[ "django", "django_views", "post", "python", "sqlite" ]
stackoverflow_0074332240_django_django_views_post_python_sqlite.txt
Q: py2neo: Graph.find_one with multiple key/values I have some trouble with the py2neo find and find_one (http://py2neo.org/2.0/essentials.html) What I want in Cypher is: MATCH (p:Person) WHERE p.name='Alice' AND p.age=22 RETURN p Say, where there are more than one key/value set (eg. if there are more than one 'Alic...
py2neo: Graph.find_one with multiple key/values
I have some trouble with the py2neo find and find_one (http://py2neo.org/2.0/essentials.html) What I want in Cypher is: MATCH (p:Person) WHERE p.name='Alice' AND p.age=22 RETURN p Say, where there are more than one key/value set (eg. if there are more than one 'Alice' in the graph). My problem is that I don't know wha...
[ "If you look at the source code you will find that unfortunately find and find_one don't support that type of queries. You should directly use the Cypher interface:\nd = {'name': 'Alice', 'age' : 22}\n\n# quote string values\nd = {k:\"'{}'\".format(v) if isinstance(v, basestring) else v \n for ...
[ 5, 2, 0 ]
[]
[]
[ "neo4j", "py2neo", "python" ]
stackoverflow_0027795874_neo4j_py2neo_python.txt
Q: can anyone provide me the solution for problem in python string Write a function to replace concatenated or splitted tokens in target string. Test Case 1: Input: name = "salman salim khan" record_name = "mohd salmansalim khan" Output: 'mohd salman salim khan' Test Case 2: Input: name = "salmansalim khan" record_na...
can anyone provide me the solution for problem in python string
Write a function to replace concatenated or splitted tokens in target string. Test Case 1: Input: name = "salman salim khan" record_name = "mohd salmansalim khan" Output: 'mohd salman salim khan' Test Case 2: Input: name = "salmansalim khan" record_name = "mohd salman salim khan" Output: 'mohd salmansalim khan' I have ...
[ "Try this code. It seems to work for the input values given. The commented out lines are just for debugging.\ninp1=input(\"Name:\") #'salman salim khan'\nrecord_name=input(\"Record name:\") #'mohd salmansalim khan'\nd1=inp1.split(\" \")\nd2=record_name.split(\" \")\nlast_d1 = None\nlast_d2 = None\nfor token in d1:\...
[ 0 ]
[]
[]
[ "python", "split", "string", "string_concatenation" ]
stackoverflow_0074325156_python_split_string_string_concatenation.txt
Q: Python problem with exporting numpy matrix to tiff file using cv2.imshow then reading it I am trying to export my NumPy matrix to a .tiff file then to read its contents to verify if it worked. Given the following snippet import numpy as np import cv2 data = np.array([[-0.1 for _ in range(128)] for _ in range(128)...
Python problem with exporting numpy matrix to tiff file using cv2.imshow then reading it
I am trying to export my NumPy matrix to a .tiff file then to read its contents to verify if it worked. Given the following snippet import numpy as np import cv2 data = np.array([[-0.1 for _ in range(128)] for _ in range(128)], dtype=np.float32) cv2.imwrite('temp.tiff', data) print('tiff file written') image = cv2.im...
[ "cv2.imread() has a second parameter, flags, which specifies how to read the image file. According the the docs, the default value of the flags argument to imread() is this:\n\nIMREAD_COLOR\nIf set, always convert image to the 3 channel BGR color image.\n\nSource: imread docs, IMREAD_COLOR docs.\nBy default, OpenCV...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x", "tiff" ]
stackoverflow_0074331447_python_python_3.x_tiff.txt
Q: Why doesn't my function work as a function but the code itself does when replaced with the function? (Python) I'm trying to get my number-guessing game to work and I got it but I just don't understand why it doesn't work, when I have my guess input as a function. Here is the original code where it doesn't work imp...
Why doesn't my function work as a function but the code itself does when replaced with the function? (Python)
I'm trying to get my number-guessing game to work and I got it but I just don't understand why it doesn't work, when I have my guess input as a function. Here is the original code where it doesn't work import random targetMin = int(input("Enter your range's minimum number: ")) targetMax = int(input("Enter your range's...
[ "You are calling takeGuess(), and takeGuess() is returning a value, but you aren't doing anything with the result. To make it work, you need to store the result of takeGuess() in guess. Like this:\nimport random\n\ntargetMin = int(input(\"Enter your range's minimum number: \"))\ntargetMax = int(input(\"Enter your r...
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074332339_function_python.txt
Q: How to add property to PostgreSQL database that is hosted on Heroku with Flask/Python? I have a database for my website that is hosted on Heroku and uses Flask and Python. The model structure looks like: class MyDataModel(db.Model): id = db.Column(db.Integer, primary_key=True) property1 = db.Column(db.Stri...
How to add property to PostgreSQL database that is hosted on Heroku with Flask/Python?
I have a database for my website that is hosted on Heroku and uses Flask and Python. The model structure looks like: class MyDataModel(db.Model): id = db.Column(db.Integer, primary_key=True) property1 = db.Column(db.String(240), default = "") property2 = db.Column(db.String(240), default = "") property3...
[ "SQLAlchemy allows you to automatically create the database structure based on your model. But this function does not update tables if they are already in the database. This is default SQLAlchemy behavior.\nTo update the table structure based on the model you need to do a migration using a migration library like Al...
[ 4, 1 ]
[]
[]
[ "flask", "heroku", "heroku_postgres", "postgresql", "python" ]
stackoverflow_0074176036_flask_heroku_heroku_postgres_postgresql_python.txt
Q: NameError: name 'lab2' is not defined I have a problem, when I am creating a Label in function (def), and after I am trying to destroy this Label, using other fucntion (def), it says, that lab2 is not defined from tkinter import* root=Tk() root.geometry("500x300") def com1(): global lab, but lab.destroy(...
NameError: name 'lab2' is not defined
I have a problem, when I am creating a Label in function (def), and after I am trying to destroy this Label, using other fucntion (def), it says, that lab2 is not defined from tkinter import* root=Tk() root.geometry("500x300") def com1(): global lab, but lab.destroy() but.destroy() lab=Label(text="Lab...
[ "just global lab2:\nfrom tkinter import*\n\nroot=Tk()\nroot.geometry(\"500x300\")\n\ndef com1():\n global lab, but,lab2\n lab.destroy()\n but.destroy()\n lab=Label(text=\"Label 2\")\n lab.place(x=237, y=27)\n but=Button(text=\"Go to first screen\", command=com2)\n but.place(x=200, y=57)\n la...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074332257_python.txt
Q: How to check a string for specific characters? How can I check if a string has several specific characters in it using Python 2? For example, given the following string: The criminals stole $1,000,000 in jewels. How do I detect if it has dollar signs ("$"), commas (","), and numbers? A: Assuming your string is...
How to check a string for specific characters?
How can I check if a string has several specific characters in it using Python 2? For example, given the following string: The criminals stole $1,000,000 in jewels. How do I detect if it has dollar signs ("$"), commas (","), and numbers?
[ "Assuming your string is s:\n'$' in s # found\n'$' not in s # not found\n\n# original answer given, but less Pythonic than the above...\ns.find('$')==-1 # not found\ns.find('$')!=-1 # found\n\nAnd so on for other characters.\n... or\npattern = re.compile(r'\\d\\$,')\nif pattern.findall(s):\n print('Fou...
[ 328, 34, 16, 6, 2, 1, 0 ]
[ "s=input(\"Enter any character:\") \nif s.isalnum(): \n print(\"Alpha Numeric Character\") \n if s.isalpha(): \n print(\"Alphabet character\") \n if s.islower(): \n print(\"Lower case alphabet character\") \n else: \n print(\"Upper case alphabet character\") \...
[ -2 ]
[ "python", "string" ]
stackoverflow_0005188792_python_string.txt
Q: Valid json pipeline Scrapy I output the scraped data in JSON format. Custom scrapy pipeline outputs a list of dictionaries in JSON format. Item type looks like this: [{ "product_id": "11980174", "brand_id": 25354, "brand_name": "Gucci", "title": "beige and brown Dionysus GG Supreme mini canvas shou...
Valid json pipeline Scrapy
I output the scraped data in JSON format. Custom scrapy pipeline outputs a list of dictionaries in JSON format. Item type looks like this: [{ "product_id": "11980174", "brand_id": 25354, "brand_name": "Gucci", "title": "beige and brown Dionysus GG Supreme mini canvas shoulder bag", "slug": "/shoppin...
[ "Don't try to convert a dictionary to JSON yourself. Instead, use json.dumps() from the json package. Like this:\nimport json\n\n\ndata = [{\n \"product_id\": \"11980174\",\n \"brand_id\": 25354,\n \"brand_name\": \"Gucci\",\n \"title\": \"beige and brown Dionysus GG Supreme mini canvas shoulder bag\",\...
[ 0, 0 ]
[]
[]
[ "json", "python", "scrapy" ]
stackoverflow_0074332369_json_python_scrapy.txt
Q: How can I print my default gateway using Python? This line is giving me an error: print(ifcfg.default_interface()) He is the whole code: import ifcfg import json for name, interface in ifcfg.interfaces().items(): # do something with interface print (interface['device']) # Device name print (inte...
How can I print my default gateway using Python? This line is giving me an error: print(ifcfg.default_interface())
He is the whole code: import ifcfg import json for name, interface in ifcfg.interfaces().items(): # do something with interface print (interface['device']) # Device name print (interface['inet']) # First IPv4 found print (interface['inet4']) # List of ips print(ifcfg.default_interf...
[ "From what I was able to gather this is a Windows specific issue. Ifcfg class WindowsParser currently has no method _default_interface.\nYou can try and write your own here's the path.\nC:..\\Programs\\Python\\Python310\\lib\\site-packages\\ifcfg\\parser.py\n\nFor reference here's the UNUX version of _default_inter...
[ 0 ]
[]
[]
[ "default", "gateway", "python" ]
stackoverflow_0074331701_default_gateway_python.txt
Q: How to understand snippet of Regex I am attempting to understand what this snippet of code does: passwd1=re.sub(r'^.*? --', ' -- ', line) password=passwd1[4:] I understand that the top line uses regex to remove the " -- ", and the bottom line I think removes something as well? I went back to this code after a whi...
How to understand snippet of Regex
I am attempting to understand what this snippet of code does: passwd1=re.sub(r'^.*? --', ' -- ', line) password=passwd1[4:] I understand that the top line uses regex to remove the " -- ", and the bottom line I think removes something as well? I went back to this code after a while and need to improve it but to do that...
[ "To break r'^.*? -- into pieces:\n\nr in front of a string in Python lets the interpreter know that it's a regex string. This lets you not have to do a bunch of confusing character escaping.\nThe ^ tells the regex to match only from the beginning of the string.\n.*? tells the regex to match any number of characters...
[ 4, 2, 1 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0074332390_python_python_3.x_regex.txt
Q: I set 3 arrays to the same thing, changing a single entry in one of them also changes the other two arrays. How can I make the three arrays separate? I am making a puzzle game in a command terminal. I have three arrays for the level, originlevel, which is the unaltered level that the game will return to if you res...
I set 3 arrays to the same thing, changing a single entry in one of them also changes the other two arrays. How can I make the three arrays separate?
I am making a puzzle game in a command terminal. I have three arrays for the level, originlevel, which is the unaltered level that the game will return to if you restart the level. Emptylevel is the level without the player. Level is just the level. I need all 3, because I will be changing the space around the player. ...
[ "This issue is caused by the way variables work in Python. If you want more background on why this is happening, you should look up 'pass by value versus pass by reference'.\nIn order for each of these arrays to be independent, you need to create a copy each time you assign it. The easiest way to do that is to use ...
[ 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074332432_arrays_python.txt
Q: Python: adding sets in a set during a 'For loop' and do the 'For loop' only for the added sets I have one initial SET containing sets within it. And I want to do a 'For loop' for each set and if conditions are met after doing some function, create a new sets and add them to the original SET. E.g. Org_Set = {frozen...
Python: adding sets in a set during a 'For loop' and do the 'For loop' only for the added sets
I have one initial SET containing sets within it. And I want to do a 'For loop' for each set and if conditions are met after doing some function, create a new sets and add them to the original SET. E.g. Org_Set = {frozenset({1}), frozenset({2}), frozenset({3}), frozenset({4})} for s in Org_Set: C = set(s) ...
[ "In Python, sets do not have a specified iteration order; adding new elements to the set during an iteration has unspecified results (and usually they are not very pleasant).\nSince Python 3.7, dictionaries do have a specified iteration order (the order in which the keys were inserted into the dictionary. However, ...
[ 0 ]
[]
[]
[ "for_loop", "iteration", "nested_for_loop", "python" ]
stackoverflow_0074332371_for_loop_iteration_nested_for_loop_python.txt
Q: Python CSV read a single column as a list I have this code: type(i[0]) == 'str'. How can I get it as a list? and later get print(i[0][0]) == 'a' import csv i = [['a', 'b'], 'c', 'd'] with open('a.csv', 'a', newline='', encoding='utf-8') as file: writer = csv.writer(file, delimiter=';') writer.writerow(i) ...
Python CSV read a single column as a list
I have this code: type(i[0]) == 'str'. How can I get it as a list? and later get print(i[0][0]) == 'a' import csv i = [['a', 'b'], 'c', 'd'] with open('a.csv', 'a', newline='', encoding='utf-8') as file: writer = csv.writer(file, delimiter=';') writer.writerow(i) file.close() with open('a.csv', 'r', newline=''...
[ "You can use a for-loop. Like this:\nexample a.csv\nhello, aloha, hola\nbye, aloha, adios\n\npython code:\nimport csv\n\n\ncol1 = []\nwith open('a.csv') as file:\n r = csv.reader(file)\n for row in r:\n col1.append(row[0])\n\nprint(col1) # => ['hello', 'bye']\n\nAlternatively, you could also use a li...
[ 1, 1 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0074332403_csv_list_python.txt
Q: Can't assign the "sum of np.random.normal" in a element of array I am using numpy and matlibplot.pyplot as libraries. I made random number by random.normal and take the summary of them. Then, I tried to assgin the value to each element in the array "sum". I made a zero array (float type) by np.zeros and then assig...
Can't assign the "sum of np.random.normal" in a element of array
I am using numpy and matlibplot.pyplot as libraries. I made random number by random.normal and take the summary of them. Then, I tried to assgin the value to each element in the array "sum". I made a zero array (float type) by np.zeros and then assign the value in following way. (code is shown below) When I conduct thi...
[ "The X array you create has a size of 10 x 1. When you do a numpy sum, the axis you select is 0-based, so you are doing a sum over the \"1\" dimension (the second dimension) and getting an array that is still 10 x 1 for Y.\nTo fix it, you want to either set the axis to 0\nX = np.random.normal(size=(10,1))\nY = np.s...
[ 0 ]
[]
[]
[ "numpy_random", "python" ]
stackoverflow_0074332452_numpy_random_python.txt
Q: Number of installations statistics for PyPI packages? I've got a couple of packages on the Python Package Index (PyPI) now. Is there any way to get hold of statistics as to how many times they have been downloaded (either manually or via easy_install or pip? Or, alternatively, how many views the main package page ...
Number of installations statistics for PyPI packages?
I've got a couple of packages on the Python Package Index (PyPI) now. Is there any way to get hold of statistics as to how many times they have been downloaded (either manually or via easy_install or pip? Or, alternatively, how many views the main package page has received?
[ "There are at least two packages that help with this: pypstats and vanity. Vanity is very easy to use from the command line: \nvanity numpy \n\nand you'll get a printout to your console. \n", "I have tried the different methods in the other answers. As far as I am concerned, vanity does not work anymore, the rea...
[ 26, 10, 9, 6, 6, 2, 2, 2, 1, 0 ]
[]
[]
[ "pypi", "python" ]
stackoverflow_0010376429_pypi_python.txt
Q: kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget error My code was pretty simple but it ended up running and closing with the message : "kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget." at the bottom, any ideas on what this might mean?...
kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget error
My code was pretty simple but it ended up running and closing with the message : "kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget." at the bottom, any ideas on what this might mean?
[ "I will suggest you following project structure:\nmain.py - Python main program\ncrying.kv - screens definition KV file (filename same as app class name, lowercase)\nmain.kv - main screen KV file\nlogin.kv - login screen KV file\nsignup.kv - signup screen KV file\n\nmain.py\nfrom kivymd.app import MDApp\nfrom kivy...
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python" ]
stackoverflow_0074329660_kivy_kivymd_python.txt
Q: how to make a pivot table based on the occurrence of a value in a certain parameter? hello! For example, I have a table with mailing addresses. Some mailing addresses read my emails and some didn't. The table looks like this: I want to make a pit, in which the index will be an email, in the columns number of the ...
how to make a pivot table based on the occurrence of a value in a certain parameter?
hello! For example, I have a table with mailing addresses. Some mailing addresses read my emails and some didn't. The table looks like this: I want to make a pit, in which the index will be an email, in the columns number of the letter (1,2,3,4). And in the values, the fact that the user read or not read (read / not r...
[ "df\n adress number\n0 A 1\n1 A 2\n2 A 4\n3 B 1\n4 B 2\n\nuse crosstab and reindex\n(pd.crosstab(df.adress, df.number)\n .reindex(columns=range(1, df.number.max() + 1))\n .fillna(0)\n .replace({1:'yes', 0:'no'})\n)\n\noutput\nnumber 1 2 3 4\nadress \nA yes yes no yes\n...
[ 0 ]
[]
[]
[ "pandas", "pivot_table", "python" ]
stackoverflow_0074332419_pandas_pivot_table_python.txt
Q: Difficulty comparing generated and google cloud storage provided CRC32c checksums I am attemptting to get a CRC32c checksum on my local file so I can compare it to the blob.crc32c provided by the gcloud library. Google says I should be using the crcmod module in order to actually calculate CRC32c hashes of my data...
Difficulty comparing generated and google cloud storage provided CRC32c checksums
I am attemptting to get a CRC32c checksum on my local file so I can compare it to the blob.crc32c provided by the gcloud library. Google says I should be using the crcmod module in order to actually calculate CRC32c hashes of my data. modifiedFile.txt has already been downloaded from a Google Cloud Storage bucket onto...
[ "Here's an example md5 and crc32c for the gsutil public tarball:\n$ gsutil ls -L gs://pub/gsutil.tar.gz | grep Hash\n Hash (crc32c): vHI6Bw==\n Hash (md5): ph7W3cCoEgMQWvA45Z9y9Q==\n\nI'll copy it locally to work with:\n$ gsutil cp gs://pub/gsutil.tar.gz /tmp/\nCopying gs://pub/gsutil.tar.gz...\nDown...
[ 11, 1, 0 ]
[]
[]
[ "crc32", "gcloud_python", "google_cloud_python", "google_cloud_storage", "python" ]
stackoverflow_0037367741_crc32_gcloud_python_google_cloud_python_google_cloud_storage_python.txt
Q: How to zip 2 lists but 1 list acts as a single unit? I have a = [5,3,7] b = [9,4] I want c = [5,3,7,9,5,3,7,4] Preferably a 1 liner solution that returns the desired output. List has to be flat. I have tried the following: [i if j==0 else j for i in [7,4] for j in [5,3,7,0]] But am wondering if there is an even...
How to zip 2 lists but 1 list acts as a single unit?
I have a = [5,3,7] b = [9,4] I want c = [5,3,7,9,5,3,7,4] Preferably a 1 liner solution that returns the desired output. List has to be flat. I have tried the following: [i if j==0 else j for i in [7,4] for j in [5,3,7,0]] But am wondering if there is an even shorter/cleaner solution.
[ "I am not sure whether the following is cleaner, but here's an option:\na = [5,3,7]\nb = [9,4]\n\noutput = [x for y in b for x in [*a, y]]\nprint(output) # [5, 3, 7, 9, 5, 3, 7, 4]\n\nAt least it is better than the original code in that it allows for a to have 0 (or any value) as its element.\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074332570_python_python_3.x.txt
Q: Merging Two Dictionaries Values If They have The Same Keys I am making a list word counter and trying to merge two dictionaries that have a counter for each character, but I keep getting the wrong outputs. Here is what I attempted in an effort to figure out why. Everything seems to go well except for the last two ...
Merging Two Dictionaries Values If They have The Same Keys
I am making a list word counter and trying to merge two dictionaries that have a counter for each character, but I keep getting the wrong outputs. Here is what I attempted in an effort to figure out why. Everything seems to go well except for the last two keys in the dictionary. counts = {"a": 1, "p": 2, "l": 1, "e": 1...
[ "If we are in Python structures, actually it is a Counter that is ideal here.\nfrom collections import Counter\n\nc1 = Counter({\"a\": 1, \"p\": 2, \"l\": 1, \"e\": 1})\nc2 = Counter({\"h\": 1, \"e\": 1, \"l\": 2, \"o\": 1})\nprint(c1 + c2)\n\n", "You can use a simple for-loop:\ncounts = {\"a\": 1, \"p\": 2, \"l\...
[ 1, 1, 0 ]
[]
[]
[ "counter", "dictionary", "letter", "python" ]
stackoverflow_0074332552_counter_dictionary_letter_python.txt
Q: Find the smallest positive number not in list I have a list in python like this: myList = [1,14,2,5,3,7,8,12] How can I easily find the first unused value? (in this case '4') A: I came up with several different ways: Iterate the first number not in set I didn't want to get the shortest code (which might be the ...
Find the smallest positive number not in list
I have a list in python like this: myList = [1,14,2,5,3,7,8,12] How can I easily find the first unused value? (in this case '4')
[ "I came up with several different ways:\nIterate the first number not in set\nI didn't want to get the shortest code (which might be the set-difference trickery) but something that could have a good running time.\nThis might be one of the best proposed here, my tests show that it might be substantially faster - esp...
[ 26, 7, 6, 5, 5, 3, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0028176866_list_python.txt
Q: Dynamic label text. / Python / Kivy I do a very simple programm, is about 2 buttons , when pressed they are displaying in IDE terminal what button was pressed and how many times. Now I try to display the counting number in a label above each button, I tried a lot of things that I saw on internet but nothing with s...
Dynamic label text. / Python / Kivy
I do a very simple programm, is about 2 buttons , when pressed they are displaying in IDE terminal what button was pressed and how many times. Now I try to display the counting number in a label above each button, I tried a lot of things that I saw on internet but nothing with success and I am stuck here for a couple o...
[ "main.py\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\n\nclass ButoaneleMele(Widget):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.numaratoarebtn1 = 0\n self.numaratoarebtn2 = 0\n\n def update_numaratoarebtn1(self):\n self.numaratoarebtn1 += ...
[ 0 ]
[]
[]
[ "dynamic", "kivy", "label", "python", "string" ]
stackoverflow_0074328252_dynamic_kivy_label_python_string.txt
Q: Handling quotes and spaces in filenames I want to create a Python (3) script that passes files to a Linux shell program. Straightforward enough to do, but I'm not sure how to pass filenames that could contain single- or double-quotes and spaces to the shell. I would presumably need to delimit filenames in case the...
Handling quotes and spaces in filenames
I want to create a Python (3) script that passes files to a Linux shell program. Straightforward enough to do, but I'm not sure how to pass filenames that could contain single- or double-quotes and spaces to the shell. I would presumably need to delimit filenames in case they contain spaces. I might consider a command ...
[ "As Tim Roberts mentioned in comments, you can use subprocess module to bypass this problem. Here is a short example (assuming you have a list of filenames) for passing a list of filenames to wc -c:\nfrom subprocess import run\n\n\n# assuming you have got a list of filenames\nfilenames = ['test.py', \"Bob's special...
[ 1 ]
[]
[]
[ "delimiter", "filenames", "python", "shell" ]
stackoverflow_0074332395_delimiter_filenames_python_shell.txt
Q: How do I convert np.uint8 into a format usable by PIL.Image? I am trying to combine my computer vision code with existing code from DepthAI(this is the code that actually retrieves each frame from the camera) in order to analyze a depth map image to determine obstacles. The issue I am running into is that each fra...
How do I convert np.uint8 into a format usable by PIL.Image?
I am trying to combine my computer vision code with existing code from DepthAI(this is the code that actually retrieves each frame from the camera) in order to analyze a depth map image to determine obstacles. The issue I am running into is that each frame of video from the DepthAI code seems to be in the form of 'np.u...
[ "Specify the grayscale mode in fromarray:\nim = Image.fromarray(reshapedFrame, 'L')\n\n", "Deleting all the code in the box and replacing with pil_image = Image.fromarray(np.uint8(frame)) solved the issue. Just had to specify the kind of data that was in the array I reckon.\n" ]
[ 0, 0 ]
[]
[]
[ "luxonis", "numpy", "python", "python_imaging_library" ]
stackoverflow_0074311324_luxonis_numpy_python_python_imaging_library.txt
Q: Making a text box function for Manim, but Tex objects insert automatic line breaks I wrote the following code, which attempts to take a list of strings, and fit them inside of a bounding box of a specified width and height. It does this by inserting line breaks in appropriate places, and if the height is still exc...
Making a text box function for Manim, but Tex objects insert automatic line breaks
I wrote the following code, which attempts to take a list of strings, and fit them inside of a bounding box of a specified width and height. It does this by inserting line breaks in appropriate places, and if the height is still exceeded, then it scales the text down by half the size and then attempts to fit it again -...
[ "You could not find the piece of code responsible for these line breaks because Manim does not insert them either: when Tex or MathTex is rendered, Manim basically compiles a LaTeX document, converts it to an SVG, and imports the result.\nJust as every other LaTeX document, the one that Manim compiles also has a pa...
[ 1 ]
[]
[]
[ "manim", "python" ]
stackoverflow_0074319370_manim_python.txt
Q: Plotly scatter not drawing line of markers above certain number of data points I am using Plotly's scatter. I want to have lines surrounding the markers, like in this plot (the black contour): I want this to happen by default, so I am setting a template like in the below MWE: import plotly.express as px import pl...
Plotly scatter not drawing line of markers above certain number of data points
I am using Plotly's scatter. I want to have lines surrounding the markers, like in this plot (the black contour): I want this to happen by default, so I am setting a template like in the below MWE: import plotly.express as px import plotly.io as pio import plotly.graph_objects as go from plotly.subplots import make_su...
[ "To cope with the large amount of data, WebGL is available, so I used it to draw a scatterplot with blue markers and a line width of 1. N number is 100,000.\nUpdate:\nTo set the line width of a marker by default, create a dedicated template and set the line width as its content.\nimport plotly.graph_objects as go\n...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074320378_plotly_python.txt
Q: Retrieving RSSI values from all devices connected to network I'm building an application that lists the hostnames of devices connected to the network and their corresponding RSSI values. Is there any way I can collect this information for each network device? I was able to use the WLAN API (I'm on Windows) in Pyth...
Retrieving RSSI values from all devices connected to network
I'm building an application that lists the hostnames of devices connected to the network and their corresponding RSSI values. Is there any way I can collect this information for each network device? I was able to use the WLAN API (I'm on Windows) in Python to get the RSSI values for nearby wireless LAN networks, but I ...
[ "Here is an idea based on one approach you seem to have pursued.\nCode will collect the signal strength using one station as a monitoring station.\nTo run correctly on a Macbook you need to disconnect the interface from the network before running.\nHere is sample output (x added to obscure mac addresses):\nx4:x9:x2...
[ 0 ]
[]
[]
[ "network_programming", "python", "rssi", "scapy" ]
stackoverflow_0074308387_network_programming_python_rssi_scapy.txt
Q: Splitting a list of objects into n lists while keeping all attributes I'm trying to code a class method that takes every nth item and puts into a separate list. Then puts each of those lists into a separate object, all with the same attributes as the original object except for the lst attribute For some reason whe...
Splitting a list of objects into n lists while keeping all attributes
I'm trying to code a class method that takes every nth item and puts into a separate list. Then puts each of those lists into a separate object, all with the same attributes as the original object except for the lst attribute For some reason when I run the program it only returns the first half of the inputted list Her...
[ "I've found the solution\nIf anyone is wondering there were actually 2 variables in the object that I needed to keep track of instead of one\nthe one I tracked here only held the object, there was another with all the string identifiers of the objects that I also needed to change\n" ]
[ 1 ]
[]
[]
[ "class", "list", "object", "oop", "python" ]
stackoverflow_0074332451_class_list_object_oop_python.txt
Q: TypeError: __init__() got an unexpected keyword argument 'service' error using Python Selenium ChromeDriver with company pac file I've been struggling with this problem for sometime, but now I'm coming back around to it. I'm attempting to use selenium to scrape data from a URL behind a company proxy using a pac f...
TypeError: __init__() got an unexpected keyword argument 'service' error using Python Selenium ChromeDriver with company pac file
I've been struggling with this problem for sometime, but now I'm coming back around to it. I'm attempting to use selenium to scrape data from a URL behind a company proxy using a pac file. I'm using Chromedriver, which my browser uses the pac file in it's configuration. I've been trying to use desired_capabilities, bu...
[ "If you are still using Selenium v3.x then you shouldn't use the Service() and in that case the key executable_path is relevant. In that case the lines of code will be:\ndriver = webdriver.Chrome(executable_path='C:\\Program Files\\Chrome Driver\\chromedriver.exe')\n\n\nElse, if you are using selenium4 then you hav...
[ 6, 2 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0070534875_google_chrome_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How do I print out every other key in a dictionary? Given: d = {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5} sorted_dict = d.keys() sorted_dict = sorted(sorted_dict) for key in sorted_dict: print(key) How do I make it so that it outputs every other key. Right now it outputs: a b c d e but I want it to output: a ...
How do I print out every other key in a dictionary?
Given: d = {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5} sorted_dict = d.keys() sorted_dict = sorted(sorted_dict) for key in sorted_dict: print(key) How do I make it so that it outputs every other key. Right now it outputs: a b c d e but I want it to output: a c e
[ "Python provides \"slicing\" for very powerful and elegant solutions to problems like this. It's too big a topic to fully explain here but lot's of information all over the net on this core topic, here's a suggestion:\nhttps://www.pythontutorial.net/advanced-python/python-slicing/\nTo solve your specific problem:\n...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074332703_dictionary_python.txt
Q: KeyError: 'date' on yyyy-mm-dd df = pd.read_csv('data.csv') df.set_index('date', inplace=True) data = pd.read_csv('data.csv') x = np.array(df['subscribersGained'].dropna().values, dtype=float) y = np.array(pd.to_datetime(df['date'].dropna()).index.values, dtype=float) Error: KeyError: 'date' In the .csv file, t...
KeyError: 'date' on yyyy-mm-dd
df = pd.read_csv('data.csv') df.set_index('date', inplace=True) data = pd.read_csv('data.csv') x = np.array(df['subscribersGained'].dropna().values, dtype=float) y = np.array(pd.to_datetime(df['date'].dropna()).index.values, dtype=float) Error: KeyError: 'date' In the .csv file, the date is in the format yyyy-mm-d...
[ "By default, set_index() deletes the column that has been set as the index. Since it's been turned into the index trying to call it by name will raise the error. If you still want to use it as a data column as well you could try\ndf.set_index('date', drop=False, inplace=True)\n\nThe documentation for the function i...
[ 0 ]
[]
[]
[ "csv", "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074332743_csv_datetime_numpy_pandas_python.txt
Q: PDF is not saving in locally in flask server im running a script that converts images to a pdf file and saves the pdf locally, it works on my windows machine, but on my flask server they arent saving. here is the code from cmath import e from os import link from pickle import GET from webbrowser import get from f...
PDF is not saving in locally in flask server
im running a script that converts images to a pdf file and saves the pdf locally, it works on my windows machine, but on my flask server they arent saving. here is the code from cmath import e from os import link from pickle import GET from webbrowser import get from flask import Flask, render_template, request, json...
[ "It won't work if you just copy your script into a Flask application. Adjust your code to the circumstances and it will work.\nYou should be concerned with the line if __name__ == '__main__': . This makes no sense within your route. Read here to get more information.\nThe example below uses Flask's async extra and ...
[ 0 ]
[]
[]
[ "apache", "flask", "fpdf", "python", "ubuntu" ]
stackoverflow_0074327157_apache_flask_fpdf_python_ubuntu.txt
Q: Ubuntu 22.04 | libssl.so.1.1: cannot open shared object file: No such file or directory I've just updated to Ubuntu 22.04 LTS and my libs using OpenSSL just stopped working. Looks like Ubuntu switched to the version 3.0 of OpenSSL. For example, poetry stopped working: Traceback (most recent call last): File "/ho...
Ubuntu 22.04 | libssl.so.1.1: cannot open shared object file: No such file or directory
I've just updated to Ubuntu 22.04 LTS and my libs using OpenSSL just stopped working. Looks like Ubuntu switched to the version 3.0 of OpenSSL. For example, poetry stopped working: Traceback (most recent call last): File "/home/robz/.local/bin/poetry", line 5, in <module> from poetry.console import main File "/...
[ "This fixes it (a problem with packaging in 22.04):\nwget http://nz2.archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2.16_amd64.deb\n\nsudo dpkg -i libssl1.1_1.1.1f-1ubuntu2.16_amd64.deb\n\nPS: If the link is expired, check http://nz2.archive.ubuntu.com/ubuntu/pool/main/o/openssl/?C=M;O=D for ...
[ 102, 8, 8, 8, 8, 5, 2, 2, 0, 0 ]
[]
[]
[ "linux", "openssl", "python", "python_poetry" ]
stackoverflow_0072133316_linux_openssl_python_python_poetry.txt
Q: vscode running tasks in sequence in a virtual environment Question How do I get a vscode task's command to run in a python virtual environment/shell created by another task? Example I'm trying to run a couple of tasks in sequence using vscode. The first task will run the command pipenv shell. The second task need...
vscode running tasks in sequence in a virtual environment
Question How do I get a vscode task's command to run in a python virtual environment/shell created by another task? Example I'm trying to run a couple of tasks in sequence using vscode. The first task will run the command pipenv shell. The second task needs to be run in the virtual environment created by the first tas...
[ "The first task to do is activate the virtual environment for the correct terminal you use (Powershell, cmd, bash, ....)\nThen run the additional terminal tasks sequentially.\nI used Powershell and Python venv for virtual environment\nI used these tasks (no terminal was active) and they run in the terminal variant ...
[ 1 ]
[]
[]
[ "pipenv", "python", "visual_studio_code", "vscode_tasks" ]
stackoverflow_0073122696_pipenv_python_visual_studio_code_vscode_tasks.txt
Q: Jupyter Notebook - run cell and save as .py file I know of the %%writefile .py cell-magic command but it causes the cell to not run. What I want is for the cell to run and create the .py as well. Edit 1: I only want the original code in the cell to be saved as a .py file. I don't need the results A: I would try ...
Jupyter Notebook - run cell and save as .py file
I know of the %%writefile .py cell-magic command but it causes the cell to not run. What I want is for the cell to run and create the .py as well. Edit 1: I only want the original code in the cell to be saved as a .py file. I don't need the results
[ "I would try to:\n\nUse the %%writefile magic in the next cell, referencing the last one\n\nor\n\nUse the %save line magic instead.\n\n", "There are some ways to deal with it.\nFollow two ideas:\n\n%%writefile in the first cell followed by %run yourscript or !python 'yourscript.py'\n\nConvert your code into a str...
[ 1, 0 ]
[]
[]
[ "jupyter_notebook", "pyspark", "python" ]
stackoverflow_0063570506_jupyter_notebook_pyspark_python.txt
Q: Why is ManimCE plotting a different graph than the one provided? I'm trying to create a graph for the function (1+1/x)^x. I wrote it in python like this: def func(x): return pow(1+(1/x),x) I then plotted it like this: graph = axes.plot(lambda x: func(x), color=BLUE, stroke_width=2, x_range=[0,X_MAX]) (X_MAX ...
Why is ManimCE plotting a different graph than the one provided?
I'm trying to create a graph for the function (1+1/x)^x. I wrote it in python like this: def func(x): return pow(1+(1/x),x) I then plotted it like this: graph = axes.plot(lambda x: func(x), color=BLUE, stroke_width=2, x_range=[0,X_MAX]) (X_MAX is a variable that equals 1000) but for some reason Manim is plotting ...
[ "you need to use small values of dt.\nclass drawgraph(Scene):\n def construct(self):\n axes= Axes()\n def func(x):\n return pow(1+(1/x),x)\n graph = axes.plot(lambda x: func(x),dt = 0.001, color=BLUE, stroke_width=2, x_range=[0,5])\n self.add(axes, graph)\n\n", "It is the...
[ 0, 0 ]
[]
[]
[ "manim", "python" ]
stackoverflow_0074323678_manim_python.txt
Q: Solving simultaneous nonlinear equations with units I am basically building a general tool for solving for the operating point of a pump in a system - i.e., two equations and two unknowns - pump curve/system curve and head (H) and flowrate (Q). My posted example is not purely MWE, but is grouped in 3 sections and ...
Solving simultaneous nonlinear equations with units
I am basically building a general tool for solving for the operating point of a pump in a system - i.e., two equations and two unknowns - pump curve/system curve and head (H) and flowrate (Q). My posted example is not purely MWE, but is grouped in 3 sections and is easy to follow. First is the imports and symbols. Seco...
[ "I commented out the module Pint stuff at the very top, and the m and n defined there, and replaced it with sympy units,\nfrom sympy.physics import units as u\nfrom sympy.abc import m, n\nm = m*u.feet\nn = n*u.feet**2\n\nand now I can solve Eq() equations with units...\nclass Problem:\n name = \"system_curve\"\n...
[ 0 ]
[]
[]
[ "pint", "python", "sympy" ]
stackoverflow_0074332458_pint_python_sympy.txt
Q: How to compile multiple python files into single .exe file using pyinstaller I have created a GUI (using Tkinter) in python and this runs python files on click of a button from GUI using os.system('python_file.py'). I wanted to bundle all these python files into single .exe file using pyinstaller by keeping the Tk...
How to compile multiple python files into single .exe file using pyinstaller
I have created a GUI (using Tkinter) in python and this runs python files on click of a button from GUI using os.system('python_file.py'). I wanted to bundle all these python files into single .exe file using pyinstaller by keeping the Tkinter file as main. I created the .exe file by doing the following in command line...
[ "Suppose you have two files: \"my_main.py\" and \"my_functions.py\". Assume that \"my_main.py\" imports methods from \"my_functions.py\"\nExecute the following command:\n\npyinstaller --onefile my_main.py my_functions.py\n\nResulting single executable file \"my_main.exe\" will be created under \"dist\" folder of p...
[ 5, 0, 0, 0 ]
[]
[]
[ "pyinstaller", "python", "python_2.7", "tkinter" ]
stackoverflow_0045183137_pyinstaller_python_python_2.7_tkinter.txt
Q: Automatically Concatenating Tables from Multiple Pages - Python I am making a program that is trying to look at small companies and gather data on insider buying. The script below is able to gather data from every company in the larger table('http://openinsider.com/latest-penny-stock-buys') and fetch a table showi...
Automatically Concatenating Tables from Multiple Pages - Python
I am making a program that is trying to look at small companies and gather data on insider buying. The script below is able to gather data from every company in the larger table('http://openinsider.com/latest-penny-stock-buys') and fetch a table showing the data I want from each company. It currently can print out each...
[ "I actually fooled around a bit and figured it out!\nBasically just make a list, add each dfn every time the loop is done, and then you can apparently just concat the list:\nList = []\nurl = 'http://openinsider.com/'\nfor entry in name:\n table2 = pd.read_html(url+entry)\n dfn=table2[11]\n List.append(dfn)\npd.c...
[ 1 ]
[]
[]
[ "automation", "database", "pandas", "python", "web_scraping" ]
stackoverflow_0074332621_automation_database_pandas_python_web_scraping.txt
Q: Python random color nested for loop For this python code I'm making squares that are being drawn in random locations on the screen, I need each square to be a random color too. Everything is working except the random color. The turtle is the only thing that changes colors. I'm not sure where to the color codes, ei...
Python random color nested for loop
For this python code I'm making squares that are being drawn in random locations on the screen, I need each square to be a random color too. Everything is working except the random color. The turtle is the only thing that changes colors. I'm not sure where to the color codes, either outside or in the nested for loop. i...
[ "The squares are not colored as expected since you're not using the begin_fill and end_fill properly.\nIn the following block of your code, you call begin_fill/end_fill every time you draw a line, that's why it's not working.\nfor j in range(4):\n bob.begin_fill()\n bob.forward(box_size)\n bob.left(90)\n ...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074332681_python_python_3.x_python_turtle_turtle_graphics.txt
Q: Is there another any alternative to torch.Generator() to support MPS device type? (M1 Mac, PyTorch) I am running python code for implementing stable diffusion on my m1 mac and getting this error in my text2img function. I understand that Pytorch has recently started supporting m1 GPU. I am getting this error (Runt...
Is there another any alternative to torch.Generator() to support MPS device type? (M1 Mac, PyTorch)
I am running python code for implementing stable diffusion on my m1 mac and getting this error in my text2img function. I understand that Pytorch has recently started supporting m1 GPU. I am getting this error (RuntimeError: Device type MPS is not supported for torch.Generator() api.) I put the code below and highlight...
[ "Since you only need a random number, just generate it in the CPU instead:\ngenerator = torch.Generator().manual_seed(int(seed))\n\n" ]
[ 0 ]
[ "I also find this problem. if I use torch.has_mps.manual_seed(SEED), it shows AttributeError: 'bool' object has no attribute 'manual_seed'\n" ]
[ -1 ]
[ "apple_m1", "python", "pytorch" ]
stackoverflow_0073897738_apple_m1_python_pytorch.txt
Q: Issues with pandas and writing to csv file I am having an issue with pandas and writing to CSV file. When I run the python scripts I either run out of memory or my computer starts running slow after script is done running. Is there any way to chunk up the data in pieces and write the chunks to CSV? I am bit new to...
Issues with pandas and writing to csv file
I am having an issue with pandas and writing to CSV file. When I run the python scripts I either run out of memory or my computer starts running slow after script is done running. Is there any way to chunk up the data in pieces and write the chunks to CSV? I am bit new to programing in Python. import itertools, hashlib...
[ "Since you are only using the dataframe to write to a file, skip it completely. You build the full data set into memory in a python list and then again in the dataframe, needlessly eating RAM. The csv module in the standard lib lets you write line by line.\nimport itertools, hashlib, time, csv\nchars = ['0','1','2'...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074332799_csv_pandas_python.txt
Q: How can I extract a specific item attribute from an ebay listing using BeautifulSoup? def get_data(url): r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') return soup current_data = get_data(link) x = current_data.find_all(text="Style Code:") I'm trying to get the style code of a shoe off e...
How can I extract a specific item attribute from an ebay listing using BeautifulSoup?
def get_data(url): r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') return soup current_data = get_data(link) x = current_data.find_all(text="Style Code:") I'm trying to get the style code of a shoe off ebay but the problem is that it doesn't have a specific class or any kind of unique identifi...
[ "soup.select_one('span.ux-textspans:-soup-contains(\"Style Code:\")').find_next('span').get_text(strip=True)\n\n", "Try this,\nspans = soup.find_all('span', attrs={'class':'ux-textspans'})\nstyle_code = None\nfor idx, span in enumerate(spans):\n if span.text == 'Style Code:':\n style_code = spans[idx+1]...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0074332215_beautifulsoup_html_python.txt
Q: for loop over pandas dataframes to take subsets I would like use a for loop over a list of pandas dataframes, to make similar changes to each one. But the changes don't seem to take effect globally. For a simpler example that works as expected (but with python lists instead of dataframes): the following works as...
for loop over pandas dataframes to take subsets
I would like use a for loop over a list of pandas dataframes, to make similar changes to each one. But the changes don't seem to take effect globally. For a simpler example that works as expected (but with python lists instead of dataframes): the following works as I would expect it to: Example 1: u=[68, 82, 75] v=[9...
[ "The thing is that the list does not contain the original references to DataFrame objects but their copies. \nThis can be fixed through initially creating DataFrame objects straight as the list values.\nimport pandas as pd\n\ndata_current = [['tom', 72], ['nick', 77], ['julie', 68]]\ndata_desired = [['mary', 65], [...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074332790_pandas_python.txt
Q: (PYTHON, PILLOW) How to make RGBA image conversion to RGB faster? I'm making fade effect by merging .png image with .jpg, but the conversion process takes too long. Is there a way how I could speed up this process? for f in range(101): print(str((200 + f) /3) + "%") if f == 0: im_rgba = img1.copy()...
(PYTHON, PILLOW) How to make RGBA image conversion to RGB faster?
I'm making fade effect by merging .png image with .jpg, but the conversion process takes too long. Is there a way how I could speed up this process? for f in range(101): print(str((200 + f) /3) + "%") if f == 0: im_rgba = img1.copy() im_rgba.putalpha(255) im_rgba = im_rgba.convert('RGB')...
[ "I'm guessing that 99% of your time is spent reading and writing images. The only way to be sure is to benchmark it, but that's my guess. That means almost everything else you manage to improve will be negligible.\nOne thing you could do is eliminate the save of mask_im. I don't know why you'd need it, and every...
[ 0 ]
[]
[]
[ "python", "python_imaging_library", "rgb", "rgba" ]
stackoverflow_0074322528_python_python_imaging_library_rgb_rgba.txt
Q: Start python scripts from a python script Im running a linux server that runs 4 python scripts on startup, but sometimes some of them crash and I need to restart it manually, so I thought about running a new script that checks if one of them stopped through ps -fA and restart. Here is the code: # Search output gen...
Start python scripts from a python script
Im running a linux server that runs 4 python scripts on startup, but sometimes some of them crash and I need to restart it manually, so I thought about running a new script that checks if one of them stopped through ps -fA and restart. Here is the code: # Search output generaldata = "site_general_data" amsniffer = "sit...
[ "As proposed by @Jeppe in the comments appending & was enough to solve my problem, the script now runs with no interruption, restarting any crashed applications.\n" ]
[ 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0074328366_linux_python.txt
Q: Does the copy dataframe equate with source dataframe? create a dataframe duplicate the dataframe modify the element of source dataframe modify the element of copy dataframe check the two dataframes and their id address The two dataframes have their idependen address, why they were changed at the same time? import...
Does the copy dataframe equate with source dataframe?
create a dataframe duplicate the dataframe modify the element of source dataframe modify the element of copy dataframe check the two dataframes and their id address The two dataframes have their idependen address, why they were changed at the same time? import pandas as pd gl_stock_001 = pd.DataFrame({'prc': [3], ...
[ "This is a common problem with pandas - sometimes it copies data, sometimes it doesn't, and when things copy can change with new releases. The documentation isn't particularly good explaining when this happens and when it doesn't. pandas wraps numpy and consider the case where you have an existing numpy array and a...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074333019_pandas_python.txt
Q: Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv I have an Ubuntu 14.04 system, on which I want to install OpenCV and use it with Python 2.x. I installed OpenCV using the instructions here: https://help.ubuntu.com/community/OpenCV The install seemed to run properly, no errors, th...
Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv
I have an Ubuntu 14.04 system, on which I want to install OpenCV and use it with Python 2.x. I installed OpenCV using the instructions here: https://help.ubuntu.com/community/OpenCV The install seemed to run properly, no errors, the script ended with output OpenCV 2.4.9 ready to be used When I try to run the sample P...
[ "I think you don't have the python-opencv package.\nI had the exact same problem and \nsudo apt-get install python-opencv\n\nsolved the issue for me.\nyou can install opencv from the following link \nhttps://www.learnopencv.com/install-opencv3-on-ubuntu/\nIt works for me . \napt-get install doesnt contain many pack...
[ 110, 30, 17, 11, 11, 8, 5, 4, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "importerror", "opencv", "python", "ubuntu" ]
stackoverflow_0025215102_importerror_opencv_python_ubuntu.txt
Q: Split string by whitespaces, except for when whitespace is inside apostrophes input: "A B C ' '" desired output: ['A', 'B', 'C', " "] I've tried a few solutions using the re package, but I m not very good with regex A: This solves the problem based your example. I have expanded the test string to show more than ...
Split string by whitespaces, except for when whitespace is inside apostrophes
input: "A B C ' '" desired output: ['A', 'B', 'C', " "] I've tried a few solutions using the re package, but I m not very good with regex
[ "This solves the problem based your example.\nI have expanded the test string to show more than one whitespace inside of apostrophes.\nimport re\ntest_string = \"A B C ' ' D E F ' '\"\n\npattern = re.compile(r\"([A-Z]\\s)|('\\s')\")\nmatches = pattern.findall(test_string)\n\nresult = [m[0].strip() if m[0] else ' ' ...
[ 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0074332641_python_split_string.txt
Q: How to convert json from url into pandas dataframe? with this code: import pandas as pd import requests import json url = 'https://www.loves.com/api/sitecore/StoreSearch/SearchStores' #get the data from url response = requests.get(url).json() df = pd.read_json(url) df1 = pd.json_normalize(response) both DFs r...
How to convert json from url into pandas dataframe?
with this code: import pandas as pd import requests import json url = 'https://www.loves.com/api/sitecore/StoreSearch/SearchStores' #get the data from url response = requests.get(url).json() df = pd.read_json(url) df1 = pd.json_normalize(response) both DFs return this: This is what the response looks like How to...
[ "Try it like this\nimport pandas as pd\nimport requests\nimport json\n\nurl = 'https://www.loves.com/api/sitecore/StoreSearch/SearchStores'\n\n#get the data from url\nresponse = requests.get(url).json()\n\ndf1 = pd.json_normalize(response, record_path=['Points'])\n\n", "I found the answer, this made the trick\ndf...
[ 3, 3 ]
[]
[]
[ "json", "pandas", "python", "python_requests", "url" ]
stackoverflow_0074332985_json_pandas_python_python_requests_url.txt
Q: What is the most efficient way to run a cosine similarity test comparing all rows to all rows of two sparse pandas dataframes? I'm working to speed up this chunk of code. It's currently taking multiple days to complete two compare two dataframes [192184 rows x 256 columns] by [7739 rows x 256 columns]. This is a r...
What is the most efficient way to run a cosine similarity test comparing all rows to all rows of two sparse pandas dataframes?
I'm working to speed up this chunk of code. It's currently taking multiple days to complete two compare two dataframes [192184 rows x 256 columns] by [7739 rows x 256 columns]. This is a relatively small use-case and its way too slow already. I'd like to compare all rows of dataframe 1 to all rows of dataframe 2. This...
[ "Let's start to see how we could have accelerated the same code. Just as an exercise about how to avoid some for loops.\nTho, spoiler alert, we won't use that algorithm at the end anyway, so it is just an exercise.\nVectorization of your code\nWhat you are doing here is calling spatial.distance.cosine for every com...
[ 1 ]
[]
[]
[ "cosine_similarity", "numpy", "pandas", "python", "scipy" ]
stackoverflow_0074332802_cosine_similarity_numpy_pandas_python_scipy.txt
Q: Python Dictionary Throwing KeyError for adding list of tuples Here is original text file: s1 10 s2 s2 12 s3 s3 25 s1 s1 14 s3 I am making a dictionary of first value in each line as a key, the output should be: {'s1': [('s2', 's10'), ('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]} When i run my code I ...
Python Dictionary Throwing KeyError for adding list of tuples
Here is original text file: s1 10 s2 s2 12 s3 s3 25 s1 s1 14 s3 I am making a dictionary of first value in each line as a key, the output should be: {'s1': [('s2', 's10'), ('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]} When i run my code I get a key error: def graph_dict(filename): dictx = {} with ...
[ "Aside of using defaultdict, you can try to catch that exception (known as It’s Easier To Ask Forgiveness Than To Get Permission):\ndef graph_dict(filename):\n dictx = {}\n with open(filename) as x:\n for i in x:\n c, c1, c2 = i.split()\n try:\n dict...
[ 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074333109_dictionary_python.txt
Q: is it possible to extract the exact upload time of a youtube video using python? I managed to obtain titles and upload dates of all videos of any given youtube channel using either the scrapetube module or simply urllib (request) and re. E.g., to obtain the date, I would first get the ids of all videos of a YT cha...
is it possible to extract the exact upload time of a youtube video using python?
I managed to obtain titles and upload dates of all videos of any given youtube channel using either the scrapetube module or simply urllib (request) and re. E.g., to obtain the date, I would first get the ids of all videos of a YT channel: videos = scrapetube.get_channel( channel_url = "https://www.youtube.com/user...
[ "You are looking for YouTube Data API v3 Videos: list#status.publishAt.\nThe following Python script shows how to use the YouTube Data API v3 to get the publishAt field of snippet for a given video.\nimport googleapiclient.discovery\n\nyoutube = googleapiclient.discovery.build(\n \"youtube\", \"v3\", developerKe...
[ 2 ]
[]
[]
[ "python", "youtube" ]
stackoverflow_0074331545_python_youtube.txt
Q: [cv2.filter2D() on Python]: why does it return these specific values? The following Python script computes the 2D convolution of the blue color channel of a .jpg image: It reads a 6x6 BGR image: It extracts the channel 0. In cv2 this corresponds to color channel blue. I print the values of the channel Input data...
[cv2.filter2D() on Python]: why does it return these specific values?
The following Python script computes the 2D convolution of the blue color channel of a .jpg image: It reads a 6x6 BGR image: It extracts the channel 0. In cv2 this corresponds to color channel blue. I print the values of the channel Input data type is uint8. Therefore, we making cv2.filter2D() and setting ddepth=-1, ...
[ "Your calculation is not wrong, but you have actually written convolution for value at [2,2], which match with your result 425.\nTo calculate value e.g. [1,1] you need values outside of the image, you have to handle surrounding edges. And by default in function filter2D they are handled as reflect 101 , in wiki its...
[ 2 ]
[]
[]
[ "convolution", "image_processing", "opencv", "python" ]
stackoverflow_0074332472_convolution_image_processing_opencv_python.txt
Q: Pandas .loc[] returning another data frame How do I get the actual string variable instead another for text processing? df.columns df.head(3) Returns Index(['text', 'is_spam'], dtype='object') 779 Subject re a note being sent out under john s... False 1552 Subject hi mind opt in referencement from h......
Pandas .loc[] returning another data frame
How do I get the actual string variable instead another for text processing? df.columns df.head(3) Returns Index(['text', 'is_spam'], dtype='object') 779 Subject re a note being sent out under john s... False 1552 Subject hi mind opt in referencement from h... True 2341 Subject ilug do not drop your lif...
[ " string = df.loc[i, 'text']\n\nUse code above instead of yours\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074333218_dataframe_pandas_python.txt
Q: ElementTree - findall to recursively select all child elements Python code: import xml.etree.ElementTree as ET root = ET.parse("h.xml") print root.findall('saybye') h.xml code: <hello> <saybye> <saybye> </saybye> </saybye> <saybye> </saybye> </hello> Code outputs, [<Element 'saybye' at 0x7fdbcbbec6...
ElementTree - findall to recursively select all child elements
Python code: import xml.etree.ElementTree as ET root = ET.parse("h.xml") print root.findall('saybye') h.xml code: <hello> <saybye> <saybye> </saybye> </saybye> <saybye> </saybye> </hello> Code outputs, [<Element 'saybye' at 0x7fdbcbbec690>, <Element 'saybye' at 0x7fdbcbbec790>] saybye which is a child ...
[ "From version 2.7 on, you can use xml.etree.ElementTree.Element.iter:\nimport xml.etree.ElementTree as ET\nroot = ET.parse(\"h.xml\")\nprint root.iter('saybye')\n\nSee 19.7. xml.etree.ElementTree β€” The ElementTree XML API\n", "If you aren't afraid of a little XPath, you can use the // syntax that means find any d...
[ 15, 13, 7, 0, 0 ]
[]
[]
[ "python", "python_2.7", "recursion", "xml" ]
stackoverflow_0030097949_python_python_2.7_recursion_xml.txt
Q: Binary search tree lazy deletion Python I've created a binary search tree class and I'm trying to get a grasp on how "lazy deletion" works. I've set a flag in order to show if a node has been removed. When I search for a value that I want to remove, self.removed would be marked as True. However, when I use the fin...
Binary search tree lazy deletion Python
I've created a binary search tree class and I'm trying to get a grasp on how "lazy deletion" works. I've set a flag in order to show if a node has been removed. When I search for a value that I want to remove, self.removed would be marked as True. However, when I use the findValue method, it still says that the removed...
[ "You should also modify the search method, otherwise there is no way to utilize the removed flag.\n def findValue(self, value):\n \"\"\"return true if there is a node containing value, false otherwise\"\"\"\n ptr = self.root\n\n while ptr is not None:\n if ptr.value == value and n...
[ 1 ]
[]
[]
[ "algorithm", "binary_search_tree", "data_structures", "python", "python_3.x" ]
stackoverflow_0074333205_algorithm_binary_search_tree_data_structures_python_python_3.x.txt
Q: scrape Shopee API v4 I have a final project where the data I want to retrieve is through scraping data on shopee, but I have a problem when I scrape shopee on a hidden API, when I try it on the Insomnia script the script runs, but when I try it on local or google colab script this is an error. How can I fix this? ...
scrape Shopee API v4
I have a final project where the data I want to retrieve is through scraping data on shopee, but I have a problem when I scrape shopee on a hidden API, when I try it on the Insomnia script the script runs, but when I try it on local or google colab script this is an error. How can I fix this? import requests im...
[ "You can add a requests header, like this headers key af-ac-enc-dat value null, this works for me.\n var request = WebRequest.Create(apiURL);\n request.Headers[\"x-api-source\"] = \"pc\";\n request.Headers[\"af-ac-enc-dat\"] = \"null\";\n var response = re...
[ 2 ]
[]
[]
[ "javascript", "python", "python_requests", "shopee", "web_deployment" ]
stackoverflow_0073424180_javascript_python_python_requests_shopee_web_deployment.txt
Q: Avoid pandas.to_sql writes into table with double quotes (PostgreSQL database) I am trying to export my dataframe to sql database (Postgres). I created the table as following: CREATE TABLE dataops.OUTPUT ( ID_TAIL CHAR(30) NOT NULL, ID_MODEL CHAR(30) NOT NULL, ID_FIN CHAR(30) NOT NULL, ID_GROUP_FIN...
Avoid pandas.to_sql writes into table with double quotes (PostgreSQL database)
I am trying to export my dataframe to sql database (Postgres). I created the table as following: CREATE TABLE dataops.OUTPUT ( ID_TAIL CHAR(30) NOT NULL, ID_MODEL CHAR(30) NOT NULL, ID_FIN CHAR(30) NOT NULL, ID_GROUP_FIN CHAR(30) NOT NULL, ID_COMPONENT CHAR(30) NOT NULL, DT_OPERATION TIMESTAMP N...
[ "Short version Pandas is double quoting identifiers which is fairly standard. When that happens with upper case identifier you have to double quote from then on when using it. Using it unquoted will fold the name to lower case and you won't find the table. For more information on this, see Identifier Syntax. You ha...
[ 0, 0, 0, 0 ]
[ "I didn't found a \"good\" solution, so what I did was to create my own function to insert the values:\nimport sqlalchemy\nimport pandas as pd\n\nconn = sqlalchemy.create_engine(\"postgres://root:1234@localhost:5432/postgres\")\ndata = [['ID_1', 'A4_DOOUE_ADM001', '1201MJ52', 'PATH_1', 'LATCHED1AFT',\n ...
[ -1, -1 ]
[ "pandas", "postgresql", "python" ]
stackoverflow_0064808427_pandas_postgresql_python.txt
Q: Producing key:value pairs from existing pairs in nested dictionary I have a rather algorithmic question. I’m using Python so that would be a bonus but in essence it’s about how to approach a problem. I have a nested dictionary where for each customer, there are their relations with another customers. Basically if ...
Producing key:value pairs from existing pairs in nested dictionary
I have a rather algorithmic question. I’m using Python so that would be a bonus but in essence it’s about how to approach a problem. I have a nested dictionary where for each customer, there are their relations with another customers. Basically if they enjoy same things, they are more compatible. The way this is calcul...
[ "As a simple solution, you can just iterate over all values in the dictionary, and for each customer-customer pair (i, j), you also set the value for (j, i).\nfrom collections import defaultdict\ncust = {\n 1: {\n 2: 1,\n 3: 0\n },\n 2: {\n 3: 1\n }\n}\nnew_cust = defaultdict(dict)\...
[ 1 ]
[]
[]
[ "algorithm", "dictionary", "key_value_coding", "python" ]
stackoverflow_0074333247_algorithm_dictionary_key_value_coding_python.txt
Q: Python OOP name error: "lib_list" not defined despite being there im trying to initialize a list object with various items found in a text file. However, whenever I call the argument, it says name "lib_list" is not defined, even though it is. I also tried calling catalog without the argument, but then it says a po...
Python OOP name error: "lib_list" not defined despite being there
im trying to initialize a list object with various items found in a text file. However, whenever I call the argument, it says name "lib_list" is not defined, even though it is. I also tried calling catalog without the argument, but then it says a positional argument, "lib_list", required. I'm just not sure what to do a...
[ "You are trying to send lib_list in the class Catalog. The problem here is, in your main() function you have nowhere defined lib_list and lib_list is a parameter name for the Catalog __init__() it is not a pre-defined variable. To fix this error:\n# Change line 82:\nLibCat = Catalog(listings) # Assuming listings is...
[ 0 ]
[]
[]
[ "object", "oop", "python" ]
stackoverflow_0074333287_object_oop_python.txt
Q: How to make a python script to run other files in separate terminals? I made some scraping files and to run them at the same time I usually open multiple terminals in VS code and write " python filename.py " for each file, there's any method to automate this process to call each file and run it? A: Simplest solu...
How to make a python script to run other files in separate terminals?
I made some scraping files and to run them at the same time I usually open multiple terminals in VS code and write " python filename.py " for each file, there's any method to automate this process to call each file and run it?
[ "Simplest solution would be to run python script1.py & python script2.py & python script3.py &\n", "I think the terms \"Automation\" and \"each time I call it and run it\" you have used to ask for running it automatically within the program or by a python script.\nFor that you just simply use one module \"OS MOD...
[ 1, 1 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0074323319_automation_python.txt
Q: Best practice for python module with thousands of classes in one file I have a generated python module file with thousands of data classes, size 6MB. These classes are generated from database structure, so I can not reduce them or not provide them with my module. This module cause two main problem: Very slow impo...
Best practice for python module with thousands of classes in one file
I have a generated python module file with thousands of data classes, size 6MB. These classes are generated from database structure, so I can not reduce them or not provide them with my module. This module cause two main problem: Very slow importing Damage performance of IDE the number of classes I currently used in ...
[ "You can have the classes available in one module without having to import them all into another module where you intend to use them.\nSay \"6megModule.py\" contains classes class1..class9999\nfrom 6megModule import class1, class2, class3\n\nIf you can give more details about how you have designed your classes othe...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074333266_python.txt
Q: Speeding up to writing to CSV file t0 = time.time() chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] numbers_list = list(range(0,25)) header = ['A', 'B', 'C'] t0 = time.time() with open('test.csv', 'w', newline='') as f: writer = csv.writer(f) writer = csv.writer(f) for combina...
Speeding up to writing to CSV file
t0 = time.time() chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] numbers_list = list(range(0,25)) header = ['A', 'B', 'C'] t0 = time.time() with open('test.csv', 'w', newline='') as f: writer = csv.writer(f) writer = csv.writer(f) for combination in itertools.combinations_with_repl...
[ "import itertools, hashlib, pandas as pd,time, csv\nchars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']\nnumbers_list = list(range(0,25))\nrows = []\nfor combination in itertools.combinations_with_replacement(chars, 10):\n for A in numbers_list:\n pure = str(A) + ':' + str(co...
[ 0 ]
[]
[]
[ "csv", "python", "python_3.x" ]
stackoverflow_0074333231_csv_python_python_3.x.txt
Q: max magnitude: finding max magnitude among integers import math def max_magnitude(val1, val2, val3): if abs(val1) > abs(val2) and abs(val3): return(val1) elif abs(val2) > abs(val3) and abs(val1): return(val2) elif abs(val3) > abs(val2) and abs(val1): return(val3) def ma...
max magnitude: finding max magnitude among integers
import math def max_magnitude(val1, val2, val3): if abs(val1) > abs(val2) and abs(val3): return(val1) elif abs(val2) > abs(val3) and abs(val1): return(val2) elif abs(val3) > abs(val2) and abs(val1): return(val3) def main(): val1 = int(input()) val2 = int(input()) ...
[ "Firstly, you have written a lot of unnecessary code. Let's simplify that by using map().\ndef max_magnitude(val1, val2, val3):\n return max([val1,val2,val3],key=abs) # Return the max value of abs\n\nmax() basically returns the maximum value present in an iterable. The key arg of max() helps us pass abs as an ar...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074333271_python.txt
Q: StreamLit App demanding each feature from classifier I am deploying my machine learning model on a web app using the Streamlit API. I am giving 6 features to the app from my dataset, but my dataset has around 66 features after one hot encoding. So i make an app front end which is fine but when ever i press predict...
StreamLit App demanding each feature from classifier
I am deploying my machine learning model on a web app using the Streamlit API. I am giving 6 features to the app from my dataset, but my dataset has around 66 features after one hot encoding. So i make an app front end which is fine but when ever i press predict button after entering values of my 6 features it says "X ...
[ "There's potentially two ways to solve your problem based on the information you've provided:\n\nIt seems like you used some sort of preprocessors/transformers during feature preprocessing that turned the 6 features into 66 features which was then passed into your model. If that is the case, you can create a Pipeli...
[ 0 ]
[]
[]
[ "machine_learning", "python", "streamlit", "web_applications" ]
stackoverflow_0074323638_machine_learning_python_streamlit_web_applications.txt
Q: How to test multiple variables for equality against a single value? I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say: x = 0 y = 1 z = 3 mylist = [] if x or y or z == 0: ...
How to test multiple variables for equality against a single value?
I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say: x = 0 y = 1 z = 3 mylist = [] if x or y or z == 0: mylist.append("c") if x or y or z == 1: mylist.append("d") if x or ...
[ "You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:\nif x == 1 or y == 1 or z == 1:\n\nx and y are otherwise evaluated on their own (False if 0, True otherwise).\nYou can shorten t...
[ 1084, 116, 76, 53, 34, 33, 31, 30, 30, 30, 26, 26, 13, 10, 9, 9, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 0, 0, 0, 0 ]
[ "#selection\n: a=np.array([0,1,3]) \n\n#options\n: np.diag(['c','d','e','f']) \narray([['c', '', '', ''],\n ['', 'd', '', ''],\n ['', '', 'e', ''],\n ['',...
[ -1 ]
[ "boolean_logic", "comparison", "if_statement", "match", "python" ]
stackoverflow_0015112125_boolean_logic_comparison_if_statement_match_python.txt
Q: How do I filter out elements in a column of a data frame based upon if it is in a list? I'm trying to filter out bogus locations from a column in a data frame. The column is filled with locations taken from tweets. Some of the locations aren't real. I am trying to separate them from the valid locations. Below is t...
How do I filter out elements in a column of a data frame based upon if it is in a list?
I'm trying to filter out bogus locations from a column in a data frame. The column is filled with locations taken from tweets. Some of the locations aren't real. I am trying to separate them from the valid locations. Below is the code I have. However, the output is not producing the right thing, it instead will only re...
[ "If your goal is to find and list country names, both valid and not, you may filter the initial results DataFrame:\n# make list from unique values of Source Location that match values from country_names\nvalid_names = list(results[results['Source Location']\n .isin(country_names)]['Source ...
[ 0 ]
[]
[]
[ "filter", "list", "pandas", "python" ]
stackoverflow_0074332946_filter_list_pandas_python.txt
Q: How to pull out specific elements in a json file and store them in another dictionary? How to properly Iterate through dictionary/json file? I have a Json file that I am trying to pull out certain values and not touch some of the others. The only way I can seem to pull out values is by appending them to a list, wh...
How to pull out specific elements in a json file and store them in another dictionary? How to properly Iterate through dictionary/json file?
I have a Json file that I am trying to pull out certain values and not touch some of the others. The only way I can seem to pull out values is by appending them to a list, which I can only access one key at a time. Theres a whole bunch of nested dictionaries and within each dictionary I need to pull out 3 key/value pa...
[ "output_dict = {}\nfor _dict in original_dict:\n output_dict[_dict[\"d\"]] = [_dict[\"a\"], _dict[\"b\"]]\n\n{400: [100, 200], 401: [101, 201], 402: [102, 202]}\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "json", "loops", "object", "python" ]
stackoverflow_0074333362_dictionary_json_loops_object_python.txt
Q: how to generate multiple lines of a random list of numbers? Noob python learner here.. maybe just ambitious but full immersion is my way to die. But I've asked google my question 15 different ways and not finding the answer. I've started out trying to create a pseudolist of lottery numbers. My wife's 42nd birthday...
how to generate multiple lines of a random list of numbers?
Noob python learner here.. maybe just ambitious but full immersion is my way to die. But I've asked google my question 15 different ways and not finding the answer. I've started out trying to create a pseudolist of lottery numbers. My wife's 42nd birthday is coming up and she wants to play the Powerball and/or Mega Mil...
[]
[]
[ "How are are you running this code?\nWhat are you running it on?\nThe code as listed should produce different results each run!\nYou don't have to use random.seed as some have suggested, in fact doing so can make the sequence of random numbers generated repeat on each run - which is what you don't want.\nIf you are...
[ -1 ]
[ "python", "random", "random_seed" ]
stackoverflow_0074333342_python_random_random_seed.txt
Q: is there function to print all the roads inside the tree ][1][2]suppose we have the tree shown in the photo.. I didn't find function that can tell all the roads inside the tree .. I just want function or algorithms that can print all the roads I am trying hard to find a function that can print all the roads inside...
is there function to print all the roads inside the tree
][1][2]suppose we have the tree shown in the photo.. I didn't find function that can tell all the roads inside the tree .. I just want function or algorithms that can print all the roads I am trying hard to find a function that can print all the roads inside the tree: for the case here , the result should be like this ...
[ "One might use depth-first-search to solve this, where roads are edges. Adapted from Wikipedia's DFS pseudo-code, where v is the vertex labelled 1, (the root.)\nprocedure DFS(G, v, S) is\n label v as discovered\n S.push(v)\n leaf := true\n for all directed edges from v to w that are in G.adjacentEdges(v...
[ 0 ]
[]
[]
[ "algorithm", "artificial_intelligence", "python" ]
stackoverflow_0074329666_algorithm_artificial_intelligence_python.txt
Q: I can't count days between two dates I'm trying to count days between two dates but I can't figure out how to do it. This is the code I am using: from datetime import datetime from datetime import date hoy = date(datetime.today().strftime("%Y,%m,%e")) #current time otra_fecha = date(2022, 11, 5) delta = hoy - otr...
I can't count days between two dates
I'm trying to count days between two dates but I can't figure out how to do it. This is the code I am using: from datetime import datetime from datetime import date hoy = date(datetime.today().strftime("%Y,%m,%e")) #current time otra_fecha = date(2022, 11, 5) delta = hoy - otra_fecha print(delta.days) This is the err...
[ "You're getting the TypeError since datetime.today().strftime(\"%Y,%m,%e\") returns a str and datetime.date() takes int as arguments.\n\nYou can use date.today() to get the current local date.\n\nhoy = date.today()\n\n\nYou can also use the date() method to extract the date from datetime object.\n\nhoy = datetime.t...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074333237_python.txt
Q: Use a function in mydict [variable]. KeyError: Until now I used a dictionary and a variable in the following way and it worked correctly: if mydict[variable] == value: Now I would like to replace the variable with the return of a function. I tried to write like this if mydict[myfunction] == value but I get an ...
Use a function in mydict [variable]. KeyError:
Until now I used a dictionary and a variable in the following way and it worked correctly: if mydict[variable] == value: Now I would like to replace the variable with the return of a function. I tried to write like this if mydict[myfunction] == value but I get an error: KeyError: <function myfunction at 0x7f6b65a0f7...
[ "You need to invoke the function (ie. make it run).\nYou do this by putting () after the function name.. myFunction()\nif mydict[myfunction()] == value\n\nWhat you had done is pass a reference to the function and tried to use that as a key in your dictionary rather than passing the result returned by your function ...
[ 0 ]
[]
[]
[ "function", "python", "python_3.x" ]
stackoverflow_0074333391_function_python_python_3.x.txt
Q: Python: Modify a list from user-defined function Python Crash Course (1st edition), by Eric MATTHES Exercice 8-10 Great Magicians "8-9. Magicians: Make a list of magician’s names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list. 8-10. Great Magicians: Start w...
Python: Modify a list from user-defined function
Python Crash Course (1st edition), by Eric MATTHES Exercice 8-10 Great Magicians "8-9. Magicians: Make a list of magician’s names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list. 8-10. Great Magicians: Start with a copy of your program from Exercise 8-9. Write a ...
[ "When you have\nfor x in whocares:\n x = x + \", the Great\"\n\nThis gives the name x to the result of your addition, which is lost at each iteration of the loop!\nThis gives a somewhat dated, but great overview of what is happening\nhttps://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#python-has...
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074333264_list_python_python_3.x.txt
Q: Why do I have this result: SyntaxError: positional argument follows keyword argument sub4 = sub4.melt(id_vars = 'Sort_order','year' ,var_name= 'sex' ,value_name= "International_migrant_stock_at_mid-year") I try to melt the dataframe to separate sex and migrant...
Why do I have this result: SyntaxError: positional argument follows keyword argument
sub4 = sub4.melt(id_vars = 'Sort_order','year' ,var_name= 'sex' ,value_name= "International_migrant_stock_at_mid-year") I try to melt the dataframe to separate sex and migrant stock. I think my codes look fine but it just keeps giving me the syntax error. Does any...
[ "need [ ] for id_vars\nsub4 = sub4.melt(\n id_vars=['Sort_order', 'year'], \n var_name='sex',\n value_name=\"International_migrant_stock_at_mid-year\"\n)\n\n" ]
[ 0 ]
[]
[]
[ "data_cleaning", "melt", "pandas", "python" ]
stackoverflow_0074333480_data_cleaning_melt_pandas_python.txt
Q: Searching CSV file and return rows as JSON I'm learning Python. I have a CSV file with these rows. I am trying to search and return rows that have year_ceremony matched with the year parameter the function accepts. year_film,year_ceremony,ceremony,category,name,film,winner 1927,1928,1,ACTOR,Richard Barthelmess,The...
Searching CSV file and return rows as JSON
I'm learning Python. I have a CSV file with these rows. I am trying to search and return rows that have year_ceremony matched with the year parameter the function accepts. year_film,year_ceremony,ceremony,category,name,film,winner 1927,1928,1,ACTOR,Richard Barthelmess,The Noose,False 1927,1928,1,ACTOR,Emil Jannings,The...
[ "Can't edit my previous reply !!\nTo convert the dict to json use\njson.dumps(s)\n\n", "You can use DictReader from csv module for reading. It maps each row to a dict. And use json.dumps for converting the result(which is a list of dictionaries) to JSON format string:\nimport csv\nimport json\n\ndef get_academy_a...
[ 0, 0 ]
[]
[]
[ "csv", "json", "python" ]
stackoverflow_0074333469_csv_json_python.txt
Q: Efficient way to rotate a 2D array of integers of n size in Python I want to rotate (anti-clockwise) a 2D nxn array of integers and the 2D array is stored as a list of lists. For example: a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] After rotation, the output should look like: b = [[3, 6, 9], [2, 5, 8], ...
Efficient way to rotate a 2D array of integers of n size in Python
I want to rotate (anti-clockwise) a 2D nxn array of integers and the 2D array is stored as a list of lists. For example: a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] After rotation, the output should look like: b = [[3, 6, 9], [2, 5, 8], [1, 4, 7]] I have written a function which performs the above rotat...
[ "The most efficient is probably using numpy for this:\n>>> import numpy as np\n>>> na = np.array(a)\n>>> np.rot90(na)\narray([[3, 6, 9],\n [2, 5, 8],\n [1, 4, 7]])\n\nAbout the efficiency of your current approach. If the matrix is an nΓ—n-matrix, then zip will work in O(n2), reversed will here work in O(...
[ 4, 0 ]
[]
[]
[ "arrays", "python", "python_3.x", "rotation" ]
stackoverflow_0046193382_arrays_python_python_3.x_rotation.txt
Q: Using Numpy Arrays to load encoded faces faster in an OpenCV project I want to build a simple face recognition project. But Every time I start my program it takes really long time to encode all the Images and the load those encoded images.Can someone please tell me if I can pre-encode all the images and then direc...
Using Numpy Arrays to load encoded faces faster in an OpenCV project
I want to build a simple face recognition project. But Every time I start my program it takes really long time to encode all the Images and the load those encoded images.Can someone please tell me if I can pre-encode all the images and then directly load the encodings. I am a beginner please help me . I was trying to c...
[ "In short words: if you already can get face encodings from your images into some data structure, - what a problem to store that data structure permanently for future use?! Use Pickle, some SQL (the simpliest one - sqlite3) or nonSQL database, whatever.\n" ]
[ 0 ]
[]
[]
[ "face_recognition", "opencv", "python" ]
stackoverflow_0074333455_face_recognition_opencv_python.txt
Q: Python to list all the combinations of any-3-elements in a list Finding a way to list all the combinations of any-3-elements in a list: Here is what I tried: import itertools the_list = ["Alpha","Beta","Gamma","Delta","Epsilon","Zeta"] list_of_trios = [(the_list[p1], the_list[p2], the_list[p3]) for p1 in range(l...
Python to list all the combinations of any-3-elements in a list
Finding a way to list all the combinations of any-3-elements in a list: Here is what I tried: import itertools the_list = ["Alpha","Beta","Gamma","Delta","Epsilon","Zeta"] list_of_trios = [(the_list[p1], the_list[p2], the_list[p3]) for p1 in range(len(the_list)) for p2 in range(p1+1,len(the_list)) for p3 in range(p1...
[ "https://docs.python.org/3/library/itertools.html?highlight=comb#itertools.combinations\nfrom itertools import combinations\n\nthe_list = [\"Alpha\",\"Beta\",\"Gamma\",\"Delta\",\"Epsilon\",\"Zeta\"]\n\nlist_of_trios = list(combinations(the_list, 3))\n\n" ]
[ 2 ]
[]
[]
[ "combinations", "list", "loops", "python" ]
stackoverflow_0074333556_combinations_list_loops_python.txt
Q: Here from the text of the file I wanted to print the details of the footballer Here from the text of the file I wanted to print the details of the footballer from re import findall f = open('soccer_player.txt', "r") mathces = 0 textin = f.readlines() for line in textin: mathces= int(('').join(findall(r'\d+', l...
Here from the text of the file I wanted to print the details of the footballer
Here from the text of the file I wanted to print the details of the footballer from re import findall f = open('soccer_player.txt', "r") mathces = 0 textin = f.readlines() for line in textin: mathces= int(('').join(findall(r'\d+', line))) if(mathces>50) print (mathces) f.close() How to do? This is the ...
[ "Though your question is not clear, may be you want to do one of the following:\n\nPrinting the value (may be a score) which is greater than 50. Your code may not work due to syntax error after if statement. Correct way will be:\n\nfrom re import findall\nf = open('soccer_player.txt', \"r\")\nmathces = 0\ntextin = ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074328122_python.txt
Q: Wait until page is loaded with Selenium WebDriver for Python I want to scrape all the data of a page implemented by a infinite scroll. The following python code works. for i in range(100): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) This means every time I scroll...
Wait until page is loaded with Selenium WebDriver for Python
I want to scrape all the data of a page implemented by a infinite scroll. The following python code works. for i in range(100): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) This means every time I scroll down to the bottom, I need to wait 5 seconds, which is generally ...
[ "The webdriver will wait for a page to load by default via .get() method.\nAs you may be looking for some specific element as @user227215 said, you should use WebDriverWait to wait for an element located in your page:\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom sel...
[ 408, 110, 70, 47, 24, 18, 13, 8, 8, 7, 5, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "execute_script", "python", "selenium" ]
stackoverflow_0026566799_execute_script_python_selenium.txt