content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: I am a new learner of Python, and I am having a major problem with my code The problem can be summarized below in this snippet of code. #! python3 people = { "alice": { "style": "bun", "length": 5}, "bob":{ "style": "ponytail", "length": 19} } cut = people["alice"["length"]...
I am a new learner of Python, and I am having a major problem with my code
The problem can be summarized below in this snippet of code. #! python3 people = { "alice": { "style": "bun", "length": 5}, "bob":{ "style": "ponytail", "length": 19} } cut = people["alice"["length"]] =+ 1 print("Alice's hair length is" + str(cut)) I tried adding and taking aw...
[ "You are very close! people[\"alice\"] would return the inner dictionary ready for your next index. Its a bit subtle, but =+ 1 assigns +1 to the length and also the cut. So you need to do something there. I changed the code to assign cut to the length plus one. That's a guess on what you wanted.\ncut = people[\"ali...
[ 0 ]
[]
[]
[ "dictionary", "math", "python", "python_3.x" ]
stackoverflow_0074242467_dictionary_math_python_python_3.x.txt
Q: How can I access to the attributes of an object of a class? I have the following code: class Animal: def __init__(self, age, name) -> None: self.age = age self.name = name def getAge(self): return self.age def getName(self): return self.name class Animals:...
How can I access to the attributes of an object of a class?
I have the following code: class Animal: def __init__(self, age, name) -> None: self.age = age self.name = name def getAge(self): return self.age def getName(self): return self.name class Animals: def __init__(self, index) -> None: self.index = ...
[ "The problem is in this line:\nprint('index: ',i,', Age: ',this.animalList[i].getAge,', Name: ',this.animalList[i].getAge)\n\nYou are printing this.animalList[i].getAge, which is a function. To actually get the age, you must call the function like this.animalList[i].getAge().\nThis alone will resolve the question, ...
[ 0 ]
[]
[]
[ "attributes", "memory_address", "object", "oop", "python" ]
stackoverflow_0074242496_attributes_memory_address_object_oop_python.txt
Q: the first name appears before the last name in this List. I want to sort the list in alphabetical order of the last name. how to do that? I would like to compare every lastname in list in def cmp_names(name1, name2): def bubble_sort(L, func): end = len(L) for i in range(end-1): for j in range(end-1...
the first name appears before the last name in this List. I want to sort the list in alphabetical order of the last name. how to do that?
I would like to compare every lastname in list in def cmp_names(name1, name2): def bubble_sort(L, func): end = len(L) for i in range(end-1): for j in range(end-1-i): i1 = (end-1) - (j+1) i2 = (end-1) - j if func(L[i1], L[i2]): L[i1],L[i2] = L[i2],L[i1]...
[ "For bubble sort you the easiest way is to keep iterating until there are 0 swaps. So using a while loop and iterating over the length of the list and incrementing the swap counter each time you make a swap.\ndef bubble_sort(L, func):\n while True:\n swaps = 0\n for i in range(1, len(L)):\n ...
[ 0 ]
[]
[]
[ "bubble_sort", "list", "python", "sorting", "string" ]
stackoverflow_0074242509_bubble_sort_list_python_sorting_string.txt
Q: Curl commands to python-requests methods conversion I am writing a python script to convert some Curl commands so that they can be called using methods from requests module of python, but I got some errors. Here is the curl commands block: export NEXRAN_XAPP=`sudo kubectl get svc -n ricxapp --field-selector metada...
Curl commands to python-requests methods conversion
I am writing a python script to convert some Curl commands so that they can be called using methods from requests module of python, but I got some errors. Here is the curl commands block: export NEXRAN_XAPP=`sudo kubectl get svc -n ricxapp --field-selector metadata.name=service-ricxapp-nexran-rmr -o jsonpath='{.items[0...
[ "\nI am new to curl commands. Can anybody help me to do the correct\nconversion?\n\nHere is a conversion of the two curl commands you posted.\nI used Convert curl commands to Python\nimport requests\n\nheaders = {\n # Already added when you pass json=\n # 'Content-type': 'application/json',\n}\n\njson_data = ...
[ 0 ]
[]
[]
[ "curl", "python", "python_requests" ]
stackoverflow_0074241516_curl_python_python_requests.txt
Q: Taking online python course and need to make a password, aka the input, more complex I'm currently in the process of learning python and having a lot of trouble with the syntax. The problem I'm currently working on is asking me to make a simple password/input more complex. So far I'm trying to use a for loop to cy...
Taking online python course and need to make a password, aka the input, more complex
I'm currently in the process of learning python and having a lot of trouble with the syntax. The problem I'm currently working on is asking me to make a simple password/input more complex. So far I'm trying to use a for loop to cycle through all the letters and see if they need to be changed, as in m -> M. I want each ...
[ "First, you must have quotes around your strings. For example, instead of letter = @, you must do letter = '@'.\nSecondly, it is a better approach to use a dictionary of replacement letters and loop over the list checking for the replacements.You can do it like this:\nword = input()\n\nreplacements = {'i': '1', 'a'...
[ 0, 0 ]
[]
[]
[ "for_loop", "if_statement", "python", "string" ]
stackoverflow_0074242562_for_loop_if_statement_python_string.txt
Q: Using a dictionary to get total points for a scrabble word I am having a really hard time answering this question for a class that I am taking. In this problem, I have to write a program using a dictionary containing letters with points. So any word that is entered, I have to output the number of points. The progr...
Using a dictionary to get total points for a scrabble word
I am having a really hard time answering this question for a class that I am taking. In this problem, I have to write a program using a dictionary containing letters with points. So any word that is entered, I have to output the number of points. The program that I am using is Python. These are the instructions: Scrab...
[ "You can enumerate the word char by char, then use this char as key to the tile_dict dictionary to obtain character value. You can sum these values with sum() function:\nword = \"PYTHON\"\n\ncnt = sum(tile_dict[char] for char in word)\nprint(cnt)\n\nPrints:\n14\n\n", "If the input is PYTHON,\nthe output is: PYTHO...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "scrabble" ]
stackoverflow_0068171037_dictionary_python_scrabble.txt
Q: How do I break out of a While loop when either the variable becomes True/False or a certain amount of times? import sys ok = True count = 0 while ok == True: try: a = int(input("What is a? Put number pls ")) ok = False count = count + 1 except ValueError: print("no u") if ...
How do I break out of a While loop when either the variable becomes True/False or a certain amount of times?
import sys ok = True count = 0 while ok == True: try: a = int(input("What is a? Put number pls ")) ok = False count = count + 1 except ValueError: print("no u") if (count >= 3): sys.exit() What I'm trying to do here is get the user to input an integer. If the user inputted...
[ "Here's an approach which you might not have thought of:\ncount = 0\nwhile count < 3:\n try:\n a = int(input(\"What is a? Put number pls \"))\n break\n except ValueError:\n print(\"no u\")\n count = count + 1\n\nThere is no need for ok because you can just use a break statement if ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074242609_python.txt
Q: Django Web Application - Monitor local folder and import csv files to database I have this Django web application project that needs to be hosted on a local network. In addition basic CRUD features, the scope requires to continuously monitor a local storage folder (C: or D: or E:) for csv files and import them to ...
Django Web Application - Monitor local folder and import csv files to database
I have this Django web application project that needs to be hosted on a local network. In addition basic CRUD features, the scope requires to continuously monitor a local storage folder (C: or D: or E:) for csv files and import them to the database (Postgresql). I have already written the code for reading the csv files...
[ "After searching, I found out there are a few ways of achieving the objective. Using Cron, Scheduler, Rocketry etc.\n" ]
[ 0 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0074203274_csv_django_python.txt
Q: Why is my code treating " " (a space) as a consonant? How can I make this code go over spaces without treating them as consonants? The example below, "text message", should return "tx msg", the code only prints consonants that don't have another consonant before them (and words that are only composed of vowels), b...
Why is my code treating " " (a space) as a consonant?
How can I make this code go over spaces without treating them as consonants? The example below, "text message", should return "tx msg", the code only prints consonants that don't have another consonant before them (and words that are only composed of vowels), but it returns "txmsg" instead. It's treating the space as a...
[ "You are adding original[i] only if its a consonant (and before has a vowel) which space its not. Add a special case for it.\n if (isConsonant(original[i]) and isVowel(original[i - 1])) or original[i]==' ':\n\n" ]
[ 1 ]
[]
[]
[ "function", "if_statement", "list", "python" ]
stackoverflow_0074242661_function_if_statement_list_python.txt
Q: Remove 2 duplicated swap sublists in list I have a two-dimensional list like this: [[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]] I want to remove all the sublists that are duplicates but in reverse order (ie: [1, 6] and [6, 1], [3, 7] and [7, 3]). The result should be: [[1, 6], [2, 5], [3, 7], ...
Remove 2 duplicated swap sublists in list
I have a two-dimensional list like this: [[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]] I want to remove all the sublists that are duplicates but in reverse order (ie: [1, 6] and [6, 1], [3, 7] and [7, 3]). The result should be: [[1, 6], [2, 5], [3, 7], [8, 9]]
[ "You can use set and frozenset:\nlst = [[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]]\n\noutput = set(map(frozenset, lst))\n\nprint(output)\n# {frozenset({1, 6}), frozenset({2, 5}), frozenset({3, 7}), frozenset({8, 9})}\n\nIf you want to have a list of lists, then you can append the following:\nou...
[ 2, 1 ]
[]
[]
[ "list", "python", "swap" ]
stackoverflow_0074242679_list_python_swap.txt
Q: No module named rest_framework i've seen a lot of people having trouble with this here, and i always see them saying other to use pip3 or just pip to install it. But in my case i've uninstalled it and installed id multiple times both using pip or pip3 and none of them seem to work. I've added 'rest_framework' to m...
No module named rest_framework
i've seen a lot of people having trouble with this here, and i always see them saying other to use pip3 or just pip to install it. But in my case i've uninstalled it and installed id multiple times both using pip or pip3 and none of them seem to work. I've added 'rest_framework' to my settings as well and still doesn't...
[ "Try using sudo pip install djangorestframework, I've seen other SO questions and it seemed to fix the problem.\n", "Add rest_framework just before agenda.apps.AgendaConfig in the installed apps in settings.py file. It seems that agenda app using some rest_framework libraries before it is initialized. \nINSTALLED...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_rest_framework", "pip3", "python", "python_3.x" ]
stackoverflow_0047763408_django_django_rest_framework_pip3_python_python_3.x.txt
Q: python manage.py dumpdata Unable to serialize database I am trying to run the command python manage.py dumpdata > data.json However, I receive such a traceback: CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-4: character maps to <undefined> Exception ignored in: <...
python manage.py dumpdata Unable to serialize database
I am trying to run the command python manage.py dumpdata > data.json However, I receive such a traceback: CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-4: character maps to <undefined> Exception ignored in: <generator object cursor_iter at 0x0000020E11353820> Tracebac...
[ "Running set PYTHONIOENCODING=utf-8 before python manage.py dumpdata > data.json has solved the issue.\n", "if this doesn't work, and if you are windows, try\npython -Xutf8 ./manage.py dumpdata > data.json\n\n" ]
[ 12, 0 ]
[ "I couldn't get the soloution above to work, however i did get this to work;\nhttps://pypi.org/project/django-dump-load-utf8/\nI installed it and used its command for dumping data and it worked, hope this helps anybody else! I think my problem was that my database had Norwegian letters in it \"ÆØÅ\"\n" ]
[ -3 ]
[ "django", "dumpdata", "python" ]
stackoverflow_0067616945_django_dumpdata_python.txt
Q: Dataframe get exact value using an array Suppose I have the following dataframe: A B C D Count 0 0 0 0 0 12.0 1 0 0 0 1 2.0 2 0 0 1 0 4.0 3 0 0 1 1 0.0 4 0 1 0 0 3.0 5 0 1 1 0 0.0 6 1 0 0 0 7.0 7 1 0 0 1 9.0 8 1 0 ...
Dataframe get exact value using an array
Suppose I have the following dataframe: A B C D Count 0 0 0 0 0 12.0 1 0 0 0 1 2.0 2 0 0 1 0 4.0 3 0 0 1 1 0.0 4 0 1 0 0 3.0 5 0 1 1 0 0.0 6 1 0 0 0 7.0 7 1 0 0 1 9.0 8 1 0 1 0 0.0 ... (truncated for readability) ...
[ "You can index the DataFrame with a list of the key column names and compare the resulting view to the array, using NumPy broadcasting to do it for each line at once. Then collapse the resulting Boolean DataFrame to a Boolean row index with all() and use that to index the Count column.\nIf df is the DataFrame and a...
[ 3, 1, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074242345_dataframe_numpy_pandas_python.txt
Q: How do I program Python to read bytes from a file as base10 and organize each byte into a list? I'm pretty amateur with python and computer data, so bare with me - I have a file called "input.nodes" and I want to have python read each byte, convert them to base10, and then organize each byte chronologically into a...
How do I program Python to read bytes from a file as base10 and organize each byte into a list?
I'm pretty amateur with python and computer data, so bare with me - I have a file called "input.nodes" and I want to have python read each byte, convert them to base10, and then organize each byte chronologically into a list. I have almost succeeded with this. I'm using Python 3.10, which if I recall correctly, is the ...
[ "The bytes type in Python represents a sequence of byte-valued integers (0-255), but displays by default as an immutable byte string. If you open your file in binary mode ('rb') the data you read is a byte string that can be accessed as integers individually through indexing or iteration, or you can convert it exp...
[ 1 ]
[]
[]
[ "base", "converters", "hex", "python", "unicode" ]
stackoverflow_0074242553_base_converters_hex_python_unicode.txt
Q: ElasticSearch Failed to build [request] after last required field arrived I am doing a ranking evaluation using ElasticSearch on the LinkSO dataset. I have made the necessary files required to curl onto using Kibana and made my ranking function as well. However, I receive an error BadRequestError: BadRequestError(...
ElasticSearch Failed to build [request] after last required field arrived
I am doing a ranking evaluation using ElasticSearch on the LinkSO dataset. I have made the necessary files required to curl onto using Kibana and made my ranking function as well. However, I receive an error BadRequestError: BadRequestError(400, 'x_content_parse_exception', 'Failed to build [request] after last require...
[ "The error comes when the json file is incorrectly created for ranking of the documents. The json file needs to be checked to have as many attributes as needed.\n" ]
[ 0 ]
[]
[]
[ "elasticsearch", "python" ]
stackoverflow_0074175976_elasticsearch_python.txt
Q: Error while using bert-base-nli-mean-tokens bert model I am using this code: model = SentenceTransformer('bert-base-nli-mean-tokens') body = list(data['preprocessedBody']) bodyEmbedding = model.encode(body, show_progress_bar = True) However, I am getting this error: ProxyError: HTTPSConnectionPool(host='huggingfa...
Error while using bert-base-nli-mean-tokens bert model
I am using this code: model = SentenceTransformer('bert-base-nli-mean-tokens') body = list(data['preprocessedBody']) bodyEmbedding = model.encode(body, show_progress_bar = True) However, I am getting this error: ProxyError: HTTPSConnectionPool(host='huggingface.co', port=443): Max retries exceeded with url: /api/model...
[ "It was simply a proxy issue. I just added https and http and their relative proxy values into system environment in windows.\n" ]
[ 1 ]
[]
[]
[ "bert_language_model", "nlp", "python", "sentence_transformers", "sslerrorhandler" ]
stackoverflow_0074228567_bert_language_model_nlp_python_sentence_transformers_sslerrorhandler.txt
Q: Python in Terminal groupby returning only NaN with multiple columns instead of 1 I am running the following code of python in a terminal: df_null_count_extract['DAY_AVG'] = df_null_count_extract.groupby(['CONTROL_COL_NAME', 'RUN_ID', 'RUN_DATE', 'CONTROL_TABLE_NAME'], as_index = False)['CONTROL_COL_VAL'].transform...
Python in Terminal groupby returning only NaN with multiple columns instead of 1
I am running the following code of python in a terminal: df_null_count_extract['DAY_AVG'] = df_null_count_extract.groupby(['CONTROL_COL_NAME', 'RUN_ID', 'RUN_DATE', 'CONTROL_TABLE_NAME'], as_index = False)['CONTROL_COL_VAL'].transform('mean') When I do however I only receive NaN values and it returns multiple instead ...
[ "I was able to figure it out, terminal did not like the as_index = False after I removed that it worked perfectly\n" ]
[ 0 ]
[]
[]
[ "multithreading", "pandas", "python" ]
stackoverflow_0074241193_multithreading_pandas_python.txt
Q: How to move files 1 at a time to multiple folders in python just want your insight on what I can do since I'm lost for 2 days now. What I'm trying to do is to move a file from 1 folder to 5 folders 1 at a time. here's what I got so far. import os import shutil #path source = 'C:/Users/folder/Downloads/Files/test'...
How to move files 1 at a time to multiple folders in python
just want your insight on what I can do since I'm lost for 2 days now. What I'm trying to do is to move a file from 1 folder to 5 folders 1 at a time. here's what I got so far. import os import shutil #path source = 'C:/Users/folder/Downloads/Files/test' destination = ['C:/Users/folder/Downloads/Files/test1', 'C:...
[ "You have a lot of extra nonsense in there to manipulate the file name, but nothing that rotates through the destinations. This does what you ask:\nimport os\nimport shutil\n\nsource = 'C:/Users/folder/Downloads/Files/test'\n\ndestination = [\n 'C:/Users/folder/Downloads/Files/test1',\n 'C:/Users/folder/Down...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074242176_python.txt
Q: Converting a CSV to dictionary then looking it up via map() function I have a dataframe called DummyData Cover Age Are AddFlag 0 COMP 33 4 1 1 COMP 67 47 1 2 COMP 17 155 1 3 COMP 24 35 1 4 COMP 66 57 1 My second data frame is called BaseRate Cover Anchor ...
Converting a CSV to dictionary then looking it up via map() function
I have a dataframe called DummyData Cover Age Are AddFlag 0 COMP 33 4 1 1 COMP 67 47 1 2 COMP 17 155 1 3 COMP 24 35 1 4 COMP 66 57 1 My second data frame is called BaseRate Cover Anchor 0 COMP 1000.0 1 TPFT 850.0 2 TPO 840.0 I run the followin...
[ "\"Anchor\" is a key in your CoverDict pointing to the map you want to use.\nYou can access it like this:\nDummyData[\"Anchor\"] = DummyData[\"Cover\"].map(CoverDict[\"Anchor\"])\n\nIn your code, you tried to access a variable called Anchor when you did .map(Anchor), buy you would have to define that variable befor...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074240927_dictionary_python.txt
Q: Python: Calculate total number of comparisons to find a match I have two arrays. One with 10 Indexes, One with 2 Indexes. I want to check if the large array has the exact values of the small array. There is a total of 9 comparisons that need to be made. How do I calculate this value for arrays of different sizes? ...
Python: Calculate total number of comparisons to find a match
I have two arrays. One with 10 Indexes, One with 2 Indexes. I want to check if the large array has the exact values of the small array. There is a total of 9 comparisons that need to be made. How do I calculate this value for arrays of different sizes? I need this value to manipulate control flow. largeArr = [1, 2, 3, ...
[ "The brute-force check will take up to len(largeArr) - len(smallArr) + 1 comparisons, each of size up to len(smallArr). It will take that many if it's not found. If found, it might take half of that on average, but that depends on the statistics of their entries. So this is O(n), where n = len(largeArr).\nHoweve...
[ 1, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074242112_numpy_python.txt
Q: How does matplotlib knows which Figure object to associate with which Axes object? I am currently learning matplotlib using a book named "python data science handbook". I found various instances where the OOP interface of matplotlib is used rather than matlab style interface. Example: fig = plt.figure() ax = plt....
How does matplotlib knows which Figure object to associate with which Axes object?
I am currently learning matplotlib using a book named "python data science handbook". I found various instances where the OOP interface of matplotlib is used rather than matlab style interface. Example: fig = plt.figure() ax = plt.axes() x = np.linspace(0, 10, 1000) ax.plot(x, np.sin(x)); I want to know, ho does the ...
[ "matplotlib.pyplot maintains a record of all existing figures, assigning to each figure a number (1, 2,...). It also keeps track which figure is currently active.\nplt.axes() adds an axes object to the currently active figure. The first line of the source code of this function is fig = gcf() which gets this figure....
[ 1 ]
[]
[]
[ "matplotlib", "oop", "python", "visualization" ]
stackoverflow_0074242461_matplotlib_oop_python_visualization.txt
Q: Pylint-django raising error about Django not being configured when that's not the case (VSCode) Pylint-django worked just fine up to version 2.3.x but since 2.4.0 it reports an error on every python-django file: Django was not configured. For more information runpylint --load-plugins=pylint_django --help-msg=djan...
Pylint-django raising error about Django not being configured when that's not the case (VSCode)
Pylint-django worked just fine up to version 2.3.x but since 2.4.0 it reports an error on every python-django file: Django was not configured. For more information runpylint --load-plugins=pylint_django --help-msg=django-not-configuredpylint(django-not-configured) This happens on VSCode and I believe I have it correc...
[ "Add the --django-settings-module argument the VS Code settings:\n {\n \"python.linting.pylintArgs\": [\n [...]\n \"--disable=django-not-configured\",\n \"--django-settings-module=<mainapp>.settings\",\n ]\n }\n\nChange <mainapp> to be your main app directory. For example, if your setti...
[ 48, 13, 4, 1, 1 ]
[]
[]
[ "django", "pylint", "python", "visual_studio_code" ]
stackoverflow_0065761250_django_pylint_python_visual_studio_code.txt
Q: What should I do to solve my problem with dropna and fillna in python? I see there are some missing data, in my data. there are NaN values in "Type 2" column. When i write this code to drop the rows which have NaN values; When i write this code to add "empty" which have NaN values; I restarted my jupyter noteb...
What should I do to solve my problem with dropna and fillna in python?
I see there are some missing data, in my data. there are NaN values in "Type 2" column. When i write this code to drop the rows which have NaN values; When i write this code to add "empty" which have NaN values; I restarted my jupyter notebook but its still the same.
[ "you can use:\ndata = data[data['Type 2'].notna()]\n\n", "Try \ndata.dropna(axis=1, inplace=True)\naxis=1 means columns axis=0 means rows\nif any column contains NaN it will remove entire column similarly row\n", "When you do data['Type 2'].dropna(inplace=True), that's creating a new series (for your \"Type 2\"...
[ 0, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0060832099_pandas_python.txt
Q: sqlanydb windows could not load dbcapi I am trying to connect to a SQL Anywhere database via python. I have created the DSN and I can use command prompt to connect to the database using dbisql - c "DNS=myDSN". When I try to connect through python using con = sqlanydb.connect(DSN= "myDSN") I get `Traceback (most ...
sqlanydb windows could not load dbcapi
I am trying to connect to a SQL Anywhere database via python. I have created the DSN and I can use command prompt to connect to the database using dbisql - c "DNS=myDSN". When I try to connect through python using con = sqlanydb.connect(DSN= "myDSN") I get `Traceback (most recent call last): File "<pyshell#5>", lin...
[ "I was able to resolve the problem. I was never able to use the sqlanydb.connect. I ended up using pyodbc. So my final connection string was con = pydobc.connect(dsn=\"myDSN\"). I think that sqlanydb is only fully functional with sqlanydb 17 and I was using a previous version.\n", "Depending on how Sybase is loca...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "sqlanydb", "sqlanywhere" ]
stackoverflow_0052723924_python_sqlanydb_sqlanywhere.txt
Q: The garbage collector is trying to clean up connection asyncmy.connection.Connection I'll try to be as complete as possible in this issue. I'm using Sanic, an ASGI Python framework, and I built a Database manager on top of this. This database manager uses the ContextVar to give access to my current db instance eve...
The garbage collector is trying to clean up connection asyncmy.connection.Connection
I'll try to be as complete as possible in this issue. I'm using Sanic, an ASGI Python framework, and I built a Database manager on top of this. This database manager uses the ContextVar to give access to my current db instance everywhere in the code. Here's the code related to the database: database.py # -*- coding:utf...
[ "This line might be causing you the problem await session_ctx.close(exc_type, exc_value, traceback).\nTry changing it to this await asyncio.shield(session_ctx.close(exc_type, exc_value, traceback)).\nThis was added to the SQLAlchemy code base in July.\n\nThis change was implemented in /asyncio/engine.py and /asynci...
[ 4, 0, 0 ]
[]
[]
[ "python", "sanic", "sqlalchemy" ]
stackoverflow_0074108354_python_sanic_sqlalchemy.txt
Q: How to accept data from a frequency table in python I need help on how to get a list of data from two different inputs, a value input and a frequency input. I think i could do it by creating a dictionary and adding the values and frequencies to it in the form {v:f,v:f,v:f} etc., but I don't know how to do that. e....
How to accept data from a frequency table in python
I need help on how to get a list of data from two different inputs, a value input and a frequency input. I think i could do it by creating a dictionary and adding the values and frequencies to it in the form {v:f,v:f,v:f} etc., but I don't know how to do that. e.g. values = First, enter or paste the VALUES, separated b...
[ "you can do this by Counter\nfrom collections import Counter\nlst = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]\nprint(Counter(lst))\n\n>>> Counter({1: 5, 2: 4, 3: 3, 4: 2, 5: 1})\n\n", "dictionary = dict(zip(input('values = First, enter or paste the VALUES, separated by spaces: ').split(' '),input('frequencies...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074242950_dictionary_python.txt
Q: linear programming in python? I need to make a linear programming model. Here are the inequalities I'm using (for example): 6x + 4y <= 24 x + 2y <= 6 -x + y <= 1 y <= 2 I need to find the area described by these inequalities, and shade it in a graph, as well as keep track of the vertices of the bounding lines of ...
linear programming in python?
I need to make a linear programming model. Here are the inequalities I'm using (for example): 6x + 4y <= 24 x + 2y <= 6 -x + y <= 1 y <= 2 I need to find the area described by these inequalities, and shade it in a graph, as well as keep track of the vertices of the bounding lines of this area, and draw the bounding li...
[ "UPDATE: The answer has become somewhat outdated in the past 4 years,\nhere is an update. You have many options:\n\nIf you do not have to do it Python then it is a lot more easier to\ndo this in a modeling langage, see Any good tools to solve\ninteger programs on linux?\n\nI personally use Gurobi these\ndays throu...
[ 70, 20, 7, 6, 4, 1, 0, 0 ]
[]
[]
[ "linear_programming", "python" ]
stackoverflow_0010697995_linear_programming_python.txt
Q: Login Button not redirecting back to home page I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked. urls.py from django....
Login Button not redirecting back to home page
I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked. urls.py from django.urls import path from .views import pplCreate, pplCr...
[ "In settings.py file, simply you can add this.\nLOGIN_REDIRECT_URL = 'pplLst' #This is path name from urls\n\nAdd this in settings.py file, then you will get redirected to home page\nJust remove auth view from views and do following way:\nIn urls.py:\nfrom django.contrib.auth import views as auth_views\n\npath('lo...
[ 1 ]
[]
[]
[ "django", "django_templates", "django_views", "python", "python_3.x" ]
stackoverflow_0074243001_django_django_templates_django_views_python_python_3.x.txt
Q: How to save python notebook cell code to file in Colab TLDR: How can I make a notebook cell save its own python code to a file so that I can reference it later? I'm doing tons of small experiments where I make adjustments to Python code to change its behaviour, and then run various algorithms to produce results fo...
How to save python notebook cell code to file in Colab
TLDR: How can I make a notebook cell save its own python code to a file so that I can reference it later? I'm doing tons of small experiments where I make adjustments to Python code to change its behaviour, and then run various algorithms to produce results for my research. I want to save the cell code (the actual pyth...
[ "All cell codes are stored in a List variable In.\nFor example you can print the lastest cell by\nprint(In[-1]) # show itself\n# print(In[-1]) # show itself\n\nSo you can easily save the content of In[-1] or In[-2] to wherever you want.\n", "Posting one potential solution but still looking for a better and clea...
[ 2, 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074234310_google_colaboratory_python.txt
Q: django.db.migrations.exceptions.InconsistentMigrationHistory When I run python manage.py migrate on my Django project, I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hari/project/env/local/lib/python2.7/site- ...
django.db.migrations.exceptions.InconsistentMigrationHistory
When I run python manage.py migrate on my Django project, I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in execute...
[ "Since you are using a custom User model, you can do 4 steps:\n\nComment out django.contrib.admin in your INSTALLED_APPS settings\n\n\nINSTALLED_APPS = [\n ...\n #'django.contrib.admin',\n ...\n]\n\n\n\nComment out admin path in urls.py\n\n\nurlpatterns = [\n ...\n #path('admin/', admin.site.urls) \n .....
[ 169, 113, 71, 68, 63, 35, 9, 9, 5, 4, 3, 3, 2, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "first of all backup your data. (copy your db file).\ndelete sqlite.db and also the migration folder.\nthen, run these commands:\n./manage.py makemigrations APP_NAME\n./manage.py migrate APP_NAME\n\nafter deleting the DB file and migration folder make sure that write the application name after the migration command...
[ -1, -1 ]
[ "database_migration", "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0044651760_database_migration_django_django_models_django_rest_framework_python.txt
Q: PHP fwrite to proc_open to Python failing with ō character but not others in text2image Daemon I created a Daemon to wrap around Invoke-AI command line interface https://github.com/invoke-ai/InvokeAI to generate images for my website. My issue is that it keeps failing on some artists names with "ō" in their name a...
PHP fwrite to proc_open to Python failing with ō character but not others in text2image Daemon
I created a Daemon to wrap around Invoke-AI command line interface https://github.com/invoke-ai/InvokeAI to generate images for my website. My issue is that it keeps failing on some artists names with "ō" in their name and I have no idea why. I had the same issue with another interface. Both were ran in an Anaconda Pyt...
[ "I found something that worked here. This setting is also in Windows 11 and is still in beta.\nUsing UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10)\nRun intl.cpl (which opens the regional settings in Control Panel) then\n\n" ]
[ 0 ]
[]
[]
[ "cmd", "php", "proc_open", "python" ]
stackoverflow_0074242722_cmd_php_proc_open_python.txt
Q: Scrape select headings and inner text from a webpage using BeautifulSoup? Source - a blog post URL I want to get the inner text of both the Heading tags AND the body copy within that tag into a table output that looks like this H2;{H2 tag inner tex}; {p tag(s) inner text} H3;{H2 tag inner tex}; {p tag(s) inner tex...
Scrape select headings and inner text from a webpage using BeautifulSoup?
Source - a blog post URL I want to get the inner text of both the Heading tags AND the body copy within that tag into a table output that looks like this H2;{H2 tag inner tex}; {p tag(s) inner text} H3;{H2 tag inner tex}; {p tag(s) inner text} H2;{H2 tag inner tex}; {p tag(s) inner text} H3;{H2 tag inner tex}; {p tag(s...
[ "I'm not sure I understand exactly how you want your table organized (which paragraphs you want for each heading? are overlaps ok for nested headings?), but the following suggested solution will set a row for each header tag, and then loop through its siblings collecting all p tags until it hits another header tag:...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074238931_beautifulsoup_python_web_scraping.txt
Q: Structure for developmental Python packages I'm starting a brand new project. I'm splitting code of different functions (e.g., utils, database, main application) into their own respective packages such that other new projects can just add them as dependencies and import them in the future. Packages may have cross-...
Structure for developmental Python packages
I'm starting a brand new project. I'm splitting code of different functions (e.g., utils, database, main application) into their own respective packages such that other new projects can just add them as dependencies and import them in the future. Packages may have cross-dependencies (e.g., database depends on utils). I...
[ "I suggest the package approach you are thinking about. The key method you're missing is to make editable installs locally for all your packages.\npip install -e . in package root directory\nEditable installs will reflect their changes right away in your environment\nSince you are using conda you probably want cond...
[ 1 ]
[]
[]
[ "anaconda", "python" ]
stackoverflow_0074243069_anaconda_python.txt
Q: Is it possible to do a depth first search iteratively without copying visited nodes? Background I am searching a 2D grid for a word. We can search left/right and up/down. For example, in this grid, searching for "abef" starting at (0,0) will return True Example (grid1): Where I'm at The recursive version gives...
Is it possible to do a depth first search iteratively without copying visited nodes?
Background I am searching a 2D grid for a word. We can search left/right and up/down. For example, in this grid, searching for "abef" starting at (0,0) will return True Example (grid1): Where I'm at The recursive version gives expected results (see dfs_rec() below). The iterative version also gives expected results...
[ "You noticed that the recursive version was able to use a single visited accumulator by resetting it with visited.remove((row,col)) when backtracking. So the same can be done here by imitating the function call stack so that we know when backtracking occurs.\ndef dfs_iter_nocopy (grid, start_word, start_row, start_...
[ 2, 0 ]
[]
[]
[ "algorithm", "depth_first_search", "graph_theory", "python", "tree_search" ]
stackoverflow_0071415614_algorithm_depth_first_search_graph_theory_python_tree_search.txt
Q: Why from utils impost fs_data_dir doesn't work? I'm studying about the searchline analysis from BrainIAK. But the code from utils import fs_data_dir, results_path print('data dir = %s' % (fs_data_dir)) I ran it on google colab but it doesn't work. I've searched for the utils package in python but I didn't find ...
Why from utils impost fs_data_dir doesn't work?
I'm studying about the searchline analysis from BrainIAK. But the code from utils import fs_data_dir, results_path print('data dir = %s' % (fs_data_dir)) I ran it on google colab but it doesn't work. I've searched for the utils package in python but I didn't find anything about fs_data_dir! I have a project that dep...
[ "The utils.py is from\nhttps://github.com/brainiak/brainiak-tutorials/blob/master/tutorials/utils.py\nSo, you can get it with\n!wget https://github.com/brainiak/brainiak-tutorials/blob/master/tutorials/utils.py\nThen you can use from utils import fs_data_dir, results_path\n" ]
[ 1 ]
[]
[]
[ "debugging", "google_colaboratory", "machine_learning", "package", "python" ]
stackoverflow_0074196219_debugging_google_colaboratory_machine_learning_package_python.txt
Q: InvalidArgumentError: Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: b'No files matched pattern: When I am running the following code on Google colab, tf.data.Dataset.list_files('/content/gdrive/MyDrive/Experiment/train/*.jpg') I am getting the following error: InvalidArgumentError...
InvalidArgumentError: Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: b'No files matched pattern:
When I am running the following code on Google colab, tf.data.Dataset.list_files('/content/gdrive/MyDrive/Experiment/train/*.jpg') I am getting the following error: InvalidArgumentError Traceback (most recent call last) <ipython-input-4-8d9cebdfe01f> in <module>() ----> 1 tf.data.Dataset.list_file...
[ "There might be some invalid characters in your filenames, like: .,*\nRemoving these characters resolved the problem for me.\n" ]
[ 0 ]
[ "\nThis is the example I am working with.\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\ndef load_image(filepath):\n raw_img = tf.io.read_file(filepath) \n img_tensor_int = tf.image.decode_jpeg(raw_img, channels=3)\n img_tensor_flt = tf.image.convert_image_dtype(img_tensor_int, tf.float3...
[ -1 ]
[ "deep_learning", "python", "tensorflow", "tensorflow2.0", "tensorflow_datasets" ]
stackoverflow_0067800765_deep_learning_python_tensorflow_tensorflow2.0_tensorflow_datasets.txt
Q: There is error in my python projects cannot find it i was making Jarvis project on python, just for fun,i dowlanded all libraries and it seems everything is good, but there is some problem I can not find out what is it,i will share both below here is my python code : import pyttsx3 import speech_recognition as sr ...
There is error in my python projects cannot find it
i was making Jarvis project on python, just for fun,i dowlanded all libraries and it seems everything is good, but there is some problem I can not find out what is it,i will share both below here is my python code : import pyttsx3 import speech_recognition as sr import datetime import webbrowser import wikipedia import...
[ "Try using 'nsss' instead of 'sapi5'\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074239589_python.txt
Q: Find index of list element with maximum value of specific property This code snippet: import numpy as np from skimage.measure import label, regionprops image = np.array([[1, 1, 0], [1, 0, 0], [0, 0, 2]]) labels = label(image, background=0, connectivity=2) props = regionprops(labels, image, cache=True) print(imag...
Find index of list element with maximum value of specific property
This code snippet: import numpy as np from skimage.measure import label, regionprops image = np.array([[1, 1, 0], [1, 0, 0], [0, 0, 2]]) labels = label(image, background=0, connectivity=2) props = regionprops(labels, image, cache=True) print(image) print(np.argmax([p.area for p in props])) will print: [[1 1 0] [1 0...
[ "What about using regionprops_table?\nfrom skimage.measure import label, regionprops_table\n\nlabels = label(image, background=0, connectivity=2)\n\nout = np.argmax(regionprops_table(labels, image, cache=True, properties=['area'])['area'])\n\nOutput: 0\n", "Mozway has given you a great solution. I answer here on ...
[ 2, 1 ]
[]
[]
[ "indexing", "max", "numpy", "python", "scikit_image" ]
stackoverflow_0074242952_indexing_max_numpy_python_scikit_image.txt
Q: How do I create my DataFrame to show only French movies in the 'Language' column of my dataset where there is multiple languages in the column? How do I create my DataFrame to show only French movies in the 'Language' column of my dataset where there is multiple languages in the column? Example: Languages column: ...
How do I create my DataFrame to show only French movies in the 'Language' column of my dataset where there is multiple languages in the column?
How do I create my DataFrame to show only French movies in the 'Language' column of my dataset where there is multiple languages in the column? Example: Languages column: French English German,French,Spanish Spanish,English,French French, English, Gernman What I have been trying only brings back the columns that have ...
[ "Use str.contains with word boundaries (\\b) to avoid matching substrings (e.g. 'Abc' matching 'Abcde'):\ndf.loc[df['column_name'].str.contains(r'\\bFrench\\b', case=False)]\n\nIf you are sure that there is no possible substring match (might be possible with languages):\ndf.loc[df['column_name'].str.contains('Frenc...
[ 3, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074242920_dataframe_pandas_python.txt
Q: Why lsp-mode prompt "command pyls is not present on the path" in emacs? OS: Arch Linux I follow the document and I enter pip install 'python-language-server[all]' --user in the terminal at last. After opening a python file in Emacs, lsp-mode promat me "command pyls is not present on the path" and no any completion...
Why lsp-mode prompt "command pyls is not present on the path" in emacs?
OS: Arch Linux I follow the document and I enter pip install 'python-language-server[all]' --user in the terminal at last. After opening a python file in Emacs, lsp-mode promat me "command pyls is not present on the path" and no any completion list. But I can run it in the terminal by entering pyls. Here is my init-lsp...
[ "I seem to have solved it. Emacs cannot find the executable for pyls because the directory of this file is not in the environment variable of Emacs. Execute M-x setenv RET PATH in Emacs, and then set the environment variable. I filled in /home/liu/.local/bin\n", "for anyone having this issue, put the following co...
[ 1, 0 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0069601017_emacs_python.txt
Q: manipulate Android apps like selenium does to chrome is there a library (preferably for python) where you can automate android apps? Something like selenium for Browsers, just with apps. couldnt find anything on the internet A: This answer would be better left in the comments, but I don't have enough rating for ...
manipulate Android apps like selenium does to chrome
is there a library (preferably for python) where you can automate android apps? Something like selenium for Browsers, just with apps. couldnt find anything on the internet
[ "This answer would be better left in the comments, but I don't have enough rating for this yet.\nThere is a library called Appium and you can find instructions how to run automations on an emulated device as well as on a device connected to your PC.\nThis library is widely used for testing mobile applications and i...
[ 0 ]
[]
[]
[ "android", "bots", "python", "selenium" ]
stackoverflow_0074242259_android_bots_python_selenium.txt
Q: Getting exception : AttributeError __aenter__ I get this exception: "Exception has occurred: AttributeError __aenter__" in line async with bot:. (I entered the token). Please help import asyncio import telegram async def main(): bot = telegram.Bot("token") async with bot: print(await bot.get_me())...
Getting exception : AttributeError __aenter__
I get this exception: "Exception has occurred: AttributeError __aenter__" in line async with bot:. (I entered the token). Please help import asyncio import telegram async def main(): bot = telegram.Bot("token") async with bot: print(await bot.get_me()) if __name__ == '__main__': asyncio.run(main...
[ "Think that's because you installed v13 (pip install python-telegram-bot) and the example you are looking at is from the v20 Github wiki.\nHead over here for a quick start guide for v13 wrapper: https://github.com/python-telegram-bot/v13.x-wiki/wiki/Extensions-%E2%80%93-Your-first-Bot\n", "Probobly that exception...
[ 4, 2, 0 ]
[]
[]
[ "python", "python_asyncio", "python_telegram_bot" ]
stackoverflow_0072327716_python_python_asyncio_python_telegram_bot.txt
Q: i have no clue how to solve this issue in pygame I'm trying to build a silly game however I'm stuck with an error here and I can't figure out the issue. please help me I'm new to Pygame? and it's my first game import pygame from pygame.locals import * from pygame.sprite import Group pygame.init() clock = pygame....
i have no clue how to solve this issue in pygame
I'm trying to build a silly game however I'm stuck with an error here and I can't figure out the issue. please help me I'm new to Pygame? and it's my first game import pygame from pygame.locals import * from pygame.sprite import Group pygame.init() clock = pygame.time.Clock() fps = 60 screen_width = 1400 screen_heig...
[ "Radiation is a class, but not an instance object of a sub class of pygame.sprite.Sprite. You have to add the instance object rad, instead of Radiation:\nrad_group.add(Radiation)\nrad = Radiation(col_count * tile_size, row_count * tile_size)\nrad_group.add(rad)\n\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074242426_pygame_python.txt
Q: solving exponential equation gives more than one solution I have code below for a simple test of sympy.solve: #!/usr/bin/python from sympy import * x = Symbol('x', real=True) #expr = sympify('exp(1 - 10*x) - 15') expr = exp(1 - x) - 15 print "Expressiong:", expr out = solve(expr) for item in out: print "Ans...
solving exponential equation gives more than one solution
I have code below for a simple test of sympy.solve: #!/usr/bin/python from sympy import * x = Symbol('x', real=True) #expr = sympify('exp(1 - 10*x) - 15') expr = exp(1 - x) - 15 print "Expressiong:", expr out = solve(expr) for item in out: print "Answer:", item expr = exp(1 - 10*x) - 15 print expr out = solve(e...
[ "I can also confirm that the solve output for the equation exp(1 - 10*x) - 15 == 0 appears unecessarily complicated. I would suggest for univariate equations to first consider sympy.solveset. For this example, it gives the following nicely formatted solutions.\nimport sympy as sp\nsp.init_printing(pretty_print=True...
[ 2, 1 ]
[]
[]
[ "equation", "python", "sympy" ]
stackoverflow_0040523328_equation_python_sympy.txt
Q: How to remove a specific Rectangle in Kivy? I want to know how to remove a specific Rectangle object in Kivy. I create the Rectangle in .py file by pressing a button and I want to the second button could be able to remove that specific Rectangle. My .py code: import kivy kivy.require("1.10.1") from kivy.uix.floatl...
How to remove a specific Rectangle in Kivy?
I want to know how to remove a specific Rectangle object in Kivy. I create the Rectangle in .py file by pressing a button and I want to the second button could be able to remove that specific Rectangle. My .py code: import kivy kivy.require("1.10.1") from kivy.uix.floatlayout import FloatLayout from kivy.uix.screenmana...
[ "One of the various ways can be adding a group attr. and remove that group later. Since RoundedRectangle is inherited from class Instruction, you can set its attr. group and later use method remove_group to remove that particular group as follows,\n def create_on_press(self):\n with self.canvas:\n ...
[ 1, 0 ]
[]
[]
[ "kivy", "kivy_language", "python" ]
stackoverflow_0074228829_kivy_kivy_language_python.txt
Q: Count pattern frequency in pandas dataframe column that has multiple patterns I have the dataframe below: details = { 'container_id' : [1, 2, 3, 4, 5, 6 ], 'container' : ['black box', 'orange box', 'blue box', 'black box','blue box', 'white box'], 'fruits' : ['apples, black currant', 'oranges','peache...
Count pattern frequency in pandas dataframe column that has multiple patterns
I have the dataframe below: details = { 'container_id' : [1, 2, 3, 4, 5, 6 ], 'container' : ['black box', 'orange box', 'blue box', 'black box','blue box', 'white box'], 'fruits' : ['apples, black currant', 'oranges','peaches, oranges', 'apples','apples, peaches, oranges', 'black berries, peaches, oranges,...
[ "You can do it like you did, but with specifying the delimiter. Be aware that when splitting the data, you get some leading whitespace unless your delimiter is a comma with a space. To be sure just use another step with str.strip.\ndf['fruits'].str.split(',', expand=False).explode().str.strip().value_counts()\n\nyo...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074243306_pandas_python.txt
Q: How to monitor the change in an element with selenium python I want to make a monitor that checks for the change in text of specific element and then sends me a notification through discord, im not sure how exactly I would do this. I know how to check what is currently in the element but I dont know how to compare...
How to monitor the change in an element with selenium python
I want to make a monitor that checks for the change in text of specific element and then sends me a notification through discord, im not sure how exactly I would do this. I know how to check what is currently in the element but I dont know how to compare that to a new change and give me an update. Does anyone know how ...
[ "Just add a while loop that will check this element again and again until it is changed\ncurrentText = element.text #current text of element\nupdatedText = element.text\nwhile currentText == updatedText:\n updatedText = driver.find_element(\"xpath\", 'xpath goes here').text\n # You can put here any sleep to r...
[ 0 ]
[]
[]
[ "monitor", "python", "selenium", "web_scraping" ]
stackoverflow_0074241539_monitor_python_selenium_web_scraping.txt
Q: How can I see all installed Python modules in Jupyter Lab (like pip freeze) with Python 3.7 or newer? I'm looking for a way to get a list of all installed/importable python modules from a within a Jupyterlab notebook. From the command line, I can get the list by running py -3 -m pip freeze (or) pip freeze In the...
How can I see all installed Python modules in Jupyter Lab (like pip freeze) with Python 3.7 or newer?
I'm looking for a way to get a list of all installed/importable python modules from a within a Jupyterlab notebook. From the command line, I can get the list by running py -3 -m pip freeze (or) pip freeze In the Jupyterlab console, running pip freeze returns The following command must be run outside of the IPython sh...
[ "You may run following snippet to the result.\n!pip list\n\n", "you can also try \n!pip freeze\n\nin your jupyter notebook. Hope it helps you.\n", "import pip._internal.operations.freeze\n_ = pip._internal.operations.freeze.get_installed_distributions()\nprint(sorted([\"%s==%s\" % (i.key, i.version) for i in _]...
[ 12, 6, 3, 1, 1 ]
[]
[]
[ "jupyter_lab", "pip", "python" ]
stackoverflow_0060000802_jupyter_lab_pip_python.txt
Q: How to Select Rows Based on Column Values in Pandas I create a dataset like that, Gender response female yes male yes female yes female no male yes female no male yes male no female no I like to count the yes responses and no responses genderwise. Like there are two females w...
How to Select Rows Based on Column Values in Pandas
I create a dataset like that, Gender response female yes male yes female yes female no male yes female no male yes male no female no I like to count the yes responses and no responses genderwise. Like there are two females who said No and 2 females who said yes. There are three ma...
[ "Please cross tabulate\npd.crosstab(df['Gender'], df['response']).reset_index()\n\n", "You can use value_counts with groupby method like this:\ndf.groupby('Gender')['response'].value_counts()\n\nResponse:\nGender response\nfemale no 3\n yes 2\nmale yes 3\n no 1...
[ 2, 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074243110_pandas_python.txt
Q: python streamlit run issue I'm trying to run streamlit application(python 3.7.3) after installing it shows that error streamlit hello File "<ipython-input-2-c7a1b683aa76>", line 1 streamlit hello ^ SyntaxError: invalid syntax A: A bit late, but here is the recommended setup for using...
python streamlit run issue
I'm trying to run streamlit application(python 3.7.3) after installing it shows that error streamlit hello File "<ipython-input-2-c7a1b683aa76>", line 1 streamlit hello ^ SyntaxError: invalid syntax
[ "A bit late, but here is the recommended setup for using on Windows: https://github.com/streamlit/streamlit/wiki/Installing-in-a-virtual-environment\n", "In windows\npy -m streamlit run hello.py\n\n", "Copy streamlit files in C:\\Users\\AppData\\Roaming\\Python\\Python36\\Scripts and paste them into your C:\\Pr...
[ 5, 4, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0060866205_python_streamlit.txt
Q: How can we confirm sleeping time in Loop Operation at Pytest? We'd like to confirm if the job was sure to wait during the loop operation as expected, in the Pytest. We set the sleep time as 30 sec in 3 times loop -- we expect and testify the total waiting time would be 90 sec in Pytest as below. -- Loop.py class L...
How can we confirm sleeping time in Loop Operation at Pytest?
We'd like to confirm if the job was sure to wait during the loop operation as expected, in the Pytest. We set the sleep time as 30 sec in 3 times loop -- we expect and testify the total waiting time would be 90 sec in Pytest as below. -- Loop.py class Loop def LoopJob(self, job_id, date, subject, fromDate, toD...
[ "You can mock the sleep method just like any other method, then you can assert the calls made to it.\nFor a simple example, if my module sleeping_beauty.py looks like this:\nimport time\n\n\ndef wait_for_my_hero():\n time.sleep(15)\n time.sleep(30)\n time.sleep(45)\n\nThe test would be (using pytest-mock):...
[ 1 ]
[]
[]
[ "mocking", "pytest", "python" ]
stackoverflow_0074237812_mocking_pytest_python.txt
Q: I want to make a calculator but i have TypeError how can i solve this How can i solve the TypeError I tried this: print("Multiplication Calculator for Kids") onenum = input("Enter a number") twonum = input("Enter a second number") calc = onenum * twonum print(calc) A: By default, the input value is a string. A...
I want to make a calculator but i have TypeError how can i solve this
How can i solve the TypeError I tried this: print("Multiplication Calculator for Kids") onenum = input("Enter a number") twonum = input("Enter a second number") calc = onenum * twonum print(calc)
[ "By default, the input value is a string. And you cannot perform operations on strings. You need to convert it to integer first.\nprint(\"Multiplication Calculator for Kids\")\n\nonenum = int(input(\"Enter a number\"))\ntwonum = int(input(\"Enter a second number\"))\ncalc = onenum * twonum\n\nprint(calc)\n\nOr you ...
[ 0, 0 ]
[]
[]
[ "python", "typeerror" ]
stackoverflow_0074243428_python_typeerror.txt
Q: serial in sys.version_info of python The sys.version_info output is ('major', 'minor', 'micro', 'releaselevel', 'serial'). I find that most of the explanations of this function outputs serial=0. I really don't understand what is this 'serial'? What does it mean? Why is it always 0? A: The .serial part of the nam...
serial in sys.version_info of python
The sys.version_info output is ('major', 'minor', 'micro', 'releaselevel', 'serial'). I find that most of the explanations of this function outputs serial=0. I really don't understand what is this 'serial'? What does it mean? Why is it always 0?
[ "The .serial part of the named tuple sys.version_info is always 0 for final releases, and when you download and install any version of Python from python.org, you're downloading final releases.\nHowever, alphas, betas and candidates can have different serials.\nSee also the documentation on API and ABI versioning o...
[ 1 ]
[]
[]
[ "python", "sys" ]
stackoverflow_0074243437_python_sys.txt
Q: Python class __str__ created and destroyed object How to use __str__ instead of #print? Here is the code: from itertools import count class Bug: _counter = 0 def __init__(self): Bug._counter += 1 self.id = Bug._counter #print("Obiekt stworzony:", self.id, self._counter) def __del__(self...
Python class __str__ created and destroyed object
How to use __str__ instead of #print? Here is the code: from itertools import count class Bug: _counter = 0 def __init__(self): Bug._counter += 1 self.id = Bug._counter #print("Obiekt stworzony:", self.id, self._counter) def __del__(self): Bug._counter -= 1 self.id = Bug._counte...
[ "If I understand the problem correctly then I would suggest this:\nclass Bug:\n _counter = 0 # number of Bug instances\n _ids = [] # list of reusable IDs\n\n def __init__(self):\n Bug._counter += 1 # increment number of Bug instances\n # reuse previously deleted ID if available otherwise use ...
[ 0 ]
[]
[]
[ "class", "python", "string" ]
stackoverflow_0074237289_class_python_string.txt
Q: Python 3.8 with Kora in Colab is not working anymore, how to fix? I did: !pip install kora import kora.install.py38 but got error: Requirement already satisfied: kora in /usr/local/lib/python3.7/dist-packages (0.9.19) Requirement already satisfied: ipython in /usr/local/lib/python3.7/dist-packages (from kora) (5....
Python 3.8 with Kora in Colab is not working anymore, how to fix?
I did: !pip install kora import kora.install.py38 but got error: Requirement already satisfied: kora in /usr/local/lib/python3.7/dist-packages (0.9.19) Requirement already satisfied: ipython in /usr/local/lib/python3.7/dist-packages (from kora) (5.5.0) Requirement already satisfied: fastcore in /usr/local/lib/python3....
[ "I'll fix it one day.\nFor now, you can use this notebook for Python 3.10\nhttps://colab.research.google.com/drive/12Uy1fTJy4XQDMdXVM_5XJ0iGEdCDOgYf\n" ]
[ 2 ]
[]
[]
[ "google_colaboratory", "kora", "python" ]
stackoverflow_0069487937_google_colaboratory_kora_python.txt
Q: No module named 'Kivy' even though I installed it I've installed Kivy and all the need files as far as I know, but I'm still getting this error message and I don't know why. from kivy.app import App from kivy.uix.gridlayout import GridLayout class Container(GridLayout): pass class MainApp(App): def buil...
No module named 'Kivy' even though I installed it
I've installed Kivy and all the need files as far as I know, but I'm still getting this error message and I don't know why. from kivy.app import App from kivy.uix.gridlayout import GridLayout class Container(GridLayout): pass class MainApp(App): def build(self): self.title = 'Awesome app!!!' ...
[ "Check if in current enviroment you have kivy installed:\nimport pip._internal as pip\n\nprint([i.key for i in pip.get_installed_distributions()]\n# or \npip.main(['freeze'])\n\nSo you will see if in this enviroment you have kivy installed.\nTo make sure you have kivy installed in this enviroment you can write some...
[ 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "importerror", "kivy", "python" ]
stackoverflow_0053686801_importerror_kivy_python.txt
Q: How to find the index of a queryset after the database is sorted in Django I am making a leaderboard for my quiz. I made this model: class LeaderBoard(models.Model): name = models.CharField(max_length=200) score = models.DecimalField(max_digits=4, decimal_places=2) This is my code for getting a queryset l...
How to find the index of a queryset after the database is sorted in Django
I am making a leaderboard for my quiz. I made this model: class LeaderBoard(models.Model): name = models.CharField(max_length=200) score = models.DecimalField(max_digits=4, decimal_places=2) This is my code for getting a queryset leaderboad_place = leaderboard.order_by("score").get(name=request.user.username)...
[ "You can make some trick:\n#user is name of field which is refered for User Model\n\nleaderboad_places = list(LeaderBoard.objects.all().order_by('-score').values_list('user', flat=True)) \nleaderboad_places.index(request.user)\n\n" ]
[ 1 ]
[]
[]
[ "database", "django", "django_views", "python" ]
stackoverflow_0074243330_database_django_django_views_python.txt
Q: A python program to take input and sqaure it using lambda function shows None as result. What am I doing wrong? print("Problem Statement: Accept a parameter and return its square") print() squareX = lambda num : num * num def sq(squareX, num): result = squareX(num) def main(): print("Please enter the nu...
A python program to take input and sqaure it using lambda function shows None as result. What am I doing wrong?
print("Problem Statement: Accept a parameter and return its square") print() squareX = lambda num : num * num def sq(squareX, num): result = squareX(num) def main(): print("Please enter the number to find its square:") value = int(input()) print() Ans = sq(squareX, value) print("The square ...
[ "You forgot the return statement in sq. So the correct code is:\nprint(\"Problem Statement: Accept a parameter and return its square\")\nprint()\n\nsquareX = lambda num : num * num\n\ndef sq(squareX, num):\n result = squareX(num)\n return result\n\ndef main():\n print(\"Please enter the number to find its ...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074243538_python_python_3.x.txt
Q: Raspberry pi Flask CSS does not work I Don't Know Why Hi i am trying to host a server my raspberry pi with flask but css does not work. It shows plain html. when i try the same thing with same file names, location and same code it works but from my raspberry pi it does not work? To Fix I Tried (so don't bother say...
Raspberry pi Flask CSS does not work I Don't Know Why
Hi i am trying to host a server my raspberry pi with flask but css does not work. It shows plain html. when i try the same thing with same file names, location and same code it works but from my raspberry pi it does not work? To Fix I Tried (so don't bother saying): Tried using static or normal way Tried doing cmd+shi...
[ "turns out i have made a typo i didnt notice it for hours my looked like this\n<link rel=\"stylesheet\" href=\"\"{{ url_for('static', filename='styles.css') }}>\n\n" ]
[ 0 ]
[ "This is how it works:\n<!DOCTYPE html>\n<html>\n <head>\n <title>THD</title>\n <link rel= \"stylesheet\" type= \"text/css\" href= \"static/styles.css\">\n </head>\n<html>\n\nYou have to call the relative path to the css file\n", "Do this:\n<link rel=\"stylesheet\" href=\"../static/styles.css/...
[ -1, -1 ]
[ "flask", "python" ]
stackoverflow_0074235039_flask_python.txt
Q: How to get while loop to get updated in python I am using a while loop in python in a project and it's not getting any updates and I have to turn it off and on again. Is there a way to make it update? Here's the code: import imaplib username ="example@gmail.com" app_password= "example" gmail_host= 'imap.gmail.com'...
How to get while loop to get updated in python
I am using a while loop in python in a project and it's not getting any updates and I have to turn it off and on again. Is there a way to make it update? Here's the code: import imaplib username ="example@gmail.com" app_password= "example" gmail_host= 'imap.gmail.com' mail = imaplib.IMAP4_SSL(gmail_host) mail.login(use...
[ "I found the answer\nimport imaplib\nusername =\"example@gmail.com\"\napp_password= \"example\"\ngmail_host= 'imap.gmail.com'\nmail = imaplib.IMAP4_SSL(gmail_host)\nmail.login(username, app_password)\nwhile True:\n mail.select()\n _, selected_mails = mail.search(None, 'ALL')\n print({len(selected_mails[0]....
[ 2, 1 ]
[]
[]
[ "gmail", "gmail_imap", "imap", "imaplib", "python" ]
stackoverflow_0074235956_gmail_gmail_imap_imap_imaplib_python.txt
Q: How do I use regex within a certain cell in a csv to edit? I have a CSV with a structure as: Test CSV: Column A Column B abc-dfcv rebtgsergbsedrfgesrg water rdfe egreg oluiuilegregreg def fefd rtjtyujdtgfhndgfhjfh water edgregerg Result needed: Column A Column B abc-dfcv water rdfe egreg def fefd w...
How do I use regex within a certain cell in a csv to edit?
I have a CSV with a structure as: Test CSV: Column A Column B abc-dfcv rebtgsergbsedrfgesrg water rdfe egreg oluiuilegregreg def fefd rtjtyujdtgfhndgfhjfh water edgregerg Result needed: Column A Column B abc-dfcv water rdfe egreg def fefd water edgregerg As can be ...
[ "you can use the function 'startswith' instead of regex and the answer would like this:\nresult = df[df[\"Column B\"].str.startswith(\"water\")]\n\n", "You can do it like this:\ndf = pd.read_csv('MyFile.csv')\ndf_new = df.loc[df['Column B'].str.contains(r'\\bwater', case=False)]\n\n" ]
[ 0, 0 ]
[]
[]
[ "csv", "pandas", "python", "regex" ]
stackoverflow_0074242190_csv_pandas_python_regex.txt
Q: VSCode fail to debug Cython wrapped CUDA code (but CLI cuda-gdb can) Background: Running VSCode on Ubuntu 20.04 The following have been accomplished: (a) Compiled and build the Cython wrapper for CUDA code (packaged as shared library .so); (b) Python script importing said .so file runs, and can be debugged directl...
VSCode fail to debug Cython wrapped CUDA code (but CLI cuda-gdb can)
Background: Running VSCode on Ubuntu 20.04 The following have been accomplished: (a) Compiled and build the Cython wrapper for CUDA code (packaged as shared library .so); (b) Python script importing said .so file runs, and can be debugged directly from cuda-gdb in terminal (thanks to this link as well as enabling the p...
[ "Make sure to compile cu file with debug symbol info.\nTry using -G -g -O0 flag\n" ]
[ 0 ]
[]
[]
[ "cuda_gdb", "cython", "nsight", "python", "vscode_debugger" ]
stackoverflow_0072825357_cuda_gdb_cython_nsight_python_vscode_debugger.txt
Q: How to print all inputs into one array and format into currency] I wrote the following code: total_sum = 0 counter = 1 for n in range(6): numbers = float(input('Enter Bill #' + str(counter) + ': ')) total_sum += float(numbers) counter += 1 Assuming I inputted six floats [1,2,3,4,5, 6], how can I prin...
How to print all inputs into one array and format into currency]
I wrote the following code: total_sum = 0 counter = 1 for n in range(6): numbers = float(input('Enter Bill #' + str(counter) + ': ')) total_sum += float(numbers) counter += 1 Assuming I inputted six floats [1,2,3,4,5, 6], how can I print the six inputs such that it will print the following: [$1, $2, $3, ...
[ "After each input, you are adding the values to the sum variable. At the end of the loop you only have the total of the values you entered. To retain these values, you must store them in a collection like a list as you input them. After each input, you add it to the list using list.append():\ntotal_sum = 0\ncounter...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074243550_python.txt
Q: How to group two dictionary items into one list entry from another? l1 = [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}, {'_id': 2, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}] l2 = [{'g_id'...
How to group two dictionary items into one list entry from another?
l1 = [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}, {'_id': 2, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}] l2 = [{'g_id': 0, 'type': 'group1', 'name': 'first',}, {'g_id': 1, 'type': 'grou...
[ "if you are using Python >= 3.9, you can use dict concatenation (assuming that len(l1) is two times len(l2)):\n[grp | {'group': grp_ids}\n for grp, grp_ids in zip(l2, [l1[i*2:(i+1)*2] for i in range(len(l2))])]\n\nThe result is:\n[{'g_id': 0, 'type': 'group1', 'name': 'first', 'group': [{'_id': 0, 'type': 'int', 'n...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x" ]
stackoverflow_0074243291_dictionary_list_python_python_3.x.txt
Q: python wrap text and reportlab I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab: This is how I try: text = '*long_text_long_text_long_text_long_text*' text = "\n".join(wrap(text, 10)) canvas.drawString(5,227, text) My pdf was created ...
python wrap text and reportlab
I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab: This is how I try: text = '*long_text_long_text_long_text_long_text*' text = "\n".join(wrap(text, 10)) canvas.drawString(5,227, text) My pdf was created but where I want to break the lines ...
[ "drawString draws a single line. so you will need to adjust the coordinate for each line in a loop.\ny = 227\nfor line in wrap(text, 10):\n canvas.drawString(5, y, line)\n y += 15\n\n", "An alternative to placing each line individually is using Paragraph:\nfrom reportlab.lib.styles import getSampleStyleShee...
[ 1, 0 ]
[]
[]
[ "python", "reportlab", "word_wrap" ]
stackoverflow_0043119284_python_reportlab_word_wrap.txt
Q: How to create a new column and save to csv after rate limit is encountered? I am trying to get the followers count of a list of users and save it to csv. Here's how my code looks like. import requests from bs4 import BeautifulSoup from time import sleep def getFollowerCount(Username): url = 'https://somewebsit...
How to create a new column and save to csv after rate limit is encountered?
I am trying to get the followers count of a list of users and save it to csv. Here's how my code looks like. import requests from bs4 import BeautifulSoup from time import sleep def getFollowerCount(Username): url = 'https://somewebsite.com'+ Username r = requests.get(url) if r.status_code == 429: ...
[ "Try using try except block inside the function and see if it works:\ndef getFollowerCount(Username):\n url = 'https://somewebsite.com'+ Username\n r = requests.get(url)\n try:\n if r.status_code == 429:\n time.sleep(1)\n \n else:\n # do something to return the ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "web_scraping" ]
stackoverflow_0074243676_dataframe_pandas_python_web_scraping.txt
Q: How to properly use By class in selenium with python I've written a code to test a page in python with selenium. The code works but now I'm trying to rewrite it better. I have created a locators.py file as described in the following documentation: selenium python binding - page objects. For simple locators this is...
How to properly use By class in selenium with python
I've written a code to test a page in python with selenium. The code works but now I'm trying to rewrite it better. I have created a locators.py file as described in the following documentation: selenium python binding - page objects. For simple locators this is straightforward. This is what I've done so far: from sele...
[ "You should be able to arrange the line you are asking about as follows:\nsomeName = driver.find_element_by_class_name('coverUpload')\nButtonName = someName.find_element_by_class_name('pButton')\nButtonName.click()\n\n", "instead of 2 class search maybe you can use relative Xpath if That element is unique.\nelem ...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0038943688_python_selenium.txt
Q: Pandas DataFrame: how to calculate how many times certain rows had the same column values? Given above dataset, I have to calculate how many times product_no 813 and 811 have the same order_id. For example, in the first three rows, all have the same order_id and 813 and 811 have the same order_id only once(do not ...
Pandas DataFrame: how to calculate how many times certain rows had the same column values?
Given above dataset, I have to calculate how many times product_no 813 and 811 have the same order_id. For example, in the first three rows, all have the same order_id and 813 and 811 have the same order_id only once(do not consider duplicates of 811). Actually, I have to do it for every product and produce some matri...
[ "You could use groupby :\ndf_group=groupby(by=\"product_no\")\n\nAnd\ndf_group.ngroups\n\nwill give you the total count\nYou can iter over every grouped dataframe (using groups attribute for instance) to perform a new groupby(by=\"order_id\").\nMake a list\nL=[product_no ,{order_id: len(df)}]\nIter over it the same...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074243023_pandas_python.txt
Q: Is it possible to use Python 3.10 in Google Colab? I would like to use the Structural Pattern Matching feature from Python 3.10 in Google Colab so using the commands !sudo apt-get install python3.10 !sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1 !sudo update-alternatives --set p...
Is it possible to use Python 3.10 in Google Colab?
I would like to use the Structural Pattern Matching feature from Python 3.10 in Google Colab so using the commands !sudo apt-get install python3.10 !sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1 !sudo update-alternatives --set python3 /usr/bin/python3.10 I was able to make !python -...
[ "You can use this notebook.\n\nmake a copy of it\nrun the first cell\nreload (Ctrl + R, or Cmd + R)\nrun the second cell\n\nSee this video demo by 1littlecoder.\n" ]
[ 4 ]
[ "You can try these commands:\n!update-alternatives --install /usr/bin/python python /usr/bin/python3.10\n\nthen\n!update-alternatives --list python\n\nThis must display your downloaded Python version.\nAfter that,\n!sudo update-alternatives --config python\n## !Set python3.10 as default.\n\nFinally,\n!sudo update-a...
[ -4 ]
[ "google_colaboratory", "python", "python_3.x" ]
stackoverflow_0070141277_google_colaboratory_python_python_3.x.txt
Q: My list gets suddenly empty and I can't restore it I'm newbie in django and I was trying to construct a site in which the user can take a quiz. In a simpler version of that, I wanted just the questions to be displayed in random order, one after another(when the user presses a button) and when all the questions hav...
My list gets suddenly empty and I can't restore it
I'm newbie in django and I was trying to construct a site in which the user can take a quiz. In a simpler version of that, I wanted just the questions to be displayed in random order, one after another(when the user presses a button) and when all the questions have been displayed to return to the main page, where there...
[ "The problem with your approach is that HTTP is stateless. Each request should have all the information required for the server to handle it. In other words the server should absolutely not keep any state. In your case, the questions list represents a state.\nMore details about HTTP and its statelessness:\nWhy is i...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074243741_django_python.txt
Q: Range as dictionary key in Python So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary. I wrote the code bellow, but I cannot get it to work. Is it even possible? stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ...
Range as dictionary key in Python
So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary. I wrote the code bellow, but I cannot get it to work. Is it even possible? stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not working. stealth_check =...
[ "It is possible on Python 3 — and on Python 2 if you use xrange instead of range:\nstealth_check = {\n xrange(1, 6) : 'You are about as stealthy as thunderstorm.', #...\n }\n\nHowever, the way you're trying to use it it won't work. You could iterate over the keys, like this:\nfor key i...
[ 39, 15, 12, 9, 5, 3, 3, 2, 1, 0 ]
[ "Thank you everyone for your responses. I kept hacking away, and I came up with a solution that will suit my purposes quite well. It is most similar to the suggestions of @PaulCornelius.\nstealth_roll = randint(1, 20)\n# select from a dictionary of 4 responses using one of four ranges.\n# only one resolution can be...
[ -1 ]
[ "dictionary", "python", "range" ]
stackoverflow_0039358092_dictionary_python_range.txt
Q: Why is Colab still running Python 3.7? I saw on this tweet that Google Colab move to Python 3.7 on February 2021. As of today however (January 2022), Python 3.10 is out, but Colab still runs Python 3.7. My (voluntarily) naive take is that this is quite a significant lag. Why are they not at least on Python 3.8 or ...
Why is Colab still running Python 3.7?
I saw on this tweet that Google Colab move to Python 3.7 on February 2021. As of today however (January 2022), Python 3.10 is out, but Colab still runs Python 3.7. My (voluntarily) naive take is that this is quite a significant lag. Why are they not at least on Python 3.8 or even 3.9? Is it simply to make sure that som...
[ "The only reason is they want to have the most compatible version of Python worldwide. Based on the Python Readiness report (Python 3.7 Readiness), version 3.7 supports almost 80.6% of the most used packages so far. Still, this coverage is 78.3% for version 3.8, 70.6% for version 3.9 and 49.7% for version 3.10 (as ...
[ 6, 0 ]
[]
[]
[ "compatibility", "google_colaboratory", "python", "python_3.x" ]
stackoverflow_0070714622_compatibility_google_colaboratory_python_python_3.x.txt
Q: ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic' I have this output : [Pandas-profiling] ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic' when trying to import pandas-profiling in this fashion : from pandas_profiling import ProfileReport It seems...
ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic'
I have this output : [Pandas-profiling] ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic' when trying to import pandas-profiling in this fashion : from pandas_profiling import ProfileReport It seems to import pandas-profiling correctly but struggles when it comes to interfacing with p...
[ "Thanks to the @aflyingtoaster's answer, the following workaround has worked fine for me:\n\nEdit the file \"~/[your_conda_env_path]/lib/site-packages/visions/dtypes/boolean.py\"\nFind the row \"from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries\" and just replace ABCIndexClass for ABCIndex.\nSave the ...
[ 22, 19, 2, 1, 0, 0, 0, 0 ]
[ "Just installed the \"visions\" package and it fixed for me.\npip install visions\n" ]
[ -1 ]
[ "pandas", "pandas_profiling", "python" ]
stackoverflow_0068704002_pandas_pandas_profiling_python.txt
Q: Django Advanced Filtering for a Queryset that can have many related foreign keys I am trying to sort a query in django on a model that can have multiple foreign keys. I only want the filtering to apply to one of those keys and I am having a hard time getting it to work. models.py class Post(models.Model): con...
Django Advanced Filtering for a Queryset that can have many related foreign keys
I am trying to sort a query in django on a model that can have multiple foreign keys. I only want the filtering to apply to one of those keys and I am having a hard time getting it to work. models.py class Post(models.Model): content = models.TextField(max_length=1000) reaction_counts = GenericRelation(Reactio...
[ "I'm not sure to understand what is the order you want so here are some examples.\nI'm you want posts with the most likes\nPost.objects.filter(reaction_count__type=ReactionCount.ReactionType.LIKE.value).order_by(\"-reaction_count__count\")\n\nIf you want the post with the most reactions\nPost.objects.alias(reaction...
[ 1 ]
[]
[]
[ "django", "filtering", "foreign_keys", "python", "sql_order_by" ]
stackoverflow_0074243030_django_filtering_foreign_keys_python_sql_order_by.txt
Q: Query in Django to sort in one table based on result of another table I have two models listing model is: class listing(models.Model): productTitle= models.CharField(max_length=60) description = models.TextField() category = models.ForeignKey(category,on_delete=models.CASCADE,null=True) productPric...
Query in Django to sort in one table based on result of another table
I have two models listing model is: class listing(models.Model): productTitle= models.CharField(max_length=60) description = models.TextField() category = models.ForeignKey(category,on_delete=models.CASCADE,null=True) productPrice = models.FloatField(default=0.0) def __str__(self): retu...
[ "You could have probably do something like this\nwatch_list = watchlist.objects.filter(wishlist=False, user=request.user.id).values('item')\n\nThen if you want to fetch items, you do like this\nitems = listing.objects.filter(id__in=watch_list)\n\n", "from django.db.models import Q \nitems = listing.objects.fil...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074242370_django_python.txt
Q: Low Speed Connection for VS Code servers to download extensions Two days ago, I installed Ubuntu and deleted windows, then I installed VS Code from Snap Store, now I have a problem with VS Code servers to download extensions. I'm from Iran and we have a low-speed connection, because of it, I get errors for a low c...
Low Speed Connection for VS Code servers to download extensions
Two days ago, I installed Ubuntu and deleted windows, then I installed VS Code from Snap Store, now I have a problem with VS Code servers to download extensions. I'm from Iran and we have a low-speed connection, because of it, I get errors for a low connection. Is there a way to install extensions for VS Code? any help...
[ "you can download extensions as a .vsix file.\nGo VS marketplace and download your extensions on your ubuntu server (or other devices, and copy to your ubuntu using disks like usb).\nAnd VScode extension tab -> meatball menu(...) -> Click 'Install from VSIX' tab and select vsix path.\nAlso you can install directly ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074243288_django_python.txt
Q: Cutting a matrix for a certain complex shape - Python I ran into a problem that I don't know how to address, if anyone has any ideas I would be very grateful. So I have a NxM matrix and number of points (minimum 4) that represent a shape resting on the matrix as show in the figure (Each point is represented by a n...
Cutting a matrix for a certain complex shape - Python
I ran into a problem that I don't know how to address, if anyone has any ideas I would be very grateful. So I have a NxM matrix and number of points (minimum 4) that represent a shape resting on the matrix as show in the figure (Each point is represented by a number, ignore the black/white points): I know how to match...
[ "You need to use a polygon filling algorithm (also called scan conversion). In a nutshell, you intersect the polygon with all horizontals through the matrix rows and find intervals covered by the inside of the polygon. Accumulate the matrix values spanned by these intervals.\n" ]
[ 0 ]
[]
[]
[ "polygon", "python", "shapes", "slice" ]
stackoverflow_0074243887_polygon_python_shapes_slice.txt
Q: Python date converstion to quarters giving integer not Q1YYYY I've having issues with converting dates as the output isn't giving me '2022Q4' but rather an integer 211. Tried a few different ways and just stuck! Tried using the index, formatting the index and then two ways i know of but can't get the result. Code...
Python date converstion to quarters giving integer not Q1YYYY
I've having issues with converting dates as the output isn't giving me '2022Q4' but rather an integer 211. Tried a few different ways and just stuck! Tried using the index, formatting the index and then two ways i know of but can't get the result. Code: df.index = pd.to_datetime(df.index) df['Date'] = ...
[ "According to the documentation you could use to_period do convert datetime data to period.\nhttps://pandas.pydata.org/docs/reference/api/pandas.DatetimeIndex.to_period.html\n" ]
[ 0 ]
[]
[]
[ "date", "python", "time_series" ]
stackoverflow_0074243778_date_python_time_series.txt
Q: How do I have nested find_all statements in BeautifulSoup (Python)? I started off by pulling the page with Selenium and I believe I passed the part of the page I needed to BeautifulSoup correctly using this code: soup = BeautifulSoup(driver.find_element("xpath", '//*[@id="version_table"]/tbody').get_attribute('out...
How do I have nested find_all statements in BeautifulSoup (Python)?
I started off by pulling the page with Selenium and I believe I passed the part of the page I needed to BeautifulSoup correctly using this code: soup = BeautifulSoup(driver.find_element("xpath", '//*[@id="version_table"]/tbody').get_attribute('outerHTML')) Now I can parse using BeautifulSoup query = soup.find_all("tr...
[ "As mentioned without any example it is hard to help or give a precise answer - However you could use a css selector:\nsoup.select('tr[id^=\"version_new_\"]:not(.hidden)')\n\nExample\nfrom bs4 import BeautifulSoup\n\nhtml = '''\n<tr id=\"version_new_1\" class=\"hidden\"></tr>\n<tr id=\"version_new_2\"></tr>\n<tr id...
[ 2, 1, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074241644_beautifulsoup_python.txt
Q: Accessing message contents of an android phone using Python Here's what I want to do. I have a Samsung galaxy phone whose message box is full. I want to download all the SMS messages from the mobile phone to my computer the Pythonic way. Before I decided to pose this question, I did a quick research on the interne...
Accessing message contents of an android phone using Python
Here's what I want to do. I have a Samsung galaxy phone whose message box is full. I want to download all the SMS messages from the mobile phone to my computer the Pythonic way. Before I decided to pose this question, I did a quick research on the internet, SO for possible answers. I hit this lead and this lead here o...
[ "To access messages on an Android phone directly, you'll need to read the \"mmssms.db\" file. This is located at data/data/com.android.providers.telephony/databases/mmssms.db, and is an SQLite database. However, this requires root to read. If you have root, use the SMS-tools library here.\nIf you don't have root ac...
[ 2, 2, 0 ]
[]
[]
[ "android", "python", "samsung_mobile" ]
stackoverflow_0037249982_android_python_samsung_mobile.txt
Q: How to get output of OS command from Jupyter notebook? I am running Jupyter notebook on a server (python 3). Want to see output of OS command (any OS command - this is just example): output = os.system("pwd") When I do print of it: print (output) Response is 0. How to get a simple output (like in CLI)? Thanks. ...
How to get output of OS command from Jupyter notebook?
I am running Jupyter notebook on a server (python 3). Want to see output of OS command (any OS command - this is just example): output = os.system("pwd") When I do print of it: print (output) Response is 0. How to get a simple output (like in CLI)? Thanks.
[ "Just found it on internet and wanted to post.\nIt needs to be:\nprint(os.popen('ls').read())\n(or any other OS command).\nThis works fine.\n", "import os\n\nprint(os.getcwd())\nprint(os.system(\"pwd\"))\n\nBut this question is a duplicate:\nhow to show current directory in ipython promp\n", "Note that os.syste...
[ 7, 3, 0 ]
[]
[]
[ "jupyter", "linux", "operating_system", "python" ]
stackoverflow_0056078935_jupyter_linux_operating_system_python.txt
Q: turtle.listen() doesn't response after opening turtle input box from Tkinter button I want to draw my turtle using arrow keys. And there's an option to change turtle pensize. Here's my code: from tkinter import * from turtle import * def ask(): someinputs = numinput('Test', 'Input size:', default=1, minval=0,...
turtle.listen() doesn't response after opening turtle input box from Tkinter button
I want to draw my turtle using arrow keys. And there's an option to change turtle pensize. Here's my code: from tkinter import * from turtle import * def ask(): someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999) pensize(someinputs) root = Tk() Label(root, text='Settings:\n').pack()...
[ "When you use the settings window, you take focus from the turtle window. The key events will only work when the turtle window has focus. Adapting this answer it is possible to get the underlying canvas and focus it by adding Screen().getcanvas().focus_force() to the end of ask:\ndef ask():\n someinputs = numinp...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x", "tkinter", "turtle_graphics" ]
stackoverflow_0073111545_python_python_3.x_tkinter_turtle_graphics.txt
Q: import "dotenv" could not be resolved I am making a program in python that I plan to host on github. I have a .env file containing an api token. I tried to import it into my code like so: first i installed the python-dotenv library by typing pip install python-dotenv in the command prompt. python-dotenv shows when...
import "dotenv" could not be resolved
I am making a program in python that I plan to host on github. I have a .env file containing an api token. I tried to import it into my code like so: first i installed the python-dotenv library by typing pip install python-dotenv in the command prompt. python-dotenv shows when i type pip list. then in my code: import o...
[ "It seems you have installed python-env, when you really wanted to install python-dotenv. The former doesn't have the function you are trying to use on it's __init__.py file, that's why Pylancereport can't resolve it.\nSolution:\nDo a pip install python-dotenv. Execute your code again and it should work.\n" ]
[ 4 ]
[ "The only thing that helped me was the complete removal of the virtual environment, creating a new one and installing requirements.txt (of course with python-dotenv inside)\n" ]
[ -1 ]
[ "python", "python_dotenv" ]
stackoverflow_0070690682_python_python_dotenv.txt
Q: Bybit API Python Invalid API key Hi I was trying to create a Bybit Trading bot and when I started testing it it stopped working and it keeps throwing the same error(10003) Invalid api key. I have checked it several times and it was correct. Do you know what can be the reason for that? A: While generating the API...
Bybit API Python Invalid API key
Hi I was trying to create a Bybit Trading bot and when I started testing it it stopped working and it keeps throwing the same error(10003) Invalid api key. I have checked it several times and it was correct. Do you know what can be the reason for that?
[ "While generating the API key, there is an option at the bottom for whitelisted IP addresses which would be allowed to access the server with the generated API keys. It is possible that you might not have whitelisted your IP address.\n", "For anyone wondering,\nYou just have to use the 'https://api.bybit.com' end...
[ 0, 0 ]
[]
[]
[ "api", "bybit", "pycrypto", "python" ]
stackoverflow_0071451240_api_bybit_pycrypto_python.txt
Q: Django Queryset with annotate I am writing one method in Django Manager model. I want to write method that finds out number of all sold copies (books) per author. I have two models and method written in Manager. My problem is that method should also be chainable from any Author queryset, for example something like...
Django Queryset with annotate
I am writing one method in Django Manager model. I want to write method that finds out number of all sold copies (books) per author. I have two models and method written in Manager. My problem is that method should also be chainable from any Author queryset, for example something like Author.objects.filter(...).exlucde...
[ "You need to use Manager.from_queryset to set your manager. Here are the docs.\nclass AuthorQueryset(models.QuerySet):\n def total_copies_sold(self):\n ...\n\nclass Author(models.Model):\n objects = models.Manager.from_queryset(AuthorQueryset)()\n\n", "What you are lookig for is :\nfrom django.db imp...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "database", "django", "django_annotate", "python" ]
stackoverflow_0059954022_database_django_django_annotate_python.txt
Q: While loops - Can I combine the these loops to create more efficient code? I am working on a basic program to sharpen my skills. I made a program that creates a pin then attempts to crack it. It functions as desired but I'm curious if the last three while loops can be combined into one more efficient loop. import ...
While loops - Can I combine the these loops to create more efficient code?
I am working on a basic program to sharpen my skills. I made a program that creates a pin then attempts to crack it. It functions as desired but I'm curious if the last three while loops can be combined into one more efficient loop. import random pin = [] pinlength = 0 while pinlength != 3: num = random.randint(1...
[ "Using functions and list comprehensions will make your code clearer and more reusable:\nimport random\n\ndef generate_pin(s: int): \n return [random.randint(0,9) for _ in range(s)]\n\ndef get_ith_digit(pin, ix):\n for n in range(10):\n if n == pin[ix]:\n return n\n\npin = generate_pin(3)\np...
[ 1 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074243109_loops_python.txt
Q: username=self.kwargs.get('username') returning Not Found: / Hi I am trying to set the show the items the is only related to a specific user who is currently logged in. I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getti...
username=self.kwargs.get('username') returning Not Found: /
Hi I am trying to set the show the items the is only related to a specific user who is currently logged in. I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getting an error of Not Found: / I am not sure why? Here is the models...
[ "Are you sure the not found error is raised from inside your view? Maybe you somehow misplaced the URLs and the request can't find the URL. Are you sure that your request reaches the view? You can verify this using a simple print. If not, make sure you've included your urls in the root urls file.\n" ]
[ 0 ]
[ "Since self.kwargs is a key value pair, you need to access the val by\nself.kwargs[f'username'] #f string if it is a variable which it should be.\nNot\nself.kwargs.get('username')\n\n" ]
[ -2 ]
[ "django", "django_views", "python" ]
stackoverflow_0074242639_django_django_views_python.txt
Q: ArgumentError 'SchemaItem' object, such as a 'Column' or a 'Constraint' expected An error occurs while trying to create a database Text of the error: Traceback (most recent call last): File "C:\Users\Alex\Desktop\AlNews\env\lib\site-packages\sqlalchemy\sql\schema.py", line 108, in _init_items spw...
ArgumentError 'SchemaItem' object, such as a 'Column' or a 'Constraint' expected
An error occurs while trying to create a database Text of the error: Traceback (most recent call last): File "C:\Users\Alex\Desktop\AlNews\env\lib\site-packages\sqlalchemy\sql\schema.py", line 108, in _init_items spwd = item._set_parent_with_dispatch AttributeError: 'function' object has no attrib...
[ "As Simon Crane observes in their comment, the problem here is a simple typo: a column has been defined using the function db.text like this:\nclass News(db.Model):\n ...\n title = db.Column(db.text, nullable=False)\n url = db.Column(db.text, unique=True, nullable=False)\n ...\n\nbut it should have been...
[ 1, 0 ]
[ "Just change the db.text to db.String()\n" ]
[ -1 ]
[ "flask_sqlalchemy", "python", "python_3.x", "sqlalchemy" ]
stackoverflow_0059522705_flask_sqlalchemy_python_python_3.x_sqlalchemy.txt
Q: Can I create an Enum of a dataclass instances? I have a fixed set of three sensors that I want to model as an enum. Each of these sensors is parametrised by a few different attributes. I therefore want to model the sensors themselves as a dataclass. My naive attempt looks something like this: @dataclass class Se...
Can I create an Enum of a dataclass instances?
I have a fixed set of three sensors that I want to model as an enum. Each of these sensors is parametrised by a few different attributes. I therefore want to model the sensors themselves as a dataclass. My naive attempt looks something like this: @dataclass class SensorLocation: address: int pins: int oth...
[ "I think you can try using a custom __init__ function for your Enum:\nfrom dataclasses import dataclass\nfrom enum import Enum\n\n\n@dataclass\nclass SensorLocation:\n address: int\n pins: int\n other_details: dict\n\n\nclass Sensors(SensorLocation, Enum):\n TOP_SENSOR = SensorLocation(address=0x10, pin...
[ 0 ]
[]
[]
[ "enums", "python", "python_dataclasses" ]
stackoverflow_0070924277_enums_python_python_dataclasses.txt
Q: AttributeError: 'WindowsPath' object has no attribute 'rpartition' when setting directory After typing STATIC_ROOT = BASE_DIR / "staticfiles" in settings.py I get the error in the tittle. I tried with STATICDIR but it still doesn't work. I am pretty new to django so I don't really know other ways to fix it. EDIT:...
AttributeError: 'WindowsPath' object has no attribute 'rpartition' when setting directory
After typing STATIC_ROOT = BASE_DIR / "staticfiles" in settings.py I get the error in the tittle. I tried with STATICDIR but it still doesn't work. I am pretty new to django so I don't really know other ways to fix it. EDIT: turns out I tried to install the template folder in the INSTALLED APPs thingy
[ "Simply you can try following way:\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]\n\nAnd in your template, load the static using following tag:\n{% load static %}\n\n", "STATIC_ROOT (and all other path-related options) must be a string, not a Path.\nCast it in the assignment:\nS...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074243956_django_python.txt
Q: How to get a 100 Images from google images I'm trying to scrape Google to get some pictures (like a 100 maybe)from a list (list_name). But my code returns only 20 and I can't figure why. Here is my code: import os import requests from bs4 import BeautifulSoup liste_name = ['blood orange','apple golden'] for name...
How to get a 100 Images from google images
I'm trying to scrape Google to get some pictures (like a 100 maybe)from a list (list_name). But my code returns only 20 and I can't figure why. Here is my code: import os import requests from bs4 import BeautifulSoup liste_name = ['blood orange','apple golden'] for name in liste_name: name_splited = name.split(" ") i...
[ "google API block you to maximum 20 images\nsee here for more details\n", "You can use selenium or playwright to get absolutely all images. Also, you can use the \"ijn\" URL parameter that defines the page number to get e.g 0 is the first page, 1 is the second, and so on. The parameter should be greater than or e...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0055693714_beautifulsoup_python.txt
Q: OpenCV object detecting and save videofile I want to object detect and save the video, but the video saved only 6kb or 0kb and it can't be play If there is no this line x, y, width, height, area = stats[index] it will be saved Do you know why And is there a solution? import cv2 import time import numpy as np cap...
OpenCV object detecting and save videofile
I want to object detect and save the video, but the video saved only 6kb or 0kb and it can't be play If there is no this line x, y, width, height, area = stats[index] it will be saved Do you know why And is there a solution? import cv2 import time import numpy as np cap = cv2.VideoCapture("rtsp://admin:admin@128.1.1....
[ "I think this will solve your problem\n# importing the module \nimport cv2 \nimport numpy as np\n \n# reading the vedio \nsource = cv2.VideoCapture(0) // add your URL insed of \"0\"\n\n# We need to set resolutions. \n# so, convert them from float to integer. \nframe_width = int(source.get(3)) \nframe_height = int...
[ 1, 0 ]
[]
[]
[ "opencv", "opencv_python", "python" ]
stackoverflow_0064798125_opencv_opencv_python_python.txt
Q: how do i send a random screenshot through my discord bot a few years ago i found this website that lets you see random screenshots people took, and i wanna make that a command in my discord bot and it works but the images dont show up in discord. heres what i have so far if message.content.startswith(prefix + "rss...
how do i send a random screenshot through my discord bot
a few years ago i found this website that lets you see random screenshots people took, and i wanna make that a command in my discord bot and it works but the images dont show up in discord. heres what i have so far if message.content.startswith(prefix + "rss"): rss = ''.join(random.choices(string.ascii_lowercas...
[ "prnt.sc format is (iirc) 2 letters, 4 numbers.\nThe image you view on the page is hardcoded in the page in b64, so the URL to image you're trying to embed is not an image. If you're wanting a URL to the image, I was able to find it in the <head> section in the og:image meta tag\n\nTo get a URL to the image, make a...
[ 1 ]
[]
[]
[ "bots", "discord", "discord.py", "python", "replit" ]
stackoverflow_0074202655_bots_discord_discord.py_python_replit.txt
Q: How can i add the gender column? I have this dataset with 5 columns and lots of rows. I've been asked to get the total number of male and females. They are string and can't figure it out. I have to use numpy too. Please help. Thanks ls = gender.values.tolist() ls top = [] for i in ls: if i == 'M': top....
How can i add the gender column?
I have this dataset with 5 columns and lots of rows. I've been asked to get the total number of male and females. They are string and can't figure it out. I have to use numpy too. Please help. Thanks ls = gender.values.tolist() ls top = [] for i in ls: if i == 'M': top.append(i) print(i) I need to ...
[ "You can use value_counts from pandas to see total number of occurrences of a categorical column.\nIn your case, it can be\ndf['gender'].value_counts()\n\nIT will return the count of male and female.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "string", "using" ]
stackoverflow_0074243049_numpy_python_string_using.txt
Q: how can i install gym[box2d] despite errors below? when i try to install gym[box2d] i get following error: i tried: pip install gym[box2d]. on anaconda prompt i installed swig and gym[box2d] but i code in python3.9 env and it still not working.(my text editor is pycharm) gym is already installed.and ERROR: Command...
how can i install gym[box2d] despite errors below?
when i try to install gym[box2d] i get following error: i tried: pip install gym[box2d]. on anaconda prompt i installed swig and gym[box2d] but i code in python3.9 env and it still not working.(my text editor is pycharm) gym is already installed.and ERROR: Command errored out with exit status 1: command: 'C:\Users\h...
[ "according to Anaconda, you should use the following command\nconda install -c conda-forge gym-box2d\n\nbut you can still just install gym and from gym.envs import box2d\n", "I think you are using windows for using openai gym which is not officially supported. gym installation for windows is not stable. Linux and...
[ 2, 0, 0, 0 ]
[]
[]
[ "box2d", "openai_gym", "pip", "python" ]
stackoverflow_0070550623_box2d_openai_gym_pip_python.txt
Q: Gym's box 2d (openAI) doesn't install successfully (pip error) I'm trying to do the follow code with OpenAI: import gym env = gym.make('CarRacing-v0') env.reset() for _ in range(1000): env.render() env.step(env.action_space.sample()) but it throws the error: fn = getattr(mod, attr_name) AttributeError: mod...
Gym's box 2d (openAI) doesn't install successfully (pip error)
I'm trying to do the follow code with OpenAI: import gym env = gym.make('CarRacing-v0') env.reset() for _ in range(1000): env.render() env.step(env.action_space.sample()) but it throws the error: fn = getattr(mod, attr_name) AttributeError: module 'gym.envs.box2d' has no attribute 'CarRacing' And then I try to...
[ "Windows support is at present moment experimental (source). That being said, on most of the occasions you will get it to work, but some of the functionality could be broken. Proceed with caution.\nHere's what could work:\n\nInstall Anaconda.\nStart Anaconda command line (it adds conda to the PATH).\nconda create -...
[ 4, 2, 0, 0 ]
[]
[]
[ "box2d", "machine_learning", "openai_gym", "python", "reinforcement_learning" ]
stackoverflow_0060268769_box2d_machine_learning_openai_gym_python_reinforcement_learning.txt
Q: Pyrogram: how to run async method in FastAPI router How i can run pyrogram method in FastApi routes? I use Pyrogram and i have some methods for working with Telegram. class UserBot: def __init__(self, username: str, debug: Optional[bool] = False) -> None: self.username = username self.app = C...
Pyrogram: how to run async method in FastAPI router
How i can run pyrogram method in FastApi routes? I use Pyrogram and i have some methods for working with Telegram. class UserBot: def __init__(self, username: str, debug: Optional[bool] = False) -> None: self.username = username self.app = Client(f"sessions/{username}") # For example get chat his...
[ "try tris code\nfrom fastapi import FastAPI, HTTPException\nimport asyncio\n\napp = FastAPI()\n\n@app.get(\"/test/\")\nasync def test():\n ubot = UserBot(username=\"donqhomo\", debug=False)\n return await bot.get_chat_history(chat_id=\"@CryptoVedma\")\n\n" ]
[ 0 ]
[]
[]
[ "fastapi", "pyrogram", "python", "python_asyncio" ]
stackoverflow_0074244112_fastapi_pyrogram_python_python_asyncio.txt
Q: Python, tkinter How to allow clicks through app? I am new to coding and python. I use tkinter to make an app and want to know how to allow your clicks to affect the apps and stuff behind my app without interacting with my app. My app is designed to turn the screen pink by adding a transparent overlay. I want to ma...
Python, tkinter How to allow clicks through app?
I am new to coding and python. I use tkinter to make an app and want to know how to allow your clicks to affect the apps and stuff behind my app without interacting with my app. My app is designed to turn the screen pink by adding a transparent overlay. I want to make the overlay visible but not affecting the other app...
[ "This is not an answer. I will delete it sooner.\nYour Entry and Button is out of window. I am not going to try this.\nIn Line 8, I changed window size.\nwin.geometry(\"640x480\")\n\nIn line 13,. Change this: Entry(win, textvariable=sec, width = 2, font = In line 13, 'Helvetica 14').place(x=20, y=90)\nIn line 16. C...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074231303_python_tkinter.txt
Q: How to get embedded http from href in html script - scrapy I'd like to get the embedded http link from this html script. I'm an a scrapy shell for https://www.brunningandprice.co.uk/architectbath/ Then if I use response.css('p.mb-0 a::attr(href)').get() I only get the '/architectbath/menus/' rather than the full h...
How to get embedded http from href in html script - scrapy
I'd like to get the embedded http link from this html script. I'm an a scrapy shell for https://www.brunningandprice.co.uk/architectbath/ Then if I use response.css('p.mb-0 a::attr(href)').get() I only get the '/architectbath/menus/' rather than the full http as pictured. Does anyone know what I have to do differently ...
[ "Read about urljoin().\nscrapy shell \"https://www.brunningandprice.co.uk/architectbath/\"\n\nIn [1]: partial_url = response.css('p.mb-0 a::attr(href)').get()\n\nIn [2]: partial_url\nOut[2]: '/architectbath/menus/'\n\nIn [3]: absolute_url = response.urljoin(partial_url)\n\nIn [4]: absolute_url\nOut[4]: 'https://www...
[ 1 ]
[]
[]
[ "html", "python", "scrapy" ]
stackoverflow_0074232947_html_python_scrapy.txt
Q: Django - Add entry to ManyToMany field through class based view I want to add / remove members from a Team model. Members are specified as a ManyToManyField. I use django-rules to specify permissions, so team owners should be able to add/remove members. # models.py from django.db import models from rules.contrib....
Django - Add entry to ManyToMany field through class based view
I want to add / remove members from a Team model. Members are specified as a ManyToManyField. I use django-rules to specify permissions, so team owners should be able to add/remove members. # models.py from django.db import models from rules.contrib.models import RulesModel from django.conf import settings class Team...
[ "TL;DR: replace the last line of form_valid by return HttpResponseRedirect(self.get_success_url())\nIt's important to understand how form_valid of UpdateView works. I recommend to visualize the methods on ccbv.co.uk.\nFrom ModelFormMixin:\nIf the form is valid, save the associated model.\ndef form_valid(self, form)...
[ 0 ]
[]
[]
[ "django", "django_rules", "python" ]
stackoverflow_0070544128_django_django_rules_python.txt