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:
Unable to install PyRFC
I would like to install pyrfc but the package doesn't seem to exist anymore:
C:\>easy_install pyrfc-1.9.3-py2.7-win32.egg
Searching for pyrfc-1.9.3-py2.7-win32.egg
Reading https://pypi.python.org/simple/pyrfc-1.9.3-py2.7-win32.egg/
Couldn't find index page for 'pyrfc-1.9.3-py2.7-win32.egg' ... | Unable to install PyRFC | I would like to install pyrfc but the package doesn't seem to exist anymore:
C:\>easy_install pyrfc-1.9.3-py2.7-win32.egg
Searching for pyrfc-1.9.3-py2.7-win32.egg
Reading https://pypi.python.org/simple/pyrfc-1.9.3-py2.7-win32.egg/
Couldn't find index page for 'pyrfc-1.9.3-py2.7-win32.egg' (maybe misspelled?)
Scanning ... | [
"get it from github \nhttps://github.com/SAP/PyRFC/tree/master/dist\nand use easy_install\nC:\\myprograms>easy_install C:\\Users*****\\PyRFC\\dist\\pyrfc-1.9.4-py2.7-win-amd\n64.egg\n",
"See https://github.com/SAP/PyRFC\nA prerequisite to download is having a customer or partner account on SAP Service Marketplace... | [
1,
0,
0
] | [] | [] | [
"pyrfc",
"python",
"saprfc"
] | stackoverflow_0037460091_pyrfc_python_saprfc.txt |
Q:
While using Cache In DRF after using POST request new data is not being displayed on client side
I have implemented cache for my articles views, and have set cache page. Currently the issue that i am facing is when i try to POST request data to create new article, the page remains the same.
What i want to do is be... | While using Cache In DRF after using POST request new data is not being displayed on client side | I have implemented cache for my articles views, and have set cache page. Currently the issue that i am facing is when i try to POST request data to create new article, the page remains the same.
What i want to do is be able to POST article while i am still in cache page time, and display the new data while being in the... | [
"You cannot.\nCache pages are intended to be static responses, unchanged for the duration of the cache. That's the whole point.\nIf you want updated content after a POST, you need to not cache that view at all.\nInstead, you could cache individual objects in the viewset, using Django's per-view caching. That will a... | [
1
] | [] | [] | [
"django",
"django_cache",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0074212668_django_django_cache_django_rest_framework_django_views_python.txt |
Q:
How to set Aggrid style height to 100% in JustPy
I am trying to set the style of Aggrid heigth to 100% but the table does not show.
I tried using viewport and pixel, they worked perfectly fine. Fow the width, percentage is also working fine.
What I want to do is to fit the Aggrid table height to the parent Div. I ... | How to set Aggrid style height to 100% in JustPy | I am trying to set the style of Aggrid heigth to 100% but the table does not show.
I tried using viewport and pixel, they worked perfectly fine. Fow the width, percentage is also working fine.
What I want to do is to fit the Aggrid table height to the parent Div. I am still learning JustPy and python in general so this... | [
"See also https://github.com/justpy-org/justpy/discussions/592\nIt looks like you are inspired by https://github.com/justpy-org/justpy/blob/master/examples/grids_tutorial/creating_grids/grid_test4.py\nWhich out of the box is creating a 100% height effect by using 99vh as the setting. Not using 100vh seems to be on ... | [
0
] | [] | [] | [
"ag_grid",
"css",
"justpy",
"python"
] | stackoverflow_0074259313_ag_grid_css_justpy_python.txt |
Q:
Extract data in subfields of multiple XML files
My XML files are stuctured like this
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<reiXmlPrenos>
<Qfl>1808</Qfl>
<fOVE>13.7</fOVE>
<NetoVolumen>613</NetoVolumen>
<Hv>104.2</Hv>
<energenti>
<energent>
<sifra>energy_zp</sifra>
<naziv... | Extract data in subfields of multiple XML files | My XML files are stuctured like this
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<reiXmlPrenos>
<Qfl>1808</Qfl>
<fOVE>13.7</fOVE>
<NetoVolumen>613</NetoVolumen>
<Hv>104.2</Hv>
<energenti>
<energent>
<sifra>energy_zp</sifra>
<naziv>Zemeljski plin [kWh]</naziv>
<vrednost>22482</... | [
"I made a progress with the following code:\nimport xml.etree.ElementTree as ETree\nimport pandas as pd\n\nxmldata = r\"C:\\...\\S1.xml\"\nprstree = ETree.parse(xmldata)\nroot = prstree.getroot()\n\n\n# print(root)\nstore_items = []\nall_items = []\n\nfor storeno in root.iter('energent'):\n \n cona_sifra = st... | [
0
] | [] | [] | [
"group_by",
"html_parsing",
"pandas",
"python",
"xml"
] | stackoverflow_0074309067_group_by_html_parsing_pandas_python_xml.txt |
Q:
Django Rest Framework File Upload
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:
class ProductList(APIView):
authentication_classes = (authentication.TokenAuthentication,)
def get(self,request):
if request.user.is_authenticated():
userCom... | Django Rest Framework File Upload | I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:
class ProductList(APIView):
authentication_classes = (authentication.TokenAuthentication,)
def get(self,request):
if request.user.is_authenticated():
userCompanyId = request.user.get_profile().com... | [
"\nEditor's note:\n\nThis answer uses pre_save, which no longer exists in Django REST framework 3.0.\nIn a sufficiently new version of Django REST framework, MultiPartParser should be available by default, which allows uploading file with no special handling. See an answer below for an example.\n\n\nI'm using the s... | [
87,
85,
47,
23,
18,
12,
10,
7,
5,
4,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"angularjs",
"django",
"django_rest_framework",
"python"
] | stackoverflow_0020473572_angularjs_django_django_rest_framework_python.txt |
Q:
How to pass argparse command line arguments to python file in azure data factory
I have a wheel file in which there are multiple packages. I have a python script main.py, outside the wheel, which contains only 2 lines of code as below
main.py
+++++++
from pkgname import modulename
modulename.func_name()
func_name... | How to pass argparse command line arguments to python file in azure data factory | I have a wheel file in which there are multiple packages. I have a python script main.py, outside the wheel, which contains only 2 lines of code as below
main.py
+++++++
from pkgname import modulename
modulename.func_name()
func_name() in the wheel file expects command line arguments using argparse library. If I pass ... | [
"You can follow the following steps to get the required output. I have used the following code as my python script.\nimport sys\n \n# total arguments\nn = len(sys.argv)\nprint(\"Total arguments passed:\", n)\nprint(sys.argv)\n\n\nThe above code would print the number of arguments and the argument list. This file is... | [
0
] | [] | [] | [
"azure_data_factory",
"azure_databricks",
"python",
"python_3.x"
] | stackoverflow_0074060243_azure_data_factory_azure_databricks_python_python_3.x.txt |
Q:
controling two tables in views
I'm new in django rest framework and i faced this problem
I have two tables Order,Payment I want to get all orders that didn't have payment in the view how can i do this
Models
class Payment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = m... | controling two tables in views | I'm new in django rest framework and i faced this problem
I have two tables Order,Payment I want to get all orders that didn't have payment in the view how can i do this
Models
class Payment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
... | [
"Try this:-\nOrder.objects.exclude(id__in=Payment.objects.all().values_list('order', flat=True))\n\nYou should get all the orders which doesn't have payments linked.\n",
"You can filter this with:\nOrder.objects.filter(payment=None)\nThis thus filters all Order objects for which the payment ForeignKey relation is... | [
0,
0,
0
] | [] | [] | [
"django_rest_framework",
"drf_queryset",
"drf_yasg",
"python"
] | stackoverflow_0074210528_django_rest_framework_drf_queryset_drf_yasg_python.txt |
Q:
Handle no element return
I have 3 documents xsd, one with minVersion = 1.1, second with minVersion = 1.0 and another one without minVersion element. I get element data from first two, but third one does not return anything, not even "None". How to handle this?
My code:
import lxml.etree as ET
dom = ET.parse(u'cbs.... | Handle no element return | I have 3 documents xsd, one with minVersion = 1.1, second with minVersion = 1.0 and another one without minVersion element. I get element data from first two, but third one does not return anything, not even "None". How to handle this?
My code:
import lxml.etree as ET
dom = ET.parse(u'cbs.xsd')
rootxml = dom.getroot()
... | [
"Your for loop isn't being entered because rootxml.xpath isn't finding anything. Try this:\nimport lxml.etree as ET\ndom = ET.parse(u'cbs.xsd')\nrootxml = dom.getroot()\nnss = rootxml.nsmap\nfor subtag in rootxml.xpath(u'//@vc:minVersion', namespaces=nss):\n print(f'Found! {subtag} version')\n break\nelse:\n ... | [
0
] | [] | [] | [
"python",
"xml",
"xpath",
"xsd"
] | stackoverflow_0074313314_python_xml_xpath_xsd.txt |
Q:
How to activate an Anaconda environment
I'm on Windows 8, using Anaconda 1.7.5 64bit.
I created a new Anaconda environment with
conda create -p ./test python=2.7 pip
from C:\Pr\TEMP\venv\.
This worked well (there is a folder with a new python distribution). conda tells me to type
activate C:\PR\TEMP\venv\test
to... | How to activate an Anaconda environment | I'm on Windows 8, using Anaconda 1.7.5 64bit.
I created a new Anaconda environment with
conda create -p ./test python=2.7 pip
from C:\Pr\TEMP\venv\.
This worked well (there is a folder with a new python distribution). conda tells me to type
activate C:\PR\TEMP\venv\test
to activate the environment, however this retur... | [
"If this happens you would need to set the PATH for your environment (so that it gets the right Python from the environment and Scripts\\ on Windows).\nImagine you have created an environment called py33 by using:\nconda create -n py33 python=3.3 anaconda\n\nHere the folders are created by default in Anaconda\\envs... | [
199,
120,
19,
18,
9,
7,
5,
4,
3,
2,
0,
0,
0
] | [
"Window:\nconda activate environment_name\nMac: conda activate environment_name\n"
] | [
-1
] | [
"anaconda",
"conda",
"python",
"virtualenv"
] | stackoverflow_0020081338_anaconda_conda_python_virtualenv.txt |
Q:
Manipulating an array afterward so that the rows and column depends on the size of two strings
I am trying to manipulate array2 so that the row and column is dependent on the len of the strings as for array1
str1 = "Hi"
str2 = "Bye"
array1 = [[[0, 0] for y in range(len(str2)+1)] for x in range(len(str1)+1)]
print(... | Manipulating an array afterward so that the rows and column depends on the size of two strings | I am trying to manipulate array2 so that the row and column is dependent on the len of the strings as for array1
str1 = "Hi"
str2 = "Bye"
array1 = [[[0, 0] for y in range(len(str2)+1)] for x in range(len(str1)+1)]
print(array1)
#output: [[[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, ... | [
"The current code has no idea what to do with array2[i], array2[j] cause neither i nor j have been defined.\nThis code is working as expected (I've organized the output for better readability):\nstr1 = \"Hi\"\nstr2 = \"Bye\"\narray1 = [[[0, 0] for y in range(len(str2)+1)] for x in range(len(str1)+1)]\nprint(array1)... | [
0
] | [] | [] | [
"arrays",
"list",
"python",
"python_3.8",
"string"
] | stackoverflow_0074290941_arrays_list_python_python_3.8_string.txt |
Q:
Pyhton for loop "stale element reference: element is not attached to the page document"
python for loop "stale element reference: element is not attached to the page document"
here is my code
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options... | Pyhton for loop "stale element reference: element is not attached to the page document" | python for loop "stale element reference: element is not attached to the page document"
here is my code
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriv... | [
"I made a few fixes to your code:\n\nInserted user_agent (it will come in handy with other experiments on selenium)\ninserted a web driver manager to run selenium on all operating systems.\nYou have to accept cookies before you can interact with the page.\nremoved unnecessary sleep.\n\nThis is the result, code test... | [
1,
0
] | [] | [] | [
"for_loop",
"python",
"web_scraping"
] | stackoverflow_0074313372_for_loop_python_web_scraping.txt |
Q:
DCP error for quadratic optimization problem
I am using cvxpy to solve quadratic optimization problem. The quadratic problem is part of another optimization routine which iteratively feeds the quadratic optimization problem P matrix and q vector. The issue is if my number of variables are less than 20, then code r... | DCP error for quadratic optimization problem | I am using cvxpy to solve quadratic optimization problem. The quadratic problem is part of another optimization routine which iteratively feeds the quadratic optimization problem P matrix and q vector. The issue is if my number of variables are less than 20, then code runs fine. Anything above 20 leads to DCP error, wh... | [
"Maybe it has a slight negative eigenvalue after all (at least up to numerical precision)? Your code has a typo in the check. Replace\nnp.all(np.linalg.eigvals(K_XX))>1e-6\n\nwith\nnp.all(np.linalg.eigvals(K_XX)>1e-6)\n\nand check again.\n"
] | [
1
] | [] | [] | [
"cvxpy",
"python"
] | stackoverflow_0074308674_cvxpy_python.txt |
Q:
subtract Stock Sales list from Stock Purchases list Python
I have a list of both stock sales & purchases. The stock purchases list is as follows:
['AAPL', 5, 80], ['AAPL', 10, 85], ['CELH', 12, 85], ['CELH', 13, 75], ['BABA', 13, 50]
And the Sales list:
['CELH', -3, 97], ['AAPL', -8, 100], ['BABA', -8, 60], ['BAB... | subtract Stock Sales list from Stock Purchases list Python | I have a list of both stock sales & purchases. The stock purchases list is as follows:
['AAPL', 5, 80], ['AAPL', 10, 85], ['CELH', 12, 85], ['CELH', 13, 75], ['BABA', 13, 50]
And the Sales list:
['CELH', -3, 97], ['AAPL', -8, 100], ['BABA', -8, 60], ['BABA', -3, 40]
I would like to get a list of sales with their cost... | [
"This isn't the most elegant solution, but should produce results you indicated:\ndef stockFn(purchase, sale):\n return [sale[0], -sale[1], sale[2], purchase[2], -sale[0]*(sale[2]-purchase[2])]\n\np = ['BABA', 13, 50]\ns = ['BABA', -3, 40]\nprint(stockFn(p,s))\n# ['BABA', 3, 40, 50, -30]\n\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074307165_list_python.txt |
Q:
Clicking on Text using Selenium
I want to click on this checkbox:
<label for="auth:RegistrationForm:multistep[gtcAgbChechbox]" class="checkbox">
::before
Ich bestätige, dass ich die
<a href="/gtc" title="AGB" class="popup" data-title="gtc" data-funnelize="A::Click,O::###page###,T::Link,ST::GTC">AGB</a... | Clicking on Text using Selenium | I want to click on this checkbox:
<label for="auth:RegistrationForm:multistep[gtcAgbChechbox]" class="checkbox">
::before
Ich bestätige, dass ich die
<a href="/gtc" title="AGB" class="popup" data-title="gtc" data-funnelize="A::Click,O::###page###,T::Link,ST::GTC">AGB</a>
gelesen und akzeptiert habe.
</... | [
"there you can locate 4 things\n<label for=\"auth:RegistrationForm:multistep[gtcAgbChechbox]\" class=\"checkbox\">\n\nIch bestätige, dass ich die \n\n<a href=\"/gtc\" title=\"AGB\" class=\"popup\" data-title=\"gtc\" data-funnelize=\"A::Click,O::###page###,T::Link,ST::GTC\">AGB</a> \n\ngelesen und akzeptiert habe.</... | [
1
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074313600_python_selenium.txt |
Q:
Can pyximport.install() of Cython build more than 2 .pyx files simultaneously without setup.py?
(1) Can pyximport.install() of Cython build more than 2 cython files(.pyx) simultaneously without setup.py?
(2) If (1) can do, can the abstract class which is separated by implemented in the mechanism (1)?
MyCode
I wan... | Can pyximport.install() of Cython build more than 2 .pyx files simultaneously without setup.py? |
(1) Can pyximport.install() of Cython build more than 2 cython files(.pyx) simultaneously without setup.py?
(2) If (1) can do, can the abstract class which is separated by implemented in the mechanism (1)?
MyCode
I want to implement the abstract class in .pyx files. And my python code (written in abst_cls2main.py) w... | [
"most of the info taken from cython documentation sharing declarations and cython documentation extension types\nyou need to declare a header file for abst_cls2base.pyx with name abst_cls2base.pxd which defines the class\n# FILENAME: abst_cls2base.pxd\n# cython: language_level=3\n# distutils: language = c++\n\ncdef... | [
1
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0074313055_cython_python.txt |
Q:
cannot set flask environment variable in macos
After typing
export FLASK_APP=use_flask.py
And then typing
printenv
which outputs inter alia:
TERM_SESSION_ID=AA805368-CF19-4631-AABB-A0112AD535CE
FLASK_APP=/users/me/documents/pcode/color/use_flask.py
USER=me
CONDA_EXE=/Users/me/Applications/miniconda3/bin/conda
... | cannot set flask environment variable in macos | After typing
export FLASK_APP=use_flask.py
And then typing
printenv
which outputs inter alia:
TERM_SESSION_ID=AA805368-CF19-4631-AABB-A0112AD535CE
FLASK_APP=/users/me/documents/pcode/color/use_flask.py
USER=me
CONDA_EXE=/Users/me/Applications/miniconda3/bin/conda
I then place in the file use_flask.py
from flask imp... | [
"I ran\npip install flask flask-alchemy\nI thought I already had flask installed because when I typed\nfrom flask import Flask\ninto my Pycharm editor and then ran the code no error message occurred. So although I solved the problem I don't understand why it didn't work the first time.\n"
] | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074313494_flask_python.txt |
Q:
How do I stop my scraper from hitting an error whenever it clicks the next button?
Hello so i'm trying to scrape next page on google shopping website. But i get an error whenever my scraper clicks the next button. It stops working when it loads the next page.
Here's my codeblock
from selenium import webdriver
impo... | How do I stop my scraper from hitting an error whenever it clicks the next button? | Hello so i'm trying to scrape next page on google shopping website. But i get an error whenever my scraper clicks the next button. It stops working when it loads the next page.
Here's my codeblock
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.co... | [
"That error means when it's looking for that element 'OSrXXb' it can't find it. You have a bunch of other elements wrapped in try blocks but it seems this one you expect to be there and it isn't.\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074313722_python_selenium_selenium_webdriver.txt |
Q:
When should I Modularize code in notebooks
I m aware that code can be modularized in Databtricks notebooks, (with the commant %run) but I m not sure when to do it.(at what point)
Currently I have a notebook that does a specific task(tha is to say, it does not make sense to divide the notebook into parts) but in tu... | When should I Modularize code in notebooks | I m aware that code can be modularized in Databtricks notebooks, (with the commant %run) but I m not sure when to do it.(at what point)
Currently I have a notebook that does a specific task(tha is to say, it does not make sense to divide the notebook into parts) but in turn this notebook use many funcions, so many that... | [
"I would define functions in the notebook when it is interesting or useful to see them there. For example, if I need to modify the function, or the notebook is quite focused on its functionality.\nOn the other side, if I have, lets say, a list of implemented algorithms and I'm comparing them in the notebook, it mig... | [
3
] | [] | [] | [
"databricks",
"jupyter_notebook",
"python"
] | stackoverflow_0074313749_databricks_jupyter_notebook_python.txt |
Q:
Hot to use pytest capture logging.debug
This is a test example from pytest document, and I change print to logging.warning.
import logging
def test_myoutput(capsys): # or use "capfd" for fd-level
print("hello")
logging.warning("world")
captured = capsys.readouterr()
assert captured.out == "hello\... | Hot to use pytest capture logging.debug | This is a test example from pytest document, and I change print to logging.warning.
import logging
def test_myoutput(capsys): # or use "capfd" for fd-level
print("hello")
logging.warning("world")
captured = capsys.readouterr()
assert captured.out == "hello\n"
assert captured.out == "world\n"
... | [
"It is documented, no? Apparently, pytest does it itself. https://docs.pytest.org/en/7.1.x/how-to/logging.html\n"
] | [
1
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074311432_pytest_python.txt |
Q:
Variable not updated on class file and pass to main in python
I try to update variable from another class file to main file but it wont update. I have a lot of variable need to set
Example below
var_global.py
BarCode1 = ""
BarCode2 = ""
BarCode3 = ""
BarCode4 = ""
BarCode5 = ""
BarCode6 = ""
BarCode7 = ""
Class_S... | Variable not updated on class file and pass to main in python | I try to update variable from another class file to main file but it wont update. I have a lot of variable need to set
Example below
var_global.py
BarCode1 = ""
BarCode2 = ""
BarCode3 = ""
BarCode4 = ""
BarCode5 = ""
BarCode6 = ""
BarCode7 = ""
Class_ServerThread.py
import var_global
from threading import Thread
clas... | [
"I move import var_global inside while True: on main.py & and Class_ServerThread.py. Its working now.\nClass_ServerThread.py\n\nfrom threading import Thread\n\nclass SocketServerThread(Thread):\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n while True:\n import var_global\n ... | [
0
] | [] | [] | [
"python",
"python_2.7",
"python_multithreading",
"raspberry_pi"
] | stackoverflow_0074313381_python_python_2.7_python_multithreading_raspberry_pi.txt |
Q:
options parameter is not detected by ChromeDriverManager() in python
I try to use both webdriver and ChromeDriverManager at the same time including options but always it returns an error:
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install(), options=options)) TypeError: __init__() got an unex... | options parameter is not detected by ChromeDriverManager() in python | I try to use both webdriver and ChromeDriverManager at the same time including options but always it returns an error:
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install(), options=options)) TypeError: __init__() got an unexpected keyword argument 'options'
My code is:
from selenium import webdriv... | [
"You have to call it like this:\ndriver = webdriver.Chrome( \n service=Service(\n ChromeDriverManager().install()\n ),\n options=options\n)\n\n"
] | [
1
] | [] | [] | [
"python",
"selenium_webdriver"
] | stackoverflow_0074313812_python_selenium_webdriver.txt |
Q:
TypeError: 'NoneType' object is not subscriptable while using fetchone()
cur.execute("""
CREATE TEMPORARY VIEW bobby_view AS
SELECT heading1, heading2
FROM bobby
WHERE heading2 = %s; """, (variable,))
cur.execute("""
SELECT d1.heading1
... | TypeError: 'NoneType' object is not subscriptable while using fetchone() | cur.execute("""
CREATE TEMPORARY VIEW bobby_view AS
SELECT heading1, heading2
FROM bobby
WHERE heading2 = %s; """, (variable,))
cur.execute("""
SELECT d1.heading1
FROM bobby_view d1
WHERE d1.heading1 >= ALL (
... | [
"you can refer the documentation here\nfetchone returns the next row of a query result set and returns a single sequence, or None if no more rows are available, so if you are fetching the last row the error will occur. Try something like this,\nanswer = cur.fetchone()\nwhile answer is not None:\n print(answer)\n ... | [
0,
0
] | [] | [] | [
"embedded_postgres",
"postgresql",
"python",
"sql"
] | stackoverflow_0074313801_embedded_postgres_postgresql_python_sql.txt |
Q:
I am trying to build an AWS Lambda function from a dockerfile deployed over CDK
lambdaFunction = _lambda.DockerImageFunction(self, f'{client_id}-prefect-lambda-handler',
code=_lambda.DockerImageCode.from_image_asset(
directory="... | I am trying to build an AWS Lambda function from a dockerfile deployed over CDK | lambdaFunction = _lambda.DockerImageFunction(self, f'{client_id}-prefect-lambda-handler',
code=_lambda.DockerImageCode.from_image_asset(
directory="cumulus_devops_cdk/prefect-lambda-handler"
),... | [
"You can build and publish the image to Amazon ECR outside of the AWS CDK, and then reference that image using _lambda.DockerImageCode.fromEcr(repository, props?) [1]\n[1] https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-lambda.DockerImageCode.html#static-fromwbrecrrepository-props\n",
"This is as Docker ... | [
0,
0
] | [] | [] | [
"amazon_web_services",
"aws_cdk",
"aws_lambda",
"docker",
"python"
] | stackoverflow_0074305846_amazon_web_services_aws_cdk_aws_lambda_docker_python.txt |
Q:
sum every nth row create new column and apply the same value every 3 rows on that column
I have a dataframe as such
Date Search Volume
Jan 2004 80,000
Feb 2004 90,000
Mar 2004 100,000
Apr 2004 40,000
May 2004 60,000
Jun 2004 50,000
I... | sum every nth row create new column and apply the same value every 3 rows on that column | I have a dataframe as such
Date Search Volume
Jan 2004 80,000
Feb 2004 90,000
Mar 2004 100,000
Apr 2004 40,000
May 2004 60,000
Jun 2004 50,000
I wish to have an output like this:
Date Search Volume Total Quarter
... | [
"First convert column Search Volume to numeric by Series.str.replace and casting to integers or floats, then convert dates to quarters by to_datetime and Series.dt.to_period and for new column use GroupBy.transform with sum per quarters:\ndef func(df):\n df['Search Volume'] = df['Search Volume'].str.replace(',',... | [
1
] | [] | [] | [
"arrays",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074313897_arrays_dataframe_pandas_python.txt |
Q:
Is there a bug when defined the return type of a function? As `def xxx() -> str:`, code highlight whill be display error when I use `->`
As def xxx() -> str:, code highlight whill be display error when I use ->
It's not a bug of the theme
If it can be solved by setting rules, can you help me solve it? Or a bug?
... | Is there a bug when defined the return type of a function? As `def xxx() -> str:`, code highlight whill be display error when I use `->` | As def xxx() -> str:, code highlight whill be display error when I use ->
It's not a bug of the theme
If it can be solved by setting rules, can you help me solve it? Or a bug?
| [
"You may have Inlay Type Hints enabled. Follow the steps below to disable.\nFile --> Preferences --> Settings, Search for python inlay hints, uncheck the two options in the picture.\n\nOr directly add the following configuration in the settings.json file\n \"python.analysis.inlayHints.functionReturnTypes\": fals... | [
1,
1
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074284777_python_visual_studio_code.txt |
Q:
Customizing schemas in marshmallow
Consider the following schema:
from pprint import pprint
from marshmallow import Schema, fields, validate, ValidationError
class UserSchema(Schema):
name = fields.Str(required= True, validate=validate.Length(min=1))
permission = fields.Str(required =True, validate=valid... | Customizing schemas in marshmallow | Consider the following schema:
from pprint import pprint
from marshmallow import Schema, fields, validate, ValidationError
class UserSchema(Schema):
name = fields.Str(required= True, validate=validate.Length(min=1))
permission = fields.Str(required =True, validate=validate.OneOf(["read", "write", "admin"]))
... | [
"I suppose you could modify the required attribute for the field but I wouldn't recommend that.\nI would remove the required constraint on the field and add a schema-level validator that would fail if the field is missing only when business logic makes it required.\n"
] | [
0
] | [] | [] | [
"marshmallow",
"python",
"validation"
] | stackoverflow_0074187456_marshmallow_python_validation.txt |
Q:
Query only existing elements in an ArrayField
from django.contrib.postgres.fields import ArrayField
from django.db import models
class Post(models.Model):
name = models.CharField(max_length=200)
tags = ArrayField(models.CharField(max_length=200), blank=True)
Post.objects.create(name='a', tags=['1'])
Post... | Query only existing elements in an ArrayField | from django.contrib.postgres.fields import ArrayField
from django.db import models
class Post(models.Model):
name = models.CharField(max_length=200)
tags = ArrayField(models.CharField(max_length=200), blank=True)
Post.objects.create(name='a', tags=['1'])
Post.objects.create(name='b', tags=['1', '2'])
Post.obj... | [
"You can use contains in the filter.\nExample for your case:\nPost.objects.filter(tags__contains=['1','2'])\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"postgresql",
"python"
] | stackoverflow_0074313892_django_django_models_postgresql_python.txt |
Q:
How to Decode GEOHASH Column using PySpark
I'm trying to decode the GEOHASH to Latitude and Longitude using the pygeohash library. Below is my code
import pygeohash as pgh
from pyspark.sql.types import StringType
udf1 = udf(lambda x: pgh.decode(x))
add_latlong = add.withColumn('location', udf1(col('GEOHASH')))
H... | How to Decode GEOHASH Column using PySpark | I'm trying to decode the GEOHASH to Latitude and Longitude using the pygeohash library. Below is my code
import pygeohash as pgh
from pyspark.sql.types import StringType
udf1 = udf(lambda x: pgh.decode(x))
add_latlong = add.withColumn('location', udf1(col('GEOHASH')))
However, I'm getting the result below:
+---------... | [
"I'm not sure if your case is the same as the link you provided, since you are using external package to do the transformation pgh.decode(x). Based on the docs:\npgh.decode(geohash='ezs42')\n# >>> ('42.6', '-5.6')\n\nI think you should use ArrayType(FloatType()) instead.\n"
] | [
1
] | [] | [] | [
"geohashing",
"pyspark",
"python"
] | stackoverflow_0074313763_geohashing_pyspark_python.txt |
Q:
how to use one function respone into another function in the same class?
We are developing a custom source connector for Airbytewhere we are pulling data from its API's. The connector has an API to pull data for each form_id. We can pass different form_ids in our connector as an array of form_id initially so it ca... | how to use one function respone into another function in the same class? | We are developing a custom source connector for Airbytewhere we are pulling data from its API's. The connector has an API to pull data for each form_id. We can pass different form_ids in our connector as an array of form_id initially so it can pull data from different forms. For every form, we create a new stream with ... | [
"If I understand your question correctly, you may self.response_json = response.json() and use json_schema = self.response_json in get_json_schema.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074313934_python.txt |
Q:
How to pass a JSON file in html form and display its content in tabular form [python flask]
Html form takes json file as input
this is my script, I'm able to get the file as input but not able to read it.
from flask import Flask, render_template, request, redirect, jsonify, json
import os
app=Flask(__name__)
app.... | How to pass a JSON file in html form and display its content in tabular form [python flask] | Html form takes json file as input
this is my script, I'm able to get the file as input but not able to read it.
from flask import Flask, render_template, request, redirect, jsonify, json
import os
app=Flask(__name__)
app.config["FILE_UPLOAD"]=""
@app.route('/')
def index():
return render_template("form.html")
... | [
"You don't need save file to local. Jf is io.BytesIO so we only need decode and json.loads to convert to json. Try it:\njf =request.files[\"file\"]\ndata = jf.read().decode(\"utf8\")\njdata = json.loads(data)\nreturn jsonify(jdata)\n\n"
] | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074313136_flask_python.txt |
Q:
Get fields from a specific Jira issue
I'm trying to get all the fields and values from a specific issue my code:
authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))
issue = authenticated_jira.issue(self.id)
print issue.fields()
Instead of returning... | Get fields from a specific Jira issue | I'm trying to get all the fields and values from a specific issue my code:
authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))
issue = authenticated_jira.issue(self.id)
print issue.fields()
Instead of returning the list of fields it returns:
<jira.resou... | [
"authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))\nissue = authenticated_jira.issue(self.id) \n\nfor field_name in issue.raw['fields']:\n print \"Field:\", field_name, \"Value:\", issue.raw['fields'][field_name]\n\nDepends on field type, sometim... | [
37,
14,
5,
0
] | [] | [] | [
"jira_rest_api",
"python",
"python_jira"
] | stackoverflow_0030615846_jira_rest_api_python_python_jira.txt |
Q:
How to avoid the QueuePool limit error using Flask-SQLAlchemy?
I'm developing a webapp using Flask-SQLAlchemy and a Postgre DB, then I have this dropdown list in my webpage which is populated from a select to the DB, after selecting different values for a couple of times I get the "sqlalchemy.exc.TimeoutError:".
M... | How to avoid the QueuePool limit error using Flask-SQLAlchemy? | I'm developing a webapp using Flask-SQLAlchemy and a Postgre DB, then I have this dropdown list in my webpage which is populated from a select to the DB, after selecting different values for a couple of times I get the "sqlalchemy.exc.TimeoutError:".
My package's versions are:
Flask-SQLAlchemy==2.5.1
psycopg2-binary==2... | [
"You are leaking connections.\nA little counterintuitively,\nyou may find you obtain better results with a lower pool limit.\nA given python thread only needs a single pooled connection,\nfor the simple single-database queries you're doing.\nSetting the limit to 1, with 0 overflow,\nwill cause you to notice a leake... | [
2,
1,
0
] | [] | [] | [
"flask_sqlalchemy",
"postgresql",
"python"
] | stackoverflow_0070625689_flask_sqlalchemy_postgresql_python.txt |
Q:
Filter method in Python is not working as expected for strings
I am filtering a list of strings according to the following condition.
list_of_strings = ["foo-bar", "foo", "bar"]
print(list(filter(lambda x: x is not "foo-bar", list_of_strings)))
>>> ["foo-bar", "foo", "bar"] # This is output. But I expected "foo-b... | Filter method in Python is not working as expected for strings | I am filtering a list of strings according to the following condition.
list_of_strings = ["foo-bar", "foo", "bar"]
print(list(filter(lambda x: x is not "foo-bar", list_of_strings)))
>>> ["foo-bar", "foo", "bar"] # This is output. But I expected "foo-bar" to be removed
But this is working fine with !=
How is this happ... | [
"The problem is in the filtering condition. Should be:\nlambda x: x != \"foo-bar\"\n\nTo compare two strings use != and == (equality test).\nis is a test for an identical object.\n\n>>> \"A\" is \"A\"\nTrue\n\nThis is an efect of an optimisation called interning. If a constant is used several times, the Python inte... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074314019_python.txt |
Q:
How to speed up nested for loop with string values in Python
I want to loop through a dictionary of values that contain protein sequences in letters. The dictionary could be as large as 200,000 keys.
Using a for loop, it takes way too long. Below is my current implementation.
def find_msa_diversity(seq_dict):
... | How to speed up nested for loop with string values in Python | I want to loop through a dictionary of values that contain protein sequences in letters. The dictionary could be as large as 200,000 keys.
Using a for loop, it takes way too long. Below is my current implementation.
def find_msa_diversity(seq_dict):
"""Find the diversity of the MSA"""
summation = 0
for n... | [
"You doing redundant and repeating work, take this example\nLets assume you have 3 sequences in your dictionary\nS1, S2, S3\nYour algorithm will check\nS1 S1 (You already know this is 1.0 because they are equal)\nS1 S2\nS1 S3\nS2 S1 (You already calculated this previously, it was S1 S2)\nS2 S2 (You already know thi... | [
1,
1
] | [] | [] | [
"bioinformatics",
"multiprocessing",
"numpy",
"python"
] | stackoverflow_0074313799_bioinformatics_multiprocessing_numpy_python.txt |
Q:
Pyenv's python is missing bzip2 module
I used pyenv to install python 3.8.2 and to create a virtualenv.
In the virtualenv, I used pipenv to install pandas.
However, when importing pandas, I'm getting the following:
[...]
File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/comm... | Pyenv's python is missing bzip2 module | I used pyenv to install python 3.8.2 and to create a virtualenv.
In the virtualenv, I used pipenv to install pandas.
However, when importing pandas, I'm getting the following:
[...]
File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module>
import bz2
... | [
"On macOS Big Sur, to get pyenv ( via homebrew ) to work I had to install zlib and bzip2 via homebrew and then add the exports in my ~/.zshrc ( or ~/.bashrc for bash I guess). The answer above by luislhl leads the way to my solution.\nbrew install zlib bzip2\n\n#Add the following to your ~/.zshrc\n# For pyenv to b... | [
15,
4,
1,
1
] | [] | [] | [
"bzip2",
"pyenv",
"python"
] | stackoverflow_0060775172_bzip2_pyenv_python.txt |
Q:
os.replace unexpected behaviour
To write to a log file on a linux system, I first create a temporary file with all of the content. Afterward, I replace the log file with os.replace because it is said to be atomic.
if os.path.exists(log_file_path):
with open(log_file_path, 'r') as f:
existing = json.loa... | os.replace unexpected behaviour | To write to a log file on a linux system, I first create a temporary file with all of the content. Afterward, I replace the log file with os.replace because it is said to be atomic.
if os.path.exists(log_file_path):
with open(log_file_path, 'r') as f:
existing = json.load(f)
else:
existing = list()
exis... | [
"You wrote some data to the temporary file, then the process got shut down before it could finish.\nThen on the next run, you appended new data to the half-written garbage from the previous run, instead of discarding that garbage, because your code opens the temporary file in a+ mode instead of w or w+ mode.\nThen ... | [
2
] | [] | [] | [
"file",
"linux",
"python"
] | stackoverflow_0074314018_file_linux_python.txt |
Q:
Queue (multiprocessing) where you can get each value twice
Is there any option to have a multiprocessing Queue where each value can be accessed twice?
My problem is I have one "Generator process" creating a constant flux of data and would like to access this in two different process each doing it's thing with the ... | Queue (multiprocessing) where you can get each value twice | Is there any option to have a multiprocessing Queue where each value can be accessed twice?
My problem is I have one "Generator process" creating a constant flux of data and would like to access this in two different process each doing it's thing with the data.
A minimal "example" of the issue.
import multiprocessing a... | [
"One way to solve your problem is, first, to use multiprocessing.Array to share, let's say, a numpy array with your data between worker processes. Second, use a multiprocessing.Barrier to synchronize the main process and the workers when generating and processing data batches. And, finally, provide each process wor... | [
1
] | [] | [] | [
"multiprocessing",
"python",
"queue"
] | stackoverflow_0074307111_multiprocessing_python_queue.txt |
Q:
Is MergeSort or QuickSort more efficient with arrays between 100 and 1000 elements?
I am implementing a sorting algorithm in python, and want to know whether MergeSort or QuickSort would have a better average case.
Are there any programs that can compare the efficiency of these sorting algorithms given an array wi... | Is MergeSort or QuickSort more efficient with arrays between 100 and 1000 elements? | I am implementing a sorting algorithm in python, and want to know whether MergeSort or QuickSort would have a better average case.
Are there any programs that can compare the efficiency of these sorting algorithms given an array with n elements?
Which algorithm is generally faster (not a specific case)?
| [
"QuickSort has worst case O(n²) and mergeSort O(n log n). So if you know nothing about your specific input, in worst case mergeSort is faster.\nIf your input has charactaristicas that avoid this worst case for QuickSort, it might be quicker on average.\nI recommend simply profile both algorithms with a big enough s... | [
1
] | [] | [] | [
"algorithm",
"mergesort",
"performance",
"python",
"sorting"
] | stackoverflow_0074312303_algorithm_mergesort_performance_python_sorting.txt |
Q:
Python Touples - Keep only the largest value if First item is found duplicate
I have a python list of touples like this:
touple = [('Northwest Airlines', 93),
('Northwest Airlines', 81),
('Southwest Airlines', 79),
('NorthWestern', 77),
('NorthWestern', 69),
('Sout... | Python Touples - Keep only the largest value if First item is found duplicate | I have a python list of touples like this:
touple = [('Northwest Airlines', 93),
('Northwest Airlines', 81),
('Southwest Airlines', 79),
('NorthWestern', 77),
('NorthWestern', 69),
('Southwest Airlines', 69)]
Several of these items are duplicate. I want to keep only un... | [
"tmp = dict((y, x) for x, y in touple)\n\nmy_dict = dict()\nfor val, key in tmp.items():\n if key not in my_dict.keys():\n my_dict[key] = val\n else:\n if my_dict[key] < val:\n my_dict[key] = val\n\nOutput: my_dict\n {'Northwest Airlines': 93, 'Southwest Airlines': 79, 'NorthWestern':... | [
1,
1
] | [] | [] | [
"arrays",
"python",
"sorting"
] | stackoverflow_0074314139_arrays_python_sorting.txt |
Q:
Is there any way to monkey patch builtin parentheses [], (), {} behaviour? (in python 3 code, without modifying C/interpreter)
I am just checking where is the limit of changing python using python (without modifying interpreter and/or C code).
I know that I can basically monkey patch every builtin function like th... | Is there any way to monkey patch builtin parentheses [], (), {} behaviour? (in python 3 code, without modifying C/interpreter) | I am just checking where is the limit of changing python using python (without modifying interpreter and/or C code).
I know that I can basically monkey patch every builtin function like this:
import builtins
int(1)
# 1
def new_int(number):
return number + 1
builtins.int = new_int
int(1)
# 2
I know I can turn pyt... | [
"This can be done as a function decorator as long as the lists to be replaced as tuples are defined in a function.\nTo do that, use ast.NodeTransformer to replace any ast.List node with an equivalent ast.Tuple node in the function's AST:\nimport ast\nimport inspect\nfrom textwrap import dedent\n\nclass ForceTuples(... | [
3
] | [] | [] | [
"built_in",
"monkeypatching",
"python"
] | stackoverflow_0074311394_built_in_monkeypatching_python.txt |
Q:
Slideshow editing with Jupyter Lab
The new Jupyter Lab is great, but I am missing the option to turn cells into slides. In classic Jupyter Notebooks, that was under "View > Cell Toolbar > Slideshow":
What happened to the feature? Is there a way to edit slides in Jupyter Lab?
A:
I have jupyter lab 1.1.4 installe... | Slideshow editing with Jupyter Lab | The new Jupyter Lab is great, but I am missing the option to turn cells into slides. In classic Jupyter Notebooks, that was under "View > Cell Toolbar > Slideshow":
What happened to the feature? Is there a way to edit slides in Jupyter Lab?
| [
"I have jupyter lab 1.1.4 installed on Ubuntu 18.04.3 LTS and am using a python 3 virtual env kernel and it works great. Just complete your notebook and then configure each cell using the \"Notebook Tools\" tab on the far left (as shown in screenshot). Then save and close the notebook and run below command to outpu... | [
11,
5,
2,
0
] | [] | [] | [
"jupyter",
"jupyter_lab",
"jupyter_notebook",
"python"
] | stackoverflow_0052677085_jupyter_jupyter_lab_jupyter_notebook_python.txt |
Q:
Building wheel for pycocotools (pyproject.toml) did not run successfully
I am trying to clone the YOLOv6 repo and install the requirements. Then the error occur -
`
Building wheel for pycocotools (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for pycocotools (pyproject.toml) ... | Building wheel for pycocotools (pyproject.toml) did not run successfully | I am trying to clone the YOLOv6 repo and install the requirements. Then the error occur -
`
Building wheel for pycocotools (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for pycocotools (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [16 lines of output]
ru... | [
"Just reading inside the error:\nerror: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n\nYou need a compiler, since you are trying to compile a library in Windows!\nGo grab the proper tools in https://visualstu... | [
0
] | [] | [] | [
"pip",
"pycocotools",
"pyproject.toml",
"python",
"yolo"
] | stackoverflow_0074312019_pip_pycocotools_pyproject.toml_python_yolo.txt |
Q:
Execute Python Script (spyder) from Excel using VBA
I have a problem regarding the question's title:
A quick intro to my situation: I'm using python within spyder and my Code (multiple hundred lines) includes a bloomberg-python api. Because I'm using multiple tickers, the code's execution time is about 24sec. The ... | Execute Python Script (spyder) from Excel using VBA | I have a problem regarding the question's title:
A quick intro to my situation: I'm using python within spyder and my Code (multiple hundred lines) includes a bloomberg-python api. Because I'm using multiple tickers, the code's execution time is about 24sec. The code will import some data from the same sheet I want to ... | [
"Does the python code depend on the working directory in which it is run? i.e. does it find excel A using a relative path?\nBecause if this is the case, then maybe the python script being executed in the VBA code is using a different directory from the one you have used when you were developing and testing your cod... | [
0
] | [] | [] | [
"blpapi",
"excel",
"interaction",
"python",
"vba"
] | stackoverflow_0074314193_blpapi_excel_interaction_python_vba.txt |
Q:
How to use progressbar module with urlretrieve
My pyhton3 script downloads a number of images over the internet using urlretrieve, and I'd like to add a progressbar with a completed percentage and download speed for each download.
The progressbar module seems like a good solution, but although I've looked through... | How to use progressbar module with urlretrieve | My pyhton3 script downloads a number of images over the internet using urlretrieve, and I'd like to add a progressbar with a completed percentage and download speed for each download.
The progressbar module seems like a good solution, but although I've looked through their examples, and example4 seems like the right t... | [
"The suggestion in the other answer did not progress for me past 1%. Here is a complete implementation that works for me on Python 3:\nimport progressbar\nimport urllib.request\n\n\npbar = None\n\n\ndef show_progress(block_num, block_size, total_size):\n global pbar\n if pbar is None:\n pbar = progress... | [
20,
14,
3,
0
] | [] | [] | [
"progress_bar",
"python",
"python_3.x"
] | stackoverflow_0037748105_progress_bar_python_python_3.x.txt |
Q:
Is there a "function comprehension" to change a value in python
Data is a list of lists, ig. [[1, 0], [0, 1], [1, 1]]
I have these two lines which get an average of val[0] in a list data based on if val[1] is 0
l = [val[0] for val in data if val[1] == 0]
return sum(l)/len(l)
Is there a way to calculate the sum wh... | Is there a "function comprehension" to change a value in python | Data is a list of lists, ig. [[1, 0], [0, 1], [1, 1]]
I have these two lines which get an average of val[0] in a list data based on if val[1] is 0
l = [val[0] for val in data if val[1] == 0]
return sum(l)/len(l)
Is there a way to calculate the sum while doing the list comprehension?
| [
"Your question is a bit vague to me but I'm trying to give some information...\nList-comprehension is supposed to create a list for you. \"A syntax which creates lists\". So it really depends on which value you need to exist after the iteration. Is it just the average? the result list? the sum?\nIf you want to have... | [
1,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0074307106_list_list_comprehension_python.txt |
Q:
XGBoost custom squarederror loss function not working similar to default implementation
I've recently been trying to implement the default reg:squarederror loss function for xgboost regression, to enable me to later change it to an asymmetrical function on the basis of this function. However, I've not been able to... | XGBoost custom squarederror loss function not working similar to default implementation | I've recently been trying to implement the default reg:squarederror loss function for xgboost regression, to enable me to later change it to an asymmetrical function on the basis of this function. However, I've not been able to get the same results with my custom version compared to the default implementation.
Here's t... | [
"Try\n def squared_error(predt: np.ndarray, dtrain: xgb.DMatrix):\n y = dtrain.get_label()\n grad = y - pred\n hess = np.ones(y.shape)\n return grad, hess\n\nThen it should work\n"
] | [
0
] | [] | [] | [
"data_science",
"machine_learning",
"python",
"regression",
"xgboost"
] | stackoverflow_0071178313_data_science_machine_learning_python_regression_xgboost.txt |
Q:
get unique labels of a list and convert to dataframe for plotting
i have a set of lists and i need the labels to be a single column in a dataframe and the values in label that is not in the value(after the merge) should be 0.
label = [0, 2, 1, 3, 4, 9, 8, 24, 86, 5] value = [103, 16, 10, 9, 5, 4, 4, 3, 3, 3]
labe... | get unique labels of a list and convert to dataframe for plotting | i have a set of lists and i need the labels to be a single column in a dataframe and the values in label that is not in the value(after the merge) should be 0.
label = [0, 2, 1, 3, 4, 9, 8, 24, 86, 5] value = [103, 16, 10, 9, 5, 4, 4, 3, 3, 3]
label1 = [0, 2, 3, 1, 9, 15, 4, 6, 5, 23] value1 = [73, 14, 8, 7, 3, 3, 3, ... | [
"one way to do this is to use outer merge, which will merge columns of dataframe based on the column you choose. Below is the code. First convert the label-value pairs into dataframes, then merge the 3 dataframes. Finally, change the column names to what you want to see...\n## Your data\nlabel = [0, 2, 1, 3, 4, 9, ... | [
0
] | [] | [] | [
"dataframe",
"list",
"python",
"python_3.x",
"visualization"
] | stackoverflow_0074308865_dataframe_list_python_python_3.x_visualization.txt |
Q:
Django orm queries with left varaible is not certain
I want to make a query like this:
Student.objects.filter(id= id).update(name=value)
And the value comes from the user.
But the problem is that I'm not only to update name but also update some
other information like address or phone number. I don't want t... | Django orm queries with left varaible is not certain | I want to make a query like this:
Student.objects.filter(id= id).update(name=value)
And the value comes from the user.
But the problem is that I'm not only to update name but also update some
other information like address or phone number. I don't want to create duplicated codes
like:
Student.objects.filter(id=... | [
"As per update docs\n\nYou can update multiple fields — there’s no limit on how many\n\nSo the following should do\nStudent.objects.filter(id=id).update(address=address_value, phone_number=phone_number_value)\n\nEDIT\n\nleft variable is not a fixed item. It could be address or just be phone_number\n\nIn that case p... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074314203_django_python.txt |
Q:
No module name pyspark error
This is the exact code from a tutorial I'm following. My classmate didn't get this error with the same code:
ImportError Traceback (most recent call last)
<ipython-input-1-c6e1bed850ab> in <module>()
----> 1 from pyspark import SparkContext
2 sc = ... | No module name pyspark error | This is the exact code from a tutorial I'm following. My classmate didn't get this error with the same code:
ImportError Traceback (most recent call last)
<ipython-input-1-c6e1bed850ab> in <module>()
----> 1 from pyspark import SparkContext
2 sc = SparkContext('local', 'Exam_3')
... | [
"You don't have pyspark installed in a place available to the python installation you're using. To confirm this, on your command line terminal, with your virtualenv activated, enter your REPL (python) and type import pyspark:\n$ python\nPython 3.5.0 (default, Dec 3 2015, 09:58:14) \n[GCC 4.2.1 Compatible Apple LLV... | [
33,
18,
12,
2,
0,
0,
0,
0
] | [] | [] | [
"pyspark",
"python"
] | stackoverflow_0034302314_pyspark_python.txt |
Q:
How to get a list of unique python modules imported from different scripts located in different folders
I have a project contained in a folder (src). It is divided into different folders and each one contains some script .py. An example of the project structure is the following:
├── src <- Source co... | How to get a list of unique python modules imported from different scripts located in different folders | I have a project contained in a folder (src). It is divided into different folders and each one contains some script .py. An example of the project structure is the following:
├── src <- Source code for use in this project.
│ │
│ ├── data <- Scripts to download or generate data.
│ │
│ ├... | [
"Run this script from src folder:\nimport pathlib\n\npath = pathlib.Path.cwd()\nmodules = set()\n\nfor file in path.glob('**/*.py'):\n lines = file.read_text(encoding='utf-8')\n for line in lines.split('\\n'):\n if line.startswith('import ') or line.startswith('from '):\n modules.add(line.sp... | [
1
] | [] | [] | [
"package",
"project_structure",
"python",
"python_module"
] | stackoverflow_0074313937_package_project_structure_python_python_module.txt |
Q:
pytest does not pass along environment variables for functional tests from root folder
So, I have my app structured like this:
# container.py
class Container(containers.DeclarativeContainer):
wiring_config = containers.WiringConfiguration(modules=[".routes"])
print(f"$$$$$$$\n testinggggg - {os.environ.ge... | pytest does not pass along environment variables for functional tests from root folder | So, I have my app structured like this:
# container.py
class Container(containers.DeclarativeContainer):
wiring_config = containers.WiringConfiguration(modules=[".routes"])
print(f"$$$$$$$\n testinggggg - {os.environ.get('ENV')}\n$$$$$$")
config = providers.Configuration(
yaml_files=[
"... | [
"This is most probably due to the execution order of the fixtures. app fixture seems to rely on what mock_settings_env_vars sets up. However, app has the scope set to session and should therefore run before mock_settings_env_vars that has the scope set to module. The unexpected thing in my opinion is that it actual... | [
0
] | [] | [] | [
"pytest",
"python",
"python_3.x"
] | stackoverflow_0074311386_pytest_python_python_3.x.txt |
Q:
Django add optional arguments to decorator
I have the following decorator and view which works fine.
Decorator
def event_admin_only(func):
"""
Checks if the current role for the user is an Event Admin or not
"""
def decorator(request, *args, **kwargs):
event = get_object_or_404(Event, slug=... | Django add optional arguments to decorator | I have the following decorator and view which works fine.
Decorator
def event_admin_only(func):
"""
Checks if the current role for the user is an Event Admin or not
"""
def decorator(request, *args, **kwargs):
event = get_object_or_404(Event, slug=kwargs['event_slug'])
allowed_roles = [... | [
"You need to wrap the decorator function creation in another function:\ndef the_decorator(arg1, arg2):\n\n def _method_wrapper(view_method):\n\n def _arguments_wrapper(request, *args, **kwargs) :\n \"\"\"\n Wrapper with arguments to invoke the method\n \"\"\"\n\n ... | [
19,
0
] | [] | [] | [
"decorator",
"django",
"python"
] | stackoverflow_0009030255_decorator_django_python.txt |
Q:
xgboost predict contrib to probabilities
I am using xgboost's feature pred_contribs in order to get kind of interpretability (shapley values) for each sample of my model.
booster.predict(test, pred_contribs=True)
It returns a vector of contribution of shape (number of sample) x (number of features). Contributions... | xgboost predict contrib to probabilities | I am using xgboost's feature pred_contribs in order to get kind of interpretability (shapley values) for each sample of my model.
booster.predict(test, pred_contribs=True)
It returns a vector of contribution of shape (number of sample) x (number of features). Contributions sum is equal to the margin score.
But, I woul... | [
"I am not sure that it is the same question and answer, you might want to take a look at my answer at a similar question here.\nBasically, you divide your vector of contributions by its sum, and multiply it by the predicted probability:\ncontributions = contributions / sum(contributions) * predicted_probability whe... | [
0
] | [] | [] | [
"data_science",
"machine_learning",
"python",
"xgboost"
] | stackoverflow_0055067176_data_science_machine_learning_python_xgboost.txt |
Q:
Reading the output of a HID hand held barcode scanner in Python on Windows
I'm currently trying to write a service that should programmatically intercepts the output of a barcode scanner. I managed to get pyusb to work on Windows (has to install libusb-1.0 as a backend) and I can enumerate all connected USB device... | Reading the output of a HID hand held barcode scanner in Python on Windows | I'm currently trying to write a service that should programmatically intercepts the output of a barcode scanner. I managed to get pyusb to work on Windows (has to install libusb-1.0 as a backend) and I can enumerate all connected USB devices along with the hierarchy of descriptors. So far so good.
Next step was to get ... | [
"I somehow managed to get this to work.\nIntercepting the barcode scanner input on Linux was straightforward: open the device, detach it from the kernel driver and you're good to go. It's pyusb tutorial 'by the book'\nOn windows, it's a bit of a mess. I had to configure the scanner as a serial device that gets reco... | [
1
] | [] | [] | [
"hidapi",
"libusb",
"python"
] | stackoverflow_0073988959_hidapi_libusb_python.txt |
Q:
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'db.models.Inventory.InventoryModel' is not mapped
I am in the process of building several example APIs to and ran into this 'is not mapped' sqlalchemy.orm.exe.UnmappedInstance Error issue. I believe this error would possible be generated if I was trying to pass an o... | sqlalchemy.orm.exc.UnmappedInstanceError: Class 'db.models.Inventory.InventoryModel' is not mapped | I am in the process of building several example APIs to and ran into this 'is not mapped' sqlalchemy.orm.exe.UnmappedInstance Error issue. I believe this error would possible be generated if I was trying to pass an object instance that wasn't a model, however, I am passing a pydanic model within the db.add() method whi... | [
"It seems that you are confused with the inheritance of model and schema, BaseModel is for schemas and Base is for models.\nTry to change the classes of:\nclass InventoryModel(BaseModel): \n\nclass InventorySchema(Base):\n __tablename__ = \"vehicles\"\n\nto:\nclass InventoryModel(Base):\n __tablena... | [
0
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0072450616_fastapi_pydantic_python.txt |
Q:
python.exe - The FastCGI process exited unexpectedly
I have read all posts about this issue, here and on IIS forum, got it to the second page on Google too... and still can't get it to work.
I want to run Flask/Python app in IIS on Windows server 2016, but I keep getting this error:
HTTP Error 500.0 - Internal Ser... | python.exe - The FastCGI process exited unexpectedly | I have read all posts about this issue, here and on IIS forum, got it to the second page on Google too... and still can't get it to work.
I want to run Flask/Python app in IIS on Windows server 2016, but I keep getting this error:
HTTP Error 500.0 - Internal Server Error
C:\Program Files\Python38\python.exe - The FastC... | [
"You could follow the below steps to configure python flask application in iis:\n1)First, you need to install the python,wfastcgi, and flask at your server.\nYou can download the python from below link:\nhttps://www.python.org/downloads/\nNote: if possible please use python version above 3.6.\n2)after installing py... | [
4,
0,
0,
0
] | [] | [] | [
"flask",
"iis",
"python",
"wfastcgi",
"windows_server_2016"
] | stackoverflow_0060043072_flask_iis_python_wfastcgi_windows_server_2016.txt |
Q:
Finding element in XML file - what if it's not?
I want to have a loop which is checking if element "CompAttrVal name" exist in XML file and if it is get element "Value" and if is not - setting the variable "Value" as empty.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<root ReleaseDate="2022102110391995" Start... | Finding element in XML file - what if it's not? | I want to have a loop which is checking if element "CompAttrVal name" exist in XML file and if it is get element "Value" and if is not - setting the variable "Value" as empty.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<root ReleaseDate="2022102110391995" StartDate="2022102110391995" EndDate="00" Version="1.0.0">... | [
"Have you thought about using a dictionary instead of single variables. Store the attributes you are interested in in a list or set:\nattribs = {\"StudPos21X\", \"StudPos21Y\", \"StudPos22X\", \"StudPos22Y\", \"StudPos23X\", \"StudPos23Y\", \"StudPos24X\", \"StudPos24Y\"}\n\nand then, when looping of your elements,... | [
0
] | [] | [] | [
"excel",
"if_statement",
"loops",
"python",
"xml"
] | stackoverflow_0074314462_excel_if_statement_loops_python_xml.txt |
Q:
Getting the average for a certain column based off specific ranges of two other columns?
I have 4 columns such as the ones below (but a total of 50,000 values not shown here):
Date Speed Area Incidents
1/1/2016 6.5 Maly L
1/2/2016 7.7 Maly H
1/3/20... | Getting the average for a certain column based off specific ranges of two other columns? | I have 4 columns such as the ones below (but a total of 50,000 values not shown here):
Date Speed Area Incidents
1/1/2016 6.5 Maly L
1/2/2016 7.7 Maly H
1/3/2016 14 Maly H
...
1/1/2017 5.5 Reet M
1/12/2017 ... | [
"Convert Date to datetimes and aggregate year with another columns for sum:\ndf['Date'] = pd.to_datetime(df['Date'])\ndf1 = (df.groupby([df['Date'].dt.year.rename('Year'), 'Area','Incidents']).Speed\n .sum() \n .reset_index()) \n\n",
"You can use masks to select the data you want, ... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074314428_dataframe_pandas_python_python_3.x.txt |
Q:
Sqlalchemy: postgresql paramstyle for engine.execute()
I am connected to postgresql with sqlalchemy. When I try this code:
e = create_engine('')
r = e.execute("select ?", 5)
it gives me:
sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at end of input
Corresponding to http://www.sqlalchemy.org/d... | Sqlalchemy: postgresql paramstyle for engine.execute() | I am connected to postgresql with sqlalchemy. When I try this code:
e = create_engine('')
r = e.execute("select ?", 5)
it gives me:
sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at end of input
Corresponding to http://www.sqlalchemy.org/docs/core/connections.html?highlight=engine#sqlalchemy.engine... | [
"The documentation you link to, directly links to PEP 249, which shows you the different styles.\nAbout pyformat it says:\n\n'pyformat' Python extended format codes, e.g. '...WHERE\n name=%(name)s'\n\nSo that's what you need to use.\nBy Googling on \"DBAPI pyformat\" the second link is the link to the psycopg... | [
4,
0
] | [] | [] | [
"postgresql",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0007077427_postgresql_python_python_3.x_sqlalchemy.txt |
Q:
SQLAlchemy trusted connection with different windows username/password than local user - Python
I am trying to connect to a sql server with a different username/password combination than on my local account. I know it is valid credentials, since i am able to login through SSMS.
I've tried the following:
connection... | SQLAlchemy trusted connection with different windows username/password than local user - Python | I am trying to connect to a sql server with a different username/password combination than on my local account. I know it is valid credentials, since i am able to login through SSMS.
I've tried the following:
connection_string = "DRIVER={SQL Server};SERVER=server;DATABASE=db;UID=username;PWD=password"
connection_url = ... | [
"You get the error, because the Windows account don't have permissions to logon to SQL Server. Note: Windows admin <> SQL admin, it has it's own permission system.\nGrant logon and other required permissions for the Windows logon.\nAccording to your error code I guess. \"Using Windows login name with SQL Server aut... | [
0,
0
] | [] | [] | [
"connection_string",
"pyodbc",
"python",
"sql_server",
"sqlalchemy"
] | stackoverflow_0074314369_connection_string_pyodbc_python_sql_server_sqlalchemy.txt |
Q:
Checking the strength of a password (how to check conditions)
I am trying to create a system that requires you to enter a password. If it is all lower, upper or num then print weak, if it is two of the conditions, then it is med and if all have been met it is strong. It just does not seem to work.
The weak and st... | Checking the strength of a password (how to check conditions) | I am trying to create a system that requires you to enter a password. If it is all lower, upper or num then print weak, if it is two of the conditions, then it is med and if all have been met it is strong. It just does not seem to work.
The weak and strong work however the medium does not.
I do not know where I have g... | [
"Holá\nThe best approach is using regular expression search\nHere is the function I am currently using\ndef password_check(password):\n \"\"\"\n Verify the strength of 'password'\n Returns a dict indicating the wrong criteria\n A password is considered strong if:\n 8 characters length or more\n ... | [
39,
6,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0016709638_python_python_3.x.txt |
Q:
Python peewee save() doesn't work as expected
I'm inserting/updating objects into a MySQL database using the peewee ORM for Python. I have a model like this:
class Person(Model):
person_id = CharField(primary_key=True)
name = CharField()
I create the objects/rows with a loop, and each time through the loo... | Python peewee save() doesn't work as expected | I'm inserting/updating objects into a MySQL database using the peewee ORM for Python. I have a model like this:
class Person(Model):
person_id = CharField(primary_key=True)
name = CharField()
I create the objects/rows with a loop, and each time through the loop have a dictionary like:
pd = {"name":"Alice","per... | [
"Person.save(force_insert=True)\n\nIt's documented: http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks\n",
"I've had a chance to re-test my answer, and I think it should be replaced. Here's the pattern I can now recommend; first, use get_or_create() on... | [
7,
3,
1
] | [
"You may do something like:\npo = Person()\nfor key,value in pd.items():\n setattr(po,key,value)\nupdated = po.save()\nif not updated:\n po.save(force_insert=True)\n\n"
] | [
-1
] | [
"mysql",
"peewee",
"python",
"upsert"
] | stackoverflow_0030038185_mysql_peewee_python_upsert.txt |
Q:
How to create a Subdirectory with os.join.path in python?
So here is my issue:
def get_datasheets(self, build_id):
catalog = self._get_catalogue(build_id)
paths = []
for key, value in catalog.items():
if "data_sheets" in value:
if value["data_sheets"] is not Non... | How to create a Subdirectory with os.join.path in python? | So here is my issue:
def get_datasheets(self, build_id):
catalog = self._get_catalogue(build_id)
paths = []
for key, value in catalog.items():
if "data_sheets" in value:
if value["data_sheets"] is not None:
paths.append(value["data_sheets"]["data_... | [
"I would suggest the standard python library pathlib for working with paths.\nfrom pathlib import Path\n\ndatasheet_path = Path(self._output_path) / \"datasheets\" / datasheet_name\ndatasheet_path.parent.mkdir(parents=True, exist_ok=True)\n\nTo fit your edit it would look something like this:\nfrom pathlib import P... | [
1
] | [] | [] | [
"os.path",
"python",
"subdirectory"
] | stackoverflow_0074314628_os.path_python_subdirectory.txt |
Q:
Acknowledge request has been received to the user
I want to send a acknowledgement to the user that request has been received and FUNCTION_NAME has been called. The FUNCTION_NAME internally calls other functions and takes about 10-15 mins to complete. So the user is acknowledged that his request is captured for pr... | Acknowledge request has been received to the user | I want to send a acknowledgement to the user that request has been received and FUNCTION_NAME has been called. The FUNCTION_NAME internally calls other functions and takes about 10-15 mins to complete. So the user is acknowledged that his request is captured for processing. Any hints/leads towards handing this approach... | [
"As mentioned in the boto3 documentation, you can invoke the other lambda synchronously or asynchronously.\nTo invoke the lambda asynchronously, change the InvocationType to Event.\nSee the documentation for reference.\nPlease do not use invoke_async, this is deprecated.\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python"
] | stackoverflow_0074314571_amazon_web_services_aws_lambda_python.txt |
Q:
Run line in Python terminal not working after Run file in terminal. Visual Studio Code
I just started using VSC. I have created a .py file with the line print('Hola mundo'). When I run the line (Mayus+Intro in Linux at least), it works fine.
>>> print('Hola mundo') Hola mundo
But then I try to Run the file (with t... | Run line in Python terminal not working after Run file in terminal. Visual Studio Code | I just started using VSC. I have created a .py file with the line print('Hola mundo'). When I run the line (Mayus+Intro in Linux at least), it works fine.
>>> print('Hola mundo') Hola mundo
But then I try to Run the file (with the play button), and this errors raises:
>>> /home/tidop/anaconda3/envs/snappy/bin/python /h... | [
"EDIT:\nThis comment under the answer addresses the OP's question.\nIf you mean directly run a line or lines in the script file instead of typing code in the terminal. Right mouse button --> Run Selection/Line in Interactive Window, this opens an interactive window to run the selected portion of code. Here is a GIF... | [
0
] | [] | [] | [
"linux",
"python",
"visual_studio_code"
] | stackoverflow_0074314436_linux_python_visual_studio_code.txt |
Q:
try/except if/else - how to replace 'None' output
I am trying to write a function that will take a target number, and a matrix as its parameter, and will return the 'co-ordinates' of the target number. If the target number doesn't exist, (-1, -1) will be returned.
It is assumed there will only be one occurrence of... | try/except if/else - how to replace 'None' output | I am trying to write a function that will take a target number, and a matrix as its parameter, and will return the 'co-ordinates' of the target number. If the target number doesn't exist, (-1, -1) will be returned.
It is assumed there will only be one occurrence of the target number.
Example matrix:
my_matrix = [
[... | [
"Explanations about your failed attempts, in order:\n\nIn the 1st one, you force raising the ValueError (and so you defeat the purpose of try...except) as soon as your target value is not found, so it will always return -1, -1 except when your target value is at position (0,0).\nThe 2nd one is the same, without try... | [
2,
1
] | [] | [] | [
"enumerate",
"if_statement",
"python",
"try_except"
] | stackoverflow_0074314605_enumerate_if_statement_python_try_except.txt |
Q:
The 'typing' package is an obsolete backport of a standard library package and is incompatible with PyInstaller
When I try to convert my python file to exe using pyinstaller.
Input:
PS C:\Users\User\Desktop\Новая папка (5)> pyinstaller -F send.py
I got this error.
Output:
`The 'typing' package is an obsolete bac... | The 'typing' package is an obsolete backport of a standard library package and is incompatible with PyInstaller | When I try to convert my python file to exe using pyinstaller.
Input:
PS C:\Users\User\Desktop\Новая папка (5)> pyinstaller -F send.py
I got this error.
Output:
`The 'typing' package is an obsolete backport of a standard library package and is incompatible with PyInstaller.
Please `pip uninstall typing` then try aga... | [
"Thanks for everybody who did not helped me. I found solution on my own, I needed to write on console this:\npip uninstall typing\n\nThat's all\n",
"When you say \"I found solution on my own\", you mean \"I have read the error message\"?\nBecause the error message you posted litteraly said\n\nPlease pip uninstall... | [
5,
1,
1
] | [] | [] | [
"console",
"module",
"pyinstaller",
"python",
"windows_console"
] | stackoverflow_0070710731_console_module_pyinstaller_python_windows_console.txt |
Q:
create dictionary while iterating over files and creating multiple dictionary entries for each file
I have a set of files in a path and am iterating over each file using a for loop. A file might look like this:
File 1
<mets>
<identifier type="1"></identifier>
<title>1. München, 26.03.1841; Bl. 1r-3v</title>
<fil... | create dictionary while iterating over files and creating multiple dictionary entries for each file | I have a set of files in a path and am iterating over each file using a for loop. A file might look like this:
File 1
<mets>
<identifier type="1"></identifier>
<title>1. München, 26.03.1841; Bl. 1r-3v</title>
<files>
<file ID="item_0" href="161_Bl_1r.jpg"></file>
<file ID="item_1" href="161_Bl_1v.jpg"></file>
<file I... | [
"I figured out a much simpler solution to the problem. I just access all the information in the initial for loop when I am getting the image files and create the dict in there. So for every image, I am automatically getting a copy of the title and identifier and saving it directly:\npath = r'C:\\programming1\\Schel... | [
0
] | [] | [] | [
"elementtree",
"for_loop",
"python",
"xml"
] | stackoverflow_0074313162_elementtree_for_loop_python_xml.txt |
Q:
Combine f-string and raw string literal
I'm wondering how to use an f-string whilst using r to get a raw string literal. I currently have it as below but would like the option of allowing any name to replace Alex I was thinking adding an f-string and then replacing Alex with curly braces and putting username insid... | Combine f-string and raw string literal | I'm wondering how to use an f-string whilst using r to get a raw string literal. I currently have it as below but would like the option of allowing any name to replace Alex I was thinking adding an f-string and then replacing Alex with curly braces and putting username inside but this doesn't work with the r.
username ... | [
"You can combine the f for an f-string with the r for a raw string:\nuser = 'Alex'\ndirToSee = fr'C:\\Users\\{user}\\Downloads'\nprint (dirToSee) # prints C:\\Users\\Alex\\Downloads\n\nThe r only disables backslash escape sequence processing, not f-string processing.\nQuoting the docs:\n\nThe 'f' may be combined wi... | [
181,
16,
3,
2,
1,
1
] | [] | [] | [
"f_string",
"python",
"python_3.x"
] | stackoverflow_0058302531_f_string_python_python_3.x.txt |
Q:
pygame sprite tagging and analyzing the stats of several sprites and one sprite
I tried to portrait my progress chart for my pygame test(simple test for making sure what function I should use) project, here is the chart:
1. call Player:
Make player into all_sprite(), players() group,
and shoot() the skill every se... | pygame sprite tagging and analyzing the stats of several sprites and one sprite | I tried to portrait my progress chart for my pygame test(simple test for making sure what function I should use) project, here is the chart:
1. call Player:
Make player into all_sprite(), players() group,
and shoot() the skill every second.
2. call Enemy:
Make Enemy into all_sprite(), mobs() group,
and gradually approa... | [
"can use trigonometric here\nimport math\n\ndef measure_distance(x1, y1, x2, y2):\n dx = abs(x2-x1)\n dy = abs(y2-y1)\n distance = math.sqrt((dx*dx)+(dy*dy))\n return distance\n\nthen compare the distance between A-O and B-O\n"
] | [
1
] | [] | [] | [
"position",
"pygame",
"python",
"sprite",
"tags"
] | stackoverflow_0074314715_position_pygame_python_sprite_tags.txt |
Q:
Python - Mock requests with side_effect
I'm trying to mock out my requests. get with a side effect. I would like to associate a different status_code for each side effect value but I didn't succeed so far.
def test_func1(mocker):
side_effect = ["Ok",'','','Failed']
# This line should be ch... | Python - Mock requests with side_effect | I'm trying to mock out my requests. get with a side effect. I would like to associate a different status_code for each side effect value but I didn't succeed so far.
def test_func1(mocker):
side_effect = ["Ok",'','','Failed']
# This line should be changed
fake_resp.status_code = 200
... | [
"Possible solution with module unittest (not pytest)\nI have written this answer before the adding of real function func1(), so I have created a file called my_file_01.py which contains my production function func1():\nimport requests\n\ndef func1():\n response1 = 'empty1'\n response2 = 'empty2'\n r = requ... | [
1,
0
] | [] | [] | [
"mocking",
"pytest",
"python",
"unit_testing"
] | stackoverflow_0074304500_mocking_pytest_python_unit_testing.txt |
Q:
python 'listen' creates established socket. why?
I created simple server.py that listen connection, but not accept connection.
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 1234
server_socket.bind(("", PORT))
server_socket.listen(5)
while 1:
pass
server_socket.clo... | python 'listen' creates established socket. why? | I created simple server.py that listen connection, but not accept connection.
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 1234
server_socket.bind(("", PORT))
server_socket.listen(5)
while 1:
pass
server_socket.close()
When I run this c... | [
"\nAs far as I know, listen just gather connection in backlog queue, and then accept creates ESTABLISHED socket.\n\nThis is wrong. listen tells the OS to accept new connections. accept then gets the inside the OS already established connections into the application. The backlog parameter for listen defines roughly... | [
0
] | [] | [] | [
"backlog",
"listen",
"python",
"tcp",
"tcpserver"
] | stackoverflow_0074314653_backlog_listen_python_tcp_tcpserver.txt |
Q:
How to set max_depth and max_leaves in Python XGboost
I have some questions regarding the max_depth and max_leaves hyperparams in XGBoost (I'm using Python).
Let's go through some examples.
Example 1.
In the following case I have set:
max_depth = 3
max_leaves = 0
Note that I have also set some params for monotone... | How to set max_depth and max_leaves in Python XGboost | I have some questions regarding the max_depth and max_leaves hyperparams in XGBoost (I'm using Python).
Let's go through some examples.
Example 1.
In the following case I have set:
max_depth = 3
max_leaves = 0
Note that I have also set some params for monotone_constraints.
model = XGBClassifier(
objective='binary:... | [
"Leaves and depth are codependent.\nXGBoost needs at least 2 leaves per depth, which means that it will need at least 2**n leaves, where n is depth. So for n=3, you would need at least 2**3=8 leaves. How can you imagine creating tree with depth 3 with just 1 leaf?\nI suggest using specific package for hyperparamete... | [
0
] | [] | [] | [
"constraints",
"depth",
"leaf",
"python",
"xgboost"
] | stackoverflow_0074281317_constraints_depth_leaf_python_xgboost.txt |
Q:
Show data values in plotly icicle chart
I want to show my value data within each box of my icicle chart, but the udpate_traces command I've used before for bar charts isn't working:
import plotly.express as px
# df is a pandas dataframe with columns level_1,2,3 and total
fig = px.icicle(df, path=['level_1', 'level... | Show data values in plotly icicle chart | I want to show my value data within each box of my icicle chart, but the udpate_traces command I've used before for bar charts isn't working:
import plotly.express as px
# df is a pandas dataframe with columns level_1,2,3 and total
fig = px.icicle(df, path=['level_1', 'level_2', 'level_3'], values='total')
fig.update_t... | [
"texttemplate requires value (without 's'):\nfig.update_traces(texttemplate=\"%{value:.1}\")\n\n"
] | [
1
] | [] | [] | [
"plotly",
"plotly_python",
"python"
] | stackoverflow_0074314314_plotly_plotly_python_python.txt |
Q:
Create active transaction past 30 days
i have data like this
user_id
date
total_transaction
100222
2021-09-01
10000
100333
2021-09-02
20000
100444
2021-09-24
0
100444
2021-09-27
30000
100555
2021-09-30
0
100666
2021-09-30
500
i need to filter the data who have active transaction (past 30 days)
active means... | Create active transaction past 30 days | i have data like this
user_id
date
total_transaction
100222
2021-09-01
10000
100333
2021-09-02
20000
100444
2021-09-24
0
100444
2021-09-27
30000
100555
2021-09-30
0
100666
2021-09-30
500
i need to filter the data who have active transaction (past 30 days)
active means total_transaction > 0
or
tota... | [
"Try this:\n# Data given above\ndata= {\"user_id\":[100222,100333,100444,100444,100555,100666], \"date\":[\"2021-09-01\", \"2021-09-02\", \"2021-09-24\", \"2021-09-27\", \"2021-09-30\", \"2021-09-30\"], \"total_transaction\": [10000,20000,0,30000,0,500]}\n# Create pandas dataframe\ndf = pd.DataFrame(data)\n# Create... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074314253_pandas_python.txt |
Q:
What is the address of a variable in python? Maybe the id() function just return the address of data, not variable
This is a simple python language code, and I want to know the address of variable a:
if __name__ == '__main__':
a = 2
print(a)
print(id(2))
print(id(a))
The output is:
2
1407042008245... | What is the address of a variable in python? Maybe the id() function just return the address of data, not variable | This is a simple python language code, and I want to know the address of variable a:
if __name__ == '__main__':
a = 2
print(a)
print(id(2))
print(id(a))
The output is:
2
140704200824512
140704200824512
But I don't think the address of variable a is 140704200824512. I think 140704200824512 is the addre... | [
"\"CPython implementation detail: This is the address of the object in memory.\" - https://docs.python.org/3/library/functions.html#id\nThe reason why you are seeing id(a) == id(2) is because Python uses something reffered to as Small Integer Caching - integers in range [-5, 256] are cached, so usually most of the ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074314546_python.txt |
Q:
Django - validating m2m relationship
I have the following models:
class Question(Model):
# ...
class Choice(Model):
question = ForeignKey(Question)
# ...
class AnswerToQuestion(Model):
user = ForeignKey(User)
question = ForeignKey(Question)
selected_choices = ManyToManyField(Choice)
What... | Django - validating m2m relationship | I have the following models:
class Question(Model):
# ...
class Choice(Model):
question = ForeignKey(Question)
# ...
class AnswerToQuestion(Model):
user = ForeignKey(User)
question = ForeignKey(Question)
selected_choices = ManyToManyField(Choice)
What I would like to do is make sure that the ... | [
"The other way may be to use a through-model.\nSay you have it like this:\nclass Choice(Model):\n question = ForeignKey(Question)\n # ...\n\nclass AnswerToQuestion(Model):\n user = ForeignKey(User)\n question = ForeignKey(Question)\n selected_choices = ManyToManyField(Choice, through=\"AnswerToQuesti... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074314407_django_django_models_python.txt |
Q:
remove or replace only the word after a specific word in column pandas using regex
I'm trying to use regex to remove or replace only the word after specific word(s) in a column of strings in a dataframe. This means I don't want the spaces to be replace. Just the word the proceeds the specific word(s)
import pandas... | remove or replace only the word after a specific word in column pandas using regex | I'm trying to use regex to remove or replace only the word after specific word(s) in a column of strings in a dataframe. This means I don't want the spaces to be replace. Just the word the proceeds the specific word(s)
import pandas as pd
df = pd.DataFrame({'STRING': [r"THERE IS NO REASON WHY THIS SHOULDN'T WORK!", r"... | [
"Note that your regex, /(?<=NO|WITHOUT)(\\s+)\\w, contains several issues:\n\n/ - is a typo, it was probably a regex delimiter that got into the pattern\n(?<=NO|WITHOUT) - is a lookbehind pattern where alternatives match strings of different length and Python lookbehinds patterns must be fixed-width\n\\w - matches ... | [
2
] | [] | [] | [
"pandas",
"python",
"regex",
"replace",
"string"
] | stackoverflow_0074314855_pandas_python_regex_replace_string.txt |
Q:
How to execute a function under limited time (eg under 5 minutes) in Python 3?
I have this line of code ("model.predict(image=img)") that I want to stop executing if it is taking longer than 5 minutes. Is there an easy way or library in python I can use to achieve this?
for filename in os.listdir():
if filenam... | How to execute a function under limited time (eg under 5 minutes) in Python 3? | I have this line of code ("model.predict(image=img)") that I want to stop executing if it is taking longer than 5 minutes. Is there an easy way or library in python I can use to achieve this?
for filename in os.listdir():
if filename.endswith(".jpg") or filename.endswith(".png"):
print(filename)
img... | [
"The solution that I know is by using thread worker and kill it. one worker for running the function, and we have another funciton to maintain the running time.\nI think you can use python-worker (link)\nimport time\nfrom worker import worker\n\ndef run_with_timeout(worker_object, timeout):\n while worker_object... | [
1,
0,
0
] | [] | [] | [
"multithreading",
"python",
"timeout",
"timer"
] | stackoverflow_0074298516_multithreading_python_timeout_timer.txt |
Q:
An updated guide on releasing and versioning PyPi packages
I have recently bumped into an issue while trying to release a new version of my PyPi package.
After updating the source code (and preparing the files for the release), I cannot find any updated guide on how to release a new version (see this, for instance... | An updated guide on releasing and versioning PyPi packages | I have recently bumped into an issue while trying to release a new version of my PyPi package.
After updating the source code (and preparing the files for the release), I cannot find any updated guide on how to release a new version (see this, for instance) to PyPi.
Most guides reference setup.py, which has now been re... | [
"Solved:\nFor reference, see Trouble following packaging libraries tutorial: upload #313.\nI was also confused about whether to use twine upload --repository testpypi dist* to update a package or twine upload --repository-url URL dist/* to update an existing package. The documentation on the issue is not clear to m... | [
0
] | [] | [] | [
"pypi",
"pyproject.toml",
"python"
] | stackoverflow_0074295330_pypi_pyproject.toml_python.txt |
Q:
ValueError at /form The view authentication.views.my_form didn't return an HttpResponse object. It returned None instead
I am trying to create a form but facing issues, any kind of help will be appreciated. Thanks in advance.
Below is my views.py
from django.contrib.auth import authenticate, login, logout
from dja... | ValueError at /form The view authentication.views.my_form didn't return an HttpResponse object. It returned None instead | I am trying to create a form but facing issues, any kind of help will be appreciated. Thanks in advance.
Below is my views.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import send_mail, EmailMessage
from django.shortcuts... | [
"I think you did mistake here. else part should be part of first if statement.\ninstead:\ndef my_form(request):\n if request.method == \"POST\":\n form = my_form(request.POST) #You mispelled my_form. You imported from .forms import MyForm. write MyForm here instead of my_form\n if form.is_valid():\... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0074314914_django_django_forms_python.txt |
Q:
ADB equivalent for iOS device with windows PC
I was looking some instrument like Android ADB in order to debug iOS devices. I've found iOS instrument, a tool of the XCode that is able to debug app on mobile iOS devices.
Any idea or comment is greatly appreciated by me.
I would like to know if it's possible execute... | ADB equivalent for iOS device with windows PC | I was looking some instrument like Android ADB in order to debug iOS devices. I've found iOS instrument, a tool of the XCode that is able to debug app on mobile iOS devices.
Any idea or comment is greatly appreciated by me.
I would like to know if it's possible execute a touch on the iOS device, such as input events li... | [
"You can use the open source tool set \"libimobiledevice\" which also exists for Windows.\nThis set of tools include e.g. ideviceinstaller for transmitting and installing IPA files on an connected iPhone, idevice_id for getting the connected iPhone UUIDs, idevicescreenshot and many more tools.\nIn addition you need... | [
1
] | [] | [] | [
"adb",
"debugging",
"go",
"ios",
"python"
] | stackoverflow_0074314387_adb_debugging_go_ios_python.txt |
Q:
When I create a csv, from a data frame in Python, a new column is added to the beginning of the table in my csv. How do I remove this column?
How do I remove the first column in the table below, in Python, which is created when I generate a csv from a data frame in Python? Or is there a way to prevent this first c... | When I create a csv, from a data frame in Python, a new column is added to the beginning of the table in my csv. How do I remove this column? |
How do I remove the first column in the table below, in Python, which is created when I generate a csv from a data frame in Python? Or is there a way to prevent this first column from being created in the first place.
| [
"When you use pandas.to_csv(), there is the index param setted True by default. This means that it will write a column for the index.\nIf you want to prevent index writing, you have to set it to false:\ndf.to_csv(your_path, index=False)\n\n"
] | [
1
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074314983_csv_dataframe_pandas_python.txt |
Q:
How to run 2 functions simultaneously , and make them stop when one of the them returns something
example:
random_list = ['foo','foo','foo','foo',56,'foo','foo','foo','foo','foo']
# in random_list there are always 10 elements, one of which is 56, but its position is unknown
def find_index_of_56_in_list_1():
... | How to run 2 functions simultaneously , and make them stop when one of the them returns something | example:
random_list = ['foo','foo','foo','foo',56,'foo','foo','foo','foo','foo']
# in random_list there are always 10 elements, one of which is 56, but its position is unknown
def find_index_of_56_in_list_1():
for index in range(0,5):
if 56 == random_list[index]:
return index
def find_index_... | [
"I feel like you could find some answers in recursion. The question is: do you want to?\nJokes aside, most search algorithms use some form of recursion, and they perform really well. Your example makes me think of binary search -> you take your list, go to the middle point. If it's not the value you're searching, y... | [
0,
0
] | [] | [] | [
"multithreading",
"python",
"python_3.x"
] | stackoverflow_0074125057_multithreading_python_python_3.x.txt |
Q:
How do I apply a function to every row of a csv file and save the new data into a new file?
I have this MNIST data set of 10,000 rows and I'm trying to apply a convolution kernel to every single row, but what my code does only produces the last line after it's done. It's been reshaped to 28,28.
This is a snippet t... | How do I apply a function to every row of a csv file and save the new data into a new file? | I have this MNIST data set of 10,000 rows and I'm trying to apply a convolution kernel to every single row, but what my code does only produces the last line after it's done. It's been reshaped to 28,28.
This is a snippet the raw original data set. 10000 rows of 784 numbers that corresponds to MNIST data.
test_data_fil... | [
"I'd recommend taking your loop body, and moving it to a function. You can use numpy's array2string to get one line of output per line of input\ndef process(record: str) -> str:\n # your loop's body\n return numpy.array2string(sharpened, separator=',', suffix='\\n')\n\nwith test_data_file = open(\"mnist_test.... | [
1
] | [] | [] | [
"convolution",
"csv",
"python"
] | stackoverflow_0074314986_convolution_csv_python.txt |
Q:
Python PDM package manager: How to enable virtual environment autodetection?
Python PDM Project
https://pdm.fming.dev/latest/
https://github.com/pdm-project/pdm
My Problem
In context below I want to activate the in-project virtual environment automatically whenever the directory changes to inclued the path ~/pydev... | Python PDM package manager: How to enable virtual environment autodetection? | Python PDM Project
https://pdm.fming.dev/latest/
https://github.com/pdm-project/pdm
My Problem
In context below I want to activate the in-project virtual environment automatically whenever the directory changes to inclued the path ~/pydev/pdm-test.
Tree View of PDM Test Folder
$ tree ~/pydev/pdm-test -aL 2
/home/joe/py... | [
"The python path is stored in the project config file .pdm.toml, view it and remove the corresponding line to clear the python path. You can also do it with command line: pdm config -ld python.path\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0072987179_python.txt |
Q:
How to remove all punctuations from string except those in decimal numbers in Python?
Input is the code I'm using, Output is the output I'm getting, required output is the output I want.
Input:
import regex as re
keyword = 'Auto: tab suspender 2.0 pro'
keyword = re.sub(r'[^\w\s]','', keyword)
words = re.findall(... | How to remove all punctuations from string except those in decimal numbers in Python? | Input is the code I'm using, Output is the output I'm getting, required output is the output I want.
Input:
import regex as re
keyword = 'Auto: tab suspender 2.0 pro'
keyword = re.sub(r'[^\w\s]','', keyword)
words = re.findall('\w+', keyword)
print(keyword)
print(len(words))
words
Output:
Auto tab suspender 20 pro
5... | [
"I would use re.findall here:\nkeyword = 'Auto: tab suspender 2.0 pro'\nmatches = re.findall(r'\\d+(?:\\.\\d+)?|\\w+', keyword)\nprint(matches) # ['Auto', 'tab', 'suspender', '2.0', 'pro']\n\nThe regex pattern used here first attempts to match an integer or float, and that failing will look for words:\n\n\\d+ matc... | [
3
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0074315089_python_regex_string.txt |
Q:
Import Error in rc.local for open cv2 module
My python 3.6 script works fine when running in the terminal once logged in but I’m having an import cv2 error (module not found) when trying to run it in rc.local. So far in that file I just have python /home/user/face_recog.py before exit 0. Maybe it has something to ... | Import Error in rc.local for open cv2 module | My python 3.6 script works fine when running in the terminal once logged in but I’m having an import cv2 error (module not found) when trying to run it in rc.local. So far in that file I just have python /home/user/face_recog.py before exit 0. Maybe it has something to do with not using the opencv path? Does anyone kno... | [
"Have you tried to install the module with sudo?\nIf you install a module via pip without sudo it's only available for the current user, rc.local uses root, so you need to add sudo in your installing command.\n"
] | [
0
] | [] | [] | [
"boot",
"linux",
"opencv",
"python",
"ubuntu"
] | stackoverflow_0061721728_boot_linux_opencv_python_ubuntu.txt |
Q:
How to change the column order in a pandas dataframe when there are too many columns?
I have a large pandas dataframe that contains many columns.
I would like to change the order of the columns so that only a subset of them appears first. I dont care about the ordering of the rest (and there are too many variables... | How to change the column order in a pandas dataframe when there are too many columns? | I have a large pandas dataframe that contains many columns.
I would like to change the order of the columns so that only a subset of them appears first. I dont care about the ordering of the rest (and there are too many variables to list them all)
For instance, if my dataframe is like this
a b c d e f g h i
5 8 7 2 1 4... | [
"You could use a column mask:\n>>> mysubset = [\"d\",\"f\"]\n>>> mask = df.columns.isin(mysubset)\n>>> pd.concat([df.loc[:,mask], df.loc[:,~mask]], axis=1)\n d f a b c e g h i\n0 2 4 5 8 7 1 1 2 3\n1 2 4 1 4 2 3 1 5 3\n\nor use sorted:\n>>> mysubset = [\"d\",\"f\"]\n>>> df[sorted(df, key... | [
7,
3,
2,
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0035994450_dataframe_pandas_python.txt |
Q:
Unsure on how to get the geomean calculation in the loop to work
I defined geomean but when running the code and inputting integers to make the calculation, the output returns that it doesn't recognize geomean. All the other functions work fine. Not sure on what to do for geomean.
A:
The calling function for geo... | Unsure on how to get the geomean calculation in the loop to work |
I defined geomean but when running the code and inputting integers to make the calculation, the output returns that it doesn't recognize geomean. All the other functions work fine. Not sure on what to do for geomean.
| [
"The calling function for geo_mean as defined above should be :\ngeo_mean(datalist, iterable)\n\nbut while calling in the else part you are calling as :\ngeo_mean(iterable, datalist)\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074315134_matplotlib_python.txt |
Q:
Unable to plot line of best fit for regression
I already referred these posts here and here and tried to plot the line of best fit for my linear regression problem.
So, my data shape looks like below
My code to plot the best fit line looks like below
plt.scatter(X_test.values, Y_test.values, color="black") # thro... | Unable to plot line of best fit for regression | I already referred these posts here and here and tried to plot the line of best fit for my linear regression problem.
So, my data shape looks like below
My code to plot the best fit line looks like below
plt.scatter(X_test.values, Y_test.values, color="black") # throws error in this line
plt.plot(Y_test, y_pred, color... | [
"As of now, you are trying to plot 63 variables (from X_test) which is not possible. The best solution is to pick one variable from your dataset and look at it. This is best if you have one particular variable you want to evaluate.\nBut, it seems like you want to understand your model's performance. Sklearn has a n... | [
2,
1
] | [] | [] | [
"linear_regression",
"matplotlib",
"pandas",
"python",
"seaborn"
] | stackoverflow_0074315177_linear_regression_matplotlib_pandas_python_seaborn.txt |
Q:
Shifting values of numpy array withing specific range for clustering
I want to shift the values of synthetic data generated by the Scikit-learn package. The data and plot:
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import numpy as np
X, y = make_blobs(n_samples=12000, centers=3, n_feat... | Shifting values of numpy array withing specific range for clustering | I want to shift the values of synthetic data generated by the Scikit-learn package. The data and plot:
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import numpy as np
X, y = make_blobs(n_samples=12000, centers=3, n_features=2, random_state=0)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()
I ... | [
"I found my way:\nX[np.where(y==0)[0], 0] += np.random.normal(8_000, 4_000, len(np.where(y==0)[0]))\nX[np.where(y==0)[0], 1] += np.random.normal(5_000, 4_000, len(np.where(y==0)[0]))\n\nX[np.where(y==1)[0], 0] += np.random.normal(19_000, 3_000, len(np.where(y==1)[0]))\nX[np.where(y==1)[0], 1] += np.random.normal(19... | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074314968_python_scikit_learn.txt |
Q:
Check presence of multiple files as a whole in folder using Regex
I am checking a folder for the presence of several files:
Insertations.df
Size.df
State.df
As all of these have quite specific routines I just check them one by one.
However for the next step it can be there is one or more additional version prese... | Check presence of multiple files as a whole in folder using Regex | I am checking a folder for the presence of several files:
Insertations.df
Size.df
State.df
As all of these have quite specific routines I just check them one by one.
However for the next step it can be there is one or more additional version present:
$ ls *df
Insertations.df Insertations_0.df Size.df Size_0.df St... | [
"It's really not clear what you are trying to ask, or why you want a regex solution. Something like this? This returns the files whose names match your regex.\nfor file in os.scandir():\n for fname in self.basiclist:\n if re.match(rf\"^{fname}_\\d+\\.df$\", file):\n matches.append(file)\n el... | [
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074315107_file_python.txt |
Q:
Django/Flask : Rewritting an Flask Azure B2C authentication in Django
I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask.
I used the documentation/tutorial of microsoft that share a github with the flask code to do it :
... | Django/Flask : Rewritting an Flask Azure B2C authentication in Django | I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask.
I used the documentation/tutorial of microsoft that share a github with the flask code to do it :
https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-auth... | [
"Not the required answer (adopting the Flask solution for DJango), but your're right, there are no examples of using Django for aadb2c auth...\nWhat I did, is used \"mozilla-django-oidc\" which fits well the azure oidc authentification..\nMore details are here:\nhttps://stackoverflow.com/a/74156780/592737\n"
] | [
0
] | [] | [] | [
"azure_b2c",
"django",
"python"
] | stackoverflow_0073321603_azure_b2c_django_python.txt |
Q:
who does IndexError: list index out of range appears ? i did some test still cant find out
Im working on a simple project python to practice , im trying to retreive data from file and do some test on a value
in my case i do retreive data as table from a file , and i do test the last value of the table if its true ... | who does IndexError: list index out of range appears ? i did some test still cant find out | Im working on a simple project python to practice , im trying to retreive data from file and do some test on a value
in my case i do retreive data as table from a file , and i do test the last value of the table if its true i add the whole line in another file
Here my data
AE300812 AFROUKH HAMZA 21 admis
AE40092... | [
"You look at tab[i+4], so you have to make sure you stop the loop before that, e.g. with range(0, len(tab)-4, 5). The step=5 alone does not guarantee that you have a full \"block\" of 5 elements left.\nBut why does this occur, since each of the lines has 5 elements? They don't! Notice how one line has 6 elements (m... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074315308_python.txt |
Q:
Log messages appearing twice - with and without formatting in Python Flask app
I set up logging module wide like so:
def setup_logging(app):
"""
Set up logging so as to include RequestId and relevant logging info
"""
RequestID(app)
handler = logging.StreamHandler()
handler.setStream(sys.std... | Log messages appearing twice - with and without formatting in Python Flask app | I set up logging module wide like so:
def setup_logging(app):
"""
Set up logging so as to include RequestId and relevant logging info
"""
RequestID(app)
handler = logging.StreamHandler()
handler.setStream(sys.stdout)
handler.propagate=False
handler.setFormatter(
logging.Formatte... | [
"I reset the handlers and got the expected behaviour:\nlogger.handlers=[]\n\n",
"swap the current handlers\nlogging.getLogger().handlers[0] = handler\n\ninstead of doing this\nlogging.getLogger().addHandler(handler)\n\n"
] | [
0,
0
] | [] | [] | [
"flask",
"logging",
"python"
] | stackoverflow_0074267909_flask_logging_python.txt |
Q:
iterate sqlalchemy query in my template python-flask
I call a function in my template that returns sqlalchemy query result, (color value from the name of the tag).
this is the query function :
def get_tag_color(name):
return db.session.query(Tag.tag_color).filter(Tag.tag_name == name).scalar()
and I call it in my... | iterate sqlalchemy query in my template python-flask | I call a function in my template that returns sqlalchemy query result, (color value from the name of the tag).
this is the query function :
def get_tag_color(name):
return db.session.query(Tag.tag_color).filter(Tag.tag_name == name).scalar()
and I call it in my template file:
{% if server.tags %}
{% for tag in ser... | [
"all these functions are working fine, the problem was that I have space between tags, and I solved it by removing space in each tag.\nthis is the new function with strip() function :\n {% if server.tags %}\n {% for tag in server.tags.split(\",\") %} \n <strong><span style=\"background-color: {{ get_tag_color(tag.... | [
0
] | [] | [] | [
"flask",
"html",
"python",
"sqlalchemy",
"tags"
] | stackoverflow_0074054724_flask_html_python_sqlalchemy_tags.txt |
Q:
Coupling LCA with process simulation in brightway2
I would like to couple my Life Cycle Assessment (LCA) with process simulation made in Aspen. Basically, I would like for my program, created within Brightway2 framework, to take data from Aspen simulation (provided in JSON file) for Life Cycle Inventory (LCI), and... | Coupling LCA with process simulation in brightway2 | I would like to couple my Life Cycle Assessment (LCA) with process simulation made in Aspen. Basically, I would like for my program, created within Brightway2 framework, to take data from Aspen simulation (provided in JSON file) for Life Cycle Inventory (LCI), and ecoinvent ones for Life Cycle Assessment (LCIA).
As I i... | [
"You can create new activities (your foreground database) based on the results from Aspen. I am not familiar with Aspen, but one option could be to create an importer that picks that json file and creates the (foreground) database with your activities modelled in Aspen connected to background processes (e.g. ecoinv... | [
0
] | [] | [] | [
"aspen",
"brightway",
"lifecycle",
"python"
] | stackoverflow_0074306735_aspen_brightway_lifecycle_python.txt |
Q:
Reason why reverse relation filtering fails when m2m field uses a string class?
I ran into a strange issue using Django 2.2 and trying to filter a reverse relation which was defined using a string reference to the class. The issue goes away if I pass the class itself, ie.
This FAILS:
class Whatever(models.Model):
... | Reason why reverse relation filtering fails when m2m field uses a string class? | I ran into a strange issue using Django 2.2 and trying to filter a reverse relation which was defined using a string reference to the class. The issue goes away if I pass the class itself, ie.
This FAILS:
class Whatever(models.Model):
providers = models.ManyToManyField('Relation', related_name='dependants')
This WO... | [
"I am tinking that your are getting this error because your two models classes are not in the same django app.\nbut you can steel using a string reference but you ought to use string dotted notation like 'app_label.model_class_name'\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074314759_django_python.txt |
Q:
How to split a column into several columns by taking the string values as column headers?
This is my dataset:
| Name | Dept | Project area/areas interested |
| -------- | -------- |-----------------------------------|
| Joe | Biotech | Cell culture//Bioinfo//Immunology |
| Ann | Biotech | ... | How to split a column into several columns by taking the string values as column headers? | This is my dataset:
| Name | Dept | Project area/areas interested |
| -------- | -------- |-----------------------------------|
| Joe | Biotech | Cell culture//Bioinfo//Immunology |
| Ann | Biotech | Cell culture |
| Ben | Math | Trigonometry//Algebra |... | [
"You can use pandas.concat in combination with pandas.get_dummies like this:\npd.concat([df[[\"Name\", \"Dept\"]], df[\"Project area/areas interested\"].str.get_dummies(sep='//')], axis=1)\n\n"
] | [
3
] | [] | [] | [
"col",
"columnsorting",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074315235_col_columnsorting_dataframe_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.