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: issue with deleting rows in python sqlite import pandas as pd import sqlite3 as sql import os sea_level_df = pd.read_csv(r"C:\Users\slaye\OneDrive\Desktop\SeaLevel.csv", skiprows=3) display(sea_level_df) conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db") cur = conn.cursor() s = sea_level_df.to_s...
issue with deleting rows in python sqlite
import pandas as pd import sqlite3 as sql import os sea_level_df = pd.read_csv(r"C:\Users\slaye\OneDrive\Desktop\SeaLevel.csv", skiprows=3) display(sea_level_df) conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db") cur = conn.cursor() s = sea_level_df.to_sql('v', conn) cur.commit(s) conn.close() class...
[ "Since \"index\" is a reserved keyword as listed here, have you tried adding brackets [index] or rename this field if you can ? Maybe something like [v_id] would be a better choice in my opinion.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074203144_python_sqlite.txt
Q: Fill diagonal of a numpy array with values with different data type I want to create a diagonal numpy array. However, I face a memory error as the matrix is very large. An idea to decrease the memory consumption is to change the data types. I thought the most effective way is to have all numbers on diagonal in flo...
Fill diagonal of a numpy array with values with different data type
I want to create a diagonal numpy array. However, I face a memory error as the matrix is very large. An idea to decrease the memory consumption is to change the data types. I thought the most effective way is to have all numbers on diagonal in float (say float32) and all zeros outside the diagonal in int8. I tried the ...
[ "The best way to handle this case is to use scipy.sparse.diags as follows:\na = numpy.float32(numpy.random.rand(10))\na = sparse.diags(a)\n\nIf the shape of your diagonal numpy array is n*n, utilizing sparse.diags would result in a matrix n times smaller.\n" ]
[ 0 ]
[]
[]
[ "arrays", "numpy", "out_of_memory", "python" ]
stackoverflow_0074200379_arrays_numpy_out_of_memory_python.txt
Q: Discord Python bot commands not responding basically i have no idea why this code is not working, ive tried using on_message and that works so long as i dont include and if statement to filter for the messages with the prefix at the start. so i scrapped that, this code worked a few months ago with a different bot ...
Discord Python bot commands not responding
basically i have no idea why this code is not working, ive tried using on_message and that works so long as i dont include and if statement to filter for the messages with the prefix at the start. so i scrapped that, this code worked a few months ago with a different bot i made and ive ended up scrapping all the other ...
[ "There are a couple of things that could be causing your problems. I fixed the issue by enabling intents for the bot. This also must be done on the developer portal. https://discord.com/developers/applications\nintents = discord.Intents().all()\nintents.members = True\nbot = commands.Bot(command_prefix=\"!\", inten...
[ 0, 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074187790_bots_discord_discord.py_python.txt
Q: How to fit a straight line to part of a curve I have a set of data from a pd.DataFrame which looks like this, with a 3rd-order polynomial fitted to it: which is fit by # Find the 3rd-order polynomial which fits the SED coefs = poly.polyfit(x, y, 3) # find the coeffs x_new = np.linspace(lower, upper, num=len(x)*10...
How to fit a straight line to part of a curve
I have a set of data from a pd.DataFrame which looks like this, with a 3rd-order polynomial fitted to it: which is fit by # Find the 3rd-order polynomial which fits the SED coefs = poly.polyfit(x, y, 3) # find the coeffs x_new = np.linspace(lower, upper, num=len(x)*10) # space to plot the fit ffit = poly.Polynomial(co...
[ "Assuming the curve shape is always going to be similar to the example, you could fit a line to the portion of your dataset limited by the ymax and ymin values. You could automate the detection of that subset by calculating the y range between the ymax and ymin values, as well as the corresponding x values. The use...
[ 0, 0 ]
[]
[]
[ "curve_fitting", "data_fitting", "matplotlib", "pandas", "python" ]
stackoverflow_0074174458_curve_fitting_data_fitting_matplotlib_pandas_python.txt
Q: Group Session in Django Channels I'm looking for a solution where I want to create a group with n number of users and let them-users join the group. and then finally, delete this group once the work is complete. (the creator of the group can delete this or when everyone from the group disconnects). I have been thi...
Group Session in Django Channels
I'm looking for a solution where I want to create a group with n number of users and let them-users join the group. and then finally, delete this group once the work is complete. (the creator of the group can delete this or when everyone from the group disconnects). I have been thinking to design this for the last 3-4 ...
[ "if I understand you correctly\nmaybe if you add for example work_status for this group model and when Every one leave the group or disconnects you can check if this work done to delete it or not\nand when users done the work you can update this field to True\nI think in this way you will not delete group in wrong ...
[ 0 ]
[]
[]
[ "django", "django_channels", "python", "websocket" ]
stackoverflow_0074203316_django_django_channels_python_websocket.txt
Q: I am looking forward to handle the errors for the sets of integers The scenerio is: I’m asking user to input only 5 numbers between 1 and 5 but how do we fix if he input 6 or more and 1 or less and also how to repeat the program again and again if he inputted negative integers like -1,-2. Also, if he input strings...
I am looking forward to handle the errors for the sets of integers
The scenerio is: I’m asking user to input only 5 numbers between 1 and 5 but how do we fix if he input 6 or more and 1 or less and also how to repeat the program again and again if he inputted negative integers like -1,-2. Also, if he input strings, I want to show the users to input only integers Num = [0,0,0,0,0] for...
[ "Try doing this:\nNum = [0,0,0,0,0]\n\ncount = 0\nwhile count < 5:\n num = int(input(\"Put the numbers only between 1 and 5!\"))\n if num > 0 and num < 6:\n Num[count] = num\n count += 1\n else:\n print(\"You must enter values from 1 to 5!\")\n \nprint(\"Your numbers are \", Num)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074203379_python.txt
Q: Get the sum of absolutes of columns for a dataframe If I have a dataframe and I want to sum the values of the columns I could do something like import pandas as pd studentdetails = { "studentname":["Ram","Sam","Scott","Ann","John","Bobo"], "mathantics" :[80,90,85,70,95,100], "science" :[85,95,...
Get the sum of absolutes of columns for a dataframe
If I have a dataframe and I want to sum the values of the columns I could do something like import pandas as pd studentdetails = { "studentname":["Ram","Sam","Scott","Ann","John","Bobo"], "mathantics" :[80,90,85,70,95,100], "science" :[85,95,80,90,75,100], "english" :[90,85,80,70,95,100] ...
[ "You need numeric columns for absolute values:\ncol_list = df.columns.difference(['studentname'])\ndf[col_list].abs().sum()\n\ndf.set_index('studentname').abs().sum()\ndf.select_dtypes(np.number).abs().sum()\n\n" ]
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074203419_pandas_python.txt
Q: How to extract attachments from MSG and save them as a valid files with mail-parser in python? I'm using mail-parser to parse emails in MSG (.msg) file format and to extract its attachments. import mailparser mail = mailparser.parse_from_file_msg('example.msg') attachments = mail.attachments for att in attachment...
How to extract attachments from MSG and save them as a valid files with mail-parser in python?
I'm using mail-parser to parse emails in MSG (.msg) file format and to extract its attachments. import mailparser mail = mailparser.parse_from_file_msg('example.msg') attachments = mail.attachments for att in attachments: file_name = att['filename'] encoded_payload = att['payload'] Attachments are base64 enco...
[ "You can use base64.urlsafe_b64decode() which takes a bytes-like object or (as in this case) ASCII string to decode. The result is returned as a bytes object, therefore we can simple write it to a file which is opened with a wb access mode.\nimport mailparser\nimport base64\n\nmail = mailparser.parse_from_file_msg(...
[ 0 ]
[]
[]
[ "email_parsing", "parsing", "python" ]
stackoverflow_0074198811_email_parsing_parsing_python.txt
Q: How to plot one line in different colors I have two list as below: latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879] lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925] now I want to plot this as a line, separate each 10 of those 'latt...
How to plot one line in different colors
I have two list as below: latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879] lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925] now I want to plot this as a line, separate each 10 of those 'latt' and 'lont' records as a period and give it a...
[ "There are several different ways to do this. The \"best\" approach will depend mostly on how many line segments you want to plot.\nIf you're just going to be plotting a handful (e.g. 10) line segments, then just do something like:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef uniqueish_color():\n ...
[ 44, 5, 2, 2, 1 ]
[ "I am aware this question is not very new, but I think this is an important answer to add:\nThe official documentation has this entry where it is explained how one can generate lines with multiple colors like so (in the example the color is given by the lines' derivative):\n\n" ]
[ -1 ]
[ "matplotlib", "python" ]
stackoverflow_0017240694_matplotlib_python.txt
Q: Dataframe summing all values of column bigger than 0 and add lowest value of other column to all of them in python (jupyter) I want to sum all values greater than zero in column 2 of the dataframe. This sum should next be assigned to all the rows that were summed in a new column (3). See the example below: Datafra...
Dataframe summing all values of column bigger than 0 and add lowest value of other column to all of them in python (jupyter)
I want to sum all values greater than zero in column 2 of the dataframe. This sum should next be assigned to all the rows that were summed in a new column (3). See the example below: Dataframe: Column 1 Column 2 0 15 0.2 1 11 0 2 13 0.4 3 19 0.4 4 14 ...
[ "Let's try\nm = df['Column 2'].eq(0)\n\ndf['Column 3'] = (df['Column 2'].mask(m, 0) # convert value with True to 0\n .groupby(m.cumsum()).transform('sum') # sum value in each group\n .mask(m, 0)) # convert value with True to 0\n\ndf['Column 4...
[ 0 ]
[]
[]
[ "dataframe", "jupyter", "python" ]
stackoverflow_0074203343_dataframe_jupyter_python.txt
Q: how can i make my discord bot do the !say command? I've never coded before so I'm pretty new and I'm trying python on replit, I've searched a lot and this is what I did so far but it isn't working. (ignore the reverse part) import os import discord from keep_alive import keep_alive client = discord...
how can i make my discord bot do the !say command?
I've never coded before so I'm pretty new and I'm trying python on replit, I've searched a lot and this is what I did so far but it isn't working. (ignore the reverse part) import os import discord from keep_alive import keep_alive client = discord.Client(intents=discord.Intents.default()) @client.even...
[ "There's a lot of problems here\n\nIntents.default() doesn't include the message contents intent, so you won't be able to read messages. For more info on intents and how to enable them, read the docs: https://discordpy.readthedocs.io/en/stable/intents.html\nYou've got two on_message functions, which doesn't work. Y...
[ 1, 0 ]
[]
[]
[ "chatbot", "discord", "discord.py", "python", "replit" ]
stackoverflow_0074106772_chatbot_discord_discord.py_python_replit.txt
Q: change camera position in PyOpenGL I've drawn a cube using PyOpenGL but need to change the camera position to look at it from a different angle (ex. move camera to (1,2,3) and look at origin) This is the code I have for drawing the cube (with triangles). When I run it I get a square (which I'm assuming is just my ...
change camera position in PyOpenGL
I've drawn a cube using PyOpenGL but need to change the camera position to look at it from a different angle (ex. move camera to (1,2,3) and look at origin) This is the code I have for drawing the cube (with triangles). When I run it I get a square (which I'm assuming is just my cube from the front view). from OpenGL i...
[ "Add Uniform variables to the shader program for the view and projection matrices and transform the vertex position with the matrices (note that matrix multiplication is not commutative, the order of multiplication is important):\n#version 330 core\n\nlayout(location = 0) in vec3 aPos;\nlayout(location = 1) in vec3...
[ 1 ]
[]
[]
[ "opengl", "pyopengl", "python" ]
stackoverflow_0074202409_opengl_pyopengl_python.txt
Q: How do I add a randomly generated password to a .txt document in Python? Basically I am working on a random password generator and I wanted a way to add the passwords that are generated into a .txt file. Below is my current code. import random letters = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") ...
How do I add a randomly generated password to a .txt document in Python?
Basically I am working on a random password generator and I wanted a way to add the passwords that are generated into a .txt file. Below is my current code. import random letters = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") # The list of letters, numbers and special characters that will be used in th...
[ "First of all it's much better to return a value from a function than to print it:\ndef generate_random_password():\n length = int(input(\"Enter password length: \"))\n ...\n random.shuffle(userpassword)\n return \"\".join(userpassword)\n\nAfter that all you have to do is to open a file for appending an...
[ 0, 0 ]
[]
[]
[ "generator", "passwords", "python", "random" ]
stackoverflow_0074203384_generator_passwords_python_random.txt
Q: python thread or pool for multiprocessing? new to this lets say I have 5 users in a list, I will need to loop the list, for each user I will need to call some API to generate a txt file to store some JSON data. Is it possible to do this 5 person at the same time with python? or any good recommendation or sample to...
python thread or pool for multiprocessing? new to this
lets say I have 5 users in a list, I will need to loop the list, for each user I will need to call some API to generate a txt file to store some JSON data. Is it possible to do this 5 person at the same time with python? or any good recommendation or sample to help out? thanks a lot.
[ "in python you can use library Threading\nusers = [1, 2, 3, 4, 5]\nimport threading\n\ndef call_api(end_point_api):\n \"your code\"\n\n\nfor user in users:\n end_point_api = ''\n start_thread = threading.Thread(target=call_api, args(end_point_api))\n start_thread.start()\n\n", "The other answer is good, b...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074203404_python.txt
Q: Flask: TypeError: downloadanddelete() got multiple values for argument 'file' There are plenty of posts regarding this specific TypeError but none seem to help in my case. I have a function which returns a file from the server but everytime I try to call it this error occurs: File "services.py", line 75, in decora...
Flask: TypeError: downloadanddelete() got multiple values for argument 'file'
There are plenty of posts regarding this specific TypeError but none seem to help in my case. I have a function which returns a file from the server but everytime I try to call it this error occurs: File "services.py", line 75, in decorated return f(user, *args, **kwargs) TypeError: downloadanddelete() got multiple val...
[ "So the solution was in hindsight very simple but the way the code is written can confuse. The auth() function returns a user object. So when you use @app.route and @auth the function expects the current user. If you don't have a user parameter in the called function (downloadanddelete) it will be passed in the fir...
[ 0 ]
[]
[]
[ "flask", "python", "web_services", "webserver" ]
stackoverflow_0074190598_flask_python_web_services_webserver.txt
Q: Adding a another level of columns for a pandas data frame I have a data frame that consists of 60 columns; and for the sake of illustration I will be showing an example data frame that looks like what I have but much shorter. the example data frame looks like this: 0 1 ... 0 1 ....
Adding a another level of columns for a pandas data frame
I have a data frame that consists of 60 columns; and for the sake of illustration I will be showing an example data frame that looks like what I have but much shorter. the example data frame looks like this: 0 1 ... 0 1 ... 0 -0.611064 -0.032586 ... -0.102049 1.582183 ... what I w...
[ "IIUC, you just need to create a repeating sequence of A's and B's, with the length of the sequence equal to the number of your current columns. You can do it using numpy:\nimport numpy as np\n\ndf.columns = pd.MultiIndex.from_arrays(\n [np.repeat(['A','B'], df.shape[1] // 2), df.columns]\n)\n\nThe first array a...
[ 2 ]
[]
[]
[ "dataframe", "multi_index", "python" ]
stackoverflow_0074203330_dataframe_multi_index_python.txt
Q: How can I get a discord bot to send a message if a command is said? I'm making a discord bot using Python but none of the commands that should be running are running. I've traced it down to the if command below: if message.content.startswith("$hello"): # <<<<<< This command is causing issues! print("Command ...
How can I get a discord bot to send a message if a command is said?
I'm making a discord bot using Python but none of the commands that should be running are running. I've traced it down to the if command below: if message.content.startswith("$hello"): # <<<<<< This command is causing issues! print("Command detected: $hello") await message.channel.send('Hello there! I am a bo...
[ "Intents.messages is not the same as Intents.message_content!\nmessages:\n\nWhether guild and direct message related events are enabled.\nThis is a shortcut to set or get both guild_messages and dm_messages.\n\nmessage_content:\n\nWhether message content, attachments, embeds and components will be available in mess...
[ 1 ]
[ "import discord\nimport os\n#make sure to set up your command syntax and set your intents so the bot can read messages\nclient= commands.Bot(command_prefix='$', intents=discord.Intents.default())\nclient.remove_command(\"help\")\n\n\n#don't use on_message for commands, it's gonna cause problems.\n#instead, use the ...
[ -1 ]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074203122_bots_discord_discord.py_python.txt
Q: Django: relation "django_site" does not exist I am running a test django server on aws and I just installed django-userena and when I try to signup a user upon clicking submit, I get the following message: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django...
Django: relation "django_site" does not exist
I am running a test django server on aws and I just installed django-userena and when I try to signup a user upon clicking submit, I get the following message: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... I am not really sure what went wrong here. ...
[ "I recently ran into this issue (Django 1.8.7) even with SITE_ID = 1 in my settings. I had to manually migrate the sites app before any other migrations:\n./manage.py migrate sites\n./manage.py migrate\n\n", "You may be calling a site object before creating site model(before syncdb or migrate)\nex: site = Site...
[ 51, 11, 10, 3, 2, 1, 1, 1, 1, 0, 0, 0 ]
[ "I just restarted my computer and problem disappeared :)\n(restarting docker-compose is not enough).\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0023925726_django_python.txt
Q: problem running a python discord bot in vps I try to run my bot xerion.py and I get an error. Basically, in my computer everything works fine, the modules are executed etc. The problem is in the VPS, the Cogs are not loaded. Does it take a library or something? root@webservice:~/xerion# python3 xerion.py xerion.py...
problem running a python discord bot in vps
I try to run my bot xerion.py and I get an error. Basically, in my computer everything works fine, the modules are executed etc. The problem is in the VPS, the Cogs are not loaded. Does it take a library or something? root@webservice:~/xerion# python3 xerion.py xerion.py:18: RuntimeWarning: coroutine 'BotBase.load_exte...
[ "The error clearly says you didn't await an async function:\nRuntimeWarning: coroutine 'BotBase.load_extension' was never awaited \nclient.load_extension(f\"modules.{folder}.cog\")\n\nCogs & extensions were made asynchronous in discord.py v2.0. The migration guide explains how to... migrate... to 2.0.\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074201897_discord.py_python.txt
Q: module `Qt.labs.qmlmodels` is not installed I'm trying to run the example of item selection for a TableView, but it needs Qt.labs.qmlmodels. The problem is, that doesn't appear to be installed, and I can't find the correct package. main.qml: import Qt.labs.qmlmodels import QtQuick import QtQuick.Controls import Qt...
module `Qt.labs.qmlmodels` is not installed
I'm trying to run the example of item selection for a TableView, but it needs Qt.labs.qmlmodels. The problem is, that doesn't appear to be installed, and I can't find the correct package. main.qml: import Qt.labs.qmlmodels import QtQuick import QtQuick.Controls import QtQuick.Layouts ApplicationWindow { visible: t...
[ "please read this:\nqt-6.4-qml-python-missing-liberary-module-qt5compat-graphical-effects-is-not-installed\nJust now, I try to change matplotlib-backends' version. I find that the pyqt6 folder doesn't have the Qt folder.\nSo I copy that in pyside6 lib to pyqt lib.\nFor me is:from D:\\Python\\Python39\\Lib\\site-pac...
[ 0 ]
[]
[]
[ "archlinux", "python", "qml", "qt", "qtquick2" ]
stackoverflow_0073430605_archlinux_python_qml_qt_qtquick2.txt
Q: Python sleep if a function runs for 20 times I have a function for sending an email which is used in a celery task i need to make the code sleep for a second if that email function is ran for 20 times how can i make this happpen. @app.task(bind=True) def send_email_reminder_due_date(self): send_email_from_tem...
Python sleep if a function runs for 20 times
I have a function for sending an email which is used in a celery task i need to make the code sleep for a second if that email function is ran for 20 times how can i make this happpen. @app.task(bind=True) def send_email_reminder_due_date(self): send_email_from_template( subject_template_path='emails/0.txt...
[ "I may be missing a vital point here around what you can/can't do because you are using celery, but I'll post in case it's useful. You can track function state by assigning attributes to functions. In the below code I assign an attribute times_without_sleep to a dummy function and track its value to sleep every 20 ...
[ 1 ]
[]
[]
[ "celery", "django", "python", "sleep", "time" ]
stackoverflow_0074203453_celery_django_python_sleep_time.txt
Q: Pandas recursively drop values from each row if outside a limit I'm working on a dataset that has temperature values from multiple sensors in 5min intervals. The requirement is to calculate the mean from all sensors in each interval if any values are > 3% from the mean (above or below) then drop the highest valu...
Pandas recursively drop values from each row if outside a limit
I'm working on a dataset that has temperature values from multiple sensors in 5min intervals. The requirement is to calculate the mean from all sensors in each interval if any values are > 3% from the mean (above or below) then drop the highest value (ie furthest from the mean) recalculate the mean repeat if any re...
[ "What you want to do is loop until your condition is met (no more values >3% from mean).\nimport pandas as pd\nvalues= {\n \"col\" :[90,85,80,70,95,100]\n }\nindex_labels=[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]\ndf = pd.DataFrame(values,index=index_labels)\n\nall_within_three_percent = False #set c...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074203220_pandas_python.txt
Q: can't make imports my project can't make import idk why the error is showing seifahmed15@Ubuntu:~/Desktop/DAC-master$ python3 main.py Traceback (most recent call last): File "/home/seifahmed15/Desktop/DAC-master/main.py", line 2, in <module> from user import create File "/home/seifahmed15/Desktop/DAC-maste...
can't make imports
my project can't make import idk why the error is showing seifahmed15@Ubuntu:~/Desktop/DAC-master$ python3 main.py Traceback (most recent call last): File "/home/seifahmed15/Desktop/DAC-master/main.py", line 2, in <module> from user import create File "/home/seifahmed15/Desktop/DAC-master/user.py", line 5, in <...
[ "The console message below offers a bit more context on one issue, specifically on line 43:\nFile \"/home/seifahmed15/.local/lib/python3.11/site-packages/seleniumwire/thirdparty/mitmproxy/net/tls.py\", line 43, in <module>\n \"SSLv2\": (SSL.SSLv2_METHOD, BASIC_OPTIONS),\n ^^^^^^^^^^^^^^^^\nAttribute...
[ 0 ]
[]
[]
[ "import", "python", "python_3.x" ]
stackoverflow_0074199348_import_python_python_3.x.txt
Q: True or False List combination Could someone please explain why the following does not achieve the desired output. I have two list: l1 and l2. I want to check if either value is 1 in each list and return this to a 3rd list l3. Have [1,1,0,0] [0,0,0,1] Want [1,1,0,1] I have figured out how to get the desired output...
True or False List combination
Could someone please explain why the following does not achieve the desired output. I have two list: l1 and l2. I want to check if either value is 1 in each list and return this to a 3rd list l3. Have [1,1,0,0] [0,0,0,1] Want [1,1,0,1] I have figured out how to get the desired output with list comprehension: desired = ...
[ "here l3 = l1 or l2 is checking if value of l3 will be l1 if l1 has any value ie l1 is not empty or None, otherwise it will be equal to l2\nyou can understand this will following example\n>>> x= [1]\n>>> y = []\n>>> z = x or y\n>>> z\n[1]\n>>> z = y or x\n>>> z\n[1]\n\nNote it is not processing internal element of ...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074203601_list_python.txt
Q: How can I download pip package for other OS? I'm running on linux and want to download pip package for windows. How can I do it ? For example: How can I run this command on linux and get the windows package ? pip3 download torch --extra-index-url https://download.pytorch.org/whl/cu113 A: You can use the argument...
How can I download pip package for other OS?
I'm running on linux and want to download pip package for windows. How can I do it ? For example: How can I run this command on linux and get the windows package ? pip3 download torch --extra-index-url https://download.pytorch.org/whl/cu113
[ "You can use the argument --platform to do this. You need to specify as well the --only-binary :all: argument to make it work.\nTry the following:\npip3 download torch --platform win_amd64 --only-binary=:all: --extra-index-url https://download.pytorch.org/whl/cu113\n\nPlatforms are for example win_amd64, linux_x86_...
[ 1, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074203409_pip_python.txt
Q: "EC" is not defined,"array" is not defined,"Image" is not defined This script used to run before the 31th of August. But it shows these three errors now. I have tried uninstall the pillow, or use the particular version, but it still not work,like this : Pyautogui screenshot - NameError: name 'Image' is not defined...
"EC" is not defined,"array" is not defined,"Image" is not defined
This script used to run before the 31th of August. But it shows these three errors now. I have tried uninstall the pillow, or use the particular version, but it still not work,like this : Pyautogui screenshot - NameError: name 'Image' is not defined Does anyone have idea on this ? "EC" is not defined, "array" is not de...
[]
[]
[ "Use the following code to comments\nWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='DraftEditor-editorContainer']/div[@class='notranslate public-DraftEditor-content' and starts-with(@aria-describedby, 'placeholder')]\"))).send_keys(\"type the comment here\")\n\n" ]
[ -1 ]
[ "pyautogui", "python", "selenium" ]
stackoverflow_0069097055_pyautogui_python_selenium.txt
Q: Python curses, splitting terminal window in 4 pads - prefresh() returned ERR I'm running a multiprocessing system in Python, and I was planning to use curses to divide the terminal window in 4 quadrants, and display the output of each of the processes in one of them. So, the final output should look something like...
Python curses, splitting terminal window in 4 pads - prefresh() returned ERR
I'm running a multiprocessing system in Python, and I was planning to use curses to divide the terminal window in 4 quadrants, and display the output of each of the processes in one of them. So, the final output should look something like: -------------------------------- | | | | PROCESS01...
[ "The lines should be changed to\npad11.refresh(0,0, 0,0, rows_mid,cols_mid)\npad12.refresh(0,0, 0,cols_mid, rows_mid,cols_tot-1)\npad21.refresh(0,0, rows_mid,0, cols_tot-1,rows_mid)\npad22.refresh(0,0, rows_mid,cols_mid, rows_tot-1,cols_tot-1)\n\nresult:\n\nFull working code\nimport curses\n\n\ndef draw_menu(stdscr...
[ 1 ]
[]
[]
[ "curses", "python", "python_curses" ]
stackoverflow_0067386382_curses_python_python_curses.txt
Q: Sort one column to ascending order while keeping another columns higher values The following link is to the colab notebook I am using, the code I am talking about is the last one I have the following table which I have already put in descending order for the column "protein". What I need to have is those first 15 ...
Sort one column to ascending order while keeping another columns higher values
The following link is to the colab notebook I am using, the code I am talking about is the last one I have the following table which I have already put in descending order for the column "protein". What I need to have is those first 15 results (the highest 15 protein results) but now in ascending or descending order of...
[ "As noted by some of the comments, it looks like you have a typo in the lines below:\ndf1 = df.sort_values(by = ['protein', 'calories'], inplace = True, ascending = [False, True])\ndf.head(15)\n\nIn the line below, you define df1 as:\ndf1 = df.sort_values(by = ['protein', 'calories'], inplace = True, ascending = [F...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "sorting" ]
stackoverflow_0074198947_dataframe_pandas_python_sorting.txt
Q: Is it possible to use IDesktopWallpaper in Python? I have a simple code for changing wallpaper: import ctypes import random import os start_path = "D:/my_wallpapers" list_images = os.listdir(start_path) img_path = os.path.join(start_path, random.choice(list_images)) ctypes.windll.user32.SystemParametersInfoW(20,...
Is it possible to use IDesktopWallpaper in Python?
I have a simple code for changing wallpaper: import ctypes import random import os start_path = "D:/my_wallpapers" list_images = os.listdir(start_path) img_path = os.path.join(start_path, random.choice(list_images)) ctypes.windll.user32.SystemParametersInfoW(20, 0, img_path, 0) I have two monitors. This code sets th...
[ "The easiest way is to call the C++ DLL from python, there is no need to deal with some syntax problems of the com interface in python.\n.py\nimport os\nimport sys\nfrom ctypes import *\n\nlib = cdll.LoadLibrary('D:\\\\Sample\\\\Debug\\\\Sample.dll')\nlib.SetWallpaper(0,'C:\\\\Users\\\\xyz\\\\Desktop\\\\panda.png')...
[ 0, 0 ]
[]
[]
[ "python", "winapi", "windows" ]
stackoverflow_0066375014_python_winapi_windows.txt
Q: while loop that is equivalent to for loop I am trying to experiment how the while loop works. docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc'] for i in range(0,len(docs)): for j in range(i,len(docs[i])): print(i, j) My output for the above code is 0 0 0 1 0 2 0 3 0 4 0 5 1 1 1 2 1 3 1 4 1 5 2 2 I a...
while loop that is equivalent to for loop
I am trying to experiment how the while loop works. docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc'] for i in range(0,len(docs)): for j in range(i,len(docs[i])): print(i, j) My output for the above code is 0 0 0 1 0 2 0 3 0 4 0 5 1 1 1 2 1 3 1 4 1 5 2 2 I attempt to play with the while loop with docs...
[ "docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']\ni = 0\nwhile i < len(docs):\n j = i # should be moved here\n while j < len(docs[i]):\n print(i, j)\n j += 1\n i += 1\n\n" ]
[ 1 ]
[]
[]
[ "for_loop", "python", "python_3.x", "while_loop" ]
stackoverflow_0074203664_for_loop_python_python_3.x_while_loop.txt
Q: pandas dataframe not creating new column I have data like this. What I am trying to do is to create a rule, based on domain names for my project. I want to create a new column named new_url based on domains. If it contains .cdn. it will take the string before .cdn. , otherwise it will call url parser library and p...
pandas dataframe not creating new column
I have data like this. What I am trying to do is to create a rule, based on domain names for my project. I want to create a new column named new_url based on domains. If it contains .cdn. it will take the string before .cdn. , otherwise it will call url parser library and parse url in another way. The problem is that i...
[ "Use .loc[row, 'column'] to create new column\nfor idx, x in df['domain'].items():\n if '.cdn.' in x:\n df.loc[idx, 'new_url'] = parsed_url\n else:\n df.loc[idx, 'new_url'] = parsed_url\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "numpy", "python", "url_parsing" ]
stackoverflow_0074203744_dataframe_numpy_python_url_parsing.txt
Q: Someone please explain what the for loop does / its meaning for this section of code? I'm learning python and I'm trying to understand what the for loop means. My assignment is to understand and comment the full code out. I know that the first two lines of code take an input. Can someone tell me what the next line...
Someone please explain what the for loop does / its meaning for this section of code?
I'm learning python and I'm trying to understand what the for loop means. My assignment is to understand and comment the full code out. I know that the first two lines of code take an input. Can someone tell me what the next lines of code mean? The for loop is extremely confusing. By the way, let's say the input for j_...
[ "Python input give you a string input, j_t and d_t are lists made from your inputs but it is still as string in the lists. for loop is actually iterating on your inputs to create dictionnaries which allow you to get j_t from a d_t value and vice versa and in a same time is casting all inputs to integers to make it ...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074203717_python.txt
Q: Select HTML elements with Selenium in Whatsapp Already sry for my English. Im writing script with selenium & python, what will choose all messages with photo in group. All messages boxes have this structure. Repo: # there is bad code, check only if it interesting for you :) https://github.com/AmirkulovOlzhas/whats...
Select HTML elements with Selenium in Whatsapp
Already sry for my English. Im writing script with selenium & python, what will choose all messages with photo in group. All messages boxes have this structure. Repo: # there is bad code, check only if it interesting for you :) https://github.com/AmirkulovOlzhas/whatsapp_group_photo_sort/tree/branch_test div1 span ...
[ "i found answer.\nProblem was in\ndriver.execute_script(\"arguments[0].click();\", select_div2)\n\nits some how taked any span.\nso i tried write it more precisely\n driver.execute_script(\"arguments[0].click();\", div1.find_element(By.CLASS_NAME, '_3BK98'))\n\n" ]
[ 1 ]
[]
[]
[ "html", "list", "python", "selenium", "whatsapp" ]
stackoverflow_0074177102_html_list_python_selenium_whatsapp.txt
Q: Binary Search with Python through recursion I have written this code for binary search in python. import math import copy def binarySearch(array, target): c=-1 flag=False org_array=copy.deepcopy(array) # Write your code here. l=array[0:math.floor(len(array)/2)] r=array[math.floor(len(array)...
Binary Search with Python through recursion
I have written this code for binary search in python. import math import copy def binarySearch(array, target): c=-1 flag=False org_array=copy.deepcopy(array) # Write your code here. l=array[0:math.floor(len(array)/2)] r=array[math.floor(len(array)/2):len(array)] for i in r: if(i==tar...
[ "In binary search the goal is to return the index of the target in the array.\nSo right off the bat you are making a mistake by splitting the array into halves because any index you find in the half won't necessarily be the same index to the original array plus making copies of arrays is not cheap and binary search...
[ 1, 1 ]
[]
[]
[ "binary_search", "python", "python_3.x" ]
stackoverflow_0074203270_binary_search_python_python_3.x.txt
Q: Getting a value after the object was created from user input Tkinter Python I cannot figure this out even though I watched videos about Object Oriented Programming and Classes in python. Simplified scenario: 2 classes. class1 is basically a window with two buttons (button1 creates an object of 2nd class and button...
Getting a value after the object was created from user input Tkinter Python
I cannot figure this out even though I watched videos about Object Oriented Programming and Classes in python. Simplified scenario: 2 classes. class1 is basically a window with two buttons (button1 creates an object of 2nd class and button2 gets the value from inside of this newly created object Entry widget via entryb...
[ "Solution\nThis is a topic I also used to struggle on. But luckily, I found a way to do this. First, make the FrameClass inherit the WindowClass. Next, in the __init__ function of the FrameClass, initialize the WindowClass. Now, when you want to access an attribute of FrameClass in the WindowClass use self. This wo...
[ 0 ]
[]
[]
[ "class", "instance_variables", "oop", "python", "tkinter" ]
stackoverflow_0074201788_class_instance_variables_oop_python_tkinter.txt
Q: Synonyms list with confidence score in Python I am looking for a resource/package in python to fetch a list of synonyms with some confidence score. Is something available for such analysis. For eg. synsets: - word: disease synonym: disorder confidence: 0.9 - word: "" synonym: congenital confide...
Synonyms list with confidence score in Python
I am looking for a resource/package in python to fetch a list of synonyms with some confidence score. Is something available for such analysis. For eg. synsets: - word: disease synonym: disorder confidence: 0.9 - word: "" synonym: congenital confidence: 0.3 - word: "abnormality" synonym: malfo...
[ "You are sort of entering the field of NLP with this question. While there are lexicons that define word polarity, I am not sure if such a mapping for synonyms exists.\nThe way I would do it is I would use a sentence transformer applied only to words. You will have to vectorize those words and then take note of the...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074203672_python.txt
Q: Prevent OS X from going to sleep with Python? Is there a way to prevent a computer running OS X from going to sleep from within a Python script? A: You can use the built-in caffeinate command. subprocess.Popen('caffeinate') This is how I use it: import sys import subprocess if 'darwin' in sys.platform: pri...
Prevent OS X from going to sleep with Python?
Is there a way to prevent a computer running OS X from going to sleep from within a Python script?
[ "You can use the built-in caffeinate command.\nsubprocess.Popen('caffeinate')\n\nThis is how I use it:\nimport sys\nimport subprocess\n\nif 'darwin' in sys.platform:\n print('Running \\'caffeinate\\' on MacOSX to prevent the system from sleeping')\n subprocess.Popen('caffeinate')\n\n", "You can also run caf...
[ 11, 4, 3, 0, 0 ]
[]
[]
[ "macos", "python", "sleep" ]
stackoverflow_0014215960_macos_python_sleep.txt
Q: How to iterate through a list with a Nonetype attribute? (Python) I'm making a script for LAN host discovery in Python(without scapy yea I know, trying to use the sockets library for a learning experience). I am able to discover hosts but am having trouble separating the live hosts from the ones that returned no r...
How to iterate through a list with a Nonetype attribute? (Python)
I'm making a script for LAN host discovery in Python(without scapy yea I know, trying to use the sockets library for a learning experience). I am able to discover hosts but am having trouble separating the live hosts from the ones that returned no response because the only indicator I have is the timeout response(ping,...
[ "Without testing your code, but if I understood you right, just use \"is None\" to check agains a None type:\nif ping is not None:\n live.append(host)\n\n", "In general, you can iterate over any iterable while excluding None values by iterating over the following generator instead:\n>>> iterable = [1, None, 2,...
[ 0, 0, 0 ]
[]
[]
[ "iteration", "network_programming", "ping", "python" ]
stackoverflow_0047581334_iteration_network_programming_ping_python.txt
Q: elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7 I have a numpy array called dt. Each element is of type datetime.timedelta. For example: >>>dt[0] datetime.timedelta(0, 1, 36000) how can I convert dt into the array dt_sec which contains only seconds without looping? my...
elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7
I have a numpy array called dt. Each element is of type datetime.timedelta. For example: >>>dt[0] datetime.timedelta(0, 1, 36000) how can I convert dt into the array dt_sec which contains only seconds without looping? my current solution (which works, but I don't like it) is: dt_sec = zeros((len(dt),1)) for i in ran...
[ "import numpy as np\n\nhelper = np.vectorize(lambda x: x.total_seconds())\ndt_sec = helper(dt)\n\n", "numpy has its own datetime and timedelta formats. Just use them ;).\nSet-up for example:\nimport datetime\nimport numpy\n\ntimes = numpy.array([datetime.timedelta(0, 1, 36000)])\n\nCode:\ntimes.astype(\"timedelta...
[ 12, 12, 1, 0, 0 ]
[ "You could use a \"list comprehension\":\ndt_sec = [delta.total_seconds() for delta in dt]\n\nBehind the scenes, numpy ought to translate that to a pretty speedy operation.\n" ]
[ -3 ]
[ "arrays", "datetime", "loops", "numpy", "python" ]
stackoverflow_0019039080_arrays_datetime_loops_numpy_python.txt
Q: How to write a loop that find the frequency of value and stop by enter number -100 numbers = input("Enter the numbers: ") count = {} for i in numbers: if i == '-100': break print('Done') elif i in count: count[i] +=1 else: count[i] = 1 for key,value in count.ite...
How to write a loop that find the frequency of value and stop by enter number -100
numbers = input("Enter the numbers: ") count = {} for i in numbers: if i == '-100': break print('Done') elif i in count: count[i] +=1 else: count[i] = 1 for key,value in count.items(): print(f'{key}:{value}') I just don't understand how to use the 'break' to s...
[ "you should use while loop for your case like this\ncount = {}\nwhile True:\n numbers = input(\"Enter the numbers: \")\n if numbers == '-100':\n print('Done')\n break\n \n count[numbers] = count.setdefault(numbers, 0) + 1\n\nfor key,value in count.items():\n print(f'{key}:{value}')\n\n"...
[ 0 ]
[]
[]
[ "frequency", "loops", "numbers", "python" ]
stackoverflow_0074203513_frequency_loops_numbers_python.txt
Q: Plot 4D Contour in Python (X,Y,Z + Data) I have a large set of measurements that I want to visualize in 4D using matplotlib in Python. Currently, my variables are arranged in this way: x = np.array(range(0, v1)) y = np.array(range(0, v2)) z = np.array(range(0, v3)) I have C which is a 3D array containing measurem...
Plot 4D Contour in Python (X,Y,Z + Data)
I have a large set of measurements that I want to visualize in 4D using matplotlib in Python. Currently, my variables are arranged in this way: x = np.array(range(0, v1)) y = np.array(range(0, v2)) z = np.array(range(0, v3)) I have C which is a 3D array containing measurement values for each combination of the previou...
[ "Regarding to @Sameeresque answer, I think the question was about a 4D graph like this (three coordinates x, y, z and a color as the fourth coordinate):\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# only for example, use your grid\nz = np.linspace(0, 1, 15)\nx = np.linspace(0, 1, 15)\ny = np.linspace(...
[ 3, 1, 1 ]
[]
[]
[ "4d", "matplotlib", "plot", "python", "python_3.x" ]
stackoverflow_0064385676_4d_matplotlib_plot_python_python_3.x.txt
Q: Python remove from list acting strange when used inline I want to loop through a list and remove a single element at a time: l1 = ["a", "b"] for l in l1: l2 = l1[:] l2.remove(l) print(l2) # ['b'] # ['a'] The behavior of the code changes when I use the remove call inline: l1 = ["a", "b"] for l in l1: ...
Python remove from list acting strange when used inline
I want to loop through a list and remove a single element at a time: l1 = ["a", "b"] for l in l1: l2 = l1[:] l2.remove(l) print(l2) # ['b'] # ['a'] The behavior of the code changes when I use the remove call inline: l1 = ["a", "b"] for l in l1: l2 = l1[:].remove(l) print(l2) # None # None Any id...
[ "Note that remove() does not return anything. That is why l2 is always None in your second example. The change is only applied to l1.\nIn your first example example the list is duplicated into l2 and then an element is removed from l2.\n", "The below code will do the job.\nl1 = [\"a\", \"b\", \"c\", \"d\"]\nfor a...
[ 3, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074203705_python.txt
Q: Create Category with the keys of a dictionary where a any string from the values as list appears anywhere in column from pandas dataframe Say you have a dataFrame that looks like this: name Description ABC 'Verdansk was the best' EDF 'Pro Clubs with the lads' LMN ...
Create Category with the keys of a dictionary where a any string from the values as list appears anywhere in column from pandas dataframe
Say you have a dataFrame that looks like this: name Description ABC 'Verdansk was the best' EDF 'Pro Clubs with the lads' LMN 'Being Druid was the best' RST 'The game of FIFA23' XYZ 'Switch on for Bio lab drop' ... .... and a...
[ "You need reverse the categories. Since you want to match FIFA23 with FIFA, you don't need \\b.\ncategories = {v.lower():k for k, lst in categories.items() for v in lst}\n\ndf['Category'] = (df['Description'].str.extract(fr\"({'|'.join(categories)})\", re.IGNORECASE)\n [0].str.lower().map(categorie...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074203877_dataframe_pandas_python.txt
Q: Remove similar Strings in Python List by Levenshtein Ratio I am trying to remove similar words in a python List by calculating the Levenshtein ratio between them. If the ratio is >0.9 the word should be removed. So I have to create a loop that iterates through the list and compare each word with each other word an...
Remove similar Strings in Python List by Levenshtein Ratio
I am trying to remove similar words in a python List by calculating the Levenshtein ratio between them. If the ratio is >0.9 the word should be removed. So I have to create a loop that iterates through the list and compare each word with each other word and then remove them if the ratio is to high. Unfortunately I have...
[ "using difflib you can match the similar strings in a list. and then remove the similar strings.\nimport difflib\n\nword_list = ['asf', 'bcd', 'ase', 'cdf', 'asl']\n\nclose_match = difflib.get_close_matches('asf', word_list)\nclose_match.remove('asf')\n\nresult = []\nfor i in word_list:\n if i not in close_match...
[ 0, 0 ]
[]
[]
[ "iteration", "levenshtein_distance", "list", "python", "string" ]
stackoverflow_0074203814_iteration_levenshtein_distance_list_python_string.txt
Q: Trying to terminate the loop early This is a code I wrote that will take the values from a CSV file and make it into a MySQL database. All the entries in the CSV file are string values. entries = "" counter = 1 with open('dataset.csv') as file_obj: heading = next(file_obj) reader_obj = csv.reader(file_obj...
Trying to terminate the loop early
This is a code I wrote that will take the values from a CSV file and make it into a MySQL database. All the entries in the CSV file are string values. entries = "" counter = 1 with open('dataset.csv') as file_obj: heading = next(file_obj) reader_obj = csv.reader(file_obj) for row in reader_obj: #pr...
[ "Is there a reason for doing it line by line? It can be done with pandas read_csv and to_sql in nearly two lines\nconn = mysql.connector.connect(host='localhost', database='test', user='root', password='********')\n\ndata = pd.read_csv('my_data.csv')\ndata.to_sql('my_table', conn, if_exists='append', index = False)...
[ 0 ]
[]
[]
[ "loops", "mysql_python", "python", "string" ]
stackoverflow_0074203959_loops_mysql_python_python_string.txt
Q: In python, dataframe also find the max and min values of data at certain intervals Hi I'm very new to both the forum and python writing language. There is something I would like to ask you, dear group members and masters, and I hope I can express it correctly. # LOAD BARS 5m bars = exchange.fetch_ohlcv(symbol...
In python, dataframe also find the max and min values of data at certain intervals
Hi I'm very new to both the forum and python writing language. There is something I would like to ask you, dear group members and masters, and I hope I can express it correctly. # LOAD BARS 5m bars = exchange.fetch_ohlcv(symbol, timeframe="5m", since = None, limit = 100) df = pd.DataFrame(bars, columns=["times...
[ "# Get last 3 data\ndf_last_3 = df.tail(3)\n\n# Get Smallest Value\nminvalue_series = df_last_3.min()\n\n# To get smallest open values\nsmallest_open = df_last_3[\"open\"].min()\n\nYou can solve the remaining problems like this.\n", "thanks for answers.\nIf we update the question to the following figure,\n\nthe s...
[ 0, 0 ]
[]
[]
[ "dataframe", "max", "min", "python" ]
stackoverflow_0074198246_dataframe_max_min_python.txt
Q: Google Cloud SDk: Python was not found After I install Google cloud sdk in my computer, I open the terminal and type "gcloud --version" but it says "python was not found" note: I unchecked the box saying "Install python bundle" when I install Google cloud sdk because I already have python 3.10.2 installed. so, how...
Google Cloud SDk: Python was not found
After I install Google cloud sdk in my computer, I open the terminal and type "gcloud --version" but it says "python was not found" note: I unchecked the box saying "Install python bundle" when I install Google cloud sdk because I already have python 3.10.2 installed. so, how do fix this? Thanks in advance.
[ "As mentioned in the document:\n\nCloud SDK requires Python; supported versions are Python 3 (preferred,\n3.5 to 3.8) and Python 2 (2.7.9 or later). By default, the Windows version of Cloud SDK comes bundled with Python 3 and Python 2. To use\nCloud SDK, your operating system must be able to run a supported\nversio...
[ 3, 1 ]
[]
[]
[ "google_cloud_platform", "python" ]
stackoverflow_0071949010_google_cloud_platform_python.txt
Q: maturin build not working with older python versions I created anaconda environment $ python --version Python 3.7.13 $ pip --version pip 22.2.2 from C:\tools\miniconda3\envs\py37\lib\site-packages\pip (python 3.7) In pyproject.toml I have requires-python = ">=3.7" [build-system] requires = ["maturin>=0.13,<0.14"]...
maturin build not working with older python versions
I created anaconda environment $ python --version Python 3.7.13 $ pip --version pip 22.2.2 from C:\tools\miniconda3\envs\py37\lib\site-packages\pip (python 3.7) In pyproject.toml I have requires-python = ">=3.7" [build-system] requires = ["maturin>=0.13,<0.14"] build-backend = "maturin" [project] name = "ecc_py" requ...
[ "So it found out it works with -i flag\n$ maturin build --release -i python\n Finished release [optimized] target(s) in 6.33s\n Built wheel for CPython 3.7 to C:\\Users\\Aleksander\\source\\repos\\Rust\\ecc\\target\\wheels\\ecc_py-0.1.0-cp37-none-win_amd64.whl\n\nI have no clue why it wouldn't work without it th...
[ 0 ]
[]
[]
[ "maturin", "pyo3", "python", "rust", "windows" ]
stackoverflow_0074203888_maturin_pyo3_python_rust_windows.txt
Q: How to pass json array to html page via flask render_template I'm working on attendance monitoring, where each student attendance status will be captured via API response in flask and need to show the response in dashboard format. Below the sample response we get - [ {"StudentName":"Name1", "Status":"Present"}, {"...
How to pass json array to html page via flask render_template
I'm working on attendance monitoring, where each student attendance status will be captured via API response in flask and need to show the response in dashboard format. Below the sample response we get - [ {"StudentName":"Name1", "Status":"Present"}, {"StudentName":"Name2", "Status":"Absent"} ] I'm able to capture ind...
[ "Did you tried to simply pass the entire array of dictionaries?\nreturn render_template(\"page.html\", attendance=array_name)\n\nThen, in the jinja2 template you can loop through it in order to display the information.\n{% for student in attendance %}\n\n<p>{{ student['StudentName'] }}</p>\n<p>{{ student['Status'] ...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074203927_flask_python.txt
Q: ValueError: list.remove(x): x not in list but the value is there in the list I am new to the world of Software Engineering and I am starting at codeacademy. could someone help me understand why I get a value error here? my list shows that that value is there but I can't seem to remove it. subjects = ["physics", "c...
ValueError: list.remove(x): x not in list but the value is there in the list
I am new to the world of Software Engineering and I am starting at codeacademy. could someone help me understand why I get a value error here? my list shows that that value is there but I can't seem to remove it. subjects = ["physics", "calculus", "poetry", "history"] grades = [98, 97, 85, 88] gradebook = [["physics",...
[ "Without knowing the actual codeacademy task it is hard to tell how the solution should be designed.\nI found a codeacademy forum post discussing these instructions, which index into the sublist and remove the value via gradebook[2].remove(85)\nDetailed explanation:\n\ngradebook is a list of lists\ngradebook[2] acc...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074189216_python.txt
Q: All predicted values of LSTM model is almost same I have trained a LSTM model to predict multiple output value. Predicted values are almost same even though the loss is less. Why is it so? How can I improve it? `from keras import backend as K import math from sklearn.metrics import mean_squared_error, mean_absolu...
All predicted values of LSTM model is almost same
I have trained a LSTM model to predict multiple output value. Predicted values are almost same even though the loss is less. Why is it so? How can I improve it? `from keras import backend as K import math from sklearn.metrics import mean_squared_error, mean_absolute_error from keras.layers.core import Dense, Dropout, ...
[ "It means you are just closing the values of x as nearest to y. Just like mapping x -> y. The Relative Error is saying to me that your y's are relatively small and when you are taking the mean difference between y_hat and y they are close enough...\nTo Break this symmetry you should increase the number of LSTM Cell...
[ 0 ]
[]
[]
[ "keras", "loss_function", "lstm", "python", "tensorflow" ]
stackoverflow_0074200607_keras_loss_function_lstm_python_tensorflow.txt
Q: Set numpy array values to zero where x,y,z are not all multiples of n Here is a naive implementation of a function which sets every value of a numpy array with index x,y,z to zero if any of x,y, or z is not a multiple of one_per_n: import numpy as np X = np.random.rand(10,10,10) one_per_n = 4 for x in range(X.s...
Set numpy array values to zero where x,y,z are not all multiples of n
Here is a naive implementation of a function which sets every value of a numpy array with index x,y,z to zero if any of x,y, or z is not a multiple of one_per_n: import numpy as np X = np.random.rand(10,10,10) one_per_n = 4 for x in range(X.shape[0]): for y in range(X.shape[1]): for z in range(X.shape[2]...
[ "In each dimension, the elements that retain their values are the ones where the modulo is zero. They are spaced one_per_n apart, so utilizing a slice with one_per_n as step size is useful.\nYou can construct a mask of elements to set to 0 for each dimension, and then zero out X at all these positions.\nThe inverse...
[ 3, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074193940_numpy_python.txt
Q: Django Rest-Framework nested serializer order Is there a way to order a nested serializer _set, for example order by pk or time-stamp. So basically order song_set shown in the json data below from the most recent to the latest object created, in this case by order_by('-timestamp') or order_by('-pk'). Json data { ...
Django Rest-Framework nested serializer order
Is there a way to order a nested serializer _set, for example order by pk or time-stamp. So basically order song_set shown in the json data below from the most recent to the latest object created, in this case by order_by('-timestamp') or order_by('-pk'). Json data { "pk": 151, "album_name": "Name", "song_s...
[ "You can use SerializerMethodField and write custom method for this.\nclass AlbumSerializer(HyperlinkedModelSerializer):\n song_set = serializers.SerializerMethodField()\n class Meta:\n model = Album\n fields = [\n 'pk',\n 'timestamp',\n 'song_set'\n ]\n\n...
[ 64, 56, 24, 6, 0 ]
[]
[]
[ "django", "django_rest_framework", "json", "python", "rest" ]
stackoverflow_0048247490_django_django_rest_framework_json_python_rest.txt
Q: How to make directed graph using Dash I copied this code: import dash import dash_core_components as dcc import dash_html_components as html import dash_cytoscape as cyto from dash.dependencies import Input, Output import plotly.express as px app = dash.Dash(__name__) app.layout = html.Div([ html.P("Dash Cyt...
How to make directed graph using Dash
I copied this code: import dash import dash_core_components as dcc import dash_html_components as html import dash_cytoscape as cyto from dash.dependencies import Input, Output import plotly.express as px app = dash.Dash(__name__) app.layout = html.Div([ html.P("Dash Cytoscape:"), cyto.Cytoscape( id='...
[ "I'm not sure if you are talking about making your layout (i) directed or to have (ii) edge arrows (or both) :\n(i) You can add the parameter 'directed':True to your layout. The new layout would be:\nlayout = {'name':'breadthfirst', 'directed':True}\nOther available parameters can be checked on the Cytoscape JavaSr...
[ 1, 0 ]
[]
[]
[ "directed_graph", "plotly_dash", "python" ]
stackoverflow_0065527815_directed_graph_plotly_dash_python.txt
Q: How to combine multiple polygons into 3d mesh (Python-trimesh) I'm dealing with stl data which can be loaded by: # load a file by name or from a buffer mesh = trimesh.load_mesh('./dummydata.stl') # preview mesh in a pyglet window from a terminal, or inline in a notebook mesh.show() This creates a 3D object which ...
How to combine multiple polygons into 3d mesh (Python-trimesh)
I'm dealing with stl data which can be loaded by: # load a file by name or from a buffer mesh = trimesh.load_mesh('./dummydata.stl') # preview mesh in a pyglet window from a terminal, or inline in a notebook mesh.show() This creates a 3D object which cannot be disclosed due to confidentiality issues. However, for the ...
[ "Probably Trimesh.util.concatenate could give you some hints\n" ]
[ 1 ]
[]
[]
[ "3d", "polygon", "python", "trimesh" ]
stackoverflow_0072285412_3d_polygon_python_trimesh.txt
Q: JSON value is converted to unicode - python My current Python Appium test automation framework reads data from JSON file using the json.load() The value "Ελλάδα" stored in JSON is converted to "Ελλάδα" when json.load() method is called. Pleases point me to a solution were I can maintain the the actual string...
JSON value is converted to unicode - python
My current Python Appium test automation framework reads data from JSON file using the json.load() The value "Ελλάδα" stored in JSON is converted to "Ελλάδα" when json.load() method is called. Pleases point me to a solution were I can maintain the the actual string value "Ελλάδα" JSON data in testdata.json { ...
[ "Use with open(file_location,encoding='utf-8'). For whatever reason, your system uses Latin 1 as the default encoding instead of UTF8.\nThe file is fine. This page, like 99.9% of web pages is UTF8. That's why you were able to write Ελλάδα without any problem.\nPython 3 strings are Unicode too. If you type \"Ελλάδα\...
[ 2 ]
[]
[]
[ "automation", "json", "python", "python_appium", "testing" ]
stackoverflow_0074204176_automation_json_python_python_appium_testing.txt
Q: In python, create index from flat representation of nested structure in a list, sorting by alphabetical order I have lists where each entry is representing a nested structure, where / represents each level in the structure. ['a','a/b/a','a/b','a/b/d',....] I want to take such a list and return an index list where...
In python, create index from flat representation of nested structure in a list, sorting by alphabetical order
I have lists where each entry is representing a nested structure, where / represents each level in the structure. ['a','a/b/a','a/b','a/b/d',....] I want to take such a list and return an index list where each level is sorted in alphabetical order. If we had the following list ['a','a/b','a/b/a','a/c','a/c/a','b'] It...
[ "Here's what I have tried:\nfrom operator import itemgetter\nfrom functools import reduce\n\nlst = ['a','a/b','a/b/a','a/c','a/c/a','b']\n\n# build a dict\ndct = {}\nfor keys in lst:\n reduce(lambda d, k: d.setdefault(k, {}), keys.split('/'), dct)\n\nprint(dct) # {'a': {'b': {'a': {}}, 'c': {'a': {}}}, 'b': {}}\...
[ 2, 2, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0074202814_algorithm_python.txt
Q: why django-daphne is not working with docker? I have a local & production docker-compose services for my django app, in the local service all be right, but in the production service daphne not work, in the same the redis connection is equals and i'm not using a special network conf for my docker compose services. ...
why django-daphne is not working with docker?
I have a local & production docker-compose services for my django app, in the local service all be right, but in the production service daphne not work, in the same the redis connection is equals and i'm not using a special network conf for my docker compose services. local compose: version: "3" services: app: ...
[ "Try using networks keyword instead of links.\nhttps://docs.docker.com/compose/compose-file/#links\n", "fix for me was adjusting working dir in docker-compose\n working_dir: /the_name_of_your_django_project/\n\n" ]
[ 0, 0 ]
[]
[]
[ "daphne", "devops", "django", "docker", "python" ]
stackoverflow_0059586073_daphne_devops_django_docker_python.txt
Q: How to duplicate a specific product attribute (product.product) in Odoo 15 I want to duplicate an attribute of a product after the user selects it. However, I want it to only contain the previously selected values in its attributes and not the values of all the attributes of the original product, in order to only ...
How to duplicate a specific product attribute (product.product) in Odoo 15
I want to duplicate an attribute of a product after the user selects it. However, I want it to only contain the previously selected values in its attributes and not the values of all the attributes of the original product, in order to only create 1 product variable. I tried this: for attribute in self.customization_att...
[ "Maybe you can try getting those selected attributes through self.env[models].active_ids\n" ]
[ 0 ]
[]
[]
[ "odoo", "odoo_15", "python" ]
stackoverflow_0074180129_odoo_odoo_15_python.txt
Q: I am unable to match a user input date with dates in a dataframe I am attempting to isolate the rows in a dataframe where dates match a user inputted date. Here is the full code with an included dataframe. Why doesn't it return my row? import pandas as pd from datetime import datetime df = pd.DataFrame({"Day": pd....
I am unable to match a user input date with dates in a dataframe
I am attempting to isolate the rows in a dataframe where dates match a user inputted date. Here is the full code with an included dataframe. Why doesn't it return my row? import pandas as pd from datetime import datetime df = pd.DataFrame({"Day": pd.to_datetime("2022-10-26"), "y": 5}, index=[0]) print(df) get_year = i...
[ "in Series checks the index, you can do in Series.tolist() or Series.eq().any()\nrundate = pd.to_datetime(inputdate)\n\nif rundate in df[\"Day\"].tolist():\n print(\"yes its in here\")\n# or\nif df[\"Day\"].eq(rundate).any():\n print(\"yes its in here\")\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "python_datetime" ]
stackoverflow_0074204337_pandas_python_python_datetime.txt
Q: Figuring out where the user clicked in a nested wx.Menu - wxPython I'm having trouble figuring out where the user clicked in a nested wx.Menu. I have the following setup... I would like a method to retrive the client's name, if he's checked in or if he's checkout and how long he ins't allowed in. The client's the...
Figuring out where the user clicked in a nested wx.Menu - wxPython
I'm having trouble figuring out where the user clicked in a nested wx.Menu. I have the following setup... I would like a method to retrive the client's name, if he's checked in or if he's checkout and how long he ins't allowed in. The client's themselves doens't have any unique ID to them. Should I do that? I haven't ...
[ "You are making life difficult for yourself, taking the menu route. You may be better off choosing something like a wx.Treectrl.\nWith that caveat out of the way, menus rely on an Id reference but the menu itself and therefore sub-menus, don't have a user assigned Id, just the menu items within the menu.\nThat refe...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0074189068_python_wxpython.txt
Q: Can't open ipynb juypter notebook file, crashed on a large df Panicking. Spend a long time working on code in Juypter Notebook on macbook (Anaconda) and i accidentally performed df.fillna(0) on a large df, not knowing it was going to try and load the whole thing in Juypter (i have it set to display all) It crashed...
Can't open ipynb juypter notebook file, crashed on a large df
Panicking. Spend a long time working on code in Juypter Notebook on macbook (Anaconda) and i accidentally performed df.fillna(0) on a large df, not knowing it was going to try and load the whole thing in Juypter (i have it set to display all) It crashed and was unresponsive. Now it's closed and won't load again (i just...
[ "Jupyter notebooks are just stored as JSON. You should be able to open it in a text editor and just pull out the code fields. – answer provided by jprebys\nOct 21 at 13:35\n" ]
[ 1 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074154376_jupyter_notebook_python.txt
Q: Flask, read image path I have a form like this <form id="imageForm" method="post" action="/printDDT"> <img name=imageFile src={{DDTimage}} width="50%" height="50%"> <br/><br/> <button type="submit">Print DDT</button> </form> and I want to read the src in my post fun...
Flask, read image path
I have a form like this <form id="imageForm" method="post" action="/printDDT"> <img name=imageFile src={{DDTimage}} width="50%" height="50%"> <br/><br/> <button type="submit">Print DDT</button> </form> and I want to read the src in my post function in app.py I tried this...
[ "<form method=post enctype=multipart/form-data>\n <input type=file name=file>\n <input type=submit value=Upload>\n</form>\n\nCan you try ?\n @app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' n...
[ 0 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074204358_flask_html_python.txt
Q: Use Sphinx doctest with :Example: Consider the following function: # in mymodule.py: def myfunc(num,mystring): """ replicates a string :param num: a positive integer :param mystring: a string :return: string concatenated with itself num times :Example: >>> num = 3 >>> mys...
Use Sphinx doctest with :Example:
Consider the following function: # in mymodule.py: def myfunc(num,mystring): """ replicates a string :param num: a positive integer :param mystring: a string :return: string concatenated with itself num times :Example: >>> num = 3 >>> mystring = "lol" >>> myfunc(num, m...
[ "Sphinx+doctest is not importing the module. You can either help him in the docstring:\n :Example:\n >>> from mymodule import myfunc\n >>> myfunc(3, 'lol')\n 'lollollol'\n\nor add this in conf.py:\ndoctest_global_setup = '''\n#if required, modif sys.path:\nimport sys\nsys.path.append('../dir...
[ 3, 1, 0, 0 ]
[]
[]
[ "doctest", "python", "python_sphinx" ]
stackoverflow_0058189699_doctest_python_python_sphinx.txt
Q: Value counts within col How could I calculate the value counts within a string col? df col 0 fruit["apple"], colour["green", "yellow" ] 1 colour["yellow"] 2 colour["brown"] Expected Output fruit 1 colour 3 A: Use Series.str.extractall with substrings joined by | for regex or: s = df['col'].str.extractall('(...
Value counts within col
How could I calculate the value counts within a string col? df col 0 fruit["apple"], colour["green", "yellow" ] 1 colour["yellow"] 2 colour["brown"] Expected Output fruit 1 colour 3
[ "Use Series.str.extractall with substrings joined by | for regex or:\ns = df['col'].str.extractall('(fruit|colour)')[0].value_counts()\nprint (s)\ncolour 3\nfruit 1\nName: 0, dtype: int64\n\nOr get words before [ for more dynamic solution:\ns = df['col'].str.extractall(r'(\\w+)\\[')[0].value_counts()\nprint ...
[ 2 ]
[]
[]
[ "list", "pandas", "python" ]
stackoverflow_0074204458_list_pandas_python.txt
Q: Playing sound using Python Basically I'm trying to write a code that opens a sound file using python, but all I get is this error. using MacOS and Python 3.10. tried many solutions but no luck. This is the code I’ve tried first: from playsound import playsound playsound('/Users/cairo/Desktop/i wish.mp3') /Us...
Playing sound using Python
Basically I'm trying to write a code that opens a sound file using python, but all I get is this error. using MacOS and Python 3.10. tried many solutions but no luck. This is the code I’ve tried first: from playsound import playsound playsound('/Users/cairo/Desktop/i wish.mp3') /Users/cairo/PycharmProjects/python...
[ "not a solution to your problem, but an alternative.\nI had the same problem and playsound seems to be broken as it is relying on python 2.7.\nYou can use pydub as an alternative.\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\nsong = AudioSegment.from_wav(\"path/to/file.wav\")\nplay(song)\n\n",...
[ 0, 0 ]
[]
[]
[ "audio", "macos", "playsound", "python", "wav" ]
stackoverflow_0074083314_audio_macos_playsound_python_wav.txt
Q: Is it OK to use Django development server for single-user applications? I'm developing an application that controls some piece of complex hardware and exposes a front-end to the users using Django, mainly for cross-platform and remote access reasons. Currently using Django templates, but soon with a separate front...
Is it OK to use Django development server for single-user applications?
I'm developing an application that controls some piece of complex hardware and exposes a front-end to the users using Django, mainly for cross-platform and remote access reasons. Currently using Django templates, but soon with a separate front-end through DRF calls. My main points of interest are: user management. Adm...
[ "From django runserver documentation:\n\nDO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that’s how it’s gonna stay. We’re in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environm...
[ 2 ]
[]
[]
[ "django", "django_rest_framework", "gunicorn", "python" ]
stackoverflow_0074204364_django_django_rest_framework_gunicorn_python.txt
Q: Unable to add data:image/jpeg;base64 to docx document with add_picture I retrieve a base64 image from the azure blob storage and decode it as follows: connection_string = environ.get('AZURE_STORAGE_CONNECTION_STRING') container_name = environ.get('AZURE_BLOB_CONTAINER') blob = BlobClient.from_connection_s...
Unable to add data:image/jpeg;base64 to docx document with add_picture
I retrieve a base64 image from the azure blob storage and decode it as follows: connection_string = environ.get('AZURE_STORAGE_CONNECTION_STRING') container_name = environ.get('AZURE_BLOB_CONTAINER') blob = BlobClient.from_connection_string(conn_str=connection_string, container_name=container_name, blob_name=f...
[ "As stated by jps in the comments, removing up until the ;base64, part of the data url did the trick before decoding! Case closed\n" ]
[ 0 ]
[]
[]
[ "azure_blob_storage", "base64", "python", "python_docx" ]
stackoverflow_0074194352_azure_blob_storage_base64_python_python_docx.txt
Q: Pause in "for i in range" with in python How can I make a pause in a "for i in range" loop, for example after 100 calls? I have this part of the code: with open(r'url\url.txt', encoding='utf8') as f: for i in range(total_urls): Now I want to make a big pause after 100 calls. All I find is to do time.sleep() o...
Pause in "for i in range" with in python
How can I make a pause in a "for i in range" loop, for example after 100 calls? I have this part of the code: with open(r'url\url.txt', encoding='utf8') as f: for i in range(total_urls): Now I want to make a big pause after 100 calls. All I find is to do time.sleep() or set a random pause between calls, but this i...
[ "Like this?\nwith open(r'url\\url.txt', encoding='utf8') as f:\n for i in range(total_urls):\n if i > 0 and i % 100 == 0:\n time.sleep(100)\n\n" ]
[ 3 ]
[]
[]
[ "loops", "pause", "python" ]
stackoverflow_0074204568_loops_pause_python.txt
Q: how can i solve tabulate issue in python? I currently use this code: tabulate.WIDE_CHARS_MODE = False def test(): conn = pymysql.connect(host=rds_host, user=name, password=password, db=db_name, charset='utf8') curs = conn.cursor(pymysql.cursors.DictCursor) sql = "query" curs.execute(sql) da = ...
how can i solve tabulate issue in python?
I currently use this code: tabulate.WIDE_CHARS_MODE = False def test(): conn = pymysql.connect(host=rds_host, user=name, password=password, db=db_name, charset='utf8') curs = conn.cursor(pymysql.cursors.DictCursor) sql = "query" curs.execute(sql) da = curs.fetchall() df = pd.DataFrame(data=da, ...
[ "You can use some python library to make any dt of the same length.\nIf you use:\ndf['1'] = df['1'].center(10,' ')\n\nYou will get any data string inserted with a length of 10 character, centered on your string, before and after filled with blank space\n" ]
[ 0 ]
[]
[]
[ "python", "tabulate" ]
stackoverflow_0074202803_python_tabulate.txt
Q: Replace the single quote (') character from a string I need to strip the character "'" from a string in python. How do I do this? I know there is a simple answer. Really what I am looking for is how to write ' in my code. for example \n = newline. A: As for how to represent a single apostrophe as a string in P...
Replace the single quote (') character from a string
I need to strip the character "'" from a string in python. How do I do this? I know there is a simple answer. Really what I am looking for is how to write ' in my code. for example \n = newline.
[ "As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes (\"'\") or you can escape it inside single quotes ('\\'').\nTo remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:\n>>> \"didn't\".repla...
[ 106, 17, 2, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003151146_python_string.txt
Q: What does arr.sort(key=lambda x: x:(x[0],int(x[1]),int(x[2])) 's lambda function write in def function? Here is a question which I understand the lambda function work ,but can't rewrite to def function. example: lst= [(2, 2), (3, 4), (4, 1), (1, 3)] lst.sort(key= lambda x:(x[0])) like def takeSecond(elem): retur...
What does arr.sort(key=lambda x: x:(x[0],int(x[1]),int(x[2])) 's lambda function write in def function?
Here is a question which I understand the lambda function work ,but can't rewrite to def function. example: lst= [(2, 2), (3, 4), (4, 1), (1, 3)] lst.sort(key= lambda x:(x[0])) like def takeSecond(elem): return elem[1] lst= [(2, 2), (3, 4), (4, 1), (1, 3)] lst.sort(key=takeSecond) but How is the below lambda to rew...
[ "The only difference involved here is that lambdas return their expression implicitly. So just use the same code, with explicit return:\ndef key_on_three(x):\n return x[0], int(x[1]), int(x[2])\n\nlst.sort(key=key_on_three)\n\nBecause of the lack of ambiguity, it's safe to omit the parentheses around the three v...
[ 1 ]
[]
[]
[ "lambda", "python", "sorting", "tuples" ]
stackoverflow_0074204620_lambda_python_sorting_tuples.txt
Q: pd.to_datetime producing "Reindexing only valid with uniquely valued Index objects" I'm getting quite an unexpected behaviour using pandas' pd.to_datetime. My pd.Series is as follows: 0 2017-01-06 14:37:16 1 2017-01-27 00:00:00 2 2017-01-18 00:00:00 3 2017-01-26 00:00:00 4 ...
pd.to_datetime producing "Reindexing only valid with uniquely valued Index objects"
I'm getting quite an unexpected behaviour using pandas' pd.to_datetime. My pd.Series is as follows: 0 2017-01-06 14:37:16 1 2017-01-27 00:00:00 2 2017-01-18 00:00:00 3 2017-01-26 00:00:00 4 None ... 454823 2019-10-22 11:20:03 454824 ...
[ "The error you are receiving isn't related to your Index. It's related to this issue which should have been fixed as of 0.25.0. The issue was related to the following inconsistent handling of multiple null types when using pd.to_datetime\nimport pandas as pd\n\npd.core.algorithms.unique([pd.NaT, None])\n#array([NaT...
[ 25, 3, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0058595395_pandas_python.txt
Q: Python error vision-1.0.0-py3.10-nspkg.pth: Whenever I run python I get this error message: Error processing line 1 of D:\Users\RBS\AppData\Local\Programs\Python\Python310\lib\site-packages\vision-1.0.0-py3.10-nspkg.pth: Traceback (most recent call last): File "D:\Users\RBS\AppData\Local\Programs\Python\Python310\...
Python error vision-1.0.0-py3.10-nspkg.pth:
Whenever I run python I get this error message: Error processing line 1 of D:\Users\RBS\AppData\Local\Programs\Python\Python310\lib\site-packages\vision-1.0.0-py3.10-nspkg.pth: Traceback (most recent call last): File "D:\Users\RBS\AppData\Local\Programs\Python\Python310\lib\site.py", line 186, in addpackage exec(line) ...
[ "Sounds a lot like what I saw at: AttributeError: 'NoneType' object has no attribute 'loader'\nBased on their comments what worked for me was going to C:\\Users\\\"username\"\\anaconda3\\envs\\\"Project name\" then looking for a file called \"vision-1.0.0-py3.7-nspkg.pth\" and deleting it.\nRan into this post befor...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074094194_python.txt
Q: How to write a program that takes the standard deviation of a list of numbers by defining a function? This is a homework assignment that asks to define a function stddev(xs) that calculates the standard deviation of a list of numbers. (Standard deviation is found by taking the square root of the sum of the mean su...
How to write a program that takes the standard deviation of a list of numbers by defining a function?
This is a homework assignment that asks to define a function stddev(xs) that calculates the standard deviation of a list of numbers. (Standard deviation is found by taking the square root of the sum of the mean subtracted from each number in the list divided by the total number of terms.) I wrote a separate function wh...
[ "The main mistake\nYou forgot to take the absolute value. The variance and standard deviation are not a sum of differences, but rather, a sum of distances, or absolute differences.\nReplace the following line:\nsum = sum + (xs[i] - average)\n\nwith:\nsum = sum + abs(xs[i] - average)\n\nOther comments\nShadowing bui...
[ 1 ]
[]
[]
[ "function", "list", "math", "python", "standard_deviation" ]
stackoverflow_0074202671_function_list_math_python_standard_deviation.txt
Q: Change value based on condition in whole dataframe with multiple columns I have a dataframe with multiple columns. I know to change the value based on condition for one specific column. But how can I change the value based on condition over all columns for the whole dataframe? I want to replace // with 1 col1;col2...
Change value based on condition in whole dataframe with multiple columns
I have a dataframe with multiple columns. I know to change the value based on condition for one specific column. But how can I change the value based on condition over all columns for the whole dataframe? I want to replace // with 1 col1;col2;col3;col4; 23;54;12;//; 54;//;2;//; 8;2;//;1;
[ "Let's try\ndf = df.replace('//', 1)\n# or\ndf = df.mask(df.eq('//'), 1)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074204750_pandas_python.txt
Q: Upload multiple files pandas I need help, I can't figure out what I need to do. The task is as follows, I need to be able to select multiple xlsx files and convert them to csv. In my code I got the ability to do this with only one file. I hope for your help and advice. Thanks path_file = sg.popup_get_file('Choose...
Upload multiple files pandas
I need help, I can't figure out what I need to do. The task is as follows, I need to be able to select multiple xlsx files and convert them to csv. In my code I got the ability to do this with only one file. I hope for your help and advice. Thanks path_file = sg.popup_get_file('Choose files', ...
[ "Without option no_window=True, it will return None or str-type filepaths with separator ';' between each file_path.\nimport PySimpleGUI as sg\n\npath_files = sg.popup_get_file(\n 'Choose files',\n title='Choose files',\n file_types=(('Excel Files', '*.xlsx'),),\n multiple_files=True,\n)\nif path_files:...
[ 0 ]
[]
[]
[ "pandas", "pysimplegui", "python" ]
stackoverflow_0074190181_pandas_pysimplegui_python.txt
Q: how to pass the result of one function to another? i am beginner of python and i have a question. How to pass the result of one function to another one. I want to make new list based on first one only with prime digits, and when i run my program second list is empty def get_list_of_int_numbers(n: int): list1 =...
how to pass the result of one function to another?
i am beginner of python and i have a question. How to pass the result of one function to another one. I want to make new list based on first one only with prime digits, and when i run my program second list is empty def get_list_of_int_numbers(n: int): list1 = [random.randint(10, 100) for x in range(random.randint(...
[ "Problem is in your get_second_list_based_on_old_one_with_prime_digits, you don't need to use n to compare with the result of get_prime_digits\ndef get_second_list_based_on_old_one_with_prime_digits(expression: list) -> list:\n list2 = [n for n in expression if n == get_prime_digits(n)]\n # ...
[ 0, 0, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074197996_function_list_python.txt
Q: How should I write custom install and uninstall nsis for electron builder? hello, I am building an electron app. I need to do 2 things while installing the app 1.set custom installation path here is the the code how I done the first step !macro preInit SetRegView 64 WriteRegExpandStr HKLM "${INSTALL_REGISTRY_K...
How should I write custom install and uninstall nsis for electron builder?
hello, I am building an electron app. I need to do 2 things while installing the app 1.set custom installation path here is the the code how I done the first step !macro preInit SetRegView 64 WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Windows\BSD" WriteRegExpandStr HKCU "${INSTALL_REGIST...
[ "I done it by myself\nResources: https://www.electron.build/configuration/nsis.html#custom-nsis-script\nHere is the code\n!macro preInit\n SetRegView 64\n WriteRegExpandStr HKLM \"${INSTALL_REGISTRY_KEY}\" InstallLocation \"C:\\Windows\\BSD\"\n WriteRegExpandStr HKCU \"${INSTALL_REGISTRY_KEY}\" InstallLocation \"...
[ 0 ]
[]
[]
[ "electron", "electron_builder", "nsis", "python" ]
stackoverflow_0074203502_electron_electron_builder_nsis_python.txt
Q: Pillow - Efficiently write texts to multiple images and then convert them into PDF this is my first stackoverflow question. I would like to write some texts into two A4 size images, and then convert those images into a 2 pages PDF in a loop. Just yesterday, I got in touch with Python Pillow and succesfully add tex...
Pillow - Efficiently write texts to multiple images and then convert them into PDF
this is my first stackoverflow question. I would like to write some texts into two A4 size images, and then convert those images into a 2 pages PDF in a loop. Just yesterday, I got in touch with Python Pillow and succesfully add texts to images and saved it to disk. I was thinking to save me a Disk Read/Write by doing ...
[ "You can write a PDF directly with PIL. First make a list of pages, each one containing a PIL Image, then write them all:\n#!/usr/bin/env python3\n\nfrom PIL import Image\n\n# Set dimensions\nh, w = 3000, 2400\n\n# Make list of pages, add as many as you like\npages = []\npages.append(Image.new('RGB', (w, h), 'red')...
[ 0 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0074202637_image_processing_python_python_imaging_library.txt
Q: Formatting todays date in python as date type I'm trying to get todays date in the format %d/%m/%y without converting to a string. I still want to have the date as the data type. Following code returns an str today = date.today().strftime('%d/%m/%y') print(type(today)) A: This is the right way to achiev...
Formatting todays date in python as date type
I'm trying to get todays date in the format %d/%m/%y without converting to a string. I still want to have the date as the data type. Following code returns an str today = date.today().strftime('%d/%m/%y') print(type(today))
[ "This is the right way to achieve your goal:\nfrom datetime import date\n\ntoday = date.today()\ntoday_string = today.strftime('%d/%m/%Y')\n\nprint(type(today))\nprint(today_string)\n\nOutput:\n<class 'datetime.date'>\n26/10/2022\n\nTo change the date class default format:\nmydatetime.py\nfrom datetime import datet...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074204192_python.txt
Q: parameters/fields for odoo's default change password form for update for an existing mobile app i want to create api through controller to communicate with odoo, i know about login fields/parameters {"jsonrpc": "2.0","params":{"db":"odoodb","login":"myemail@smtpserver.com","password":"admin123"}} for which api al...
parameters/fields for odoo's default change password form for update
for an existing mobile app i want to create api through controller to communicate with odoo, i know about login fields/parameters {"jsonrpc": "2.0","params":{"db":"odoodb","login":"myemail@smtpserver.com","password":"admin123"}} for which api already have created, but now i want to know about odoo's default change pas...
[ "You can use this url to change the password of the user.\n\nBut the user must be logged to an Odoo session in the request headers\n\nhttp://localhost:8069/my/security\n\nYou can send the params through GET or POST:\nold = Old password \nnew1 = New password \nnew2 = Re-enter new Password\n\nSee the code in the web ...
[ 1, 0 ]
[]
[]
[ "api", "passwords", "python" ]
stackoverflow_0066151298_api_passwords_python.txt
Q: How to read pairwise csv and json files having same names inside a folder using python? Consider my folder structure having files in these fashion:- abc.csv abc.json bcd.csv bcd.json efg.csv efg.json and so on i.e. a pair of csv files and json files having the same names, i have to perform the same operation by r...
How to read pairwise csv and json files having same names inside a folder using python?
Consider my folder structure having files in these fashion:- abc.csv abc.json bcd.csv bcd.json efg.csv efg.json and so on i.e. a pair of csv files and json files having the same names, i have to perform the same operation by reading the same named files , do some operation and proceed to the next pair of files. How do...
[ "Did you think of something like this?\nimport os\n\n# collects filenames in the folder\nfilelist = os.listdir()\n# iterates through filenames in the folder\nfor file in filelist:\n# pairs the .csv files with the .json files\n if file.endswith(\".csv\"):\n with open(file) as csv_file:\n pre, ex...
[ 1, 1, 1 ]
[]
[]
[ "csv", "file", "json", "pandas", "python" ]
stackoverflow_0074204648_csv_file_json_pandas_python.txt
Q: No resources of this type found under this subscription Azure Logic Apps I tried to create a workflow using Azure Logic Apps, I used Recurrence as my trigger (Daily) and Azure Function (Timer Trigger) as my Process to create some dataframe and export to csv, and both of them Dataframe, and CSV file need to send it...
No resources of this type found under this subscription Azure Logic Apps
I tried to create a workflow using Azure Logic Apps, I used Recurrence as my trigger (Daily) and Azure Function (Timer Trigger) as my Process to create some dataframe and export to csv, and both of them Dataframe, and CSV file need to send it via email. At first, I use SMTP in my Azure Function, but it got an error whe...
[ "We have tested this in our local environment , Below analysis are based on our observations.\nIn our local environment , we have created a logic app of both consumption based & standard based with recurrence as trigger tried to call AZURE function from the logic apps.\n\nIf you are trying to add existing azure...
[ 1, 0 ]
[]
[]
[ "azure", "azure_functions", "azure_logic_apps", "python", "smtp" ]
stackoverflow_0070526679_azure_azure_functions_azure_logic_apps_python_smtp.txt
Q: Python: The _imagingft C module is not installed I've tried lots of solution that posted on the net, they don't work. >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> So the system can find the _imaging but still can't use truetype font from PIL import Image, Ima...
Python: The _imagingft C module is not installed
I've tried lots of solution that posted on the net, they don't work. >>> import _imaging >>> _imaging.__file__ 'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd' >>> So the system can find the _imaging but still can't use truetype font from PIL import Image, ImageDraw, ImageFilter, ImageFont im = Image.new('RGB',...
[ "On Ubuntu, you need to have libfreetype-dev installed before compiling PIL.\ni.e.\n$ sudo apt-get install libfreetype6-dev\n$ sudo -s\n\\# pip uninstall pil\n\\# pip install --no-cache-dir pil\n\nPS! Running pip install as sudo will usually install packages to /usr/local/lib on most Ubuntu versions. You may consid...
[ 85, 57, 54, 17, 14, 12, 12, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0004011705_image_python_python_imaging_library.txt
Q: How to mock redshift queries integration test in Python and Pytest I have Python code that looks like this: db = de_core.db.redshift.get_connection() ... query = get_query(f"export_user_{user_component}").render() result = util.execute_query(db, query, user_id=user_id) And it actually executes sql. I want to writ...
How to mock redshift queries integration test in Python and Pytest
I have Python code that looks like this: db = de_core.db.redshift.get_connection() ... query = get_query(f"export_user_{user_component}").render() result = util.execute_query(db, query, user_id=user_id) And it actually executes sql. I want to write an integration test that tests this sql. The sql is Redshift flavored ...
[ "In general, mocking a database requires the database engine to run somewhere to execute your SQL.\nThat is why things like test-containers or embedded-postgres exist. Traditional apps would use these for their integration testing.\nBut as you noted Redshift is Posgtres-flavored, so if your code is Redshift-specifi...
[ 0 ]
[]
[]
[ "amazon_redshift", "pytest", "python" ]
stackoverflow_0074141935_amazon_redshift_pytest_python.txt
Q: Convert numpy array full of time deltas to hours I have a numpy array full of timedeltas I want to be able to convert them to hours. print(times_arr) array([datetime.timedelta(seconds=28800), datetime.timedelta(seconds=30600), datetime.timedelta(seconds=23400), datetime.timedelta(seconds=270...
Convert numpy array full of time deltas to hours
I have a numpy array full of timedeltas I want to be able to convert them to hours. print(times_arr) array([datetime.timedelta(seconds=28800), datetime.timedelta(seconds=30600), datetime.timedelta(seconds=23400), datetime.timedelta(seconds=27000), datetime.timedelta(seconds=23400), ...
[ "Convert to timedelta64[m] dtype, then go from there:\narr.astype('timedelta64[m]').astype(int) / 60\n# array([8. , 8.5, 6.5, 7.5, 6.5, 6.5, 8.5, 6.5, 7.5, 6.5, 8.5, 7.5, 6.5,\n# 6.5, 8.5, 8. , 6.5])\n\n", "You can divide the total seconds in each timedelta by 3600 to get your desired output.\nnew = np.arr...
[ 2, 0, 0, 0 ]
[]
[]
[ "numpy", "python", "timedelta" ]
stackoverflow_0055625486_numpy_python_timedelta.txt
Q: How to enable GPU for SetFit? I am following this tutorial for SetFit: https://www.philschmid.de/getting-started-setfit When the training is running, it is using my CPU instead of my GPU. Is there a way I can enable it? Here is the main part of the code: from setfit import SetFitModel, SetFitTrainer from sentence_...
How to enable GPU for SetFit?
I am following this tutorial for SetFit: https://www.philschmid.de/getting-started-setfit When the training is running, it is using my CPU instead of my GPU. Is there a way I can enable it? Here is the main part of the code: from setfit import SetFitModel, SetFitTrainer from sentence_transformers.losses import CosineSi...
[ "If your training is running on CPU rather than GPU, it is because:\n\nEither you installed the CPU version of the PyTorch.\nEither the version of CUDA/CUDNN and PyTorch are not compatible, and the training falls back to CPU instead of GPU.\n\nIn essence it has nothing to do with the SetFit model.\nA working exampl...
[ 1 ]
[]
[]
[ "huggingface_transformers", "python", "sentence_transformers" ]
stackoverflow_0074198547_huggingface_transformers_python_sentence_transformers.txt
Q: Squish test functions always pass when used with squishtest module We are using Squish for Qt 6.6.2 on Windows 10 with Python 3.8.7 and running our tests using squishtest module with Robot Framework 4.0.1. We are having an issue with the test functions provided by the Squish API where any verifications done with s...
Squish test functions always pass when used with squishtest module
We are using Squish for Qt 6.6.2 on Windows 10 with Python 3.8.7 and running our tests using squishtest module with Robot Framework 4.0.1. We are having an issue with the test functions provided by the Squish API where any verifications done with such a call (for example squishtest.test.imagePresent) will Pass. The iss...
[ "Have a look at the documented: bool testSettings.throwOnFailure flag.\nIn your robot you can set this and you would not have to patch / rewrite every test.vp, test.compare, ... method.\nWhen running from within the Squish IDE, this flag can be unset. Probably robotframework provides some environment variables to d...
[ 1, 0 ]
[]
[]
[ "python", "squish" ]
stackoverflow_0069314520_python_squish.txt
Q: Why I am getting "Not Implemented Error: Database objects do not implement truth value testing or bool()." while running makemigration cmd in django I am trying to connect Django with MongoDB using Djongo. I have changed the Database parameter but I am getting this error Not Implemented Error: Database objects do ...
Why I am getting "Not Implemented Error: Database objects do not implement truth value testing or bool()." while running makemigration cmd in django
I am trying to connect Django with MongoDB using Djongo. I have changed the Database parameter but I am getting this error Not Implemented Error: Database objects do not implement truth value testing or bool(). when I am running makemigration command. Please can anybody explain why I am getting this error and how to re...
[ "The problem is with the new version of pymongo (4.0 from 29.11.2021) which is not supported by Djongo 1.3.6. You need to install pymongo 3.12.1. I had the same problem 2 hours ago.\n", "The actual problem is with pymongo==4.0.1.\nwhen installing the mongoengine by pip install mongoengine it installs the pymongo=...
[ 68, 16, 7, 6, 2, 0, 0 ]
[ "Try to install django-mongoengine and it will solve the problem for sure.\n" ]
[ -2 ]
[ "django", "djongo", "mongodb", "python" ]
stackoverflow_0070185942_django_djongo_mongodb_python.txt
Q: I need to calculate month-on-month change and change in same month last year from a table fetched from SQL database using python Here how the departure table should look like and the headers: Report_Month Aircraft_Departures(Domestic) Aircraft_Departures(International) MOM Change(domestic) MOM Change(internationa...
I need to calculate month-on-month change and change in same month last year from a table fetched from SQL database using python
Here how the departure table should look like and the headers: Report_Month Aircraft_Departures(Domestic) Aircraft_Departures(International) MOM Change(domestic) MOM Change(international) change_SMLY(Domestic) change_SMLY(International) Here is the code which I have written to get this table from SQL as pivot t...
[ "Create DatetimeIndex first, then use DataFrame.shift by one and 12 months, subtract and divide and last join all DataFrames together:\ncols = ['Aircraft_Departures(Domestic)','Aircraft_Departures(International)']\n\ndf1['Report_Month'] = pd.to_datetime(df1['Report_Month'], dayfirst=True)\ndf = df1.set_index('Repor...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pymssql", "python" ]
stackoverflow_0074190137_dataframe_pandas_pymssql_python.txt
Q: Python, improving speed of multi values stresstest I would like to improve the speed of the following code. The data set is a list of trades that I would like to stresstest, by simulating various parameters and have all the results stored in a table. The way I'm performing this, it's by designing the range of para...
Python, improving speed of multi values stresstest
I would like to improve the speed of the following code. The data set is a list of trades that I would like to stresstest, by simulating various parameters and have all the results stored in a table. The way I'm performing this, it's by designing the range of parameters and then I iterate over their values, I initiate ...
[ "Concatenating pandas dataframes onto one another takes a long time. It's better to create a list of dataframes and then use pd.concat to concatenate them all at once.\nYou can test this yourself like this:\nimport pandas as pd\nimport numpy as np\nfrom time import time\n\ndfs = []\ncolumns = [f\"{i:02d}\" for i in...
[ 2 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0074204900_performance_python.txt
Q: How can I remove "days" when computing the difference between two dates? When computing the difference between two dates using the following: df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']) I get a third column with "x Days". How can I convert "x Days" into int "x". e.g., "50 days" into ...
How can I remove "days" when computing the difference between two dates?
When computing the difference between two dates using the following: df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']) I get a third column with "x Days". How can I convert "x Days" into int "x". e.g., "50 days" into "50"? Someone in a previous thread suggested to use: df_test['Difference'] = (...
[ "If it is a string variable. then you can do the following and strip of the unwanted part. (say your variable is xDays)\ndf[\"xDays\"] = df[\"xDays\"].map(lambda x: x[:-5])\n\nif it is a timedelta value you can do following\ndf[\"xDays\"].dt.days\n\n", "If I stick to your code but fill in with made up data, this ...
[ 7, 0, 0, 0 ]
[]
[]
[ "pandas", "python", "python_2.7", "python_3.x" ]
stackoverflow_0049234502_pandas_python_python_2.7_python_3.x.txt
Q: Need python dictionary to act like deque (have maximum length) Is there any builtin (or very simple) method of having a python dictionary work in a similar fashion as deque. I need it to have a maximum size, and when new keys are added, if the maximum length is reached then the key added first is deleted. It shoul...
Need python dictionary to act like deque (have maximum length)
Is there any builtin (or very simple) method of having a python dictionary work in a similar fashion as deque. I need it to have a maximum size, and when new keys are added, if the maximum length is reached then the key added first is deleted. It shouldn't be too difficult to implement as a custom class, but using buil...
[ "It sounds like a variant of OrderedDict.\nclass FixSizeOrderedDict(OrderedDict):\n def __init__(self, *args, max=0, **kwargs):\n self._max = max\n super().__init__(*args, **kwargs)\n\n def __setitem__(self, key, value):\n OrderedDict.__setitem__(self, key, value)\n if self._max > ...
[ 12, 6, 0 ]
[]
[]
[ "python", "python_3.6" ]
stackoverflow_0049274177_python_python_3.6.txt
Q: Why does my sjoin() return me an emtpy GeoDataFrame? I'm trying to make a join between two GeoDataFrame. The first one gathers the coordinates of points associated with a name. The second one is a set of polygons based on the French cadastre. I would like to be able to join the two GeoDataFrame based on their geog...
Why does my sjoin() return me an emtpy GeoDataFrame?
I'm trying to make a join between two GeoDataFrame. The first one gathers the coordinates of points associated with a name. The second one is a set of polygons based on the French cadastre. I would like to be able to join the two GeoDataFrame based on their geographical relationships. Based on an inner join, the names ...
[ "After getting a good night's sleep, I realized that my points were WGS84 (EPSG:4326) based coordinates so I had set them wrong.\nI changed the coordinates and everything worked fine.\n" ]
[ 1 ]
[]
[]
[ "geopandas", "python" ]
stackoverflow_0074195263_geopandas_python.txt
Q: python how to delete all files whose name is a date in a folder I have a folder with two categories of folder naming 1st category folders are the ones that naming is a date 2nd category folder are the one that has a fixed name 'master'. Please refer to below screenshot. How can I remove the all the 'date' folders...
python how to delete all files whose name is a date in a folder
I have a folder with two categories of folder naming 1st category folders are the ones that naming is a date 2nd category folder are the one that has a fixed name 'master'. Please refer to below screenshot. How can I remove the all the 'date' folders and keep the 'master' folder by python? Before I use below code to d...
[ "Use os package to list folders\nTry this code:\nimport os\nimport shutil\n\nparent_dir = '../../test/subtest/'\nmy_list = os.listdir(parent_dir)\nfor sub_dir in my_list:\n if sub_dir != 'master':\n print(\"deleting folder: \" + sub_dir)\n try:\n shutil.rmtree(parent_dir + sub_dir)\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074204824_python.txt
Q: Python Pillow - RLE compression of BMP image I'm working on a script, which builds an image, combines it with another image and saves it locally as an 8-bit BMP-file. The image is then read by a ESP32 microcontroller, but the problem is that due to memorylimitations, the allowed file size is somewhat limited. As a...
Python Pillow - RLE compression of BMP image
I'm working on a script, which builds an image, combines it with another image and saves it locally as an 8-bit BMP-file. The image is then read by a ESP32 microcontroller, but the problem is that due to memorylimitations, the allowed file size is somewhat limited. As a consequence, I made a BMP decoder for the ESP32, ...
[ "Pillow does not support writing BMP files with compression, which can be determined by investigating the source. BmpImagePlugin._write:\n # bitmap info header\n fp.write(\n o32(header) # info header size\n + o32(im.size[0]) # width\n + o32(im.size[1]) # height\n + o16(1) # pla...
[ 2, 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074194290_python_python_imaging_library.txt
Q: how to stop the loop in while in python? i tried to do a while loop in which after the user inputs 'no' then the loop will stop and end the program but it did not work and i can't find the problem finish = True while (finish) : kg = float(input('Enter kg: ')) total = kg * 2.2 print('The converted kg is...
how to stop the loop in while in python?
i tried to do a while loop in which after the user inputs 'no' then the loop will stop and end the program but it did not work and i can't find the problem finish = True while (finish) : kg = float(input('Enter kg: ')) total = kg * 2.2 print('The converted kg is: ', total, 'lbs') question = input('do yo...
[ "The problem here is that your identation is off. The if/else statement is not ran inside the loop but after it. Modify your code like so:\nfinish = True\nwhile (finish) :\n kg = float(input('Enter kg: '))\n total = kg * 2.2\n print('The converted kg is: ', total, 'lbs')\n question = input('do you want ...
[ 1, 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074204918_python_while_loop.txt
Q: XML Python output not as expected (EAD & DC) Hello dear Overflowers, I work mainly with Python processing XMLs, mostly EAD but in this case DC. I have to make a comparsion of two datasets 1. EAD and 2. DC. The goal is to remove all duplicates from the DC-dataset based on a list of EAD-IDs. The DC-file looks like t...
XML Python output not as expected (EAD & DC)
Hello dear Overflowers, I work mainly with Python processing XMLs, mostly EAD but in this case DC. I have to make a comparsion of two datasets 1. EAD and 2. DC. The goal is to remove all duplicates from the DC-dataset based on a list of EAD-IDs. The DC-file looks like this and has a relatively flat hierarchy: NOTE: the...
[ "Dear Overflowers and @Parfait,\nThe mistake lies in the last chunk of Code.\nif dc_record_id_txt in line.strip():\n if dc_record.getparent() is not None:\n dc_record.getparent().remove(dc_record)\n\nin the sector if dc_record_id_txt in line.strip(): it should not be \"in\" it shou...
[ 0 ]
[]
[]
[ "dc", "python", "xml" ]
stackoverflow_0074194656_dc_python_xml.txt
Q: Double free or corruption (!prev) but in python cI am using pygame on repl.it, and as far as I can tell from digging around, this error usually coms from a c or c++ compiler when you attempt to free the same memory twice, but this is python, and it seems to be a repl.it thing because the error doesn't happen in at...
Double free or corruption (!prev) but in python
cI am using pygame on repl.it, and as far as I can tell from digging around, this error usually coms from a c or c++ compiler when you attempt to free the same memory twice, but this is python, and it seems to be a repl.it thing because the error doesn't happen in atom using my python install. This is the full error fo...
[ "I've done a lot of debugging and I think I know what the problem is, because of faulty conversion from precise float coordinates to array coordinates a negative result can sometimes be outputed, or worse but this doesn't seem to bother pygame as much, a slice can be taken where the upper coordinate is lower than t...
[ 0 ]
[]
[]
[ "double_free", "pygame", "python", "repl.it", "sigabrt" ]
stackoverflow_0074152453_double_free_pygame_python_repl.it_sigabrt.txt