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: How to put/stream data into an Excel file on sftp What works With the following code, I can write the content of TheList into a CSV on an SFTP. import paramiko import csv # code part to make and open sftp connection TheList = [['name', 'address'], [ 'peter', 'london']] with sftp.open(SftpPath + "anewfile.csv", ...
How to put/stream data into an Excel file on sftp
What works With the following code, I can write the content of TheList into a CSV on an SFTP. import paramiko import csv # code part to make and open sftp connection TheList = [['name', 'address'], [ 'peter', 'london']] with sftp.open(SftpPath + "anewfile.csv", mode='w', bufsize=32768) as csvfile: writer = csv.w...
[ "You need to close the Workbook. Either using the with statement:\nwith sftp.open(SftpPath + \"anewfile.xlsx\", mode='wb', bufsize=32768) as f, \\\n xlsxwriter.Workbook(f) as workbook:\n worksheet = workbook.add_worksheet()\n for row_num, data in enumerate(TheList):\n worksheet.write_row(row_num, 0...
[ 2 ]
[]
[]
[ "paramiko", "python", "sftp", "xlsxwriter" ]
stackoverflow_0074472747_paramiko_python_sftp_xlsxwriter.txt
Q: How do I add Multiple Python Interactive Windows in VS Code? I am trying to create a second Ipython window in my VS Code Environment. A: Sorry to say, but currently there can only be one Interactive Window open at a time. We do have an issue filed on allowing multiple windows here: https://github.com/Microsoft/v...
How do I add Multiple Python Interactive Windows in VS Code?
I am trying to create a second Ipython window in my VS Code Environment.
[ "Sorry to say, but currently there can only be one Interactive Window open at a time. We do have an issue filed on allowing multiple windows here:\nhttps://github.com/Microsoft/vscode-python/issues/3104\nWhich you can upvote or comment on if you would like. \n", "The response above is longer up-to-date. Now, VS c...
[ 6, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0055719899_python_visual_studio_code.txt
Q: Python: Get multiple id's from checkbox I wanted to get multiple id's from a list using checkbox. I got an error Field 'id' expected a number but got []. Below is my code. sample.html <button href="/sample/save">Save</button> {% for obj in queryset %} <tr> <td><input type="checkbox" name="sid" value="{{obj.i...
Python: Get multiple id's from checkbox
I wanted to get multiple id's from a list using checkbox. I got an error Field 'id' expected a number but got []. Below is my code. sample.html <button href="/sample/save">Save</button> {% for obj in queryset %} <tr> <td><input type="checkbox" name="sid" value="{{obj.id}}"></td> <td>{{ obj.sample_name }}</td>...
[ "the field id should be int you passed a list, that's why you got error:\n\nField 'id' expected a number but got [].\n\nHere you can use the in Filed lookup\nTry this\nsample = SampleList.objects.filter(id__in=sid)[0:10]\n\nthis will show all the SampleList items with the id's in sid\nUpdate\nChange your context to...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074473135_django_html_python.txt
Q: ValueError: cannot switch from manual field specification to automatic field numbering The class: class Book(object): def __init__(self, title, author): self.title = title self.author = author def get_entry(self): return "{0} by {1} on {}".format(self.title, self.author, self.press...
ValueError: cannot switch from manual field specification to automatic field numbering
The class: class Book(object): def __init__(self, title, author): self.title = title self.author = author def get_entry(self): return "{0} by {1} on {}".format(self.title, self.author, self.press) Create an instance of my book from it: In [72]: mybook = Book('HTML','Lee') In [75]: mybo...
[ "return \"{0} by {1} on {}\".format(self.title, self.author, self.press)\n\nthat doesn't work. If you specify positions, you have to do it through the end:\nreturn \"{0} by {1} on {2}\".format(self.title, self.author, self.press)\n\nIn your case, best is to leave python treat that automatically:\nreturn \"{} by {} ...
[ 62, 2, 1, 0 ]
[]
[]
[ "python", "python_3.x", "string_formatting" ]
stackoverflow_0046768088_python_python_3.x_string_formatting.txt
Q: How to conditionally declare code according to Python version in Cython? I have the following pxd header which augments a regular Python module: #!/usr/bin/env python # coding: utf-8 cimport cython @cython.locals(media_type=unicode, format=unicode, charset=unicode, render_style=unicode) cdef class BaseRenderer(o...
How to conditionally declare code according to Python version in Cython?
I have the following pxd header which augments a regular Python module: #!/usr/bin/env python # coding: utf-8 cimport cython @cython.locals(media_type=unicode, format=unicode, charset=unicode, render_style=unicode) cdef class BaseRenderer(object): """ All renderers should extend this class, setting the `media...
[ "The Python version constants are in https://github.com/cython/cython/blob/master/Cython/Includes/cpython/version.pxd\nYou can include them with cimport cpython.version and use them with either compile time IF or a runtime if.\nBe careful, if you want to distribute the C code without requiring to install Cython usi...
[ 5, 0 ]
[]
[]
[ "cython", "python", "python_2.7", "python_3.x" ]
stackoverflow_0028299202_cython_python_python_2.7_python_3.x.txt
Q: not showing error to indicating missing keys in dictionary using python I am trying the below code to find missing keys in dictionary. It should function like if the user tries to access a missing key, an error need to popped indicating missing keys. # missing value error # initializing Dictionary d = { 'a' : 1 , ...
not showing error to indicating missing keys in dictionary using python
I am trying the below code to find missing keys in dictionary. It should function like if the user tries to access a missing key, an error need to popped indicating missing keys. # missing value error # initializing Dictionary d = { 'a' : 1 , 'b' : 2 } # trying to output value of absent key print ("The value associat...
[ "In the above example, no key named ‘c’ in the dictionary popped a runtime error. To avoid such conditions, and to make the aware user that a particular key is absent or to pop a default message in that place, we can use get()\nget(key,def_val) method is useful when we have to check for the key. If the key is prese...
[ 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074470570_dictionary_python.txt
Q: Pandas merging rows on two unique column values I have problem that I have been trying to find a solution for. You would think that it wouldn't be that hard to figure out. I have a pandas DataFrame with the below format: Id Name Now Then There Sold Needed 0 1 Caden 8.1 ...
Pandas merging rows on two unique column values
I have problem that I have been trying to find a solution for. You would think that it wouldn't be that hard to figure out. I have a pandas DataFrame with the below format: Id Name Now Then There Sold Needed 0 1 Caden 8.1 3.40 3.95 NaN NaN 1 7 Bankis...
[ "here is one way to do it\n# using groupby on Id, backfill the Sold and Needed where values are null\ndf[['Sold','Needed']] = df.groupby(['Id'], as_index=False)[['Sold','Needed']].bfill()\n\n# drop the rows that has Null in a name\nout=df.dropna(subset='Name')\n\nout\n\n\nId Name Now Then There Sold ...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "nan", "pandas", "python", "row" ]
stackoverflow_0074467918_dataframe_nan_pandas_python_row.txt
Q: How to implement a Priority Queue in numba where one element of the item is a list of tuples? I am trying to create the PriorityQueue in numba for a very specific task. To achieve that, I need the nodes to have an element which is list of tuples. However, when I try to do that, it raises an error that I don't unde...
How to implement a Priority Queue in numba where one element of the item is a list of tuples?
I am trying to create the PriorityQueue in numba for a very specific task. To achieve that, I need the nodes to have an element which is list of tuples. However, when I try to do that, it raises an error that I don't understand. (Most of the implementation of PriorityQueue taken from How can I implement a numba jitted ...
[ "The problem is that the inferred type for a Python list is a reflected list, but your lists are Numba typed lists. If you do:\nq.put(5.0, 1, nb.typed.List([(0, 1)]))\nq.put(2.0, 2, nb.typed.List([(0, 1), (1, 2)]))\nq.put(3.0, 3, nb.typed.List([(0, 1), (0, 1), (1, 1)]))\n\nthen your code runs to completion and prod...
[ 2 ]
[]
[]
[ "numba", "priority_queue", "python", "types" ]
stackoverflow_0074469770_numba_priority_queue_python_types.txt
Q: Intel Vtune cannot find python source file This is an old problem as is demonstrated as in https://community.intel.com/t5/Analyzers/Unable-to-view-source-code-when-analyzing-results/td-p/1153210. I have tried all the listed methods, none of them works, and I cannot find any more solutions on the internet. Basicall...
Intel Vtune cannot find python source file
This is an old problem as is demonstrated as in https://community.intel.com/t5/Analyzers/Unable-to-view-source-code-when-analyzing-results/td-p/1153210. I have tried all the listed methods, none of them works, and I cannot find any more solutions on the internet. Basically vtune cannot find the custom python source fil...
[ "VTune offer full support for profiling python code and the tool should be able to display the source code in your python file as you expected. Could you please check if the function you are expecting to see in the VTune results, ran long enough?\nJust to confirm that everything is working fine, I wrote a matrix mu...
[ 0 ]
[]
[]
[ "intel", "intel_vtune", "profiling", "python" ]
stackoverflow_0065447496_intel_intel_vtune_profiling_python.txt
Q: KeyError: "None of [Index(['...', '...'], dtype='object')] are in the [index]" Can someone helps in identifying the problem ? I have written this code below, and then import numpy as np import pandas as pd retail = pd.read_csv('online_retail2.csv') retail.groupby(['Country','Description'])['Quantity','Price'].agg...
KeyError: "None of [Index(['...', '...'], dtype='object')] are in the [index]"
Can someone helps in identifying the problem ? I have written this code below, and then import numpy as np import pandas as pd retail = pd.read_csv('online_retail2.csv') retail.groupby(['Country','Description'])['Quantity','Price'].agg([np.mean,max]) retail.loc[('Australia','DOLLY GIRL BEAKER'),('Quantity','mean')] T...
[ "I think it's because you are not saving the result of groupby+aggregation to a new variable (groupby+aggregation is not an inplace operation, i.e. it will create a new dataframe and you need to save it otherwise it will just compute and print the result). Basically with your current code you're trying to index you...
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074472853_pandas_python_python_3.x.txt
Q: AttributeError: 'numpy.float64' object has no attribute 'cpu' I am trying to run BERT and train a model using pytorch. I am not sure why I am getting this error after finishing the first Epoch. I am using this code link history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): # Show deta...
AttributeError: 'numpy.float64' object has no attribute 'cpu'
I am trying to run BERT and train a model using pytorch. I am not sure why I am getting this error after finishing the first Epoch. I am using this code link history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): # Show details print(f"Epoch {epoch + 1}/{EPOCHS}") print("-" * 10) ...
[ "I checked kaggle link and I see that there is no cpu() reference as you have posted in your code. It should simply be:\nhistory['train_acc'].append(train_acc)\nhistory['train_loss'].append(train_loss)\nhistory['val_acc'].append(val_acc)\nhistory['val_loss'].append(val_loss)\n\n" ]
[ 1 ]
[]
[]
[ "bert_language_model", "python", "pytorch" ]
stackoverflow_0074473271_bert_language_model_python_pytorch.txt
Q: Run and follow remote Python script execution from Django website I am running a Django website where user can perform some light calculation. This website is hosted in a Docker container on one of our server. I would like now to add the ability for the users to run some more complicated simulations from the same ...
Run and follow remote Python script execution from Django website
I am running a Django website where user can perform some light calculation. This website is hosted in a Docker container on one of our server. I would like now to add the ability for the users to run some more complicated simulations from the same website. These simulations will have to run on a dedicated calculation ...
[ "\"Best\" depends on lots of local decisions that we can't help with.\nDjango can use Python subprocess to execute any Linux shell command. So once you decide on how to submit a job to the local machine from the command line, you can do it from your server. (Note, it may need a way to specify a linux user correspon...
[ 1 ]
[]
[]
[ "django", "hpc", "python" ]
stackoverflow_0074468489_django_hpc_python.txt
Q: JavaScript: Parse python class I upload python file with a python class(react form). myfile.py class MyClass(): """ a: string - parameter a """ Is there any way I can get an annotation or list parans from the file with class using javascript? (without regexp) A: If you insist on not using regex, there are only ...
JavaScript: Parse python class
I upload python file with a python class(react form). myfile.py class MyClass(): """ a: string - parameter a """ Is there any way I can get an annotation or list parans from the file with class using javascript? (without regexp)
[ "If you insist on not using regex, there are only one other way : parse the file using a python parser.\nYou can do it in pure Javascript. It may be possible for example with dt-python-parser to visitor the nodes you are interested in, but I have not tested it.\nOr you can use Python code. Either you call your own ...
[ 0 ]
[]
[]
[ "javascript", "parsing", "python" ]
stackoverflow_0074458913_javascript_parsing_python.txt
Q: How to remove the all values of a specific person from dataframe which is not continuous based on date time date consumption customer_id 2018-01-01 12 111 2018-01-02 12 111 *2018-01-03* 14 111 *2018-01-05* 12 111 2018-01-06 45 111...
How to remove the all values of a specific person from dataframe which is not continuous based on date time
date consumption customer_id 2018-01-01 12 111 2018-01-02 12 111 *2018-01-03* 14 111 *2018-01-05* 12 111 2018-01-06 45 111 2018-01-07 34 111 2018-01-01 23 112 2018-01-02 23 112 2018-01-...
[ "You can compute the successive delta and check if any is greater than 1d:\ndrop = (pd.to_datetime(df['date'])\n .groupby(df['customer_id'])\n .apply(lambda s: s.diff().gt('1d').any())\n )\n\nout = df[df['customer_id'].isin(drop[~drop].index)]\n\nOr with groupby.filter:\ndf['date'] = pd.to_d...
[ 0 ]
[]
[]
[ "data_preprocessing", "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074473320_data_preprocessing_dataframe_datetime_pandas_python.txt
Q: Compare tables A and B, and if there are duplicate values, insert the code defined in table B I am trying to compare the following two tables. After comparing the words in table B with the words in table A, I want to put the code of the overlapping value in the empty Code column of table A. Since it is not case-se...
Compare tables A and B, and if there are duplicate values, insert the code defined in table B
I am trying to compare the following two tables. After comparing the words in table B with the words in table A, I want to put the code of the overlapping value in the empty Code column of table A. Since it is not case-sensitive, I want to change all words to lower case before proceeding with the comparison. If they do...
[ "First create a new column with the lower case\nthen just do a standard merge\ndf3 = pd.merge(\n df1,\n df2,\n how = 'left',\n on = 'cat',\n suffixes = ['_x', '']\n )[['Code', 'Title_x']].rename(columns = {'Title_x': 'Title'})\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074473396_dataframe_pandas_python.txt
Q: How to loop forward and backward in a range in python? enter image description here I want to program motion as described in the drawing above. The angle changes according to this equation:theta = Amp*np.sin(2*np.pi*ftheta*p) . I am looping through p(time) and that is the only variable in this equation, nothing el...
How to loop forward and backward in a range in python?
enter image description here I want to program motion as described in the drawing above. The angle changes according to this equation:theta = Amp*np.sin(2*np.pi*ftheta*p) . I am looping through p(time) and that is the only variable in this equation, nothing else changes. How do i make it stop once it reaches the amplit...
[ "have you tried to write some code yourself? If it is so, please share so we can help.\nAs far as I understood while loop can work for you:\nexit_flag = 0\ntime = 0\ntheta = 0\namplitude = 1\nwhile(exit_flag == 0):\n if(amplitude > 0):\n time = time + 1\n else:\n time = time - 1\n \n theta...
[ 0, 0 ]
[]
[]
[ "angle", "loops", "python" ]
stackoverflow_0074472274_angle_loops_python.txt
Q: can I 'inner-search' most similar vectors within a FAISS index? I have a FAISS index populated with 8M embedding vectors. I don't have the embedding vectors anymore, only the index, and it is expensive to recompute the embeddings. Can I search the index for the top-k most similar vectors to each of the index's vec...
can I 'inner-search' most similar vectors within a FAISS index?
I have a FAISS index populated with 8M embedding vectors. I don't have the embedding vectors anymore, only the index, and it is expensive to recompute the embeddings. Can I search the index for the top-k most similar vectors to each of the index's vectors? To be more concrete, say this is how my index was populated: d ...
[ "First of all seems like you forgot train() your embeddings before add() it.\nWhat is about your question you can just copy embeddings before adding it into the index.\n" ]
[ 0 ]
[]
[]
[ "faiss", "python" ]
stackoverflow_0074097858_faiss_python.txt
Q: Css not loading in Django My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs. Setting.py DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'technicalCourse.apps.Tec...
Css not loading in Django
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs. Setting.py DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'djang...
[ "try this command:\npython manage.py collectstatic\n\nand check again.\n", "It's weird that images are working and CSS isn't. There could be a multitude of possibilities for your problem.\nThe simplest way to solve this is to set the path to the CSS files via an absolute or a relative path.\nRelavtive path case\n...
[ 0, 0, 0, 0 ]
[]
[]
[ "django", "django_staticfiles", "python" ]
stackoverflow_0061405964_django_django_staticfiles_python.txt
Q: Why do I keep getting errors when I try to install PySide6 on windows PC? I have been trying to install PySide6 on my PC (Windows 10 64bits) with Python 3.9.0 installed, but I keep getting errors every time. I used the command pip install PySide6 It is not working for me. Any help will be appreciated. Error: ERROR...
Why do I keep getting errors when I try to install PySide6 on windows PC?
I have been trying to install PySide6 on my PC (Windows 10 64bits) with Python 3.9.0 installed, but I keep getting errors every time. I used the command pip install PySide6 It is not working for me. Any help will be appreciated. Error: ERROR: Could not find a version that satisfies the requirement pyside2 (from version...
[ "Check if you Python installation is 64 bit and not 32 bit. It has an impact on compatible and thus available binaries.\n", "At the time of writing:\nThe problem is that most of the binaries are not yet compatible and are not yet compiled for Python 3.9 at the time of writing. If you want the best compatibility, ...
[ 1, 0 ]
[]
[]
[ "pip", "pyside6", "python" ]
stackoverflow_0067635487_pip_pyside6_python.txt
Q: how to deal with variable width of Buttons in ipywidgets I have the need to display a bunch of buttons. the description of every button corresponds to every word of a text. In order to give a text appearance I want to make button width accoding to the length of the word inside. So I create a variable that gives me...
how to deal with variable width of Buttons in ipywidgets
I have the need to display a bunch of buttons. the description of every button corresponds to every word of a text. In order to give a text appearance I want to make button width accoding to the length of the word inside. So I create a variable that gives me the width px according to the number of letters. I dont know ...
[ "There's limited control for the CSS for widgets. There seems to be a cutoff around 40px where text will get truncated. I used a simple max comparison to get hopefully close to what you are looking for:\nfrom ipywidgets import *\nmylist=['loren','ipsum','whapmmtever','loren','ipsum','otra','the','palabra','concept'...
[ 1, 1 ]
[]
[]
[ "button", "ipywidgets", "jupyter_notebook", "python", "voila" ]
stackoverflow_0061278187_button_ipywidgets_jupyter_notebook_python_voila.txt
Q: Creating a Maya animation control with a custom shape I have a small python script that calls a MEL command to build a nurbs curve circle. The shape of the curve is then placed with a new transform node and together they generate an animation control. But nothing is being generated when the script is run and there...
Creating a Maya animation control with a custom shape
I have a small python script that calls a MEL command to build a nurbs curve circle. The shape of the curve is then placed with a new transform node and together they generate an animation control. But nothing is being generated when the script is run and there is no error message. import pymel.all as pm import maya.cm...
[ "If you receive no error message, I'd bet you fogot to call the function with makeHandle(). But this function would not work anyway. You are heavily mixing mel, cmds and pymel concepts. I'd recommend to stay with one approach only, e.g. pymel. This way you do not need any mel scripts or eval calls, just create a ci...
[ 0 ]
[]
[]
[ "maya", "mel", "python" ]
stackoverflow_0074463399_maya_mel_python.txt
Q: How to find index of a list element I want to create a program that gives you the position of the string in a list. a = [1,3,4,5,6,7,8,9,2,"rick",56,"open"] A: You should read more on operations you can do on Lists here: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists In this case, you can u...
How to find index of a list element
I want to create a program that gives you the position of the string in a list. a = [1,3,4,5,6,7,8,9,2,"rick",56,"open"]
[ "You should read more on operations you can do on Lists here: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists\nIn this case, you can use the index() function to get the index of a specific item in the list:\na=[1,3,4,5,6,7,8,9,2,\"rick\",56,\"open\"]\nprint(a.index(7))\nprint(a.index(\"rick\"))...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074473509_python.txt
Q: Creating AWS SES SMTP credentials in python2 I am creating an SES SMTP credentials from my iam accesskey and secretkey. i have referred to this document for creating the SES SMTP credentials But the code produces different SES SMTP credentials for python2 and python3 but the python3 key is the valid one. how can i...
Creating AWS SES SMTP credentials in python2
I am creating an SES SMTP credentials from my iam accesskey and secretkey. i have referred to this document for creating the SES SMTP credentials But the code produces different SES SMTP credentials for python2 and python3 but the python3 key is the valid one. how can i get the same key while executing the script with ...
[ "After a lot of debugging i found out bytes([VERSION]) does not work same in both python3 and python2 thats why it was returning 2 different calue for both 2 and 3\nMy simple fix was that to hardcode the bytes value of the hex 0x04 as b'\\x04'\nsignature_and_version = b'\\x04' + signature\n\nMake sure to return the...
[ 0 ]
[]
[]
[ "amazon_web_services", "python", "python_2.7" ]
stackoverflow_0074471381_amazon_web_services_python_python_2.7.txt
Q: Grouping pandas dataframe by column specificity to row values - python I have a dataset of this type: id 1 2 3 4 5 A 10 40 80 12 50 B 20 60 70 77 60 C 30 15 50 20 60 C 30 15 20 45 43 ...
Grouping pandas dataframe by column specificity to row values - python
I have a dataset of this type: id 1 2 3 4 5 A 10 40 80 12 50 B 20 60 70 77 60 C 30 15 50 20 60 C 30 15 20 45 43 B 50 100 70 77 32 C 30 15 20 80 21 ...
[ "(df.melt('id')\n .groupby(['id', 'variable'])\n .agg(lambda x: x.max() if x.max() == x.min() else None)\n .unstack())\n\nresult\n value\nvariable 1 2 3 4 5\nid \nA NaN NaN NaN 12.0 50.0\nB NaN NaN 70.0 77.0 NaN\nC 30.0 15.0 NaN NaN NaN\n\n...
[ 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074473141_dataframe_pandas_python.txt
Q: Detect whether Celery is Available/Running I'm using Celery to manage asynchronous tasks. Occasionally, however, the celery process goes down which causes none of the tasks to get executed. I would like to be able to check the status of celery and make sure everything is working fine, and if I detect any problems ...
Detect whether Celery is Available/Running
I'm using Celery to manage asynchronous tasks. Occasionally, however, the celery process goes down which causes none of the tasks to get executed. I would like to be able to check the status of celery and make sure everything is working fine, and if I detect any problems display an error message to the user. From the C...
[ "Here's the code I've been using. celery.task.control.Inspect.stats() returns a dict containing lots of details about the currently available workers, None if there are no workers running, or raises an IOError if it can't connect to the message broker. I'm using RabbitMQ - it's possible that other messaging syste...
[ 66, 18, 12, 7, 5, 3, 2, 1, 0, 0 ]
[]
[]
[ "celery", "django", "django_celery", "python" ]
stackoverflow_0008506914_celery_django_django_celery_python.txt
Q: How to put dynamic json response in panda dataframe? I have the following JSON response which is dynamic, most of the fields(bccRecipients ,replyTo, and ccRecipients) can be empty sometimes, and sometimes it contains values { "hasAttachments": False, "sender": { "emailAddress": { "nam...
How to put dynamic json response in panda dataframe?
I have the following JSON response which is dynamic, most of the fields(bccRecipients ,replyTo, and ccRecipients) can be empty sometimes, and sometimes it contains values { "hasAttachments": False, "sender": { "emailAddress": { "name": "John Henry", "address": "john@abc.com" ...
[ "import pandas as pd\n\nresponse = {...}\nemail_metadata = pd.json_normalize(response)\n\nUpdated answer after question update:\nimport pandas as pd\n\ndef get_seperated_data(metadata, column_name):\n tmp = pd.json_normalize(metadata[column_name][0]).apply(', '.join).to_frame().T\n tmp = tmp.rename(columns={c...
[ 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074471956_dataframe_json_pandas_python.txt
Q: Buildozer fails to compile libffi on arm64/aarch64 CPU I am Trying to run Buildozer on my Android Phone. For this i am using Arch Linux pRoot on Termux App (Android 7)(redmi Note 4) Since Google Only distributes x86_64 version of NDK, i am using aarch64/arm64 Android NDK (version r21d) and SDK from this GitHub Rep...
Buildozer fails to compile libffi on arm64/aarch64 CPU
I am Trying to run Buildozer on my Android Phone. For this i am using Arch Linux pRoot on Termux App (Android 7)(redmi Note 4) Since Google Only distributes x86_64 version of NDK, i am using aarch64/arm64 Android NDK (version r21d) and SDK from this GitHub Repo : https://github.com/Lzhiyong/termux-ndk And i am using JD...
[ "Did you try to get the latest clang compiler? Seems like there is no working c compiler on your installation of arch on termux. If you do have a c compiler working, you may try to get the base-devel package and make an alias for the c compiler as gcc\n", "I too had this error.\nAfter many hours looking at config...
[ 1, 0, 0 ]
[]
[]
[ "android", "buildozer", "libffi", "python", "termux" ]
stackoverflow_0065916898_android_buildozer_libffi_python_termux.txt
Q: How to sum and count values within a list of dicts? I have a list of Dicts as follows [{"Sender":"bob","Receiver":"alice","Amount":50},{"Sender":"bob","Receiver":"alice","Amount":60},{"Sender":"bob","Receiver":"alice","Amount":70},{"Sender":"joe","Receiver":"bob","Amount":50},{"Sender":"joe","Receiver":"bob","Amou...
How to sum and count values within a list of dicts?
I have a list of Dicts as follows [{"Sender":"bob","Receiver":"alice","Amount":50},{"Sender":"bob","Receiver":"alice","Amount":60},{"Sender":"bob","Receiver":"alice","Amount":70},{"Sender":"joe","Receiver":"bob","Amount":50},{"Sender":"joe","Receiver":"bob","Amount":150},{"Sender":"alice","Receiver":"bob","Amount":100}...
[ "Make a new dictionary where the key is the sender/receiver pair.\nIterate over the list of senders/receivers. If that sender/receiver pair does not exist in the new dict, create it. Otherwise increment the count for that pair by one.\nnewdict = {}\nfor row in transactions:\n sender = row['Sender']\n receiv...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0074469414_dictionary_list_python_sorting.txt
Q: Connect to MySQL database using python So I am having a super hard time connecting to a local database using the python mysql.connector module. So I am trying to connect using the highlighted connection. I use the password abcdefghijkl to log into the SQL environment. I am trying to connect to a database named fl...
Connect to MySQL database using python
So I am having a super hard time connecting to a local database using the python mysql.connector module. So I am trying to connect using the highlighted connection. I use the password abcdefghijkl to log into the SQL environment. I am trying to connect to a database named flight_school. My python script looks like so....
[ "Please read always the official documentation\nYour cooenction stirng has to have this form(if you do it this way=\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"testpaaword\",\n database=\"testdb\"\n )\n\n", "Check out SQL-Alchemy module, works wonders from m...
[ 1, 0, 0 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0061513711_database_mysql_python.txt
Q: python concurrent.futures.ProcessPoolExecutor crashing with full RAM Python concurrent.futures.ProcessPoolExecutor crashing with full RAM Program description Hi, I've got a computationally heavy function which I want to run in parallel. The function is a test that accepts as inputs: a DataFrame to test on paramet...
python concurrent.futures.ProcessPoolExecutor crashing with full RAM
Python concurrent.futures.ProcessPoolExecutor crashing with full RAM Program description Hi, I've got a computationally heavy function which I want to run in parallel. The function is a test that accepts as inputs: a DataFrame to test on parameters based on which the calculations will be ran. The return value is a sh...
[ "See my comment on what map actually returns.\nThis answer is relevant according to how large your parameters list is, i.e. how many total tasks are being placed on the multiprocessing pool's task queue:\nYou are currently creating and passing a copy of your dataframe (with large_df.copy()) every time you are submi...
[ 1, 0 ]
[]
[]
[ "concurrent.futures", "multiprocessing", "process_pool", "python" ]
stackoverflow_0074433987_concurrent.futures_multiprocessing_process_pool_python.txt
Q: Splitting a string based on multiple delimeters using split() function in python by ignoring certain special characters present in the string Not getting desired result while splitting a string based on multiple delimiters and based on specific conditions. I tried executing below code: import re text = r'ced"|"ms|...
Splitting a string based on multiple delimeters using split() function in python by ignoring certain special characters present in the string
Not getting desired result while splitting a string based on multiple delimiters and based on specific conditions. I tried executing below code: import re text = r'ced"|"ms|n"|4|98' finallist = re.split('\"\|\"|\"\||\|', text) Here i'm trying to split string based on 3 delimiters by joining all using OR (|). First del...
[ "You can use\n\"?\\|(?!(?:(?<=[A-Za-z]\\|)|(?<=[A-Za-z]\\\\\\|))(?=[a-zA-Z]))\"?\n\nSee the regex demo. Details:\n\n\"? - an optional \" char\n\\| - a | char\n(?!(?:(?<=[A-Za-z]\\|)|(?<=[A-Za-z]\\\\\\|))(?=[a-zA-Z])) - a negative lookahead that fails the match if there is an ASCII letter immediately after the | cha...
[ 0 ]
[]
[]
[ "list", "python", "regex", "split", "string" ]
stackoverflow_0074472442_list_python_regex_split_string.txt
Q: Tensorflow loss is diverging in my RNN I'm trying to get my hand wet with Tensorflow by solving this challenge: https://www.kaggle.com/c/integer-sequence-learning. My work is based on these blog posts: https://danijar.com/variable-sequence-lengths-in-tensorflow/ https://gist.github.com/evanthebouncy/8e16148687e8...
Tensorflow loss is diverging in my RNN
I'm trying to get my hand wet with Tensorflow by solving this challenge: https://www.kaggle.com/c/integer-sequence-learning. My work is based on these blog posts: https://danijar.com/variable-sequence-lengths-in-tensorflow/ https://gist.github.com/evanthebouncy/8e16148687e807a46e3f A complete working example - with ...
[ "RNNs suffer from an exploding gradient, so you should clip the gradients for the RNN parameters. Look at this post:\nHow to effectively apply gradient clipping in tensor flow?\n", "use AdamOptimizer instead\noptimizer = tf.train.AdamOptimizer()\n\n", "Try using LSTM which is more optimized and better version o...
[ 3, 0, 0 ]
[]
[]
[ "deep_learning", "neural_network", "python", "sequence", "tensorflow" ]
stackoverflow_0038762104_deep_learning_neural_network_python_sequence_tensorflow.txt
Q: Python makemigrations does not work right I use Django framework This is my models.py from django.db import models # Create your models here. class Destination(models.Model): name: models.CharField(max_length=100) img: models.ImageField(upload_to='pics') desc: models.TextField price: models.Inte...
Python makemigrations does not work right
I use Django framework This is my models.py from django.db import models # Create your models here. class Destination(models.Model): name: models.CharField(max_length=100) img: models.ImageField(upload_to='pics') desc: models.TextField price: models.IntegerField offer: models.BooleanField(defaul...
[ "You have added model fields in incorrect way. You can't add like this.\nchange this:\nclass Destination(models.Model):\n name: models.CharField(max_length=100)\n img: models.ImageField(upload_to='pics')\n desc: models.TextField\n price: models.IntegerField\n offer: models.BooleanField(default=False)...
[ 1 ]
[]
[]
[ "django", "makemigrations", "migrate", "python" ]
stackoverflow_0074473808_django_makemigrations_migrate_python.txt
Q: AttributeError: 'UnaryOp' object has no attribute 'evaluate' when using eval function in Python for test_ind, case_data in test_df.iterrows(): case_data = case_data.to_frame().T rule = "Ask_before>-0.4843681 & 0.5255821<=BidVol_before<=0.07581073 & Volume>0.1107559" print(case_data, "case_data") ...
AttributeError: 'UnaryOp' object has no attribute 'evaluate' when using eval function in Python
for test_ind, case_data in test_df.iterrows(): case_data = case_data.to_frame().T rule = "Ask_before>-0.4843681 & 0.5255821<=BidVol_before<=0.07581073 & Volume>0.1107559" print(case_data, "case_data") if case_data.eval(rule).all() == True: print("TRUE") Here, when the rule contains ne...
[ "It isn't a problem in your code, it's a bug in pandas https://github.com/pandas-dev/pandas/issues/16363\nIt is fixed by now.\n", "Seems like it's still open as of 2022 January\nhttps://github.com/pandas-dev/pandas/issues/16363\nin my experience resolving negative index values solved iit\n", "Change the \"unary...
[ 0, 0, 0 ]
[]
[]
[ "conditional_operator", "dataframe", "eval", "python", "python_3.x" ]
stackoverflow_0063528707_conditional_operator_dataframe_eval_python_python_3.x.txt
Q: How to convert date/time to YYYY-MM-DDTHH:mm:ss.000+000 format? How to convert DD-MM-YYYY to YYYY-MM-DDTHH:mm:ss.000+0000 format using Python. I want to convert this 20-05-2022 14:03:02 to 2022-05-20T14:03:02.000+0000 A: Use the datetime module from datetime import datetime, timezone dtt = datetime.strptime("2...
How to convert date/time to YYYY-MM-DDTHH:mm:ss.000+000 format?
How to convert DD-MM-YYYY to YYYY-MM-DDTHH:mm:ss.000+0000 format using Python. I want to convert this 20-05-2022 14:03:02 to 2022-05-20T14:03:02.000+0000
[ "Use the datetime module\nfrom datetime import datetime, timezone\n\ndtt = datetime.strptime(\"20-05-2022 14:03:02\", \"%d-%m-%Y %H:%M:%S\")\nprint(dtt.replace(tzinfo=timezone.utc).isoformat(timespec=\"milliseconds\"))\n\nPrints 2022-05-20T14:03:02.000+00:00\nSee this answer for python datetime and ISO 8601.\n" ]
[ 1 ]
[]
[]
[ "python", "python_datetime" ]
stackoverflow_0074473622_python_python_datetime.txt
Q: Creating custom protocol with Raspberry Pi 4 Hello and thank you for reading. As a hobby project I thought it would be fun to try and create my own communication protocol. I am trying to use the GPIO-pins on my Raspberry Pi 4 to send a digital signal. The reason for using a Raspberry Pi is because I want to connec...
Creating custom protocol with Raspberry Pi 4
Hello and thank you for reading. As a hobby project I thought it would be fun to try and create my own communication protocol. I am trying to use the GPIO-pins on my Raspberry Pi 4 to send a digital signal. The reason for using a Raspberry Pi is because I want to connect it to a webpage that I want to run on the Pi. I ...
[ "I think this offset could come from the time it takes to run GPIO.output(pin, GPIO.HIGH).\nYou could improve this by measuring this execution time and condier it in the time.sleep(...). (e.g. time.sleep(pulse_time - some_gpio_time)\nHave a look at timeit to measure the time experimentally or you could try to meas...
[ 0 ]
[]
[]
[ "c++", "python", "raspberry_pi", "signal_processing" ]
stackoverflow_0074473437_c++_python_raspberry_pi_signal_processing.txt
Q: Finding IP Camera using OpenCV So this is what I have currently following this tutorial. #number 0 is front web cam, number 1 is back webcam capture = cv2.VideoCapture(0) capture.set(3, 640) capture.set(4, 480) while True: success, img = capture.read() cv2.imshow("video", img) #This function loops ...
Finding IP Camera using OpenCV
So this is what I have currently following this tutorial. #number 0 is front web cam, number 1 is back webcam capture = cv2.VideoCapture(0) capture.set(3, 640) capture.set(4, 480) while True: success, img = capture.read() cv2.imshow("video", img) #This function loops -> Delay -> press Q it breaks loop ...
[ "This issue is old, but just in case someone has the same issue. Use the VimbaPython example for asynchronous streaming with openCV from GitHub.\nGitHub VimbaPython examples\nYou use Vimba to open the camera and access the frames and convert them to an openCV format. Then you can continue image manipulation/analysi...
[ 0 ]
[]
[]
[ "computer_vision", "cv2", "opencv", "python" ]
stackoverflow_0063527336_computer_vision_cv2_opencv_python.txt
Q: CPU throttling in chrome via python selenium Is it possible to throttle CPU in chrome's devtools via python selenium? And if so, how? It would appear the driver has a method execute_cdp_cmd which stands for "Execute Chrome Devtools Protocol command" but I do not know what command I would give it. A: It would ap...
CPU throttling in chrome via python selenium
Is it possible to throttle CPU in chrome's devtools via python selenium? And if so, how? It would appear the driver has a method execute_cdp_cmd which stands for "Execute Chrome Devtools Protocol command" but I do not know what command I would give it.
[ "It would appear to be possible in chromedriver 75. \n## rate 1 is no throttle, 2 is 2x slower, etc. \ndriver.execute_cdp_cmd(\"Emulation.setCPUThrottlingRate\", {'rate': 10})\n\nNOTE:\n2.38 didn't seem to support execute_cdp_cmd() while 2.48 did. Chromedriver also appears to have changed their versioning scheme ...
[ 1, 0 ]
[]
[]
[ "google_chrome_devtools", "python", "python_3.x", "selenium", "selenium_chromedriver" ]
stackoverflow_0057008946_google_chrome_devtools_python_python_3.x_selenium_selenium_chromedriver.txt
Q: In Regex after match use group method to return only a part of the string I am using the regular expression below to get the names of 40 hotels from a HTML file using python using grouping. [edit]- The catch is that we have to do this only using Regex and no other module like Beautiful Soup pattern_names = re.comp...
In Regex after match use group method to return only a part of the string
I am using the regular expression below to get the names of 40 hotels from a HTML file using python using grouping. [edit]- The catch is that we have to do this only using Regex and no other module like Beautiful Soup pattern_names = re.compile(r'\t(?P<Hotel_name>[a-zA-Z0-9][a-z0-9]*.+)\n</a>\n') name_list=pattern_name...
[ "There\npattern_names = re.compile(r'\\t(?P<Hotel_name>[a-zA-Z0-9][a-z0-9]*.+^[&amp;])\\n</a>\\n')\n\nyou have ^ inside which does not make sense for ^ which denotes begin of line, also observe that [&amp;] means one of characters listed, i.e. & or a or m or p or ;.\nI suggest to properly process text from HTML rat...
[ 0 ]
[]
[]
[ "group", "python", "regex" ]
stackoverflow_0074473813_group_python_regex.txt
Q: Go to definition in VS code doesn't show the body of a function When I right click on a function and then select "Go to definition" there shows up a module with that function, but it only shows the parameters which have to be passed to it, and I can't see anything about the body of the function. Here is what's sh...
Go to definition in VS code doesn't show the body of a function
When I right click on a function and then select "Go to definition" there shows up a module with that function, but it only shows the parameters which have to be passed to it, and I can't see anything about the body of the function. Here is what's shown when I went to the definition of itertools.dropwhile:
[ "As mentioned in the comments, VSCode can only show you source code it has access to, and many of the Python builtins and stdlib (including the itertools module) are implemented in compiled C -- there's no source code to show you.\n", "Sometimes this happens if you develop code that runs inside an environment who...
[ 6, 0 ]
[]
[]
[ "go_to_definition", "python", "visual_studio_code" ]
stackoverflow_0059339718_go_to_definition_python_visual_studio_code.txt
Q: Convert list into columns by matching values I have a pandas dataframe like so: df = pd.DataFrame({'column': [[np.nan, np.nan, np.nan], [1, np.nan, np.nan], [2, 3, np.nan], [3, 2, 1]]}) column 0 [nan, nan, nan] 1 [1, nan, nan] 2 [2, 3, nan] 3 [3, 2, 1] Note that there is never the same value twice in a r...
Convert list into columns by matching values
I have a pandas dataframe like so: df = pd.DataFrame({'column': [[np.nan, np.nan, np.nan], [1, np.nan, np.nan], [2, 3, np.nan], [3, 2, 1]]}) column 0 [nan, nan, nan] 1 [1, nan, nan] 2 [2, 3, nan] 3 [3, 2, 1] Note that there is never the same value twice in a row. I wish to transform this single column into mu...
[ "Use dict comprehension to compute pandas Series of columns:\nimport math\ndf = df.apply(lambda row: pd.Series(data={f\"column_{v}\": v for v in row[\"column\"] if not math.isnan(v)}, dtype=\"float64\"), axis=1)\n\n[Out]:\n column_1 column_2 column_3\n0 NaN NaN NaN\n1 1.0 NaN ...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074472549_pandas_python.txt
Q: Invalid object name "django_migrations" when trying to runserver I wanted to connect my Django app to client's MSSQL database (Previously my app worked on SQLite). I made an migration on their test server and It worked successfully, then they copied this database to destination server and when I try to python man...
Invalid object name "django_migrations" when trying to runserver
I wanted to connect my Django app to client's MSSQL database (Previously my app worked on SQLite). I made an migration on their test server and It worked successfully, then they copied this database to destination server and when I try to python manage.py runserver It shows me just django.db.utils.ProgrammingError: (...
[ "So the reason this is happening is likely because the default schema you've set for django's internal tables isn't the same as the default schema of your current user.\nYou can test this by checking the actual schema of django_migrations table in your database, and then run a python script to verify your current d...
[ 1, 0 ]
[]
[]
[ "django", "odbc", "python", "sql_server" ]
stackoverflow_0056630509_django_odbc_python_sql_server.txt
Q: Pandas percentage of two columns I have a data frame that looks like this: Vendor GRDate Pass/Fail 0 204177 2022-22 1.0 1 204177 2022-22 0.0 2 204177 2022-22 0.0 3 204177 2022-22 1.0 4 204177 2022-22 1.0 5 204177 2022-22 1.0 7 201645 2022-22 0.0 8 201645 2022-22 0.0 9 201645 2022-2...
Pandas percentage of two columns
I have a data frame that looks like this: Vendor GRDate Pass/Fail 0 204177 2022-22 1.0 1 204177 2022-22 0.0 2 204177 2022-22 0.0 3 204177 2022-22 1.0 4 204177 2022-22 1.0 5 204177 2022-22 1.0 7 201645 2022-22 0.0 8 201645 2022-22 0.0 9 201645 2022-22 1.0 10 201645 2022-22 1.0 I am tr...
[ "Try:\nx = (\n df.groupby([\"GRDate\", \"Vendor\"])[\"Pass/Fail\"]\n .mean()\n .reset_index()\n .rename(columns={\"Pass/Fail\": \"Performance\"})\n)\nprint(x)\n\nPrints:\n GRDate Vendor Performance\n0 2022-22 201645 0.500000\n1 2022-22 204177 0.666667\n\n", "As you have 0/1, you can u...
[ 2, 2 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074474022_group_by_pandas_python.txt
Q: Unwanted RST TCP packet with Scapy In order to understand how TCP works, I tried to forge my own TCP SYN/SYN-ACK/ACK (based on the tutorial: http://www.thice.nl/creating-ack-get-packets-with-scapy/ ). The problem is that whenever my computer recieve the SYN-ACK from the server, it generates a RST packet that stops...
Unwanted RST TCP packet with Scapy
In order to understand how TCP works, I tried to forge my own TCP SYN/SYN-ACK/ACK (based on the tutorial: http://www.thice.nl/creating-ack-get-packets-with-scapy/ ). The problem is that whenever my computer recieve the SYN-ACK from the server, it generates a RST packet that stops the connection process. I tried on a OS...
[ "The article you cited makes this pretty clear...\n\nSince you are not completing the full TCP handshake your operating system might try to take control and can start sending RST (reset) packets, to avoid this we can use iptables:\n\niptables -A OUTPUT -p tcp --tcp-flags RST RST -s 192.168.1.20 -j DROP\n\nEssential...
[ 34, 6, 6, 1 ]
[]
[]
[ "networking", "python", "scapy", "tcp" ]
stackoverflow_0009058052_networking_python_scapy_tcp.txt
Q: Schedule an iterative function every x seconds without drifting Complete newbie here so bare with me. I've got a number of devices that report status updates to a singular location, and as more sites have been added, drift with time.sleep(x) is becoming more noticeable, and with as many sites connected now it has...
Schedule an iterative function every x seconds without drifting
Complete newbie here so bare with me. I've got a number of devices that report status updates to a singular location, and as more sites have been added, drift with time.sleep(x) is becoming more noticeable, and with as many sites connected now it has completely doubles the sleep time between iterations. import time ...
[ "Create a variable equal to the desired system time at the next interval. Increment that variable by 5 seconds each time through the loop. Calculate the sleep time so that the sleep will end at the desired time. The timings will not be perfect because sleep intervals are not super precise, but errors will not ac...
[ 0 ]
[]
[]
[ "concurrent.futures", "python", "python_3.x", "python_multithreading", "sched" ]
stackoverflow_0074467045_concurrent.futures_python_python_3.x_python_multithreading_sched.txt
Q: How to create a nested dictionary from a string list (Python)? I'm trying to create a nested dictionary from a list of strings. Each index of the strings corresponds to a key, while each character a value. I have a list: list = ['game', 'club', 'party', 'play'] I would like to create a (nested) dictionary: dict =...
How to create a nested dictionary from a string list (Python)?
I'm trying to create a nested dictionary from a list of strings. Each index of the strings corresponds to a key, while each character a value. I have a list: list = ['game', 'club', 'party', 'play'] I would like to create a (nested) dictionary: dict = {0: {'g', 'c', 'p', 'p'}, 1: {'a', 'l', 'a', 'l'}, 2: {'m', 'u', 'r...
[ "Note: you cannot have sets with duplicate values. Instead, create a dictinary where values are lists or tuples:\nfrom itertools import zip_longest\n\nlst = [\"game\", \"club\", \"party\", \"play\"]\n\nout = {\n i: [v for v in t if not v is None] for i, t in enumerate(zip_longest(*lst))\n}\n\nprint(out)\n\nPrint...
[ 2, 1 ]
[]
[]
[ "dictionary", "list", "python", "string" ]
stackoverflow_0074474058_dictionary_list_python_string.txt
Q: How could I get a result for every column after comparing dataframes? I have two csv files, and the two files have the exact same amount of rows and columns containing only numerical values. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file...
How could I get a result for every column after comparing dataframes?
I have two csv files, and the two files have the exact same amount of rows and columns containing only numerical values. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" and check the difference and so on for all the numbers in the column (...
[ "I find the recordlinkage package very useful for comparing values from 2 datasets. You can define which columns to compare and it returns a 0 or 1 if they match. Next, you can filter for all matching values\nhttps://recordlinkage.readthedocs.io/en/latest/about.html\n\nCode looks like this:\n# create pair of datafr...
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074474117_dataframe_for_loop_pandas_python.txt
Q: Django: How to display a pdf file in a new tab? Most of the posts showing how to open a pdf file in a new tab are 3 years old. What is the best way in Django to open a pdf file uploaded to a model? invoice.py class Invoice(models.Model): file = models.FileField(upload_to='estimates/', blank =True) nam...
Django: How to display a pdf file in a new tab?
Most of the posts showing how to open a pdf file in a new tab are 3 years old. What is the best way in Django to open a pdf file uploaded to a model? invoice.py class Invoice(models.Model): file = models.FileField(upload_to='estimates/', blank =True) name = models.CharField(max_length=250, blank =True) ...
[ "You should be able to use the FileField's url:\n<a href=\"{{ invoice.file.url }}\"><i class=\"fas fa-eye\"></i>&nbsp;</a>\n\n", "you can use this\n<a href=\"{{ invoice.file.url }}\" target=\"_blank\"><i class=\"fas fa-eye\"></i>&nbsp;</a>\n\n" ]
[ 3, 0 ]
[ "Into the link add:\n<a href=\"{{ invoice.pdf.url }}\" target=\"_blank\"><i class=\"fas fa-eye\"></i>&nbsp;</a>\n\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0065926111_django_python.txt
Q: Can't click button in pop up UI Selenium Hi I am trying to click on a button within a pop up("klant aanpassen"), I already tried allot of options including ActionChains but I just don't get it to work. Right now this is my script: driver.find_element_by_xpath('//*[@title="Acties"]').click() time.sleep(2) wait.un...
Can't click button in pop up UI Selenium
Hi I am trying to click on a button within a pop up("klant aanpassen"), I already tried allot of options including ActionChains but I just don't get it to work. Right now this is my script: driver.find_element_by_xpath('//*[@title="Acties"]').click() time.sleep(2) wait.until(EC.element_to_be_clickable((By.CSS_SELECTO...
[ "Locators like this CSS Selector button[class='_2f9OE _2nG1g yG7LA mekFH _2zshv _2enAb _2g-UE iyvDv _17-jo'] are problematic since they based on too much class names. These class names may be dynamically changing per session and per page state.\nThis locator can also be not unique.\nWhat we can try here is text bas...
[ 1 ]
[]
[]
[ "css_selectors", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074473367_css_selectors_python_selenium_selenium_webdriver_xpath.txt
Q: Get class labels from Keras functional model I have a functional model in Keras (Resnet50 from repo examples). I trained it with ImageDataGenerator and flow_from_directory data and saved model to .h5 file. When I call model.predict I get an array of class probabilities. But I want to associate them with class labe...
Get class labels from Keras functional model
I have a functional model in Keras (Resnet50 from repo examples). I trained it with ImageDataGenerator and flow_from_directory data and saved model to .h5 file. When I call model.predict I get an array of class probabilities. But I want to associate them with class labels (in my case - folder names). How can I get them...
[ "y_prob = model.predict(x) \ny_classes = y_prob.argmax(axis=-1)\n\nAs suggested here.\n", "When one uses flow_from_directory the problem is how to interpret the probability outputs. As in, how to map the probability outputs and the class labels as how flow_from_directory creates one-hot vectors is not known in pr...
[ 89, 57, 17, 6, 3, 2, 1, 0 ]
[ "You can use:\nmodel.predict(x_test).argmax(axis=-1)\n\n" ]
[ -1 ]
[ "keras", "python" ]
stackoverflow_0038971293_keras_python.txt
Q: How to catch Error in telegram_send when there is no connection to the internet? I'm trying to add a try-catch to my script that is supposed to notify my when my script is done executing using telegram_send(). So I ran the script with the internet connection off to see what error is raised by the function so I cou...
How to catch Error in telegram_send when there is no connection to the internet?
I'm trying to add a try-catch to my script that is supposed to notify my when my script is done executing using telegram_send(). So I ran the script with the internet connection off to see what error is raised by the function so I could catch it and add a small print() message to inform the user that the internet was o...
[ "If you try to catch the error without specifying the type, you can see the error type is telegram.error.NetworkError (which is the last one in your stack trace).\nThen, if you want to write an except statement specific to this error, you can first import telegram.error as tg_error in your code and change your exce...
[ 1 ]
[]
[]
[ "python", "python_3.x", "telegram" ]
stackoverflow_0074055738_python_python_3.x_telegram.txt
Q: Using Pillow and img2pdf to convert images to pdf I have a task that requires me to get data from an image upload (jpg or png), resize it based on the requirement, and then transform it into pdf and then store in s3. The file comes in as ByteIO I have Pillow available so I can resize the image with it Now the fil...
Using Pillow and img2pdf to convert images to pdf
I have a task that requires me to get data from an image upload (jpg or png), resize it based on the requirement, and then transform it into pdf and then store in s3. The file comes in as ByteIO I have Pillow available so I can resize the image with it Now the file type is class 'PIL.Image.Image' and I don't know how ...
[ "The problem is that u use Image.Image object instead of JPEG or something like it\nTry this:\n\nbytes_io = io.BytesIO()\n\nimage.save(bytes_io, 'PNG')\n\nwith open(output_pdf, \"wb\") as f:\n f.write(img2pdf.convert(bytes_io.getvalue()))\n\n" ]
[ 0 ]
[]
[]
[ "img2pdf", "python", "python_imaging_library" ]
stackoverflow_0058458485_img2pdf_python_python_imaging_library.txt
Q: What is proper way to close connection in psyopcg2 with "with statement"? I want to konw, what is a proper way to closing connection with Postgres database using with statement and psyopcg2. import pandas as pd import psycopg2 def create_df_from_postgres(params: dict, columns: st...
What is proper way to close connection in psyopcg2 with "with statement"?
I want to konw, what is a proper way to closing connection with Postgres database using with statement and psyopcg2. import pandas as pd import psycopg2 def create_df_from_postgres(params: dict, columns: str, tablename: str, ...
[ "Proper way to close a connection: \nFrom official psycopg docs:\n\nWarning Unlike file objects or other resources, exiting the connection’s with\n block doesn’t close the connection, but only the transaction associated to\n it. If you want to make sure the connection is closed after a certain point, you\n shoul...
[ 7, 0 ]
[ "The whole point of a with statement is that the resources are cleaned up automatically when it exits. So there is no need to call conn.close() explicitly at all.\n" ]
[ -2 ]
[ "pandas", "psycopg2", "python" ]
stackoverflow_0055334704_pandas_psycopg2_python.txt
Q: Empty dataframe when importing CSV file Importing data from CSV file doesn't work. Data: df = pd.DataFrame({'Result1': [1552, 3954, 7495], 'Result2': [1552, 3950, 1559]}, index=['Customer1', 'Customer2', 'Customer3']) I want to search for any customer who has a particular value in any column: results_to_keep = [...
Empty dataframe when importing CSV file
Importing data from CSV file doesn't work. Data: df = pd.DataFrame({'Result1': [1552, 3954, 7495], 'Result2': [1552, 3950, 1559]}, index=['Customer1', 'Customer2', 'Customer3']) I want to search for any customer who has a particular value in any column: results_to_keep = ['155101', '1551011'] df2 = df[df.isin(results...
[ "Failing to read a column as an index results in an empty DataFrame. Assuming data in CSV file like:\n\n\n\n\n\n\nResult 1\nResult2\n\n\n\n\n0\nCustomer1\n1552\n7495\n\n\n1\nCustomer2\n3954\n3950\n\n\n2\nCustomer3\n7495\n1559\n\n\n\n\nThe Customer columns should be read as an index:\nimport pandas as pd\n\ndf=pd.re...
[ 0 ]
[]
[]
[ "csv", "dataframe", "import", "python" ]
stackoverflow_0074474096_csv_dataframe_import_python.txt
Q: Is it possible to change the seed of a random generator in NumPy? Say I instantiated a random generator with import numpy as np rng = np.random.default_rng(seed=42) and I want to change its seed. Is it possible to update the seed of the generator instead of instantiating a new generator with the new seed? I manag...
Is it possible to change the seed of a random generator in NumPy?
Say I instantiated a random generator with import numpy as np rng = np.random.default_rng(seed=42) and I want to change its seed. Is it possible to update the seed of the generator instead of instantiating a new generator with the new seed? I managed to find that you can see the state of the generator with rng.__getst...
[ "A Numpy call like default_rng() gives you a Generator with an implicitly created BitGenerator. The difference between these is that a BitGenerator is the low-level method that just knows how to generate uniform uint32s, uint64s, and doubles. The Generator can then take these and turn them into other distribution...
[ 3, 1 ]
[]
[]
[ "numpy", "python", "python_3.x", "random", "random_seed" ]
stackoverflow_0074469039_numpy_python_python_3.x_random_random_seed.txt
Q: SQLAlchemy: How to order query results (order_by) on a relationship's field? Models from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, ForeignKey from sqlalchemy import Integer from sqlalchemy import Unicode from sqlalchemy import TIMESTAMP from sqlalchemy.orm import relationshi...
SQLAlchemy: How to order query results (order_by) on a relationship's field?
Models from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, ForeignKey from sqlalchemy import Integer from sqlalchemy import Unicode from sqlalchemy import TIMESTAMP from sqlalchemy.orm import relationship BaseModel = declarative_base() class Base(BaseModel): __tablename__ = 'base...
[ "SQLAlchemy wants you to think in terms of SQL. If you do a query for \"Base\", that's:\nSELECT * FROM base\n\neasy. So how, in SQL, would you select the rows from \"base\" and order by the \"name\" column in a totally different table, that is, \"player\"? You use a join:\nSELECT base.* FROM base JOIN player O...
[ 39, 0 ]
[]
[]
[ "field", "python", "relationship", "sql_order_by", "sqlalchemy" ]
stackoverflow_0009861990_field_python_relationship_sql_order_by_sqlalchemy.txt
Q: Differentiable round function in Tensorflow? So the output of my network is a list of propabilities, which I then round using tf.round() to be either 0 or 1, this is crucial for this project. I then found out that tf.round isn't differentiable so I'm kinda lost there.. :/ A: Something along the lines of x - si...
Differentiable round function in Tensorflow?
So the output of my network is a list of propabilities, which I then round using tf.round() to be either 0 or 1, this is crucial for this project. I then found out that tf.round isn't differentiable so I'm kinda lost there.. :/
[ "Something along the lines of x - sin(2pi x)/(2pi)?\nI'm sure there's a way to squish the slope to be a bit steeper.\n\n", "You can use the fact that tf.maximum() and tf.minimum() are differentiable, and the inputs are probabilities from 0 to 1\n# round numbers less than 0.5 to zero;\n# by making them negative an...
[ 20, 11, 7, 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0046596636_python_tensorflow.txt
Q: I made a code with Biopython but it does not work every time. What is wrong with my code? I have a FASTA file which contains sequences classified in an order from 1 (the first sequence: from > to *) to n (the last). The content is as follows: >TRINITY_GG_10000_c0_g1_i1.p2 TRINITY_GG_10000_c0_g1~~TRINITY_GG_10000_...
I made a code with Biopython but it does not work every time. What is wrong with my code?
I have a FASTA file which contains sequences classified in an order from 1 (the first sequence: from > to *) to n (the last). The content is as follows: >TRINITY_GG_10000_c0_g1_i1.p2 TRINITY_GG_10000_c0_g1~~TRINITY_GG_10000_c0_g1_i1.p2 ORF type:complete len:381 (+),score=55.64 TRINITY_GG_10000_c0_g1_i1:244-1386(+) MN...
[ "Hey I hope you still need an answer:\nThe problem faulty list I provided my answer as code I tested it and it works.\nI also provided a alternative more biopythonic way to do it:\n#!/bin/python3\n\nimport sys\nfasta_name = 'test.fasta'\nnums_name = 'test.list'\nout_name = 'out2.fasta'\n\nfrom Bio import SeqIO\nfro...
[ 0 ]
[]
[]
[ "biopython", "extract", "fasta", "python", "sequence" ]
stackoverflow_0074358827_biopython_extract_fasta_python_sequence.txt
Q: Closest, index and minimum distance between points I have a code that calculates the distance between closest points in a list, by using cdist. However, I would like an improved version also gives me the index of the Points. distance.cdist(Coordinates,Points).min(axis=1) A: Use argmin instead. ( padding)
Closest, index and minimum distance between points
I have a code that calculates the distance between closest points in a list, by using cdist. However, I would like an improved version also gives me the index of the Points. distance.cdist(Coordinates,Points).min(axis=1)
[ "Use argmin instead.\n( padding)\n" ]
[ 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0074457742_python_scipy.txt
Q: How to not show the webdriver console when running an exe file created with python? I am writing a parser using the selenium library, which is launched via an exe file (converted from a python script with the --windowed parameter), but when parsing starts, the chromedriver.exe console window opens, how can I preve...
How to not show the webdriver console when running an exe file created with python?
I am writing a parser using the selenium library, which is launched via an exe file (converted from a python script with the --windowed parameter), but when parsing starts, the chromedriver.exe console window opens, how can I prevent it from opening? I searched for information about this, but did not find anything norm...
[ "After some digging, I found the answer to this question and the console no longer opened. All you need to do is add some code to the python script.\nThis will only work for Windows!!\nImport the required libraries:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service as ChromeServ...
[ 0 ]
[]
[]
[ "exe", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074464796_exe_python_selenium_selenium_webdriver.txt
Q: How to get last date of the previous 9 months in python Here I need to get the previous 9 months last date when we provide year and quarter as a input. Input to my program is year and quarter Example: year = 2022 quarter = 'Q3' Expected output 2022-06-30 2022-05-30 2022-04-30 2022-03-31 2022-02-28 2022-01-31 202...
How to get last date of the previous 9 months in python
Here I need to get the previous 9 months last date when we provide year and quarter as a input. Input to my program is year and quarter Example: year = 2022 quarter = 'Q3' Expected output 2022-06-30 2022-05-30 2022-04-30 2022-03-31 2022-02-28 2022-01-31 2021-12-31 2021-11-30 2021-10-31 Is there any way to achieve th...
[ "You can use date_range:\nyear = 2022\nquarter = 'Q3'\n\npd.Series(pd.date_range(end=pd.Timestamp(f'{year}-{quarter}'), periods=9, freq='1M')[::-1])\n\nOutput:\n0 2022-06-30\n1 2022-05-31\n2 2022-04-30\n3 2022-03-31\n4 2022-02-28\n5 2022-01-31\n6 2021-12-31\n7 2021-11-30\n8 2021-10-31\ndtype: date...
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074474242_datetime_python.txt
Q: Using Python 3.3 in C++ 'python33_d.lib' not found I am trying to #include <Python.h> in my C++ code and when I go to compile my code I get this error: fatal error LNK1104: cannot open file 'python33_d.lib' I have tried to find python33_d.lib on my computer to include in my linker dependencies, but I cannot find ...
Using Python 3.3 in C++ 'python33_d.lib' not found
I am trying to #include <Python.h> in my C++ code and when I go to compile my code I get this error: fatal error LNK1104: cannot open file 'python33_d.lib' I have tried to find python33_d.lib on my computer to include in my linker dependencies, but I cannot find it. I have been able to find python33.lib. Where can I f...
[ "Simple solution from the python bug tracker:\n#ifdef _DEBUG\n #undef _DEBUG\n #include <python.h>\n #define _DEBUG\n#else\n #include <python.h>\n#endif\n\n", "In the event that you need a debug version (as I do for work), it is possible to build the library yourself:\n\nDownload the source tarball from http:...
[ 35, 25, 18, 12, 9, 0, 0 ]
[]
[]
[ "c++", "python", "visual_c++" ]
stackoverflow_0017028576_c++_python_visual_c++.txt
Q: Expand folium map size on mobile devices I make a web app using Django, Folium. I have a navbar and a Folium map on the web page. It works fine om computers and landscape screen devices, but on portrait screen devices the map has a free space. My code for map: current_map = folium.Map(location=start_location, zoom...
Expand folium map size on mobile devices
I make a web app using Django, Folium. I have a navbar and a Folium map on the web page. It works fine om computers and landscape screen devices, but on portrait screen devices the map has a free space. My code for map: current_map = folium.Map(location=start_location, zoom_start=6) fig = branca.element.Figure(heig...
[ "Well, I might to use Figure and modify folium package.\ncurrent_map = folium.Map(location=(48.51, 32.25), zoom_start=6)\nmap_container = branca.element.Figure(height=\"100%\")\nmap_container.add_child(current_map)\n...\ncontext = {\"current_map\": map_container.render(), \"form\": form}\nreturn render(request, tem...
[ 1 ]
[ "Try this:\ncontext = {'map': map.get_root().render()}\nreturn render(request, template_name=\"index.html\", context=context)\n\nindex.html:\n<html> \n {{map|safe}}\n</html>\n \n\n" ]
[ -1 ]
[ "django", "folium", "python" ]
stackoverflow_0073791474_django_folium_python.txt
Q: How to call device function inside an object from CUDA kernel in python I am writing very specific Neural Network and I have many classes of different activation functions, each has function for normal python and one jitted as device function. The problem is calling that method from inside a CUDA kernel. @cuda.jit...
How to call device function inside an object from CUDA kernel in python
I am writing very specific Neural Network and I have many classes of different activation functions, each has function for normal python and one jitted as device function. The problem is calling that method from inside a CUDA kernel. @cuda.jit(device=True) def activation_fn(z): return max(0, z) @cuda.jit def backp...
[ "@cuda.jit has to be used with functions, not members, so you need to define the decorated functions inside methods, and capture the activation function when you define the kernel:\nfrom numba import cuda\nimport numpy as np\n\n\nclass Activation:\n def __init__(self):\n @cuda.jit(device=True)\n de...
[ 0 ]
[]
[]
[ "cuda", "machine_learning", "numba", "python" ]
stackoverflow_0074343708_cuda_machine_learning_numba_python.txt
Q: Create a new column in multiple dataframes using for loop I have multiple dataframes with the same structure but different values for instance, df0, df1, df2...., df9 To each dataframe I want to add a column named eventdate that consists of one date, for instance, 2019-09-15 using for loop for i in range(0, 9); ...
Create a new column in multiple dataframes using for loop
I have multiple dataframes with the same structure but different values for instance, df0, df1, df2...., df9 To each dataframe I want to add a column named eventdate that consists of one date, for instance, 2019-09-15 using for loop for i in range(0, 9); df+str(i)['eventdate'] = "2021-09-15" but I get an error me...
[ "dfs = [df0, df1, df2...., df9]\ndfs_new = []\n\nfor i, df in enumerate(dfs):\n df['eventdate'] = \"2021-09-15\"\n dfs_new.append(df)\n\nif you can't generate a list then you could use eval(f\"df{str(num)}\") but this method isn't recommended from what I've seen\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074474322_dataframe_pandas_python.txt
Q: Is there a way to diff two files, and move common lines to a third file? My case is fairly simple in theory. As a refactoring task, I have two python files consisting purely of variables, each referring to a testing environment's own version. These files are thousands of lines long, but there is only a handful (<1...
Is there a way to diff two files, and move common lines to a third file?
My case is fairly simple in theory. As a refactoring task, I have two python files consisting purely of variables, each referring to a testing environment's own version. These files are thousands of lines long, but there is only a handful (<100) of variables in each file that are version specific, the rest could be mov...
[ "You can try \"difflib\" library and then use unified_diff() to compare and find out difference.\n" ]
[ 0 ]
[]
[]
[ "diff", "grep", "python" ]
stackoverflow_0074474444_diff_grep_python.txt
Q: Poetry installed but `poetry: command not found` I've had a million and one issues with Poetry recently. I got it fully installed and working yesterday, but after a restart of my machine I'm back to having issues with it ;( Is there anyway to have Poetry consistently recognised in my Terminal, even after reboot? ...
Poetry installed but `poetry: command not found`
I've had a million and one issues with Poetry recently. I got it fully installed and working yesterday, but after a restart of my machine I'm back to having issues with it ;( Is there anyway to have Poetry consistently recognised in my Terminal, even after reboot? System Specs: Windows 10, Visual Studio Code, Bash - ...
[ "When I run this, after shutdown of bash Terminal:\nexport PATH=\"$HOME/.poetry/bin:$PATH\"\n\npoetry command is then recognised.\nHowever, this isn't enough alone; as every time I shutdown the terminal I need to run the export.\nPossibly needs to be saved in a file.\n", "Since this is the top StackOverflow resul...
[ 18, 11, 8, 2, 1, 0 ]
[]
[]
[ "python", "python_poetry" ]
stackoverflow_0070003829_python_python_poetry.txt
Q: ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects The Heroku Build is returning this error when I'm trying to deploy a Django application for the past few days. The Django Code and File Structure are the same as Django's Official Documentation and Proc...
ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects
The Heroku Build is returning this error when I'm trying to deploy a Django application for the past few days. The Django Code and File Structure are the same as Django's Official Documentation and Procfile is added in the root folder. Log - -----> Building on the Heroku-20 stack -----> Determining which buildpack to u...
[ "I was having the same error while deploying my application on heroku and well the problem is actually that when you are deploying it on heroku so heroku by default uses python version 3.10.x and backports.zoneinfo is not working properly with this version so I suggest you to switch to version 3.8.x(stable).\nIn or...
[ 39, 35, 7, 3, 1, 1, 0, 0 ]
[]
[]
[ "django", "heroku", "python" ]
stackoverflow_0071712258_django_heroku_python.txt
Q: Totally stuck on putting code into functions I've written code which loops 5 times for product and 5 times for product price. This saves the product and the price into separate arrays which then goes through a bubble sorting algorithm, sorting the price and corresponding products from high to low. It then calculat...
Totally stuck on putting code into functions
I've written code which loops 5 times for product and 5 times for product price. This saves the product and the price into separate arrays which then goes through a bubble sorting algorithm, sorting the price and corresponding products from high to low. It then calculates the total discounting the fifth (cheapest) prod...
[ "It would be simpler to have only one container, with dictionaries or tuples inside, but having two arrays can do.\nBased on my advanced knowledge of commerce, I think you should have a condition that \"if the price sum is more than XXX money, then the fifth item is free\".\nWhich literally translates into :\nif su...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074462579_python_python_3.x.txt
Q: Csv file with multiple lines in the same cell I am trying to write down a CSV using python with multiple lines inside the same cell. For example i want the next result: But I am getting this result: I have tried several ways to insert a "\n" between both elements of the cell but not working. My last attempt was ...
Csv file with multiple lines in the same cell
I am trying to write down a CSV using python with multiple lines inside the same cell. For example i want the next result: But I am getting this result: I have tried several ways to insert a "\n" between both elements of the cell but not working. My last attempt was the next piece of code: f=open("prueba.csv","a",new...
[ "please try:\nprueba2=str(f'{prueba21}\\n{prueba22}')\n\nshould result:\n\nIf you are concatenating variables with strings, try to use f\"Hello {variable}\" (fstrings) - recommended or \"Hello, %s.\" % variable.\nIf you search python fstrings or string formating for python on google, you`ll have a better idea than ...
[ 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074461758_csv_python.txt
Q: Python: Convert PDF to DOC How to convert a pdf file to docx. Is there a way of doing this using python? I've saw some pages that allow user to upload PDF and returns a DOC file, like PdfToWord Thanks in advance A: If you have LibreOffice installed lowriter --invisible --convert-to doc '/your/file.pdf' If you w...
Python: Convert PDF to DOC
How to convert a pdf file to docx. Is there a way of doing this using python? I've saw some pages that allow user to upload PDF and returns a DOC file, like PdfToWord Thanks in advance
[ "If you have LibreOffice installed\nlowriter --invisible --convert-to doc '/your/file.pdf'\n\nIf you want to use Python for this:\nimport os\nimport subprocess\n\nfor top, dirs, files in os.walk('/my/pdf/folder'):\n for filename in files:\n if filename.endswith('.pdf'):\n abspath = os.path.join...
[ 20, 9, 7, 2, 1, 0, 0 ]
[]
[]
[ "bash", "doc", "docx", "pdf", "python" ]
stackoverflow_0026358281_bash_doc_docx_pdf_python.txt
Q: Pytorch RuntimeError: CUDA out of memory with a huge amount of free memory While training the model, I encountered the following problem: RuntimeError: CUDA out of memory. Tried to allocate 304.00 MiB (GPU 0; 8.00 GiB total capacity; 142.76 MiB already allocated; 6.32 GiB free; 158.00 MiB reserved in total by PyTo...
Pytorch RuntimeError: CUDA out of memory with a huge amount of free memory
While training the model, I encountered the following problem: RuntimeError: CUDA out of memory. Tried to allocate 304.00 MiB (GPU 0; 8.00 GiB total capacity; 142.76 MiB already allocated; 6.32 GiB free; 158.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to ...
[ "I tried hours til i found out:\nto reduce the batch size\nand the resize my input image image size\n", "Your problem may be due to fragmentation of your GPU memory.You may want to empty your cached memory used by caching allocator.\nimport torch\ntorch.cuda.empty_cache()\n\n", "I was trying this command:\npy...
[ 1, 0, 0 ]
[ "Exit the docker image and stop the docker and start it again.\n" ]
[ -3 ]
[ "computer_vision", "machine_learning", "python", "pytorch" ]
stackoverflow_0071498324_computer_vision_machine_learning_python_pytorch.txt
Q: How to fix this TypeError? I get this error: TypeError: clear() missing 1 required positional argument: 'self' from this bit of code as far as I know: def drawHUD(self,score): self.hud.clear() self.hud.color("white") self.hud.penup() self.hud.hideturtle() self.hud.goto(0, -400) I'm not reall...
How to fix this TypeError?
I get this error: TypeError: clear() missing 1 required positional argument: 'self' from this bit of code as far as I know: def drawHUD(self,score): self.hud.clear() self.hud.color("white") self.hud.penup() self.hud.hideturtle() self.hud.goto(0, -400) I'm not really sure what to do. I'm expectin...
[ "This means that the call to clear expects to be given an argument. In your call to clear you dont pass any.\nYou should take a look at its documentation and/or its declaration.\n" ]
[ 0 ]
[]
[]
[ "project", "python", "typeerror" ]
stackoverflow_0074468243_project_python_typeerror.txt
Q: Week number of the month? Does python offer a way to easily get the current week of the month (1:4) ? A: In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to ...
Week number of the month?
Does python offer a way to easily get the current week of the month (1:4) ?
[ "In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the...
[ 53, 25, 16, 14, 5, 4, 3, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ " import datetime\n \n def week_number_of_month(date_value):\n week_number = (date_value.isocalendar()[1] - date_value.replace(day=1).isocalendar()[1] + 1)\n if week_number == -46:\n week_number = 6\n return week_number\n \n date_given = datetime.da...
[ -1 ]
[ "python", "time", "week_number" ]
stackoverflow_0003806473_python_time_week_number.txt
Q: python usgsm2m module how to specify bounding box in cli been trying to use usgsm2m module using CLI but get "is not a valid floating point value" if I try the --location option for a single point it works usgsm2m search --username ####### --password ####### --dataset landsat_tm_c2_l1 --bbox 30.32,78.03,31.5,79.0 ...
python usgsm2m module how to specify bounding box in cli
been trying to use usgsm2m module using CLI but get "is not a valid floating point value" if I try the --location option for a single point it works usgsm2m search --username ####### --password ####### --dataset landsat_tm_c2_l1 --bbox 30.32,78.03,31.5,79.0 --clouds 5 --start 2005-01-01 --end 2005-12-31 --output displ...
[ "You should have used spaces instead of commas\nusgsm2m search --username ####### --password ####### --dataset landsat_tm_c2_l1 --bbox 30.32 78.03 31.5 79.0 --clouds 5 --start 2005-01-01 --end 2005-12-31 --output display_id\n\n" ]
[ 0 ]
[]
[]
[ "command_line_interface", "python" ]
stackoverflow_0074473118_command_line_interface_python.txt
Q: Need to extract data from a column, if a particular character exists, extracting the substring before the character I've got a column which I am trying to clean, the data is like this: Wherever the pattern is of x-y year, I want to extract only the 'x' value and leave it in the string. For any other value, I want...
Need to extract data from a column, if a particular character exists, extracting the substring before the character
I've got a column which I am trying to clean, the data is like this: Wherever the pattern is of x-y year, I want to extract only the 'x' value and leave it in the string. For any other value, I want to keep it as is. Using str.extract('(.{,2}(-))') is returning a NaN value for all the other rows.
[ "The solution first compiles the regex then the compiled regex will be used on each row.\nThe lambda also relies on the walrus operator :=.\nAssumes that your 2nd column is named col2.\nimport re\n\npattern = re.compile(\"([\\d]+)-[\\d]+ year\")\ndf[\"col2\"] = df[\"col2\"].map(lambda x: m[1] if (m:=pattern.match(x...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "regex" ]
stackoverflow_0074474329_pandas_python_regex.txt
Q: Python multiprocessing: exit on error in any process import time from multiprocessing import Process def possible_error_causer(a, b): time.sleep(5) c = a / b print(c) time.sleep(100) for i in range(3): p = Process(target=possible_error_causer, args=(i, i)) p.start() The code above will e...
Python multiprocessing: exit on error in any process
import time from multiprocessing import Process def possible_error_causer(a, b): time.sleep(5) c = a / b print(c) time.sleep(100) for i in range(3): p = Process(target=possible_error_causer, args=(i, i)) p.start() The code above will execute after an exception occured in process that receiv...
[ "I didn't succeed with that exactly, as I would probably need to collect processes objects in main thread and then pass them to child processes via Queue and calling terminate on them after except (yes, I gave up other than try except, sys.excepthook didn't work for me).\nHowever, as I didn't need async to be exact...
[ 0, 0 ]
[]
[]
[ "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0074463220_multiprocessing_python_python_multiprocessing.txt
Q: Wildcard assertions with python unittest Checking if there is anyway to assertEqual an object with some of the key/value being wildcarded. I have a function, that returns an object, with one of the key being current timestamp in nanoseconds. Because this nanoseconds will change everytime I run the test, I can not ...
Wildcard assertions with python unittest
Checking if there is anyway to assertEqual an object with some of the key/value being wildcarded. I have a function, that returns an object, with one of the key being current timestamp in nanoseconds. Because this nanoseconds will change everytime I run the test, I can not expect that based on any inputs. What I want t...
[ "Not sure if there is a solution in the unittests. But you can check value using regexp or convert value to datetime and check types. Here is an example:\nimport time\nimport unittest\nfrom datetime import datetime\nimport re\n\n\nclass Something:\n def __init__(self) -> None:\n self.key1 = 'val1'\n ...
[ 0 ]
[]
[]
[ "python", "python_unittest", "wildcard" ]
stackoverflow_0074450904_python_python_unittest_wildcard.txt
Q: Call one serializer's update() method from another serilaizer's create() method I have 2 serializers serializer_1 and serializer_2 which are both model serilizer i want to execute update method of serializer_1 from create method of serializer_2 how can i achieve that? class serializer_1(serializers.ModelSerializer...
Call one serializer's update() method from another serilaizer's create() method
I have 2 serializers serializer_1 and serializer_2 which are both model serilizer i want to execute update method of serializer_1 from create method of serializer_2 how can i achieve that? class serializer_1(serializers.ModelSerializer): date = serializers.DateTimeField(required=False, allow_null=True) ispu...
[ "I think you can achieve this way\nclass serializer_2(serializers.ModelsSerializer):\n class Meta:\n model = Fedia\n fields = \"__all__\"\n\n def create(self, validated_data):\n request = self.context['request']\n **serilizer_1_data** = validated_data.pop('serialzer_1_data', N...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "django_serializer", "django_views", "python" ]
stackoverflow_0074474226_django_django_rest_framework_django_serializer_django_views_python.txt
Q: Can't access input field in POP UP UI selenium. StaleElementReferenceException after element found clickable I am trying to access an input field in a pop up UI(Aantal KvK uittreksels). Right now I am trying this code: element = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[contains(.,'custom_field_387...
Can't access input field in POP UP UI selenium. StaleElementReferenceException after element found clickable
I am trying to access an input field in a pop up UI(Aantal KvK uittreksels). Right now I am trying this code: element = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[contains(.,'custom_field_387439')]"))) element.send_keys("testing") That results in this error: selenium.common.exceptions.StaleElementRefere...
[ "StaleElementReferenceException appearing after applying WebDriverWait element_to_be_clickable expected_conditions means that the page you are working on is built with not Selenium friendly dynamic DOM technique. The page rendering is performed so that on some step the desired physical element is already exists and...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "staleelementreferenceexception" ]
stackoverflow_0074474645_python_selenium_selenium_webdriver_staleelementreferenceexception.txt
Q: How do I generate a small image randomly in different parts of the big image? Let's assume there are two images. One is called small image and another one is called big image. I want to randomly generate the small image inside the different parts of the big image one at a time everytime I run. So, currently I have...
How do I generate a small image randomly in different parts of the big image?
Let's assume there are two images. One is called small image and another one is called big image. I want to randomly generate the small image inside the different parts of the big image one at a time everytime I run. So, currently I have this image. Let's call it big image I also have smaller image: def mask_generati...
[ "I suppose you only want the small random image you generated in this iteration in your code.\nThe problem you have, is due to the modification of your calling args.\nWhen you call your function multiple times with the same big image\nmarkup_image = ...\nresult_1 = mask_generation(blob_index=0, image_index=0)\nresu...
[ 0 ]
[]
[]
[ "image_processing", "numpy", "python" ]
stackoverflow_0074474704_image_processing_numpy_python.txt
Q: Tkinter button executes when the window opens, and not when I click it I have the following python code with tkinter module. I would like buttons to be an inner function in my code, below is an example where I face the same issue of tkinter button executing itself before I click it from tkinter import * from tkint...
Tkinter button executes when the window opens, and not when I click it
I have the following python code with tkinter module. I would like buttons to be an inner function in my code, below is an example where I face the same issue of tkinter button executing itself before I click it from tkinter import * from tkinter.filedialog import asksaveasfile def main(): root = Tk() roo...
[ "You called save() function before enters mainloop thats why it shows.\nAlso in button command you called function with a parameter where function doesn't accept any arguments.\n.\n.\n.\n text = Text(root, width = 405 , height = 205)\n text.place(x=500, y=10, anchor=S)\n\n def save():\n Files = [('A...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074473726_python_tkinter.txt
Q: Filtering pandas dataframe based on repeated column values - Python So, I have a data frame of this type: Name 1 2 3 4 5 Alex 10 40 20 11 50 Alex 10 60 20 11 60 Sam 30 15 50 15 60 Sam 30 12 50 15 43 ...
Filtering pandas dataframe based on repeated column values - Python
So, I have a data frame of this type: Name 1 2 3 4 5 Alex 10 40 20 11 50 Alex 10 60 20 11 60 Sam 30 15 50 15 60 Sam 30 12 50 15 43 John 50 18 100 8 32 John 50 15 100 8 21...
[ "Using a simple list inside agg:\ncond = df.groupby('Name').agg(list).applymap(lambda x: len(x) != len(set(x)))\n\ndupe_cols = cond.columns[cond.all()]\n\n", "this is the easiest way I can think of\nfrom collections import Counter\n\nimport pandas as pd\n\ndata = [[ 'Name', 1, 2, 3, 4, 5],\n[ 'Alex'...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074474504_dataframe_pandas_python.txt
Q: Python OpenCV: mouse callback for drawing rectangle I want to save an image from the video stream and then draw a rectangle onto the shown image to produce a region of interest. Later, save that ROI in a file. I used opencv python grabcut example to use the setMouseCallback function. But I don't know what I'm doin...
Python OpenCV: mouse callback for drawing rectangle
I want to save an image from the video stream and then draw a rectangle onto the shown image to produce a region of interest. Later, save that ROI in a file. I used opencv python grabcut example to use the setMouseCallback function. But I don't know what I'm doing incorrect as it is not giving the result I expect. I wo...
[ "You need to reset the image everytime when the {event == cv2.EVENT_MOUSEMOVE:} called.\nYour code should look something like this:\nif event == cv2.EVENT_LBUTTONDOWN:\n rectangle = True\n ix,iy = x,y\n\nelif event == cv2.EVENT_MOUSEMOVE:\n if rectangle == True:\n sceneImg = sceneImg2.copy()\n ...
[ 1, 0, 0 ]
[]
[]
[ "draw", "mouseevent", "opencv", "python" ]
stackoverflow_0028823243_draw_mouseevent_opencv_python.txt
Q: Subclassing Pandas and Openpyxl to read excel and skip cells with "strikethrough" The Problem at hand: I want to parse and concatenate hundreds of excel tables. However, many of these have entries that are formatted with strikethrough. I need to skip these entries. Per request, this is a minimal example file, and ...
Subclassing Pandas and Openpyxl to read excel and skip cells with "strikethrough"
The Problem at hand: I want to parse and concatenate hundreds of excel tables. However, many of these have entries that are formatted with strikethrough. I need to skip these entries. Per request, this is a minimal example file, and a picture of the example table (values are randomized and may differ in the file): The...
[ "The problem might be related to versions of libraries you are using.\nI've tried your code with the following versions and it worked (but I had to change the way the engines are imported from pandas):\n\npandas==1.4.1\nopenpyxl==3.0.10\n\nimport pandas as pd\nfrom pandas.io.excel._openpyxl import OpenpyxlReader\nf...
[ 2 ]
[]
[]
[ "openpyxl", "pandas", "python" ]
stackoverflow_0074237797_openpyxl_pandas_python.txt
Q: Python, concurency, critical sections here I have some question about possible critical sections. In my code I have a function dealing with queue. This function is one and only to put elements in the queue. But a number of threads operating concurently get elements from this queue. Since there is a chance (I am n...
Python, concurency, critical sections
here I have some question about possible critical sections. In my code I have a function dealing with queue. This function is one and only to put elements in the queue. But a number of threads operating concurently get elements from this queue. Since there is a chance (I am not sure if such a chance exists tbh) that m...
[ "Your first question is easy to answer with the documentation of the queue class. If you implemented a custom queue, the locking is on you but the python queue module states:\n\nInternally, those three types of queues use locks to temporarily block competing threads; however, they are not designed to handle reentra...
[ 1 ]
[]
[]
[ "concurrency", "critical_section", "python", "queue" ]
stackoverflow_0074474863_concurrency_critical_section_python_queue.txt
Q: Update Django model field when actions taking place in another model I want to make changes in a model instance A, when a second model instance B is saved,updated or deleted. All models are in the same Django app. What would be the optimal way to do it? Should I use signals? Override default methods[save, update,...
Update Django model field when actions taking place in another model
I want to make changes in a model instance A, when a second model instance B is saved,updated or deleted. All models are in the same Django app. What would be the optimal way to do it? Should I use signals? Override default methods[save, update,delete]? Something else? Django documentation warns: Where possible you ...
[ "The performance impact of your signal handlers depends of course on their functionality. But you should be aware of the fact that they are executed synchronously when the signal is fired, so if there's a lot of action going on in the handlers (for example a lot of database calls) the execution will be delayed.\n" ...
[ 0 ]
[]
[]
[ "django", "model", "python", "signals" ]
stackoverflow_0074474918_django_model_python_signals.txt
Q: Login Automation Using Selenium Not Working Properly I have built a login Automator using Selenium, and the code executes without errors but the script doesn't login. The page is stuck at login page, email and password are entered, but login is not completed. enter image description here I have tried 2 ways to log...
Login Automation Using Selenium Not Working Properly
I have built a login Automator using Selenium, and the code executes without errors but the script doesn't login. The page is stuck at login page, email and password are entered, but login is not completed. enter image description here I have tried 2 ways to login: By clicking on Login through Click () e = self.drive...
[ "Before you start with scripting. please understand the AUT. how exactly it works.\nusing quora login page. as you enter the valid email address there is backend validation happening with server if the email is valid.\nUnless and untill email address is validated and correct password the login button is disabled.\n...
[ 1, 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074447578_automation_python_selenium_selenium_webdriver.txt
Q: Python code to draw a path on a map with arrows using lat/long data Along with time and heading, I also have the latitude & longitude data. From the data, I want to draw a path with arrows that indicate the path a vehicle took. I can create a path, but I am not able to make arrows on the path, in order to specify ...
Python code to draw a path on a map with arrows using lat/long data
Along with time and heading, I also have the latitude & longitude data. From the data, I want to draw a path with arrows that indicate the path a vehicle took. I can create a path, but I am not able to make arrows on the path, in order to specify the path and the direction, it took. I want to create a plot that looks l...
[ "If you are using matplotlib, you could use quiver\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots()\n# Arrow locations\nlon = [1,1,2,2]\nlat = [1,2,2,1]\n# Arrow directions\nx_dir = [1,0,-1,0]\ny_dir = [0,-1,0,1]\n# add to plot using quiver\nax.quiver(lon,lat,x_dir,y_dir,angles='xy', scale_units='xy')\npl...
[ 0 ]
[]
[]
[ "maps", "python", "python_3.x" ]
stackoverflow_0074473185_maps_python_python_3.x.txt
Q: create a new column for each strategy and add or subtract an amount I want to extract from a dataset the amount accumulated by strategy according to the transactions between the strategies (from or to): import pandas as pd df = pd.DataFrame({"value": [1000, 4000, 2000, 3000], "out": ["cash", "c...
create a new column for each strategy and add or subtract an amount
I want to extract from a dataset the amount accumulated by strategy according to the transactions between the strategies (from or to): import pandas as pd df = pd.DataFrame({"value": [1000, 4000, 2000, 3000], "out": ["cash", "cash", "lending", "DCA"], "in": ["DCA", "lending", "cas...
[ "You can try like this:\nimport pandas as pd\n\ndf = pd.DataFrame({\"value\": [1000, 4000, 2000, 3000],\n \"out\": [\"cash\", \"cash\", \"lending\", \"DCA\"],\n \"in\": [\"DCA\", \"lending\", \"cash\", \"lending\"]})\n\n# get strategies from data source and create an account for ...
[ 1 ]
[]
[]
[ "finance", "pandas", "python" ]
stackoverflow_0074467844_finance_pandas_python.txt
Q: Record not getting edited in django form using instance The model is not getting updated in the database while using the below methods. This is upload form in views def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): upload = form.sav...
Record not getting edited in django form using instance
The model is not getting updated in the database while using the below methods. This is upload form in views def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): upload = form.save(commit= False) upload.user = request.user u...
[ "I have following suggestions:\n\nOnly redirect if the form is valid.\n\nAlso use request.FILES while editing.\n\nUse get_object_or_404() instead of get().\n\n\nSo, upload view should be:\ndef upload(request):\n if request.method == 'POST':\n form = UploadForm(request.POST, request.FILES)\n if form...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_urls", "python" ]
stackoverflow_0074474785_django_django_forms_django_models_django_urls_python.txt
Q: how to write a function that calculates the age category I need to write a function that calculates the age category, so this is the function : def age_category(dob_years): if dob_years < 0 or pd.isna(dob_years): return 'NA' elif dob_years < 20: return '10-19' elif dob_years < 30: ...
how to write a function that calculates the age category
I need to write a function that calculates the age category, so this is the function : def age_category(dob_years): if dob_years < 0 or pd.isna(dob_years): return 'NA' elif dob_years < 20: return '10-19' elif dob_years < 30: return '20-29' elif dob_years < 40: return '30-...
[ "def age_category(dob_years):\n if not isinstance(dob_years, (float, int)):\n try:\n dob_years = int(dob_years)\n except ValueError:\n return 'NA'\n\n if dob_years < 0:\n return 'NA'\n\n return {\n 0: '0-9',\n 10: '10-19',\n 20: '20-29',\n ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074467111_pandas_python.txt
Q: Is it possible to export a screenshot of a GRC flowgraph in commandline? What is my problem? Is it possible to export a screenshot of a gnuradio-companion flowgraph in commandline? The command grcc provides the ability to compile .grc flowgraph files into python files. But it doesn't provide the funtionality to ex...
Is it possible to export a screenshot of a GRC flowgraph in commandline?
What is my problem? Is it possible to export a screenshot of a gnuradio-companion flowgraph in commandline? The command grcc provides the ability to compile .grc flowgraph files into python files. But it doesn't provide the funtionality to export the graph as a screenshot, which is possible when you use the gnuradio-co...
[ "Ok, so a solution that kinda works for me now is using a virtual X server (with Xvfb) and manually executing the export functionality. The script looks like this:\n#!/bin/bash\n\nif [ -z \"$1\" ];\nthen\n echo \"Usage: $1 [flowgraph .grc file]\"\n echo \"This script outputs an output.png file\"\n exit 1\n...
[ 2 ]
[]
[]
[ "gnuradio", "gnuradio_companion", "python", "qt" ]
stackoverflow_0074473535_gnuradio_gnuradio_companion_python_qt.txt
Q: Dash data table add a column on user input with predefined values I have a simple dash app containing a data table.Two user inputs make it possible to add a row or a column. Juste like when I add a row I get default values (here 0 hours) for every column, I would also like to have default values for all rows when ...
Dash data table add a column on user input with predefined values
I have a simple dash app containing a data table.Two user inputs make it possible to add a row or a column. Juste like when I add a row I get default values (here 0 hours) for every column, I would also like to have default values for all rows when adding a new column. Here is the code: import pathlib as pl import dash...
[ "I figured out a way using one callback only to add a column or a row. It's not the prettiest but it works. If anyone has a better way, allowing to keep the two callbacks separated I would appreciate it.\nHere is the code:\nimport pathlib as pl\nimport dash\nfrom dash import dash_table\nfrom dash.dash_table.Format ...
[ 1, 1 ]
[]
[]
[ "datatable", "plotly_dash", "python" ]
stackoverflow_0074460862_datatable_plotly_dash_python.txt
Q: configure: error: C compiler cannot create executables in buildozer kivy I'm trying to compile an apk using buildozer and kivy. I have configure: error: C compiler cannot create executables error when I want to convert my kivy file to apk android file with buildozer android debug deploy. Here is the complete error...
configure: error: C compiler cannot create executables in buildozer kivy
I'm trying to compile an apk using buildozer and kivy. I have configure: error: C compiler cannot create executables error when I want to convert my kivy file to apk android file with buildozer android debug deploy. Here is the complete error: STDERR: Traceback (most recent call last): File "/usr/lib/python3.6/ru...
[ "I had the exact same issue for three weeks with windows (ubuntu subsystem 20.4.1), NDK r25b, android api 31, sdk 21, p4a develop.\nIf I run the command that failed in the terminal everything works fine, because my system use a different compiler outside of buildozer. If I am correct, you are using Ubuntu-Gnome, so...
[ 1 ]
[]
[]
[ "android", "buildozer", "c", "kivy", "python" ]
stackoverflow_0073986991_android_buildozer_c_kivy_python.txt
Q: How ignore specific range of rows in a dataframe I have a dataframe with 1000000 rows and I want to ignore 8000 rows in first 40000 rows and then ignore 80000 rows in next 40000 rows. How can I achieve this ? As an example: Drop 1 to 8000, 40001 to 48000, 80001 to 88000 rows and so on. A: Approach Adapted Numpy...
How ignore specific range of rows in a dataframe
I have a dataframe with 1000000 rows and I want to ignore 8000 rows in first 40000 rows and then ignore 80000 rows in next 40000 rows. How can I achieve this ? As an example: Drop 1 to 8000, 40001 to 48000, 80001 to 88000 rows and so on.
[ "Approach\n\nAdapted Numpy slicing function: Dynamically create slice indices np.r an answer that uses a mask rather than np.r_ so can be done dynamically\nTwo solutions\n\nFor loop solution (to illustrate method)\nVectorized solution (for performance) using\n\n[numpy.ma.masked_where(https://numpy.org/doc/stable/re...
[ 1 ]
[]
[]
[ "dataframe", "python", "statistics" ]
stackoverflow_0074473469_dataframe_python_statistics.txt
Q: Merge columns with more than one value in pandas dataframe I've got this DataFrame in Python using pandas: Column 1 Column 2 Column 3 hello a,b,c 1,2,3 hi b,c,a 4,5,6 The values in column 3 belong to the categories in column 2. Is there a way to combine columns 2 and 3 that I get this output? Column 1 a b c ...
Merge columns with more than one value in pandas dataframe
I've got this DataFrame in Python using pandas: Column 1 Column 2 Column 3 hello a,b,c 1,2,3 hi b,c,a 4,5,6 The values in column 3 belong to the categories in column 2. Is there a way to combine columns 2 and 3 that I get this output? Column 1 a b c hello 1 2 3 hi 6 4 5 Any advise will be ve...
[ "You can use pd.crosstab after exploding the commas:\nnew_df = ( df.assign(t=df['Column 2'].str.split(','), a=df['Column 3'].str.split(',')).\n explode(['t', 'a']) )\n\noutput = ( pd.crosstab(index=new_df['Column 1'], columns=new_df['t'], \n values=new_df['a'], aggfunc='sum'...
[ 2, 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074474220_dataframe_pandas_python.txt
Q: Extracting the letter of specific index from each word in the list I have a list of words, and I need to extract the letter of specific index from each word in the list to the dictionary, counting their amount. For example, my list consists of "carrot", "sky", "house", "picture" words. Then the dictionary of first...
Extracting the letter of specific index from each word in the list
I have a list of words, and I need to extract the letter of specific index from each word in the list to the dictionary, counting their amount. For example, my list consists of "carrot", "sky", "house", "picture" words. Then the dictionary of first indexes would be: {"c":1, "s":1, "h":1, "p":1}, the second indexes: {"a...
[ "There is the standard collections.Counter that can help you. Given an iterable (in your case a list of letters), it gives you a counter object.\nSo you have to pass it list of letters per index.\nI added a word so that counts are not always 0.\nfrom collections import Counter\n\nwords = [\n \"carrot\",\n \"s...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074462378_dictionary_python.txt
Q: AttributeError: module 'collections' has no attribute 'MutableMapping' I recently installed python3.10 on my ubuntu system and I believe I made a link from /usr/bin/python3 to /usr/bin/python3.10 If I run python --version I get Python 2.7.17 and if I run python3 --version I get Python 3.10.2 I believe something I ...
AttributeError: module 'collections' has no attribute 'MutableMapping'
I recently installed python3.10 on my ubuntu system and I believe I made a link from /usr/bin/python3 to /usr/bin/python3.10 If I run python --version I get Python 2.7.17 and if I run python3 --version I get Python 3.10.2 I believe something I did broke something in my global python / pip. Whenever I try to use pip glo...
[ "The question already seems to have a solution but for better understanding of the problem, in python 3.10, the attribute MutableMapping from the module collections have been removed.\nIn your case, /usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/_vendor/pyparsing.py uses the Mutable...
[ 18, 17, 8, 3, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0070943244_pip_python_python_3.x.txt
Q: Objects from query results are working with dot notation but throwing not callable with .get sample_object = db.fetch_one(sample_query) # Object from db query result print(sample_object.key) #working when called` #does not work when print(sample_object.get("key")) It's working in version python 3.9.6 but not fro...
Objects from query results are working with dot notation but throwing not callable with .get
sample_object = db.fetch_one(sample_query) # Object from db query result print(sample_object.key) #working when called` #does not work when print(sample_object.get("key")) It's working in version python 3.9.6 but not from 3.10.4
[ "Based on fetchone() [sqlalchemy-docs], it returns:\n\nFetch one row.\nWhen all rows are exhausted, returns None.\n\nAnd the fetchone() method is a method of Row object in sqlalchemy ORM which:\n\nRepresent a single result row.\nThe Row object represents a row of a database result. It is typically associated in the...
[ 0 ]
[]
[]
[ "fastapi", "pydantic", "python", "python_3.x" ]
stackoverflow_0074473427_fastapi_pydantic_python_python_3.x.txt