content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
I am getting the vscode error: "The editor could not be opened due to an unexpected error". How do I fix this?
Basically I am making a discord bot on github codespaces (online vscode), and it was working for a while, but after I closed out of my tab, and re-opened it, it is giving me this error:
This is the picture of the error.
I don't know what is causing this error. I tried creating a new codespace for the repo, but it still has the same issue. I created a new repository with a codespace to see if I got the same error. It again worked at first, but then came up with the same error. Can someone tell me what is happening, and how to fix it? The git tab (source control) also says No source control providers registered. Sometimes, the run button (looks like play button), doesn't show up. Any ideas on how to fix this?
A:
Use vscode client. Check if the file path exists. Follow this document.
|
I am getting the vscode error: "The editor could not be opened due to an unexpected error". How do I fix this?
|
Basically I am making a discord bot on github codespaces (online vscode), and it was working for a while, but after I closed out of my tab, and re-opened it, it is giving me this error:
This is the picture of the error.
I don't know what is causing this error. I tried creating a new codespace for the repo, but it still has the same issue. I created a new repository with a codespace to see if I got the same error. It again worked at first, but then came up with the same error. Can someone tell me what is happening, and how to fix it? The git tab (source control) also says No source control providers registered. Sometimes, the run button (looks like play button), doesn't show up. Any ideas on how to fix this?
|
[
"Use vscode client. Check if the file path exists. Follow this document.\n"
] |
[
0
] |
[] |
[] |
[
"github",
"github_codespaces",
"python",
"python_3.x",
"visual_studio_code"
] |
stackoverflow_0074496835_github_github_codespaces_python_python_3.x_visual_studio_code.txt
|
Q:
Python/Tkinter: need code to define / import a widget as a class outside root window
I have been wrestling for a very long time with the issue of creating a Tkinter gui in modular fashion using classes. While there are many examples on this site - and believe me, I have read them all - they have all been too complex for me to understand. In particular, I could not work out how the imported modules could 'talk to' functions in the main application. I have finally had a eureka moment - I created a class in a module that defines a root window and a button. Then, I wrote a main python file that imports the root window / button module, and tests interactions between the imported module and the main app. All of those tests were successful, which is huge progress for me, as far as it goes. Here is the module code, saved as 'fmod.py':
import tkinter as tk
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title('Tkinter titlebar title')
self.geometry('300x50')
# create button within root window
self.button = tk.Button(self, text='Click Me')
self.button.pack()
Here is the python file written to import the module, and test all the interactions I was interested in understanding:
import tkinter as tk
# import module
import fmod
# create gui root window as an instance of imported MainWindow class
MainWin = fmod.MainWindow()
# define a local function for testing purposes
def ButtonClicked():
print("Button clicked")
# alter attributes of imported root/button from within this file
MainWin.geometry("700x400")
MainWin.config(bg = "yellow")
MainWin.button.config(bg="lightblue")
# add a new widget to root from within this file
NewLabel = tk.Label(MainWin,text="Label")
NewLabel.pack()
# connect an imported widget to the above local function
MainWin.button.config(command=ButtonClicked)
# mainloop
MainWin.mainloop()
As mentioned, all of the tests in the above code worked successfully. The question is this: I would rather have the MainWindow class define the root window and nothing else. So rather than including the button in that code, I'd like to write another entirely separate class that simply defines a button, which could be imported into my app separately. Would anyone be kind enough to help me write that code? I tried copying code from the MainWindow class, and it worked, but it opened an entirely new window (probably because of the init / super init code, which I do not fully understand, and don't really need to understand at the moment - it works, and I'm fine with that). I want code for a simple button that I could import into the main app, as a widget, and that I could place in the MainWin window inside the app.
A:
You can define the class in a separate module and then import it, but you will still want to initiate the button inside of your main window like you are doing now. After all the button does belong on the window.
To create a button class it would be similar to how you created the MainWindow...
import tkinter as tk
class MyButton(tk.Button):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
... do something
def buttonClicked(self, *args):
print("Button Clicked")
Then you could just leave you mainwindow the way it is except switch out the class for your class. I also suggest moving a lot of your logic that is in the global scope inside of your MainWindow, and minimizing your use of the global scope as much as possible. For example:
import tkinter as tk
from mybuttonmodule import MyButton
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title('Tkinter titlebar title')
self.geometry('300x50')
# create button within root window
self.button = MyButton(self, text='Click Me')
self.button.pack()
self.button.config(command=self.button.buttonClicked)
self.newlabel = tk.Label(self, text="Label")
self.newlabel.pack()
self.geometry("700x400")
self.config(bg = "yellow")
self.button.config(bg="lightblue")
if __name__ == "__main__":
window = MainWindow()
window.mainloop()
|
Python/Tkinter: need code to define / import a widget as a class outside root window
|
I have been wrestling for a very long time with the issue of creating a Tkinter gui in modular fashion using classes. While there are many examples on this site - and believe me, I have read them all - they have all been too complex for me to understand. In particular, I could not work out how the imported modules could 'talk to' functions in the main application. I have finally had a eureka moment - I created a class in a module that defines a root window and a button. Then, I wrote a main python file that imports the root window / button module, and tests interactions between the imported module and the main app. All of those tests were successful, which is huge progress for me, as far as it goes. Here is the module code, saved as 'fmod.py':
import tkinter as tk
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
# configure the root window
self.title('Tkinter titlebar title')
self.geometry('300x50')
# create button within root window
self.button = tk.Button(self, text='Click Me')
self.button.pack()
Here is the python file written to import the module, and test all the interactions I was interested in understanding:
import tkinter as tk
# import module
import fmod
# create gui root window as an instance of imported MainWindow class
MainWin = fmod.MainWindow()
# define a local function for testing purposes
def ButtonClicked():
print("Button clicked")
# alter attributes of imported root/button from within this file
MainWin.geometry("700x400")
MainWin.config(bg = "yellow")
MainWin.button.config(bg="lightblue")
# add a new widget to root from within this file
NewLabel = tk.Label(MainWin,text="Label")
NewLabel.pack()
# connect an imported widget to the above local function
MainWin.button.config(command=ButtonClicked)
# mainloop
MainWin.mainloop()
As mentioned, all of the tests in the above code worked successfully. The question is this: I would rather have the MainWindow class define the root window and nothing else. So rather than including the button in that code, I'd like to write another entirely separate class that simply defines a button, which could be imported into my app separately. Would anyone be kind enough to help me write that code? I tried copying code from the MainWindow class, and it worked, but it opened an entirely new window (probably because of the init / super init code, which I do not fully understand, and don't really need to understand at the moment - it works, and I'm fine with that). I want code for a simple button that I could import into the main app, as a widget, and that I could place in the MainWin window inside the app.
|
[
"You can define the class in a separate module and then import it, but you will still want to initiate the button inside of your main window like you are doing now. After all the button does belong on the window.\nTo create a button class it would be similar to how you created the MainWindow...\nimport tkinter as tk\n\n\nclass MyButton(tk.Button):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n ... do something\n\n def buttonClicked(self, *args):\n print(\"Button Clicked\")\n\nThen you could just leave you mainwindow the way it is except switch out the class for your class. I also suggest moving a lot of your logic that is in the global scope inside of your MainWindow, and minimizing your use of the global scope as much as possible. For example:\nimport tkinter as tk\nfrom mybuttonmodule import MyButton\n\nclass MainWindow(tk.Tk):\n def __init__(self):\n super().__init__()\n\n # configure the root window\n self.title('Tkinter titlebar title')\n self.geometry('300x50')\n\n # create button within root window\n self.button = MyButton(self, text='Click Me')\n self.button.pack()\n self.button.config(command=self.button.buttonClicked)\n self.newlabel = tk.Label(self, text=\"Label\")\n self.newlabel.pack()\n self.geometry(\"700x400\")\n self.config(bg = \"yellow\")\n self.button.config(bg=\"lightblue\")\n\n\nif __name__ == \"__main__\":\n window = MainWindow()\n window.mainloop()\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0074513607_python_tkinter.txt
|
Q:
How to parse and get specific data from a huge json file to implement search in python
I have a json file with lot of information so I'm trying to just extract specific data where there is a position and I need to get the immediate name data, also trying to implement search in python.
I'm uploading a part of sample json data from the file ex.json
`
{
"storables": [
{
"columns": [
{
"position": 0,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "CAT",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
"sageOutputColumnId": "",
"defaultAggrType": "NONE",
"ownerName": "",
"ownerType": "WORKSHEET",
"entityCategory": "DEFAULT",
"spotiqPreference": "DEFAULT",
"isAdditive": false,
"indexType": "DEFAULT",
"indexPriority": 1,
"sources": [
{
"tableId": "",
"tableName": "",
"columnId": "",
"columnName": "CATASTROPHE"
}
],
"synonyms": [],
"injectedInlineValues": [],
"precision": -1,
"scale": 0,
"isPrimaryKey": false,
"isAttributionDimension": true,
"derivationExpr": {
"exprType": "LOGICAL_COLUMN_REFERENCE",
"logicalColumn": {
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "CATASTROPHE",
"author": "",
"created": 1630716505804,
"modified": 1668211006637,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"schemaStripe": "",
"databaseStripe": "",
"tags": [],
"isExternal": false,
"isDeprecated": false
}
},
"joinPaths": [
{
"joins": [
{
"sourceTable": "",
"destinationTable": "",
"content": {
"relationships": [
{
"sourceColumn": "",
"destinationColumn": ""
}
],
"weight": 1
},
"joinType": "INNER",
"type": "USER_DEFINED",
"isOneToOneJoin": false,
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "",
"description": "",
"author": "",
"created": 1650658367043,
"modified": 1668211006686,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"type": "USER_DEFINED",
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"sourceColumns": [
""
],
"targetColumns": [
""
]
}
]
}
]
}
},
{
"position": 1,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "Peril",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
"sageOutputColumnId": "",
"defaultAggrType": "NONE",
"ownerName": "",
"ownerType": "WORKSHEET",
"entityCategory": "DEFAULT",
"spotiqPreference": "DEFAULT",
"isAdditive": false,
"indexType": "DEFAULT",
"indexPriority": 1,
"sources": [
{
"tableId": "",
"tableName": "",
"columnId": "",
"columnName": "TYPE_OF"
}
],
"synonyms": [],
"injectedInlineValues": [],
"precision": -1,
"scale": 0,
"isPrimaryKey": false,
"isAttributionDimension": true,
"derivationExpr": {
"exprType": "LOGICAL_COLUMN_REFERENCE",
"logicalColumn": {
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "TYPE_OF",
"author": "",
"created": 1630716505804,
"modified": 1668211006637,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"schemaStripe": "",
"databaseStripe": "",
"tags": [],
"isExternal": false,
"isDeprecated": false
}
},
"joinPaths": [
{
"joins": [
{
"sourceTable": "",
"destinationTable": "",
"content": {
"relationships": [
{
"sourceColumn": "",
"destinationColumn": ""
}
],
"weight": 1
},
"joinType": "INNER",
"type": "USER_DEFINED",
"isOneToOneJoin": false,
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "",
"description": "Copy of user table relationship",
"author": "",
"created": 1650658367043,
"modified": 1668211006686,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"type": "USER_DEFINED",
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"sourceColumns": [
""
],
"targetColumns": [
""
]
}
]
}
]
}
},
{
"position": 2,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "Job",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
"sageOutputColumnId": "",
"defaultAggrType": "NONE",
"ownerName": "",
"ownerType": "WORKSHEET",
"entityCategory": "DEFAULT",
"spotiqPreference": "DEFAULT",
"isAdditive": false,
"indexType": "DEFAULT",
"indexPriority": 1,
"sources": [
{
"tableId": "",
"tableName": "",
"columnId": "",
"columnName": ""
}
],
"synonyms": [],
"injectedInlineValues": [],
"precision": -1,
"scale": 0,
"isPrimaryKey": false,
"isAttributionDimension": true,
"derivationExpr": {
"exprType": "LOGICAL_COLUMN_REFERENCE",
"logicalColumn": {
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "ROTATION_TRADE",
"author": "",
"created": 1630716505804,
"modified": 1668211006637,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"schemaStripe": "",
"databaseStripe": "",
"tags": [],
"isExternal": false,
"isDeprecated": false
}
},
"joinPaths": [
{
"joins": [
{
"sourceTable": "",
"destinationTable": "",
"content": {
"relationships": [
{
"sourceColumn": "",
"destinationColumn": ""
}
],
"weight": 1
},
"joinType": "INNER",
"type": "USER_DEFINED",
"isOneToOneJoin": false,
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "",
"description": "Copy of user table relationship",
"author": "",
"created": 1650658367043,
"modified": 1668211006686,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"type": "USER_DEFINED",
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"sourceColumns": [
""
],
"targetColumns": [
""
]
}
]
}
]
}
},
{
"position": 3,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "Job Lenghth",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
`
`
with open('ex.json', 'r') as f:
for line in f:
if 'position' in line:
for line in f:
if ' name: ' in line:
print(line)
`
I tried this python piece of code but it din't work. I'm not sure how to return just the immediate name after the position. There are multiple name instances in the file but I need just the one after position...
A:
import json
with open('ex.json', 'r') as f:
data = json.load(f)
Now you can access all json items just like you access any dictionary/object in python from data variable
A:
Your code may works, but you need to change the logic a little bit. Here is fast sketch of the solution:
prevWasPosition = False
with open('ex.json', 'r') as f:
for line in f:
if '"position":' in line:
prevWasPosition = True
continue
if prevWasPosition and '"name":' in line:
print(line)
prevWasPosition = False
Beware that this solution based on the assumption that json file is properly formatted. If it is not, you may get unexpected results. Stronger solution would be to use read file chunk by chunk and parse it as json, but it's beyond the scope of this answer.
|
How to parse and get specific data from a huge json file to implement search in python
|
I have a json file with lot of information so I'm trying to just extract specific data where there is a position and I need to get the immediate name data, also trying to implement search in python.
I'm uploading a part of sample json data from the file ex.json
`
{
"storables": [
{
"columns": [
{
"position": 0,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "CAT",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
"sageOutputColumnId": "",
"defaultAggrType": "NONE",
"ownerName": "",
"ownerType": "WORKSHEET",
"entityCategory": "DEFAULT",
"spotiqPreference": "DEFAULT",
"isAdditive": false,
"indexType": "DEFAULT",
"indexPriority": 1,
"sources": [
{
"tableId": "",
"tableName": "",
"columnId": "",
"columnName": "CATASTROPHE"
}
],
"synonyms": [],
"injectedInlineValues": [],
"precision": -1,
"scale": 0,
"isPrimaryKey": false,
"isAttributionDimension": true,
"derivationExpr": {
"exprType": "LOGICAL_COLUMN_REFERENCE",
"logicalColumn": {
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "CATASTROPHE",
"author": "",
"created": 1630716505804,
"modified": 1668211006637,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"schemaStripe": "",
"databaseStripe": "",
"tags": [],
"isExternal": false,
"isDeprecated": false
}
},
"joinPaths": [
{
"joins": [
{
"sourceTable": "",
"destinationTable": "",
"content": {
"relationships": [
{
"sourceColumn": "",
"destinationColumn": ""
}
],
"weight": 1
},
"joinType": "INNER",
"type": "USER_DEFINED",
"isOneToOneJoin": false,
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "",
"description": "",
"author": "",
"created": 1650658367043,
"modified": 1668211006686,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"type": "USER_DEFINED",
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"sourceColumns": [
""
],
"targetColumns": [
""
]
}
]
}
]
}
},
{
"position": 1,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "Peril",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
"sageOutputColumnId": "",
"defaultAggrType": "NONE",
"ownerName": "",
"ownerType": "WORKSHEET",
"entityCategory": "DEFAULT",
"spotiqPreference": "DEFAULT",
"isAdditive": false,
"indexType": "DEFAULT",
"indexPriority": 1,
"sources": [
{
"tableId": "",
"tableName": "",
"columnId": "",
"columnName": "TYPE_OF"
}
],
"synonyms": [],
"injectedInlineValues": [],
"precision": -1,
"scale": 0,
"isPrimaryKey": false,
"isAttributionDimension": true,
"derivationExpr": {
"exprType": "LOGICAL_COLUMN_REFERENCE",
"logicalColumn": {
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "TYPE_OF",
"author": "",
"created": 1630716505804,
"modified": 1668211006637,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"schemaStripe": "",
"databaseStripe": "",
"tags": [],
"isExternal": false,
"isDeprecated": false
}
},
"joinPaths": [
{
"joins": [
{
"sourceTable": "",
"destinationTable": "",
"content": {
"relationships": [
{
"sourceColumn": "",
"destinationColumn": ""
}
],
"weight": 1
},
"joinType": "INNER",
"type": "USER_DEFINED",
"isOneToOneJoin": false,
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "",
"description": "Copy of user table relationship",
"author": "",
"created": 1650658367043,
"modified": 1668211006686,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"type": "USER_DEFINED",
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"sourceColumns": [
""
],
"targetColumns": [
""
]
}
]
}
]
}
},
{
"position": 2,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "Job",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
"sageOutputColumnId": "",
"defaultAggrType": "NONE",
"ownerName": "",
"ownerType": "WORKSHEET",
"entityCategory": "DEFAULT",
"spotiqPreference": "DEFAULT",
"isAdditive": false,
"indexType": "DEFAULT",
"indexPriority": 1,
"sources": [
{
"tableId": "",
"tableName": "",
"columnId": "",
"columnName": ""
}
],
"synonyms": [],
"injectedInlineValues": [],
"precision": -1,
"scale": 0,
"isPrimaryKey": false,
"isAttributionDimension": true,
"derivationExpr": {
"exprType": "LOGICAL_COLUMN_REFERENCE",
"logicalColumn": {
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "ROTATION_TRADE",
"author": "",
"created": 1630716505804,
"modified": 1668211006637,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"schemaStripe": "",
"databaseStripe": "",
"tags": [],
"isExternal": false,
"isDeprecated": false
}
},
"joinPaths": [
{
"joins": [
{
"sourceTable": "",
"destinationTable": "",
"content": {
"relationships": [
{
"sourceColumn": "",
"destinationColumn": ""
}
],
"weight": 1
},
"joinType": "INNER",
"type": "USER_DEFINED",
"isOneToOneJoin": false,
"header": {
"id": "",
"indexVersion": 35499,
"generationNum": 35499,
"name": "",
"description": "Copy of user table relationship",
"author": "",
"created": 1650658367043,
"modified": 1668211006686,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"type": "USER_DEFINED",
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"sourceColumns": [
""
],
"targetColumns": [
""
]
}
]
}
]
}
},
{
"position": 3,
"header": {
"id": "",
"indexVersion": 35643,
"generationNum": 35643,
"name": "Job Lenghth",
"author": "",
"created": 1620247188226,
"modified": 1668544812673,
"modifiedBy": "",
"owner": "",
"isDeleted": false,
"isHidden": false,
"tags": [],
"isExternal": false,
"isDeprecated": false
},
"complete": true,
"incompleteDetail": [],
"isDerived": true,
"dataType": "VARCHAR",
"type": "ATTRIBUTE",
`
`
with open('ex.json', 'r') as f:
for line in f:
if 'position' in line:
for line in f:
if ' name: ' in line:
print(line)
`
I tried this python piece of code but it din't work. I'm not sure how to return just the immediate name after the position. There are multiple name instances in the file but I need just the one after position...
|
[
"import json\nwith open('ex.json', 'r') as f:\n data = json.load(f)\n\nNow you can access all json items just like you access any dictionary/object in python from data variable\n",
"Your code may works, but you need to change the logic a little bit. Here is fast sketch of the solution:\nprevWasPosition = False\nwith open('ex.json', 'r') as f:\n for line in f:\n if '\"position\":' in line:\n prevWasPosition = True\n continue\n\n if prevWasPosition and '\"name\":' in line:\n print(line)\n prevWasPosition = False\n\nBeware that this solution based on the assumption that json file is properly formatted. If it is not, you may get unexpected results. Stronger solution would be to use read file chunk by chunk and parse it as json, but it's beyond the scope of this answer.\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"json",
"parsing",
"python"
] |
stackoverflow_0074513435_arrays_json_parsing_python.txt
|
Q:
Can't index through graph containing string values
My goal im to be able to read the shortest distance between a specific building between all other buildings using the Dijkstra algorithm. I believe if I can fix the error, I will be able to complete my goal. The error below stops at a for loop, where it's trying to index through the vertices. I think it might have to do with the graph not containing an integer datatype, but that shouldn't matter because it should only be comparing the numbers in the graph. If someone could point me in the right direction so I can understand what I am doing wrong, that would be great.
Traceback (most recent call last):
File "main.py", line 26, in dijkstra
for v in self.graph[u]:
KeyError: 0
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = {}
def min_distance(self,distance,traversed):
min_index = 0
min_value = sys.maxsize
for i in range(self.V):
if traversed[i] is False and min_value > distance[i]:
min_value = distance[i]
min_index = i
return min_index
def dijkstra(self,source):
distance = [sys.maxsize] * self.V
traversed = [False] * self.V
distance[source] = 0
for i in range(self.V):
u = self.min_distance(distance,traversed)
traversed[u] = True
for v in self.graph[u]: #ERROR
if(traversed[v] is False):
distance[v] = min(distance[v],distance[u]+self.graph[u][v])
print("from the give source vertex -- > ",source)
for vertex in range(self.V):
print("Vertex ",vertex," --> Distance = ",distance[vertex])
g = Graph(19)
g.graph = {
'College Square':{'Lewis Science Center':200, 'Prince Center':300},
'Lewis Science Center':{'College Square':200, 'Speech Language Hearing':250, 'Computer Science':150},
'Speech Language Hearing':{'Lewis Science Center':250, 'Burdick':100, 'Maintenance College':120},
'Computer Science':{'Prince Center':80, 'Torreyson Library':40, 'Burdick':30, 'Lewis Science Center':150},
'Burdick':{'Computer Science':30, 'Speech Language Hearing':100, 'Torreyson Library':80, 'Maintenance College':300, 'McALister Hall':200},
'Prince Center':{'College Square':300, 'Computer Science':80, 'Torreyson Library':30, 'Police Dept.':100},
'Torreyson Library':{'Prince Center':30, 'Computer Science':40, 'Burdick':80, 'Old Main':30},
'Old Main':{'Torreyson Library':30, 'Police Dept.':200, 'Fine Art':90, 'McALister Hall':100},
'Maintenance College':{'Speech Language Hearing':120, 'Burdick':300, 'McALister Hall':150, 'Wingo':100, 'New Business Building':150, 'Oak Tree Apt.':160},
'Police Dept.':{'Prince Center':100, 'Old Main':200, 'Fine Art':50, 'Student Health Center':100},
'Fine Art':{'Police Dept.':50, 'Old Main':90, 'McALister Hall':180, 'Student Center':80},
'McALister Hall':{'Fine Art':180, 'Old Main':100, 'Burdick':200, 'Maintenance College':150, 'Wingo':50, 'Student Center':100},
'Student Center':{'Fine Art':80, 'McALister Hall':100, 'Wingo':100, 'New Business Building':110, 'Student Health Center':50},
'Wingo':{'Student Center':100, 'McALister Hall':50, 'Maintenance College':100, 'New Business Building':50},
'Student Health Center':{'Police Dept.':100, 'Student Center':50, 'Brewer-Hegeman':200},
'New Business Building':{'Student Center':110, 'Wingo':50, 'Maintenance College':150, 'Oak Tree Apt.':30, 'Brewer-Hegeman':20},
'Oak Tree Apt.':{'Maintenance College':160, 'New Business Building':30, 'Brewer-Hegeman':40},
'Brewer-Hegeman':{'Student Health Center':200, 'New Business Building':20, 'Oak Tree Apt.':40, 'Bear village Apt.':350},
'Bear village Apt.':{'Brewer-Hegeman':350}
}
g.dijkstra(0)
A:
changed to work with strings"
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = {}
def min_distance(self,distance,traversed):
min_index = 0
min_value = sys.maxsize
for i in self.graph:
if traversed[i] is False and min_value > distance[i]:
min_value = distance[i]
min_index = i
return min_index
def dijkstra(self,source):
distance={}
traversed={}
for i in self.graph:
traversed[i] = False
distance[i] = sys.maxsize
distance[source] = 0
for i in self.graph:
u = self.min_distance(distance,traversed)
traversed[u] = True
for v in self.graph[u]: #ERROR
if(traversed[v] is False):
distance[v] = min(distance[v],distance[u]+self.graph[u][v])
print("from the give source vertex -- > ",source)
for vertex in self.graph:
print("Vertex ",vertex," --> Distance = ",distance[vertex])
g = Graph(19)
g.graph = {
'College Square':{'Lewis Science Center':200, 'Prince Center':300},
'Lewis Science Center':{'College Square':200, 'Speech Language Hearing':250, 'Computer Science':150},
'Speech Language Hearing':{'Lewis Science Center':250, 'Burdick':100, 'Maintenance College':120},
'Computer Science':{'Prince Center':80, 'Torreyson Library':40, 'Burdick':30, 'Lewis Science Center':150},
'Burdick':{'Computer Science':30, 'Speech Language Hearing':100, 'Torreyson Library':80, 'Maintenance College':300, 'McALister Hall':200},
'Prince Center':{'College Square':300, 'Computer Science':80, 'Torreyson Library':30, 'Police Dept.':100},
'Torreyson Library':{'Prince Center':30, 'Computer Science':40, 'Burdick':80, 'Old Main':30},
'Old Main':{'Torreyson Library':30, 'Police Dept.':200, 'Fine Art':90, 'McALister Hall':100},
'Maintenance College':{'Speech Language Hearing':120, 'Burdick':300, 'McALister Hall':150, 'Wingo':100, 'New Business Building':150, 'Oak Tree Apt.':160},
'Police Dept.':{'Prince Center':100, 'Old Main':200, 'Fine Art':50, 'Student Health Center':100},
'Fine Art':{'Police Dept.':50, 'Old Main':90, 'McALister Hall':180, 'Student Center':80},
'McALister Hall':{'Fine Art':180, 'Old Main':100, 'Burdick':200, 'Maintenance College':150, 'Wingo':50, 'Student Center':100},
'Student Center':{'Fine Art':80, 'McALister Hall':100, 'Wingo':100, 'New Business Building':110, 'Student Health Center':50},
'Wingo':{'Student Center':100, 'McALister Hall':50, 'Maintenance College':100, 'New Business Building':50},
'Student Health Center':{'Police Dept.':100, 'Student Center':50, 'Brewer-Hegeman':200},
'New Business Building':{'Student Center':110, 'Wingo':50, 'Maintenance College':150, 'Oak Tree Apt.':30, 'Brewer-Hegeman':20},
'Oak Tree Apt.':{'Maintenance College':160, 'New Business Building':30, 'Brewer-Hegeman':40},
'Brewer-Hegeman':{'Student Health Center':200, 'New Business Building':20, 'Oak Tree Apt.':40, 'Bear village Apt.':350},
'Bear village Apt.':{'Brewer-Hegeman':350}
}
g.dijkstra('College Square')
|
Can't index through graph containing string values
|
My goal im to be able to read the shortest distance between a specific building between all other buildings using the Dijkstra algorithm. I believe if I can fix the error, I will be able to complete my goal. The error below stops at a for loop, where it's trying to index through the vertices. I think it might have to do with the graph not containing an integer datatype, but that shouldn't matter because it should only be comparing the numbers in the graph. If someone could point me in the right direction so I can understand what I am doing wrong, that would be great.
Traceback (most recent call last):
File "main.py", line 26, in dijkstra
for v in self.graph[u]:
KeyError: 0
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = {}
def min_distance(self,distance,traversed):
min_index = 0
min_value = sys.maxsize
for i in range(self.V):
if traversed[i] is False and min_value > distance[i]:
min_value = distance[i]
min_index = i
return min_index
def dijkstra(self,source):
distance = [sys.maxsize] * self.V
traversed = [False] * self.V
distance[source] = 0
for i in range(self.V):
u = self.min_distance(distance,traversed)
traversed[u] = True
for v in self.graph[u]: #ERROR
if(traversed[v] is False):
distance[v] = min(distance[v],distance[u]+self.graph[u][v])
print("from the give source vertex -- > ",source)
for vertex in range(self.V):
print("Vertex ",vertex," --> Distance = ",distance[vertex])
g = Graph(19)
g.graph = {
'College Square':{'Lewis Science Center':200, 'Prince Center':300},
'Lewis Science Center':{'College Square':200, 'Speech Language Hearing':250, 'Computer Science':150},
'Speech Language Hearing':{'Lewis Science Center':250, 'Burdick':100, 'Maintenance College':120},
'Computer Science':{'Prince Center':80, 'Torreyson Library':40, 'Burdick':30, 'Lewis Science Center':150},
'Burdick':{'Computer Science':30, 'Speech Language Hearing':100, 'Torreyson Library':80, 'Maintenance College':300, 'McALister Hall':200},
'Prince Center':{'College Square':300, 'Computer Science':80, 'Torreyson Library':30, 'Police Dept.':100},
'Torreyson Library':{'Prince Center':30, 'Computer Science':40, 'Burdick':80, 'Old Main':30},
'Old Main':{'Torreyson Library':30, 'Police Dept.':200, 'Fine Art':90, 'McALister Hall':100},
'Maintenance College':{'Speech Language Hearing':120, 'Burdick':300, 'McALister Hall':150, 'Wingo':100, 'New Business Building':150, 'Oak Tree Apt.':160},
'Police Dept.':{'Prince Center':100, 'Old Main':200, 'Fine Art':50, 'Student Health Center':100},
'Fine Art':{'Police Dept.':50, 'Old Main':90, 'McALister Hall':180, 'Student Center':80},
'McALister Hall':{'Fine Art':180, 'Old Main':100, 'Burdick':200, 'Maintenance College':150, 'Wingo':50, 'Student Center':100},
'Student Center':{'Fine Art':80, 'McALister Hall':100, 'Wingo':100, 'New Business Building':110, 'Student Health Center':50},
'Wingo':{'Student Center':100, 'McALister Hall':50, 'Maintenance College':100, 'New Business Building':50},
'Student Health Center':{'Police Dept.':100, 'Student Center':50, 'Brewer-Hegeman':200},
'New Business Building':{'Student Center':110, 'Wingo':50, 'Maintenance College':150, 'Oak Tree Apt.':30, 'Brewer-Hegeman':20},
'Oak Tree Apt.':{'Maintenance College':160, 'New Business Building':30, 'Brewer-Hegeman':40},
'Brewer-Hegeman':{'Student Health Center':200, 'New Business Building':20, 'Oak Tree Apt.':40, 'Bear village Apt.':350},
'Bear village Apt.':{'Brewer-Hegeman':350}
}
g.dijkstra(0)
|
[
"changed to work with strings\"\nimport sys \n \nclass Graph(): \n \n def __init__(self, vertices): \n self.V = vertices \n self.graph = {}\n \n def min_distance(self,distance,traversed):\n min_index = 0 \n min_value = sys.maxsize\n for i in self.graph:\n if traversed[i] is False and min_value > distance[i]:\n min_value = distance[i]\n min_index = i\n return min_index\n \n def dijkstra(self,source):\n distance={}\n traversed={}\n for i in self.graph:\n traversed[i] = False\n distance[i] = sys.maxsize\n distance[source] = 0\n \n for i in self.graph:\n u = self.min_distance(distance,traversed)\n traversed[u] = True\n for v in self.graph[u]: #ERROR\n if(traversed[v] is False):\n distance[v] = min(distance[v],distance[u]+self.graph[u][v])\n print(\"from the give source vertex -- > \",source)\n for vertex in self.graph:\n print(\"Vertex \",vertex,\" --> Distance = \",distance[vertex])\n \ng = Graph(19)\n\ng.graph = {\n 'College Square':{'Lewis Science Center':200, 'Prince Center':300},\n 'Lewis Science Center':{'College Square':200, 'Speech Language Hearing':250, 'Computer Science':150},\n 'Speech Language Hearing':{'Lewis Science Center':250, 'Burdick':100, 'Maintenance College':120},\n 'Computer Science':{'Prince Center':80, 'Torreyson Library':40, 'Burdick':30, 'Lewis Science Center':150},\n 'Burdick':{'Computer Science':30, 'Speech Language Hearing':100, 'Torreyson Library':80, 'Maintenance College':300, 'McALister Hall':200},\n 'Prince Center':{'College Square':300, 'Computer Science':80, 'Torreyson Library':30, 'Police Dept.':100},\n 'Torreyson Library':{'Prince Center':30, 'Computer Science':40, 'Burdick':80, 'Old Main':30},\n 'Old Main':{'Torreyson Library':30, 'Police Dept.':200, 'Fine Art':90, 'McALister Hall':100},\n 'Maintenance College':{'Speech Language Hearing':120, 'Burdick':300, 'McALister Hall':150, 'Wingo':100, 'New Business Building':150, 'Oak Tree Apt.':160},\n 'Police Dept.':{'Prince Center':100, 'Old Main':200, 'Fine Art':50, 'Student Health Center':100},\n 'Fine Art':{'Police Dept.':50, 'Old Main':90, 'McALister Hall':180, 'Student Center':80},\n 'McALister Hall':{'Fine Art':180, 'Old Main':100, 'Burdick':200, 'Maintenance College':150, 'Wingo':50, 'Student Center':100},\n 'Student Center':{'Fine Art':80, 'McALister Hall':100, 'Wingo':100, 'New Business Building':110, 'Student Health Center':50},\n 'Wingo':{'Student Center':100, 'McALister Hall':50, 'Maintenance College':100, 'New Business Building':50},\n 'Student Health Center':{'Police Dept.':100, 'Student Center':50, 'Brewer-Hegeman':200},\n 'New Business Building':{'Student Center':110, 'Wingo':50, 'Maintenance College':150, 'Oak Tree Apt.':30, 'Brewer-Hegeman':20},\n 'Oak Tree Apt.':{'Maintenance College':160, 'New Business Building':30, 'Brewer-Hegeman':40},\n 'Brewer-Hegeman':{'Student Health Center':200, 'New Business Building':20, 'Oak Tree Apt.':40, 'Bear village Apt.':350},\n 'Bear village Apt.':{'Brewer-Hegeman':350}\n\n }\n\ng.dijkstra('College Square')\n\n"
] |
[
1
] |
[] |
[] |
[
"algorithm",
"graph",
"python"
] |
stackoverflow_0074513489_algorithm_graph_python.txt
|
Q:
Is there a way to find the position of my for loop variable in a integer list
For example, num = [4, 6, 2, 5, 7]
for i in num:
for j in num:
j = num[i+1]
Is there a way to find if i is in the 0 position, 1 position, 2 position, ...
so that I can make it were j = what position i is in +1
I also want to make it were if, lets say i was in position 1;
if i == i+1:
num.remove(i)
I already tried i+1 just doing i plus one and i could do a bunch of if statements and just make it do 1 over but i have like 4 variable for the for loop all in different position of i and I'm worried it will say list(x) out of index. I also tried .find put it didn't work for a list.
Also, I need to make it as too were it doesn’t change the original value of the integer so that I can add them up, would I have to make too lists.
A:
Yes, what you're looking for is the enumerate function, which takes in a list and gives you both the index and the value of each element in the list:
nums = [4, 6, 2, 5, 7]
for index, value in enumerate(nums):
print(index, value)
# will print
# (0, 4)
# (1, 6)
# (2, 2)
# (3, 5)
# (4, 7)
Some extra info from RealPython: https://realpython.com/python-enumerate/
|
Is there a way to find the position of my for loop variable in a integer list
|
For example, num = [4, 6, 2, 5, 7]
for i in num:
for j in num:
j = num[i+1]
Is there a way to find if i is in the 0 position, 1 position, 2 position, ...
so that I can make it were j = what position i is in +1
I also want to make it were if, lets say i was in position 1;
if i == i+1:
num.remove(i)
I already tried i+1 just doing i plus one and i could do a bunch of if statements and just make it do 1 over but i have like 4 variable for the for loop all in different position of i and I'm worried it will say list(x) out of index. I also tried .find put it didn't work for a list.
Also, I need to make it as too were it doesn’t change the original value of the integer so that I can add them up, would I have to make too lists.
|
[
"Yes, what you're looking for is the enumerate function, which takes in a list and gives you both the index and the value of each element in the list:\nnums = [4, 6, 2, 5, 7]\n\nfor index, value in enumerate(nums):\n print(index, value)\n\n# will print\n# (0, 4)\n# (1, 6)\n# (2, 2)\n# (3, 5)\n# (4, 7)\n\nSome extra info from RealPython: https://realpython.com/python-enumerate/\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074513681_python.txt
|
Q:
Python get mouse x, y position on click
Coming from IDL, I find it quite hard in python to get the x-y position of the mouse on a single left click using a method that is not an overkill as in tkinter. Does anyone know about a python package that contains a method simply returning x-y when the mouse is clicked (similar to the cursor method in IDL)?
A:
There are a number of libraries you could use. Here are two third party ones:
Using PyAutoGui
A powerful GUI automation library allows you to get screen size, control the mouse, keyboard and more.
To get the position you just need to use the position() function. Here is an example:
>>>import pyautogui
>>>pyautogui.position()
(1358, 146)
>>>
Where 1358 is the X position and 146 is the Y position.
Relavent link to the documentation
Using Pynput
Another (more minimalistic) library is Pynput:
>>> from pynput.mouse import Controller
>>> mouse = Controller()
>>> mouse.position
(1182, 153)
>>>
Where 1182 is the X position and 153 is the second.
Documentation
This library is quite easy to learn, does not require dependencies, making this library ideal for small tasks like this (where PyAutoGui would be an overkill). Once again though, it does not provide so many features though.
Windows Specific:
For platform dependant, but default library options (though you may still consider them overkills) can be found here: Getting cursor position in Python.
A:
Using PyMouse:
>>> import pymouse
>>> mouse = pymouse.PyMouse()
>>> mouse.position()
(231L, 479L)
A:
As an example, for plot or images, it is possible to use the matplotlib tool called ginput.
At every click of the mouse the [x,y] coordinates of the selected point are stored in a variable.
# show image
fig, ax=plt.subplots()
ax.imshow(img)
# select point
yroi = plt.ginput(0,0)
using ginput(0,0) you can select any points on the plot or image.
here the link for the ginput documentation
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.ginput.html
A:
I made this the other day.
It a function to get color or pos on right click / left click:
#Add Any helpfull stuff in functions here for later use
def GetMouseInfos(WhatToGet="leaving emety will get you x and y", GetXOnly=False, GetYOnly=False, GetColor=False, Key='Right', OverrideKey=False):#gets color of whats under Key cursor on right click
try:
import win32api
except ModuleNotFoundError:
print("win32api not found, to install do pip install pywin32")
try:
import time
except ModuleNotFoundError:
print("time not found, to install do pip install time?")
try:
import pyautogui
except ModuleNotFoundError:
print("py auto gui not found, to install do pip install pyautogui")
#--------------------------------------------------------------
#above checks if needed modules are installed if not tells user
#code below is to get all varibles needed
#---------------------------------------------------------------
print(WhatToGet)
if OverrideKey:
Key_To_click = Key
if Key == 'Left':
Key_To_click = 0x01
if Key == 'Right':
Key_To_click = 0x02
if Key == 'Wheel':
Key_To_click = 0x04
state_left = win32api.GetKeyState(Key_To_click) # Left button up = 0 or 1. Button down = -127 or -128
IsTrue = True
while IsTrue:
a = win32api.GetKeyState(Key_To_click)
if a != state_left: # Button state changed
state_left = a
if a < 0:
global Xpos, Ypos
Xpos, Ypos = win32api.GetCursorPos()
x, y = pyautogui.position()
pixelColor = pyautogui.screenshot().getpixel((x, y))
else:
posnowX, posnowY = win32api.GetCursorPos()
win32api.SetCursorPos((posnowX, posnowY))
IsTrue = False#remove this for it to keep giving coords on click without it just quitting after 1 click
time.sleep(0.001)
#--------------------------------------------------------------------
#The Code above is the code to get all varibles and code below is for the user to get what he wants
#--------------------------------------------------------------------
if GetXOnly: #Checks if we should get Only X (def options) the command to do this would be GetKeyInfos("Click To get X ONLY", True)
if GetYOnly:
return(Xpos , Ypos)
if GetColor:
return(Xpos, pixelColor)
return(Xpos)
if GetYOnly: #Checks if we should get Only Y (def options) the command to do this would be GetKeyInfos("Click To get X ONLY",False, True)
if GetXOnly:
return(Xpos , Ypos)
if GetColor:
return(Ypos, pixelColor)
return(Ypos)
if GetColor:
return(pixelColor) #Checks
return(Xpos, Ypos)
# getKeyinfos("Anything here without any other guidelines will give u x and y only on right click")
A:
Use pygame
import pygame
mouse_pos = pygame.mouse.get_pos()
This returns the x and y position of the mouse.
See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos
A:
Here is an example for canvas with tkinter:
def callback(event):
print("clicked at: ", event.x, event.y)
canvas.bind("<Button-1>", callback)
A:
For turtle :
def get_mouse_click_coor(x, y):
print(x, y)
turtle.onscreenclick(get_mouse_click_coor)
A:
Capture the coordinates (x,y) of the mouse, when clicking with the left button, without using Tkinter?
It's simple:
Install pynput (use pip install pynput (without the 'i').
Copy and paste this code into your editor:
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
x = x
y = y
print('X =', x, '\nY =', y)
with Listener(on_click=on_click) as listener:
listener.join()
I hope this help you =D
|
Python get mouse x, y position on click
|
Coming from IDL, I find it quite hard in python to get the x-y position of the mouse on a single left click using a method that is not an overkill as in tkinter. Does anyone know about a python package that contains a method simply returning x-y when the mouse is clicked (similar to the cursor method in IDL)?
|
[
"There are a number of libraries you could use. Here are two third party ones:\nUsing PyAutoGui\nA powerful GUI automation library allows you to get screen size, control the mouse, keyboard and more.\nTo get the position you just need to use the position() function. Here is an example:\n>>>import pyautogui\n>>>pyautogui.position()\n(1358, 146)\n>>>\n\nWhere 1358 is the X position and 146 is the Y position.\nRelavent link to the documentation\nUsing Pynput\nAnother (more minimalistic) library is Pynput:\n>>> from pynput.mouse import Controller\n>>> mouse = Controller()\n>>> mouse.position\n(1182, 153)\n>>>\n\nWhere 1182 is the X position and 153 is the second.\nDocumentation\nThis library is quite easy to learn, does not require dependencies, making this library ideal for small tasks like this (where PyAutoGui would be an overkill). Once again though, it does not provide so many features though.\nWindows Specific:\nFor platform dependant, but default library options (though you may still consider them overkills) can be found here: Getting cursor position in Python.\n",
"Using PyMouse:\n>>> import pymouse\n>>> mouse = pymouse.PyMouse()\n>>> mouse.position()\n(231L, 479L)\n\n",
"As an example, for plot or images, it is possible to use the matplotlib tool called ginput.\nAt every click of the mouse the [x,y] coordinates of the selected point are stored in a variable.\n# show image\nfig, ax=plt.subplots()\nax.imshow(img)\n\n# select point\nyroi = plt.ginput(0,0)\n\nusing ginput(0,0) you can select any points on the plot or image.\nhere the link for the ginput documentation\nhttps://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.ginput.html\n",
"I made this the other day.\nIt a function to get color or pos on right click / left click:\n#Add Any helpfull stuff in functions here for later use\ndef GetMouseInfos(WhatToGet=\"leaving emety will get you x and y\", GetXOnly=False, GetYOnly=False, GetColor=False, Key='Right', OverrideKey=False):#gets color of whats under Key cursor on right click\n try:\n import win32api\n except ModuleNotFoundError:\n print(\"win32api not found, to install do pip install pywin32\")\n try:\n import time\n except ModuleNotFoundError:\n print(\"time not found, to install do pip install time?\")\n try:\n import pyautogui\n except ModuleNotFoundError:\n print(\"py auto gui not found, to install do pip install pyautogui\")\n #--------------------------------------------------------------\n #above checks if needed modules are installed if not tells user\n #code below is to get all varibles needed\n #---------------------------------------------------------------\n print(WhatToGet)\n if OverrideKey:\n Key_To_click = Key\n if Key == 'Left':\n Key_To_click = 0x01\n if Key == 'Right':\n Key_To_click = 0x02\n if Key == 'Wheel':\n Key_To_click = 0x04\n state_left = win32api.GetKeyState(Key_To_click) # Left button up = 0 or 1. Button down = -127 or -128\n IsTrue = True\n while IsTrue:\n a = win32api.GetKeyState(Key_To_click)\n if a != state_left: # Button state changed\n state_left = a\n if a < 0:\n global Xpos, Ypos\n Xpos, Ypos = win32api.GetCursorPos()\n x, y = pyautogui.position()\n pixelColor = pyautogui.screenshot().getpixel((x, y))\n else:\n posnowX, posnowY = win32api.GetCursorPos()\n win32api.SetCursorPos((posnowX, posnowY))\n IsTrue = False#remove this for it to keep giving coords on click without it just quitting after 1 click\n time.sleep(0.001)\n #--------------------------------------------------------------------\n #The Code above is the code to get all varibles and code below is for the user to get what he wants\n #--------------------------------------------------------------------\n \n if GetXOnly: #Checks if we should get Only X (def options) the command to do this would be GetKeyInfos(\"Click To get X ONLY\", True)\n if GetYOnly:\n return(Xpos , Ypos)\n if GetColor:\n return(Xpos, pixelColor)\n return(Xpos)\n if GetYOnly: #Checks if we should get Only Y (def options) the command to do this would be GetKeyInfos(\"Click To get X ONLY\",False, True)\n if GetXOnly:\n return(Xpos , Ypos)\n if GetColor:\n return(Ypos, pixelColor) \n return(Ypos)\n if GetColor:\n return(pixelColor) #Checks \n return(Xpos, Ypos)\n# getKeyinfos(\"Anything here without any other guidelines will give u x and y only on right click\")\n\n",
"Use pygame\nimport pygame\n\nmouse_pos = pygame.mouse.get_pos()\n\nThis returns the x and y position of the mouse. \nSee this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos\n",
"Here is an example for canvas with tkinter:\ndef callback(event): \n print(\"clicked at: \", event.x, event.y) \n\ncanvas.bind(\"<Button-1>\", callback)\n\n",
"For turtle :\ndef get_mouse_click_coor(x, y):\n print(x, y)\n\nturtle.onscreenclick(get_mouse_click_coor)\n\n",
"Capture the coordinates (x,y) of the mouse, when clicking with the left button, without using Tkinter?\nIt's simple:\n\nInstall pynput (use pip install pynput (without the 'i').\nCopy and paste this code into your editor:\n\nfrom pynput.mouse import Listener\n\ndef on_click(x, y, button, pressed):\n x = x\n y = y\n print('X =', x, '\\nY =', y)\n\nwith Listener(on_click=on_click) as listener:\n listener.join()\n\nI hope this help you =D\n"
] |
[
21,
14,
3,
3,
2,
1,
1,
0
] |
[
"You all are making it too hard, its just as easy as:\nimport pyautogui as pg\n\npos = pg.position()\n\n# for x pos\nprint(pos[0])\n\n# for y pos\nprint(pos[1])\n\n"
] |
[
-2
] |
[
"python",
"python_2.7"
] |
stackoverflow_0025848951_python_python_2.7.txt
|
Q:
ValueError: No password or public key available
I'm trying to connect to a remote MySQL database through an SSH Tunnel and deploying my code to Streamlit. When I try to do it, I get this error:
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 966, in __init__
(self.ssh_password, self.ssh_pkeys) = self._consolidate_auth(
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 1169, in _consolidate_auth
raise ValueError('No password or public key available!')
ValueError: No password or public key available!
I've tried a lot of things, from updating my SSH keys to my server and github to changing my code.
The code I have for the SSH - MySQL section looks like this:
import MySQLdb as db
from sshtunnel import SSHTunnelForwarder
def query(q):
with SSHTunnelForwarder(
ssh_address_or_host=("host_ip"),
ssh_username=("host_username"),
ssh_pkey=("path_to_private_sshkey"),
remote_bind_address=("private_host_ip", "host_port")
) as server:
conn = db.connect(
host="localhost",
port=server.local_bind_port,
user="db_username",
passwd="db_password",
db="db_database"
)
return pd.read_sql_query(q, conn)
I appreciate any help you can give me.
A:
conn = db.connect(host="localhost"),
port=server.local_bind_port,
user=("db_username"),
passwd=("db_password"),
db=("db_database")
Because you have a closing parentheses on the first line, only the host argument is being passed to the db.connect() function. And so the function is complaining that it doesn't have a password, username, etc.
The other lines are creating plain local variables.
|
ValueError: No password or public key available
|
I'm trying to connect to a remote MySQL database through an SSH Tunnel and deploying my code to Streamlit. When I try to do it, I get this error:
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 966, in __init__
(self.ssh_password, self.ssh_pkeys) = self._consolidate_auth(
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 1169, in _consolidate_auth
raise ValueError('No password or public key available!')
ValueError: No password or public key available!
I've tried a lot of things, from updating my SSH keys to my server and github to changing my code.
The code I have for the SSH - MySQL section looks like this:
import MySQLdb as db
from sshtunnel import SSHTunnelForwarder
def query(q):
with SSHTunnelForwarder(
ssh_address_or_host=("host_ip"),
ssh_username=("host_username"),
ssh_pkey=("path_to_private_sshkey"),
remote_bind_address=("private_host_ip", "host_port")
) as server:
conn = db.connect(
host="localhost",
port=server.local_bind_port,
user="db_username",
passwd="db_password",
db="db_database"
)
return pd.read_sql_query(q, conn)
I appreciate any help you can give me.
|
[
"conn = db.connect(host=\"localhost\"), \nport=server.local_bind_port, \nuser=(\"db_username\"), \npasswd=(\"db_password\"), \ndb=(\"db_database\")\n\nBecause you have a closing parentheses on the first line, only the host argument is being passed to the db.connect() function. And so the function is complaining that it doesn't have a password, username, etc.\nThe other lines are creating plain local variables.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"ssh_tunnel",
"streamlit"
] |
stackoverflow_0074513690_python_ssh_tunnel_streamlit.txt
|
Q:
Optimize conversion of numpy ndarray to string
I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.
I currently use imageio to get an RGB matrix from the image and then convert that to hex. I'm trying to optimize the Image to bytes part, as it takes around 2.5 seconds for a 442KB image of 918 x 575 pixels.
How could I make it quicker?
Here's the code:
def rgb2hex(rgb):
"""
convert a list or tuple of RGB values
to a string in hex
"""
r,g,b = rgb
return '{:02x}{:02x}{:02x}'.format(r, g, b)
def arrayToString(array):
"""
convert an array to a string
"""
string = ""
for element in array:
string += str(element)
return string
def sliceStr(string,sliceLenght):
"""
slice a string in chunks of sliceLenght lenght
"""
string = str(string)
array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)])
return array
def hexToRGB(hexadecimal):
"""
convert a hex string to an array of RGB values
"""
h = hexadecimal.lstrip('#')
if len(h)!=6:
return
return [int(h[i:i+2], 16) for i in (0, 2, 4)]
def ImageToBytes(image):
"""
Image to convert from image to bytes
"""
dataToEncrypt =imageio.imread(image)
if dataToEncrypt.shape[2] ==4:
dataToEncrypt = np.delete(dataToEncrypt,3,2)
originalRows, originalColumns,_ = dataToEncrypt.shape
#converting rgb to hex
hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt)
hexVal = np.apply_along_axis(arrayToString, 1, hexVal)
hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal))
byteImage = bytes.fromhex(hexVal)
return (byteImage, [originalRows,originalColumns])
A:
One simple approach is to use tobytes on the numpy array. E.g.,
image = imageio.imread(filename)
# Drop the alpha channel.
if image.shape[2] == 4:
image = image[..., :3]
# Convert to bytes directly.
byte_image = image.tobytes()
On my machine, this gives a 250x speed up compared with converting to strings first. Note: this will only work if the dtype of the array is uint8. But that's luckily the default provided by imread.
A:
This should be more faster due to less conversions
def ImageToBytes2(image):
"""
Image to convert from image to bytes
"""
dataToEncrypt =imageio.imread(image)
if dataToEncrypt.shape[2] ==4:
dataToEncrypt = np.delete(dataToEncrypt,3,2)
originalRows, originalColumns,_ = dataToEncrypt.shape
dataToEncrypt = dataToEncrypt.reshape(1,originalRows*originalColumns*3)
#converting rgb to hex
byteImage = bytes(dataToEncrypt)
return (byteImage, [originalRows,originalColumns])
|
Optimize conversion of numpy ndarray to string
|
I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.
I currently use imageio to get an RGB matrix from the image and then convert that to hex. I'm trying to optimize the Image to bytes part, as it takes around 2.5 seconds for a 442KB image of 918 x 575 pixels.
How could I make it quicker?
Here's the code:
def rgb2hex(rgb):
"""
convert a list or tuple of RGB values
to a string in hex
"""
r,g,b = rgb
return '{:02x}{:02x}{:02x}'.format(r, g, b)
def arrayToString(array):
"""
convert an array to a string
"""
string = ""
for element in array:
string += str(element)
return string
def sliceStr(string,sliceLenght):
"""
slice a string in chunks of sliceLenght lenght
"""
string = str(string)
array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)])
return array
def hexToRGB(hexadecimal):
"""
convert a hex string to an array of RGB values
"""
h = hexadecimal.lstrip('#')
if len(h)!=6:
return
return [int(h[i:i+2], 16) for i in (0, 2, 4)]
def ImageToBytes(image):
"""
Image to convert from image to bytes
"""
dataToEncrypt =imageio.imread(image)
if dataToEncrypt.shape[2] ==4:
dataToEncrypt = np.delete(dataToEncrypt,3,2)
originalRows, originalColumns,_ = dataToEncrypt.shape
#converting rgb to hex
hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt)
hexVal = np.apply_along_axis(arrayToString, 1, hexVal)
hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal))
byteImage = bytes.fromhex(hexVal)
return (byteImage, [originalRows,originalColumns])
|
[
"One simple approach is to use tobytes on the numpy array. E.g.,\nimage = imageio.imread(filename)\n# Drop the alpha channel.\nif image.shape[2] == 4:\n image = image[..., :3]\n# Convert to bytes directly.\nbyte_image = image.tobytes()\n\nOn my machine, this gives a 250x speed up compared with converting to strings first. Note: this will only work if the dtype of the array is uint8. But that's luckily the default provided by imread.\n",
"This should be more faster due to less conversions\ndef ImageToBytes2(image):\n \"\"\"\n Image to convert from image to bytes\n \"\"\"\n dataToEncrypt =imageio.imread(image)\n\n if dataToEncrypt.shape[2] ==4:\n dataToEncrypt = np.delete(dataToEncrypt,3,2)\n\n originalRows, originalColumns,_ = dataToEncrypt.shape\n\n dataToEncrypt = dataToEncrypt.reshape(1,originalRows*originalColumns*3)\n\n #converting rgb to hex\n byteImage = bytes(dataToEncrypt)\n\n return (byteImage, [originalRows,originalColumns])\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"numpy",
"python",
"python_3.x",
"python_imageio"
] |
stackoverflow_0074513611_numpy_python_python_3.x_python_imageio.txt
|
Q:
In Python code below, how can I immediately exit the code?
I have been trying below this two days, but cannot make it work.
I have tried
except KeyboardInterrupt:
sys.exit()
exit()
control+C
, and so on.
I have tried the code, but it terminates only after 30 seconds or 1 minute. It seems like "listener" in the code makes the code complicated.
I need to make the code terminate immediately when I press ESC. "Terminate" here means stop the code from running or close the entire terminal. Either way is fine, but it needs to work "immediately".
I am using Windows10. It does not need to be compatible with MAC os.
import pydirectinput
import datetime
import time
import threading
from pynput.mouse import Controller, Button
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="`")
clicking = False
mouse = Controller()
def clicker():
global fishpause
global a_press
global d_press
global maxtime
duration = 0
while True and duration <= maxtime:
qtime = datetime.datetime.utcnow()
if qtime.hour == 11 and qtime.minute == 30:
print("Quiting by using an error...")
pydirectinput.keydown('alt')
else:
if clicking:
mouse.press(Button.right)
#print("Button pressed")
goleft(fishpause, a_press)
duration += 1
print(f"Duration is: {duration}")
time.sleep(0.5)
time.sleep(0.5)
mouse.release(Button.right)
def toggle_event(key):
if key == TOGGLE_KEY:
global clicking
clicking = not clicking
print("Clicking changed")
def goleft(fishpause, a_press):
pydirectinput.press('a', presses=1, interval=a_press)
print("Moving left")
pydirectinput.PAUSE = fishpause
print(f"PAUSING: {fishpause}")
maxtime = 4500
fishpause = 9.0
a_press = 0.1
time.sleep(1)
print("Starting")
pydirectinput.press('esc', presses=1, interval=0.1)
click_thread = threading.Thread(target=clicker)
click_thread.start()
time.sleep(3)
with Listener(on_press=toggle_event) as listener:
listener.join()
A:
The program won't exit while the click_thread is still running.
If the clicker knows that it's supposed to exit it can break the loop and return. Alternatively, if you mark the thread as a daemon:
click_thread = threading.Thread(target=clicker, daemon=True)
then it will exit when the main program exits.
You can test this with the tiny program below. Try with daemon=True and with daemon=None:
import threading
import time
def thread_loop():
while True:
print("!");
time.sleep(.5)
if __name__ == '__main__':
bkgnd = threading.Thread(target=thread_loop, daemon=True)
bkgnd.start()
print("exit main")
|
In Python code below, how can I immediately exit the code?
|
I have been trying below this two days, but cannot make it work.
I have tried
except KeyboardInterrupt:
sys.exit()
exit()
control+C
, and so on.
I have tried the code, but it terminates only after 30 seconds or 1 minute. It seems like "listener" in the code makes the code complicated.
I need to make the code terminate immediately when I press ESC. "Terminate" here means stop the code from running or close the entire terminal. Either way is fine, but it needs to work "immediately".
I am using Windows10. It does not need to be compatible with MAC os.
import pydirectinput
import datetime
import time
import threading
from pynput.mouse import Controller, Button
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="`")
clicking = False
mouse = Controller()
def clicker():
global fishpause
global a_press
global d_press
global maxtime
duration = 0
while True and duration <= maxtime:
qtime = datetime.datetime.utcnow()
if qtime.hour == 11 and qtime.minute == 30:
print("Quiting by using an error...")
pydirectinput.keydown('alt')
else:
if clicking:
mouse.press(Button.right)
#print("Button pressed")
goleft(fishpause, a_press)
duration += 1
print(f"Duration is: {duration}")
time.sleep(0.5)
time.sleep(0.5)
mouse.release(Button.right)
def toggle_event(key):
if key == TOGGLE_KEY:
global clicking
clicking = not clicking
print("Clicking changed")
def goleft(fishpause, a_press):
pydirectinput.press('a', presses=1, interval=a_press)
print("Moving left")
pydirectinput.PAUSE = fishpause
print(f"PAUSING: {fishpause}")
maxtime = 4500
fishpause = 9.0
a_press = 0.1
time.sleep(1)
print("Starting")
pydirectinput.press('esc', presses=1, interval=0.1)
click_thread = threading.Thread(target=clicker)
click_thread.start()
time.sleep(3)
with Listener(on_press=toggle_event) as listener:
listener.join()
|
[
"The program won't exit while the click_thread is still running.\nIf the clicker knows that it's supposed to exit it can break the loop and return. Alternatively, if you mark the thread as a daemon:\nclick_thread = threading.Thread(target=clicker, daemon=True)\n\nthen it will exit when the main program exits.\nYou can test this with the tiny program below. Try with daemon=True and with daemon=None:\nimport threading\nimport time\n\ndef thread_loop():\n while True:\n print(\"!\");\n time.sleep(.5)\n\nif __name__ == '__main__':\n bkgnd = threading.Thread(target=thread_loop, daemon=True)\n bkgnd.start()\n print(\"exit main\")\n\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074511971_python.txt
|
Q:
Is it possible somehow without refreshing the pages on Django to send a request via SSH to a virtual machine running Ubuntu?
Good afternoon, I have a frequently asked question, for example,
<button>Check</button>
Is it possible somehow without refreshing the page to send a request via SSH to a virtual machine running Ubuntu?
For example:
The csgo server is on a permanent machine, it has possible options:
IP: 192.168.44.122/94.32.143.84
PORT for SSH: 44
USER NAME: test
PASSWORD: test
Django is on local machine 127.0.0.1:8000 or localhost:8000.
The csgo server is started with "./csgoserver start". Is it possible somehow to send a request with "./csgoserver start" to the local machine, on the click of a button on the page, to start the server?
I searched for information and did not find it. With the help of ajax, if I understand correctly, it is possible to send a request only if there are servers on the same machine, right? I would be grateful for the answer where should I look, what to study, so that I can implement this idea.
One guy suggested that you can look towards REST, but I can't figure out how to implement what I need through REST.
A:
So you want to execute a script/program on a machine (the virtual machine) from another (here your local machine).
Yes SSH is one way you can do that. Try ssh -p 44 test@192.168.44.122 "csgoserver start" (side note: I'm assuming here that the . in ./csgoserver start is the user's home directory. . means "current directory"... that's another topic, but make sure you understand relative vs. absolute paths in unix-like systems)
This can be done in Python from your Django view, which should receive a request (an ajax request is fine if you don't want the page to refresh) from the button click (How can I send an Ajax Request on button click from a form with 2 buttons?). This answer should help you with the details of using SSH in python: Perform commands over ssh with Python
Keep security in mind before deploying this publicly though (i.e read the Django documentation on authentication, CSRF tokens etc...)
|
Is it possible somehow without refreshing the pages on Django to send a request via SSH to a virtual machine running Ubuntu?
|
Good afternoon, I have a frequently asked question, for example,
<button>Check</button>
Is it possible somehow without refreshing the page to send a request via SSH to a virtual machine running Ubuntu?
For example:
The csgo server is on a permanent machine, it has possible options:
IP: 192.168.44.122/94.32.143.84
PORT for SSH: 44
USER NAME: test
PASSWORD: test
Django is on local machine 127.0.0.1:8000 or localhost:8000.
The csgo server is started with "./csgoserver start". Is it possible somehow to send a request with "./csgoserver start" to the local machine, on the click of a button on the page, to start the server?
I searched for information and did not find it. With the help of ajax, if I understand correctly, it is possible to send a request only if there are servers on the same machine, right? I would be grateful for the answer where should I look, what to study, so that I can implement this idea.
One guy suggested that you can look towards REST, but I can't figure out how to implement what I need through REST.
|
[
"So you want to execute a script/program on a machine (the virtual machine) from another (here your local machine).\n\nYes SSH is one way you can do that. Try ssh -p 44 test@192.168.44.122 \"csgoserver start\" (side note: I'm assuming here that the . in ./csgoserver start is the user's home directory. . means \"current directory\"... that's another topic, but make sure you understand relative vs. absolute paths in unix-like systems)\nThis can be done in Python from your Django view, which should receive a request (an ajax request is fine if you don't want the page to refresh) from the button click (How can I send an Ajax Request on button click from a form with 2 buttons?). This answer should help you with the details of using SSH in python: Perform commands over ssh with Python\n\nKeep security in mind before deploying this publicly though (i.e read the Django documentation on authentication, CSRF tokens etc...)\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python",
"ssh"
] |
stackoverflow_0074513068_django_python_ssh.txt
|
Q:
Python Error: 'float' object has no attribute 'replace'
I am an R User that is trying to learn more about Python.
I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser
I was able to try an example over here:
from ez_address_parser import AddressParser
ap = AddressParser()
result = ap.parse("290 Bremner Blvd, Toronto, ON M5V 3L9")
print(results)
[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')]
I have the following file that I imported:
df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')
name address
1 name1 290 Bremner Blvd, Toronto, ON M5V 3L9
2 name2 291 Bremner Blvd, Toronto, ON M5V 3L9
3 name3 292 Bremner Blvd, Toronto, ON M5V 3L9
I then applied the above function and export the file and everything works:
df['Address_Parse'] = df['ADDRESS'].apply(ap.parse)
df = pd.DataFrame(df)
df.to_csv(r'C:/Users/me/OneDrive/Documents/python_file.csv', index=False, header=True)
Problem: I now have another file (similar format) - but this time, I am getting an error:
df1 = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file1.csv', encoding='latin-1')
df1['Address_Parse'] = df1['ADDRESS'].apply(ap.parse)
AttributeError: 'float' object has no attribute 'replace'
I am confused as to why the same code will not work for this file. As I am still learning Python, I am not sure where to begin to debug this problem. My guesses are that perhaps there are special characters in the second file, formatting issues or incorrect variable types that are preventing this ap.parse function from working, but I am still not sure.
Can someone please show me what to do?
Thank you!
A:
Looking at the code from the library, we have this method for parse in the AddressParser class, and then this function for tokenize that is called by parse
# method of AddressParser
def parse(self, address):
if not self.crf:
raise RuntimeError("Model is not loaded")
tokens = tokenize(address)
labels = self.crf.predict([transform(address)])[0]
return list(zip(tokens, labels))
def tokenize(s):
s = s.replace("#", " # ")
return [token for token in split(fr"[{puncts}\s]+", s) if token]
We can see here that tokenize calls replace, and so that is likely where your error is coming from. tokenize is probably expecting a str here (not a float), and that s.replace() is almost certainly for a string replacement.
So, your column likely has floats in it when it expects strings. The tokenize function should probably handle that better, but now it is up to you.
You should be able to resolve this by forcing your Address column to be strings (pandas will call it 'object').
df1['string_address'] = df1['ADDRESS'].astype(str)
df1['Address_Parse'] = df1['string_address'].apply(ap.parse)
A:
You can try read the csv file all in string by adding the dtype=str
df1 = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file1.csv', encoding='latin-1', dtype=str)
|
Python Error: 'float' object has no attribute 'replace'
|
I am an R User that is trying to learn more about Python.
I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser
I was able to try an example over here:
from ez_address_parser import AddressParser
ap = AddressParser()
result = ap.parse("290 Bremner Blvd, Toronto, ON M5V 3L9")
print(results)
[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')]
I have the following file that I imported:
df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')
name address
1 name1 290 Bremner Blvd, Toronto, ON M5V 3L9
2 name2 291 Bremner Blvd, Toronto, ON M5V 3L9
3 name3 292 Bremner Blvd, Toronto, ON M5V 3L9
I then applied the above function and export the file and everything works:
df['Address_Parse'] = df['ADDRESS'].apply(ap.parse)
df = pd.DataFrame(df)
df.to_csv(r'C:/Users/me/OneDrive/Documents/python_file.csv', index=False, header=True)
Problem: I now have another file (similar format) - but this time, I am getting an error:
df1 = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file1.csv', encoding='latin-1')
df1['Address_Parse'] = df1['ADDRESS'].apply(ap.parse)
AttributeError: 'float' object has no attribute 'replace'
I am confused as to why the same code will not work for this file. As I am still learning Python, I am not sure where to begin to debug this problem. My guesses are that perhaps there are special characters in the second file, formatting issues or incorrect variable types that are preventing this ap.parse function from working, but I am still not sure.
Can someone please show me what to do?
Thank you!
|
[
"Looking at the code from the library, we have this method for parse in the AddressParser class, and then this function for tokenize that is called by parse\n# method of AddressParser\ndef parse(self, address):\n if not self.crf:\n raise RuntimeError(\"Model is not loaded\")\n\n tokens = tokenize(address)\n labels = self.crf.predict([transform(address)])[0]\n return list(zip(tokens, labels))\n\ndef tokenize(s):\n s = s.replace(\"#\", \" # \")\n return [token for token in split(fr\"[{puncts}\\s]+\", s) if token]\n\nWe can see here that tokenize calls replace, and so that is likely where your error is coming from. tokenize is probably expecting a str here (not a float), and that s.replace() is almost certainly for a string replacement.\nSo, your column likely has floats in it when it expects strings. The tokenize function should probably handle that better, but now it is up to you.\nYou should be able to resolve this by forcing your Address column to be strings (pandas will call it 'object').\ndf1['string_address'] = df1['ADDRESS'].astype(str)\ndf1['Address_Parse'] = df1['string_address'].apply(ap.parse)\n\n",
"You can try read the csv file all in string by adding the dtype=str\ndf1 = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file1.csv', encoding='latin-1', dtype=str)\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074513701_python.txt
|
Q:
Run specific function for exactly 2 hours
There is a function which is needed to run for 2 hours, Interrupting it manually after 2 hours is not desired in this case. What is the best practice to implement such a task?
def fib():
sequence = [0,1]
while True:
sequence.append(sequence[-1]+sequence[-2])
return sequence
I know it is possible to write such program using time library, but I'm curious if there is another way to do it in Python or not.
import time
def fib():
sequence = [0,1]
tic = time.time()
while True:
sequence.append(sequence[-1]+sequence[-2])
toc = time.time()
if toc-tic> 2*60*60: # reaching two hours
break
return sequence
A:
You can clean up the poll a bit by
import time
def fib():
sequence = [0,1]
end = time.time() + 2*60*60
while time.time() < end:
sequence.append(sequence[-1]+sequence[-2])
return sequence
This adds the cost of time.time() on each loop, which can be significant - especially in this case. You could have some counter where you only call time() once every, say, 100 rounds of the loop.
Another option is to start a background thread the sleeps and then sets a varible to True when done. Wrap that in a class to make it look fancy and you'd have
import threading
import time
class TimeoutIndicator(threading.Thread):
def __init__(self, timeout):
self.timeout = timeout
self.done = False
super().__init__(name="timeout_indicator", daemon=True)
self.start()
def run(self):
time.sleep(self.timeout)
self.done = True
def __bool__(self):
if self.done:
self.join()
return self.done
def fib(stop_now):
sequence = [0,1]
while not stop_now:
sequence.append(sequence[-1]+sequence[-2])
return sequence
fib(TimeoutIndicator(2*60*60))
|
Run specific function for exactly 2 hours
|
There is a function which is needed to run for 2 hours, Interrupting it manually after 2 hours is not desired in this case. What is the best practice to implement such a task?
def fib():
sequence = [0,1]
while True:
sequence.append(sequence[-1]+sequence[-2])
return sequence
I know it is possible to write such program using time library, but I'm curious if there is another way to do it in Python or not.
import time
def fib():
sequence = [0,1]
tic = time.time()
while True:
sequence.append(sequence[-1]+sequence[-2])
toc = time.time()
if toc-tic> 2*60*60: # reaching two hours
break
return sequence
|
[
"You can clean up the poll a bit by\nimport time\n\ndef fib():\n sequence = [0,1]\n end = time.time() + 2*60*60\n while time.time() < end:\n sequence.append(sequence[-1]+sequence[-2])\n return sequence\n\nThis adds the cost of time.time() on each loop, which can be significant - especially in this case. You could have some counter where you only call time() once every, say, 100 rounds of the loop.\nAnother option is to start a background thread the sleeps and then sets a varible to True when done. Wrap that in a class to make it look fancy and you'd have\nimport threading\nimport time\n\nclass TimeoutIndicator(threading.Thread):\n\n def __init__(self, timeout):\n self.timeout = timeout\n self.done = False\n super().__init__(name=\"timeout_indicator\", daemon=True)\n self.start()\n\n def run(self):\n time.sleep(self.timeout)\n self.done = True\n\n def __bool__(self):\n if self.done:\n self.join()\n return self.done\n\ndef fib(stop_now):\n sequence = [0,1]\n while not stop_now:\n sequence.append(sequence[-1]+sequence[-2])\n return sequence\n\nfib(TimeoutIndicator(2*60*60))\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x",
"time"
] |
stackoverflow_0074513792_python_python_3.x_time.txt
|
Q:
Flask-SQLAlchemy raising: AttributeError: module 'psycopg2' has no attribute 'paramstyle'
I'm running a generic (because I don't know enough to do anything beyond the basics) Flask-SQLAlchemy 3.0.2 setup on Python 3.10.
Not sure what happened, but at some point it started throwing this error every time I tried to query the db:
AttributeError: module 'psycopg2' has no attribute 'paramstyle'
I'm doing package management through poetry and SQLAlchemy 1.4.44 really wanted to use psycopg2 2.7, which I guess pre-dates paramstyle.
A:
I uninstalled psycopg2 (and removed its requirement from the poetry lock file), and installed psycopg2-binary 2.9.5 manually. Now it works.
|
Flask-SQLAlchemy raising: AttributeError: module 'psycopg2' has no attribute 'paramstyle'
|
I'm running a generic (because I don't know enough to do anything beyond the basics) Flask-SQLAlchemy 3.0.2 setup on Python 3.10.
Not sure what happened, but at some point it started throwing this error every time I tried to query the db:
AttributeError: module 'psycopg2' has no attribute 'paramstyle'
I'm doing package management through poetry and SQLAlchemy 1.4.44 really wanted to use psycopg2 2.7, which I guess pre-dates paramstyle.
|
[
"I uninstalled psycopg2 (and removed its requirement from the poetry lock file), and installed psycopg2-binary 2.9.5 manually. Now it works.\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"flask_sqlalchemy",
"psycopg2",
"python",
"sqlalchemy"
] |
stackoverflow_0074513831_flask_flask_sqlalchemy_psycopg2_python_sqlalchemy.txt
|
Q:
How to parse and get known individual elements, not characters, from a smiles string in Python
In Python, I am trying to break a SMILES string into a list of valid SMILES elements. I wanted to ask if RDKit already has a method to do this kind of deconstruction of the SMILES string? I DO have created a list of valid SMILES elements separately.
For example, I want to convert this string CC(Cl)c1ccn(C)c1 into this list ['C', 'C', '(', 'Cl', ')', 'c', '1', 'c', 'c', 'n', '(', 'C', ')', 'c', '1']. Unfortunately, this is not as straightforward as simply getting the characters from the string: occurrence of a lower case alphabet could either mean that it is an element denoted by more than one character (like Cl for Chlorine) or indicate that the element is part of an aromatic ring (like n for Nitrogen). Examples of other valid SMILE elements that are not a single character are Mg, Ca, Uub, %13, +2, @@, etc.
Before I write a parsing algorithm to accomplish this, which I think would be less than ideal because I might miss a SMILES rule here and there (I am neither an expert at SMILES, nor at parsing). For example, occurrence of two digit numbers are another complication that I know I will have to deal with when creating my own parsing algorithm.
A:
This can be accomplished by extending the following function (from Molecular Transformer):
import re
def smi_tokenizer(smi):
"""
Tokenize a SMILES molecule or reaction
"""
pattern = "(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
regex = re.compile(pattern)
tokens = [token for token in regex.findall(smi)]
assert smi == ''.join(tokens)
return tokens
smi_tokenizer("CC(Cl)c1ccn(C)c1")
This will output :
['C', 'C', '(', 'Cl', ')', 'c', '1', 'c', 'c', 'n', '(', 'C', ')', 'c', '1']
Reference :
You might want to take a look at the paper for Molecular Transformer by Schwaller et.al. and the code.
A:
Here's an rdkit solution:
import rdkit
from rdkit import Chem
def get_atom_chars(smi):
atoms_chars=[]
mol = Chem.MolFromSmiles(smi,sanitize=False)
for a in mol.GetAtoms():
atom=Chem.RWMol()
atom.AddAtom(a)
atoms_chars.append(Chem.MolToSmiles(atom))
return atoms_chars
get_atom_chars("CC(Cl)c1ccn(C)c1")
this outputs
['C', 'C', 'Cl', 'c', 'c', 'c', 'n', 'C', 'c']
It works as follows: the SMILES gets parsed without sanitization (otherwise it wold turn C1=CC=CC=C1 into c1ccccc1 etc). then, it loops through every atom, creates an RWmol instance, adds that one atom to it, and then convert to single atom SMILES,repeat for every atom.
Note that the numbers "1" and "1" are not in the list, because in the SMILES string these correspond to ring opening/closures, not atoms
|
How to parse and get known individual elements, not characters, from a smiles string in Python
|
In Python, I am trying to break a SMILES string into a list of valid SMILES elements. I wanted to ask if RDKit already has a method to do this kind of deconstruction of the SMILES string? I DO have created a list of valid SMILES elements separately.
For example, I want to convert this string CC(Cl)c1ccn(C)c1 into this list ['C', 'C', '(', 'Cl', ')', 'c', '1', 'c', 'c', 'n', '(', 'C', ')', 'c', '1']. Unfortunately, this is not as straightforward as simply getting the characters from the string: occurrence of a lower case alphabet could either mean that it is an element denoted by more than one character (like Cl for Chlorine) or indicate that the element is part of an aromatic ring (like n for Nitrogen). Examples of other valid SMILE elements that are not a single character are Mg, Ca, Uub, %13, +2, @@, etc.
Before I write a parsing algorithm to accomplish this, which I think would be less than ideal because I might miss a SMILES rule here and there (I am neither an expert at SMILES, nor at parsing). For example, occurrence of two digit numbers are another complication that I know I will have to deal with when creating my own parsing algorithm.
|
[
"This can be accomplished by extending the following function (from Molecular Transformer):\nimport re\n\ndef smi_tokenizer(smi):\n \"\"\"\n Tokenize a SMILES molecule or reaction\n \"\"\"\n pattern = \"(\\[[^\\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\\(|\\)|\\.|=|#|-|\\+|\\\\\\\\|\\/|:|~|@|\\?|>|\\*|\\$|\\%[0-9]{2}|[0-9])\"\n regex = re.compile(pattern)\n tokens = [token for token in regex.findall(smi)]\n assert smi == ''.join(tokens)\n return tokens\n\nsmi_tokenizer(\"CC(Cl)c1ccn(C)c1\")\n\nThis will output :\n['C', 'C', '(', 'Cl', ')', 'c', '1', 'c', 'c', 'n', '(', 'C', ')', 'c', '1']\n\nReference : \nYou might want to take a look at the paper for Molecular Transformer by Schwaller et.al. and the code.\n",
"Here's an rdkit solution:\nimport rdkit\nfrom rdkit import Chem\ndef get_atom_chars(smi):\n atoms_chars=[]\n mol = Chem.MolFromSmiles(smi,sanitize=False)\n for a in mol.GetAtoms():\n atom=Chem.RWMol()\n atom.AddAtom(a)\n atoms_chars.append(Chem.MolToSmiles(atom))\n return atoms_chars\n \n \nget_atom_chars(\"CC(Cl)c1ccn(C)c1\")\n\nthis outputs\n['C', 'C', 'Cl', 'c', 'c', 'c', 'n', 'C', 'c']\nIt works as follows: the SMILES gets parsed without sanitization (otherwise it wold turn C1=CC=CC=C1 into c1ccccc1 etc). then, it loops through every atom, creates an RWmol instance, adds that one atom to it, and then convert to single atom SMILES,repeat for every atom.\nNote that the numbers \"1\" and \"1\" are not in the list, because in the SMILES string these correspond to ring opening/closures, not atoms\n"
] |
[
1,
0
] |
[] |
[] |
[
"cheminformatics",
"parsing",
"python",
"rdkit"
] |
stackoverflow_0074205361_cheminformatics_parsing_python_rdkit.txt
|
Q:
Python. flask, wfastCGI, and IIS - Very short url length limit (or something)
I'm using Python 3.10.4 and Flask on a Windows 2016 Server with IIS and wfastCGI.
I stripped down my Python script to bare minimum for testing:
from flask import Flask, request, abort, render_template
from functools import wraps
app = Flask(__name__, static_url_path='/dwapi')
app.config["APPLICATION_ROOT"] = "/dwapi"
@app.route("/dwapi")
def dwapi_index():
return "Invalid URL Path"
@app.route("/dwapi/myroute/<startdate>/<propertyid>")
def get_data(startdate,propertyid):
return "xxx"
if __name__ == "__main__":
app.run()
When I use the URL:
http://myservdwiis/dwapi/myroute/2021-8-01/80712,80804
it works - the browser shows "xxx"
I then use this longer URL:
http://myservdwiis/dwapi/myroute/2021-8-01/80712,80804,53009,80602,80519,80517,80802,38025,80705,80514,80515,80516,80807,38026,80808,20001,38400,51022,51023,80522,38027,32010,80527,54130,54131,38456,38017,80520,80521,80528,80805,38018,80523,80524,08030,56120,56121,56122,56123,56124,98145,98142,98143,981
It returns:
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid
If I remove ONE character from the above URL, it works.
http://myservdwiis/dwapi/myroute/2021-8-01/80712,80804,53009,80602,80519,80517,80802,38025,80705,80514,80515,80516,80807,38026,80808,20001,38400,51022,51023,80522,38027,32010,80527,54130,54131,38456,38017,80520,80521,80528,80805,38018,80523,80524,08030,56120,56121,56122,56123,56124,98145,98142,98143,98
This returns "xxx" as it should.
It doesn't look like this should be too long. There are no limits set (that I can see) in IIS - it has the default 2048 limit. But the above is only 306 characters, counting the hostname and protocol.
What could be limiting this, or is it due to something else?
When I run this locally on my Windows 10 system, not through IIS or wfastCGI, it does not have this issue.
.
A:
In addition to iis settings, you can also set registry keys to tell HTTP.sys to allow longer URLs. By default, HTTP.sys permits 255 segments at a maximum length of 260 characters each. That 260 character limit was the cause of this issue.
You can change that setting in the registry. once you reboot, the url will work.
Registry:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters]
"UrlSegmentMaxLength"=dword:00000400
This will effectively set the segment length to 1024.
More information you can refer to this link: Response 400 (Bad Request) on Long Url.
|
Python. flask, wfastCGI, and IIS - Very short url length limit (or something)
|
I'm using Python 3.10.4 and Flask on a Windows 2016 Server with IIS and wfastCGI.
I stripped down my Python script to bare minimum for testing:
from flask import Flask, request, abort, render_template
from functools import wraps
app = Flask(__name__, static_url_path='/dwapi')
app.config["APPLICATION_ROOT"] = "/dwapi"
@app.route("/dwapi")
def dwapi_index():
return "Invalid URL Path"
@app.route("/dwapi/myroute/<startdate>/<propertyid>")
def get_data(startdate,propertyid):
return "xxx"
if __name__ == "__main__":
app.run()
When I use the URL:
http://myservdwiis/dwapi/myroute/2021-8-01/80712,80804
it works - the browser shows "xxx"
I then use this longer URL:
http://myservdwiis/dwapi/myroute/2021-8-01/80712,80804,53009,80602,80519,80517,80802,38025,80705,80514,80515,80516,80807,38026,80808,20001,38400,51022,51023,80522,38027,32010,80527,54130,54131,38456,38017,80520,80521,80528,80805,38018,80523,80524,08030,56120,56121,56122,56123,56124,98145,98142,98143,981
It returns:
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid
If I remove ONE character from the above URL, it works.
http://myservdwiis/dwapi/myroute/2021-8-01/80712,80804,53009,80602,80519,80517,80802,38025,80705,80514,80515,80516,80807,38026,80808,20001,38400,51022,51023,80522,38027,32010,80527,54130,54131,38456,38017,80520,80521,80528,80805,38018,80523,80524,08030,56120,56121,56122,56123,56124,98145,98142,98143,98
This returns "xxx" as it should.
It doesn't look like this should be too long. There are no limits set (that I can see) in IIS - it has the default 2048 limit. But the above is only 306 characters, counting the hostname and protocol.
What could be limiting this, or is it due to something else?
When I run this locally on my Windows 10 system, not through IIS or wfastCGI, it does not have this issue.
.
|
[
"In addition to iis settings, you can also set registry keys to tell HTTP.sys to allow longer URLs. By default, HTTP.sys permits 255 segments at a maximum length of 260 characters each. That 260 character limit was the cause of this issue.\nYou can change that setting in the registry. once you reboot, the url will work.\nRegistry:\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\HTTP\\Parameters]\n\"UrlSegmentMaxLength\"=dword:00000400\n\nThis will effectively set the segment length to 1024.\nMore information you can refer to this link: Response 400 (Bad Request) on Long Url.\n"
] |
[
0
] |
[] |
[] |
[
"iis",
"python",
"wfastcgi"
] |
stackoverflow_0074483997_iis_python_wfastcgi.txt
|
Q:
Own dataset ValueError: Tensor conversion requested dtype string for Tensor with dtype float32
I'm trying to use my own dataset to train a GAN network. I'm having issues with loading my own dataset in .jpg format. I have existing jpg datasets that work, I can't see a difference in the jpg encoding between the working and not working datasets.
The photos are converted using a windows machine and renamed to 001.jpg 002.jpg etc. For training I'm using a linux machine.
The python program I'm using the following code to load and convert images to tensors:
def _image_batch(image_paths,
batch_size,
load_size=286,
crop_size=256,
channels=3,
prefetch_batch=2,
drop_remainder=True,
num_threads=16,
shuffle=True,
buffer_size=4096,
repeat=-1):
def _parse_func(path):
img = tf.read_file(path)
img = tf.image.decode_jpeg(img, channels=channels)
img = tf.image.random_flip_left_right(img)
img = tf.image.resize_images(img, [load_size, load_size])
img = (img - tf.reduce_min(img)) / (tf.reduce_max(img) - tf.reduce_min(img))
img = tf.random_crop(img, [crop_size, crop_size, channels])
img = img * 2 - 1
return img
The full error is:
Traceback (most recent call last):
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 510, in _apply_op_helper
preferred_dtype=default_dtype)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1040, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 883, in _TensorTensorConversionFunction
(dtype.name, t.dtype.name, str(t)))
ValueError: Tensor conversion requested dtype string for Tensor with dtype float32: 'Tensor("arg0:0", shape=(), dtype=float32)'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "train.py", line 112, in <module>
a_test_pool = data.ImageData(sess, a_test_img_paths, batch_size, load_size=load_size, crop_size=crop_size)
File "/mnt/storage/scratch/ag17634/CycleGAN-Tensorflow-Pytorch/data.py", line 35, in __init__
repeat)
File "/mnt/storage/scratch/ag17634/CycleGAN-Tensorflow-Pytorch/data.py", line 68, in _image_batch
dataset = dataset.map(_parse_func, num_parallel_calls=num_threads)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 840, in map
return ParallelMapDataset(self, map_func, num_parallel_calls)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1857, in __init__
super(ParallelMapDataset, self).__init__(input_dataset, map_func)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1826, in __init__
self._map_func.add_to_graph(ops.get_default_graph())
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/function.py", line 488, in add_to_graph
self._create_definition_if_needed()
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/function.py", line 321, in _create_definition_if_needed
self._create_definition_if_needed_impl()
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/function.py", line 338, in _create_definition_if_needed_impl
outputs = self._func(*inputs)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1791, in tf_map_func
ret = map_func(nested_args)
File "/mnt/storage/scratch/ag17634/CycleGAN-Tensorflow-Pytorch/data.py", line 57, in _parse_func
img = tf.read_file(path)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/ops/gen_io_ops.py", line 527, in read_file
"ReadFile", filename=filename, name=name)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 533, in _apply_op_helper
(prefix, dtypes.as_dtype(input_arg.type).name))
TypeError: Input 'filename' of 'ReadFile' Op has type float32 that does not match expected type of string.
A:
I have got same error with you.
I solve it: change the path name correctly.
I guess in your case, you should check you "path" name in codes
img = tf.read_file(path)
A:
This sounds like a converting issue.
I think you may have to call
str(input)
on the input you are passing as filename.
A:
Maybe your question is missing the line where you call your function, _image_batch but in any case I encountered your error too when doing the writing.
Originally I had
image_path = "original.jpg"
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img)
img_resized = tf.image.resize(img, [224, 224])
resized_filename = "resized.jpg"
tf.io.write_file(str(resized_filename), img_resized)
which caused
ValueError: Tensor conversion requested dtype string for Tensor with dtype float32
Change that ended up working for me was
image_path = "original.jpg"
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img)
img_resized = tf.image.resize(img, [224, 224])
img_encoded = tf.image.encode_jpeg(tf.cast(img_resized, tf.uint8))
resized_filename = "resized.jpg"
tf.io.write_file(resized_filename, img_encoded)
|
Own dataset ValueError: Tensor conversion requested dtype string for Tensor with dtype float32
|
I'm trying to use my own dataset to train a GAN network. I'm having issues with loading my own dataset in .jpg format. I have existing jpg datasets that work, I can't see a difference in the jpg encoding between the working and not working datasets.
The photos are converted using a windows machine and renamed to 001.jpg 002.jpg etc. For training I'm using a linux machine.
The python program I'm using the following code to load and convert images to tensors:
def _image_batch(image_paths,
batch_size,
load_size=286,
crop_size=256,
channels=3,
prefetch_batch=2,
drop_remainder=True,
num_threads=16,
shuffle=True,
buffer_size=4096,
repeat=-1):
def _parse_func(path):
img = tf.read_file(path)
img = tf.image.decode_jpeg(img, channels=channels)
img = tf.image.random_flip_left_right(img)
img = tf.image.resize_images(img, [load_size, load_size])
img = (img - tf.reduce_min(img)) / (tf.reduce_max(img) - tf.reduce_min(img))
img = tf.random_crop(img, [crop_size, crop_size, channels])
img = img * 2 - 1
return img
The full error is:
Traceback (most recent call last):
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 510, in _apply_op_helper
preferred_dtype=default_dtype)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1040, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 883, in _TensorTensorConversionFunction
(dtype.name, t.dtype.name, str(t)))
ValueError: Tensor conversion requested dtype string for Tensor with dtype float32: 'Tensor("arg0:0", shape=(), dtype=float32)'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "train.py", line 112, in <module>
a_test_pool = data.ImageData(sess, a_test_img_paths, batch_size, load_size=load_size, crop_size=crop_size)
File "/mnt/storage/scratch/ag17634/CycleGAN-Tensorflow-Pytorch/data.py", line 35, in __init__
repeat)
File "/mnt/storage/scratch/ag17634/CycleGAN-Tensorflow-Pytorch/data.py", line 68, in _image_batch
dataset = dataset.map(_parse_func, num_parallel_calls=num_threads)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 840, in map
return ParallelMapDataset(self, map_func, num_parallel_calls)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1857, in __init__
super(ParallelMapDataset, self).__init__(input_dataset, map_func)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1826, in __init__
self._map_func.add_to_graph(ops.get_default_graph())
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/function.py", line 488, in add_to_graph
self._create_definition_if_needed()
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/function.py", line 321, in _create_definition_if_needed
self._create_definition_if_needed_impl()
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/function.py", line 338, in _create_definition_if_needed_impl
outputs = self._func(*inputs)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1791, in tf_map_func
ret = map_func(nested_args)
File "/mnt/storage/scratch/ag17634/CycleGAN-Tensorflow-Pytorch/data.py", line 57, in _parse_func
img = tf.read_file(path)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/ops/gen_io_ops.py", line 527, in read_file
"ReadFile", filename=filename, name=name)
File "/mnt/storage/software/languages/anaconda/Anaconda3-5.2.0-tflow-1.7/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 533, in _apply_op_helper
(prefix, dtypes.as_dtype(input_arg.type).name))
TypeError: Input 'filename' of 'ReadFile' Op has type float32 that does not match expected type of string.
|
[
"I have got same error with you.\nI solve it: change the path name correctly.\nI guess in your case, you should check you \"path\" name in codes\nimg = tf.read_file(path)\n\n",
"This sounds like a converting issue.\nI think you may have to call\n str(input)\non the input you are passing as filename. \n",
"Maybe your question is missing the line where you call your function, _image_batch but in any case I encountered your error too when doing the writing.\nOriginally I had\nimage_path = \"original.jpg\"\nimg = tf.io.read_file(image_path)\nimg = tf.image.decode_jpeg(img)\nimg_resized = tf.image.resize(img, [224, 224])\nresized_filename = \"resized.jpg\"\ntf.io.write_file(str(resized_filename), img_resized)\n\nwhich caused\nValueError: Tensor conversion requested dtype string for Tensor with dtype float32\n\nChange that ended up working for me was\nimage_path = \"original.jpg\"\nimg = tf.io.read_file(image_path)\nimg = tf.image.decode_jpeg(img)\nimg_resized = tf.image.resize(img, [224, 224])\n\nimg_encoded = tf.image.encode_jpeg(tf.cast(img_resized, tf.uint8))\nresized_filename = \"resized.jpg\"\ntf.io.write_file(resized_filename, img_encoded)\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"image",
"jpeg",
"python",
"tensorflow",
"type_conversion"
] |
stackoverflow_0051139028_image_jpeg_python_tensorflow_type_conversion.txt
|
Q:
Genrate grid information file from MODIS HDFEOS data
Is there a way to generate grid information (lat-lon) from the MODIS MCD19A2 files in python?.
The file is downloaded from
Link to the data file
.In MATLAB it can be done using the following block code
import matlab.io.hdf4.*
import matlab.io.hdfeos.*
% Open the HDF-EOS2 Grid file.
FILE_NAME='MCD19A2.A2010010.h25v06.006.2018047103710.hdf';
file_id = gd.open(FILE_NAME, 'rdonly');
% Read data from a data field.
GRID_NAME='grid1km';
grid_id = gd.attach(file_id, GRID_NAME);
DATAFIELD_NAME='Optical_Depth_055';
[data, lat, lon] = gd.readField(grid_id, DATAFIELD_NAME, [], [], []);
In short, I am looking for a pyhdf/python equivalent for gd.readField of MATLAB package
A:
HDF-EOS Tools and Information Center Help was so nice to provide a script to deal with grid definition. This can be found here. In case the link is not working, here is the code:
"""
Copyright (C) 2014-2019 The HDF Group
Copyright (C) 2014 John Evans
This example code illustrates how to access and visualize an LP DAAC MCD19A2
v6 HDF-EOS2 Sinusoidal Grid file in Python.
If you have any questions, suggestions, or comments on this example, please use
the HDF-EOS Forum (http://hdfeos.org/forums). If you would like to see an
example of any other NASA HDF/HDF-EOS data product that is not listed in the
HDF-EOS Comprehensive Examples page (http://hdfeos.org/zoo), feel free to
contact us at eoshelp@hdfgroup.org or post it at the HDF-EOS Forum
(http://hdfeos.org/forums).
Usage: save this script and run
$python MCD19A2.A2010010.h25v06.006.2018047103710.hdf.py
Tested under: Python 3.7.3 :: Anaconda custom (64-bit)
Last updated: 2019-09-20
"""
import os
import re
import pyproj
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from pyhdf.SD import SD, SDC
from mpl_toolkits.basemap import Basemap
FILE_NAME = 'MCD19A2.A2010010.h25v06.006.2018047103710.hdf'
DATAFIELD_NAME = 'Optical_Depth_055'
hdf = SD(FILE_NAME, SDC.READ)
# Read dataset.
data3D = hdf.select(DATAFIELD_NAME)
data = data3D[1,:,:].astype(np.double)
# Read attributes.
attrs = data3D.attributes(full=1)
lna=attrs["long_name"]
long_name = lna[0]
vra=attrs["valid_range"]
valid_range = vra[0]
fva=attrs["_FillValue"]
_FillValue = fva[0]
sfa=attrs["scale_factor"]
scale_factor = sfa[0]
ua=attrs["unit"]
units = ua[0]
aoa=attrs["add_offset"]
add_offset = aoa[0]
# Apply the attributes to the data.
invalid = np.logical_or(data < valid_range[0], data > valid_range[1])
invalid = np.logical_or(invalid, data == _FillValue)
data[invalid] = np.nan
data = (data - add_offset) * scale_factor
data = np.ma.masked_array(data, np.isnan(data))
# Construct the grid. The needed information is in a global attribute
# called 'StructMetadata.0'. Use regular expressions to tease out the
# extents of the grid.
fattrs = hdf.attributes(full=1)
ga = fattrs["StructMetadata.0"]
gridmeta = ga[0]
ul_regex = re.compile(r'''UpperLeftPointMtrs=\(
(?P<upper_left_x>[+-]?\d+\.\d+)
,
(?P<upper_left_y>[+-]?\d+\.\d+)
\)''', re.VERBOSE)
match = ul_regex.search(gridmeta)
x0 = np.float(match.group('upper_left_x'))
y0 = np.float(match.group('upper_left_y'))
lr_regex = re.compile(r'''LowerRightMtrs=\(
(?P<lower_right_x>[+-]?\d+\.\d+)
,
(?P<lower_right_y>[+-]?\d+\.\d+)
\)''', re.VERBOSE)
match = lr_regex.search(gridmeta)
x1 = np.float(match.group('lower_right_x'))
y1 = np.float(match.group('lower_right_y'))
nx, ny = data.shape
x = np.linspace(x0, x1, nx)
y = np.linspace(y0, y1, ny)
xv, yv = np.meshgrid(x, y)
sinu = pyproj.Proj("+proj=sinu +R=6371007.181 +nadgrids=@null +wktext")
wgs84 = pyproj.Proj("+init=EPSG:4326")
lon, lat= pyproj.transform(sinu, wgs84, xv, yv)
# There is a wrap-around issue to deal with, as some of the grid extends
# eastward over the international dateline. Adjust the longitude to avoid
# a smearing effect.
lon[lon < 0] += 360
m = Basemap(projection='cyl', resolution='l',
llcrnrlat=np.min(lat), urcrnrlat = np.max(lat),
llcrnrlon=np.min(lon), urcrnrlon = np.max(lon))
m.drawcoastlines(linewidth=0.5)
m.drawparallels(np.arange(np.floor(np.min(lat)), np.ceil(np.max(lat)), 5),
labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(np.floor(np.min(lon)), np.ceil(np.max(lon)), 5),
labels=[0, 0, 0, 1])
# Subset data if you don't see any plot due to limited memory.
# m.pcolormesh(lon[::2,::2], lat[::2,::2], data[::2,::2], latlon=True)
m.pcolormesh(lon, lat, data, latlon=True)
cb = m.colorbar()
cb.set_label(units)
basename = os.path.basename(FILE_NAME)
plt.title('{0}\n{1}'.format(basename, long_name))
fig = plt.gcf()
pngfile = "{0}.py.png".format(basename)
fig.savefig(pngfile)
A:
Thanks for sharing the python file, but there is a problem:
the latitude and longitude read by python and matlab are not always the same.
For example, the dimension of h23v04 read by python starts at 50°N, while the value read by matlab starts at 49.9958°N
|
Genrate grid information file from MODIS HDFEOS data
|
Is there a way to generate grid information (lat-lon) from the MODIS MCD19A2 files in python?.
The file is downloaded from
Link to the data file
.In MATLAB it can be done using the following block code
import matlab.io.hdf4.*
import matlab.io.hdfeos.*
% Open the HDF-EOS2 Grid file.
FILE_NAME='MCD19A2.A2010010.h25v06.006.2018047103710.hdf';
file_id = gd.open(FILE_NAME, 'rdonly');
% Read data from a data field.
GRID_NAME='grid1km';
grid_id = gd.attach(file_id, GRID_NAME);
DATAFIELD_NAME='Optical_Depth_055';
[data, lat, lon] = gd.readField(grid_id, DATAFIELD_NAME, [], [], []);
In short, I am looking for a pyhdf/python equivalent for gd.readField of MATLAB package
|
[
"HDF-EOS Tools and Information Center Help was so nice to provide a script to deal with grid definition. This can be found here. In case the link is not working, here is the code:\n\"\"\"\nCopyright (C) 2014-2019 The HDF Group\nCopyright (C) 2014 John Evans\n\nThis example code illustrates how to access and visualize an LP DAAC MCD19A2\nv6 HDF-EOS2 Sinusoidal Grid file in Python.\n\nIf you have any questions, suggestions, or comments on this example, please use\nthe HDF-EOS Forum (http://hdfeos.org/forums). If you would like to see an\nexample of any other NASA HDF/HDF-EOS data product that is not listed in the\nHDF-EOS Comprehensive Examples page (http://hdfeos.org/zoo), feel free to\ncontact us at eoshelp@hdfgroup.org or post it at the HDF-EOS Forum\n(http://hdfeos.org/forums).\n\nUsage: save this script and run\n\n $python MCD19A2.A2010010.h25v06.006.2018047103710.hdf.py\n\n\nTested under: Python 3.7.3 :: Anaconda custom (64-bit)\nLast updated: 2019-09-20\n\"\"\"\nimport os\nimport re\nimport pyproj\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom pyhdf.SD import SD, SDC\nfrom mpl_toolkits.basemap import Basemap\n\nFILE_NAME = 'MCD19A2.A2010010.h25v06.006.2018047103710.hdf'\nDATAFIELD_NAME = 'Optical_Depth_055'\nhdf = SD(FILE_NAME, SDC.READ)\n\n# Read dataset.\ndata3D = hdf.select(DATAFIELD_NAME)\ndata = data3D[1,:,:].astype(np.double)\n\n# Read attributes.\nattrs = data3D.attributes(full=1)\nlna=attrs[\"long_name\"]\nlong_name = lna[0]\nvra=attrs[\"valid_range\"]\nvalid_range = vra[0]\nfva=attrs[\"_FillValue\"]\n_FillValue = fva[0]\nsfa=attrs[\"scale_factor\"]\nscale_factor = sfa[0] \nua=attrs[\"unit\"]\nunits = ua[0]\naoa=attrs[\"add_offset\"]\nadd_offset = aoa[0]\n\n# Apply the attributes to the data.\ninvalid = np.logical_or(data < valid_range[0], data > valid_range[1])\ninvalid = np.logical_or(invalid, data == _FillValue)\ndata[invalid] = np.nan\ndata = (data - add_offset) * scale_factor\ndata = np.ma.masked_array(data, np.isnan(data))\n\n# Construct the grid. The needed information is in a global attribute\n# called 'StructMetadata.0'. Use regular expressions to tease out the\n# extents of the grid.\nfattrs = hdf.attributes(full=1)\nga = fattrs[\"StructMetadata.0\"]\ngridmeta = ga[0]\nul_regex = re.compile(r'''UpperLeftPointMtrs=\\(\n (?P<upper_left_x>[+-]?\\d+\\.\\d+)\n ,\n (?P<upper_left_y>[+-]?\\d+\\.\\d+)\n \\)''', re.VERBOSE)\n\nmatch = ul_regex.search(gridmeta)\nx0 = np.float(match.group('upper_left_x'))\ny0 = np.float(match.group('upper_left_y'))\n\nlr_regex = re.compile(r'''LowerRightMtrs=\\(\n (?P<lower_right_x>[+-]?\\d+\\.\\d+)\n ,\n (?P<lower_right_y>[+-]?\\d+\\.\\d+)\n \\)''', re.VERBOSE)\nmatch = lr_regex.search(gridmeta)\nx1 = np.float(match.group('lower_right_x'))\ny1 = np.float(match.group('lower_right_y'))\n\nnx, ny = data.shape\nx = np.linspace(x0, x1, nx)\ny = np.linspace(y0, y1, ny)\nxv, yv = np.meshgrid(x, y)\n\nsinu = pyproj.Proj(\"+proj=sinu +R=6371007.181 +nadgrids=@null +wktext\")\nwgs84 = pyproj.Proj(\"+init=EPSG:4326\") \nlon, lat= pyproj.transform(sinu, wgs84, xv, yv)\n\n\n# There is a wrap-around issue to deal with, as some of the grid extends\n# eastward over the international dateline. Adjust the longitude to avoid\n# a smearing effect.\nlon[lon < 0] += 360\n\nm = Basemap(projection='cyl', resolution='l',\n llcrnrlat=np.min(lat), urcrnrlat = np.max(lat),\n llcrnrlon=np.min(lon), urcrnrlon = np.max(lon)) \nm.drawcoastlines(linewidth=0.5)\nm.drawparallels(np.arange(np.floor(np.min(lat)), np.ceil(np.max(lat)), 5),\n labels=[1, 0, 0, 0])\nm.drawmeridians(np.arange(np.floor(np.min(lon)), np.ceil(np.max(lon)), 5),\n labels=[0, 0, 0, 1])\n\n# Subset data if you don't see any plot due to limited memory.\n# m.pcolormesh(lon[::2,::2], lat[::2,::2], data[::2,::2], latlon=True)\nm.pcolormesh(lon, lat, data, latlon=True)\n\n\ncb = m.colorbar()\ncb.set_label(units)\n\nbasename = os.path.basename(FILE_NAME)\nplt.title('{0}\\n{1}'.format(basename, long_name))\nfig = plt.gcf()\npngfile = \"{0}.py.png\".format(basename)\nfig.savefig(pngfile)\n\n",
"Thanks for sharing the python file, but there is a problem:\nthe latitude and longitude read by python and matlab are not always the same.\nFor example, the dimension of h23v04 read by python starts at 50°N, while the value read by matlab starts at 49.9958°N\n"
] |
[
0,
0
] |
[] |
[] |
[
"hdf",
"matlab",
"pyhdf",
"python"
] |
stackoverflow_0057990038_hdf_matlab_pyhdf_python.txt
|
Q:
How can I draw a projectile arc on turtle graphics?
I need help with learning how to draw a arc in turtle graphics. I would prefer a simple set of code that I can easily incorporate into my pre-existing code.
I've tried to make an arc following online instructions but its not projectile, its more like a smiley face arc would be.
A:
This code keeps track of two variables, one called x_velocity, and the other called y_velocity. These variables represent the speed that the projectile is moving in x and y directions respectively. It then loops through a couple times, moving the turtle at those velocities and then applying gravity to the y_velocity.
import turtle
t = turtle.Turtle()
t.speed(3) # 1:slowest, 3:slow, 5:normal, 10:fast, 0:fastest
x_velocity = 4
y_velocity = 20
for i in range(50):
# apply velocity to the turtle, move it
t.goto(t.xcor() + x_velocity, t.ycor() + y_velocity)
# apply gravity to the projectile
y_velocity -= 1
|
How can I draw a projectile arc on turtle graphics?
|
I need help with learning how to draw a arc in turtle graphics. I would prefer a simple set of code that I can easily incorporate into my pre-existing code.
I've tried to make an arc following online instructions but its not projectile, its more like a smiley face arc would be.
|
[
"This code keeps track of two variables, one called x_velocity, and the other called y_velocity. These variables represent the speed that the projectile is moving in x and y directions respectively. It then loops through a couple times, moving the turtle at those velocities and then applying gravity to the y_velocity.\nimport turtle\nt = turtle.Turtle()\nt.speed(3) # 1:slowest, 3:slow, 5:normal, 10:fast, 0:fastest\n\nx_velocity = 4\ny_velocity = 20\n\nfor i in range(50):\n # apply velocity to the turtle, move it\n t.goto(t.xcor() + x_velocity, t.ycor() + y_velocity)\n # apply gravity to the projectile\n y_velocity -= 1\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.9",
"python_turtle",
"turtle_graphics"
] |
stackoverflow_0074513719_python_python_3.9_python_turtle_turtle_graphics.txt
|
Q:
Selenium getting banned from cloudflare
I am using selenium python but when I load my target page it gets banned.
I find if I run this code while trying load page then everything getting fine.
driver.service.stop()
Cloudflare is accept my connection and my target page is loaded success.
But still don't know how to deal with Cloudflare because when I resume selenium in current browser then Cloudflare continue ban me. What should I do? I use proxy to change my ip and anti-detected browser named Gologin already.
my target page keeps loading to infinity
A:
When I run into this problem I usually use a library called "cloudscraper"
Read more about it here: https://github.com/VeNoMouS/cloudscraper
|
Selenium getting banned from cloudflare
|
I am using selenium python but when I load my target page it gets banned.
I find if I run this code while trying load page then everything getting fine.
driver.service.stop()
Cloudflare is accept my connection and my target page is loaded success.
But still don't know how to deal with Cloudflare because when I resume selenium in current browser then Cloudflare continue ban me. What should I do? I use proxy to change my ip and anti-detected browser named Gologin already.
my target page keeps loading to infinity
|
[
"When I run into this problem I usually use a library called \"cloudscraper\"\nRead more about it here: https://github.com/VeNoMouS/cloudscraper\n"
] |
[
2
] |
[] |
[] |
[
"cloudflare",
"python",
"selenium"
] |
stackoverflow_0074513547_cloudflare_python_selenium.txt
|
Q:
How do I fix indentation error when creating a class in Python?
Every time I try to create a class, it gives me the IndentationError when I haven't even added indentations yet.
I have tried restarting Jupyter and my PC and there is no luck. I have also tried using another notebook but still face the error.
A:
As the error shows, it is expecting an indented block after the class.
So add a statement in there, example:
class Animal():
pass
A:
You should understand the basics of classes in python for this. It is working fine, the only thing is that your code is incomplete. After you declare a class, it is simply expecting a class body.
|
How do I fix indentation error when creating a class in Python?
|
Every time I try to create a class, it gives me the IndentationError when I haven't even added indentations yet.
I have tried restarting Jupyter and my PC and there is no luck. I have also tried using another notebook but still face the error.
|
[
"As the error shows, it is expecting an indented block after the class.\nSo add a statement in there, example:\nclass Animal():\n pass\n\n",
"You should understand the basics of classes in python for this. It is working fine, the only thing is that your code is incomplete. After you declare a class, it is simply expecting a class body.\n"
] |
[
2,
0
] |
[] |
[] |
[
"class",
"python",
"syntax_error"
] |
stackoverflow_0074514050_class_python_syntax_error.txt
|
Q:
BeautifulSoup - Scrape product and product variants and export it to csv
I am trying to scrape this website products listing what I am trying to achieve here is grab all the info per product for example: product_name, price and their variants info as well like 10kg, 20kg, 3kg and their prices accordingly. I have search the html they don't provide all the info I am looking for but under script tag they have a json residing which could be useful. Here is the json script tag:
</script><script type="text/x-magento-init">
{
"[data-role=swatch-option-111105]": {
"Magento_Swatches/js/swatch-renderer": {
"selectorProduct": ".product-item-details",
"onlySwatches": true,
"enableControlLabel": false,
"numberToShow": 16,
"jsonConfig": {"attributes":{"1299":{"id":"1299","code":"size","label":"Size","options":[{"id":"6651","label":"10kg","products":["116724"]},{"id":"6780","label":"20kg","products":["108981"]},{"id":"6234","label":"3kg","products":["108987"]}],"position":"0"}},"template":"$<%- data.price %>","currencyFormat":"$%s","optionPrices":{"108987":{"baseOldPrice":{"amount":49.990908090909},"oldPrice":{"amount":54.99},"basePrice":{"amount":42.718180818182},"finalPrice":{"amount":46.99},"tierPrices":[],"msrpPrice":{"amount":0}},"108981":{"baseOldPrice":{"amount":172.71818081818},"oldPrice":{"amount":189.99},"basePrice":{"amount":128.17272627273},"finalPrice":{"amount":140.99},"tierPrices":[],"msrpPrice":{"amount":0}},"116724":{"baseOldPrice":{"amount":120.899999},"oldPrice":{"amount":132.99},"basePrice":{"amount":102.71818081818},"finalPrice":{"amount":112.99},"tierPrices":[],"msrpPrice":{"amount":0}}},"priceFormat":{"pattern":"$%s","precision":2,"requiredPrecision":2,"decimalSymbol":".","groupSymbol":",","groupLength":3,"integerRequired":false},"prices":{"baseOldPrice":{"amount":49.990908090909},"oldPrice":{"amount":54.99},"basePrice":{"amount":172.71818081818},"finalPrice":{"amount":189.99}},"productId":"111105","chooseText":"Choose an Option...","images":[],"index":{"108987":{"1299":"6234"},"108981":{"1299":"6780"},"116724":{"1299":"6651"}},"preSelectedGallery":[],"channel":"website","salesChannelCode":"base","sku":{"108987":"127956","108981":"127960","116724":"501600"},"labels":{"108987":{"sales_flag_label":"Great low price"},"108981":{"sales_flag_label":"Great low price"},"116724":{"sales_flag_label":"Great low price"}},"hasEndDate":{"108987":false,"108981":false,"116724":false},"dynamic":{"name":{"108987":{"value":"Black Hawk Fish And Potato Adult Dog Food - 3kg"},"108981":{"value":"Black Hawk Fish And Potato Adult Dog Food - 20kg"},"116724":{"value":"Black Hawk Fish & Potato Dog Food 10kg"}},"sku":{"108987":{"value":"127956"},"108981":{"value":"127960"},"116724":{"value":"501600"}},"gtin":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"marketing_offer_short":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"advice_care":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"product_category":{"108987":{"value":"Dry Food"},"108981":{"value":"Dry Food"},"116724":{"value":"Dry Food"}},"benefits":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"feeding_guide":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"health_condition_dietary":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"brand_filter":{"108987":{"value":"Black Hawk"},"108981":{"value":"Black Hawk"},"116724":{"value":"Black Hawk"}},"ingredients":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"activity_level":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"size":{"108987":{"value":"3kg"},"108981":{"value":"20kg"},"116724":{"value":"10kg"}},"food_type":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"health_benefits":{"108987":{"value":"Total Wellbeing"},"108981":{"value":"Total Wellbeing"},"116724":{"value":"Total Wellbeing"}},"life_stage":{"108987":{"value":"Adult"},"108981":{"value":"Adult"},"116724":{"value":"Adult"}},"flavour":{"108987":{"value":"Fish"},"108981":{"value":"Fish"},"116724":{"value":"Fish"}},"nutritional_info":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"breed":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"nutritional_info_table":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"australia_made":{"108987":{"value":"No"},"108981":{"value":"No"},"116724":{"value":"No"}},"nutrition_grade":{"108987":{"value":"Premium"},"108981":{"value":"Premium"},"116724":{"value":"Premium"}},"lifestyle":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"weight_control":{"108987":{"value":"No"},"108981":{"value":"No"},"116724":{"value":"No"}},"frequent_feeder_price":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"size_swatches":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}}}},
"jsonSwatchConfig": {"1299":{"6651":{"type":"0","value":null,"label":"10kg"},"6780":{"type":"0","value":null,"label":"20kg"},"6234":{"type":"0","value":null,"label":"3kg"},"additional_data":"{\"update_product_preview_image\":\"1\",\"use_product_image_for_swatch\":0,\"text_swatch_as_multiple_select\":\"1\",\"swatch_input_type\":\"text\"}"}},
"mediaCallback": "https\u003A\u002F\u002Fwww.petbarn.com.au\u002Fswatches\u002Fajax\u002Fmedia\u002F",
"jsonSwatchImageSizeConfig": {"swatchImage":{"width":30,"height":20},"swatchThumb":{"height":90,"width":110}},
"showTooltip": 1 }
}
}
</script>
I have manage to parse that script tag and turned that into python dictionary via json.loads() but couldn't figure out the best way to extract info and export it to csv. here is my code so far:
import requests
import pandas as pd
from bs4 import BeautifulSoup
import json
from datetime import datetime
from datetime import date
now = datetime.now()
today = date.today()
class PetBarnProdScraper:
all_info = []
def fetch(self, url):
print(f"HTTP GET request to URL: {url}", end="")
res = requests.get(url)
print(f" | Status Code: {res.status_code}")
return res
def parse(self, response):
soup = BeautifulSoup(response.text, "html.parser")
product_urls = [a.get("href") for a in soup.select("a.product-item-link")]
product_ids = [
pid.get("id").split("-")[-1] for pid in soup.select("div.product-item-info")
]
titles = [
a.text.replace("\n", "").strip() for a in soup.select("a.product-item-link")
]
old_price = [
p.select_one("span.price").text for p in soup.select("span.old-price")
]
ratings = [r.get("title") for r in soup.select("div.rating-result")]
no_of_reviews = [review.text for review in soup.select("a.action.view")]
data = (
soup.select('script[type="text/x-magento-init"]')[3]
.text.replace("\n", "")
.strip()
)
data_json = json.loads(data)
data_j = json.loads(
data_json["*"]["Overdose_AdobeAnalytics/js/view/datalayer"]["datalayer"][0]
)
for idx in range(len(titles)):
try:
ratings_count = ratings[idx]
reviews_count = no_of_reviews[idx]
last_price = old_price[idx]
except:
ratings_count = "N/A"
reviews_count = "N/A"
last_price = "N/A"
d = {
"Scraped_Date": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[0],
"Scraped_Time": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[1],
"product_name": titles[idx],
"price": data_j["PLP"]["products"][idx]["productPrice"],
"old_price": last_price,
"ratings": ratings_count,
"number_of_reviews": reviews_count,
"productSKU": data_j["PLP"]["products"][idx]["productSKU"],
"productSize": data_j["PLP"]["products"][idx]["productSize"],
"priceWithoutTax": data_j["PLP"]["products"][idx][
"productPriceLessTax"
],
"lifeStage": data_j["PLP"]["products"][idx]["lifeStage"],
}
for prod_id in product_ids:
details = soup.select_one(
f"script:-soup-contains('[data-role=swatch-option-{prod_id}]')"
)
labels = []
if details:
json_details = json.loads(details.text.replace("\n", "").strip())
json_endpoint = json_details[f"[data-role=swatch-option-{prod_id}]"]
label_option_list = json_endpoint[
"Magento_Swatches/js/swatch-renderer"
]["jsonConfig"]["attributes"]["1299"]["options"]
for lab in label_option_list:
labels.append(lab["label"])
d["label_options"] = labels
print(d)
self.all_info.append(d)
def to_csv(self):
df = pd.DataFrame(self.all_info).fillna("")
df.to_csv(f"{today}_petbarn.csv", index=False)
print('Stored results to "petbarn.csv"')
def run(self):
for i in range(1, 2): # total_number of pages
url = f"https://www.petbarn.com.au/dogs/dog-food/dry-dog-food?p={i}"
response = self.fetch(url)
self.parse(response)
self.to_csv()
if __name__ == "__main__":
scraper = PetBarnProdScraper()
scraper.run()
every time I run that code the label_options column has always the same values which is the last one I am guessing. here is the output I am getting:
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,label_options
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,"['10kg', '20kg', '3kg']"
11/21/2022, 00:31:47,SavourLife Ancient Grains Lean Chicken Adult Dog Food,159.99,N/A,N/A,N/A,savourlife-ancient-grains-lean-chicken-adult-dog-food,,145.45,Adult,"['10kg', '20kg', '3kg']"
Expected output:
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,label_options
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,10kg
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,20kg
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,3kg
11/21/2022, 00:31:47,SavourLife Ancient Grains Lean Chicken Adult Dog Food,159.99,N/A,N/A,N/A,savourlife-ancient-grains-lean-chicken-adult-dog-food,,145.45,Adult,3kg
11/21/2022, 00:31:47,SavourLife Ancient Grains Lean Chicken Adult Dog Food,159.99,N/A,N/A,N/A,savourlife-ancient-grains-lean-chicken-adult-dog-food,,145.45,Adult,20kg
Can anyone help me figure out the best way to get the expected output? Thanks!
UPDATE:
Updated the code based on Driftr95' answer:
import requests
import pandas as pd
from bs4 import BeautifulSoup
import json
import csv
from datetime import datetime
from datetime import date
now = datetime.now()
today = date.today()
class PetBarnProdScraper:
all_info = []
def fetch(self, url):
print(f"HTTP GET request to URL: {url}", end="")
res = requests.get(url)
print(f" | Status Code: {res.status_code}")
return res
def parse(self, response):
soup = BeautifulSoup(response.text, "html.parser")
product_urls = [a.get("href") for a in soup.select("a.product-item-link")]
product_ids = [
pid.get("id").split("-")[-1] for pid in soup.select("div.product-item-info")
]
titles = [
a.text.replace("\n", "").strip() for a in soup.select("a.product-item-link")
]
old_price = [
p.select_one("span.price").text for p in soup.select("span.old-price")
]
ratings = [r.get("title") for r in soup.select("div.rating-result")]
no_of_reviews = [review.text for review in soup.select("a.action.view")]
data = (
soup.select('script[type="text/x-magento-init"]')[3]
.text.replace("\n", "")
.strip()
)
data_json = json.loads(data)
data_j = json.loads(
data_json["*"]["Overdose_AdobeAnalytics/js/view/datalayer"]["datalayer"][0]
)
for idx in range(len(titles)):
try:
ratings_count = ratings[idx]
reviews_count = no_of_reviews[idx]
last_price = old_price[idx]
except:
ratings_count = "N/A"
reviews_count = "N/A"
last_price = "N/A"
d = {
"Scraped_Date": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[0],
"Scraped_Time": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[1],
"product_name": titles[idx],
"price": data_j["PLP"]["products"][idx]["productPrice"],
"old_price": last_price,
"ratings": ratings_count,
"number_of_reviews": reviews_count,
"productSKU": data_j["PLP"]["products"][idx]["productSKU"],
"productSize": data_j["PLP"]["products"][idx]["productSize"],
"priceWithoutTax": data_j["PLP"]["products"][idx][
"productPriceLessTax"
],
"lifeStage": data_j["PLP"]["products"][idx]["lifeStage"],
}
for prod_id in product_ids:
details = soup.select_one(
f"script:-soup-contains('[data-role=swatch-option-{prod_id}]')"
)
if details:
json_details = json.loads(details.text.replace("\n", "").strip())
dataJC = json_details[f"[data-role=swatch-option-{prod_id}]"][
"Magento_Swatches/js/swatch-renderer"
]["jsonConfig"]
productId = dataJC["productId"]
jcInfs = [
{
"productId": productId,
"optionKey": k,
"sku": "?",
"index": v["1299"] if "1299" in v else None,
}
for k, v in dataJC["index"].items()
]
orInfs = [
("optionPrices", "amount", "reverseNest"),
("dynamic", "value", "nest1"),
("labels", "", "reverseNest"),
("hasEndDate", "", "noNesting"),
]
relevInfs = []
for kk, vk, nt in orInfs:
if kk not in dataJC:
continue
if nt == "noNesting":
relevInfs += [(kk, vk, dataJC[kk])]
continue
if nt == "nest1":
relevInfs += [(kk, vk, vd) for kk, vd in dataJC[kk].items()]
continue
if nt != "reverseNest":
## can put a default action here
continue
## nt == 'reverseNest'
orInf = {}
for pk, po in dataJC[kk].items():
for kpo, vpo in po.items():
if kpo not in orInf:
orInf[kpo] = {}
orInf[kpo][pk] = vpo
relevInfs += [(kk, vk, vi) for kk, vi in orInf.items()]
for i, j in enumerate(jcInfs):
for kk, vk, vd in relevInfs:
if j["optionKey"] not in vd:
continue
relevInf = vd[j["optionKey"]]
if type(relevInf) != dict:
j[kk] = relevInf
elif vk in relevInf and relevInf[vk]:
j[kk] = relevInf[vk]
# combine with main variation
jcInfs[i] = {
k: v
for k, v in (
list(d.items())
+ [(jk, jv) for jk, jv in j.items() if jk not in d]
)
}
for j in jcInfs:
self.all_info.append(j)
self.all_info.append(d)
def to_csv(self):
df = pd.DataFrame(self.all_info).fillna("")
df.to_csv(f"{today}_petbarn.csv", index=False)
print('Stored results to "petbarn.csv"')
def run(self):
for i in range(1, 2): # total_number of pages
url = f"https://www.petbarn.com.au/dogs/dog-food/dry-dog-food?p={i}"
response = self.fetch(url)
self.parse(response)
self.to_csv()
if __name__ == "__main__":
scraper = PetBarnProdScraper()
scraper.run()
the code and output matches the expectation but not paired up instead product_name rows keep repeating itself where on the other hand name column have just 3 rows so it'd be great to have those rows intact with each other.
Here is the output:
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,productId,optionKey,sku,index,baseOldPrice,oldPrice,basePrice,finalPrice,tierPrices,name,product_category,brand_filter,size,health_benefits,life_stage,flavour,australia_made,nutrition_grade,weight_control,on_sale,hasEndDate,breed,new,marketing_offer_short,sales_flag_label,activity_level
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,111105,108987,127956,6234,49.990908090909,54.99,42.718180818182,46.99,[],Black Hawk Fish And Potato Adult Dog Food - 3kg,Dry Food,Black Hawk,3kg,Total Wellbeing,Adult,Fish,No,Premium,No,Sale,True,,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,111105,108981,127960,6780,172.71818081818,189.99,128.17272627273,140.99,[],Black Hawk Fish And Potato Adult Dog Food - 20kg,Dry Food,Black Hawk,20kg,Total Wellbeing,Adult,Fish,No,Premium,No,Sale,True,,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,111105,116724,501600,6651,120.899999,132.99,102.71818081818,112.99,[],Black Hawk Fish & Potato Dog Food 10kg,Dry Food,Black Hawk,10kg,Total Wellbeing,Adult,Fish,No,Premium,No,Sale,True,,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145209,143157,140846,6234,41.809089909091,45.99,41.809089909091,45.99,[],SavourLife Ancient Grains Lean Chicken Adult Dog Food 3kg,Dry Food,SavourLife Ancient Grains,3kg,Weight Management,Adult,Chicken,No,Essential,Yes,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145209,143163,140847,6780,145.44545354545,159.99,99.090908090909,109.0,[],SavourLife Ancient Grains Lean Chicken Adult Dog Food 20kg,Dry Food,SavourLife Ancient Grains,20kg,Weight Management,Adult,Chicken,No,Essential,Yes,,False,All,New,Only $109,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144663,142980,141739,6234,48.172726272727,52.99,39.990908090909,43.99,[],Black Hawk Chicken & Rice Medium Puppy Food 3kg,Dry Food,Black Hawk,3kg,Healthy Development,Puppy,Chicken,No,Premium,No,Sale,True,Medium,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144663,142983,141740,6651,114.53636263636,125.99,101.80908990909,111.99,[],Black Hawk Chicken & Rice Medium Puppy Food 10kg,Dry Food,Black Hawk,10kg,,Puppy,Chicken,No,Premium,No,Sale,True,Medium,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144663,142959,141741,6780,169.99090809091,186.99,135.99090809091,149.59,[],Black Hawk Chicken & Rice Medium Puppy Food 20kg,Dry Food,Black Hawk,20kg,,Puppy,Chicken,No,Premium,No,Sale,True,Medium,,20% off,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144600,144351,141490,7815,36.354544454545,39.99,30.899999,33.99,[],ProBalance Care Joint Care Adult Dog Dry Food 2.5kg,Dry Food,ProBalance,2.5kg,Hip and Joint Support,Adult,,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144600,144009,141491,17823,117.26363536364,128.99,93.809089909091,103.19,[],ProBalance Care Joint Care Adult Dog Dry Food 12kg,Dry Food,ProBalance,12kg,Hip and Joint Support,Adult,,No,Superior,No,,False,,,20% off,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,113391,63624,30318,6687,173.62727172727,190.99,115.03636263636,126.54,[],Royal Canin Maxi Puppy Dog Food 15kg,Dry Food,ROYAL CANIN,15kg,Growth Support,Puppy,Chicken,No,Superior,No,,False,"Giant, Large",,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,113391,63111,29321,84219,64.536362636364,70.99,51.809089909091,56.99,[],Royal Canin Maxi Puppy Dog Food 4kg,Dry Food,ROYAL CANIN,4kg,Growth Support,Puppy,Chicken,No,Superior,No,,False,Large,,Buy 2 for $106.49,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,113391,123852,140248,8373,20.899999,22.99,17.763635363636,19.54,[],Royal Canin Maxi Breed Puppy Food 1kg,Dry Food,ROYAL CANIN,1kg,Healthy Development,Puppy,Chicken,No,Superior,No,,False,Large,,Buy 2 for $34.49,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145119,143145,140840,7815,45.445453545455,49.99,45.445453545455,49.99,[],SavourLife Grain Free Sensitive OFish Adult Dog Food 2.5kg,Dry Food,SavourLife,2.5kg,"Grain Free, Sensitive Skin, Sensitive Stomach",Adult,Fish,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145119,143148,140841,6651,113.62727172727,124.99,113.62727172727,124.99,[],SavourLife Grain Free Sensitive OFish Adult Dog Food 10kg,Dry Food,SavourLife,10kg,"Grain Free, Sensitive Skin, Sensitive Stomach",Adult,Fish,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144657,142974,141735,6651,114.53636263636,125.99,99.990908090909,109.99,[],Black Hawk Lamb & Rice Large Puppy Food 10kg,Dry Food,Black Hawk,10kg,Healthy Development,Puppy,Lamb,No,Premium,No,Sale,True,Large,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144657,142953,141736,6780,169.99090809091,186.99,135.99090809091,149.59,[],Black Hawk Lamb & Rice Large Puppy Food 20kg,Dry Food,Black Hawk,20kg,,Puppy,Lamb,No,Premium,No,Sale,True,Large,,20% off,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,112734,62448,29328,6234,49.081817181818,53.99,36.118180818182,39.73,[],Royal Canin Labrador Dog Food 3kg,Dry Food,ROYAL CANIN,3kg,,"Adult, Senior",Chicken,No,Superior,No,,False,Labrador Retriever,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,112734,62985,30327,17823,148.17272627273,162.99,92.718180818182,101.99,[],Royal Canin Labrador Dog Food 12kg,Dry Food,ROYAL CANIN,12kg,,"Adult, Senior",Chicken,No,Superior,No,,False,Labrador Retriever,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172479,128169,140460,8514,45.445453545455,49.99,40.899999,44.99,[],Acana Light & Fit Dry Dog Food 2kg,Dry Food,Acana,2kg,Weight Management,Adult,Chicken,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172479,128175,140469,292890,159.08181718182,174.99,149.99090809091,164.99,[],Acana Light & Fit Dry Dog Food 11.3kg,Dry Food,Acana,11.3kg,Weight Management,Adult,Chicken,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145083,143316,140842,7815,43.627271727273,47.99,43.627271727273,47.99,[],SavourLife Grain Free Chicken 7+ Senior Dog Food 2.5kg,Dry Food,SavourLife,2.5kg,"Ageing, Grain Free",Senior,Chicken,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145083,143322,140843,6651,109.08181718182,119.99,109.08181718182,119.99,[],SavourLife Grain Free Chicken 7+ Senior Dog Food 10kg,Dry Food,SavourLife,10kg,"Ageing, Grain Free",Senior,Chicken,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144618,144387,141488,7815,38.172726272727,41.99,32.445453545455,35.69,[],ProBalance Care Sensitive Skin Adult Dog Dry Food 2.5kg,Dry Food,ProBalance,2.5kg,Sensitive Skin,Adult,,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144618,144021,141489,17823,118.17272627273,129.99,94.536362636364,103.99,[],ProBalance Care Sensitive Skin Adult Dog Dry Food 12kg,Dry Food,ProBalance,12kg,Sensitive Skin,Adult,,No,Superior,No,,False,,,20% off,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172476,128235,140423,8514,54.536362636364,59.99,51.809089909091,56.99,[],Orijen Six Fish Dry Dog Food 2kg,Dry Food,Orijen,2kg,Grain Free,Adult,Fish,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172476,128214,140431,2825802,190.899999,209.99,181.80908990909,199.99,[],Orijen Six Fish Dry Dog Food 11.4kg,Dry Food,Orijen,11.4kg,Grain Free,Adult,Fish,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,115260,109329,127959,6780,156.35454445455,171.99,119.99090809091,131.99,[],Black Hawk Lamb And Rice Adult Dog Food - 20kg,Dry Food,Black Hawk,20kg,,Adult,Lamb,No,Premium,No,Sale,True,,,,,High Activity
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,115260,109323,127955,6234,46.354544454545,50.99,28.172726272727,30.99,[],Black Hawk Lamb And Rice Adult Dog Food - 3kg,Dry Food,Black Hawk,3kg,,Adult,Lamb,No,Premium,No,Sale,True,,,3kg bags for $30.99,,High Activity
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,115260,109317,501601,6651,110.899999,121.99,93.627271727273,102.99,[],Black Hawk Lamb & Rice Adult Dog Food 10kg,Dry Food,Black Hawk,10kg,,Adult,Lamb,No,Premium,No,Sale,True,,,,,High Activity
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,,,,,,,,,,,,,,,,,,,,,,,,,,
A:
every time I run that code the label_options column has always the same values which is the last one I am guessing
Are you sure that they don't just all happen to have the same set of options? It shouldn't be repeating since you're clearing the list with labels = [] in the loop - although you can just append label_options outside the for lab... loop:
for lab in label_option_list:
labels.append(lab["label"])
d["label_options"] = labels
instead of updating it for every label in label_option_list.
Anyway, I think your main issue is on the part where you want separate rows for each variant, and I can help a bit there.
Can anyone help me figure out the best way to get the expected output
I don't know if this is the best way, but this how I would get the maximum amount of information from the JSON in the script:
For this example, I copied the JSON inside the script tag from the html snippet in your question (to a variable pasted_jstr) as well as some of your output to set d and dataJC with
dataj = json.loads(pasted_jstr)
dataJC = dataj['[data-role=swatch-option-111105]']['Magento_Swatches/js/swatch-renderer']['jsonConfig']
# from io import StringIO
csvStr = '''
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,label_options
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,"['10kg', '20kg', '3kg']"
'''.split('\n')
d = dict(zip(csvStr[1].split(',')[:-1], csvStr[2].split(',')))
and then
productId = dataJC['productId']
jcInfs = [{
'productId': productId, 'optionKey': k, 'sku': '?',
'index': v['1299'] if '1299' in v else None
} for k, v in dataJC['index'].items()]
orInfs = [
('optionPrices', 'amount', 'reverseNest'),
('dynamic', 'value', 'nest1'),
('labels', '', 'reverseNest'),
('hasEndDate', '', 'noNesting')
]
relevInfs = []
for kk, vk, nt in orInfs:
if kk not in dataJC: continue
if nt == 'noNesting':
relevInfs += [(kk, vk, dataJC[kk])]
continue
if nt == 'nest1':
relevInfs += [(kk, vk, vd) for kk, vd in dataJC[kk].items()]
continue
if nt != 'reverseNest':
## can put a default action here
continue
## nt == 'reverseNest'
orInf = {}
for pk, po in dataJC[kk].items():
for kpo, vpo in po.items():
if kpo not in orInf: orInf[kpo] = {}
orInf[kpo][pk] = vpo
relevInfs += [(kk, vk, vi) for kk, vi in orInf.items()]
for i, j in enumerate(jcInfs):
for kk, vk, vd in relevInfs:
if j['optionKey'] not in vd: continue
relevInf = vd[j['optionKey']]
if type(relevInf) != dict: j[kk] = relevInf
elif vk in relevInf and relevInf[vk]: j[kk] = relevInf[vk]
# combine with main variation
jcInfs[i] = {k:v for k, v in (list(d.items()) + [
(jk, jv) for jk, jv in j.items() if jk not in d
])}
You can set orInfs somewhere outside the loops and add in any keys [with which you want to get info from the json], and you can also add the actions for new formats/nt ("nesting type") into the for kk, vk, nt in orInfs loop. (You can also separate the loop out into its own function...)
I was able to print the table below with print(pd.DataFrame(jcInfs).to_markdown(index=False))
| Scraped_Date | Scraped_Time | product_name | price | old_price | ratings | number_of_reviews | productSKU | productSize | priceWithoutTax | lifeStage | productId | optionKey | sku | index | baseOldPrice | oldPrice | basePrice | finalPrice | tierPrices | name | product_category | brand_filter | size | health_benefits | life_stage | flavour | australia_made | nutrition_grade | weight_control | sales_flag_label | hasEndDate |
|:---------------|:---------------|:------------------------------------------|--------:|:------------|:----------|:--------------------|:----------------------------------------|:--------------|------------------:|:------------|------------:|------------:|-------:|--------:|---------------:|-----------:|------------:|-------------:|:-------------|:-------------------------------------------------|:-------------------|:---------------|:-------|:------------------|:-------------|:----------|:-----------------|:------------------|:-----------------|:-------------------|:-------------|
| 11/21/2022 | 00:31:47 | Black Hawk Fish And Potato Adult Dog Food | 189.99 | N/A | N/A | N/A | black-hawk-fish-&-potato-adult-dog-food | | 172.72 | Adult | 111105 | 108987 | 127956 | 6234 | 49.9909 | 54.99 | 42.7182 | 46.99 | [] | Black Hawk Fish And Potato Adult Dog Food - 3kg | Dry Food | Black Hawk | 3kg | Total Wellbeing | Adult | Fish | No | Premium | No | Great low price | False |
| 11/21/2022 | 00:31:47 | Black Hawk Fish And Potato Adult Dog Food | 189.99 | N/A | N/A | N/A | black-hawk-fish-&-potato-adult-dog-food | | 172.72 | Adult | 111105 | 108981 | 127960 | 6780 | 172.718 | 189.99 | 128.173 | 140.99 | [] | Black Hawk Fish And Potato Adult Dog Food - 20kg | Dry Food | Black Hawk | 20kg | Total Wellbeing | Adult | Fish | No | Premium | No | Great low price | False |
| 11/21/2022 | 00:31:47 | Black Hawk Fish And Potato Adult Dog Food | 189.99 | N/A | N/A | N/A | black-hawk-fish-&-potato-adult-dog-food | | 172.72 | Adult | 111105 | 116724 | 501600 | 6651 | 120.9 | 132.99 | 102.718 | 112.99 | [] | Black Hawk Fish & Potato Dog Food 10kg | Dry Food | Black Hawk | 10kg | Total Wellbeing | Adult | Fish | No | Premium | No | Great low price | False |
|
BeautifulSoup - Scrape product and product variants and export it to csv
|
I am trying to scrape this website products listing what I am trying to achieve here is grab all the info per product for example: product_name, price and their variants info as well like 10kg, 20kg, 3kg and their prices accordingly. I have search the html they don't provide all the info I am looking for but under script tag they have a json residing which could be useful. Here is the json script tag:
</script><script type="text/x-magento-init">
{
"[data-role=swatch-option-111105]": {
"Magento_Swatches/js/swatch-renderer": {
"selectorProduct": ".product-item-details",
"onlySwatches": true,
"enableControlLabel": false,
"numberToShow": 16,
"jsonConfig": {"attributes":{"1299":{"id":"1299","code":"size","label":"Size","options":[{"id":"6651","label":"10kg","products":["116724"]},{"id":"6780","label":"20kg","products":["108981"]},{"id":"6234","label":"3kg","products":["108987"]}],"position":"0"}},"template":"$<%- data.price %>","currencyFormat":"$%s","optionPrices":{"108987":{"baseOldPrice":{"amount":49.990908090909},"oldPrice":{"amount":54.99},"basePrice":{"amount":42.718180818182},"finalPrice":{"amount":46.99},"tierPrices":[],"msrpPrice":{"amount":0}},"108981":{"baseOldPrice":{"amount":172.71818081818},"oldPrice":{"amount":189.99},"basePrice":{"amount":128.17272627273},"finalPrice":{"amount":140.99},"tierPrices":[],"msrpPrice":{"amount":0}},"116724":{"baseOldPrice":{"amount":120.899999},"oldPrice":{"amount":132.99},"basePrice":{"amount":102.71818081818},"finalPrice":{"amount":112.99},"tierPrices":[],"msrpPrice":{"amount":0}}},"priceFormat":{"pattern":"$%s","precision":2,"requiredPrecision":2,"decimalSymbol":".","groupSymbol":",","groupLength":3,"integerRequired":false},"prices":{"baseOldPrice":{"amount":49.990908090909},"oldPrice":{"amount":54.99},"basePrice":{"amount":172.71818081818},"finalPrice":{"amount":189.99}},"productId":"111105","chooseText":"Choose an Option...","images":[],"index":{"108987":{"1299":"6234"},"108981":{"1299":"6780"},"116724":{"1299":"6651"}},"preSelectedGallery":[],"channel":"website","salesChannelCode":"base","sku":{"108987":"127956","108981":"127960","116724":"501600"},"labels":{"108987":{"sales_flag_label":"Great low price"},"108981":{"sales_flag_label":"Great low price"},"116724":{"sales_flag_label":"Great low price"}},"hasEndDate":{"108987":false,"108981":false,"116724":false},"dynamic":{"name":{"108987":{"value":"Black Hawk Fish And Potato Adult Dog Food - 3kg"},"108981":{"value":"Black Hawk Fish And Potato Adult Dog Food - 20kg"},"116724":{"value":"Black Hawk Fish & Potato Dog Food 10kg"}},"sku":{"108987":{"value":"127956"},"108981":{"value":"127960"},"116724":{"value":"501600"}},"gtin":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"marketing_offer_short":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"advice_care":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"product_category":{"108987":{"value":"Dry Food"},"108981":{"value":"Dry Food"},"116724":{"value":"Dry Food"}},"benefits":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"feeding_guide":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"health_condition_dietary":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"brand_filter":{"108987":{"value":"Black Hawk"},"108981":{"value":"Black Hawk"},"116724":{"value":"Black Hawk"}},"ingredients":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"activity_level":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"size":{"108987":{"value":"3kg"},"108981":{"value":"20kg"},"116724":{"value":"10kg"}},"food_type":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"health_benefits":{"108987":{"value":"Total Wellbeing"},"108981":{"value":"Total Wellbeing"},"116724":{"value":"Total Wellbeing"}},"life_stage":{"108987":{"value":"Adult"},"108981":{"value":"Adult"},"116724":{"value":"Adult"}},"flavour":{"108987":{"value":"Fish"},"108981":{"value":"Fish"},"116724":{"value":"Fish"}},"nutritional_info":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"breed":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"nutritional_info_table":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"australia_made":{"108987":{"value":"No"},"108981":{"value":"No"},"116724":{"value":"No"}},"nutrition_grade":{"108987":{"value":"Premium"},"108981":{"value":"Premium"},"116724":{"value":"Premium"}},"lifestyle":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"weight_control":{"108987":{"value":"No"},"108981":{"value":"No"},"116724":{"value":"No"}},"frequent_feeder_price":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}},"size_swatches":{"108987":{"value":""},"108981":{"value":""},"116724":{"value":""}}}},
"jsonSwatchConfig": {"1299":{"6651":{"type":"0","value":null,"label":"10kg"},"6780":{"type":"0","value":null,"label":"20kg"},"6234":{"type":"0","value":null,"label":"3kg"},"additional_data":"{\"update_product_preview_image\":\"1\",\"use_product_image_for_swatch\":0,\"text_swatch_as_multiple_select\":\"1\",\"swatch_input_type\":\"text\"}"}},
"mediaCallback": "https\u003A\u002F\u002Fwww.petbarn.com.au\u002Fswatches\u002Fajax\u002Fmedia\u002F",
"jsonSwatchImageSizeConfig": {"swatchImage":{"width":30,"height":20},"swatchThumb":{"height":90,"width":110}},
"showTooltip": 1 }
}
}
</script>
I have manage to parse that script tag and turned that into python dictionary via json.loads() but couldn't figure out the best way to extract info and export it to csv. here is my code so far:
import requests
import pandas as pd
from bs4 import BeautifulSoup
import json
from datetime import datetime
from datetime import date
now = datetime.now()
today = date.today()
class PetBarnProdScraper:
all_info = []
def fetch(self, url):
print(f"HTTP GET request to URL: {url}", end="")
res = requests.get(url)
print(f" | Status Code: {res.status_code}")
return res
def parse(self, response):
soup = BeautifulSoup(response.text, "html.parser")
product_urls = [a.get("href") for a in soup.select("a.product-item-link")]
product_ids = [
pid.get("id").split("-")[-1] for pid in soup.select("div.product-item-info")
]
titles = [
a.text.replace("\n", "").strip() for a in soup.select("a.product-item-link")
]
old_price = [
p.select_one("span.price").text for p in soup.select("span.old-price")
]
ratings = [r.get("title") for r in soup.select("div.rating-result")]
no_of_reviews = [review.text for review in soup.select("a.action.view")]
data = (
soup.select('script[type="text/x-magento-init"]')[3]
.text.replace("\n", "")
.strip()
)
data_json = json.loads(data)
data_j = json.loads(
data_json["*"]["Overdose_AdobeAnalytics/js/view/datalayer"]["datalayer"][0]
)
for idx in range(len(titles)):
try:
ratings_count = ratings[idx]
reviews_count = no_of_reviews[idx]
last_price = old_price[idx]
except:
ratings_count = "N/A"
reviews_count = "N/A"
last_price = "N/A"
d = {
"Scraped_Date": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[0],
"Scraped_Time": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[1],
"product_name": titles[idx],
"price": data_j["PLP"]["products"][idx]["productPrice"],
"old_price": last_price,
"ratings": ratings_count,
"number_of_reviews": reviews_count,
"productSKU": data_j["PLP"]["products"][idx]["productSKU"],
"productSize": data_j["PLP"]["products"][idx]["productSize"],
"priceWithoutTax": data_j["PLP"]["products"][idx][
"productPriceLessTax"
],
"lifeStage": data_j["PLP"]["products"][idx]["lifeStage"],
}
for prod_id in product_ids:
details = soup.select_one(
f"script:-soup-contains('[data-role=swatch-option-{prod_id}]')"
)
labels = []
if details:
json_details = json.loads(details.text.replace("\n", "").strip())
json_endpoint = json_details[f"[data-role=swatch-option-{prod_id}]"]
label_option_list = json_endpoint[
"Magento_Swatches/js/swatch-renderer"
]["jsonConfig"]["attributes"]["1299"]["options"]
for lab in label_option_list:
labels.append(lab["label"])
d["label_options"] = labels
print(d)
self.all_info.append(d)
def to_csv(self):
df = pd.DataFrame(self.all_info).fillna("")
df.to_csv(f"{today}_petbarn.csv", index=False)
print('Stored results to "petbarn.csv"')
def run(self):
for i in range(1, 2): # total_number of pages
url = f"https://www.petbarn.com.au/dogs/dog-food/dry-dog-food?p={i}"
response = self.fetch(url)
self.parse(response)
self.to_csv()
if __name__ == "__main__":
scraper = PetBarnProdScraper()
scraper.run()
every time I run that code the label_options column has always the same values which is the last one I am guessing. here is the output I am getting:
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,label_options
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,"['10kg', '20kg', '3kg']"
11/21/2022, 00:31:47,SavourLife Ancient Grains Lean Chicken Adult Dog Food,159.99,N/A,N/A,N/A,savourlife-ancient-grains-lean-chicken-adult-dog-food,,145.45,Adult,"['10kg', '20kg', '3kg']"
Expected output:
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,label_options
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,10kg
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,20kg
11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,3kg
11/21/2022, 00:31:47,SavourLife Ancient Grains Lean Chicken Adult Dog Food,159.99,N/A,N/A,N/A,savourlife-ancient-grains-lean-chicken-adult-dog-food,,145.45,Adult,3kg
11/21/2022, 00:31:47,SavourLife Ancient Grains Lean Chicken Adult Dog Food,159.99,N/A,N/A,N/A,savourlife-ancient-grains-lean-chicken-adult-dog-food,,145.45,Adult,20kg
Can anyone help me figure out the best way to get the expected output? Thanks!
UPDATE:
Updated the code based on Driftr95' answer:
import requests
import pandas as pd
from bs4 import BeautifulSoup
import json
import csv
from datetime import datetime
from datetime import date
now = datetime.now()
today = date.today()
class PetBarnProdScraper:
all_info = []
def fetch(self, url):
print(f"HTTP GET request to URL: {url}", end="")
res = requests.get(url)
print(f" | Status Code: {res.status_code}")
return res
def parse(self, response):
soup = BeautifulSoup(response.text, "html.parser")
product_urls = [a.get("href") for a in soup.select("a.product-item-link")]
product_ids = [
pid.get("id").split("-")[-1] for pid in soup.select("div.product-item-info")
]
titles = [
a.text.replace("\n", "").strip() for a in soup.select("a.product-item-link")
]
old_price = [
p.select_one("span.price").text for p in soup.select("span.old-price")
]
ratings = [r.get("title") for r in soup.select("div.rating-result")]
no_of_reviews = [review.text for review in soup.select("a.action.view")]
data = (
soup.select('script[type="text/x-magento-init"]')[3]
.text.replace("\n", "")
.strip()
)
data_json = json.loads(data)
data_j = json.loads(
data_json["*"]["Overdose_AdobeAnalytics/js/view/datalayer"]["datalayer"][0]
)
for idx in range(len(titles)):
try:
ratings_count = ratings[idx]
reviews_count = no_of_reviews[idx]
last_price = old_price[idx]
except:
ratings_count = "N/A"
reviews_count = "N/A"
last_price = "N/A"
d = {
"Scraped_Date": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[0],
"Scraped_Time": now.strftime("%m/%d/%Y, %H:%M:%S").split(",")[1],
"product_name": titles[idx],
"price": data_j["PLP"]["products"][idx]["productPrice"],
"old_price": last_price,
"ratings": ratings_count,
"number_of_reviews": reviews_count,
"productSKU": data_j["PLP"]["products"][idx]["productSKU"],
"productSize": data_j["PLP"]["products"][idx]["productSize"],
"priceWithoutTax": data_j["PLP"]["products"][idx][
"productPriceLessTax"
],
"lifeStage": data_j["PLP"]["products"][idx]["lifeStage"],
}
for prod_id in product_ids:
details = soup.select_one(
f"script:-soup-contains('[data-role=swatch-option-{prod_id}]')"
)
if details:
json_details = json.loads(details.text.replace("\n", "").strip())
dataJC = json_details[f"[data-role=swatch-option-{prod_id}]"][
"Magento_Swatches/js/swatch-renderer"
]["jsonConfig"]
productId = dataJC["productId"]
jcInfs = [
{
"productId": productId,
"optionKey": k,
"sku": "?",
"index": v["1299"] if "1299" in v else None,
}
for k, v in dataJC["index"].items()
]
orInfs = [
("optionPrices", "amount", "reverseNest"),
("dynamic", "value", "nest1"),
("labels", "", "reverseNest"),
("hasEndDate", "", "noNesting"),
]
relevInfs = []
for kk, vk, nt in orInfs:
if kk not in dataJC:
continue
if nt == "noNesting":
relevInfs += [(kk, vk, dataJC[kk])]
continue
if nt == "nest1":
relevInfs += [(kk, vk, vd) for kk, vd in dataJC[kk].items()]
continue
if nt != "reverseNest":
## can put a default action here
continue
## nt == 'reverseNest'
orInf = {}
for pk, po in dataJC[kk].items():
for kpo, vpo in po.items():
if kpo not in orInf:
orInf[kpo] = {}
orInf[kpo][pk] = vpo
relevInfs += [(kk, vk, vi) for kk, vi in orInf.items()]
for i, j in enumerate(jcInfs):
for kk, vk, vd in relevInfs:
if j["optionKey"] not in vd:
continue
relevInf = vd[j["optionKey"]]
if type(relevInf) != dict:
j[kk] = relevInf
elif vk in relevInf and relevInf[vk]:
j[kk] = relevInf[vk]
# combine with main variation
jcInfs[i] = {
k: v
for k, v in (
list(d.items())
+ [(jk, jv) for jk, jv in j.items() if jk not in d]
)
}
for j in jcInfs:
self.all_info.append(j)
self.all_info.append(d)
def to_csv(self):
df = pd.DataFrame(self.all_info).fillna("")
df.to_csv(f"{today}_petbarn.csv", index=False)
print('Stored results to "petbarn.csv"')
def run(self):
for i in range(1, 2): # total_number of pages
url = f"https://www.petbarn.com.au/dogs/dog-food/dry-dog-food?p={i}"
response = self.fetch(url)
self.parse(response)
self.to_csv()
if __name__ == "__main__":
scraper = PetBarnProdScraper()
scraper.run()
the code and output matches the expectation but not paired up instead product_name rows keep repeating itself where on the other hand name column have just 3 rows so it'd be great to have those rows intact with each other.
Here is the output:
Scraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,productId,optionKey,sku,index,baseOldPrice,oldPrice,basePrice,finalPrice,tierPrices,name,product_category,brand_filter,size,health_benefits,life_stage,flavour,australia_made,nutrition_grade,weight_control,on_sale,hasEndDate,breed,new,marketing_offer_short,sales_flag_label,activity_level
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,111105,108987,127956,6234,49.990908090909,54.99,42.718180818182,46.99,[],Black Hawk Fish And Potato Adult Dog Food - 3kg,Dry Food,Black Hawk,3kg,Total Wellbeing,Adult,Fish,No,Premium,No,Sale,True,,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,111105,108981,127960,6780,172.71818081818,189.99,128.17272627273,140.99,[],Black Hawk Fish And Potato Adult Dog Food - 20kg,Dry Food,Black Hawk,20kg,Total Wellbeing,Adult,Fish,No,Premium,No,Sale,True,,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,111105,116724,501600,6651,120.899999,132.99,102.71818081818,112.99,[],Black Hawk Fish & Potato Dog Food 10kg,Dry Food,Black Hawk,10kg,Total Wellbeing,Adult,Fish,No,Premium,No,Sale,True,,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145209,143157,140846,6234,41.809089909091,45.99,41.809089909091,45.99,[],SavourLife Ancient Grains Lean Chicken Adult Dog Food 3kg,Dry Food,SavourLife Ancient Grains,3kg,Weight Management,Adult,Chicken,No,Essential,Yes,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145209,143163,140847,6780,145.44545354545,159.99,99.090908090909,109.0,[],SavourLife Ancient Grains Lean Chicken Adult Dog Food 20kg,Dry Food,SavourLife Ancient Grains,20kg,Weight Management,Adult,Chicken,No,Essential,Yes,,False,All,New,Only $109,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144663,142980,141739,6234,48.172726272727,52.99,39.990908090909,43.99,[],Black Hawk Chicken & Rice Medium Puppy Food 3kg,Dry Food,Black Hawk,3kg,Healthy Development,Puppy,Chicken,No,Premium,No,Sale,True,Medium,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144663,142983,141740,6651,114.53636263636,125.99,101.80908990909,111.99,[],Black Hawk Chicken & Rice Medium Puppy Food 10kg,Dry Food,Black Hawk,10kg,,Puppy,Chicken,No,Premium,No,Sale,True,Medium,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144663,142959,141741,6780,169.99090809091,186.99,135.99090809091,149.59,[],Black Hawk Chicken & Rice Medium Puppy Food 20kg,Dry Food,Black Hawk,20kg,,Puppy,Chicken,No,Premium,No,Sale,True,Medium,,20% off,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144600,144351,141490,7815,36.354544454545,39.99,30.899999,33.99,[],ProBalance Care Joint Care Adult Dog Dry Food 2.5kg,Dry Food,ProBalance,2.5kg,Hip and Joint Support,Adult,,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144600,144009,141491,17823,117.26363536364,128.99,93.809089909091,103.19,[],ProBalance Care Joint Care Adult Dog Dry Food 12kg,Dry Food,ProBalance,12kg,Hip and Joint Support,Adult,,No,Superior,No,,False,,,20% off,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,113391,63624,30318,6687,173.62727172727,190.99,115.03636263636,126.54,[],Royal Canin Maxi Puppy Dog Food 15kg,Dry Food,ROYAL CANIN,15kg,Growth Support,Puppy,Chicken,No,Superior,No,,False,"Giant, Large",,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,113391,63111,29321,84219,64.536362636364,70.99,51.809089909091,56.99,[],Royal Canin Maxi Puppy Dog Food 4kg,Dry Food,ROYAL CANIN,4kg,Growth Support,Puppy,Chicken,No,Superior,No,,False,Large,,Buy 2 for $106.49,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,113391,123852,140248,8373,20.899999,22.99,17.763635363636,19.54,[],Royal Canin Maxi Breed Puppy Food 1kg,Dry Food,ROYAL CANIN,1kg,Healthy Development,Puppy,Chicken,No,Superior,No,,False,Large,,Buy 2 for $34.49,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145119,143145,140840,7815,45.445453545455,49.99,45.445453545455,49.99,[],SavourLife Grain Free Sensitive OFish Adult Dog Food 2.5kg,Dry Food,SavourLife,2.5kg,"Grain Free, Sensitive Skin, Sensitive Stomach",Adult,Fish,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145119,143148,140841,6651,113.62727172727,124.99,113.62727172727,124.99,[],SavourLife Grain Free Sensitive OFish Adult Dog Food 10kg,Dry Food,SavourLife,10kg,"Grain Free, Sensitive Skin, Sensitive Stomach",Adult,Fish,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144657,142974,141735,6651,114.53636263636,125.99,99.990908090909,109.99,[],Black Hawk Lamb & Rice Large Puppy Food 10kg,Dry Food,Black Hawk,10kg,Healthy Development,Puppy,Lamb,No,Premium,No,Sale,True,Large,,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144657,142953,141736,6780,169.99090809091,186.99,135.99090809091,149.59,[],Black Hawk Lamb & Rice Large Puppy Food 20kg,Dry Food,Black Hawk,20kg,,Puppy,Lamb,No,Premium,No,Sale,True,Large,,20% off,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,112734,62448,29328,6234,49.081817181818,53.99,36.118180818182,39.73,[],Royal Canin Labrador Dog Food 3kg,Dry Food,ROYAL CANIN,3kg,,"Adult, Senior",Chicken,No,Superior,No,,False,Labrador Retriever,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,112734,62985,30327,17823,148.17272627273,162.99,92.718180818182,101.99,[],Royal Canin Labrador Dog Food 12kg,Dry Food,ROYAL CANIN,12kg,,"Adult, Senior",Chicken,No,Superior,No,,False,Labrador Retriever,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172479,128169,140460,8514,45.445453545455,49.99,40.899999,44.99,[],Acana Light & Fit Dry Dog Food 2kg,Dry Food,Acana,2kg,Weight Management,Adult,Chicken,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172479,128175,140469,292890,159.08181718182,174.99,149.99090809091,164.99,[],Acana Light & Fit Dry Dog Food 11.3kg,Dry Food,Acana,11.3kg,Weight Management,Adult,Chicken,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145083,143316,140842,7815,43.627271727273,47.99,43.627271727273,47.99,[],SavourLife Grain Free Chicken 7+ Senior Dog Food 2.5kg,Dry Food,SavourLife,2.5kg,"Ageing, Grain Free",Senior,Chicken,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,145083,143322,140843,6651,109.08181718182,119.99,109.08181718182,119.99,[],SavourLife Grain Free Chicken 7+ Senior Dog Food 10kg,Dry Food,SavourLife,10kg,"Ageing, Grain Free",Senior,Chicken,No,Superior,No,Sale,False,All,New,,,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144618,144387,141488,7815,38.172726272727,41.99,32.445453545455,35.69,[],ProBalance Care Sensitive Skin Adult Dog Dry Food 2.5kg,Dry Food,ProBalance,2.5kg,Sensitive Skin,Adult,,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,144618,144021,141489,17823,118.17272627273,129.99,94.536362636364,103.99,[],ProBalance Care Sensitive Skin Adult Dog Dry Food 12kg,Dry Food,ProBalance,12kg,Sensitive Skin,Adult,,No,Superior,No,,False,,,20% off,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172476,128235,140423,8514,54.536362636364,59.99,51.809089909091,56.99,[],Orijen Six Fish Dry Dog Food 2kg,Dry Food,Orijen,2kg,Grain Free,Adult,Fish,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,172476,128214,140431,2825802,190.899999,209.99,181.80908990909,199.99,[],Orijen Six Fish Dry Dog Food 11.4kg,Dry Food,Orijen,11.4kg,Grain Free,Adult,Fish,No,Superior,No,,False,,,,Great low price,
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,115260,109329,127959,6780,156.35454445455,171.99,119.99090809091,131.99,[],Black Hawk Lamb And Rice Adult Dog Food - 20kg,Dry Food,Black Hawk,20kg,,Adult,Lamb,No,Premium,No,Sale,True,,,,,High Activity
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,115260,109323,127955,6234,46.354544454545,50.99,28.172726272727,30.99,[],Black Hawk Lamb And Rice Adult Dog Food - 3kg,Dry Food,Black Hawk,3kg,,Adult,Lamb,No,Premium,No,Sale,True,,,3kg bags for $30.99,,High Activity
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,115260,109317,501601,6651,110.899999,121.99,93.627271727273,102.99,[],Black Hawk Lamb & Rice Adult Dog Food 10kg,Dry Food,Black Hawk,10kg,,Adult,Lamb,No,Premium,No,Sale,True,,,,,High Activity
11/21/2022, 14:34:56,Advance Oodles Puppy Food 2.5kg,40.77,$47.99,100%,1,143138,,37.06,Puppy,,,,,,,,,,,,,,,,,,,,,,,,,,
|
[
"\nevery time I run that code the label_options column has always the same values which is the last one I am guessing\n\nAre you sure that they don't just all happen to have the same set of options? It shouldn't be repeating since you're clearing the list with labels = [] in the loop - although you can just append label_options outside the for lab... loop:\n for lab in label_option_list:\n labels.append(lab[\"label\"])\n\n d[\"label_options\"] = labels\n\ninstead of updating it for every label in label_option_list.\n\n\nAnyway, I think your main issue is on the part where you want separate rows for each variant, and I can help a bit there.\n\nCan anyone help me figure out the best way to get the expected output\n\nI don't know if this is the best way, but this how I would get the maximum amount of information from the JSON in the script:\n\nFor this example, I copied the JSON inside the script tag from the html snippet in your question (to a variable pasted_jstr) as well as some of your output to set d and dataJC with\ndataj = json.loads(pasted_jstr)\ndataJC = dataj['[data-role=swatch-option-111105]']['Magento_Swatches/js/swatch-renderer']['jsonConfig']\n\n# from io import StringIO\ncsvStr = '''\nScraped_Date,Scraped_Time,product_name,price,old_price,ratings,number_of_reviews,productSKU,productSize,priceWithoutTax,lifeStage,label_options\n11/21/2022, 00:31:47,Black Hawk Fish And Potato Adult Dog Food,189.99,N/A,N/A,N/A,black-hawk-fish-&-potato-adult-dog-food,,172.72,Adult,\"['10kg', '20kg', '3kg']\"\n'''.split('\\n')\nd = dict(zip(csvStr[1].split(',')[:-1], csvStr[2].split(',')))\n\n\nand then\nproductId = dataJC['productId']\njcInfs = [{\n 'productId': productId, 'optionKey': k, 'sku': '?',\n 'index': v['1299'] if '1299' in v else None\n} for k, v in dataJC['index'].items()] \norInfs = [\n ('optionPrices', 'amount', 'reverseNest'), \n ('dynamic', 'value', 'nest1'),\n ('labels', '', 'reverseNest'),\n ('hasEndDate', '', 'noNesting')\n]\nrelevInfs = []\nfor kk, vk, nt in orInfs:\n if kk not in dataJC: continue\n if nt == 'noNesting':\n relevInfs += [(kk, vk, dataJC[kk])]\n continue\n \n if nt == 'nest1':\n relevInfs += [(kk, vk, vd) for kk, vd in dataJC[kk].items()]\n continue\n \n if nt != 'reverseNest':\n ## can put a default action here\n continue\n \n ## nt == 'reverseNest'\n orInf = {}\n for pk, po in dataJC[kk].items():\n for kpo, vpo in po.items():\n if kpo not in orInf: orInf[kpo] = {}\n orInf[kpo][pk] = vpo\n relevInfs += [(kk, vk, vi) for kk, vi in orInf.items()]\n \nfor i, j in enumerate(jcInfs):\n for kk, vk, vd in relevInfs:\n if j['optionKey'] not in vd: continue\n relevInf = vd[j['optionKey']]\n if type(relevInf) != dict: j[kk] = relevInf\n elif vk in relevInf and relevInf[vk]: j[kk] = relevInf[vk]\n \n # combine with main variation\n jcInfs[i] = {k:v for k, v in (list(d.items()) + [\n (jk, jv) for jk, jv in j.items() if jk not in d\n ])}\n\nYou can set orInfs somewhere outside the loops and add in any keys [with which you want to get info from the json], and you can also add the actions for new formats/nt (\"nesting type\") into the for kk, vk, nt in orInfs loop. (You can also separate the loop out into its own function...)\nI was able to print the table below with print(pd.DataFrame(jcInfs).to_markdown(index=False))\n| Scraped_Date | Scraped_Time | product_name | price | old_price | ratings | number_of_reviews | productSKU | productSize | priceWithoutTax | lifeStage | productId | optionKey | sku | index | baseOldPrice | oldPrice | basePrice | finalPrice | tierPrices | name | product_category | brand_filter | size | health_benefits | life_stage | flavour | australia_made | nutrition_grade | weight_control | sales_flag_label | hasEndDate |\n|:---------------|:---------------|:------------------------------------------|--------:|:------------|:----------|:--------------------|:----------------------------------------|:--------------|------------------:|:------------|------------:|------------:|-------:|--------:|---------------:|-----------:|------------:|-------------:|:-------------|:-------------------------------------------------|:-------------------|:---------------|:-------|:------------------|:-------------|:----------|:-----------------|:------------------|:-----------------|:-------------------|:-------------|\n| 11/21/2022 | 00:31:47 | Black Hawk Fish And Potato Adult Dog Food | 189.99 | N/A | N/A | N/A | black-hawk-fish-&-potato-adult-dog-food | | 172.72 | Adult | 111105 | 108987 | 127956 | 6234 | 49.9909 | 54.99 | 42.7182 | 46.99 | [] | Black Hawk Fish And Potato Adult Dog Food - 3kg | Dry Food | Black Hawk | 3kg | Total Wellbeing | Adult | Fish | No | Premium | No | Great low price | False |\n| 11/21/2022 | 00:31:47 | Black Hawk Fish And Potato Adult Dog Food | 189.99 | N/A | N/A | N/A | black-hawk-fish-&-potato-adult-dog-food | | 172.72 | Adult | 111105 | 108981 | 127960 | 6780 | 172.718 | 189.99 | 128.173 | 140.99 | [] | Black Hawk Fish And Potato Adult Dog Food - 20kg | Dry Food | Black Hawk | 20kg | Total Wellbeing | Adult | Fish | No | Premium | No | Great low price | False |\n| 11/21/2022 | 00:31:47 | Black Hawk Fish And Potato Adult Dog Food | 189.99 | N/A | N/A | N/A | black-hawk-fish-&-potato-adult-dog-food | | 172.72 | Adult | 111105 | 116724 | 501600 | 6651 | 120.9 | 132.99 | 102.718 | 112.99 | [] | Black Hawk Fish & Potato Dog Food 10kg | Dry Food | Black Hawk | 10kg | Total Wellbeing | Adult | Fish | No | Premium | No | Great low price | False |\n\n"
] |
[
1
] |
[] |
[] |
[
"beautifulsoup",
"csv",
"python",
"python_3.x",
"web_scraping"
] |
stackoverflow_0074511414_beautifulsoup_csv_python_python_3.x_web_scraping.txt
|
Q:
Weird list in python
So I was trying to fetch member of my discord server using discord.py, using the guild.members I was iterating over it and it returned me the names of the members but then I printed it directly and I got something like this:
[<Member id=102833403109497170 name='Xiaoling' discriminator='147' bot=False nick=None guild=<Guild id=102393565654216714 name='DarkFuture' chunked=True member_count=22>>, <Member id=94117068084664839 name='Rishit' discriminator='0184' bot=False nick=None guild=<Guild id=1023935685654216714 name='DarkFuture' chunked=True member_count=22>>, <Member id=9417194317169792 name='麦わら帽子・Zoro' discriminator='905' bot=False nick=None guild=<Guild id=102393565654216714 name='DarkFuture' chunked=True member_count=22>>]
is this a List?? I checked it's type and it says list but it doesn't looks like a list to me, if I paste it directly in the code editor the there's a error highlighting, and if I run it it gives me a syntax error, what is this? How is python iterating over it?
Just found a weird list in python which I don't know what is, Needed information
A:
Take a look at the class Member
class Member:
def __init__(self,id,name,somethingElse=True):
self.id = id
self.name = name
self.somethingElse = somethingElse
def addExtraValue(self,extra):
self.extra = extra
def __repr__(self):
return "<id = {}, name = '{}'>".format(self.id, self.name)
Here,
the Member class has its own attributes like id, name, etc.
Let's create a list of this class
m1 = Member(1,'name 1')
m1.addExtraValue(15)
m2 = Member(2,'name 2', False)
members = [m1,m2]
When we print members at this point. It will show output like,
[<id = 1, name = 'name 1'>, <id = 2, name = 'name 2'>]
instead of
[<__main__.Member object at 0x7fb9c093e4c0>, <__main__.Member object at 0x7fb9c07e8130>]
It is due to the def __repr__(self) function in class, which is used to create custom output.
I hope this will clear the confusion regarding the print of < mark in the output.
Then, Class attributes are not iterable, hence we can not directly iterate over it or can not access the attributes as a list (i.e. member[key] is not supported).
To solve this issue you can use the eval method as shown below.
possibleKeys = ['id','name','somethingElse','extra']
for member in members:
for key in possibleKeys:
try:
value = eval('member.{}'.format(key))
except:
value = 'Not Available'
print("{} => {}".format(key,value))
print()
The eval is wrapped in try and catch because the extra attribute is not necessary to be available in all class objects.
I hope this will clear the way to iterate over class objects to get other attributes.
|
Weird list in python
|
So I was trying to fetch member of my discord server using discord.py, using the guild.members I was iterating over it and it returned me the names of the members but then I printed it directly and I got something like this:
[<Member id=102833403109497170 name='Xiaoling' discriminator='147' bot=False nick=None guild=<Guild id=102393565654216714 name='DarkFuture' chunked=True member_count=22>>, <Member id=94117068084664839 name='Rishit' discriminator='0184' bot=False nick=None guild=<Guild id=1023935685654216714 name='DarkFuture' chunked=True member_count=22>>, <Member id=9417194317169792 name='麦わら帽子・Zoro' discriminator='905' bot=False nick=None guild=<Guild id=102393565654216714 name='DarkFuture' chunked=True member_count=22>>]
is this a List?? I checked it's type and it says list but it doesn't looks like a list to me, if I paste it directly in the code editor the there's a error highlighting, and if I run it it gives me a syntax error, what is this? How is python iterating over it?
Just found a weird list in python which I don't know what is, Needed information
|
[
"Take a look at the class Member\nclass Member:\n def __init__(self,id,name,somethingElse=True):\n self.id = id\n self.name = name\n self.somethingElse = somethingElse\n\n def addExtraValue(self,extra):\n self.extra = extra\n \n def __repr__(self):\n return \"<id = {}, name = '{}'>\".format(self.id, self.name)\n\nHere,\nthe Member class has its own attributes like id, name, etc.\nLet's create a list of this class\nm1 = Member(1,'name 1')\nm1.addExtraValue(15)\nm2 = Member(2,'name 2', False)\n\nmembers = [m1,m2]\n\nWhen we print members at this point. It will show output like,\n[<id = 1, name = 'name 1'>, <id = 2, name = 'name 2'>]\n\ninstead of\n[<__main__.Member object at 0x7fb9c093e4c0>, <__main__.Member object at 0x7fb9c07e8130>]\n\nIt is due to the def __repr__(self) function in class, which is used to create custom output.\nI hope this will clear the confusion regarding the print of < mark in the output.\nThen, Class attributes are not iterable, hence we can not directly iterate over it or can not access the attributes as a list (i.e. member[key] is not supported).\nTo solve this issue you can use the eval method as shown below.\npossibleKeys = ['id','name','somethingElse','extra']\nfor member in members:\n for key in possibleKeys:\n try:\n value = eval('member.{}'.format(key))\n except:\n value = 'Not Available'\n print(\"{} => {}\".format(key,value))\n print()\n\nThe eval is wrapped in try and catch because the extra attribute is not necessary to be available in all class objects.\nI hope this will clear the way to iterate over class objects to get other attributes.\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"list",
"python"
] |
stackoverflow_0074513648_discord_discord.py_list_python.txt
|
Q:
In python, can locateCenterOnScreen be used with region?
There is a large picture including number 8.
First, I want to detect the large picture as below:
left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3)
Second, if the large picture is detected, then I want to narrow down to find the number 8.
x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
Finally, I want to click the number 8
pyautogui.click(x, y)
This is my code, but it returns error below:
TypeError: cannot unpack non-iterable NoneType object
import time
import pyautogui
time.sleep(1)
left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3)
if left is None:
print("Not Detected")
else:
print("Detected")
x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
if x is None:
print("Error")
else:
print("Clicked")
pyautogui.click(x, y)
A:
Yes locateCenterOnScreen can be used with region. That error you get is because pyautogui simply cannot find the object. And since there is no result, it cannot use iteration to assign variables to your x and y
this line here will never be true
if x is None:
Because this line will throw an error if the object is not found
x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
To fix your issue, do not force the result on iteration. Assign it to a single variable, then call out each x & y from that variable
Coord = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
if Coord is None:
print("Error")
else:
pyautogui.click(Coord.x, Coord.y)
|
In python, can locateCenterOnScreen be used with region?
|
There is a large picture including number 8.
First, I want to detect the large picture as below:
left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3)
Second, if the large picture is detected, then I want to narrow down to find the number 8.
x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
Finally, I want to click the number 8
pyautogui.click(x, y)
This is my code, but it returns error below:
TypeError: cannot unpack non-iterable NoneType object
import time
import pyautogui
time.sleep(1)
left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3)
if left is None:
print("Not Detected")
else:
print("Detected")
x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
if x is None:
print("Error")
else:
print("Clicked")
pyautogui.click(x, y)
|
[
"Yes locateCenterOnScreen can be used with region. That error you get is because pyautogui simply cannot find the object. And since there is no result, it cannot use iteration to assign variables to your x and y\nthis line here will never be true\nif x is None: \n\nBecause this line will throw an error if the object is not found\nx, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))\n\nTo fix your issue, do not force the result on iteration. Assign it to a single variable, then call out each x & y from that variable\nCoord = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))\nif Coord is None:\n print(\"Error\")\nelse:\n pyautogui.click(Coord.x, Coord.y)\n\n"
] |
[
2
] |
[] |
[] |
[
"pyautogui",
"python"
] |
stackoverflow_0074513744_pyautogui_python.txt
|
Q:
Why my tabula template does not output the data from PDF file when running through Python?
I selected the area using Tabula as below in the app and created a template. The out put in web works. But when I do it via code below I get an error "The output file is empty".
Area selection
Code
import tabula
df = tabula.io.read_pdf_with_template(input_path="C:/Users/dnalaka/Desktop/DEF.2400-20221117.pdf",
template_path="C:/Users/dnalaka/Desktop/DEF.json",
format="csv",
output_path= "C:/Users/dnalaka/Desktop/DEF.2400-20221117.csv",stream=True)
When I check the CSV file it has below data in it.
[{"extraction_method":"stream","top":107.867,"left":27.011,"width":185.21499633789062,"height":44.198997497558594,"right":212.226,"bottom":152.066,"data":[[{"top":113.68,"left":29.48,"width":45.7966423034668,"height":5.309999942779541,"text":"Net. Liq."},{"top":0.0,"left":0.0,"width":0.0,"height":0.0,"text":""},{"top":113.68,"left":150.46,"width":53.329994201660156,"height":5.309999942779541,"text":"39,749,795"}],[{"top":127.63,"left":29.48,"width":37.35663986206055,"height":5.309999942779541,"text":"Haircut"},{"top":0.0,"left":0.0,"width":0.0,"height":0.0,"text":""},{"top":127.63,"left":150.47,"width":57.230003356933594,"height":5.309999942779541,"text":"20,659,245-"}],[{"top":141.57,"left":29.48,"width":33.08664321899414,"height":5.309999942779541,"text":"Excess"},{"top":0.0,"left":0.0,"width":0.0,"height":0.0,"text":""},{"top":141.57,"left":150.47,"width":53.329994201660156,"height":5.309999942779541,"text":"19,090,549"}]]}]
My template content
[{"page":1,"extraction_method":"guess","x1":27.010627264785583,"x2":212.22643048744183,"y1":107.86715812683106,"y2":152.06638389587403,"width":185.21580322265626,"height":44.19922576904297}]
How can I get the data saved into a CSV ?
A:
I notice the out put format defining really doesn't work in the function. However, it does out put the data in JSON format. As we have it in a data frame we can simply save it to a csv file.
df[0].to_csv(csv_path)
|
Why my tabula template does not output the data from PDF file when running through Python?
|
I selected the area using Tabula as below in the app and created a template. The out put in web works. But when I do it via code below I get an error "The output file is empty".
Area selection
Code
import tabula
df = tabula.io.read_pdf_with_template(input_path="C:/Users/dnalaka/Desktop/DEF.2400-20221117.pdf",
template_path="C:/Users/dnalaka/Desktop/DEF.json",
format="csv",
output_path= "C:/Users/dnalaka/Desktop/DEF.2400-20221117.csv",stream=True)
When I check the CSV file it has below data in it.
[{"extraction_method":"stream","top":107.867,"left":27.011,"width":185.21499633789062,"height":44.198997497558594,"right":212.226,"bottom":152.066,"data":[[{"top":113.68,"left":29.48,"width":45.7966423034668,"height":5.309999942779541,"text":"Net. Liq."},{"top":0.0,"left":0.0,"width":0.0,"height":0.0,"text":""},{"top":113.68,"left":150.46,"width":53.329994201660156,"height":5.309999942779541,"text":"39,749,795"}],[{"top":127.63,"left":29.48,"width":37.35663986206055,"height":5.309999942779541,"text":"Haircut"},{"top":0.0,"left":0.0,"width":0.0,"height":0.0,"text":""},{"top":127.63,"left":150.47,"width":57.230003356933594,"height":5.309999942779541,"text":"20,659,245-"}],[{"top":141.57,"left":29.48,"width":33.08664321899414,"height":5.309999942779541,"text":"Excess"},{"top":0.0,"left":0.0,"width":0.0,"height":0.0,"text":""},{"top":141.57,"left":150.47,"width":53.329994201660156,"height":5.309999942779541,"text":"19,090,549"}]]}]
My template content
[{"page":1,"extraction_method":"guess","x1":27.010627264785583,"x2":212.22643048744183,"y1":107.86715812683106,"y2":152.06638389587403,"width":185.21580322265626,"height":44.19922576904297}]
How can I get the data saved into a CSV ?
|
[
"I notice the out put format defining really doesn't work in the function. However, it does out put the data in JSON format. As we have it in a data frame we can simply save it to a csv file.\ndf[0].to_csv(csv_path)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tabula",
"tabula_py"
] |
stackoverflow_0074485053_python_tabula_tabula_py.txt
|
Q:
Adding flag according to a condition in Dataframes
Suppose I have a dataframe that looks likes this->
ID time-A time-B time-C
A 30 40 50
B NULL 60 50
C 30 20 50
I want to add a flag such that if time-A is NULL and time-B/time-c>=1 I put 'Y' flag otherwise I put 'N'
Desired result->
ID time-A time-B time-C Flag
A 30 40 50 N
B NULL 60 50 Y
C 30 20 50 N
A:
Could try this one :D
import numpy as np
df['Flag'] = np.where((df['time-A'].isna() & (df['time-B']>df['time-C'])), 'Y', 'N')
|
Adding flag according to a condition in Dataframes
|
Suppose I have a dataframe that looks likes this->
ID time-A time-B time-C
A 30 40 50
B NULL 60 50
C 30 20 50
I want to add a flag such that if time-A is NULL and time-B/time-c>=1 I put 'Y' flag otherwise I put 'N'
Desired result->
ID time-A time-B time-C Flag
A 30 40 50 N
B NULL 60 50 Y
C 30 20 50 N
|
[
"Could try this one :D\nimport numpy as np\ndf['Flag'] = np.where((df['time-A'].isna() & (df['time-B']>df['time-C'])), 'Y', 'N')\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"numpy",
"pandas",
"python"
] |
stackoverflow_0074514034_dataframe_numpy_pandas_python.txt
|
Q:
How to vertically stack the results of a for loop to a 2D array?
I've trained the CNN model to classify the images of 35 persons. To test the trained CNN model, I have used 70 images (2 from each person). The following for loop was written to predict the probabilities of the 70 images.
I need the predicted probabilities of 70 images (70 * 35) to be assigned to the ndarray predicted_probabilities.
actual_values_images = []
predicted_values_images = []
predicted_probabilities = np.empty((70, 35), int)
for testImage in test_image_folder:
img = folder_path+str(testImage)
img = image.load_img(img, target_size=(64, 64))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
result=classifier.predict(img,verbose=0)
actual_values_images.append(str(testImage[1:-4]))
predicted_probabilities = numpy.vstack([predicted_probabilities, result])
predicted_values_images.append(ResultMap[np.argmax(result)])
predicted_probabilities_images.append(result)
But when the above code is run, the shape of the predicted_probabilities will be (140, 35). Looks like the same result is vertically appended twice. How can I correctly append the probability values vertically to the 2D array to get a shape of (70, 35)?
A:
A simplest way is to assign results directly to the array.
actual_values_images = []
predicted_values_images = []
predicted_probabilities = np.empty((70, 35), int)
for index, testImage in enumerate(test_image_folder):
img = folder_path+str(testImage)
img = image.load_img(img, target_size=(64, 64))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
result=classifier.predict(img,verbose=0)
actual_values_images.append(str(testImage[1:-4]))
predicted_probabilities[index] = result[0] # assign directly to the array
predicted_values_images.append(ResultMap[np.argmax(result)])
predicted_probabilities_images.append(result)
A slightly better way is to collect the results in a list and then convert it to an array. But most efficient way is to process images in batches and then combine the results. Fast sketch:
def load2tensor(image_path):
img = image.load_img(image_path, target_size=(64, 64))
img = image.img_to_array(img)
return img
def batchify(images_list, actual_values, batch_size=32):
batch = []
batchNames = []
batchActual = []
for img, actual in zip(images_list, actual_values):
batchActual.append(actual)
batchNames.append(img)
batch.append(load2tensor(img))
if len(batch) == batch_size:
yield np.vstack(batch), batchNames, batchActual
batch = []
continue
if len(batch) > 0:
yield np.vstack(batch), batchNames, batchActual
return
actual_values_images = []
predicted_values_images = []
predicted_probabilities = []
for batch, names, actual in batchify(test_images, actual_values_images, batch_size=32):
result = classifier.predict(batch, verbose=0)
predicted_probabilities.append(result)
# ... rest of the code with actual_values_images, predicted_values_images
I'm not sure if this is totally correct, but it should give you a general idea.
|
How to vertically stack the results of a for loop to a 2D array?
|
I've trained the CNN model to classify the images of 35 persons. To test the trained CNN model, I have used 70 images (2 from each person). The following for loop was written to predict the probabilities of the 70 images.
I need the predicted probabilities of 70 images (70 * 35) to be assigned to the ndarray predicted_probabilities.
actual_values_images = []
predicted_values_images = []
predicted_probabilities = np.empty((70, 35), int)
for testImage in test_image_folder:
img = folder_path+str(testImage)
img = image.load_img(img, target_size=(64, 64))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
result=classifier.predict(img,verbose=0)
actual_values_images.append(str(testImage[1:-4]))
predicted_probabilities = numpy.vstack([predicted_probabilities, result])
predicted_values_images.append(ResultMap[np.argmax(result)])
predicted_probabilities_images.append(result)
But when the above code is run, the shape of the predicted_probabilities will be (140, 35). Looks like the same result is vertically appended twice. How can I correctly append the probability values vertically to the 2D array to get a shape of (70, 35)?
|
[
"A simplest way is to assign results directly to the array.\nactual_values_images = []\npredicted_values_images = []\npredicted_probabilities = np.empty((70, 35), int)\n\nfor index, testImage in enumerate(test_image_folder):\n img = folder_path+str(testImage)\n img = image.load_img(img, target_size=(64, 64))\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n\n result=classifier.predict(img,verbose=0) \n actual_values_images.append(str(testImage[1:-4]))\n\n predicted_probabilities[index] = result[0] # assign directly to the array\n \n predicted_values_images.append(ResultMap[np.argmax(result)])\n predicted_probabilities_images.append(result)\n\nA slightly better way is to collect the results in a list and then convert it to an array. But most efficient way is to process images in batches and then combine the results. Fast sketch:\ndef load2tensor(image_path):\n img = image.load_img(image_path, target_size=(64, 64))\n img = image.img_to_array(img)\n return img\n\ndef batchify(images_list, actual_values, batch_size=32):\n batch = []\n batchNames = []\n batchActual = []\n for img, actual in zip(images_list, actual_values):\n batchActual.append(actual)\n batchNames.append(img)\n batch.append(load2tensor(img))\n if len(batch) == batch_size:\n yield np.vstack(batch), batchNames, batchActual\n batch = []\n continue\n if len(batch) > 0:\n yield np.vstack(batch), batchNames, batchActual\n return\n\nactual_values_images = []\npredicted_values_images = []\npredicted_probabilities = []\n\nfor batch, names, actual in batchify(test_images, actual_values_images, batch_size=32):\n result = classifier.predict(batch, verbose=0)\n predicted_probabilities.append(result)\n # ... rest of the code with actual_values_images, predicted_values_images\n\n\nI'm not sure if this is totally correct, but it should give you a general idea.\n"
] |
[
1
] |
[] |
[] |
[
"for_loop",
"multidimensional_array",
"numpy_ndarray",
"python",
"vstack"
] |
stackoverflow_0074514008_for_loop_multidimensional_array_numpy_ndarray_python_vstack.txt
|
Q:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! when resuming training
I saved a checkpoint while training on gpu. After reloading the checkpoint and continue training I get the following error:
Traceback (most recent call last):
File "main.py", line 140, in <module>
train(model,optimizer,train_loader,val_loader,criteria=args.criterion,epoch=epoch,batch=batch)
File "main.py", line 71, in train
optimizer.step()
File "/opt/conda/lib/python3.7/site-packages/torch/autograd/grad_mode.py", line 26, in decorate_context
return func(*args, **kwargs)
File "/opt/conda/lib/python3.7/site-packages/torch/optim/sgd.py", line 106, in step
buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
My training code is as follows:
def train(model,optimizer,train_loader,val_loader,criteria,epoch=0,batch=0):
batch_count = batch
if criteria == 'l1':
criterion = L1_imp_Loss()
elif criteria == 'l2':
criterion = L2_imp_Loss()
if args.gpu and torch.cuda.is_available():
model.cuda()
criterion = criterion.cuda()
print(f'{datetime.datetime.now().time().replace(microsecond=0)} Starting to train..')
while epoch <= args.epochs-1:
print(f'********{datetime.datetime.now().time().replace(microsecond=0)} Epoch#: {epoch+1} / {args.epochs}')
model.train()
interval_loss, total_loss= 0,0
for i , (input,target) in enumerate(train_loader):
batch_count += 1
if args.gpu and torch.cuda.is_available():
input, target = input.cuda(), target.cuda()
input, target = input.float(), target.float()
pred = model(input)
loss = criterion(pred,target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
....
The saving process happened after finishing each epoch.
torch.save({'epoch': epoch,'batch':batch_count,'model_state_dict': model.state_dict(),'optimizer_state_dict':
optimizer.state_dict(),'loss': total_loss/len(train_loader),'train_set':args.train_set,'val_set':args.val_set,'args':args}, f'{args.weights_dir}/FastDepth_Final.pth')
I can't figure why I get this error.
args.gpu == True, and I'm passing the model, all data, and loss function to cuda, somehow there is still a tensor on cpu, could anyone figure out what's wrong?
Thanks.
A:
There might be an issue with the device parameters are on:
If you need to move a model to GPU via .cuda() , please do so before constructing optimizers for it. Parameters of a model after .cuda() will be different objects with those before the call.
In general, you should make sure that optimized parameters live in consistent locations when optimizers are constructed and used.
A:
Make sure to add .to(device) to both the model and the model inputs.
A:
I added below code at the start of the file. It solved my issue
os.environ['CUDA_VISIBLE_DEVICES'] ='0'
A:
this answer of Shirley Ow helped me
Make sure to add .to(device) to both the model and the model inputs.
img = torch.from_numpy(img).to(device) # Code in yolov7
A:
adding two lines below resolved the issue for me on colab.
(add in both saving and loading)
device = torch.device("cuda")
model.cuda()
note: if you are using google colab obviously you should set your colab runtime to GPU
A:
I'm going through the Fast AI 2022 course and trying to use my M1 Max. I've found that at least with some of the Fastbook code, I could set default_device(torch.device("mps")) and it would resolve my problems.
Here is a reusable snippet that I put at the top of the Jupyter Notebooks I've been dabbling in:
# Check that MPS is available
if not torch.backends.mps.is_available():
if not torch.backends.mps.is_built():
print("MPS not available because the current PyTorch install was not "
"built with MPS enabled.")
else:
print("MPS not available because the current MacOS version is not 12.3+ "
"and/or you do not have an MPS-enabled device on this machine.")
else:
print("MPS is available. Setting as default device.")
mps_device = torch.device("mps")
default_device(mps_device)
|
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! when resuming training
|
I saved a checkpoint while training on gpu. After reloading the checkpoint and continue training I get the following error:
Traceback (most recent call last):
File "main.py", line 140, in <module>
train(model,optimizer,train_loader,val_loader,criteria=args.criterion,epoch=epoch,batch=batch)
File "main.py", line 71, in train
optimizer.step()
File "/opt/conda/lib/python3.7/site-packages/torch/autograd/grad_mode.py", line 26, in decorate_context
return func(*args, **kwargs)
File "/opt/conda/lib/python3.7/site-packages/torch/optim/sgd.py", line 106, in step
buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
My training code is as follows:
def train(model,optimizer,train_loader,val_loader,criteria,epoch=0,batch=0):
batch_count = batch
if criteria == 'l1':
criterion = L1_imp_Loss()
elif criteria == 'l2':
criterion = L2_imp_Loss()
if args.gpu and torch.cuda.is_available():
model.cuda()
criterion = criterion.cuda()
print(f'{datetime.datetime.now().time().replace(microsecond=0)} Starting to train..')
while epoch <= args.epochs-1:
print(f'********{datetime.datetime.now().time().replace(microsecond=0)} Epoch#: {epoch+1} / {args.epochs}')
model.train()
interval_loss, total_loss= 0,0
for i , (input,target) in enumerate(train_loader):
batch_count += 1
if args.gpu and torch.cuda.is_available():
input, target = input.cuda(), target.cuda()
input, target = input.float(), target.float()
pred = model(input)
loss = criterion(pred,target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
....
The saving process happened after finishing each epoch.
torch.save({'epoch': epoch,'batch':batch_count,'model_state_dict': model.state_dict(),'optimizer_state_dict':
optimizer.state_dict(),'loss': total_loss/len(train_loader),'train_set':args.train_set,'val_set':args.val_set,'args':args}, f'{args.weights_dir}/FastDepth_Final.pth')
I can't figure why I get this error.
args.gpu == True, and I'm passing the model, all data, and loss function to cuda, somehow there is still a tensor on cpu, could anyone figure out what's wrong?
Thanks.
|
[
"There might be an issue with the device parameters are on:\n\nIf you need to move a model to GPU via .cuda() , please do so before constructing optimizers for it. Parameters of a model after .cuda() will be different objects with those before the call.\nIn general, you should make sure that optimized parameters live in consistent locations when optimizers are constructed and used.\n\n",
"Make sure to add .to(device) to both the model and the model inputs.\n",
"I added below code at the start of the file. It solved my issue\nos.environ['CUDA_VISIBLE_DEVICES'] ='0'\n",
"this answer of Shirley Ow helped me\nMake sure to add .to(device) to both the model and the model inputs.\nimg = torch.from_numpy(img).to(device) # Code in yolov7\n\n",
"adding two lines below resolved the issue for me on colab.\n(add in both saving and loading)\ndevice = torch.device(\"cuda\")\nmodel.cuda()\n\nnote: if you are using google colab obviously you should set your colab runtime to GPU\n",
"I'm going through the Fast AI 2022 course and trying to use my M1 Max. I've found that at least with some of the Fastbook code, I could set default_device(torch.device(\"mps\")) and it would resolve my problems.\nHere is a reusable snippet that I put at the top of the Jupyter Notebooks I've been dabbling in:\n# Check that MPS is available\nif not torch.backends.mps.is_available():\n if not torch.backends.mps.is_built():\n print(\"MPS not available because the current PyTorch install was not \"\n \"built with MPS enabled.\")\n else:\n print(\"MPS not available because the current MacOS version is not 12.3+ \"\n \"and/or you do not have an MPS-enabled device on this machine.\")\n\nelse:\n print(\"MPS is available. Setting as default device.\")\n mps_device = torch.device(\"mps\")\n default_device(mps_device)\n\n"
] |
[
28,
3,
0,
0,
0,
0
] |
[] |
[] |
[
"deep_learning",
"python",
"pytorch",
"runtime_error"
] |
stackoverflow_0066091226_deep_learning_python_pytorch_runtime_error.txt
|
Q:
How to control Newport controller model 8742 with python?
I have the Newport New Focus Picomotor Controller/Driver, Model 8742, and it comes with software to control the motors. I want to be able to command the controller with python. There is a similar question here already but for some reason that code is not working for me. So far I have
import serial as s
from time import sleep
try:
s.Serial.close()
except:
pass
ser= s.Serial('COMX',baudrate=921600,timeout=1.0,parity=s.PARITY_NONE,stopbits=s.STOPBITS_ONE,bytesize=s.EIGHTBITS)
command = '1PAU0.00\r\n'
bcommand = bytes(command,'UTF-8')
a = ser.write(bcommand)
sleep(0.1)
print(ser.read(10))
ser.close()
Part of the problem is that I'm not sure what port number I put in the code where 'COMX' is inserted. This is my first time using python for serial communication, so any help is appreciated. Thank you.
A:
The USB driver for 8742 / 8743 controllers does not expose an actual serial port. However, you can communicate using ASCII commands thru its USB endpoints on any operating system, which can be done with PyUSB. Here's an excellent starting point: https://github.com/bdhammel/python_newport_controller
|
How to control Newport controller model 8742 with python?
|
I have the Newport New Focus Picomotor Controller/Driver, Model 8742, and it comes with software to control the motors. I want to be able to command the controller with python. There is a similar question here already but for some reason that code is not working for me. So far I have
import serial as s
from time import sleep
try:
s.Serial.close()
except:
pass
ser= s.Serial('COMX',baudrate=921600,timeout=1.0,parity=s.PARITY_NONE,stopbits=s.STOPBITS_ONE,bytesize=s.EIGHTBITS)
command = '1PAU0.00\r\n'
bcommand = bytes(command,'UTF-8')
a = ser.write(bcommand)
sleep(0.1)
print(ser.read(10))
ser.close()
Part of the problem is that I'm not sure what port number I put in the code where 'COMX' is inserted. This is my first time using python for serial communication, so any help is appreciated. Thank you.
|
[
"The USB driver for 8742 / 8743 controllers does not expose an actual serial port. However, you can communicate using ASCII commands thru its USB endpoints on any operating system, which can be done with PyUSB. Here's an excellent starting point: https://github.com/bdhammel/python_newport_controller\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0045575568_python.txt
|
Q:
How to run background tasks in python
I'm developing a small web service with Flask which needs to run background tasks, preferably from a task queue. However, after googling the subject the only results were essentially Celery and Redis Queue, which apparently require separate queuing services and thus are options that are far too heavy and convoluted to deploy. As all I'm looking for is a simple background task queue that enables tasks to be queued and executed on separate threads/processes, does anyone know if there is anything like this available in Python?
A:
import threading
import time
class BackgroundTasks(threading.Thread):
def run(self,*args,**kwargs):
while True:
print('Hello')
time.sleep(1)
t = BackgroundTasks()
t.start()
After the while statement , you can put the code you want to run in background. Maybe deleting some models , sending email or whatever.
A:
The asyncio library might be what you are looking for
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
# Python 3.7+
asyncio.run(main())
A:
If you are using FastAPI, there is already implementation of BackgroundTasks
You don't need to implement Threading and Queues for doing background tasks after receiving the request.
Code Implementation:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
# function that will run in background after sending the response
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Tasks are happening in background"}
|
How to run background tasks in python
|
I'm developing a small web service with Flask which needs to run background tasks, preferably from a task queue. However, after googling the subject the only results were essentially Celery and Redis Queue, which apparently require separate queuing services and thus are options that are far too heavy and convoluted to deploy. As all I'm looking for is a simple background task queue that enables tasks to be queued and executed on separate threads/processes, does anyone know if there is anything like this available in Python?
|
[
"import threading\nimport time\n\nclass BackgroundTasks(threading.Thread):\n def run(self,*args,**kwargs):\n while True:\n print('Hello')\n time.sleep(1)\n\nt = BackgroundTasks()\nt.start()\n\nAfter the while statement , you can put the code you want to run in background. Maybe deleting some models , sending email or whatever.\n",
"The asyncio library might be what you are looking for \nimport asyncio\n\nasync def main():\n print('Hello ...')\n await asyncio.sleep(1)\n print('... World!')\n\n# Python 3.7+\nasyncio.run(main())\n\n",
"If you are using FastAPI, there is already implementation of BackgroundTasks\nYou don't need to implement Threading and Queues for doing background tasks after receiving the request.\nCode Implementation:\nfrom fastapi import BackgroundTasks, FastAPI\n\napp = FastAPI()\n\n# function that will run in background after sending the response\ndef write_notification(email: str, message=\"\"):\n with open(\"log.txt\", mode=\"w\") as email_file:\n content = f\"notification for {email}: {message}\"\n email_file.write(content)\n\n\n@app.post(\"/send-notification/{email}\")\nasync def send_notification(email: str, background_tasks: BackgroundTasks):\n background_tasks.add_task(write_notification, email, message=\"some notification\")\n return {\"message\": \"Tasks are happening in background\"}\n\n\n"
] |
[
8,
5,
0
] |
[] |
[] |
[
"multithreading",
"python",
"python_3.x"
] |
stackoverflow_0059850517_multithreading_python_python_3.x.txt
|
Q:
tkinter Image is not displayed unless the mainloop() is called in the same class
I am new to tkinter and encounter this strange behavior with the images.
Please pay attention to the *.mainloop() in the code below.
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class BaseWindow(tk.Tk):
def __init__(self):
super(BaseWindow, self).__init__()
self.geometry("800x700")
self.title("test title")
frame = ttk.Frame(self)
frame.pack()
ttk.Label(frame, text="test label").pack()
img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(frame, image=img).pack()
frame_parent = ttk.Frame(self)
frame_parent.pack()
ParentWindow(frame_parent, self)
# self.mainloop()
class ParentWindow(ttk.Frame):
def __init__(self, parent, app):
super(ParentWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="parent label test").pack()
img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(self, image=img).pack()
ttk.Label(self, text="test label").pack()
frame_child = ttk.Frame(self)
frame_child.pack()
ChildWindow(frame_child, app)
# app.mainloop()
class ChildWindow(ttk.Frame):
def __init__(self, parent, app):
super(ChildWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="child label test").pack()
img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(self, image=img).pack()
ttk.Label(self, text="test label").pack()
# app.mainloop()
if __name__ == '__main__':
# BaseWindow().mainloop()
BaseWindow()
There are three classes, but the image is created by each class is shown only if the mainloop() is called in the respective class.
All the other widgets work just fine regardless of where I call the mainloop() for instance the Label() widget as in example code below.
Only the images do not display if I don't call the mainloop() in the proper way.
Explaination
1.) if name == .............. in this block if I call the BaseWindow().mainloop() then everything works fine, all the widgets are displayed, but the images are not displayed.
Images created in all the classes are not shown.
2.) class BaseWindow()....... if the self.mainloop() is called here then, one image i.e. image created in this class is shown/displayed and other images are not displayed.
3.) class ParentWindow().......... if the app.mainloop() is called here then, two images are displayed, i.e. the image created in the BaseWindow class and ParentWindow class are displayed.
4.) similarly the image in the ChildWindow() class is only displayed if the app.mainloop() is called in this class.
So, in order to display all the images, I need to call the mainloop in the last class, but in this way, I need to pass the app object to all the child classes.
Isn't there a way to call mainloop only once in the app and get everything work.?
How do I display the images by calling mainloop() only in the BaseWindow() class...?
A:
I beginner at this stuff but I think you do need all of those .mainloop() because it updates the UI. But I am not sure. Hope you get more answers!
A:
Here i have some thing for you. You can add a single line in child Window class and your problem will be solved.
class ChildWindow(ttk.Frame):
def __init__(self, parent, app):
super(ChildWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="child label test").pack()
img = ImageTk.PhotoImage(Image.open("COMSATS.png").resize((200, 200)))
ttk.Label(self, image=img).pack()
ttk.Label(self, text="test label").pack()
self.mainloop()
Add self.mainloop() at the end of last class you have to visit.
self.mainloop()
Then,
if __name__ == '__main__':
BaseWindow()
All the images will be displayed at once.
A:
I figured out a way. The following solutions works fine. But I don't know if its the correct way. Correct me if I'm wrong...
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class BaseWindow(tk.Tk):
def __init__(self):
super(BaseWindow, self).__init__()
self.geometry("800x700")
self.title("test title")
frame = ttk.Frame(self)
frame.pack()
ttk.Label(frame, text="test label").pack()
self.__img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(frame, image=self.__img).pack()
frame_parent = ttk.Frame(self)
frame_parent.pack()
ParentWindow(frame_parent, self)
class ParentWindow(ttk.Frame):
def __init__(self, parent, app):
super(ParentWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="parent label test").pack()
self.__img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(self, image=self.__img).pack()
ttk.Label(self, text="test label").pack()
frame_child = ttk.Frame(self)
frame_child.pack()
ChildWindow(frame_child, app)
class ChildWindow(ttk.Frame):
def __init__(self, parent, app):
super(ChildWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="child label test").pack()
self.__img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(self, image=self.__img).pack()
ttk.Label(self, text="test label").pack()
if __name__ == '__main__':
BaseWindow().mainloop()
|
tkinter Image is not displayed unless the mainloop() is called in the same class
|
I am new to tkinter and encounter this strange behavior with the images.
Please pay attention to the *.mainloop() in the code below.
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class BaseWindow(tk.Tk):
def __init__(self):
super(BaseWindow, self).__init__()
self.geometry("800x700")
self.title("test title")
frame = ttk.Frame(self)
frame.pack()
ttk.Label(frame, text="test label").pack()
img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(frame, image=img).pack()
frame_parent = ttk.Frame(self)
frame_parent.pack()
ParentWindow(frame_parent, self)
# self.mainloop()
class ParentWindow(ttk.Frame):
def __init__(self, parent, app):
super(ParentWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="parent label test").pack()
img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(self, image=img).pack()
ttk.Label(self, text="test label").pack()
frame_child = ttk.Frame(self)
frame_child.pack()
ChildWindow(frame_child, app)
# app.mainloop()
class ChildWindow(ttk.Frame):
def __init__(self, parent, app):
super(ChildWindow, self).__init__(parent)
self.pack()
ttk.Label(self, text="child label test").pack()
img = ImageTk.PhotoImage(Image.open("res/male_avatar.png").resize(
(200, 200)))
ttk.Label(self, image=img).pack()
ttk.Label(self, text="test label").pack()
# app.mainloop()
if __name__ == '__main__':
# BaseWindow().mainloop()
BaseWindow()
There are three classes, but the image is created by each class is shown only if the mainloop() is called in the respective class.
All the other widgets work just fine regardless of where I call the mainloop() for instance the Label() widget as in example code below.
Only the images do not display if I don't call the mainloop() in the proper way.
Explaination
1.) if name == .............. in this block if I call the BaseWindow().mainloop() then everything works fine, all the widgets are displayed, but the images are not displayed.
Images created in all the classes are not shown.
2.) class BaseWindow()....... if the self.mainloop() is called here then, one image i.e. image created in this class is shown/displayed and other images are not displayed.
3.) class ParentWindow().......... if the app.mainloop() is called here then, two images are displayed, i.e. the image created in the BaseWindow class and ParentWindow class are displayed.
4.) similarly the image in the ChildWindow() class is only displayed if the app.mainloop() is called in this class.
So, in order to display all the images, I need to call the mainloop in the last class, but in this way, I need to pass the app object to all the child classes.
Isn't there a way to call mainloop only once in the app and get everything work.?
How do I display the images by calling mainloop() only in the BaseWindow() class...?
|
[
"I beginner at this stuff but I think you do need all of those .mainloop() because it updates the UI. But I am not sure. Hope you get more answers!\n",
"Here i have some thing for you. You can add a single line in child Window class and your problem will be solved.\nclass ChildWindow(ttk.Frame):\ndef __init__(self, parent, app):\n super(ChildWindow, self).__init__(parent)\n self.pack()\n ttk.Label(self, text=\"child label test\").pack()\n\n img = ImageTk.PhotoImage(Image.open(\"COMSATS.png\").resize((200, 200)))\n ttk.Label(self, image=img).pack()\n ttk.Label(self, text=\"test label\").pack()\n self.mainloop()\n\nAdd self.mainloop() at the end of last class you have to visit.\nself.mainloop()\n\nThen,\nif __name__ == '__main__':\nBaseWindow()\n\nAll the images will be displayed at once.\n",
"I figured out a way. The following solutions works fine. But I don't know if its the correct way. Correct me if I'm wrong...\nimport tkinter as tk\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\n\nclass BaseWindow(tk.Tk):\n def __init__(self):\n super(BaseWindow, self).__init__()\n self.geometry(\"800x700\")\n self.title(\"test title\")\n\n frame = ttk.Frame(self)\n frame.pack()\n ttk.Label(frame, text=\"test label\").pack()\n self.__img = ImageTk.PhotoImage(Image.open(\"res/male_avatar.png\").resize(\n (200, 200)))\n ttk.Label(frame, image=self.__img).pack()\n\n frame_parent = ttk.Frame(self)\n frame_parent.pack()\n\n ParentWindow(frame_parent, self)\n\n\nclass ParentWindow(ttk.Frame):\n def __init__(self, parent, app):\n super(ParentWindow, self).__init__(parent)\n self.pack()\n ttk.Label(self, text=\"parent label test\").pack()\n\n self.__img = ImageTk.PhotoImage(Image.open(\"res/male_avatar.png\").resize(\n (200, 200)))\n ttk.Label(self, image=self.__img).pack()\n ttk.Label(self, text=\"test label\").pack()\n\n frame_child = ttk.Frame(self)\n frame_child.pack()\n\n ChildWindow(frame_child, app)\n\n\nclass ChildWindow(ttk.Frame):\n def __init__(self, parent, app):\n super(ChildWindow, self).__init__(parent)\n self.pack()\n ttk.Label(self, text=\"child label test\").pack()\n\n self.__img = ImageTk.PhotoImage(Image.open(\"res/male_avatar.png\").resize(\n (200, 200)))\n ttk.Label(self, image=self.__img).pack()\n ttk.Label(self, text=\"test label\").pack()\n\n\nif __name__ == '__main__':\n BaseWindow().mainloop()\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python",
"python_imaging_library",
"tkinter"
] |
stackoverflow_0074510343_python_python_imaging_library_tkinter.txt
|
Q:
Why am i getting "Name Error : name x is not defiened" in this program?
# UNQ_C2
# GRADED FUNCTION: compute_gradient
def compute_gradient(x, y, w, b):
"""
Computes the gradient for linear regression
Args:
x (ndarray): Shape (m,) Input to the model (Population of cities)
y (ndarray): Shape (m,) Label (Actual profits for the cities)
w, b (scalar): Parameters of the model
Returns
dj_dw (scalar): The gradient of the cost w.r.t. the parameters w
dj_db (scalar): The gradient of the cost w.r.t. the parameter b
"""
# Number of training examples
n = x.shape[0]
# You need to return the following variables correctly
dj_dw = 0
dj_db = 0
### START CODE HERE ###
for i in range (n):
f_wb = w*x[i] + b
dj_db_i = f_wb - y[i]
dj_db += dj_db_i
dj_dw_i = (f_wb - y[i]) * [i]
dj_dw += dj_dw_i
dj_dw = dj_dw / m
dj_db = dj_db / m
### END CODE HERE ###
return dj_dw, dj_db
I was trying to run this code of compute gradient dj/wb, dj/db and I was getting the Name Error: name X is not defined in this program if anyone is having a solution to my problem thay can post it below.
I will be really thankful if anyone will be able to solve my problem, I am stuck on this problem from the past few days.
A:
Here, x must be your input which you have not specified anywhere. When you try to do a shape on something that has not even been set up/defined yet you encountered this error. Try something like assigning x = your_input_array/matrix etc before you do a shape on it.
|
Why am i getting "Name Error : name x is not defiened" in this program?
|
# UNQ_C2
# GRADED FUNCTION: compute_gradient
def compute_gradient(x, y, w, b):
"""
Computes the gradient for linear regression
Args:
x (ndarray): Shape (m,) Input to the model (Population of cities)
y (ndarray): Shape (m,) Label (Actual profits for the cities)
w, b (scalar): Parameters of the model
Returns
dj_dw (scalar): The gradient of the cost w.r.t. the parameters w
dj_db (scalar): The gradient of the cost w.r.t. the parameter b
"""
# Number of training examples
n = x.shape[0]
# You need to return the following variables correctly
dj_dw = 0
dj_db = 0
### START CODE HERE ###
for i in range (n):
f_wb = w*x[i] + b
dj_db_i = f_wb - y[i]
dj_db += dj_db_i
dj_dw_i = (f_wb - y[i]) * [i]
dj_dw += dj_dw_i
dj_dw = dj_dw / m
dj_db = dj_db / m
### END CODE HERE ###
return dj_dw, dj_db
I was trying to run this code of compute gradient dj/wb, dj/db and I was getting the Name Error: name X is not defined in this program if anyone is having a solution to my problem thay can post it below.
I will be really thankful if anyone will be able to solve my problem, I am stuck on this problem from the past few days.
|
[
"Here, x must be your input which you have not specified anywhere. When you try to do a shape on something that has not even been set up/defined yet you encountered this error. Try something like assigning x = your_input_array/matrix etc before you do a shape on it.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074514182_python.txt
|
Q:
How to split a 2D array into a list of smaller 2D arrays with overlapping? Python
I want to split a 2D array x * y into some smaller 2D arrays which are N * N with overlapping and store these smaller arrays as values in a dictionary, the key will be the index of the top-left item in the larger array.
From
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
To
{(0,0):[[1,2],[5,6]], (0,1):[[2,3],[6,7]], (0,2):[[3,4],[7,8]], (1,0):[[5,6],[9,10]], (1,1):[[6,7],[10,11]], (1,2):[[7,8],[11,12]]}
I have idea of splitting it into smaller arrays without overlapping using numpy, but I have no idea of this case.
How can this be done? Full of thanks!
A:
The operation you want to do is a sliding window.
import numpy as np
A = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
result = dict(zip(
[(i, j) for i in range(2) for j in range(3)],
np.lib.stride_tricks.sliding_window_view(A, (2, 2)).reshape(-1, 2, 2).tolist()
))
# {(0, 0): [[1, 2], [5, 6]], (0, 1): [[2, 3], [6, 7]], (0, 2): [[3, 4], [7, 8]], (1, 0): [[5, 6], [9, 10]], (1, 1): [[6, 7], [10, 11]], (1, 2): [[7, 8], [11, 12]]}
|
How to split a 2D array into a list of smaller 2D arrays with overlapping? Python
|
I want to split a 2D array x * y into some smaller 2D arrays which are N * N with overlapping and store these smaller arrays as values in a dictionary, the key will be the index of the top-left item in the larger array.
From
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
To
{(0,0):[[1,2],[5,6]], (0,1):[[2,3],[6,7]], (0,2):[[3,4],[7,8]], (1,0):[[5,6],[9,10]], (1,1):[[6,7],[10,11]], (1,2):[[7,8],[11,12]]}
I have idea of splitting it into smaller arrays without overlapping using numpy, but I have no idea of this case.
How can this be done? Full of thanks!
|
[
"The operation you want to do is a sliding window.\nimport numpy as np\n\nA = np.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]\n])\n\nresult = dict(zip(\n [(i, j) for i in range(2) for j in range(3)],\n np.lib.stride_tricks.sliding_window_view(A, (2, 2)).reshape(-1, 2, 2).tolist()\n))\n\n# {(0, 0): [[1, 2], [5, 6]], (0, 1): [[2, 3], [6, 7]], (0, 2): [[3, 4], [7, 8]], (1, 0): [[5, 6], [9, 10]], (1, 1): [[6, 7], [10, 11]], (1, 2): [[7, 8], [11, 12]]}\n\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"numpy",
"python"
] |
stackoverflow_0074513892_arrays_numpy_python.txt
|
Q:
how to round off a float
i want to round off a float to 3 dp in python with 00 in the end if the float don't have 3 dp
like 15.4 into 15.400
thank you.
programme:
x=round(15.4)
result:
15.400
A:
The "rounding" you are talking about can only be done if you convert the float to a string. This is usually only done for display purposes. In this case you can use a so-called f-string to do this formatting:
x = 15.4
print(f"{x:.3f}")
A:
Hello its pretty simple you can do something like this
a=15.4
b=("%.3f" % a)
print(b)
A:
15.4 and 15.400 are the same number. round() returns a number. What you want is to have a different representation when you convert it to a string.
You need to do string formatting. Just copying the other answers here, there are two ways.
f-strings:
n = 15.4
n_str = f"{n:.3f}"
%-formatting:
n_str = "%.3f" % n
|
how to round off a float
|
i want to round off a float to 3 dp in python with 00 in the end if the float don't have 3 dp
like 15.4 into 15.400
thank you.
programme:
x=round(15.4)
result:
15.400
|
[
"The \"rounding\" you are talking about can only be done if you convert the float to a string. This is usually only done for display purposes. In this case you can use a so-called f-string to do this formatting:\nx = 15.4\nprint(f\"{x:.3f}\")\n\n",
"Hello its pretty simple you can do something like this\na=15.4\nb=(\"%.3f\" % a)\nprint(b)\n\n",
"15.4 and 15.400 are the same number. round() returns a number. What you want is to have a different representation when you convert it to a string.\nYou need to do string formatting. Just copying the other answers here, there are two ways.\n\nf-strings:\n\nn = 15.4\nn_str = f\"{n:.3f}\"\n\n\n%-formatting:\n\nn_str = \"%.3f\" % n\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074514179_python.txt
|
Q:
I want to Remove the addition symbol from in-between the numbers using python and please find the below my code
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
This is my output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
I want the + symbol only in between the numbers.Not to be in the last or the first.
A:
A likely solution is using " + ".join(), which uses the string method on the " + " to collect the values together
>>> values = "1 2 3 4 5".split()
>>> " + ".join(values)
'1 + 2 + 3 + 4 + 5'
A:
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
if count != limit:
allvalue += str(number) + " + "
else:
allvalue += str(number)
print(allvalue)
Hope this help.
A:
I would like to share with you a sure shot mathematical solution to this problem.
This problem is a typical variation of Sum of n numbers problem, where the sum depicting limit here is already given as input, instead of n.
import math
limit = int(input("Limit: ")) # n * (n + 1) / 2 >= limit
n = math.ceil( ((1 + 4*2*limit)**0.5 - 1) / 2 ) # ((b^2 - 4ac)^(1/2) - b) / 2a where a = b = 1, c = 2*limit
allValue = " + ".join([str(i) for i in range(1, n+1)])
print(allValue)
A:
You don't need both the number and count variables, and by starting from initial value you can add the + before the number.
limit = int(input("Limit: "))
count = 1
allvalue = str(count)
while count < limit:
count += 1
allvalue += " + " + str(count)
print(allvalue)
A:
You could also try using a for loop.
limit = int(input("Limit: "))
allvalue = ""
for i in range(0, limit):
if i+1 == limit:
allvalue += str(i+1)
else:
allvalue += str(i+1) + "+"
print(allvalue)
A:
Here is simple and easy approach, you can try slice in the result string
print(allvalue[:-2])
code:
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
print(allvalue[:-2])
output:
result shared : https://onlinegdb.com/HFC2Hv4wq
Limit: 9
1 + 2 + 3 + 4 +
1 + 2 + 3 + 4
|
I want to Remove the addition symbol from in-between the numbers using python and please find the below my code
|
limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
number += 1
count += number
allvalue += str(number) + " + "
print(allvalue)
This is my output 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
I want the + symbol only in between the numbers.Not to be in the last or the first.
|
[
"A likely solution is using \" + \".join(), which uses the string method on the \" + \" to collect the values together\n>>> values = \"1 2 3 4 5\".split()\n>>> \" + \".join(values)\n'1 + 2 + 3 + 4 + 5'\n\n",
"limit = int(input(\"Limit: \"))\nallvalue = \"\"\ncount = 0\nnumber = 0\nwhile count < limit:\n number += 1\n count += number\n if count != limit:\n allvalue += str(number) + \" + \" \n else:\n allvalue += str(number)\n\nprint(allvalue)\n\nHope this help.\n",
"I would like to share with you a sure shot mathematical solution to this problem.\n\nThis problem is a typical variation of Sum of n numbers problem, where the sum depicting limit here is already given as input, instead of n.\n\nimport math\n\nlimit = int(input(\"Limit: \")) # n * (n + 1) / 2 >= limit\nn = math.ceil( ((1 + 4*2*limit)**0.5 - 1) / 2 ) # ((b^2 - 4ac)^(1/2) - b) / 2a where a = b = 1, c = 2*limit\n\nallValue = \" + \".join([str(i) for i in range(1, n+1)])\nprint(allValue)\n\n",
"You don't need both the number and count variables, and by starting from initial value you can add the + before the number.\nlimit = int(input(\"Limit: \"))\ncount = 1\nallvalue = str(count)\nwhile count < limit:\n count += 1\n allvalue += \" + \" + str(count)\n \nprint(allvalue)\n\n",
"You could also try using a for loop.\nlimit = int(input(\"Limit: \"))\nallvalue = \"\"\n\nfor i in range(0, limit):\n if i+1 == limit:\n allvalue += str(i+1)\n else:\n allvalue += str(i+1) + \"+\"\n\nprint(allvalue)\n\n",
"Here is simple and easy approach, you can try slice in the result string\nprint(allvalue[:-2])\n\ncode:\nlimit = int(input(\"Limit: \"))\nallvalue = \"\"\ncount = 0\nnumber = 0\n\n\nwhile count < limit:\n number += 1\n count += number \n allvalue += str(number) + \" + \"\n\nprint(allvalue)\nprint(allvalue[:-2])\n\noutput:\nresult shared : https://onlinegdb.com/HFC2Hv4wq\nLimit: 9\n1 + 2 + 3 + 4 + \n1 + 2 + 3 + 4 \n\n"
] |
[
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074514064_python_python_3.x.txt
|
Q:
Disapprove password if it contains exactly 4 digits (validation)
I can't figure out how to modify my regex to make sure the password follows the last condition:
at least 2 capital letters in a row
doesn't have space symbols
contains digits
doesn't contain 4 consecutive digits
{4} It currently disapproves the password if it has 4 and more digits but I need it to disapprove the password with EXACTLY 4 digits.
s1 = 'annII#443'
s2 = 'annII#4343'
s3 = 'annII#43434'
pattern = r"^(?=.*[A-Z]{2,})(?=.*[A-Za-z])(?=.*[0-9])(?!.*[0-9]{4})(?!.*[\s]).*$"
re.findall(pattern, s1) # ['aШnnII#443']
re.findall(pattern, s2) # []
re.findall(pattern, s3) # []
PS: It's just a task so don't worry. It's not gonna be used for any real purposes.
A:
To match exactly four digits, you can use at start ^ e.g. (?!(?:.*\D)?\d{4}(?!\d)).
This requires start or a \D non-digit before the 4 digits and disallows a digit after.
(?=.*[A-Za-z]) looks redundant if you already require (?=.*[A-Z]{2,}) (2 upper).
{2,} two or more is redundant. {2} would suffice and does not change the logic.
Instead of (?!.*[\s]).*$ you can just use \S*$ (upper matches non-whitespaces).
It's generally more efficient to use lazy .*? or even a negated class where possible.
^(?=[^A-Z]*[A-Z]{2})(?=\D*\d)(?!(?:.*\D)?\d{4}(?!\d))\S*$
See this demo at regex101 (added \n to negations in multiline demo for staying in line)
|
Disapprove password if it contains exactly 4 digits (validation)
|
I can't figure out how to modify my regex to make sure the password follows the last condition:
at least 2 capital letters in a row
doesn't have space symbols
contains digits
doesn't contain 4 consecutive digits
{4} It currently disapproves the password if it has 4 and more digits but I need it to disapprove the password with EXACTLY 4 digits.
s1 = 'annII#443'
s2 = 'annII#4343'
s3 = 'annII#43434'
pattern = r"^(?=.*[A-Z]{2,})(?=.*[A-Za-z])(?=.*[0-9])(?!.*[0-9]{4})(?!.*[\s]).*$"
re.findall(pattern, s1) # ['aШnnII#443']
re.findall(pattern, s2) # []
re.findall(pattern, s3) # []
PS: It's just a task so don't worry. It's not gonna be used for any real purposes.
|
[
"\nTo match exactly four digits, you can use at start ^ e.g. (?!(?:.*\\D)?\\d{4}(?!\\d)).\nThis requires start or a \\D non-digit before the 4 digits and disallows a digit after.\n(?=.*[A-Za-z]) looks redundant if you already require (?=.*[A-Z]{2,}) (2 upper).\n{2,} two or more is redundant. {2} would suffice and does not change the logic.\nInstead of (?!.*[\\s]).*$ you can just use \\S*$ (upper matches non-whitespaces).\nIt's generally more efficient to use lazy .*? or even a negated class where possible.\n\n^(?=[^A-Z]*[A-Z]{2})(?=\\D*\\d)(?!(?:.*\\D)?\\d{4}(?!\\d))\\S*$\n\nSee this demo at regex101 (added \\n to negations in multiline demo for staying in line)\n"
] |
[
1
] |
[] |
[] |
[
"python",
"regex",
"validation"
] |
stackoverflow_0074511690_python_regex_validation.txt
|
Q:
How can I detect collision in pygame while using colliderect() to make an object disappear without using sprites?
I have two classes that both create squares. One that puts squares randomly in the window and another that the user can control. I need to detect collision between them but I keep getting an error that the I need a rect style object when I use the colliderect() function. I am pretty sure my drawings are rects but I might be wrong.
I tried using the win.blit method to use draw my rects but I cannot make that work and need some help
import random
import pygame
pygame.init() # initialize pygame managers
# create a window
w = 600
h = 600
win = pygame.display.set_mode((w,h)) # define window variable
# pygame.display.set_caption("Read carefully.")
#global variables
WHITE = (255,255,255) # some handy RGB values
BLACK = (0,0,0)
YELLOW = (255, 186, 8)
x = random.randint(0,600)
y = random.randint(0,600)
#======================== Variables & functions ===================================================
#where we will create our class
#attributes of our class defining our object
def main():
class Enemy1():
color: str
radius: int
x: int
y: int
def __init__(self, color, radius, x=100, y=100):
self.color = color
self.radius = radius
self.x= x
self.y = y
self.w = 50
self.h = 50
self.appear = True
self.red = pygame.draw.rect(win,self.color,(self.y,self.x,self.w,self.h))
def move_rect(self):
if self.appear == True:
self.red = pygame.draw.rect(win,self.color,(self.y,self.x,self.w,self.h))
def collide(self):
if (self.appear):
if self.red.colliderect(self):
self.appear = False
class Player():
def __init__(self):
self.y = 300
self.x= 300
self.w = 100
self.h = 100
self.color = WHITE
self.appear = True
self.circle = pygame.draw.rect(win,self.color,(self.x,self.y,self.w,self.h))
def spawn(self):
if self.appear == True:
self.circle = pygame.draw.rect(win,self.color,(self.x,self.y,self.w,self.h))
def keyPress(self, event, step= 20, up=pygame.K_UP, down=pygame.K_DOWN, left=pygame.K_LEFT, right=pygame.K_RIGHT):
if event.type == pygame.KEYDOWN:
if event.key == up:
self.y -= step
elif event.key == down:
self.y += step
elif event.key == left:
self.x -= step
elif event.key == right:
self.x += step
#creating a player
player = Player()
red = Enemy1((229,190,237), 20, 200, 150) # creating an enemy 1
small = Enemy1((124,144,219), 15, 30, 130) # creating an enemy 2
circle = Enemy1((115,107,146), 25, 150, 50) # creating an enemy 3
#================================ Animation loop ===================================================
# start run function def here
running = True
clock = pygame.time.Clock() # for framerate timing
#starting the animation loop
while running:
win.fill(BLACK)
#================== Your animation tasks ================
# call functions, increment values
player.spawn()
red.move_rect()
small.move_rect()
for event in pygame.event.get():
player.keyPress(event)
#================== Interactinos ================
# This loop allows windows when exit is clicked.
# Do not change, remove or augment this loop...yet.
# stop conditional would go here
#player.collide(red.move_rect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # stops animation
pygame.quit() # stops running code & closes window
#================== Animation control ===================
pygame.display.update()
clock.tick(60) # framerate in fps (30-60 is typical)
main()
# pygame.display.quit() # uncomment to automatically close window at end of animation
A:
You do have a rectangle, but it's not a PyGame Rect. The collision functions can only be used with a Rect.
The Rect is really handy. The code doesn't need to store x, y, w, h ... all these can be put into a Rect:
class Player():
def __init__(self):
self.rect = pygame.Rect( 300, 300, 100, 100 )
self.color = WHITE
self.appear = True
If ever you do want access to the x, y, width, height - these are all still available from the Rect: self.rect.x, self.rect.height, etc.
This makes the collision checking simple:
class Player():
# ...
def collidesWith( self, other_rect ):
collides = self.rect.colliderect( other_rect ) #<<-- HERE
if ( collides ):
print( "Player collides" )
return collides
I made a similar change to the Enemy class. This allows the code to make a list of all Enemy1 objects, then iterate through them, testing for collisions:
enemies = [ red, small, circle ]
# ...
while running:
# check for collision with every enemy
for enemy in enemies:
enemy.collidesWith( player.rect )
Full code:
import random
import pygame
pygame.init() # initialize pygame managers
# create a window
w = 600
h = 600
win = pygame.display.set_mode((w,h)) # define window variable
# pygame.display.set_caption("Read carefully.")
#global variables
WHITE = (255,255,255) # some handy RGB values
BLACK = (0,0,0)
YELLOW = (255, 186, 8)
x = random.randint(0,600)
y = random.randint(0,600)
#======================== Variables & functions ===================
#where we will create our class
#attributes of our class defining our object
def main():
class Enemy1():
color: str
radius: int
x: int
y: int
def __init__(self, color, radius, x=100, y=100):
self.color = color
self.radius = radius
self.rect = pygame.Rect( x, y, 50, 50 )
self.appear = True
def move_rect(self):
if self.appear == True:
pygame.draw.rect( win, self.color, self.rect )
def collidesWith( self, other_rect ):
collides = self.rect.colliderect( other_rect )
if (self.appear):
if collides:
print( "Enemy1 collides" )
self.appear = False
return collides;
class Player():
def __init__(self):
self.rect = pygame.Rect( 300, 300, 100, 100 )
self.color = WHITE
self.appear = True
def spawn(self):
if self.appear == True:
self.circle = pygame.draw.rect( win, self.color, self.rect )
def collidesWith( self, other_rect ):
collides = self.rect.colliderect( other_rect )
if ( collides ):
print( "Player collides" )
return collides
def keyPress(self, event, step= 20, up=pygame.K_UP, down=pygame.K_DOWN, left=pygame.K_LEFT, right=pygame.K_RIGHT):
used_event = False
if event.type == pygame.KEYDOWN:
if event.key == up:
self.rect.y -= step
used_event = True
elif event.key == down:
self.rect.y += step
used_event = True
elif event.key == left:
self.rect.x -= step
used_event = True
elif event.key == right:
self.rect.x += step
used_event = True
return used_event
#creating a player
player = Player()
red = Enemy1((229,190,237), 20, 200, 150) # creating an enemy 1
small = Enemy1((124,144,219), 15, 30, 130) # creating an enemy 2
circle = Enemy1((115,107,146), 25, 150, 50) # creating an enemy 3
enemies = [ red, small, circle ]
#================================ Animation loop ====================
# start run function def here
running = True
clock = pygame.time.Clock() # for framerate timing
#starting the animation loop
while running:
win.fill(BLACK)
#================== Your animation tasks ================
# call functions, increment values
player.spawn()
red.move_rect()
small.move_rect()
#================== Interactinos ================
# This loop allows windows when exit is clicked.
# Do not change, remove or augment this loop...yet.
# stop conditional would go here
# check for collision with every enemy
for enemy in enemies:
enemy.collidesWith( player.rect )
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # stops animation
elif player.keyPress(event):
pass # player used event
#================== Animation control ===================
pygame.display.update()
clock.tick(60) # framerate in fps (30-60 is typical)
main()
pygame.quit() # stops running code & closes window
There was also a little bug in handling the Window events, I fixed this.
|
How can I detect collision in pygame while using colliderect() to make an object disappear without using sprites?
|
I have two classes that both create squares. One that puts squares randomly in the window and another that the user can control. I need to detect collision between them but I keep getting an error that the I need a rect style object when I use the colliderect() function. I am pretty sure my drawings are rects but I might be wrong.
I tried using the win.blit method to use draw my rects but I cannot make that work and need some help
import random
import pygame
pygame.init() # initialize pygame managers
# create a window
w = 600
h = 600
win = pygame.display.set_mode((w,h)) # define window variable
# pygame.display.set_caption("Read carefully.")
#global variables
WHITE = (255,255,255) # some handy RGB values
BLACK = (0,0,0)
YELLOW = (255, 186, 8)
x = random.randint(0,600)
y = random.randint(0,600)
#======================== Variables & functions ===================================================
#where we will create our class
#attributes of our class defining our object
def main():
class Enemy1():
color: str
radius: int
x: int
y: int
def __init__(self, color, radius, x=100, y=100):
self.color = color
self.radius = radius
self.x= x
self.y = y
self.w = 50
self.h = 50
self.appear = True
self.red = pygame.draw.rect(win,self.color,(self.y,self.x,self.w,self.h))
def move_rect(self):
if self.appear == True:
self.red = pygame.draw.rect(win,self.color,(self.y,self.x,self.w,self.h))
def collide(self):
if (self.appear):
if self.red.colliderect(self):
self.appear = False
class Player():
def __init__(self):
self.y = 300
self.x= 300
self.w = 100
self.h = 100
self.color = WHITE
self.appear = True
self.circle = pygame.draw.rect(win,self.color,(self.x,self.y,self.w,self.h))
def spawn(self):
if self.appear == True:
self.circle = pygame.draw.rect(win,self.color,(self.x,self.y,self.w,self.h))
def keyPress(self, event, step= 20, up=pygame.K_UP, down=pygame.K_DOWN, left=pygame.K_LEFT, right=pygame.K_RIGHT):
if event.type == pygame.KEYDOWN:
if event.key == up:
self.y -= step
elif event.key == down:
self.y += step
elif event.key == left:
self.x -= step
elif event.key == right:
self.x += step
#creating a player
player = Player()
red = Enemy1((229,190,237), 20, 200, 150) # creating an enemy 1
small = Enemy1((124,144,219), 15, 30, 130) # creating an enemy 2
circle = Enemy1((115,107,146), 25, 150, 50) # creating an enemy 3
#================================ Animation loop ===================================================
# start run function def here
running = True
clock = pygame.time.Clock() # for framerate timing
#starting the animation loop
while running:
win.fill(BLACK)
#================== Your animation tasks ================
# call functions, increment values
player.spawn()
red.move_rect()
small.move_rect()
for event in pygame.event.get():
player.keyPress(event)
#================== Interactinos ================
# This loop allows windows when exit is clicked.
# Do not change, remove or augment this loop...yet.
# stop conditional would go here
#player.collide(red.move_rect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # stops animation
pygame.quit() # stops running code & closes window
#================== Animation control ===================
pygame.display.update()
clock.tick(60) # framerate in fps (30-60 is typical)
main()
# pygame.display.quit() # uncomment to automatically close window at end of animation
|
[
"You do have a rectangle, but it's not a PyGame Rect. The collision functions can only be used with a Rect.\nThe Rect is really handy. The code doesn't need to store x, y, w, h ... all these can be put into a Rect:\nclass Player():\n def __init__(self):\n self.rect = pygame.Rect( 300, 300, 100, 100 )\n self.color = WHITE\n self.appear = True\n\nIf ever you do want access to the x, y, width, height - these are all still available from the Rect: self.rect.x, self.rect.height, etc.\nThis makes the collision checking simple:\nclass Player():\n # ...\n\n def collidesWith( self, other_rect ):\n collides = self.rect.colliderect( other_rect ) #<<-- HERE\n if ( collides ):\n print( \"Player collides\" )\n return collides\n\nI made a similar change to the Enemy class. This allows the code to make a list of all Enemy1 objects, then iterate through them, testing for collisions:\nenemies = [ red, small, circle ]\n\n# ...\n\nwhile running:\n\n # check for collision with every enemy\n for enemy in enemies:\n enemy.collidesWith( player.rect )\n\nFull code:\nimport random\n\nimport pygame\n\npygame.init() # initialize pygame managers\n\n\n\n# create a window \nw = 600\nh = 600\nwin = pygame.display.set_mode((w,h)) # define window variable\n\n# pygame.display.set_caption(\"Read carefully.\") \n\n\n#global variables \nWHITE = (255,255,255) # some handy RGB values\nBLACK = (0,0,0)\nYELLOW = (255, 186, 8)\nx = random.randint(0,600)\ny = random.randint(0,600)\n\n#======================== Variables & functions ===================\n\n#where we will create our class\n\n #attributes of our class defining our object \n\n\ndef main():\n class Enemy1():\n color: str\n radius: int\n x: int\n y: int\n\n def __init__(self, color, radius, x=100, y=100):\n self.color = color\n self.radius = radius\n self.rect = pygame.Rect( x, y, 50, 50 )\n self.appear = True\n\n def move_rect(self):\n if self.appear == True:\n pygame.draw.rect( win, self.color, self.rect )\n\n def collidesWith( self, other_rect ):\n collides = self.rect.colliderect( other_rect )\n if (self.appear):\n if collides:\n print( \"Enemy1 collides\" )\n self.appear = False\n return collides;\n\n\n class Player():\n\n def __init__(self):\n self.rect = pygame.Rect( 300, 300, 100, 100 )\n self.color = WHITE\n self.appear = True\n\n def spawn(self):\n if self.appear == True:\n self.circle = pygame.draw.rect( win, self.color, self.rect )\n\n\n def collidesWith( self, other_rect ):\n collides = self.rect.colliderect( other_rect )\n if ( collides ):\n print( \"Player collides\" )\n return collides\n\n def keyPress(self, event, step= 20, up=pygame.K_UP, down=pygame.K_DOWN, left=pygame.K_LEFT, right=pygame.K_RIGHT):\n used_event = False\n if event.type == pygame.KEYDOWN:\n if event.key == up:\n self.rect.y -= step\n used_event = True\n\n elif event.key == down:\n self.rect.y += step\n used_event = True\n\n elif event.key == left:\n self.rect.x -= step\n used_event = True\n\n elif event.key == right:\n self.rect.x += step \n used_event = True\n\n return used_event\n \n\n \n\n #creating a player\n player = Player()\n red = Enemy1((229,190,237), 20, 200, 150) # creating an enemy 1\n small = Enemy1((124,144,219), 15, 30, 130) # creating an enemy 2\n circle = Enemy1((115,107,146), 25, 150, 50) # creating an enemy 3\n\n enemies = [ red, small, circle ]\n\n #================================ Animation loop ====================\n\n # start run function def here\n\n running = True\n clock = pygame.time.Clock() # for framerate timing\n\n #starting the animation loop\n while running:\n win.fill(BLACK)\n\n #================== Your animation tasks ================\n # call functions, increment values\n\n player.spawn()\n red.move_rect()\n small.move_rect()\n\n \n #================== Interactinos ================\n # This loop allows windows when exit is clicked.\n # Do not change, remove or augment this loop...yet.\n # stop conditional would go here \n\n # check for collision with every enemy\n for enemy in enemies:\n enemy.collidesWith( player.rect )\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False # stops animation\n\n elif player.keyPress(event):\n pass # player used event\n\n #================== Animation control ===================\n\n pygame.display.update()\n\n clock.tick(60) # framerate in fps (30-60 is typical)\n\nmain()\npygame.quit() # stops running code & closes window\n\nThere was also a little bug in handling the Window events, I fixed this.\n"
] |
[
0
] |
[] |
[] |
[
"collision_detection",
"pygame",
"python"
] |
stackoverflow_0074513106_collision_detection_pygame_python.txt
|
Q:
Using Dataframes Column names within function
I am just getting started with functions and want to try using them to streamline some of my code, but I run into a issue when trying to define a function to create different dataframes:
def my_function(region):
y = df_expert.loc[:,region]
X['Price_24'] = df_expert[region].shift(24)
my_function("'Price_REG1'")
KeyError: "'Price_REG1'"
If I remove the single quotes ('') from the argument, it works fine. I guess I could use df.Column_1 style to refer to the columns instead, but sometimes I think it is nice to use the brackets.
Thank you.
A:
'Price_REG1' == "Price_REG1" -> True
so
x['Price_REG1'] == x["Price_REG1"] -> True
so when you pass "Price_REG1" and use it as x["Price_REG1"],
that the correct.
but if you pass "'Price_REG1'" that means you use it as x["'Price_REG1'"]
is incorrect.
|
Using Dataframes Column names within function
|
I am just getting started with functions and want to try using them to streamline some of my code, but I run into a issue when trying to define a function to create different dataframes:
def my_function(region):
y = df_expert.loc[:,region]
X['Price_24'] = df_expert[region].shift(24)
my_function("'Price_REG1'")
KeyError: "'Price_REG1'"
If I remove the single quotes ('') from the argument, it works fine. I guess I could use df.Column_1 style to refer to the columns instead, but sometimes I think it is nice to use the brackets.
Thank you.
|
[
"'Price_REG1' == \"Price_REG1\" -> True\nso\nx['Price_REG1'] == x[\"Price_REG1\"] -> True\nso when you pass \"Price_REG1\" and use it as x[\"Price_REG1\"],\nthat the correct.\nbut if you pass \"'Price_REG1'\" that means you use it as x[\"'Price_REG1'\"]\nis incorrect.\n"
] |
[
0
] |
[] |
[] |
[
"function",
"pandas",
"python"
] |
stackoverflow_0074510428_function_pandas_python.txt
|
Q:
Fast way to convert string to numpy ndarray
I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.
I currently use imageio to get an RGB matrix from the image and then convert that to hex. That one is fast, around 2.5 seconds for a 442KB image of 918 x 575 pixels.
In order to get the image from the string, I convert that to a matrix of hex values and then convert that to RGB to use imageio to create an image. This one is where the problem arises since it takes 36 seconds to do the process on the string corresponding to the same 918 x 575 image.
How could I make it quicker?
Here's the code:
def rgb2hex(rgb):
"""
convert a list or tuple of RGB values
to a string in hex
"""
r,g,b = rgb
return '{:02x}{:02x}{:02x}'.format(r, g, b)
def arrayToString(array):
"""
convert an array to a string
"""
string = ""
for element in array:
string += str(element)
return string
def sliceStr(string,sliceLenght):
"""
slice a string in chunks of sliceLenght lenght
"""
string = str(string)
array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)])
return array
def hexToRGB(hexadecimal):
"""
convert a hex string to an array of RGB values
"""
h = hexadecimal.lstrip('#')
if len(h)!=6:
return
return [int(h[i:i+2], 16) for i in (0, 2, 4)]
def ImageToBytes(image):
"""
Image to convert from image to bytes
"""
dataToEncrypt =imageio.imread(image)
if dataToEncrypt.shape[2] ==4:
dataToEncrypt = np.delete(dataToEncrypt,3,2)
originalRows, originalColumns,_ = dataToEncrypt.shape
#converting rgb to hex
hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt)
hexVal = np.apply_along_axis(arrayToString, 1, hexVal)
hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal))
byteImage = bytes.fromhex(hexVal)
return (byteImage, [originalRows,originalColumns])
def BytesToImage(byteToConvert,originalRows,originalColumns,name):
"""
Convert from Bytes to Image
"""
Data = byteToConvert.hex()
stepOne = sliceStr(Data,originalColumns*6)
stepTwo = []
for i in stepOne:
step = sliceStr(i,6)
#Add lost pixels
while len(step) != originalColumns:
step = np.append(step,"ffffff")
stepTwo.append(step)
stepThree = []
for i in stepTwo:
d = []
for j in i:
d.append(hexToRGB(j))
if len(stepThree) < originalRows:
stepThree.append(d)
Img = np.asarray(stepThree)
imageio.imwrite(name,Img)
A:
remove incorrect indentation on this line:
Img = np.asarray(stepThree)
It is inside the for loop and it should not
Also the code is doing innecesary conversion from byte to string to int instead of doing it directly byte to int, consider changing to the following which is shorter and faster
def BytesToImage2(byteToConvert,originalRows,originalColumns,name):
"""
Convert from Bytes to Image
"""
ia=[]
for i in range(0,len(byteToConvert),originalColumns*3):
row=[[y for y in x] for x in [byteToConvert[j:j+3] for j in range(i,i+originalColumns*3,3)]]
ia.append(row)
Img = np.asarray(ia)
imageio.imwrite(name,Img)
A:
If your bytes length is compliant, the following code should be the fastest method, it is 500k times faster than list comprehension on a 918 * 575 image (ignore the time of imwrite):
def BytesToImage(byteToConvert, originalRows, originalColumns, name):
img = np.frombuffer(byteToConvert, np.uint8).reshape(originalRows, originalColumns, 3)
imageio.imwrite(name, img)
|
Fast way to convert string to numpy ndarray
|
I am currently doing a python program to convert from image to hex string and the other way around. I need two functions, one that takes an image and returns a hex string that corresponds to the RGB values of each pixel, and another function that takes a hex string, two ints, and generates a visible image of that size corresponding to that hex string.
I currently use imageio to get an RGB matrix from the image and then convert that to hex. That one is fast, around 2.5 seconds for a 442KB image of 918 x 575 pixels.
In order to get the image from the string, I convert that to a matrix of hex values and then convert that to RGB to use imageio to create an image. This one is where the problem arises since it takes 36 seconds to do the process on the string corresponding to the same 918 x 575 image.
How could I make it quicker?
Here's the code:
def rgb2hex(rgb):
"""
convert a list or tuple of RGB values
to a string in hex
"""
r,g,b = rgb
return '{:02x}{:02x}{:02x}'.format(r, g, b)
def arrayToString(array):
"""
convert an array to a string
"""
string = ""
for element in array:
string += str(element)
return string
def sliceStr(string,sliceLenght):
"""
slice a string in chunks of sliceLenght lenght
"""
string = str(string)
array = np.array([string[i:i+sliceLenght] for i in range(0,len(string),sliceLenght)])
return array
def hexToRGB(hexadecimal):
"""
convert a hex string to an array of RGB values
"""
h = hexadecimal.lstrip('#')
if len(h)!=6:
return
return [int(h[i:i+2], 16) for i in (0, 2, 4)]
def ImageToBytes(image):
"""
Image to convert from image to bytes
"""
dataToEncrypt =imageio.imread(image)
if dataToEncrypt.shape[2] ==4:
dataToEncrypt = np.delete(dataToEncrypt,3,2)
originalRows, originalColumns,_ = dataToEncrypt.shape
#converting rgb to hex
hexVal = np.apply_along_axis(rgb2hex, 2, dataToEncrypt)
hexVal = np.apply_along_axis(arrayToString, 1, hexVal)
hexVal = str(np.apply_along_axis(arrayToString, 0, hexVal))
byteImage = bytes.fromhex(hexVal)
return (byteImage, [originalRows,originalColumns])
def BytesToImage(byteToConvert,originalRows,originalColumns,name):
"""
Convert from Bytes to Image
"""
Data = byteToConvert.hex()
stepOne = sliceStr(Data,originalColumns*6)
stepTwo = []
for i in stepOne:
step = sliceStr(i,6)
#Add lost pixels
while len(step) != originalColumns:
step = np.append(step,"ffffff")
stepTwo.append(step)
stepThree = []
for i in stepTwo:
d = []
for j in i:
d.append(hexToRGB(j))
if len(stepThree) < originalRows:
stepThree.append(d)
Img = np.asarray(stepThree)
imageio.imwrite(name,Img)
|
[
"remove incorrect indentation on this line:\nImg = np.asarray(stepThree)\n\nIt is inside the for loop and it should not\nAlso the code is doing innecesary conversion from byte to string to int instead of doing it directly byte to int, consider changing to the following which is shorter and faster\ndef BytesToImage2(byteToConvert,originalRows,originalColumns,name):\n\n \"\"\"\n Convert from Bytes to Image\n \"\"\"\n ia=[]\n for i in range(0,len(byteToConvert),originalColumns*3):\n row=[[y for y in x] for x in [byteToConvert[j:j+3] for j in range(i,i+originalColumns*3,3)]]\n ia.append(row)\n \n Img = np.asarray(ia)\n imageio.imwrite(name,Img)\n\n",
"If your bytes length is compliant, the following code should be the fastest method, it is 500k times faster than list comprehension on a 918 * 575 image (ignore the time of imwrite):\ndef BytesToImage(byteToConvert, originalRows, originalColumns, name):\n img = np.frombuffer(byteToConvert, np.uint8).reshape(originalRows, originalColumns, 3)\n imageio.imwrite(name, img)\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"numpy",
"python",
"python_3.x",
"python_imageio"
] |
stackoverflow_0074512390_numpy_python_python_3.x_python_imageio.txt
|
Q:
Is it possible to secure Tabs in my PySimpleGUI code?
Dears,
Is it possible to secure Tabs in my PySimpleGUI code ? Means that only 1st Tab can be kept accessible and the other ones request password:
Knowing that I'm able to do that using Collapsible function as follows :
def Collapsible(layout, key, title='', arrows=(sg.SYMBOL_DOWN, sg.SYMBOL_UP),
collapsed=False):
return sg.Column([[sg.T((arrows[1] if collapsed else arrows[0]), enable_events=True,
text_color='DeepSkyBlue2', k=key+'-BUTTON-'),
sg.T(title, enable_events=True, text_color='yellow', key=key+'-TITLE-')],
[sg.pin(sg.Column(layout, key=key, visible=not collapsed,
metadata=arrows))]], pad=(0,0))
==> Here's teh Layout Part
#### 1st part ####
[Collapsible(Menu1, SEC1_KEY,, collapsed=True)],
#### 2nd part ####
[Collapsible(Menu2, SEC2_KEY, collapsed=True)],
while True: # Event Loop
event, values = window.read()
#print(event, values)
if event == s
if event.startswith(SEC2_KEY):
window[SEC2_KEY].update(visible=not window[SEC2_KEY].visible)
else:
window[SEC2_KEY+'-BUTTON-'].update(window[SEC2_KEY].metadata[0] if
window[SEC2_KEY].visible else window[SEC2_KEY].metadata[1])
Any one can help on that ? Thanks
A:
Information for a question here, IMO, it will be better.
Add everything required
Remove everything not related.
Most simple layout if GUI required.
Here, just for how to set which tab accessible. tkinter code required here.
import PySimpleGUI as sg
accessible = [0, 3]
layout = [[sg.TabGroup([[sg.Tab(f'TAB {i}',[[sg.Text(f'This is the Tab {i}')]],key=f'Tab {i}',) for i in range(5)]], key='TabGroup')]]
window = sg.Window('Tab Group', layout, finalize=True)
window['TabGroup'].bind('<Button-1>', ' Change', propagate=False)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == 'TabGroup Change':
e = window['TabGroup'].user_bind_event
if e.widget.identify(e.x, e.y) == 'label':
index = e.widget.index(f'@{e.x},{e.y}')
if index in accessible:
window[f'Tab {index}'].select()
""" Password secured
else:
if sg.popup_get_text("Password") == 'Hello':
window[f'Tab {index}'].select()
"""
window.close()
|
Is it possible to secure Tabs in my PySimpleGUI code?
|
Dears,
Is it possible to secure Tabs in my PySimpleGUI code ? Means that only 1st Tab can be kept accessible and the other ones request password:
Knowing that I'm able to do that using Collapsible function as follows :
def Collapsible(layout, key, title='', arrows=(sg.SYMBOL_DOWN, sg.SYMBOL_UP),
collapsed=False):
return sg.Column([[sg.T((arrows[1] if collapsed else arrows[0]), enable_events=True,
text_color='DeepSkyBlue2', k=key+'-BUTTON-'),
sg.T(title, enable_events=True, text_color='yellow', key=key+'-TITLE-')],
[sg.pin(sg.Column(layout, key=key, visible=not collapsed,
metadata=arrows))]], pad=(0,0))
==> Here's teh Layout Part
#### 1st part ####
[Collapsible(Menu1, SEC1_KEY,, collapsed=True)],
#### 2nd part ####
[Collapsible(Menu2, SEC2_KEY, collapsed=True)],
while True: # Event Loop
event, values = window.read()
#print(event, values)
if event == s
if event.startswith(SEC2_KEY):
window[SEC2_KEY].update(visible=not window[SEC2_KEY].visible)
else:
window[SEC2_KEY+'-BUTTON-'].update(window[SEC2_KEY].metadata[0] if
window[SEC2_KEY].visible else window[SEC2_KEY].metadata[1])
Any one can help on that ? Thanks
|
[
"Information for a question here, IMO, it will be better.\n\nAdd everything required\nRemove everything not related.\nMost simple layout if GUI required.\n\nHere, just for how to set which tab accessible. tkinter code required here.\nimport PySimpleGUI as sg\n\naccessible = [0, 3]\n\nlayout = [[sg.TabGroup([[sg.Tab(f'TAB {i}',[[sg.Text(f'This is the Tab {i}')]],key=f'Tab {i}',) for i in range(5)]], key='TabGroup')]]\nwindow = sg.Window('Tab Group', layout, finalize=True)\nwindow['TabGroup'].bind('<Button-1>', ' Change', propagate=False)\n\nwhile True:\n\n event, values = window.read()\n\n if event == sg.WIN_CLOSED:\n break\n\n elif event == 'TabGroup Change':\n e = window['TabGroup'].user_bind_event\n if e.widget.identify(e.x, e.y) == 'label':\n index = e.widget.index(f'@{e.x},{e.y}')\n if index in accessible:\n window[f'Tab {index}'].select()\n \"\"\" Password secured\n else:\n if sg.popup_get_text(\"Password\") == 'Hello':\n window[f'Tab {index}'].select()\n \"\"\"\n\nwindow.close()\n\n"
] |
[
0
] |
[] |
[] |
[
"passwords",
"pysimplegui",
"python",
"security",
"tabs"
] |
stackoverflow_0074512833_passwords_pysimplegui_python_security_tabs.txt
|
Q:
Playwright Python: Get Attribute inside Iframe
I'm trying to get 'src' of iframe element using Playwright and Python.
Here is the HTML I'm trying to access:
<iframe title="IFRAME_NAME" src="https://www.data_I_want_TO_get.com"> </iframe>
my goal is to grab 'src' attribute.
here is what I've tried so far
src=page.frame_locator("IFRAME_NAME")
print(src.inner_html())
#also
src=page.frame_locator("IFRAME_NAME").get_by_role("src")
print(src)
and many other things that are NOT working,
most of the time I get:
AttributeError: 'FrameLocator' object has no attribute 'inner_html'
nor .get_attribute
How should I proceed about this?
A:
Absent seeing the actual site, a traditional selection and get_attribute should be sufficient:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
<iframe title="IFRAME_NAME" src="https://www.data_I_want_TO_get.com"></iframe>
""")
src = page.get_attribute('iframe[title="IFRAME_NAME"]', "src")
print(src) # => https://www.data_I_want_TO_get.com
browser.close()
If the frame isn't immediately visible you can wait for it by replacing the src = line with
src = (
page.wait_for_selector('iframe[title="IFRAME_NAME"]')
.get_attribute("src")
)
|
Playwright Python: Get Attribute inside Iframe
|
I'm trying to get 'src' of iframe element using Playwright and Python.
Here is the HTML I'm trying to access:
<iframe title="IFRAME_NAME" src="https://www.data_I_want_TO_get.com"> </iframe>
my goal is to grab 'src' attribute.
here is what I've tried so far
src=page.frame_locator("IFRAME_NAME")
print(src.inner_html())
#also
src=page.frame_locator("IFRAME_NAME").get_by_role("src")
print(src)
and many other things that are NOT working,
most of the time I get:
AttributeError: 'FrameLocator' object has no attribute 'inner_html'
nor .get_attribute
How should I proceed about this?
|
[
"Absent seeing the actual site, a traditional selection and get_attribute should be sufficient:\nfrom playwright.sync_api import sync_playwright\n\nwith sync_playwright() as p:\n browser = p.chromium.launch(headless=True)\n page = browser.new_page()\n page.set_content(\"\"\"\n <iframe title=\"IFRAME_NAME\" src=\"https://www.data_I_want_TO_get.com\"></iframe>\n \"\"\")\n src = page.get_attribute('iframe[title=\"IFRAME_NAME\"]', \"src\")\n print(src) # => https://www.data_I_want_TO_get.com\n browser.close()\n\nIf the frame isn't immediately visible you can wait for it by replacing the src = line with\nsrc = (\n page.wait_for_selector('iframe[title=\"IFRAME_NAME\"]')\n .get_attribute(\"src\")\n)\n\n"
] |
[
1
] |
[] |
[] |
[
"playwright",
"playwright_python",
"python"
] |
stackoverflow_0074508896_playwright_playwright_python_python.txt
|
Q:
DashPlotly and Pandas choosing excel file via dropdown
I have a folder with xlsx files. I want to use names of these files to populate the dropdown menu from dash plotly. I am stacked with what to begin from.
I read files from folder, list and append. If I put df_list[0] or df_list[1] I can manually choose which excel file to use for dataframe but how do I choose which file to use using dropdown menu? So even if new files will be added to the folder you can just select them via dropdown menu in dash app instead of changing the code?
```
path = os.getcwd()
csv_files = glob.glob(os.path.join(path, "*.xlsx"))
df_list = []
for f in csv_files:
# read the csv file
df_1 = pd.read_excel(f)
df_list.append(df_1)
```
A:
Here is a method that works:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import pandas as pd
import os
# 1. first create sample Excel files
data1 = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]
data2 = [{'x': 10, 'y': -6}, {'x': -10, 'y': 8}]
pd.DataFrame(data1).to_excel('file1.xlsx', index=False)
pd.DataFrame(data2).to_excel('file2.xlsx', index=False)
# 2. read the Excel files and add a 'file_name' column
data_frames = []
for file_name in os.listdir():
if file_name.endswith('.xlsx'):
dfx = pd.read_excel(file_name)
dfx['file_name'] = file_name
data_frames.append(dfx)
# 3. concat the data frames
df = pd.concat(data_frames, axis=0)
excel_files = sorted(df['file_name'].unique().tolist())
# 4. dash code
app = dash.Dash()
fig_dropdown = html.Div([
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in excel_files],
value=excel_files[0]
)])
fig_plot = html.Div(id='fig_plot')
app.layout = html.Div([fig_dropdown, fig_plot])
@app.callback(
dash.dependencies.Output('fig_plot', 'children'),
[dash.dependencies.Input('fig_dropdown', 'value')])
def name_to_figure(fig_name):
dff = df[df.file_name == fig_name]
figure = go.Figure()
figure.add_trace(go.Scatter(y=dff.y, x=dff.x))
return dcc.Graph(figure=figure)
app.run_server(debug=True, use_reloader=False)
We create 2 sample Excel files (you will not do this).
We read files ending in .xlsx.
Then we turn the files into Pandas dataframes.
Next, we add a column called 'file_name' to filter our data later.
We simply concatenate all the Excel files/ Padas dataframes.
We implement our Dash code.
I used this example from Stack Overflow to help with this part.
Here, we are using a callback function to update our figure.
This is where we use the 'file_name' filter from above.
Alternatively, you can read the Excel files directly instead of creating this filter.
|
DashPlotly and Pandas choosing excel file via dropdown
|
I have a folder with xlsx files. I want to use names of these files to populate the dropdown menu from dash plotly. I am stacked with what to begin from.
I read files from folder, list and append. If I put df_list[0] or df_list[1] I can manually choose which excel file to use for dataframe but how do I choose which file to use using dropdown menu? So even if new files will be added to the folder you can just select them via dropdown menu in dash app instead of changing the code?
```
path = os.getcwd()
csv_files = glob.glob(os.path.join(path, "*.xlsx"))
df_list = []
for f in csv_files:
# read the csv file
df_1 = pd.read_excel(f)
df_list.append(df_1)
```
|
[
"Here is a method that works:\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objects as go\nimport pandas as pd\nimport os\n\n# 1. first create sample Excel files\ndata1 = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]\ndata2 = [{'x': 10, 'y': -6}, {'x': -10, 'y': 8}]\npd.DataFrame(data1).to_excel('file1.xlsx', index=False)\npd.DataFrame(data2).to_excel('file2.xlsx', index=False)\n\n# 2. read the Excel files and add a 'file_name' column\ndata_frames = []\nfor file_name in os.listdir():\n if file_name.endswith('.xlsx'):\n dfx = pd.read_excel(file_name)\n dfx['file_name'] = file_name\n data_frames.append(dfx)\n\n# 3. concat the data frames\ndf = pd.concat(data_frames, axis=0)\n\nexcel_files = sorted(df['file_name'].unique().tolist())\n\n# 4. dash code\napp = dash.Dash()\n\nfig_dropdown = html.Div([\n dcc.Dropdown(\n id='fig_dropdown',\n options=[{'label': x, 'value': x} for x in excel_files],\n value=excel_files[0]\n )])\nfig_plot = html.Div(id='fig_plot')\napp.layout = html.Div([fig_dropdown, fig_plot])\n\n@app.callback(\n dash.dependencies.Output('fig_plot', 'children'),\n [dash.dependencies.Input('fig_dropdown', 'value')])\ndef name_to_figure(fig_name):\n dff = df[df.file_name == fig_name]\n figure = go.Figure()\n figure.add_trace(go.Scatter(y=dff.y, x=dff.x))\n return dcc.Graph(figure=figure)\n\napp.run_server(debug=True, use_reloader=False)\n\n\nWe create 2 sample Excel files (you will not do this).\nWe read files ending in .xlsx. \nThen we turn the files into Pandas dataframes. \nNext, we add a column called 'file_name' to filter our data later.\nWe simply concatenate all the Excel files/ Padas dataframes.\nWe implement our Dash code. \nI used this example from Stack Overflow to help with this part. \nHere, we are using a callback function to update our figure. \nThis is where we use the 'file_name' filter from above. \nAlternatively, you can read the Excel files directly instead of creating this filter.\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"plotly",
"plotly_dash",
"python"
] |
stackoverflow_0074513669_pandas_plotly_plotly_dash_python.txt
|
Q:
Find all HTML tags and append target blank values using Python regular expression
I want to find all
<a href='https://example.com/'>
references in a large file and append the
target='_blank' rel='noopener noreferrer'
option to the end of the tag, if it is missing.
Roughly, I did the following:
re.sub(r'<a href=([^>]+)', r'<a href=([^>]+)' + " target='_blank' rel='noopener noreferrer'", content)
Note: content contains the body of text to alter.
But, the second argument, which should be the value to replace is messing up the result.
The output I am getting is:
<a href=([^>]+) target='_blank' rel='noopener noreferrer'>
The expected result should be:
<a href='https://example.com/' target='_blank' rel='noopener noreferrer'>
What am I doing incorrectly, and how do I fix this issue?
A:
Try this: (*** If coding professionally, use the tool ti7 suggested.)
import re
content = "<a href='https://example.com/'>"
x = re.sub(r'(<a href=([^>]+))', r'\1' + " target='_blank' rel='noopener noreferrer'", content)
print(x)
output:
<a href='https://example.com/' target='_blank' rel='noopener noreferrer'>
A:
If you can use a 3rd-party library, BeautifulSoup may work very well for you!
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_contents, "html.parser")
soup.find_all("a")
|
Find all HTML tags and append target blank values using Python regular expression
|
I want to find all
<a href='https://example.com/'>
references in a large file and append the
target='_blank' rel='noopener noreferrer'
option to the end of the tag, if it is missing.
Roughly, I did the following:
re.sub(r'<a href=([^>]+)', r'<a href=([^>]+)' + " target='_blank' rel='noopener noreferrer'", content)
Note: content contains the body of text to alter.
But, the second argument, which should be the value to replace is messing up the result.
The output I am getting is:
<a href=([^>]+) target='_blank' rel='noopener noreferrer'>
The expected result should be:
<a href='https://example.com/' target='_blank' rel='noopener noreferrer'>
What am I doing incorrectly, and how do I fix this issue?
|
[
"Try this: (*** If coding professionally, use the tool ti7 suggested.)\nimport re\ncontent = \"<a href='https://example.com/'>\"\nx = re.sub(r'(<a href=([^>]+))', r'\\1' + \" target='_blank' rel='noopener noreferrer'\", content)\nprint(x)\n\noutput:\n <a href='https://example.com/' target='_blank' rel='noopener noreferrer'>\n\n",
"If you can use a 3rd-party library, BeautifulSoup may work very well for you!\nhttps://www.crummy.com/software/BeautifulSoup/bs4/doc/\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(html_contents, \"html.parser\")\nsoup.find_all(\"a\")\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"append",
"python"
] |
stackoverflow_0074514366_append_python.txt
|
Q:
i want to composite a data hourly with 4 years data
i have hourly data from January 2018 - December 2021
i want to sum the data each hour for four years. i.e. in a day we have 2pm just one hour, right?.but, in 4 years(365*3+366=1461) we have 1461 hours. i want to sum a data in each hour (00.00 - 23.00) for four years. but i dont get the idea how to code. this is my code
binstas=pd.DataFrame(ch)
df = binstas.copy()
df['new_column'] = pd.Series(pd.date_range('2018-01-01 00:00:00', '2021-12-31 23:50:00', freq='1H'))
df = df.set_index('new_column')
my expectation with not actual data
00:00 = 23
01:00 = 45
..
..
23:00 = 23
A:
Floor/truncate the timestamp to hour and format using strftime then groupby and sum:
i = df.index.floor('H').strftime('%H:%M')
df.groupby(i).sum()
|
i want to composite a data hourly with 4 years data
|
i have hourly data from January 2018 - December 2021
i want to sum the data each hour for four years. i.e. in a day we have 2pm just one hour, right?.but, in 4 years(365*3+366=1461) we have 1461 hours. i want to sum a data in each hour (00.00 - 23.00) for four years. but i dont get the idea how to code. this is my code
binstas=pd.DataFrame(ch)
df = binstas.copy()
df['new_column'] = pd.Series(pd.date_range('2018-01-01 00:00:00', '2021-12-31 23:50:00', freq='1H'))
df = df.set_index('new_column')
my expectation with not actual data
00:00 = 23
01:00 = 45
..
..
23:00 = 23
|
[
"Floor/truncate the timestamp to hour and format using strftime then groupby and sum:\ni = df.index.floor('H').strftime('%H:%M')\ndf.groupby(i).sum()\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074513634_pandas_python.txt
|
Q:
In Python, what is the difference between df["row_name"] and df.loc["row_name"]
I am trying to add another row to my data Frame
When I use df["new_row"] = [5, True, "joe", 20] , I get the error
ValueError: Length of values (4) does not match length of index (11)
but if I use df.loc["new_row"] = [5, True, "joe", 20], I can succesfully add a new row.
A:
To answer your question about the difference, in pandas, df["colname"] is used to access a column of a given data frame.
loc[r,c] is used to access specific cells within that data frame in the order of row and column. So, if you use df.loc[r], it will access the entire row.
In your case,df.loc['new_row'], creates a new row, at which you are inserting [5, True, "joe", 20]
|
In Python, what is the difference between df["row_name"] and df.loc["row_name"]
|
I am trying to add another row to my data Frame
When I use df["new_row"] = [5, True, "joe", 20] , I get the error
ValueError: Length of values (4) does not match length of index (11)
but if I use df.loc["new_row"] = [5, True, "joe", 20], I can succesfully add a new row.
|
[
"To answer your question about the difference, in pandas, df[\"colname\"] is used to access a column of a given data frame.\nloc[r,c] is used to access specific cells within that data frame in the order of row and column. So, if you use df.loc[r], it will access the entire row.\nIn your case,df.loc['new_row'], creates a new row, at which you are inserting [5, True, \"joe\", 20]\n"
] |
[
0
] |
[] |
[] |
[
"indexing",
"pandas",
"pandas_loc",
"python"
] |
stackoverflow_0074514469_indexing_pandas_pandas_loc_python.txt
|
Q:
Palindrome LinkedList Leetcode challenge
Given the following Leetcode challenge,
Leet code challenge
I have 2 questions:
1- I am confused about head =[1,2,3,4] in the question. To me, this looks like a whole linked list and not just a head. I would expect the head would be the first element in the input data array.
I think I am not sure how the head can equal multiple values in a list?
2- Below is the same code from the official solution and it's not working:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
vals = []
current_node = head
while current_node is not None:
vals.append(current_node.val)
current_node = current_node.next
return vals == vals[::-1]
If I run this code using these 2 lines:
node = ListNode([1,2])
Solution().isPalindrome(node)
I was expecting it to to output False for this example but it always outputs true because the vals is a nested list. The [::-1] python function doesn't work with nested lists.
Not sure what I am missing.
Thanks!
A:
Point 1
You have the correct understanding. What whey mean in attached screenshot is that the "head" is pointing to the first element of the linked list.
Point 2
The problem is with the constructor. ListNode represents a single node and the corresponding contructor __init__(self, val=0, next=None) is expecting two arguments:
Value: Value of the node
Next: Pointer to the next ListNode
I tried the following code and its returning the expected results:
#One that returns false:
s = Solution()
n1 = ListNode(1)
n2 = ListNode(1, n1)
n3 = ListNode(3, n2)
n4 = ListNode(1, n3)
head = n4;
result = s.isPalindrome(head);
print(result)
#One that returns true:
s = Solution()
n1 = ListNode(1)
n2 = ListNode(2, n1)
n3 = ListNode(2, n2)
n4 = ListNode(1, n3)
head = n4;
result = s.isPalindrome(head);
print(result)
|
Palindrome LinkedList Leetcode challenge
|
Given the following Leetcode challenge,
Leet code challenge
I have 2 questions:
1- I am confused about head =[1,2,3,4] in the question. To me, this looks like a whole linked list and not just a head. I would expect the head would be the first element in the input data array.
I think I am not sure how the head can equal multiple values in a list?
2- Below is the same code from the official solution and it's not working:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
vals = []
current_node = head
while current_node is not None:
vals.append(current_node.val)
current_node = current_node.next
return vals == vals[::-1]
If I run this code using these 2 lines:
node = ListNode([1,2])
Solution().isPalindrome(node)
I was expecting it to to output False for this example but it always outputs true because the vals is a nested list. The [::-1] python function doesn't work with nested lists.
Not sure what I am missing.
Thanks!
|
[
"Point 1\nYou have the correct understanding. What whey mean in attached screenshot is that the \"head\" is pointing to the first element of the linked list.\nPoint 2\nThe problem is with the constructor. ListNode represents a single node and the corresponding contructor __init__(self, val=0, next=None) is expecting two arguments:\n\nValue: Value of the node\nNext: Pointer to the next ListNode\n\nI tried the following code and its returning the expected results:\n#One that returns false:\ns = Solution()\nn1 = ListNode(1)\nn2 = ListNode(1, n1)\nn3 = ListNode(3, n2)\nn4 = ListNode(1, n3)\nhead = n4;\nresult = s.isPalindrome(head);\nprint(result)\n\n#One that returns true:\ns = Solution()\nn1 = ListNode(1)\nn2 = ListNode(2, n1)\nn3 = ListNode(2, n2)\nn4 = ListNode(1, n3)\nhead = n4;\nresult = s.isPalindrome(head);\nprint(result)\n\n"
] |
[
0
] |
[] |
[] |
[
"class",
"palindrome",
"python"
] |
stackoverflow_0074513928_class_palindrome_python.txt
|
Q:
Django Conditional to remove css class if not on main url
Im wondering if someone could help me figure this out;
Working on a web app using the django framework and for my navbar, I have a css class that makes it transparent on the main page. This of course worked on a static website, but does not in django. How can i write an if statement to only apply this class on a specific url - the home page?
{% load static %}
<header id="home">
<!-- Navbar -->
<nav id="navbar" class="main-page">
<a href="{% url 'home' %}"><img src="{% static 'images/farmec-logo-2.png' %}" alt="" id="logo"></a>
<ul>
<li><a href="{% url 'home' %}" class="current">Home</a></li>
<li><a href="{% url 'teams' %}">About</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="suppliers.html">Suppliers</a></li>
<li><a href="parts.html">Spare Parts</a></li>
</ul>
</nav>
</header>
#navbar {
display: flex;
justify-content: space-between;
padding-top: 1rem;
position: absolute;
background: transparent;
width: 100vw;
z-index: 1;
background: var(--dark-color);
transition: 0.5s ease-in;
}
#navbar.main-page {
background: transparent;
}
A:
In Django, you can check active URL like this...
I put code for if the home URL is active and then applied id="navbar" else not.
{% load static %}
<header id="home">
<!-- Navbar -->
<nav {% if request.resolver_match.url_name == 'home' %}id="navbar"{% endif %} class="main-page">
<a href="{% url 'home' %}"><img src="{% static 'images/farmec-logo-2.png' %}" alt="" id="logo"></a>
<ul>
<li><a href="{% url 'home' %}" class="current">Home</a></li>
<li><a href="{% url 'teams' %}">About</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="suppliers.html">Suppliers</a></li>
<li><a href="parts.html">Spare Parts</a></li>
</ul>
</nav>
</header>
|
Django Conditional to remove css class if not on main url
|
Im wondering if someone could help me figure this out;
Working on a web app using the django framework and for my navbar, I have a css class that makes it transparent on the main page. This of course worked on a static website, but does not in django. How can i write an if statement to only apply this class on a specific url - the home page?
{% load static %}
<header id="home">
<!-- Navbar -->
<nav id="navbar" class="main-page">
<a href="{% url 'home' %}"><img src="{% static 'images/farmec-logo-2.png' %}" alt="" id="logo"></a>
<ul>
<li><a href="{% url 'home' %}" class="current">Home</a></li>
<li><a href="{% url 'teams' %}">About</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="suppliers.html">Suppliers</a></li>
<li><a href="parts.html">Spare Parts</a></li>
</ul>
</nav>
</header>
#navbar {
display: flex;
justify-content: space-between;
padding-top: 1rem;
position: absolute;
background: transparent;
width: 100vw;
z-index: 1;
background: var(--dark-color);
transition: 0.5s ease-in;
}
#navbar.main-page {
background: transparent;
}
|
[
"In Django, you can check active URL like this...\nI put code for if the home URL is active and then applied id=\"navbar\" else not.\n{% load static %}\n<header id=\"home\">\n <!-- Navbar -->\n <nav {% if request.resolver_match.url_name == 'home' %}id=\"navbar\"{% endif %} class=\"main-page\">\n <a href=\"{% url 'home' %}\"><img src=\"{% static 'images/farmec-logo-2.png' %}\" alt=\"\" id=\"logo\"></a>\n <ul>\n <li><a href=\"{% url 'home' %}\" class=\"current\">Home</a></li>\n <li><a href=\"{% url 'teams' %}\">About</a></li>\n <li><a href=\"blog.html\">Blog</a></li>\n <li><a href=\"suppliers.html\">Suppliers</a></li>\n <li><a href=\"parts.html\">Spare Parts</a></li>\n </ul>\n </nav>\n</header>\n\n"
] |
[
0
] |
[] |
[] |
[
"css",
"django",
"django_templates",
"html",
"python"
] |
stackoverflow_0074510241_css_django_django_templates_html_python.txt
|
Q:
How to place all files in python module to the same top level namespace?
I have example python project with multiple files:
src/common.py:
def toint(x):
return int(x)
src/foo1.py:
import common
def add(a,b):
return common.toint(a) + common.toint(b)
src/foo2.py:
import common
def sub(a,b):
return common.toint(a)-common.toint(b)
setup.py:
from setuptools import setup
setup (name = 'test_py_project',
version = '1.0',
author='Vladislav Tsendrovskii',
description = 'test python modules',
package_dir = {'': 'src'}
)
Now I want to install this project. I run python3 setup.py install --user and it installs.
But it installs not in a way that I want.
When I try to use it, I have problems.
I can not do import test_py_project.foo1
But I can do import foo1
How should I modify my project, to place all stuff inside test_py_project namespace?
I have tried to google for solution. But I've failed(
A:
Reference the python docs https://docs.python.org/2/tutorial/modules.html#intra-package-references for creating modules and project directory format. E.g. Modulename/ModuleFiles.py and existence of a __init__.py and __main__.py files. From __init__ you can import * or use relative/absolute imports.
A:
But I can do import foo1
As it seems, your Python can already find stuff inside the src folder.
If you want to make test_py_project.foo1 work, create the necessary directory under src and move foo1.py there, so that you'll have src/test_py_project/foo1.py.
Then the import import test_py_project.foo1 should work.
|
How to place all files in python module to the same top level namespace?
|
I have example python project with multiple files:
src/common.py:
def toint(x):
return int(x)
src/foo1.py:
import common
def add(a,b):
return common.toint(a) + common.toint(b)
src/foo2.py:
import common
def sub(a,b):
return common.toint(a)-common.toint(b)
setup.py:
from setuptools import setup
setup (name = 'test_py_project',
version = '1.0',
author='Vladislav Tsendrovskii',
description = 'test python modules',
package_dir = {'': 'src'}
)
Now I want to install this project. I run python3 setup.py install --user and it installs.
But it installs not in a way that I want.
When I try to use it, I have problems.
I can not do import test_py_project.foo1
But I can do import foo1
How should I modify my project, to place all stuff inside test_py_project namespace?
I have tried to google for solution. But I've failed(
|
[
"Reference the python docs https://docs.python.org/2/tutorial/modules.html#intra-package-references for creating modules and project directory format. E.g. Modulename/ModuleFiles.py and existence of a __init__.py and __main__.py files. From __init__ you can import * or use relative/absolute imports.\n",
"\nBut I can do import foo1\n\nAs it seems, your Python can already find stuff inside the src folder.\nIf you want to make test_py_project.foo1 work, create the necessary directory under src and move foo1.py there, so that you'll have src/test_py_project/foo1.py.\nThen the import import test_py_project.foo1 should work.\n"
] |
[
0,
0
] |
[] |
[] |
[
"namespaces",
"python"
] |
stackoverflow_0074341189_namespaces_python.txt
|
Q:
Extract an array of numbers from a Python array
Suppose I have a 10x10 Python array, M. I would like to extract the 3x3 array with the values of the rows [2,3,5], and columns [2,3,5]. How do I do this? I would like to obtain the equivalent of M[0:3,0:3] but using coordinates [2,3,5] instead of [0,1,2].
I have tried M[[2,3,5],[2,3,5]], but this produces three values, not a 3x3 array.
A:
You could .take() twice
>>> a = np.arange(100).reshape(10,10)
>>> a
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
>>> np.take(np.take(a, [2,3,5], axis=1), [2,3,5], axis=0)
array([[22, 23, 25],
[32, 33, 35],
[52, 53, 55]])
A:
One option to use is numpy.ix_.
It should be as simple as M[np.ix_([2, 3, 5], [2, 3, 5])].
|
Extract an array of numbers from a Python array
|
Suppose I have a 10x10 Python array, M. I would like to extract the 3x3 array with the values of the rows [2,3,5], and columns [2,3,5]. How do I do this? I would like to obtain the equivalent of M[0:3,0:3] but using coordinates [2,3,5] instead of [0,1,2].
I have tried M[[2,3,5],[2,3,5]], but this produces three values, not a 3x3 array.
|
[
"You could .take() twice\n>>> a = np.arange(100).reshape(10,10)\n>>> a\narray([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],\n [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],\n [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],\n [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],\n [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])\n>>> np.take(np.take(a, [2,3,5], axis=1), [2,3,5], axis=0)\narray([[22, 23, 25],\n [32, 33, 35],\n [52, 53, 55]])\n\n",
"One option to use is numpy.ix_.\nIt should be as simple as M[np.ix_([2, 3, 5], [2, 3, 5])].\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"numpy",
"python"
] |
stackoverflow_0074514379_arrays_numpy_python.txt
|
Q:
How to use conditional statement to map duplicates first and last with multiple columns in a dataframe?
I am working with the following dataframe:
issue_status market_phase trading_status is_and_mp market_state reason
0 10 0 B0 100 UNSCHEDULED_AUCTION
1 20 0 200 CONTINUOUS_TRADING
2 40 0 D1 400 POST_TRADE
3 10 0 100
4 10 0 100
5 40 0 400
6 40 0 400
7 40 0 400
I am trying to write a Python condition where if is_and_mp is 100 and trading_status is None, then for the first instance of is_and_mp of 100, mark an F in the reason column.
And do the same if is_and_mp is 400 and trading_status is None.
For the second last instance where is_and_mp is 400 and trading_status is None, mark an SL in the reason column.
Finally for the last instance where is_and_mp is 400 and trading_status is None, mark L in the reason column.
So the above dataframe should look like this:
issue_status market_phase trading_status is_and_mp market_state reason
0 10 0 B0 100 UNSCHEDULED_AUCTION
1 20 0 200 CONTINUOUS_TRADING
2 40 0 D1 400 POST_TRADE
3 10 0 100 F
4 10 0 100
5 40 0 400
6 40 0 400 SL
7 40 0 400 L
The logic for 100 and 400 doesn't have to be together, it can be separated if it is easier!
@Azhar thank you for your solution, I tried it for the following input but it doesn't quite do the desired mapping- could you kindly advise?:
trading_status is_and_mp market_state groups
0 000 CLOSED 1
1 200 CONTINUOUS_TRADING 2
2 103 None 3
3 204 UNSCHEDULED_AUCTION 4
4 203 UNSCHEDULED_AUCTION 5
5 B0 100 UNSCHEDULED_AUCTION 6
6 B1 200 CONTINUOUS_TRADING 7
7 400 None 8
8 A0 400 HALTED 9
9 100 None 10
10 100 None 10
11 400 None 11
12 400 None 12
expected output for group` column:
groups
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 10
11 8
12 8
A:
UPDATE
Following answer is updated after @PatrickChong 's updated logic:
# df = pd.DataFrame(data=[[None,"000","CLOSED"],[None,"200","CONTINUOUS_TRADING"],[None,"103","None"],[None,"204","UNSCHEDULED_AUCTION"],[None,"203","UNSCHEDULED_AUCTION"],["B0","100","UNSCHEDULED_AUCTION"],["B1","200","CONTINUOUS_TRADING"],[None,"400","None"],["A0","400","HALTED"],[None,"100","None"],[None,"100","None"],[None,"400","None"],[None,"400","None"]], columns=["trading_status","is_and_mp","market_state"])
# df = pd.DataFrame(data=[[10,0,"B0","100","UNSCHEDULED_AUCTION"],[20,0,None,"200","CONTINUOUS_TRADING"],[40,0,"D1","400","POST_TRADE"],[10,0,None,"100",""],[10,0,None,"100",""],[40,0,None,"400",""],[40,0,None,"400",""],[40,0,None,"400",""]], columns=["issue_status","market_phase","trading_status","is_and_mp","market_state"])
# df = pd.DataFrame(data=[["100","A0"],["100",None],["400",None],["100",None],["400",None],["100",'B2'],["400",None],["100",None],["400","A6"]], columns=["is_and_mp","trading_status"])
df = pd.DataFrame(data=[["400",None],["100","A0"],["400",None],["400","A0"],["100",None],["100",None]], columns=["is_and_mp","trading_status"])
df["tmp"] = list(zip(df.is_and_mp, df.trading_status))
df["reason"] = df.groupby(["is_and_mp", df.trading_status.astype(str)])["tmp"].transform(lambda grp: ["F" if v[0]=="100" and v[1]==None and i==0 else "SL" if v[0]=="400" and v[1]==None and len(grp)>1 and i==len(grp)-2 else "L" if v[0]=="400" and v[1]==None and len(grp)>1 and i==len(grp)-1 else "" for i,v in enumerate(grp)])
df = df.drop("tmp", axis=1)
[Out]:
is_and_mp trading_status reason
0 400 None SL
1 100 A0
2 400 None L
3 400 A0
4 100 None F
5 100 None
Another related post
Create a "group" column to represent similar group of records which match the given condition:
df["group"] = (~((df["is_and_mp"].eq(df["is_and_mp"].shift())) & (df["trading_status"] == ""))).cumsum()
Then create the output "reason" column by matching the required logic:
df["reason"] = df.groupby("group")["is_and_mp"].transform(lambda grp: ["F" if v=="100" and len(grp)>1 and i==0 else "SL" if v=="400" and len(grp)>1 and i==len(grp)-2 else "L" if v=="400" and len(grp)>1 and i==len(grp)-1 else "" for i,v in enumerate(grp)])
Full example:
df = pd.DataFrame(data=[[10,0,"B0","100","UNSCHEDULED_AUCTION"],[20,0,"","200","CONTINUOUS_TRADING"],[40,0,"D1","400","POST_TRADE"],[10,0,"","100",""],[10,0,"","100",""],[40,0,"","400",""],[40,0,"","400",""],[40,0,"","400",""]], columns=["issue_status","market_phase","trading_status","is_and_mp","market_state"])
df["group"] = (~((df["is_and_mp"].eq(df["is_and_mp"].shift())) & (df["trading_status"] == ""))).cumsum()
df["reason"] = df.groupby("group")["is_and_mp"].transform(lambda grp: ["F" if v=="100" and len(grp)>1 and i==0 else "SL" if v=="400" and len(grp)>1 and i==len(grp)-2 else "L" if v=="400" and len(grp)>1 and i==len(grp)-1 else "" for i,v in enumerate(grp)])
[Out]:
issue_status market_phase trading_status is_and_mp market_state group reason
0 10 0 B0 100 UNSCHEDULED_AUCTION 1
1 20 0 200 CONTINUOUS_TRADING 2
2 40 0 D1 400 POST_TRADE 3
3 10 0 100 4 F
4 10 0 100 4
5 40 0 400 5
6 40 0 400 5 SL
7 40 0 400 5 L
|
How to use conditional statement to map duplicates first and last with multiple columns in a dataframe?
|
I am working with the following dataframe:
issue_status market_phase trading_status is_and_mp market_state reason
0 10 0 B0 100 UNSCHEDULED_AUCTION
1 20 0 200 CONTINUOUS_TRADING
2 40 0 D1 400 POST_TRADE
3 10 0 100
4 10 0 100
5 40 0 400
6 40 0 400
7 40 0 400
I am trying to write a Python condition where if is_and_mp is 100 and trading_status is None, then for the first instance of is_and_mp of 100, mark an F in the reason column.
And do the same if is_and_mp is 400 and trading_status is None.
For the second last instance where is_and_mp is 400 and trading_status is None, mark an SL in the reason column.
Finally for the last instance where is_and_mp is 400 and trading_status is None, mark L in the reason column.
So the above dataframe should look like this:
issue_status market_phase trading_status is_and_mp market_state reason
0 10 0 B0 100 UNSCHEDULED_AUCTION
1 20 0 200 CONTINUOUS_TRADING
2 40 0 D1 400 POST_TRADE
3 10 0 100 F
4 10 0 100
5 40 0 400
6 40 0 400 SL
7 40 0 400 L
The logic for 100 and 400 doesn't have to be together, it can be separated if it is easier!
@Azhar thank you for your solution, I tried it for the following input but it doesn't quite do the desired mapping- could you kindly advise?:
trading_status is_and_mp market_state groups
0 000 CLOSED 1
1 200 CONTINUOUS_TRADING 2
2 103 None 3
3 204 UNSCHEDULED_AUCTION 4
4 203 UNSCHEDULED_AUCTION 5
5 B0 100 UNSCHEDULED_AUCTION 6
6 B1 200 CONTINUOUS_TRADING 7
7 400 None 8
8 A0 400 HALTED 9
9 100 None 10
10 100 None 10
11 400 None 11
12 400 None 12
expected output for group` column:
groups
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 10
11 8
12 8
|
[
"UPDATE\nFollowing answer is updated after @PatrickChong 's updated logic:\n# df = pd.DataFrame(data=[[None,\"000\",\"CLOSED\"],[None,\"200\",\"CONTINUOUS_TRADING\"],[None,\"103\",\"None\"],[None,\"204\",\"UNSCHEDULED_AUCTION\"],[None,\"203\",\"UNSCHEDULED_AUCTION\"],[\"B0\",\"100\",\"UNSCHEDULED_AUCTION\"],[\"B1\",\"200\",\"CONTINUOUS_TRADING\"],[None,\"400\",\"None\"],[\"A0\",\"400\",\"HALTED\"],[None,\"100\",\"None\"],[None,\"100\",\"None\"],[None,\"400\",\"None\"],[None,\"400\",\"None\"]], columns=[\"trading_status\",\"is_and_mp\",\"market_state\"])\n# df = pd.DataFrame(data=[[10,0,\"B0\",\"100\",\"UNSCHEDULED_AUCTION\"],[20,0,None,\"200\",\"CONTINUOUS_TRADING\"],[40,0,\"D1\",\"400\",\"POST_TRADE\"],[10,0,None,\"100\",\"\"],[10,0,None,\"100\",\"\"],[40,0,None,\"400\",\"\"],[40,0,None,\"400\",\"\"],[40,0,None,\"400\",\"\"]], columns=[\"issue_status\",\"market_phase\",\"trading_status\",\"is_and_mp\",\"market_state\"])\n# df = pd.DataFrame(data=[[\"100\",\"A0\"],[\"100\",None],[\"400\",None],[\"100\",None],[\"400\",None],[\"100\",'B2'],[\"400\",None],[\"100\",None],[\"400\",\"A6\"]], columns=[\"is_and_mp\",\"trading_status\"])\ndf = pd.DataFrame(data=[[\"400\",None],[\"100\",\"A0\"],[\"400\",None],[\"400\",\"A0\"],[\"100\",None],[\"100\",None]], columns=[\"is_and_mp\",\"trading_status\"])\n\ndf[\"tmp\"] = list(zip(df.is_and_mp, df.trading_status))\ndf[\"reason\"] = df.groupby([\"is_and_mp\", df.trading_status.astype(str)])[\"tmp\"].transform(lambda grp: [\"F\" if v[0]==\"100\" and v[1]==None and i==0 else \"SL\" if v[0]==\"400\" and v[1]==None and len(grp)>1 and i==len(grp)-2 else \"L\" if v[0]==\"400\" and v[1]==None and len(grp)>1 and i==len(grp)-1 else \"\" for i,v in enumerate(grp)])\ndf = df.drop(\"tmp\", axis=1)\n\n[Out]:\n is_and_mp trading_status reason\n0 400 None SL\n1 100 A0 \n2 400 None L\n3 400 A0 \n4 100 None F\n5 100 None \n\nAnother related post\n\nCreate a \"group\" column to represent similar group of records which match the given condition:\ndf[\"group\"] = (~((df[\"is_and_mp\"].eq(df[\"is_and_mp\"].shift())) & (df[\"trading_status\"] == \"\"))).cumsum()\n\nThen create the output \"reason\" column by matching the required logic:\ndf[\"reason\"] = df.groupby(\"group\")[\"is_and_mp\"].transform(lambda grp: [\"F\" if v==\"100\" and len(grp)>1 and i==0 else \"SL\" if v==\"400\" and len(grp)>1 and i==len(grp)-2 else \"L\" if v==\"400\" and len(grp)>1 and i==len(grp)-1 else \"\" for i,v in enumerate(grp)])\n\nFull example:\ndf = pd.DataFrame(data=[[10,0,\"B0\",\"100\",\"UNSCHEDULED_AUCTION\"],[20,0,\"\",\"200\",\"CONTINUOUS_TRADING\"],[40,0,\"D1\",\"400\",\"POST_TRADE\"],[10,0,\"\",\"100\",\"\"],[10,0,\"\",\"100\",\"\"],[40,0,\"\",\"400\",\"\"],[40,0,\"\",\"400\",\"\"],[40,0,\"\",\"400\",\"\"]], columns=[\"issue_status\",\"market_phase\",\"trading_status\",\"is_and_mp\",\"market_state\"])\n\ndf[\"group\"] = (~((df[\"is_and_mp\"].eq(df[\"is_and_mp\"].shift())) & (df[\"trading_status\"] == \"\"))).cumsum()\n\ndf[\"reason\"] = df.groupby(\"group\")[\"is_and_mp\"].transform(lambda grp: [\"F\" if v==\"100\" and len(grp)>1 and i==0 else \"SL\" if v==\"400\" and len(grp)>1 and i==len(grp)-2 else \"L\" if v==\"400\" and len(grp)>1 and i==len(grp)-1 else \"\" for i,v in enumerate(grp)])\n\n[Out]:\n issue_status market_phase trading_status is_and_mp market_state group reason\n0 10 0 B0 100 UNSCHEDULED_AUCTION 1 \n1 20 0 200 CONTINUOUS_TRADING 2 \n2 40 0 D1 400 POST_TRADE 3 \n3 10 0 100 4 F\n4 10 0 100 4 \n5 40 0 400 5 \n6 40 0 400 5 SL\n7 40 0 400 5 L\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074509614_dataframe_pandas_python.txt
|
Q:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! in simple chatbot codes
I made my first Korean chatbot program with python, pytorch and pycharm. It works in my local environment but so slow, So I want to move my codes to Google Colab to make it fast. But I have runtime error : two devices(cuda and cpu) works in same space. I looked for this error and found out that I should upload all of my codes to GPU to work correctly. However, I added .to(device) / .tocuda() something like this for several times but it wasn't worked yet. Please help me. Below this text, this is my whole train codes : Trainer.py and I have problem when call this code to other one. (Import trainer)
import aboutDataSets
import numpy as np
import pandas as pd
import torch
from tqdm import tqdm # 학습 진행률 시각화 1
from time import sleep # 학습 진행률 시각화 2
import re # 정규식 계산
import os
import urllib.request # url로 csv파일 받아오기
from torch.utils.data import DataLoader, Dataset
from transformers.optimization import AdamW # optimizer
from transformers import PreTrainedTokenizerFast, GPT2LMHeadModel
Q_TKN = "<usr>"
A_TKN = "<sys>"
BOS = '</s>'
EOS = '</s>'
MASK = '<unused0>'
SENT = '<unused1>'
PAD = '<pad>'
tokenizer = PreTrainedTokenizerFast.from_pretrained("skt/kogpt2-base-v2",
bos_token=BOS,
eos_token=BOS,
unk_token='unk',
pad_token=PAD,
mask_token=MASK)
model = GPT2LMHeadModel.from_pretrained('skt/kogpt2-base-v2')
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/songys/Chatbot_data/master/ChatbotData.csv",
filename="ChatBotDataMain.csv",
)
ChatData = pd.read_csv("ChatBotDataMain.csv")
ChatData = ChatData[:300]
# print(ChatData.head())
#dataset 만들기
dataset = aboutDataSets.ChatDataset(ChatData)
batch_size = 32
num_workers = 0
def collate_batch(batch):
data = [item[0] for item in batch]
mask = [item[1] for item in batch]
label = [item[2] for item in batch]
return torch.LongTensor(data), torch.LongTensor(mask), torch.LongTensor(label)
# 아래 collate_batch 변수때문에 여기 한번 더 호출.
#dataloader 선언
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_set = aboutDataSets.ChatDataset(ChatData, max_len=40)
train_dataLoader = DataLoader(train_set,
batch_size=batch_size,
num_workers=num_workers,
shuffle=True,
collate_fn=collate_batch,)
model.to(device)
model.train()
lr = 3e-5
criterion = torch.nn.CrossEntropyLoss(reduction='none')
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
epoch = 10
sneg = -1e18
# 학습 시작
print("::start::")
for epoch in tqdm(range(epoch)): # 시각화를 위한 tqdm library
for batch_idx, samples in enumerate(train_dataLoader):
#print(batch_idx, samples)
optimizer.zero_grad()
token_ids, mask, label = samples
out = model(token_ids)
out = out.logits # returns a new tensor with the logit of the elements of input
mask_3d = mask.unsqueeze(dim=2).repeat_interleave(repeats=out.shape[2], dim=2)
mask_out = torch.where(mask_3d == 1, out, sneg * torch.ones_like(out))
loss = criterion(mask_out.transpose(2, 1), label)
avg_loss = loss.sum() / mask.sum() # avg_loss[0] / avg_loss[1] <- loss 정규화
avg_loss.backward()
# 학습 끝
optimizer.step()
print("end")
A:
Replace token_ids, mask, label = samples with token_ids, mask, label = [t.to(device) for t in samples]
This is because the samples generated by the dataloader is on CPU instead of CUDA by default. You have to move them to CUDA before performing forward.
|
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! in simple chatbot codes
|
I made my first Korean chatbot program with python, pytorch and pycharm. It works in my local environment but so slow, So I want to move my codes to Google Colab to make it fast. But I have runtime error : two devices(cuda and cpu) works in same space. I looked for this error and found out that I should upload all of my codes to GPU to work correctly. However, I added .to(device) / .tocuda() something like this for several times but it wasn't worked yet. Please help me. Below this text, this is my whole train codes : Trainer.py and I have problem when call this code to other one. (Import trainer)
import aboutDataSets
import numpy as np
import pandas as pd
import torch
from tqdm import tqdm # 학습 진행률 시각화 1
from time import sleep # 학습 진행률 시각화 2
import re # 정규식 계산
import os
import urllib.request # url로 csv파일 받아오기
from torch.utils.data import DataLoader, Dataset
from transformers.optimization import AdamW # optimizer
from transformers import PreTrainedTokenizerFast, GPT2LMHeadModel
Q_TKN = "<usr>"
A_TKN = "<sys>"
BOS = '</s>'
EOS = '</s>'
MASK = '<unused0>'
SENT = '<unused1>'
PAD = '<pad>'
tokenizer = PreTrainedTokenizerFast.from_pretrained("skt/kogpt2-base-v2",
bos_token=BOS,
eos_token=BOS,
unk_token='unk',
pad_token=PAD,
mask_token=MASK)
model = GPT2LMHeadModel.from_pretrained('skt/kogpt2-base-v2')
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/songys/Chatbot_data/master/ChatbotData.csv",
filename="ChatBotDataMain.csv",
)
ChatData = pd.read_csv("ChatBotDataMain.csv")
ChatData = ChatData[:300]
# print(ChatData.head())
#dataset 만들기
dataset = aboutDataSets.ChatDataset(ChatData)
batch_size = 32
num_workers = 0
def collate_batch(batch):
data = [item[0] for item in batch]
mask = [item[1] for item in batch]
label = [item[2] for item in batch]
return torch.LongTensor(data), torch.LongTensor(mask), torch.LongTensor(label)
# 아래 collate_batch 변수때문에 여기 한번 더 호출.
#dataloader 선언
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_set = aboutDataSets.ChatDataset(ChatData, max_len=40)
train_dataLoader = DataLoader(train_set,
batch_size=batch_size,
num_workers=num_workers,
shuffle=True,
collate_fn=collate_batch,)
model.to(device)
model.train()
lr = 3e-5
criterion = torch.nn.CrossEntropyLoss(reduction='none')
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
epoch = 10
sneg = -1e18
# 학습 시작
print("::start::")
for epoch in tqdm(range(epoch)): # 시각화를 위한 tqdm library
for batch_idx, samples in enumerate(train_dataLoader):
#print(batch_idx, samples)
optimizer.zero_grad()
token_ids, mask, label = samples
out = model(token_ids)
out = out.logits # returns a new tensor with the logit of the elements of input
mask_3d = mask.unsqueeze(dim=2).repeat_interleave(repeats=out.shape[2], dim=2)
mask_out = torch.where(mask_3d == 1, out, sneg * torch.ones_like(out))
loss = criterion(mask_out.transpose(2, 1), label)
avg_loss = loss.sum() / mask.sum() # avg_loss[0] / avg_loss[1] <- loss 정규화
avg_loss.backward()
# 학습 끝
optimizer.step()
print("end")
|
[
"Replace token_ids, mask, label = samples with token_ids, mask, label = [t.to(device) for t in samples]\nThis is because the samples generated by the dataloader is on CPU instead of CUDA by default. You have to move them to CUDA before performing forward.\n"
] |
[
0
] |
[] |
[] |
[
"cpu",
"gpu",
"python",
"pytorch"
] |
stackoverflow_0074514534_cpu_gpu_python_pytorch.txt
|
Q:
type object 'datetime.datetime' has no attribute 'datetime'
I have gotten the following error:
type object 'datetime.datetime' has no attribute 'datetime'
On the following line:
date = datetime.datetime(int(year), int(month), 1)
Does anybody know the reason for the error?
I imported datetime with from datetime import datetime if that helps
Thanks
A:
Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.
Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.
>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)
But, if you import datetime.datetime:
>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work
# as you imported the type, not the module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)
I suspect you or one of the modules you're using has imported like this:
from datetime import datetime.
A:
For python 3.3
from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)
A:
You should really import the module into its own alias.
import datetime as dt
my_datetime = dt.datetime(year, month, day)
The above has the following benefits over the other solutions:
Calling the variable my_datetime instead of date reduces confusion since there is already a date in the datetime module (datetime.date).
The module and the class (both called datetime) do not shadow each other.
A:
You should use
date = datetime(int(year), int(month), 1)
Or change
from datetime import datetime
to
import datetime
A:
If you have used:
from datetime import datetime
Then simply write the code as:
date = datetime(int(year), int(month), 1)
But if you have used:
import datetime
then only you can write:
date = datetime.datetime(int(2005), int(5), 1)
A:
I run into the same error maybe you have already imported the module by using only import datetime so change from datetime import datetime to only import datetime. It worked for me after I changed it back.
A:
import time
import datetime
from datetime import date,timedelta
You must have imported datetime from datetime.
A:
I found this to be a lot easier
from dateutil import relativedelta
relativedelta.relativedelta(end_time,start_time).seconds
A:
Avoid to write:
from datetime import datetime
datetime.datetime.function()
Solution No. 1:
import datetime
datetime.datetime.function()
Solution No. 2:
from datetime import datetime
datetime.function()
A:
from datetime import datetime
import time
from calendar import timegm
d = datetime.utcnow()
d = d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
utc_time = time.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = timegm(utc_time)
A:
delete one datetime from:
date = datetime.datetime(int(year), int(month), 1)
and you get this:
date = datetime(int(year), int(month), 1)
you already imported the first one with this:
from datetime import datetime
so its redundant.
|
type object 'datetime.datetime' has no attribute 'datetime'
|
I have gotten the following error:
type object 'datetime.datetime' has no attribute 'datetime'
On the following line:
date = datetime.datetime(int(year), int(month), 1)
Does anybody know the reason for the error?
I imported datetime with from datetime import datetime if that helps
Thanks
|
[
"Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.\nYour error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.\n>>> import datetime\n>>> datetime\n<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>\n>>> datetime.datetime(2001,5,1)\ndatetime.datetime(2001, 5, 1, 0, 0)\n\nBut, if you import datetime.datetime:\n>>> from datetime import datetime\n>>> datetime\n<type 'datetime.datetime'>\n>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work \n # as you imported the type, not the module\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: type object 'datetime.datetime' has no attribute 'datetime'\n>>> datetime(2001,5,1)\ndatetime.datetime(2001, 5, 1, 0, 0)\n\nI suspect you or one of the modules you're using has imported like this:\n from datetime import datetime.\n",
"For python 3.3\nfrom datetime import datetime, timedelta\nfuturedate = datetime.now() + timedelta(days=10)\n\n",
"You should really import the module into its own alias.\nimport datetime as dt\nmy_datetime = dt.datetime(year, month, day)\n\nThe above has the following benefits over the other solutions:\n\nCalling the variable my_datetime instead of date reduces confusion since there is already a date in the datetime module (datetime.date).\nThe module and the class (both called datetime) do not shadow each other.\n\n",
"You should use\ndate = datetime(int(year), int(month), 1)\n\nOr change\nfrom datetime import datetime\n\nto\nimport datetime\n\n",
"If you have used:\nfrom datetime import datetime\n\nThen simply write the code as:\ndate = datetime(int(year), int(month), 1)\n\nBut if you have used:\nimport datetime\n\nthen only you can write:\ndate = datetime.datetime(int(2005), int(5), 1)\n\n",
"I run into the same error maybe you have already imported the module by using only import datetime so change from datetime import datetime to only import datetime. It worked for me after I changed it back.\n",
"import time\nimport datetime\nfrom datetime import date,timedelta\n\nYou must have imported datetime from datetime.\n",
"I found this to be a lot easier \nfrom dateutil import relativedelta\nrelativedelta.relativedelta(end_time,start_time).seconds\n\n",
"Avoid to write:\nfrom datetime import datetime\ndatetime.datetime.function()\n\nSolution No. 1:\nimport datetime\ndatetime.datetime.function()\n\nSolution No. 2:\nfrom datetime import datetime\ndatetime.function()\n\n",
"from datetime import datetime\nimport time\nfrom calendar import timegm\nd = datetime.utcnow()\nd = d.strftime(\"%Y-%m-%dT%H:%M:%S.%fZ\")\nutc_time = time.strptime(d,\"%Y-%m-%dT%H:%M:%S.%fZ\")\nepoch_time = timegm(utc_time)\n\n",
"delete one datetime from:\ndate = datetime.datetime(int(year), int(month), 1)\n\nand you get this:\ndate = datetime(int(year), int(month), 1)\n\nyou already imported the first one with this:\nfrom datetime import datetime\nso its redundant.\n"
] |
[
333,
156,
23,
22,
6,
4,
3,
1,
1,
0,
0
] |
[
"The Problem Is That You Are Using The Tag\nfrom datetime\n\nI had The Same Problem You Need To use It Like This Instead\nimport datetime\n\n"
] |
[
-3
] |
[
"datetime",
"namespaces",
"python"
] |
stackoverflow_0012906402_datetime_namespaces_python.txt
|
Q:
Convert a specific date into fiscal year in python
I am trying to classified a specific date by fiscal year in python. My code is as follows. As you can see, the date I want to convert is 5/10/2017 which is in 2017 fiscal year,
!pip install fiscalyear
import fiscalyear
fiscalyear.START_MONTH = 9
New_CF_Date='5/10/2017 12:00:00 AM'
blank_pos=New_CF_Date.index(' 12:00:00 AM')
New_CF_Date_0=New_CF_Date[:blank_pos]
format = "%m/%d/%Y"
New_CF_Date = datetime.datetime.strptime(New_CF_Date_0, format)
intTargetFiscalYear = fiscalyear.FiscalYear.New_CF_Date.fiscal_year
print(intTargetFiscalYear)
However, it keeps showing error. AttributeError: type object 'FiscalYear' has no attribute 'New_CF_Date' . Please help me to find the bug.
A:
The fiscalyear.FiscalDate() does not take the datetime.datetime object as an input, so you may want to explicitly create a new fiscalyear.FiscalDate object using the datetime object.
import datetime
import fiscalyear
fiscalyear.setup_fiscal_calendar(start_month=9)
input_date='5/10/2017'
New_CF_Date = datetime.datetime.strptime(input_date, "%m/%d/%Y")
fiscal_date = fiscalyear.FiscalDate(New_CF_Date.year, New_CF_Date.month, New_CF_Date.day)
print(fiscal_date)
print(fiscal_date.fiscal_year)
Output:
2017-05-10
2017
|
Convert a specific date into fiscal year in python
|
I am trying to classified a specific date by fiscal year in python. My code is as follows. As you can see, the date I want to convert is 5/10/2017 which is in 2017 fiscal year,
!pip install fiscalyear
import fiscalyear
fiscalyear.START_MONTH = 9
New_CF_Date='5/10/2017 12:00:00 AM'
blank_pos=New_CF_Date.index(' 12:00:00 AM')
New_CF_Date_0=New_CF_Date[:blank_pos]
format = "%m/%d/%Y"
New_CF_Date = datetime.datetime.strptime(New_CF_Date_0, format)
intTargetFiscalYear = fiscalyear.FiscalYear.New_CF_Date.fiscal_year
print(intTargetFiscalYear)
However, it keeps showing error. AttributeError: type object 'FiscalYear' has no attribute 'New_CF_Date' . Please help me to find the bug.
|
[
"The fiscalyear.FiscalDate() does not take the datetime.datetime object as an input, so you may want to explicitly create a new fiscalyear.FiscalDate object using the datetime object.\nimport datetime\nimport fiscalyear\n\nfiscalyear.setup_fiscal_calendar(start_month=9)\n\ninput_date='5/10/2017'\nNew_CF_Date = datetime.datetime.strptime(input_date, \"%m/%d/%Y\")\nfiscal_date = fiscalyear.FiscalDate(New_CF_Date.year, New_CF_Date.month, New_CF_Date.day)\nprint(fiscal_date)\nprint(fiscal_date.fiscal_year)\n\nOutput:\n2017-05-10\n2017\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074514495_python.txt
|
Q:
How do I make my function work on negative numbers?
repeat = "y"
while repeat == "y":
#First get the two integers from the user
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
#Start the answer with 0
answer = 0
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
#loop while 'b' is even number
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
I am writing a program that uses Ancient Egyptian method to multiply. My program works for positive numbers but not negative. How do I fix it so that if both inputted values of user are negative. My result should give the product of any two positive, negative or one negative and positive number. My current program gives the product for any two positive values, or negative a value and positive b value. However, when user enters a negative b value, it produces infinite outputs.
A:
The issue is with the floor division b//2, when b is negative the result will be the lower integer, so -0.5 will be rounded to -1. To avoid it cast to an int a regular division b = int(b / 2).
After removing duplicate code the while loop looks like that
while b != 0:
if b % 2 != 0:
answer = answer + a
print(a * 2, int(b / 2))
a = a * 2
b = int(b / 2)
Edit
To get the correct sign you can check the expected sign after getting the numbers and multiple by 1 or -1 at the end. Since you only check a for the answer you need to work on a positive a
....
answer = 0
sign = 1 if a * b > 0 else -1
a = abs(a)
while b != 0:
....
print("The product is {}.".format(answer * sign))
A:
Welcome to Stack Overflow!!
This is what the program returned when I used -2 on the second integer (b).
A B
---
1 -2
2 -1
4 -1
8 -1
16 -1
If you notice, B stays on -1, while A starts increasing *2 and it does indifinitely because the while loop doesn't break.
Let's look at the code
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
#loop while 'b' is even number
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
So on the if section, you do a=a*2 and b=b//2 since b%2!=0 (-1%2 is -1). However, for the while to break, you need to get b=0, and you get that by doing b=b//2. The problem, as Guy said before, is that when you get b=-1 (as you saw on my example), doing -1//2 will give you -1, instead of the supposed 0 that you'll get if you do 1//2. Since you won't get b=0, the program never stops multiplying.
The solution is simple, as guy mentioned, use b=int(b/2)
EDIT for the negative numbers
The reason it gives you the wrong sign when you are using multiplication is this instruction
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a #<--------------- THE INSTRUCTION
a = a*2 #double every 'a' integers
# b = b//2 #halve the 'b' integers
b = int(b/2)
print(a, b)
answer = answer + a #<--------------- THE INSTRUCTION
since you get your answer by just adding up A, you will have these two wrong scenarios
----> a positive and b negative ->gives you positive (the sign of A) when it should be negative
----> a negative and b negative -> gives you negative (the sign of A) when it should be positive
I tried to find on google how you handled negative numbers with the egyptian method but i didn't find anything, so I guess you can handle that issue with whichever method you prefer.
An alternative to Guy method is multiplying the sign (1 or -1) to the result depending of b, not the multiplication
#------------------Your code-------------------------
#Start the answer with 0
answer = 0
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
#------------------The fix proposed-------------------------
#Start the answer with 0
answer = 0
sign = 1 if b > 0 else -1 #---------> the fix
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
and at the end, you multiply the sign with the general answer
#------------------Your code-------------------------
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
#------------------The fix proposed-------------------------
elif (b % 2 == 0):
a = a*2 #double every 'a' integers
b = int(b/2) #---->the previous fix to your first problem
print(a,b)
# b = b//2 #halve the 'b' integers
answer=answer*sign #---->The another fix: the multiplication i mentioned
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
With that, you should have the signs working properly
btw, the reason I changed the print insruction that you used to just print (a,b) at the end of the operation of the if sentence is to avoid redundant operations on the program.
|
How do I make my function work on negative numbers?
|
repeat = "y"
while repeat == "y":
#First get the two integers from the user
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
#Start the answer with 0
answer = 0
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
#loop while 'b' is even number
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
I am writing a program that uses Ancient Egyptian method to multiply. My program works for positive numbers but not negative. How do I fix it so that if both inputted values of user are negative. My result should give the product of any two positive, negative or one negative and positive number. My current program gives the product for any two positive values, or negative a value and positive b value. However, when user enters a negative b value, it produces infinite outputs.
|
[
"The issue is with the floor division b//2, when b is negative the result will be the lower integer, so -0.5 will be rounded to -1. To avoid it cast to an int a regular division b = int(b / 2).\nAfter removing duplicate code the while loop looks like that\nwhile b != 0:\n if b % 2 != 0:\n answer = answer + a\n print(a * 2, int(b / 2))\n a = a * 2\n b = int(b / 2)\n\nEdit\nTo get the correct sign you can check the expected sign after getting the numbers and multiple by 1 or -1 at the end. Since you only check a for the answer you need to work on a positive a\n....\nanswer = 0\nsign = 1 if a * b > 0 else -1\na = abs(a)\n\nwhile b != 0:\n ....\n\nprint(\"The product is {}.\".format(answer * sign))\n\n",
"Welcome to Stack Overflow!!\nThis is what the program returned when I used -2 on the second integer (b).\nA B\n---\n1 -2\n2 -1\n4 -1\n8 -1\n16 -1\n\nIf you notice, B stays on -1, while A starts increasing *2 and it does indifinitely because the while loop doesn't break.\nLet's look at the code\nwhile b != 0: \n #loop while 'b' is odd number\n if (b % 2 != 0):\n answer = answer + a \n print(a*2, b//2) \n a = a*2 #double every 'a' integers\n b = b//2 #halve the 'b' integers\n #loop while 'b' is even number\n elif (b % 2 == 0):\n print(a*2, b//2)\n a = a*2 #double every 'a' integers\n b = b//2 #halve the 'b' integers\n\nSo on the if section, you do a=a*2 and b=b//2 since b%2!=0 (-1%2 is -1). However, for the while to break, you need to get b=0, and you get that by doing b=b//2. The problem, as Guy said before, is that when you get b=-1 (as you saw on my example), doing -1//2 will give you -1, instead of the supposed 0 that you'll get if you do 1//2. Since you won't get b=0, the program never stops multiplying.\nThe solution is simple, as guy mentioned, use b=int(b/2)\nEDIT for the negative numbers\nThe reason it gives you the wrong sign when you are using multiplication is this instruction\n while b != 0: \n #loop while 'b' is odd number\n if (b % 2 != 0):\n answer = answer + a #<--------------- THE INSTRUCTION\n a = a*2 #double every 'a' integers\n # b = b//2 #halve the 'b' integers\n b = int(b/2)\n print(a, b) \n\nanswer = answer + a #<--------------- THE INSTRUCTION\n\nsince you get your answer by just adding up A, you will have these two wrong scenarios\n----> a positive and b negative ->gives you positive (the sign of A) when it should be negative\n----> a negative and b negative -> gives you negative (the sign of A) when it should be positive\nI tried to find on google how you handled negative numbers with the egyptian method but i didn't find anything, so I guess you can handle that issue with whichever method you prefer.\nAn alternative to Guy method is multiplying the sign (1 or -1) to the result depending of b, not the multiplication\n#------------------Your code-------------------------\n #Start the answer with 0\n answer = 0\n\n print(\"A\", \"B\")\n print(\"---\")\n print(a, b)\n #run loop until b is not zero\n\n#------------------The fix proposed-------------------------\n #Start the answer with 0\n answer = 0\n sign = 1 if b > 0 else -1 #---------> the fix\n print(\"A\", \"B\")\n print(\"---\")\n print(a, b)\n #run loop until b is not zero \n\nand at the end, you multiply the sign with the general answer\n#------------------Your code-------------------------\n elif (b % 2 == 0):\n print(a*2, b//2)\n a = a*2 #double every 'a' integers\n b = b//2 #halve the 'b' integers\n print(\"The product is {}.\".format(answer))\n repeat = input(\"Would you like to repeat? (y/n)\")\nprint(\"Goodbye!\")\n\n#------------------The fix proposed-------------------------\n elif (b % 2 == 0):\n a = a*2 #double every 'a' integers\n b = int(b/2) #---->the previous fix to your first problem\n print(a,b)\n # b = b//2 #halve the 'b' integers\n answer=answer*sign #---->The another fix: the multiplication i mentioned\n print(\"The product is {}.\".format(answer))\n repeat = input(\"Would you like to repeat? (y/n)\")\nprint(\"Goodbye!\")\n\n\nWith that, you should have the signs working properly\nbtw, the reason I changed the print insruction that you used to just print (a,b) at the end of the operation of the if sentence is to avoid redundant operations on the program.\n"
] |
[
0,
0
] |
[] |
[] |
[
"multiplication",
"python"
] |
stackoverflow_0074514540_multiplication_python.txt
|
Q:
django MultiValueDictKeyError when trying to retrieve "type"
I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here:
<div class="p-1 col-12 fw-bold mb-2">
<label class="text-r mb-1">Select File Type:</label>
<select name="type" class="form-select" aria-label="Default select example">
<option value="accounts">Accounts</option>
<option value="contacts">Contacts</option>
<option value="membership">Membership</option>
<option value="cg">Community Group</option>
<option value="cgm">Community Group Member</option>
<option value="so">Sales Order</option>
<option value="item">Item</option>
<option value="event">Event</option>
<option value="tt">Ticket Type</option>
<option value="si">Schedule Item</option>
<option value="attendee">Attendee</option>
</select>
</div>
<div class="p-1 col-12 fw-bold mb-2">
<label class="text-r mb-1">Organization Name:</label>
<input class="form-control" placeholder="Organization Name" type="text" name="name" required />
</div>
The python function that calls it is as follows:
class CsvView(View):
def post(self, request, *args, **kwargs):
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
data = request.POST["raees"]
name = request.POST["name"]
d_type = request.POST["type"]
data = list(data.split(","))
last = data[-1]
first = data[0]
data[0] = first.replace("[", "")
data[-1] = last.replace("]", "")
row = 0
col = 0
for i in data:
i = i.replace("'", "")
worksheet.write(row, col, i)
row = row + 1
workbook.close()
output.seek(0)
filename = f"{name} {d_type} Issue Tracker.xlsx"
response = HttpResponse(
output,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
response["Content-Disposition"] = "attachment; filename=%s" % filename
return response
The name = request.POST["name"] part seems to work ok, but not the d_type = request.POST["type"] part that I added. I also tried d_type = request.POST.get("type"), to no avail. The first one gets me the error indicated in the title but the latter code (as well as d_type = request.GET.get("type") just do not pull the value when needed. There's a previous function that does call "type" without any problems so I'm not sure what's needed here. Any help would be appreciated.
(If you're wondering about this 'previous function' that calls "type", it's as follows):
class HomeView(View):
def get(self, request, *args, **kwargs):
return render(request, "myapp/file-form.html")
def post(self, request, *args, **kwargs):
type = request.POST["type"]
file = request.FILES['file'].name
# file = request.FILES["file"].read().decode("utf-8")
name = request.POST["name"]
# dataset = Dataset().load(file, format="csv")
dataset = pd.read_csv(request.FILES['file'], encoding = "ISO-8859-1")
if type == "accounts":
errors = accounts_checker(dataset)
elif type == "contacts":
errors = contacts_checker(dataset)
elif type == "membership":
errors = member_ship_checker(dataset)
elif type == "cg":
errors = cg_checker(dataset)
elif type == "cgm":
errors = cgm_checker(dataset)
elif type == "so":
errors = so_checker(dataset)
elif type == "item":
errors = item_checker(dataset)
elif type == "event":
errors = event_checker(dataset)
elif type == "tt":
errors = tt_checker(dataset)
elif type == "si":
errors = si_checker(dataset)
elif type == "attendee":
errors = att_checker(dataset)
context = {
"results": errors,
"name": name,
}
return render(request, "myapp/results.html", context=context)
A:
You might try this as an alternative if you can't find the bug:
#your Forms.py
from django import forms
my_d_types=(("accounts","Accounts"),("contacts","Contacts"),
("membership","Membership"),("cg","Community Group"),
("cgm","Community Group Member"),("so","Sales Order"),
("item","Item"),("event","Event"),("tt","Ticket Type"),
("si","Schedule Item"),("attendee","Attendee")
)
class CsvViewForm(forms.Form):
#include this to replace existing 'd_type' variable in your form related to the CsvView
d_type=forms.ChoiceField(label='Select File Type:',choices=my_d_types,required=False)
#yourfile.HTML
#replace the section <select .... </select> with the following
<div>
<p>{{ form.d_type.label_tag }}</p>
<p>{{ form.d_type }}</p>
</div>
#your Views.py
from .forms import CsvViewForm
class CsvView(View):
form = CsvViewForm(request.POST)
You might also check that the HTML code includes "enctype="multipart/form-data"' in the start of the form tag depending how what the rest of the file has in it, since you only showed the bit you think might have the bug.
|
django MultiValueDictKeyError when trying to retrieve "type"
|
I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here:
<div class="p-1 col-12 fw-bold mb-2">
<label class="text-r mb-1">Select File Type:</label>
<select name="type" class="form-select" aria-label="Default select example">
<option value="accounts">Accounts</option>
<option value="contacts">Contacts</option>
<option value="membership">Membership</option>
<option value="cg">Community Group</option>
<option value="cgm">Community Group Member</option>
<option value="so">Sales Order</option>
<option value="item">Item</option>
<option value="event">Event</option>
<option value="tt">Ticket Type</option>
<option value="si">Schedule Item</option>
<option value="attendee">Attendee</option>
</select>
</div>
<div class="p-1 col-12 fw-bold mb-2">
<label class="text-r mb-1">Organization Name:</label>
<input class="form-control" placeholder="Organization Name" type="text" name="name" required />
</div>
The python function that calls it is as follows:
class CsvView(View):
def post(self, request, *args, **kwargs):
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
data = request.POST["raees"]
name = request.POST["name"]
d_type = request.POST["type"]
data = list(data.split(","))
last = data[-1]
first = data[0]
data[0] = first.replace("[", "")
data[-1] = last.replace("]", "")
row = 0
col = 0
for i in data:
i = i.replace("'", "")
worksheet.write(row, col, i)
row = row + 1
workbook.close()
output.seek(0)
filename = f"{name} {d_type} Issue Tracker.xlsx"
response = HttpResponse(
output,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
response["Content-Disposition"] = "attachment; filename=%s" % filename
return response
The name = request.POST["name"] part seems to work ok, but not the d_type = request.POST["type"] part that I added. I also tried d_type = request.POST.get("type"), to no avail. The first one gets me the error indicated in the title but the latter code (as well as d_type = request.GET.get("type") just do not pull the value when needed. There's a previous function that does call "type" without any problems so I'm not sure what's needed here. Any help would be appreciated.
(If you're wondering about this 'previous function' that calls "type", it's as follows):
class HomeView(View):
def get(self, request, *args, **kwargs):
return render(request, "myapp/file-form.html")
def post(self, request, *args, **kwargs):
type = request.POST["type"]
file = request.FILES['file'].name
# file = request.FILES["file"].read().decode("utf-8")
name = request.POST["name"]
# dataset = Dataset().load(file, format="csv")
dataset = pd.read_csv(request.FILES['file'], encoding = "ISO-8859-1")
if type == "accounts":
errors = accounts_checker(dataset)
elif type == "contacts":
errors = contacts_checker(dataset)
elif type == "membership":
errors = member_ship_checker(dataset)
elif type == "cg":
errors = cg_checker(dataset)
elif type == "cgm":
errors = cgm_checker(dataset)
elif type == "so":
errors = so_checker(dataset)
elif type == "item":
errors = item_checker(dataset)
elif type == "event":
errors = event_checker(dataset)
elif type == "tt":
errors = tt_checker(dataset)
elif type == "si":
errors = si_checker(dataset)
elif type == "attendee":
errors = att_checker(dataset)
context = {
"results": errors,
"name": name,
}
return render(request, "myapp/results.html", context=context)
|
[
"You might try this as an alternative if you can't find the bug:\n#your Forms.py\nfrom django import forms\nmy_d_types=((\"accounts\",\"Accounts\"),(\"contacts\",\"Contacts\"),\n (\"membership\",\"Membership\"),(\"cg\",\"Community Group\"),\n (\"cgm\",\"Community Group Member\"),(\"so\",\"Sales Order\"),\n (\"item\",\"Item\"),(\"event\",\"Event\"),(\"tt\",\"Ticket Type\"),\n (\"si\",\"Schedule Item\"),(\"attendee\",\"Attendee\")\n )\n\nclass CsvViewForm(forms.Form): \n #include this to replace existing 'd_type' variable in your form related to the CsvView\n d_type=forms.ChoiceField(label='Select File Type:',choices=my_d_types,required=False)\n\n#yourfile.HTML\n#replace the section <select .... </select> with the following\n <div> \n <p>{{ form.d_type.label_tag }}</p>\n <p>{{ form.d_type }}</p>\n</div>\n\n#your Views.py\nfrom .forms import CsvViewForm\n\nclass CsvView(View):\n form = CsvViewForm(request.POST)\n\nYou might also check that the HTML code includes \"enctype=\"multipart/form-data\"' in the start of the form tag depending how what the rest of the file has in it, since you only showed the bit you think might have the bug.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python",
"python_requests"
] |
stackoverflow_0074463372_django_python_python_requests.txt
|
Q:
Django: data from Views.py not displaying in HTML page
My home.html in div where I called the { data } to display in HTML
<div id= "main">
<h1> DATA SCRAPPER</h1>
<h2>Header Data from html Page</h2>
{ data }
</div>
The local host shows
But in terminal it is showing the scrapped data
Views.py where
def home(request):
soup= None
URL = 'https://www.abc.html'
page = requests.get(URL)
soup = bs(page.content, 'html.parser')
print(soup.h1.text)
head=soup.h1.text
return render(request, 'home.html', {'data': head})
A:
You're just missing some curly braces.
You need:
{{ data }}
not
{ data }
A:
For displaying variable data you have to use double bracket
{{data}}
A:
<!doctype html>
<html>
<head>
<title>code </title>
</head>
<body>
<div id="main">
<h1> data </h1>
<h2> header data from html </h2>
{{data}}
</div>
</body>
</html>
|
Django: data from Views.py not displaying in HTML page
|
My home.html in div where I called the { data } to display in HTML
<div id= "main">
<h1> DATA SCRAPPER</h1>
<h2>Header Data from html Page</h2>
{ data }
</div>
The local host shows
But in terminal it is showing the scrapped data
Views.py where
def home(request):
soup= None
URL = 'https://www.abc.html'
page = requests.get(URL)
soup = bs(page.content, 'html.parser')
print(soup.h1.text)
head=soup.h1.text
return render(request, 'home.html', {'data': head})
|
[
"You're just missing some curly braces.\nYou need:\n{{ data }}\n\nnot\n{ data }\n\n",
"For displaying variable data you have to use double bracket\n{{data}}\n\n",
"\n\n<!doctype html>\n<html>\n<head>\n<title>code </title>\n</head>\n<body>\n<div id=\"main\">\n<h1> data </h1>\n<h2> header data from html </h2>\n{{data}}\n</div>\n</body>\n</html>\n\n\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"django",
"django_models",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0074514579_django_django_models_django_templates_django_views_python.txt
|
Q:
Importing modules from different folders
I am following the pytest "Get Started" guide, and I just can't make it work. It seems to be something very elementary, but I just cant find it. The problem resides in importing modules from other folders, and, although I am following the official documentation, I cant make it work
Following PyPa and the official documentation, I have assembled the following file structure:
(lpthw) ex47_pypa> tree
.
├── dist
│ ├── example_package_vcmota-0.0.1-py3-none-any.whl
│ └── example_package_vcmota-0.0.1.tar.gz
├── LICENSE
├── pyproject.toml
├── README.md
├── src
│ └── example_package_VCMota
│ ├── example.py
│ └── __init__.py
└── tests
└── test_example.py
4 directories, 8 files
(lpthw) ex47_pypa> cat src/example_package_VCMota/example.py
def add_one(number):
return number+1
(lpthw) ex47_pypa> cat tests/test_example.py
# import example
# import example_package_VCMota
# from src/example_package_VCMota import example
# from src import example_package_VCMota/example
# import src
# import importlib
# from src.example_package_VCMota.example import add_one
from ..src.example import add_one
def test_dif():
assert add_one(2) == 9
(lpthw) ex47_pypa>
That seems to me as an ok implementation of everything in pytest pages, except that it does not work:
(lpthw) ex47_pypa> pytest
=============================================================================================== test session starts ================================================================================================
platform linux -- Python 3.10.8, pytest-7.1.3, pluggy-1.0.0
rootdir: /archive/MyBooks/LearnPython3TheHardWay/mypython/projects/ex47_pypa
collected 0 items / 1 error
====================================================================================================== ERRORS ======================================================================================================
______________________________________________________________________________________ ERROR collecting tests/test_example.py ______________________________________________________________________________________
ImportError while importing test module '/archive/MyBooks/LearnPython3TheHardWay/mypython/projects/ex47_pypa/tests/test_example.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.10/importlib/__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_example.py:8: in <module>
from example_package_VCMota.example import add_one
E ModuleNotFoundError: No module named 'example_package_VCMota'
============================================================================================= short test summary info ==============================================================================================
ERROR tests/test_example.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
================================================================================================= 1 error in 0.05s =================================================================================================
(lpthw) ex47_pypa>
The error is due to how I call the function add_one in example.p, and, as you may see in the test_example.py, I have tried every imaginable way of calling this function.
The only thing I know for sure is that the error has nothing to do with pytest: I have assembled another file structure:
teste> tree
.
├── src
│ ├── example.py
│ └── __init__.py
└── tests
└── test_example.py
2 directories, 3 files
teste> cd tests/
tests> cat test_example.py
# import example
# import example_package_VCMota
# from src/example_package_VCMota import example
# from src import example_package_VCMota/example
# import src
# import importlib
# from src.example_package_VCMota.example import add_one
from ..src.example import add_one
def test_dif():
assert add_one(2) == 9
tests>
but it still does not work:
tests>python test_example.py
Traceback (most recent call last):
File "/archive/MyBooks/LearnPython3TheHardWay/mypython/projects/teste/tests/test_example.py", line 10, in <module>
from ..src.example import add_one
ImportError: attempted relative import with no known parent package
tests>
I am aware that there are multiple other ways of importing modules from other folders, as stated in this 11 years old post from stackoverflow itself, but the dot one is surely the simplest way, and, since it is clearly stated in the official documentation, it should work, but I cant make it work.
Thank you all for your attention.
EDIT:
Following Raphael's comments, I have started to suspect of errors/problems in my python installs, and therefore assembled the following file structure inside a virtual machine running Ubuntu LTS 20:
├── source
│ ├── example.py
│ └── init.py
└── tests
└── test_example.py
where I have tried multiple import commands in test_example.py, such as:
from .source.example import add_one
from ...source.example import add_one
and so on, and, again, none have worked. Since I am running Gentoo in my main machine, I suspect that this test indicates that whatever is the issue, it is certainly not with my python installs.
A:
It's a common issue in Python that the tests for a package cannot find the package itself.
The main reason for the issues is your working directory. You cannot just cd into the tests folder and run the tests. In fact, you need to be one level above your project folder, so you need to be in ex47_pypa/.. and then run python -m ex47_pypa.tests.test_example.
This will give Python enough directory hierarchy to actually resolve the relative imports in your tests, so the from ..src.example can be resolved.
I've created an experimental, new import library: ultraimport
It gives you more control over your imports and lets you do file system based imports.
In your test_example.py your could then write:
import ultraimport
add_one = ultraimport('__dir__/../src/example_package_VCMota/example.py', 'add_one')
This will always work, no matter how you run your code or what's your current working directory or what's in your sys.path.
|
Importing modules from different folders
|
I am following the pytest "Get Started" guide, and I just can't make it work. It seems to be something very elementary, but I just cant find it. The problem resides in importing modules from other folders, and, although I am following the official documentation, I cant make it work
Following PyPa and the official documentation, I have assembled the following file structure:
(lpthw) ex47_pypa> tree
.
├── dist
│ ├── example_package_vcmota-0.0.1-py3-none-any.whl
│ └── example_package_vcmota-0.0.1.tar.gz
├── LICENSE
├── pyproject.toml
├── README.md
├── src
│ └── example_package_VCMota
│ ├── example.py
│ └── __init__.py
└── tests
└── test_example.py
4 directories, 8 files
(lpthw) ex47_pypa> cat src/example_package_VCMota/example.py
def add_one(number):
return number+1
(lpthw) ex47_pypa> cat tests/test_example.py
# import example
# import example_package_VCMota
# from src/example_package_VCMota import example
# from src import example_package_VCMota/example
# import src
# import importlib
# from src.example_package_VCMota.example import add_one
from ..src.example import add_one
def test_dif():
assert add_one(2) == 9
(lpthw) ex47_pypa>
That seems to me as an ok implementation of everything in pytest pages, except that it does not work:
(lpthw) ex47_pypa> pytest
=============================================================================================== test session starts ================================================================================================
platform linux -- Python 3.10.8, pytest-7.1.3, pluggy-1.0.0
rootdir: /archive/MyBooks/LearnPython3TheHardWay/mypython/projects/ex47_pypa
collected 0 items / 1 error
====================================================================================================== ERRORS ======================================================================================================
______________________________________________________________________________________ ERROR collecting tests/test_example.py ______________________________________________________________________________________
ImportError while importing test module '/archive/MyBooks/LearnPython3TheHardWay/mypython/projects/ex47_pypa/tests/test_example.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.10/importlib/__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_example.py:8: in <module>
from example_package_VCMota.example import add_one
E ModuleNotFoundError: No module named 'example_package_VCMota'
============================================================================================= short test summary info ==============================================================================================
ERROR tests/test_example.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
================================================================================================= 1 error in 0.05s =================================================================================================
(lpthw) ex47_pypa>
The error is due to how I call the function add_one in example.p, and, as you may see in the test_example.py, I have tried every imaginable way of calling this function.
The only thing I know for sure is that the error has nothing to do with pytest: I have assembled another file structure:
teste> tree
.
├── src
│ ├── example.py
│ └── __init__.py
└── tests
└── test_example.py
2 directories, 3 files
teste> cd tests/
tests> cat test_example.py
# import example
# import example_package_VCMota
# from src/example_package_VCMota import example
# from src import example_package_VCMota/example
# import src
# import importlib
# from src.example_package_VCMota.example import add_one
from ..src.example import add_one
def test_dif():
assert add_one(2) == 9
tests>
but it still does not work:
tests>python test_example.py
Traceback (most recent call last):
File "/archive/MyBooks/LearnPython3TheHardWay/mypython/projects/teste/tests/test_example.py", line 10, in <module>
from ..src.example import add_one
ImportError: attempted relative import with no known parent package
tests>
I am aware that there are multiple other ways of importing modules from other folders, as stated in this 11 years old post from stackoverflow itself, but the dot one is surely the simplest way, and, since it is clearly stated in the official documentation, it should work, but I cant make it work.
Thank you all for your attention.
EDIT:
Following Raphael's comments, I have started to suspect of errors/problems in my python installs, and therefore assembled the following file structure inside a virtual machine running Ubuntu LTS 20:
├── source
│ ├── example.py
│ └── init.py
└── tests
└── test_example.py
where I have tried multiple import commands in test_example.py, such as:
from .source.example import add_one
from ...source.example import add_one
and so on, and, again, none have worked. Since I am running Gentoo in my main machine, I suspect that this test indicates that whatever is the issue, it is certainly not with my python installs.
|
[
"It's a common issue in Python that the tests for a package cannot find the package itself.\nThe main reason for the issues is your working directory. You cannot just cd into the tests folder and run the tests. In fact, you need to be one level above your project folder, so you need to be in ex47_pypa/.. and then run python -m ex47_pypa.tests.test_example.\nThis will give Python enough directory hierarchy to actually resolve the relative imports in your tests, so the from ..src.example can be resolved.\nI've created an experimental, new import library: ultraimport\nIt gives you more control over your imports and lets you do file system based imports.\nIn your test_example.py your could then write:\nimport ultraimport\nadd_one = ultraimport('__dir__/../src/example_package_VCMota/example.py', 'add_one')\n\nThis will always work, no matter how you run your code or what's your current working directory or what's in your sys.path.\n"
] |
[
0
] |
[] |
[] |
[
"directory",
"module",
"pytest",
"python"
] |
stackoverflow_0074268066_directory_module_pytest_python.txt
|
Q:
Standard way to embed version into Python package?
Is there a standard way to associate version string with a Python package in such way that I could do the following?
import foo
print(foo.version)
I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that I found was to have import __version__ in my foo/__init__.py and then have __version__.py generated by setup.py.
A:
Not directly an answer to your question, but you should consider naming it __version__, not version.
This is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.
Usually, __version__ is a string, but sometimes it's also a float or tuple.
As mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:
Module Level Dunder Names
Module level "dunders" (i.e. names with two leading and two trailing
underscores) such as __all__, __author__, __version__, etc.
should be placed after the module docstring but before any import
statements except from __future__ imports.
You should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).
A:
I use a single _version.py file as the "once cannonical place" to store version information:
It provides a __version__ attribute.
It provides the standard metadata version. Therefore it will be detected by pkg_resources or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345).
It doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.)
There is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions.
Here is how it works: the "one canonical place" to store the version number is a .py file, named "_version.py" which is in your Python package, for example in myniftyapp/_version.py. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like:
__version__ = "3.6.5"
And so your setup.py opens the file and parses it, with code like:
import re
VERSIONFILE="myniftyapp/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
Then your setup.py passes that string as the value of the "version" argument to setup(), thus satisfying feature 2.
To satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from myniftyapp/__init__.py like this:
from _version import __version__
Here is an example of this technique that I've been using for years.
The code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation.
Here is example code of importing the version.
If you see anything wrong with this approach, please let me know.
A:
Rewritten 2017-05
After 13+ years of writing Python code and managing various packages, I came to the conclusion that DIY is maybe not the best approach.
I started using the pbr package for dealing with versioning in my packages. If you are using git as your SCM, this will fit into your workflow like magic, saving your weeks of work (you will be surprised about how complex the issue can be).
As of today, pbr has 12M mongthly downloads, and reaching this level didn't include any dirty tricks. It was only one thing -- fixing a common packaging problem in a very simple way.
pbr can do more of the package maintenance burden, and is not limited to versioning, but it does not force you to adopt all its benefits.
So to give you an idea about how it looks to adopt pbr in one commit have a look switching packaging to pbr
Probably you would observed that the version is not stored at all in the repository. PBR does detect it from Git branches and tags.
No need to worry about what happens when you do not have a git repository because pbr does "compile" and cache the version when you package or install the applications, so there is no runtime dependency on git.
Old solution
Here is the best solution I've seen so far and it also explains why:
Inside yourpackage/version.py:
# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '0.12'
Inside yourpackage/__init__.py:
from .version import __version__
Inside setup.py:
exec(open('yourpackage/version.py').read())
setup(
...
version=__version__,
...
If you know another approach that seems to be better let me know.
A:
Per the deferred [STOP PRESS: rejected] PEP 396 (Module Version Numbers), there is a proposed way to do this. It describes, with rationale, an (admittedly optional) standard for modules to follow. Here's a snippet:
When a module (or package) includes a version number, the version SHOULD be available in the __version__ attribute.
For modules which live inside a namespace package, the module SHOULD include the __version__ attribute. The namespace package itself SHOULD NOT include its own __version__ attribute.
The __version__ attribute's value SHOULD be a string.
A:
There is a slightly simpler alternative to some of the other answers:
__version_info__ = ('1', '2', '3')
__version__ = '.'.join(__version_info__)
(And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using str().)
Of course, from what I've seen, people tend to use something like the previously-mentioned version when using __version_info__, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, int() and str() can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)
This is, of course, my own view, and I would gladly like others' input on using a numerical tuple.
As shezi reminded me, (lexical) comparisons of number strings do not necessarily have the same result as direct numerical comparisons; leading zeroes would be required to provide for that. So in the end, storing __version_info__ (or whatever it would be called) as a tuple of integer values would allow for more efficient version comparisons.
A:
Many of these solutions here ignore git version tags which still means you have to track version in multiple places (bad). I approached this with the following goals:
Derive all python version references from a tag in the git repo
Automate git tag/push and setup.py upload steps with a single command that takes no inputs.
How it works:
From a make release command, the last tagged version in the git repo is found and incremented. The tag is pushed back to origin.
The Makefile stores the version in src/_version.py where it will be read by setup.py and also included in the release. Do not check _version.py into source control!
setup.py command reads the new version string from package.__version__.
Details:
Makefile
# remove optional 'v' and trailing hash "v1.0-N-HASH" -> "v1.0-N"
git_describe_ver = $(shell git describe --tags | sed -E -e 's/^v//' -e 's/(.*)-.*/\1/')
git_tag_ver = $(shell git describe --abbrev=0)
next_patch_ver = $(shell python versionbump.py --patch $(call git_tag_ver))
next_minor_ver = $(shell python versionbump.py --minor $(call git_tag_ver))
next_major_ver = $(shell python versionbump.py --major $(call git_tag_ver))
.PHONY: ${MODULE}/_version.py
${MODULE}/_version.py:
echo '__version__ = "$(call git_describe_ver)"' > $@
.PHONY: release
release: test lint mypy
git tag -a $(call next_patch_ver)
$(MAKE) ${MODULE}/_version.py
python setup.py check sdist upload # (legacy "upload" method)
# twine upload dist/* (preferred method)
git push origin master --tags
The release target always increments the 3rd version digit, but you can use the next_minor_ver or next_major_ver to increment the other digits. The commands rely on the versionbump.py script that is checked into the root of the repo
versionbump.py
"""An auto-increment tool for version strings."""
import sys
import unittest
import click
from click.testing import CliRunner # type: ignore
__version__ = '0.1'
MIN_DIGITS = 2
MAX_DIGITS = 3
@click.command()
@click.argument('version')
@click.option('--major', 'bump_idx', flag_value=0, help='Increment major number.')
@click.option('--minor', 'bump_idx', flag_value=1, help='Increment minor number.')
@click.option('--patch', 'bump_idx', flag_value=2, default=True, help='Increment patch number.')
def cli(version: str, bump_idx: int) -> None:
"""Bumps a MAJOR.MINOR.PATCH version string at the specified index location or 'patch' digit. An
optional 'v' prefix is allowed and will be included in the output if found."""
prefix = version[0] if version[0].isalpha() else ''
digits = version.lower().lstrip('v').split('.')
if len(digits) > MAX_DIGITS:
click.secho('ERROR: Too many digits', fg='red', err=True)
sys.exit(1)
digits = (digits + ['0'] * MAX_DIGITS)[:MAX_DIGITS] # Extend total digits to max.
digits[bump_idx] = str(int(digits[bump_idx]) + 1) # Increment the desired digit.
# Zero rightmost digits after bump position.
for i in range(bump_idx + 1, MAX_DIGITS):
digits[i] = '0'
digits = digits[:max(MIN_DIGITS, bump_idx + 1)] # Trim rightmost digits.
click.echo(prefix + '.'.join(digits), nl=False)
if __name__ == '__main__':
cli() # pylint: disable=no-value-for-parameter
This does the heavy lifting how to process and increment the version number from git.
__init__.py
The my_module/_version.py file is imported into my_module/__init__.py. Put any static install config here that you want distributed with your module.
from ._version import __version__
__author__ = ''
__email__ = ''
setup.py
The last step is to read the version info from the my_module module.
from setuptools import setup, find_packages
pkg_vars = {}
with open("{MODULE}/_version.py") as fp:
exec(fp.read(), pkg_vars)
setup(
version=pkg_vars['__version__'],
...
...
)
Of course, for all of this to work you'll have to have at least one version tag in your repo to start.
git tag -a v0.0.1
A:
I use a JSON file in the package dir. This fits Zooko's requirements.
Inside pkg_dir/pkg_info.json:
{"version": "0.1.0"}
Inside setup.py:
from distutils.core import setup
import json
with open('pkg_dir/pkg_info.json') as fp:
_info = json.load(fp)
setup(
version=_info['version'],
...
)
Inside pkg_dir/__init__.py:
import json
from os.path import dirname
with open(dirname(__file__) + '/pkg_info.json') as fp:
_info = json.load(fp)
__version__ = _info['version']
I also put other information in pkg_info.json, like author. I
like to use JSON because I can automate management of metadata.
A:
Lots of work toward uniform versioning and in support of conventions has been completed since this question was first asked. Palatable options are now detailed in the Python Packaging User Guide. Also noteworthy is that version number schemes are relatively strict in Python per PEP 440, and so keeping things sane is critical if your package will be released to the Cheese Shop.
Here's a shortened breakdown of versioning options:
Read the file in setup.py (setuptools) and get the version.
Use an external build tool (to update both __init__.py as well as source control), e.g. bump2version, changes or zest.releaser.
Set the value to a __version__ global variable in a specific module.
Place the value in a simple VERSION text file for both setup.py and code to read.
Set the value via a setup.py release, and use importlib.metadata to pick it up at runtime. (Warning, there are pre-3.8 and post-3.8 versions.)
Set the value to __version__ in sample/__init__.py and import sample in setup.py.
Use setuptools_scm to extract versioning from source control so that it's the canonical reference, not code.
NOTE that (7) might be the most modern approach (build metadata is independent of code, published by automation). Also NOTE that if setup is used for package release that a simple python3 setup.py --version will report the version directly.
A:
Also worth noting is that as well as __version__ being a semi-std. in python so is __version_info__ which is a tuple, in the simple cases you can just do something like:
__version__ = '1.2.3'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])
...and you can get the __version__ string from a file, or whatever.
A:
arrow handles it in an interesting way.
Now (since 2e5031b)
In arrow/__init__.py:
__version__ = 'x.y.z'
In setup.py:
from arrow import __version__
setup(
name='arrow',
version=__version__,
# [...]
)
Before
In arrow/__init__.py:
__version__ = 'x.y.z'
VERSION = __version__
In setup.py:
def grep(attrname):
pattern = r"{0}\W*=\W*'([^']+)'".format(attrname)
strval, = re.findall(pattern, file_text)
return strval
file_text = read(fpath('arrow/__init__.py'))
setup(
name='arrow',
version=grep('__version__'),
# [...]
)
A:
There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner
Embed the version in setup.py and have setup.py generate a module (e.g. version.py) containing only version info, that's imported by your package, or
The reverse: put the version info in your package itself, and import that to set the version in setup.py
A:
I also saw another style:
>>> django.VERSION
(1, 1, 0, 'final', 0)
A:
Using setuptools and pbr
There is not a standard way to manage version, but the standard way to manage your packages is setuptools.
The best solution I've found overall for managing version is to use setuptools with the pbr extension. This is now my standard way of managing version.
Setting up your project for full packaging may be overkill for simple projects, but if you need to manage version, you are probably at the right level to just set everything up. Doing so also makes your package releasable at PyPi so everyone can download and use it with Pip.
PBR moves most metadata out of the setup.py tools and into a setup.cfg file that is then used as a source for most metadata, which can include version. This allows the metadata to be packaged into an executable using something like pyinstaller if needed (if so, you will probably need this info), and separates the metadata from the other package management/setup scripts. You can directly update the version string in setup.cfg manually, and it will be pulled into the *.egg-info folder when building your package releases. Your scripts can then access the version from the metadata using various methods (these processes are outlined in sections below).
When using Git for VCS/SCM, this setup is even better, as it will pull in a lot of the metadata from Git so that your repo can be your primary source of truth for some of the metadata, including version, authors, changelogs, etc. For version specifically, it will create a version string for the current commit based on git tags in the repo.
PyPA - Packaging Python Packages with SetupTools - Tutorial
PBR latest build usage documentation - How to setup an 8-line setup.py and a setup.cfg file with the metadata.
As PBR will pull version, author, changelog and other info directly from your git repo, so some of the metadata in setup.cfg can be left out and auto generated whenever a distribution is created for your package (using setup.py)
Get the current version in real-time
setuptools will pull the latest info in real-time using setup.py:
python setup.py --version
This will pull the latest version either from the setup.cfg file, or from the git repo, based on the latest commit that was made and tags that exist in the repo. This command doesn't update the version in a distribution though.
Updating the version metadata
When you create a distribution with setup.py (i.e. py setup.py sdist, for example), then all the current info will be extracted and stored in the distribution. This essentially runs the setup.py --version command and then stores that version info into the package.egg-info folder in a set of files that store distribution metadata.
Note on process to update version meta-data:
If you are not using pbr to pull version data from git, then just update your setup.cfg directly with new version info (easy enough, but make sure this is a standard part of your release process).
If you are using git, and you don't need to create a source or binary distribution (using python setup.py sdist or one of the python setup.py bdist_xxx commands) the simplest way to update the git repo info into your <mypackage>.egg-info metadata folder is to just run the python setup.py install command. This will run all the PBR functions related to pulling metadata from the git repo and update your local .egg-info folder, install script executables for any entry-points you have defined, and other functions you can see from the output when you run this command.
Note that the .egg-info folder is generally excluded from being stored in the git repo itself in standard Python .gitignore files (such as from Gitignore.IO), as it can be generated from your source. If it is excluded, make sure you have a standard "release process" to get the metadata updated locally before release, and any package you upload to PyPi.org or otherwise distribute must include this data to have the correct version. If you want the Git repo to contain this info, you can exclude specific files from being ignored (i.e. add !*.egg-info/PKG_INFO to .gitignore)
Accessing the version from a script
You can access the metadata from the current build within Python scripts in the package itself. For version, for example, there are several ways to do this I have found so far:
## This one is a new built-in as of Python 3.8.0 should become the standard
from importlib.metadata import version
v0 = version("mypackage")
print('v0 {}'.format(v0))
## I don't like this one because the version method is hidden
import pkg_resources # part of setuptools
v1 = pkg_resources.require("mypackage")[0].version
print('v1 {}'.format(v1))
# Probably best for pre v3.8.0 - the output without .version is just a longer string with
# both the package name, a space, and the version string
import pkg_resources # part of setuptools
v2 = pkg_resources.get_distribution('mypackage').version
print('v2 {}'.format(v2))
## This one seems to be slower, and with pyinstaller makes the exe a lot bigger
from pbr.version import VersionInfo
v3 = VersionInfo('mypackage').release_string()
print('v3 {}'.format(v3))
You can put one of these directly in your __init__.py for the package to extract the version info as follows, similar to some other answers:
__all__ = (
'__version__',
'my_package_name'
)
import pkg_resources # part of setuptools
__version__ = pkg_resources.get_distribution("mypackage").version
A:
After several hours of trying to find the simplest reliable solution, here are the parts:
create a version.py file INSIDE the folder of your package "/mypackage":
# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '1.2.7'
in setup.py:
exec(open('mypackage/version.py').read())
setup(
name='mypackage',
version=__version__,
in the main folder init.py:
from .version import __version__
The exec() function runs the script outside of any imports, since setup.py is run before the module can be imported. You still only need to manage the version number in one file in one place, but unfortunately it is not in setup.py. (that's the downside, but having no import bugs is the upside)
A:
pbr with bump2version
This solution was derived from this article
The use case - python GUI package distributed via PyInstaller. Needs to show version info.
Here is the structure of the project packagex
packagex
├── packagex
│ ├── __init__.py
│ ├── main.py
│ └── _version.py
├── packagex.spec
├── LICENSE
├── README.md
├── .bumpversion.cfg
├── requirements.txt
├── setup.cfg
└── setup.py
where setup.py is
# setup.py
import os
import setuptools
about = {}
with open("packagex/_version.py") as f:
exec(f.read(), about)
os.environ["PBR_VERSION"] = about["__version__"]
setuptools.setup(
setup_requires=["pbr"],
pbr=True,
version=about["__version__"],
)
packagex/_version.py contains just
__version__ = "0.0.1"
and packagex/__init__.py
from ._version import __version__
and for .bumpversion.cfg
[bumpversion]
current_version = 0.0.1
commit = False
tag = False
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\-(?P<release>[a-z]+)(?P<build>\d+))?
serialize =
{major}.{minor}.{patch}-{release}{build}
{major}.{minor}.{patch}
[bumpversion:part:release]
optional_value = prod
first_value = dev
values =
dev
prod
[bumpversion:file:packagex/_version.py]
A:
I prefer to read the package version from installation environment.
This is my src/foo/_version.py:
from pkg_resources import get_distribution
__version__ = get_distribution('foo').version
Makesure foo is always already installed, that's why a src/ layer is required to prevent foo imported without installation.
In the setup.py, I use setuptools-scm to generate the version automatically.
Update in 2022.7.5:
There is another way, which is my faviourate now. Use setuptools-scm to generate a _version.py file.
setup(
...
use_scm_version={
'write_to':
'src/foo/_version.py',
'write_to_template':
'"""Generated version file."""\n'
'__version__ = "{version}"\n',
},
)
A:
Create a file named by _version.txt in the same folder as __init__.py and write version as a single line:
0.8.2
Read this infomation from file _version.txt in __init__.py:
import os
def get_version():
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), "_version.txt")) as f:
return f.read().strip()
__version__ = get_version()
A:
I described a standard and modern way here, relying on setuptools_scm.
This pattern has worked successfully for dozens of published packages over the past years, so I can warmly recommend it.
Note that you do not need the getversion package to implement this pattern. It just happens that the getversion documentation hosts this tip.
A:
Using setuptools and pyproject.toml
Setuptools now offers a way to dynamically get version in pyproject.toml
Reproducing the example here, you can create something like the following in your pyproject.toml
# ...
[project]
name = "my_package"
dynamic = ["version"]
# ...
[tool.setuptools.dynamic]
version = {attr = "my_package.__version__"}
|
Standard way to embed version into Python package?
|
Is there a standard way to associate version string with a Python package in such way that I could do the following?
import foo
print(foo.version)
I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that I found was to have import __version__ in my foo/__init__.py and then have __version__.py generated by setup.py.
|
[
"Not directly an answer to your question, but you should consider naming it __version__, not version.\nThis is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.\nUsually, __version__ is a string, but sometimes it's also a float or tuple.\nAs mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:\n\nModule Level Dunder Names\nModule level \"dunders\" (i.e. names with two leading and two trailing\nunderscores) such as __all__, __author__, __version__, etc.\nshould be placed after the module docstring but before any import\nstatements except from __future__ imports.\n\nYou should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).\n",
"I use a single _version.py file as the \"once cannonical place\" to store version information:\n\nIt provides a __version__ attribute.\nIt provides the standard metadata version. Therefore it will be detected by pkg_resources or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345).\nIt doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.)\nThere is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions.\n\nHere is how it works: the \"one canonical place\" to store the version number is a .py file, named \"_version.py\" which is in your Python package, for example in myniftyapp/_version.py. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like:\n__version__ = \"3.6.5\"\n\nAnd so your setup.py opens the file and parses it, with code like:\nimport re\nVERSIONFILE=\"myniftyapp/_version.py\"\nverstrline = open(VERSIONFILE, \"rt\").read()\nVSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\nmo = re.search(VSRE, verstrline, re.M)\nif mo:\n verstr = mo.group(1)\nelse:\n raise RuntimeError(\"Unable to find version string in %s.\" % (VERSIONFILE,))\n\nThen your setup.py passes that string as the value of the \"version\" argument to setup(), thus satisfying feature 2.\nTo satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from myniftyapp/__init__.py like this:\nfrom _version import __version__\n\nHere is an example of this technique that I've been using for years.\nThe code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation.\nHere is example code of importing the version.\nIf you see anything wrong with this approach, please let me know.\n",
"Rewritten 2017-05\nAfter 13+ years of writing Python code and managing various packages, I came to the conclusion that DIY is maybe not the best approach.\nI started using the pbr package for dealing with versioning in my packages. If you are using git as your SCM, this will fit into your workflow like magic, saving your weeks of work (you will be surprised about how complex the issue can be).\nAs of today, pbr has 12M mongthly downloads, and reaching this level didn't include any dirty tricks. It was only one thing -- fixing a common packaging problem in a very simple way.\npbr can do more of the package maintenance burden, and is not limited to versioning, but it does not force you to adopt all its benefits.\nSo to give you an idea about how it looks to adopt pbr in one commit have a look switching packaging to pbr\nProbably you would observed that the version is not stored at all in the repository. PBR does detect it from Git branches and tags.\nNo need to worry about what happens when you do not have a git repository because pbr does \"compile\" and cache the version when you package or install the applications, so there is no runtime dependency on git.\nOld solution\nHere is the best solution I've seen so far and it also explains why:\nInside yourpackage/version.py:\n# Store the version here so:\n# 1) we don't load dependencies by storing it in __init__.py\n# 2) we can import it in setup.py for the same reason\n# 3) we can import it into your module module\n__version__ = '0.12'\n\nInside yourpackage/__init__.py:\nfrom .version import __version__\n\nInside setup.py:\nexec(open('yourpackage/version.py').read())\nsetup(\n ...\n version=__version__,\n ...\n\nIf you know another approach that seems to be better let me know.\n",
"Per the deferred [STOP PRESS: rejected] PEP 396 (Module Version Numbers), there is a proposed way to do this. It describes, with rationale, an (admittedly optional) standard for modules to follow. Here's a snippet:\n\n\nWhen a module (or package) includes a version number, the version SHOULD be available in the __version__ attribute.\n\n\n\n\nFor modules which live inside a namespace package, the module SHOULD include the __version__ attribute. The namespace package itself SHOULD NOT include its own __version__ attribute.\n\n\n\n\nThe __version__ attribute's value SHOULD be a string.\n\n\n",
"There is a slightly simpler alternative to some of the other answers:\n__version_info__ = ('1', '2', '3')\n__version__ = '.'.join(__version_info__)\n\n(And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using str().)\nOf course, from what I've seen, people tend to use something like the previously-mentioned version when using __version_info__, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, int() and str() can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)\nThis is, of course, my own view, and I would gladly like others' input on using a numerical tuple.\n\nAs shezi reminded me, (lexical) comparisons of number strings do not necessarily have the same result as direct numerical comparisons; leading zeroes would be required to provide for that. So in the end, storing __version_info__ (or whatever it would be called) as a tuple of integer values would allow for more efficient version comparisons.\n",
"Many of these solutions here ignore git version tags which still means you have to track version in multiple places (bad). I approached this with the following goals:\n\nDerive all python version references from a tag in the git repo\nAutomate git tag/push and setup.py upload steps with a single command that takes no inputs.\n\nHow it works:\n\nFrom a make release command, the last tagged version in the git repo is found and incremented. The tag is pushed back to origin.\nThe Makefile stores the version in src/_version.py where it will be read by setup.py and also included in the release. Do not check _version.py into source control!\nsetup.py command reads the new version string from package.__version__.\n\nDetails:\nMakefile\n# remove optional 'v' and trailing hash \"v1.0-N-HASH\" -> \"v1.0-N\"\ngit_describe_ver = $(shell git describe --tags | sed -E -e 's/^v//' -e 's/(.*)-.*/\\1/')\ngit_tag_ver = $(shell git describe --abbrev=0)\nnext_patch_ver = $(shell python versionbump.py --patch $(call git_tag_ver))\nnext_minor_ver = $(shell python versionbump.py --minor $(call git_tag_ver))\nnext_major_ver = $(shell python versionbump.py --major $(call git_tag_ver))\n\n.PHONY: ${MODULE}/_version.py\n${MODULE}/_version.py:\n echo '__version__ = \"$(call git_describe_ver)\"' > $@\n\n.PHONY: release\nrelease: test lint mypy\n git tag -a $(call next_patch_ver)\n $(MAKE) ${MODULE}/_version.py\n python setup.py check sdist upload # (legacy \"upload\" method)\n # twine upload dist/* (preferred method)\n git push origin master --tags\n\nThe release target always increments the 3rd version digit, but you can use the next_minor_ver or next_major_ver to increment the other digits. The commands rely on the versionbump.py script that is checked into the root of the repo\nversionbump.py\n\"\"\"An auto-increment tool for version strings.\"\"\"\n\nimport sys\nimport unittest\n\nimport click\nfrom click.testing import CliRunner # type: ignore\n\n__version__ = '0.1'\n\nMIN_DIGITS = 2\nMAX_DIGITS = 3\n\n\n@click.command()\n@click.argument('version')\n@click.option('--major', 'bump_idx', flag_value=0, help='Increment major number.')\n@click.option('--minor', 'bump_idx', flag_value=1, help='Increment minor number.')\n@click.option('--patch', 'bump_idx', flag_value=2, default=True, help='Increment patch number.')\ndef cli(version: str, bump_idx: int) -> None:\n \"\"\"Bumps a MAJOR.MINOR.PATCH version string at the specified index location or 'patch' digit. An\n optional 'v' prefix is allowed and will be included in the output if found.\"\"\"\n prefix = version[0] if version[0].isalpha() else ''\n digits = version.lower().lstrip('v').split('.')\n\n if len(digits) > MAX_DIGITS:\n click.secho('ERROR: Too many digits', fg='red', err=True)\n sys.exit(1)\n\n digits = (digits + ['0'] * MAX_DIGITS)[:MAX_DIGITS] # Extend total digits to max.\n digits[bump_idx] = str(int(digits[bump_idx]) + 1) # Increment the desired digit.\n\n # Zero rightmost digits after bump position.\n for i in range(bump_idx + 1, MAX_DIGITS):\n digits[i] = '0'\n digits = digits[:max(MIN_DIGITS, bump_idx + 1)] # Trim rightmost digits.\n click.echo(prefix + '.'.join(digits), nl=False)\n\n\nif __name__ == '__main__':\n cli() # pylint: disable=no-value-for-parameter\n\nThis does the heavy lifting how to process and increment the version number from git.\n__init__.py\nThe my_module/_version.py file is imported into my_module/__init__.py. Put any static install config here that you want distributed with your module.\nfrom ._version import __version__\n__author__ = ''\n__email__ = ''\n\nsetup.py\nThe last step is to read the version info from the my_module module.\nfrom setuptools import setup, find_packages\n\npkg_vars = {}\n\nwith open(\"{MODULE}/_version.py\") as fp:\n exec(fp.read(), pkg_vars)\n\nsetup(\n version=pkg_vars['__version__'],\n ...\n ...\n)\n\nOf course, for all of this to work you'll have to have at least one version tag in your repo to start.\ngit tag -a v0.0.1\n\n",
"I use a JSON file in the package dir. This fits Zooko's requirements.\nInside pkg_dir/pkg_info.json:\n{\"version\": \"0.1.0\"}\n\nInside setup.py:\nfrom distutils.core import setup\nimport json\n\nwith open('pkg_dir/pkg_info.json') as fp:\n _info = json.load(fp)\n\nsetup(\n version=_info['version'],\n ...\n )\n\nInside pkg_dir/__init__.py:\nimport json\nfrom os.path import dirname\n\nwith open(dirname(__file__) + '/pkg_info.json') as fp:\n _info = json.load(fp)\n\n__version__ = _info['version']\n\nI also put other information in pkg_info.json, like author. I\nlike to use JSON because I can automate management of metadata.\n",
"Lots of work toward uniform versioning and in support of conventions has been completed since this question was first asked. Palatable options are now detailed in the Python Packaging User Guide. Also noteworthy is that version number schemes are relatively strict in Python per PEP 440, and so keeping things sane is critical if your package will be released to the Cheese Shop. \nHere's a shortened breakdown of versioning options: \n\nRead the file in setup.py (setuptools) and get the version.\nUse an external build tool (to update both __init__.py as well as source control), e.g. bump2version, changes or zest.releaser.\nSet the value to a __version__ global variable in a specific module.\nPlace the value in a simple VERSION text file for both setup.py and code to read.\nSet the value via a setup.py release, and use importlib.metadata to pick it up at runtime. (Warning, there are pre-3.8 and post-3.8 versions.)\nSet the value to __version__ in sample/__init__.py and import sample in setup.py.\nUse setuptools_scm to extract versioning from source control so that it's the canonical reference, not code. \n\nNOTE that (7) might be the most modern approach (build metadata is independent of code, published by automation). Also NOTE that if setup is used for package release that a simple python3 setup.py --version will report the version directly. \n",
"Also worth noting is that as well as __version__ being a semi-std. in python so is __version_info__ which is a tuple, in the simple cases you can just do something like:\n__version__ = '1.2.3'\n__version_info__ = tuple([ int(num) for num in __version__.split('.')])\n\n...and you can get the __version__ string from a file, or whatever.\n",
"arrow handles it in an interesting way.\nNow (since 2e5031b)\nIn arrow/__init__.py:\n__version__ = 'x.y.z'\n\nIn setup.py:\nfrom arrow import __version__\n\nsetup(\n name='arrow',\n version=__version__,\n # [...]\n)\n\nBefore\nIn arrow/__init__.py:\n__version__ = 'x.y.z'\nVERSION = __version__\n\nIn setup.py:\ndef grep(attrname):\n pattern = r\"{0}\\W*=\\W*'([^']+)'\".format(attrname)\n strval, = re.findall(pattern, file_text)\n return strval\n\nfile_text = read(fpath('arrow/__init__.py'))\n\nsetup(\n name='arrow',\n version=grep('__version__'),\n # [...]\n)\n\n",
"There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner\n\nEmbed the version in setup.py and have setup.py generate a module (e.g. version.py) containing only version info, that's imported by your package, or\nThe reverse: put the version info in your package itself, and import that to set the version in setup.py \n\n",
"I also saw another style:\n>>> django.VERSION\n(1, 1, 0, 'final', 0)\n\n",
"Using setuptools and pbr\nThere is not a standard way to manage version, but the standard way to manage your packages is setuptools.\nThe best solution I've found overall for managing version is to use setuptools with the pbr extension. This is now my standard way of managing version.\nSetting up your project for full packaging may be overkill for simple projects, but if you need to manage version, you are probably at the right level to just set everything up. Doing so also makes your package releasable at PyPi so everyone can download and use it with Pip.\nPBR moves most metadata out of the setup.py tools and into a setup.cfg file that is then used as a source for most metadata, which can include version. This allows the metadata to be packaged into an executable using something like pyinstaller if needed (if so, you will probably need this info), and separates the metadata from the other package management/setup scripts. You can directly update the version string in setup.cfg manually, and it will be pulled into the *.egg-info folder when building your package releases. Your scripts can then access the version from the metadata using various methods (these processes are outlined in sections below).\nWhen using Git for VCS/SCM, this setup is even better, as it will pull in a lot of the metadata from Git so that your repo can be your primary source of truth for some of the metadata, including version, authors, changelogs, etc. For version specifically, it will create a version string for the current commit based on git tags in the repo.\n\nPyPA - Packaging Python Packages with SetupTools - Tutorial\nPBR latest build usage documentation - How to setup an 8-line setup.py and a setup.cfg file with the metadata.\n\nAs PBR will pull version, author, changelog and other info directly from your git repo, so some of the metadata in setup.cfg can be left out and auto generated whenever a distribution is created for your package (using setup.py)\n\n\nGet the current version in real-time\nsetuptools will pull the latest info in real-time using setup.py:\npython setup.py --version\n\nThis will pull the latest version either from the setup.cfg file, or from the git repo, based on the latest commit that was made and tags that exist in the repo. This command doesn't update the version in a distribution though.\n\n\nUpdating the version metadata\nWhen you create a distribution with setup.py (i.e. py setup.py sdist, for example), then all the current info will be extracted and stored in the distribution. This essentially runs the setup.py --version command and then stores that version info into the package.egg-info folder in a set of files that store distribution metadata.\n\nNote on process to update version meta-data:\nIf you are not using pbr to pull version data from git, then just update your setup.cfg directly with new version info (easy enough, but make sure this is a standard part of your release process).\nIf you are using git, and you don't need to create a source or binary distribution (using python setup.py sdist or one of the python setup.py bdist_xxx commands) the simplest way to update the git repo info into your <mypackage>.egg-info metadata folder is to just run the python setup.py install command. This will run all the PBR functions related to pulling metadata from the git repo and update your local .egg-info folder, install script executables for any entry-points you have defined, and other functions you can see from the output when you run this command.\nNote that the .egg-info folder is generally excluded from being stored in the git repo itself in standard Python .gitignore files (such as from Gitignore.IO), as it can be generated from your source. If it is excluded, make sure you have a standard \"release process\" to get the metadata updated locally before release, and any package you upload to PyPi.org or otherwise distribute must include this data to have the correct version. If you want the Git repo to contain this info, you can exclude specific files from being ignored (i.e. add !*.egg-info/PKG_INFO to .gitignore)\n\n\n\nAccessing the version from a script\nYou can access the metadata from the current build within Python scripts in the package itself. For version, for example, there are several ways to do this I have found so far:\n## This one is a new built-in as of Python 3.8.0 should become the standard\nfrom importlib.metadata import version\n\nv0 = version(\"mypackage\")\nprint('v0 {}'.format(v0))\n\n## I don't like this one because the version method is hidden\nimport pkg_resources # part of setuptools\n\nv1 = pkg_resources.require(\"mypackage\")[0].version\nprint('v1 {}'.format(v1))\n\n# Probably best for pre v3.8.0 - the output without .version is just a longer string with\n# both the package name, a space, and the version string\nimport pkg_resources # part of setuptools\n\nv2 = pkg_resources.get_distribution('mypackage').version\nprint('v2 {}'.format(v2))\n\n## This one seems to be slower, and with pyinstaller makes the exe a lot bigger\nfrom pbr.version import VersionInfo\n\nv3 = VersionInfo('mypackage').release_string()\nprint('v3 {}'.format(v3))\n\nYou can put one of these directly in your __init__.py for the package to extract the version info as follows, similar to some other answers:\n__all__ = (\n '__version__',\n 'my_package_name'\n)\n\nimport pkg_resources # part of setuptools\n\n__version__ = pkg_resources.get_distribution(\"mypackage\").version\n\n",
"After several hours of trying to find the simplest reliable solution, here are the parts:\ncreate a version.py file INSIDE the folder of your package \"/mypackage\":\n# Store the version here so:\n# 1) we don't load dependencies by storing it in __init__.py\n# 2) we can import it in setup.py for the same reason\n# 3) we can import it into your module module\n__version__ = '1.2.7'\n\nin setup.py:\nexec(open('mypackage/version.py').read())\nsetup(\n name='mypackage',\n version=__version__,\n\nin the main folder init.py:\nfrom .version import __version__\n\nThe exec() function runs the script outside of any imports, since setup.py is run before the module can be imported. You still only need to manage the version number in one file in one place, but unfortunately it is not in setup.py. (that's the downside, but having no import bugs is the upside)\n",
"pbr with bump2version\nThis solution was derived from this article\nThe use case - python GUI package distributed via PyInstaller. Needs to show version info.\nHere is the structure of the project packagex\npackagex\n├── packagex\n│ ├── __init__.py\n│ ├── main.py\n│ └── _version.py\n├── packagex.spec\n├── LICENSE\n├── README.md\n├── .bumpversion.cfg\n├── requirements.txt\n├── setup.cfg\n└── setup.py\n\n\nwhere setup.py is\n# setup.py\nimport os\n\nimport setuptools\n\nabout = {}\nwith open(\"packagex/_version.py\") as f:\n exec(f.read(), about)\n\nos.environ[\"PBR_VERSION\"] = about[\"__version__\"]\n\nsetuptools.setup(\n setup_requires=[\"pbr\"],\n pbr=True,\n version=about[\"__version__\"],\n)\n\npackagex/_version.py contains just\n__version__ = \"0.0.1\"\n\nand packagex/__init__.py\nfrom ._version import __version__\n\nand for .bumpversion.cfg\n[bumpversion]\ncurrent_version = 0.0.1\ncommit = False\ntag = False\nparse = (?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)(\\-(?P<release>[a-z]+)(?P<build>\\d+))?\nserialize = \n {major}.{minor}.{patch}-{release}{build}\n {major}.{minor}.{patch}\n\n[bumpversion:part:release]\noptional_value = prod\nfirst_value = dev\nvalues = \n dev\n prod\n\n[bumpversion:file:packagex/_version.py]\n\n",
"I prefer to read the package version from installation environment.\nThis is my src/foo/_version.py:\nfrom pkg_resources import get_distribution \n \n__version__ = get_distribution('foo').version\n\nMakesure foo is always already installed, that's why a src/ layer is required to prevent foo imported without installation.\nIn the setup.py, I use setuptools-scm to generate the version automatically.\n\nUpdate in 2022.7.5:\nThere is another way, which is my faviourate now. Use setuptools-scm to generate a _version.py file.\nsetup(\n ...\n use_scm_version={\n 'write_to':\n 'src/foo/_version.py',\n 'write_to_template':\n '\"\"\"Generated version file.\"\"\"\\n'\n '__version__ = \"{version}\"\\n',\n },\n)\n\n",
"\nCreate a file named by _version.txt in the same folder as __init__.py and write version as a single line:\n\n0.8.2\n\n\nRead this infomation from file _version.txt in __init__.py:\n\n import os \n def get_version():\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), \"_version.txt\")) as f:\n return f.read().strip() \n __version__ = get_version()\n\n",
"I described a standard and modern way here, relying on setuptools_scm.\nThis pattern has worked successfully for dozens of published packages over the past years, so I can warmly recommend it.\nNote that you do not need the getversion package to implement this pattern. It just happens that the getversion documentation hosts this tip.\n",
"Using setuptools and pyproject.toml\nSetuptools now offers a way to dynamically get version in pyproject.toml\nReproducing the example here, you can create something like the following in your pyproject.toml\n# ...\n[project]\nname = \"my_package\"\ndynamic = [\"version\"]\n# ...\n[tool.setuptools.dynamic]\nversion = {attr = \"my_package.__version__\"}\n\n"
] |
[
185,
160,
128,
34,
31,
15,
14,
11,
7,
6,
5,
5,
5,
5,
5,
1,
1,
1,
0
] |
[
"\nUse a version.py file only with __version__ = <VERSION> param in the file. In the setup.py file import the __version__ param and put it's value in the setup.py file like this:\nversion=__version__\nAnother way is to use just a setup.py file with version=<CURRENT_VERSION> - the CURRENT_VERSION is hardcoded.\n\nSince we don't want to manually change the version in the file every time we create a new tag (ready to release a new package version), we can use the following..\nI highly recommend bumpversion package. I've been using it for years to bump a version.\nstart by adding version=<VERSION> to your setup.py file if you don't have it already.\nYou should use a short script like this every time you bump a version:\nbumpversion (patch|minor|major) - choose only one option\ngit push\ngit push --tags\n\nThen add one file per repo called: .bumpversion.cfg:\n[bumpversion]\ncurrent_version = <CURRENT_TAG>\ncommit = True\ntag = True\ntag_name = {new_version}\n[bumpversion:file:<RELATIVE_PATH_TO_SETUP_FILE>]\n\nNote: \n\nYou can use __version__ parameter under version.py file like it was suggested in other posts and update the bumpversion file like this:\n[bumpversion:file:<RELATIVE_PATH_TO_VERSION_FILE>]\nYou must git commit or git reset everything in your repo, otherwise you'll get a dirty repo error. \nMake sure that your virtual environment includes the package of bumpversion, without it it will not work.\n\n",
"For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration has a make_svn_version_py() method that embeds the revision number inside package.__svn_version__ in the variable version .\n",
"If you use CVS (or RCS) and want a quick solution, you can use:\n__version__ = \"$Revision: 1.1 $\"[11:-2]\n__version_info__ = tuple([int(s) for s in __version__.split(\".\")])\n\n(Of course, the revision number will be substituted for you by CVS.)\nThis gives you a print-friendly version and a version info that you can use to check that the module you are importing has at least the expected version:\nimport my_module\nassert my_module.__version_info__ >= (1, 1)\n\n"
] |
[
-1,
-3,
-3
] |
[
"package",
"python",
"string"
] |
stackoverflow_0000458550_package_python_string.txt
|
Q:
How to show Ag grid pop up menu above Quasar QDialog
I am using Ag grid inside quasar QDialog. When the dialog is displayed and I click the column option menu, the Ag grid pop up menu appears behind QDialog, see the picture below:
is there any way to make the ag grid pop up menu shows in the front of the QDialog?
For reference, I see this commmit in Aggrid code:
https://github.com/xh/hoist-react/commit/25522b12155f551fcf95e32211a6cbb8aae8ea35
This adds z-index: 9999 !important to the css style.
Maybe there are ways to add the style using justpy directly or is there more correct way?
My code to produce the above apps is written in python using JustPy v0.10.5 library.
https://github.com/justpy-org/justpy
import justpy as jp
import pandas as pd
def open_dialog(self, msg):
self.dialog.value = True
wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
def main():
wp = jp.QuasarPage(title='Negative Keyword Editor')
b1 = jp.QBtn(label='Open dialog', color='primary', a=wp)
b1.on('click', open_dialog)
c3_dialog = jp.QDialog(name='alert_dialog', persistent=False, a=wp, maximized=False, full_width=True, transition_show="slide-up", transition_hide="slide-down")
c4_dialog = jp.QCard(a=c3_dialog)
c5_dialog = jp.QCardSection(a=c4_dialog)
c6_dialog = jp.Div(classes='text-h6', a=c5_dialog, text='アカウントを選択:')
c7_dialog = jp.QCardSection(a=c4_dialog, classes='q-pa-none')
grid_dialog = jp.AgGrid(a=c4_dialog, auto_size=True, style = "height: 60vh; width: 100%")
grid_dialog.load_pandas_frame(wm_df)
grid_dialog.options.columnDefs[0].checkboxSelection = True
grid_dialog.options.columnDefs[0].headerCheckboxSelection = True
grid_dialog.options.columnDefs[0].headerCheckboxSelectionFilteredOnly = True
grid_dialog.options.columnDefs[1].filter = 'agTextColumnFilter'
grid_dialog.options.columnDefs[1].cellStyle = {"textAlign": "left"}
grid_dialog.options.defaultColDef.filter = True
grid_dialog.options.defaultColDef.floatingFilter = True
grid_dialog.options.defaultColDef.enableValue = True
grid_dialog.options.defaultColDef.editable = True
grid_dialog.options.defaultColDef.sortable = False
grid_dialog.options.animateRows = True
grid_dialog.options.enableCharts = True
grid_dialog.options.enableRangeSelection = True
grid_dialog.options.statusBar = {
'statusPanels': [
{'statusPanel': 'agTotalAndFilteredRowCountComponent'},
{'statusPanel': 'agTotalRowCountComponent'},
{'statusPanel': 'agFilteredRowCountComponent' },
{'statusPanel': 'agSelectedRowCountComponent' },
{'statusPanel': 'agAggregationComponent' },
],
}
grid_dialog.options.rowSelection = 'multiple'
grid_dialog.options.sideBar = True
c8_dialog = jp.QCardActions(align='right', a=c4_dialog)
c9_dialog = jp.QBtn(flat=True, label='Cancel', color='primary', v_close_popup=True, a=c8_dialog)
c11_dialog = jp.QBtn(flat=True, label='Download', color='primary', v_close_popup=True, a=c8_dialog)
b1.dialog = c3_dialog
return wp
jp.justpy(main)
A:
I add the required css into the wp.css:
wp.css = """
.ag-menu {z-index: 9999 !important;}
"""
reference:
https://github.com/justpy-org/justpy/blob/master/jpcore/webpage.py#L52
the result looks like below, which shows the ag grid pop up menu above the quasar dialog.
|
How to show Ag grid pop up menu above Quasar QDialog
|
I am using Ag grid inside quasar QDialog. When the dialog is displayed and I click the column option menu, the Ag grid pop up menu appears behind QDialog, see the picture below:
is there any way to make the ag grid pop up menu shows in the front of the QDialog?
For reference, I see this commmit in Aggrid code:
https://github.com/xh/hoist-react/commit/25522b12155f551fcf95e32211a6cbb8aae8ea35
This adds z-index: 9999 !important to the css style.
Maybe there are ways to add the style using justpy directly or is there more correct way?
My code to produce the above apps is written in python using JustPy v0.10.5 library.
https://github.com/justpy-org/justpy
import justpy as jp
import pandas as pd
def open_dialog(self, msg):
self.dialog.value = True
wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2)
def main():
wp = jp.QuasarPage(title='Negative Keyword Editor')
b1 = jp.QBtn(label='Open dialog', color='primary', a=wp)
b1.on('click', open_dialog)
c3_dialog = jp.QDialog(name='alert_dialog', persistent=False, a=wp, maximized=False, full_width=True, transition_show="slide-up", transition_hide="slide-down")
c4_dialog = jp.QCard(a=c3_dialog)
c5_dialog = jp.QCardSection(a=c4_dialog)
c6_dialog = jp.Div(classes='text-h6', a=c5_dialog, text='アカウントを選択:')
c7_dialog = jp.QCardSection(a=c4_dialog, classes='q-pa-none')
grid_dialog = jp.AgGrid(a=c4_dialog, auto_size=True, style = "height: 60vh; width: 100%")
grid_dialog.load_pandas_frame(wm_df)
grid_dialog.options.columnDefs[0].checkboxSelection = True
grid_dialog.options.columnDefs[0].headerCheckboxSelection = True
grid_dialog.options.columnDefs[0].headerCheckboxSelectionFilteredOnly = True
grid_dialog.options.columnDefs[1].filter = 'agTextColumnFilter'
grid_dialog.options.columnDefs[1].cellStyle = {"textAlign": "left"}
grid_dialog.options.defaultColDef.filter = True
grid_dialog.options.defaultColDef.floatingFilter = True
grid_dialog.options.defaultColDef.enableValue = True
grid_dialog.options.defaultColDef.editable = True
grid_dialog.options.defaultColDef.sortable = False
grid_dialog.options.animateRows = True
grid_dialog.options.enableCharts = True
grid_dialog.options.enableRangeSelection = True
grid_dialog.options.statusBar = {
'statusPanels': [
{'statusPanel': 'agTotalAndFilteredRowCountComponent'},
{'statusPanel': 'agTotalRowCountComponent'},
{'statusPanel': 'agFilteredRowCountComponent' },
{'statusPanel': 'agSelectedRowCountComponent' },
{'statusPanel': 'agAggregationComponent' },
],
}
grid_dialog.options.rowSelection = 'multiple'
grid_dialog.options.sideBar = True
c8_dialog = jp.QCardActions(align='right', a=c4_dialog)
c9_dialog = jp.QBtn(flat=True, label='Cancel', color='primary', v_close_popup=True, a=c8_dialog)
c11_dialog = jp.QBtn(flat=True, label='Download', color='primary', v_close_popup=True, a=c8_dialog)
b1.dialog = c3_dialog
return wp
jp.justpy(main)
|
[
"I add the required css into the wp.css:\nwp.css = \"\"\"\n .ag-menu {z-index: 9999 !important;}\n \"\"\"\n\nreference:\nhttps://github.com/justpy-org/justpy/blob/master/jpcore/webpage.py#L52\nthe result looks like below, which shows the ag grid pop up menu above the quasar dialog.\n\n"
] |
[
0
] |
[] |
[] |
[
"ag_grid",
"css",
"justpy",
"python",
"quasar_framework"
] |
stackoverflow_0074379959_ag_grid_css_justpy_python_quasar_framework.txt
|
Q:
Check if an specific file available or not in a directory
File_Name = "Invoice_Dmart"
Folder-Name = "c:\Documents\Scripts\Bills"
How to check if the specific filename exist in the "Folder-Name" with any extension, If Yes Get the full path in a variable.
Code i have been using:
import os.path
if not os.path.Folder-Name(File_Name):
print("The File s% it's not created "%File_Name)
os.touch(File_Name)
print("The file s% has been Created ..."%File_Name)
Please Suggest the best possible way to solve it.
A:
Before, you should fix the syntax of the variable Folder-Name to Folder_Name.
I guess you can solve the problem by simply adding the two strings through a slash, and using the function os.path.exists() like:
import os.path
File_Name = "Invoice_Dmart"
Folder_Name = "c:\Documents\Scripts\Bills"
path = os.path.join(Folder_Name, File_Name)
exist = os.path.exists(path)
print(exist)
Using os.path.join() aswell to add up the strings, it automatically puts a slash in between.
It worked for me, hope it also does for you.
A:
I would use pathlib.Path here. It provides convenient apis to iterate over the directories(.iterdir()) and also to get the filename without extension(.stem). So you can do somewhat like this.
>>> from pathlib import Path
>>> [str(child) for child in Path(your_folder_name).iterdir() if child.stem == your_file_name]
A:
try the code below
import os
file_name = "Invoice_Dmart"
folder_name = "c:\Documents\Scripts\Bills"
# os.path.splitext() split filename and ext
# os.listdir() list all files in the given dir
filenames_wo_ext = [os.path.splitext(elem)[0] for elem in os.listdir(folder_name)]
if file_name not in filenames_wo_ext:
print("The File %s it's not created "% file_name)
with open(file_name, 'w'):
print("The file %s has been Created ..."% file_name)
A:
Library pathlib is more powerfull than os. os treats paths like string and pathlib treats them as pathways (based on Operating System you are using).
from pathlib import Path
data_path = PurePath(f'C:\YourPath\{even_with_variables}\file.txt')
if not Path(data_path).exists():
return None
else:
return True
|
Check if an specific file available or not in a directory
|
File_Name = "Invoice_Dmart"
Folder-Name = "c:\Documents\Scripts\Bills"
How to check if the specific filename exist in the "Folder-Name" with any extension, If Yes Get the full path in a variable.
Code i have been using:
import os.path
if not os.path.Folder-Name(File_Name):
print("The File s% it's not created "%File_Name)
os.touch(File_Name)
print("The file s% has been Created ..."%File_Name)
Please Suggest the best possible way to solve it.
|
[
"Before, you should fix the syntax of the variable Folder-Name to Folder_Name.\nI guess you can solve the problem by simply adding the two strings through a slash, and using the function os.path.exists() like:\nimport os.path\n\nFile_Name = \"Invoice_Dmart\"\nFolder_Name = \"c:\\Documents\\Scripts\\Bills\"\n\npath = os.path.join(Folder_Name, File_Name)\n \nexist = os.path.exists(path)\nprint(exist)\n\nUsing os.path.join() aswell to add up the strings, it automatically puts a slash in between.\nIt worked for me, hope it also does for you.\n",
"I would use pathlib.Path here. It provides convenient apis to iterate over the directories(.iterdir()) and also to get the filename without extension(.stem). So you can do somewhat like this.\n>>> from pathlib import Path\n>>> [str(child) for child in Path(your_folder_name).iterdir() if child.stem == your_file_name]\n\n",
"try the code below\nimport os\n\nfile_name = \"Invoice_Dmart\"\nfolder_name = \"c:\\Documents\\Scripts\\Bills\"\n\n# os.path.splitext() split filename and ext\n# os.listdir() list all files in the given dir\nfilenames_wo_ext = [os.path.splitext(elem)[0] for elem in os.listdir(folder_name)]\nif file_name not in filenames_wo_ext:\n print(\"The File %s it's not created \"% file_name)\n with open(file_name, 'w'):\n print(\"The file %s has been Created ...\"% file_name)\n\n\n",
"Library pathlib is more powerfull than os. os treats paths like string and pathlib treats them as pathways (based on Operating System you are using).\nfrom pathlib import Path\n\ndata_path = PurePath(f'C:\\YourPath\\{even_with_variables}\\file.txt')\n \n if not Path(data_path).exists():\n return None\n else:\n return True\n\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074444773_python_python_3.x.txt
|
Q:
pyautogui throws me error message. How can I fix my code?
It gives me error message like below. How can I fix this?
Traceback (most recent call last):
File "c:\Users\jayjeo\tempCodeRunnerFile.py", line 3, in <module>
x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
TypeError: cannot unpack non-iterable NoneType object
I made a code as below. I think that if x.size == 0: is the problem.
import pyautogui
x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
if x.size == 0:
print("Not Detected")
pyautogui.click(1280,720)
else:
print("Detected")
pyautogui.click(x, y)
When I do print(x), I get the same error message.
A:
This was changed in version 0.9.41. After that point, if the window is not found, it raises an exception. Before that point, it returns None. So, you need:
pt = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
if not pt:
print("Not Detected")
pyautogui.click(1280,720)
else:
x, y = pt
print("Detected")
pyautogui.click(x, y)
If you upgrade, you will have to add exception handling for this case.
|
pyautogui throws me error message. How can I fix my code?
|
It gives me error message like below. How can I fix this?
Traceback (most recent call last):
File "c:\Users\jayjeo\tempCodeRunnerFile.py", line 3, in <module>
x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
TypeError: cannot unpack non-iterable NoneType object
I made a code as below. I think that if x.size == 0: is the problem.
import pyautogui
x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
if x.size == 0:
print("Not Detected")
pyautogui.click(1280,720)
else:
print("Detected")
pyautogui.click(x, y)
When I do print(x), I get the same error message.
|
[
"This was changed in version 0.9.41. After that point, if the window is not found, it raises an exception. Before that point, it returns None. So, you need:\npt = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)\nif not pt:\n print(\"Not Detected\")\n pyautogui.click(1280,720)\nelse:\n x, y = pt\n print(\"Detected\")\n pyautogui.click(x, y)\n\nIf you upgrade, you will have to add exception handling for this case.\n"
] |
[
5
] |
[] |
[] |
[
"pyautogui",
"python"
] |
stackoverflow_0074514720_pyautogui_python.txt
|
Q:
Predict new data based on previously clustered set
I have a large set of binary data that I need to cluster. For example
[[0 1 1 0 ... 0 1 0 1 ],
[1 0 1 1 ... 0 0 1 1 ],
...
[0 0 1 0 ... 1 0 1 1 ]]
From what I've read, the best clustering algorithms for binary data are hierarchical such as agglomerative clustering. So I implemented that using scikit.
I have a very large data set with new data coming in all the time which I would like to cluster into a previously clustered group. So my thinking was to take a random sample of the existing data, run the AgglomerativeClustering on it and save the results to a file using joblib.
Then when a new set of data arrives, load the previously cluster up and call predict() to figure out where it would fall. It's almost like I'm training a cluster similar to a classifier but without the labels. The problem is that AgglomerativeClustering doesn't have a predict() method. Other clustering algorithms in scikit do have predict() such as KMeans but based on my research, that's not a good algorithm to use when dealing with binary data.
So I'm stuck. I don't want to have to run the clustering every single time new data arrives because hierarchical algorithms to do scale well with a lot of data but I'm not sure which algorithm to use that would work with binary data and also provide a predict() functionality.
Is there a way I can transform the binary data so that other algorithms, like KMeans, can provide useful outputs? Or is there a completely different algorithm not implemented in scikit that would work? I'm not tied to scikit so switching is not an issue.
A:
When you want to predict, use a classifier, not clustering.
Here, the most appropriate classifier would likely be a 1NN classifier. For performance reasons I'd choose DT or SVM instead though.
A:
For the followers, you can see the relevant posts:
scikit-learn: Predicting new points with DBSCAN
Why k-means in scikit learn have a predict function but DBSCAN/agglomerative doesnt?
scikit-learn clustering: predict(X) vs. fit_predict(X)
|
Predict new data based on previously clustered set
|
I have a large set of binary data that I need to cluster. For example
[[0 1 1 0 ... 0 1 0 1 ],
[1 0 1 1 ... 0 0 1 1 ],
...
[0 0 1 0 ... 1 0 1 1 ]]
From what I've read, the best clustering algorithms for binary data are hierarchical such as agglomerative clustering. So I implemented that using scikit.
I have a very large data set with new data coming in all the time which I would like to cluster into a previously clustered group. So my thinking was to take a random sample of the existing data, run the AgglomerativeClustering on it and save the results to a file using joblib.
Then when a new set of data arrives, load the previously cluster up and call predict() to figure out where it would fall. It's almost like I'm training a cluster similar to a classifier but without the labels. The problem is that AgglomerativeClustering doesn't have a predict() method. Other clustering algorithms in scikit do have predict() such as KMeans but based on my research, that's not a good algorithm to use when dealing with binary data.
So I'm stuck. I don't want to have to run the clustering every single time new data arrives because hierarchical algorithms to do scale well with a lot of data but I'm not sure which algorithm to use that would work with binary data and also provide a predict() functionality.
Is there a way I can transform the binary data so that other algorithms, like KMeans, can provide useful outputs? Or is there a completely different algorithm not implemented in scikit that would work? I'm not tied to scikit so switching is not an issue.
|
[
"When you want to predict, use a classifier, not clustering.\nHere, the most appropriate classifier would likely be a 1NN classifier. For performance reasons I'd choose DT or SVM instead though.\n",
"For the followers, you can see the relevant posts:\n\nscikit-learn: Predicting new points with DBSCAN\nWhy k-means in scikit learn have a predict function but DBSCAN/agglomerative doesnt?\nscikit-learn clustering: predict(X) vs. fit_predict(X)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"cluster_analysis",
"machine_learning",
"python",
"scikit_learn"
] |
stackoverflow_0055983983_cluster_analysis_machine_learning_python_scikit_learn.txt
|
Q:
How do I remove second row from the column name in pandas?
How do I remove the row that says "UN member states"?
A:
You can use droplevel to completely remove a multi-index level:
df.columns = df.columns.droplevel(1)
|
How do I remove second row from the column name in pandas?
|
How do I remove the row that says "UN member states"?
|
[
"You can use droplevel to completely remove a multi-index level:\ndf.columns = df.columns.droplevel(1)\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] |
stackoverflow_0074514741_dataframe_jupyter_notebook_pandas_python.txt
|
Q:
handling infinite supply in minimum cost flow problem
I got a typical problem about minimum cost flow problem. I'm given a dataset
# node : {pos, demand}
nodes_dict = {1: {'pos': (0, 0, 1), 'demand': 'NA'}, 2: {'pos': (0, 3, 1), 'demand': 'NA'}, 3: {'pos': (0, 6, 1), 'demand': 'NA'}, 4: {'pos': (4, 0, 1), 'demand': 1}, 5: {'pos': (4, 3, 1), 'demand': 2}, 6: {'pos': (4, 6, 1), 'demand': 3}, 7: {'pos': (10, 3, 1), 'demand': 0}}
# (node_start, node_end) : capacity
edges = {(1, 4): 2, (3, 6): 4, (2, 5): 1, (6, 5): 3, (6, 7): 0, (5, 7): 0, (4, 7): 0}
I got no problem modeling with NetworkX, except for a particular case where a node demand is 'NA' that implies node has infinite supply.
For example above, a graph looks like this with edge costs and no capacities considered:
My code for solving this example and try to find minimum cost flow goes like this:
def solve(N,E):
G = nx.DiGraph()
for k,v in N.items():
#node wants to send (negative demand) or receive (positive demand)
if v["demand"] == 'NA':
demand = 'Inf Supply'
else:
demand = int(v["demand"])
G.add_node(k, demand=demand)
for k,v in E.items():
index_node_1 = k[0]
index_node_2 = k[1]
#cost_edge is defined above and returns a integer
G.add_edge(k[0], k[1], weight=cost_edge( N[index_node_1]['pos'], N[index_node_2]['pos'] ))
return nx.min_cost_flow_cost(G)
I'm stuck on how should I treat infinite supply node. If I treat like demand = 0, graph goes like this:
But I got:
NetworkXUnfeasible: total node demand is not zero
And same with a very large int instead 0. I know that mass principle implies that total demand must sum 0, but in that case, I can't write a solution for infinite supply then.
Any idea about I'm not seeing?
Thanks community!
A:
This feature is not implemented in networkx version 2.8 (might be implemented in the future).
One thing that comes to mind is that if you are working with a special case of 'infinite supply' nodes that each have a single connection (like in the post), then you can work out a solution by solving for all feasible supply values that make total demand = 0 and then iterate over all distributions of supply across such infinite supply nodes.
For example, if total demand for nodes with positive demand is 6, then the possible allocations across supply nodes are: (0,0,6), (0,1,5), (0,2,4), ..., (0,6,0), ...,(6,0,0). That is a lot of combinations to try, so it's not efficient, and depending on the specifics of the problem you can reduce the search space a bit more.
|
handling infinite supply in minimum cost flow problem
|
I got a typical problem about minimum cost flow problem. I'm given a dataset
# node : {pos, demand}
nodes_dict = {1: {'pos': (0, 0, 1), 'demand': 'NA'}, 2: {'pos': (0, 3, 1), 'demand': 'NA'}, 3: {'pos': (0, 6, 1), 'demand': 'NA'}, 4: {'pos': (4, 0, 1), 'demand': 1}, 5: {'pos': (4, 3, 1), 'demand': 2}, 6: {'pos': (4, 6, 1), 'demand': 3}, 7: {'pos': (10, 3, 1), 'demand': 0}}
# (node_start, node_end) : capacity
edges = {(1, 4): 2, (3, 6): 4, (2, 5): 1, (6, 5): 3, (6, 7): 0, (5, 7): 0, (4, 7): 0}
I got no problem modeling with NetworkX, except for a particular case where a node demand is 'NA' that implies node has infinite supply.
For example above, a graph looks like this with edge costs and no capacities considered:
My code for solving this example and try to find minimum cost flow goes like this:
def solve(N,E):
G = nx.DiGraph()
for k,v in N.items():
#node wants to send (negative demand) or receive (positive demand)
if v["demand"] == 'NA':
demand = 'Inf Supply'
else:
demand = int(v["demand"])
G.add_node(k, demand=demand)
for k,v in E.items():
index_node_1 = k[0]
index_node_2 = k[1]
#cost_edge is defined above and returns a integer
G.add_edge(k[0], k[1], weight=cost_edge( N[index_node_1]['pos'], N[index_node_2]['pos'] ))
return nx.min_cost_flow_cost(G)
I'm stuck on how should I treat infinite supply node. If I treat like demand = 0, graph goes like this:
But I got:
NetworkXUnfeasible: total node demand is not zero
And same with a very large int instead 0. I know that mass principle implies that total demand must sum 0, but in that case, I can't write a solution for infinite supply then.
Any idea about I'm not seeing?
Thanks community!
|
[
"This feature is not implemented in networkx version 2.8 (might be implemented in the future).\nOne thing that comes to mind is that if you are working with a special case of 'infinite supply' nodes that each have a single connection (like in the post), then you can work out a solution by solving for all feasible supply values that make total demand = 0 and then iterate over all distributions of supply across such infinite supply nodes.\nFor example, if total demand for nodes with positive demand is 6, then the possible allocations across supply nodes are: (0,0,6), (0,1,5), (0,2,4), ..., (0,6,0), ...,(6,0,0). That is a lot of combinations to try, so it's not efficient, and depending on the specifics of the problem you can reduce the search space a bit more.\n"
] |
[
1
] |
[] |
[] |
[
"graph",
"logistics",
"networkx",
"python"
] |
stackoverflow_0074514546_graph_logistics_networkx_python.txt
|
Q:
How to prevent the repetition of code suggest for Python in VSCode?
I am using VSCode for writing Python code in a Jupyter Notebook. The relevant extensions installed are Python, Pylance and Jupyter. The problem occurs when I am coding, VSCode will give two same suggestion in the box. It looks like this:
Problem
How can I remove the duplicated code suggestion?
A:
Upgrade Jupyter extension to pre-release version.
|
How to prevent the repetition of code suggest for Python in VSCode?
|
I am using VSCode for writing Python code in a Jupyter Notebook. The relevant extensions installed are Python, Pylance and Jupyter. The problem occurs when I am coding, VSCode will give two same suggestion in the box. It looks like this:
Problem
How can I remove the duplicated code suggestion?
|
[
"Upgrade Jupyter extension to pre-release version.\n\n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"pylance",
"python",
"visual_studio_code"
] |
stackoverflow_0074499443_jupyter_notebook_pylance_python_visual_studio_code.txt
|
Q:
Transform Pandas column to get a key value pair in a column post group by
My DataFrame:
Col X Col Y ID Value
A a 'r' 3
A a 'b' 2
A a 'c' 1
B b 'd' 5
B b 's' 6
B b 'd' 7
Output required:
Col X Col Y Out
A a {'r':3, 'b':2, 'c':1}
B b {'d': 5, 's': 6, 'd':7}
Approach tried so far:
df = df.set_index(['Col X', 'Col Y', 'ID']).Value
dict_column = {k: df.xs((k, v)).to_dict() for k,v,v2 in df.index}
A:
Use GroupBy.apply with lambda function:
df['ID'] = df['ID'].str.strip("'")
df1 = (df.groupby(['Col X', 'Col Y'])[['ID','Value']]
.apply(lambda x: dict(x.to_numpy()))
.reset_index(name='Out'))
print (df1)
Col X Col Y Out
0 A a {'r': 3, 'b': 2, 'c': 1}
1 B b {'d': 7, 's': 6}
Duplicated keys not exist in python dictionary. You can aggregate values, e.g. by sum:
df['ID'] = df['ID'].str.strip("'")
df = df.groupby(['Col X', 'Col Y','ID'], as_index=False)['Value'].sum()
print (df)
Col X Col Y ID Value
0 A a b 2
1 A a c 1
2 A a r 3
3 B b d 12
4 B b s 6
df1 = (df.groupby(['Col X', 'Col Y'])[['ID','Value']]
.apply(lambda x: dict(x.to_numpy()))
.reset_index(name='Out'))
print (df1)
Col X Col Y Out
0 A a {'b': 2, 'c': 1, 'r': 3}
1 B b {'d': 12, 's': 6}
A:
You can create pd.Series inside apply and use to_dict:
output = ( df.groupby(['Col X', 'Col Y'])[['ID', 'Value']].
apply(lambda x: pd.Series(x['Value'].values,index=x['ID']).to_dict()) )
A:
You can use groupby.apply with dict and zip:
(df.groupby(['Col X', 'Col Y'])
.apply(lambda x: dict(zip(x['ID'], x['Value'])))
.reset_index(name='Out')
)
Output:
Col X Col Y Out
0 A a {'r': 3, 'b': 2, 'c': 1}
1 B b {'d': 7, 's': 6}
If you want to aggregate the duplicated keys:
(df.groupby(['Col X', 'Col Y'])
.apply(lambda x: x['Value'].groupby(x['ID']).sum().to_dict())
.reset_index(name='Out')
)
Output:
Col X Col Y Out
0 A a {'b': 2, 'c': 1, 'r': 3}
1 B b {'d': 12, 's': 6}
|
Transform Pandas column to get a key value pair in a column post group by
|
My DataFrame:
Col X Col Y ID Value
A a 'r' 3
A a 'b' 2
A a 'c' 1
B b 'd' 5
B b 's' 6
B b 'd' 7
Output required:
Col X Col Y Out
A a {'r':3, 'b':2, 'c':1}
B b {'d': 5, 's': 6, 'd':7}
Approach tried so far:
df = df.set_index(['Col X', 'Col Y', 'ID']).Value
dict_column = {k: df.xs((k, v)).to_dict() for k,v,v2 in df.index}
|
[
"Use GroupBy.apply with lambda function:\ndf['ID'] = df['ID'].str.strip(\"'\")\n\ndf1 = (df.groupby(['Col X', 'Col Y'])[['ID','Value']]\n .apply(lambda x: dict(x.to_numpy()))\n .reset_index(name='Out'))\nprint (df1)\n Col X Col Y Out\n0 A a {'r': 3, 'b': 2, 'c': 1}\n1 B b {'d': 7, 's': 6}\n\nDuplicated keys not exist in python dictionary. You can aggregate values, e.g. by sum:\ndf['ID'] = df['ID'].str.strip(\"'\")\n\ndf = df.groupby(['Col X', 'Col Y','ID'], as_index=False)['Value'].sum()\nprint (df)\n Col X Col Y ID Value\n0 A a b 2\n1 A a c 1\n2 A a r 3\n3 B b d 12\n4 B b s 6\n\ndf1 = (df.groupby(['Col X', 'Col Y'])[['ID','Value']]\n .apply(lambda x: dict(x.to_numpy()))\n .reset_index(name='Out'))\nprint (df1)\n Col X Col Y Out\n0 A a {'b': 2, 'c': 1, 'r': 3}\n1 B b {'d': 12, 's': 6}\n\n",
"You can create pd.Series inside apply and use to_dict:\noutput = ( df.groupby(['Col X', 'Col Y'])[['ID', 'Value']].\n apply(lambda x: pd.Series(x['Value'].values,index=x['ID']).to_dict()) )\n\n",
"You can use groupby.apply with dict and zip:\n(df.groupby(['Col X', 'Col Y'])\n .apply(lambda x: dict(zip(x['ID'], x['Value'])))\n .reset_index(name='Out')\n )\n\nOutput:\n Col X Col Y Out\n0 A a {'r': 3, 'b': 2, 'c': 1}\n1 B b {'d': 7, 's': 6}\n\nIf you want to aggregate the duplicated keys:\n(df.groupby(['Col X', 'Col Y'])\n .apply(lambda x: x['Value'].groupby(x['ID']).sum().to_dict())\n .reset_index(name='Out')\n )\n\nOutput:\n Col X Col Y Out\n0 A a {'b': 2, 'c': 1, 'r': 3}\n1 B b {'d': 12, 's': 6}\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074514826_pandas_python.txt
|
Q:
Error : strptime() argument 1 must be str, not int
I am trying to substract two times and getting an error. In below total error is coming up
if result[0]['outTime'] != None:
type = "bothPunchDone"
FMT = '%H:%M:%S'
total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT)
I tried but not able to solve the issue.
A:
from datetime import datetime
result = datetime.now().strftime("%H:%M:%S")
if result != None:
type = "bothPunchDone"
FMT = '%H:%M:%S'
total= datetime.strptime(result, FMT) - datetime.strptime(result, FMT)
print(total)
is working for me. Try to check the type of result[0]['outTime']
|
Error : strptime() argument 1 must be str, not int
|
I am trying to substract two times and getting an error. In below total error is coming up
if result[0]['outTime'] != None:
type = "bothPunchDone"
FMT = '%H:%M:%S'
total= datetime.strptime(result[0]['outTime'], FMT) - datetime.strptime(result[0]['inTime'], FMT)
I tried but not able to solve the issue.
|
[
"from datetime import datetime\n\nresult = datetime.now().strftime(\"%H:%M:%S\")\n\nif result != None:\n type = \"bothPunchDone\"\n \nFMT = '%H:%M:%S'\ntotal= datetime.strptime(result, FMT) - datetime.strptime(result, FMT)\n\nprint(total)\n\nis working for me. Try to check the type of result[0]['outTime']\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python",
"time"
] |
stackoverflow_0074514820_django_python_time.txt
|
Q:
Python Pandas rows merging different column values include Binary or Yes or No values
Column1 Column2 Column3
Eswar IT Yes
Eswar Admin No
Column1 Column2 Column3
Eswar IT,Admin No
I need this as
Where Yes/No becomes No
Or
1/0 become 0
A:
You can aggreagte values by join and min, it working for Yes/No and 1/0 values very well:
df1 = (df.groupby('Column1', as_index=False)
.agg(Column2=('Column2', ','.join), Column3=('Column3', 'min')))
print (df1)
Column1 Column2 Column3
0 Eswar IT,Admin No
print (df)
Column1 Column2 Column3 Col4 Col5
0 Eswar IT Yes 10 a
1 Eswar Admin No 10 a
df1 = (df.groupby(['Column1', 'Col4', 'Col5'], as_index=False)
.agg(Column2=('Column2', ','.join), Column3=('Column3', 'min')))
print (df1)
Column1 Col4 Col5 Column2 Column3
0 Eswar 10 a IT,Admin No
|
Python Pandas rows merging different column values include Binary or Yes or No values
|
Column1 Column2 Column3
Eswar IT Yes
Eswar Admin No
Column1 Column2 Column3
Eswar IT,Admin No
I need this as
Where Yes/No becomes No
Or
1/0 become 0
|
[
"You can aggreagte values by join and min, it working for Yes/No and 1/0 values very well:\ndf1 = (df.groupby('Column1', as_index=False)\n .agg(Column2=('Column2', ','.join), Column3=('Column3', 'min')))\nprint (df1)\n Column1 Column2 Column3\n0 Eswar IT,Admin No\n\n\nprint (df)\n Column1 Column2 Column3 Col4 Col5\n0 Eswar IT Yes 10 a\n1 Eswar Admin No 10 a\n\n\ndf1 = (df.groupby(['Column1', 'Col4', 'Col5'], as_index=False)\n .agg(Column2=('Column2', ','.join), Column3=('Column3', 'min')))\nprint (df1)\n\n Column1 Col4 Col5 Column2 Column3\n0 Eswar 10 a IT,Admin No\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074514827_pandas_python.txt
|
Q:
Pandas Column Content Editing
I was wondering what method is best for changing contents in the whole column in my dataframe.
Part of my dataframe has the column "Percentage" and the contents in that column labeled as "#%". Here, I want to adjust the whole column from percentage to decimal numbers. For instance, 80% to 0.80 and 42% to 0.42. What would be the best way to make this adjustment?
Thanks in advance.
A:
df['DataFrame Column'] = df['DataFrame Column'].str[:-1].astype(float)/100
|
Pandas Column Content Editing
|
I was wondering what method is best for changing contents in the whole column in my dataframe.
Part of my dataframe has the column "Percentage" and the contents in that column labeled as "#%". Here, I want to adjust the whole column from percentage to decimal numbers. For instance, 80% to 0.80 and 42% to 0.42. What would be the best way to make this adjustment?
Thanks in advance.
|
[
"df['DataFrame Column'] = df['DataFrame Column'].str[:-1].astype(float)/100\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074514865_dataframe_pandas_python.txt
|
Q:
i want to do Maxzero function in Python
Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.
This question was originally made for java but i would like to do it in python still i cant solve it.
kindly help me
zeroMax([0, 5, 0, 3])→[5, 5, 3, 3]
A:
This should do the trick:
def odd_right(a):
return [i for i in a if i%2 != 0]
def zeroMax(l):
for i, v in enumerate(l[:]):
if v == 0:
temp_list = odd_right(l[i:])
rep = max(temp_list) if temp_list else 0
l[i] = rep
return l
Although stackoverflow, I feel is not the right place for coding questions like this.
|
i want to do Maxzero function in Python
|
Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.
This question was originally made for java but i would like to do it in python still i cant solve it.
kindly help me
zeroMax([0, 5, 0, 3])→[5, 5, 3, 3]
|
[
"This should do the trick:\ndef odd_right(a):\n return [i for i in a if i%2 != 0]\n\ndef zeroMax(l):\n for i, v in enumerate(l[:]):\n if v == 0:\n temp_list = odd_right(l[i:])\n rep = max(temp_list) if temp_list else 0 \n l[i] = rep\n return l\n\nAlthough stackoverflow, I feel is not the right place for coding questions like this.\n"
] |
[
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0074514760_list_python.txt
|
Q:
zip dict converts a integer list to a string while creating a JSON file
I am trying to save a JSON file from a dataframe.
Sample data:
import pandas as pd
import json
df
Metric Value
0 Line1 10% off
1 Line2 15% off
2 Line3 20% off
3 Line4 25% off
4 Line5 30% off
5 revenueXaxis ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8']
6 Revenuedata1 [30, 30, 30, 30, 30, 30, 30, 30]
7 Revenuedata2 [25, 25, 25, 20, 25, 25, 25, 25]
8 Revenuedata3 [15, 15, 15, 15, 15, 15, 15, 15]
9 Revenuedata4 [15, 10, 10, 10, 10, 10, 10, 10]
10 Revenuedata5 [10, 10, 10, 10, 10, 10, 10, 10]
When I perform below zip operation to convert it as a dictionary, the list values in Revenuedata1 to Revenuedata5 is converted into a string as below:
dict(zip(df.iloc[:,0], df.iloc[:,1]))
{'Line1': '10% off',
'Line2': '15% off',
'Line3': '20% off',
'Line4': '25% off',
'Line5': '30% off',
'revenueXaxis': "['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8']",
'Revenuedata1': '[30, 30, 30, 30, 30, 30, 30, 30]',
'Revenuedata2': '[25, 25, 25, 20, 25, 25, 25, 25]',
'Revenuedata3': '[15, 15, 15, 15, 15, 15, 15, 15]',
'Revenuedata4': '[15, 10, 10, 10, 10, 10, 10, 10]',
'Revenuedata5': '[10, 10, 10, 10, 10, 10, 10, 10]'}
And when I write it to a file using json.dump, this is the output I get:
"ExpectedRevenue": {
"Line1": "10% off",
"Line2": "15% off",
"Line3": "20% off",
"Line4": "25% off",
"Line5": "30% off",
"revenueXaxis": "['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8']",
"Revenuedata1": "[50, 110, 180, 260, 350, 450, 550, 650]",
"Revenuedata2": "[20, 45, 75, 110, 150, 195, 245, 300]",
"Revenuedata3": "[5, 15, 28, 43, 60, 78, 98, 120]",
"Revenuedata4": "[4, 10, 17, 2, 35, 46, 58, 72]",
"Revenuedata5": "[3, 8, 13.5, 19.5, 26.5, 34.5, 44, 54]"
},
Could someone please let me know how to keep the integer list values as is and not a string.
Expected Output:
"ExpectedRevenue": [{
"Line1": "10% off",
"Line2": "15% off",
"Line3": "20% off",
"Line4": "25% off",
"Line5": "30% off",
"revenueXaxis": ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7", "Week 8"],
"Revenuedata1": [50, 110, 180, 260, 350, 450, 550, 650],
"Revenuedata2": [20, 45, 75, 110, 150, 195, 245, 300],
"Revenuedata3": [5, 15, 28, 43, 60, 78, 98, 120],
"Revenuedata4": [4, 10, 17, 2, 35, 46, 58, 72],
"Revenuedata5": [3, 8, 13.5, 19.5, 26.5, 34.5, 44, 54]
}]
A:
If string starting by [ convert values to lists by ast.literal_eval only for filtered rows:
import ast
m = df['Value'].str.startswith('[')
df.loc[m, 'Value'] = df.loc[m, 'Value'].apply(ast.literal_eval)
Last create dictionary:
print (df.set_index('Metric')['Value'].to_dict())
print (dict(zip(df.iloc[:,0], df.iloc[:,1])))
EDIT: You can check not converted values and repalce them by empty list, also use print for see what values failed:
import ast
def literal_eval_cust(x):
try:
return ast.literal_eval(x)
except Exception:
print (x)
return []
df.loc[m, 'Value'] = df.loc[m, 'Value'].apply(literal_eval_cust)
|
zip dict converts a integer list to a string while creating a JSON file
|
I am trying to save a JSON file from a dataframe.
Sample data:
import pandas as pd
import json
df
Metric Value
0 Line1 10% off
1 Line2 15% off
2 Line3 20% off
3 Line4 25% off
4 Line5 30% off
5 revenueXaxis ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8']
6 Revenuedata1 [30, 30, 30, 30, 30, 30, 30, 30]
7 Revenuedata2 [25, 25, 25, 20, 25, 25, 25, 25]
8 Revenuedata3 [15, 15, 15, 15, 15, 15, 15, 15]
9 Revenuedata4 [15, 10, 10, 10, 10, 10, 10, 10]
10 Revenuedata5 [10, 10, 10, 10, 10, 10, 10, 10]
When I perform below zip operation to convert it as a dictionary, the list values in Revenuedata1 to Revenuedata5 is converted into a string as below:
dict(zip(df.iloc[:,0], df.iloc[:,1]))
{'Line1': '10% off',
'Line2': '15% off',
'Line3': '20% off',
'Line4': '25% off',
'Line5': '30% off',
'revenueXaxis': "['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8']",
'Revenuedata1': '[30, 30, 30, 30, 30, 30, 30, 30]',
'Revenuedata2': '[25, 25, 25, 20, 25, 25, 25, 25]',
'Revenuedata3': '[15, 15, 15, 15, 15, 15, 15, 15]',
'Revenuedata4': '[15, 10, 10, 10, 10, 10, 10, 10]',
'Revenuedata5': '[10, 10, 10, 10, 10, 10, 10, 10]'}
And when I write it to a file using json.dump, this is the output I get:
"ExpectedRevenue": {
"Line1": "10% off",
"Line2": "15% off",
"Line3": "20% off",
"Line4": "25% off",
"Line5": "30% off",
"revenueXaxis": "['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8']",
"Revenuedata1": "[50, 110, 180, 260, 350, 450, 550, 650]",
"Revenuedata2": "[20, 45, 75, 110, 150, 195, 245, 300]",
"Revenuedata3": "[5, 15, 28, 43, 60, 78, 98, 120]",
"Revenuedata4": "[4, 10, 17, 2, 35, 46, 58, 72]",
"Revenuedata5": "[3, 8, 13.5, 19.5, 26.5, 34.5, 44, 54]"
},
Could someone please let me know how to keep the integer list values as is and not a string.
Expected Output:
"ExpectedRevenue": [{
"Line1": "10% off",
"Line2": "15% off",
"Line3": "20% off",
"Line4": "25% off",
"Line5": "30% off",
"revenueXaxis": ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7", "Week 8"],
"Revenuedata1": [50, 110, 180, 260, 350, 450, 550, 650],
"Revenuedata2": [20, 45, 75, 110, 150, 195, 245, 300],
"Revenuedata3": [5, 15, 28, 43, 60, 78, 98, 120],
"Revenuedata4": [4, 10, 17, 2, 35, 46, 58, 72],
"Revenuedata5": [3, 8, 13.5, 19.5, 26.5, 34.5, 44, 54]
}]
|
[
"If string starting by [ convert values to lists by ast.literal_eval only for filtered rows:\nimport ast\n\nm = df['Value'].str.startswith('[')\ndf.loc[m, 'Value'] = df.loc[m, 'Value'].apply(ast.literal_eval)\n\nLast create dictionary:\nprint (df.set_index('Metric')['Value'].to_dict())\n\nprint (dict(zip(df.iloc[:,0], df.iloc[:,1])))\n\nEDIT: You can check not converted values and repalce them by empty list, also use print for see what values failed:\nimport ast\n\ndef literal_eval_cust(x):\n try:\n return ast.literal_eval(x)\n except Exception:\n print (x)\n return []\n \n\ndf.loc[m, 'Value'] = df.loc[m, 'Value'].apply(literal_eval_cust)\n \n\n"
] |
[
1
] |
[] |
[] |
[
"json",
"pandas",
"python"
] |
stackoverflow_0074513906_json_pandas_python.txt
|
Q:
How to check specific file and run another python script
I want to use watchdog for monitoring specific filename in directory for run specific python script.
for example:
First, I want to use watchdog for monitor all of .avi file.
If name of .avi file in path (C:/User/AAxxx/video/) is : ABxxx_11.avi, I want to run ABxxx_11.py
If name of .avi file in path (C:/User/BBxxx/video/) is : CDxxx_22.avi, I want to run CDxxx_22.py
If name of .avi file in path (C:/User/CCxxx/video/) is : EFxxx_33.avi, I want to run EFxxx_33.py
And I want to pass sub-folder directory of AAxxx, BBxxx amd CCxxx folder.
I want to focus only .avi file.
Now I have only watchdog for monitor .avi file and run python only one script.
please see as below.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from watchdog.events import PatternMatchingEventHandler
class Watcher:
def __init__(self, path, filename):
self.observer = Observer()
self.path = path
self.filename = filename
def run(self):
event_handler = Handler(self.filename)
self.observer.schedule(event_handler, self.path, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
except:
self.observer.stop()
print("Error")
self.observer.join()
class Handler(PatternMatchingEventHandler):
def __init__(self, filename):
super(Handler, self).__init__(
patterns=[filename],
ignore_patterns=["*.tmp"],
ignore_directories=True,
case_sensitive=False,
)
def on_any_event(self, event):
print(
"[{}] noticed: [{}] on: [{}] ".format(
time.asctime(), event.event_type, event.src_path
)
)
#process1 = subprocess.Popen(["python", "ABxxx_11.py"])
if __name__ == "__main__":
path = "C:/Users/xxx/AAxxx/video/"
filename = "*.avi"
w = Watcher(path, filename)
w.run()
A:
I can't get your code to run, so I hardcoded the values. Just check for the modified and created files, get the file name and execute the python script accordingly.
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Watcher:
DIRECTORY_TO_WATCH = "C:/Users/test/AAxxx/video"
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except:
self.observer.stop()
print "Error"
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
# Take any action here when a file is first created.
print "Received created event - %s." % event.src_path
if ".avi" in event.src_path:
print "run this file ->" + str(event.src_path.rsplit('\\')[1].split('.')[0]) + ".py"
elif event.event_type == 'modified':
# Taken any action here when a file is modified.
print "Received modified event - %s." % event.src_path
if ".avi" in event.src_path:
print "run this file ->" + str(event.src_path.rsplit('\\')[1].split('.')[0]) + ".py"
if __name__ == '__main__':
w = Watcher()
w.run()
when I create a new .avi file in the path, the following is the output:
|
How to check specific file and run another python script
|
I want to use watchdog for monitoring specific filename in directory for run specific python script.
for example:
First, I want to use watchdog for monitor all of .avi file.
If name of .avi file in path (C:/User/AAxxx/video/) is : ABxxx_11.avi, I want to run ABxxx_11.py
If name of .avi file in path (C:/User/BBxxx/video/) is : CDxxx_22.avi, I want to run CDxxx_22.py
If name of .avi file in path (C:/User/CCxxx/video/) is : EFxxx_33.avi, I want to run EFxxx_33.py
And I want to pass sub-folder directory of AAxxx, BBxxx amd CCxxx folder.
I want to focus only .avi file.
Now I have only watchdog for monitor .avi file and run python only one script.
please see as below.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from watchdog.events import PatternMatchingEventHandler
class Watcher:
def __init__(self, path, filename):
self.observer = Observer()
self.path = path
self.filename = filename
def run(self):
event_handler = Handler(self.filename)
self.observer.schedule(event_handler, self.path, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
except:
self.observer.stop()
print("Error")
self.observer.join()
class Handler(PatternMatchingEventHandler):
def __init__(self, filename):
super(Handler, self).__init__(
patterns=[filename],
ignore_patterns=["*.tmp"],
ignore_directories=True,
case_sensitive=False,
)
def on_any_event(self, event):
print(
"[{}] noticed: [{}] on: [{}] ".format(
time.asctime(), event.event_type, event.src_path
)
)
#process1 = subprocess.Popen(["python", "ABxxx_11.py"])
if __name__ == "__main__":
path = "C:/Users/xxx/AAxxx/video/"
filename = "*.avi"
w = Watcher(path, filename)
w.run()
|
[
"I can't get your code to run, so I hardcoded the values. Just check for the modified and created files, get the file name and execute the python script accordingly.\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n\nclass Watcher:\n DIRECTORY_TO_WATCH = \"C:/Users/test/AAxxx/video\"\n\n def __init__(self):\n self.observer = Observer()\n\n def run(self):\n event_handler = Handler()\n self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)\n self.observer.start()\n try:\n while True:\n time.sleep(5)\n except:\n self.observer.stop()\n print \"Error\"\n\n self.observer.join()\n\n\nclass Handler(FileSystemEventHandler):\n\n @staticmethod\n def on_any_event(event):\n if event.is_directory:\n return None\n\n elif event.event_type == 'created':\n # Take any action here when a file is first created.\n print \"Received created event - %s.\" % event.src_path\n if \".avi\" in event.src_path:\n print \"run this file ->\" + str(event.src_path.rsplit('\\\\')[1].split('.')[0]) + \".py\"\n\n elif event.event_type == 'modified':\n # Taken any action here when a file is modified.\n print \"Received modified event - %s.\" % event.src_path\n if \".avi\" in event.src_path:\n print \"run this file ->\" + str(event.src_path.rsplit('\\\\')[1].split('.')[0]) + \".py\"\n\n\nif __name__ == '__main__':\n w = Watcher()\n w.run()\n\nwhen I create a new .avi file in the path, the following is the output:\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"watchdog"
] |
stackoverflow_0074514273_python_watchdog.txt
|
Q:
Is there a vim plugin for Python that will check if a non-existant object is called from a package?
I have been using the flake 8 python extension, which when ran will tell me whether a variable is not defined, if there are too many white spaces, etc. But flake8 will not produce an error if I call a nonexistent object from some package. For example, the following will not produce an error with flake8:
import numpy as np
x = np.aa_bb_cc()
np.aa_bb_cc() does not exist so I would like to have a plug in that would tell me so before I run my python script. Is there a plugin that will produce an error for the above? For example, this feature is built into Visual Studio Code but I would like to also be able to have this same feature in vim if possible.
A:
Install pylint then create a vim map to run it from within vim.
nnoremap <leader>l :!python3 -m pylint % <bar> grep no-member<cr>
Notes: I'm using <leader>l but it could be anything else. Also, <bar> grep no-member will only output the error you're looking for. Remove it to see other pylint warnings.
|
Is there a vim plugin for Python that will check if a non-existant object is called from a package?
|
I have been using the flake 8 python extension, which when ran will tell me whether a variable is not defined, if there are too many white spaces, etc. But flake8 will not produce an error if I call a nonexistent object from some package. For example, the following will not produce an error with flake8:
import numpy as np
x = np.aa_bb_cc()
np.aa_bb_cc() does not exist so I would like to have a plug in that would tell me so before I run my python script. Is there a plugin that will produce an error for the above? For example, this feature is built into Visual Studio Code but I would like to also be able to have this same feature in vim if possible.
|
[
"Install pylint then create a vim map to run it from within vim.\nnnoremap <leader>l :!python3 -m pylint % <bar> grep no-member<cr>\n\nNotes: I'm using <leader>l but it could be anything else. Also, <bar> grep no-member will only output the error you're looking for. Remove it to see other pylint warnings.\n"
] |
[
0
] |
[] |
[] |
[
"plugins",
"python",
"vim"
] |
stackoverflow_0074435856_plugins_python_vim.txt
|
Q:
how read a specific sheet from a CSV file using read_csv() function of pandas library by passing sheet name as an argument?
i want to read a csv file with the file name, when i pass the sheet name as an argument i am getting an error message.
i tried the following code and it did not work.
import pandas as pd df = pd.read_csv('file_name.csv',sheet_name='sheet 1',header = 1)
The error message is " read_csv() got an unexpected keyword argument 'sheet_name' "
A:
I think you should use excel_parse instead of parse_CSV , because CSV is a comma separated text file, which does not contain multiple sheets.
xls = pd.ExcelFile('path_to_file.xls')
sheet1 = xls.parse(0)
# above will give you first sheet
sheet1 = xls.parse(1)
#This will give you second sheet
|
how read a specific sheet from a CSV file using read_csv() function of pandas library by passing sheet name as an argument?
|
i want to read a csv file with the file name, when i pass the sheet name as an argument i am getting an error message.
i tried the following code and it did not work.
import pandas as pd df = pd.read_csv('file_name.csv',sheet_name='sheet 1',header = 1)
The error message is " read_csv() got an unexpected keyword argument 'sheet_name' "
|
[
"I think you should use excel_parse instead of parse_CSV , because CSV is a comma separated text file, which does not contain multiple sheets.\nxls = pd.ExcelFile('path_to_file.xls')\nsheet1 = xls.parse(0)\n\n# above will give you first sheet\n\nsheet1 = xls.parse(1)\n\n#This will give you second sheet\n\n"
] |
[
0
] |
[] |
[] |
[
"csv",
"pandas",
"python"
] |
stackoverflow_0074515076_csv_pandas_python.txt
|
Q:
Python Pandas Plot graphs in percentage
I have data of States and Classes as below. I am trying to plot the total, and different percentages using matplotlib.
data = [['FL', 2], ['AR', 0], ['CA', 0], ['CA', 1], ['AR', 1], ['FL', 0], ['CA', 0], ['CA', 1], ['AR', 2], ['FL', 1],
['AR', 0], ['FL', 2], ['CA', 1], ['FL', 1], ['AR', 1], ['AR', 2], ['AR', 1], ['FL', 2], ['CA', 2], ['FL', 0],
['FL', 2], ['AR', 2], ['AR', 1], ['FL', 0], ['AR', 1], ['CA', 0], ['CA', 0], ['CA', 2]]
columns = ['State', 'Class']
df = pd.DataFrame(data=data, columns=columns)
df.groupby(['State', 'Class']).size()
The counts were plotted using the code below:
df.groupby(['State', 'Class']).size().to_frame('Size').unstack(level=-1).sort_values([('Size', 0)], ascending=False).plot(kind='bar', rot=45, figsize=(8,8), fontsize=10)
plt.legend(['Class 0', 'Class 1', 'Class 2'], prop ={'size' : 15})
Similarly, percentages (state level, class level and overall) need to be plotted as well. Here's what I'm looking for:
Graph 1 : State on x axis and State level percentage of 'Size' on y axis with bars colored for each class (i.e., 3 bars per state)
Graph 2 : Class on x axis and Class level percentage of 'Size' on y axis with bars colored for each state (i.e., 51 bars per class)
Graph 3 : same as Graph 1 with Overall percentage of 'Size' on y axis.
Would you please help with how it can be done with an elegant approach ?
Below is my current solution. Need to plot StatePercent, ClassPercent and OverallPercent (Pic#3). My wish is to generate the 3 graphs without creating columns, like how it's done for 'Size' (Pic#2). (In the actual data frame, I have 100s of other columns; so looking for options not to create unnecessary columns if possible. These three columns are needed only for the stats, not for any of the processing)
Pic#1 - the dataframe
Pic#2 - Plotting 'Size' without creating a column in df
Pic#3 - Need to plot StatePercent, ClassPercent and OverallPercent values as calculated below
A:
I assume your terms are defined like these.
State level percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for the class C and all states)
Class level percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for the state S and all classes)
Overall percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for all states and all classes)
You can use the apply() and sum() like the following example.
df0 = df.groupby(['State', 'Class']).size().to_frame('Size')
df1 = df0.unstack(level=1).apply(lambda row: 100*row/sum(row), axis=1)
df2 = df0.unstack(level=0).apply(lambda row: 100*row/sum(row), axis=1)
df3 = 100*df0.unstack(level=1)/df0.sum().sum()
You can plot df1, df2 and df3 for case 1, 2 and 3 respectively.
|
Python Pandas Plot graphs in percentage
|
I have data of States and Classes as below. I am trying to plot the total, and different percentages using matplotlib.
data = [['FL', 2], ['AR', 0], ['CA', 0], ['CA', 1], ['AR', 1], ['FL', 0], ['CA', 0], ['CA', 1], ['AR', 2], ['FL', 1],
['AR', 0], ['FL', 2], ['CA', 1], ['FL', 1], ['AR', 1], ['AR', 2], ['AR', 1], ['FL', 2], ['CA', 2], ['FL', 0],
['FL', 2], ['AR', 2], ['AR', 1], ['FL', 0], ['AR', 1], ['CA', 0], ['CA', 0], ['CA', 2]]
columns = ['State', 'Class']
df = pd.DataFrame(data=data, columns=columns)
df.groupby(['State', 'Class']).size()
The counts were plotted using the code below:
df.groupby(['State', 'Class']).size().to_frame('Size').unstack(level=-1).sort_values([('Size', 0)], ascending=False).plot(kind='bar', rot=45, figsize=(8,8), fontsize=10)
plt.legend(['Class 0', 'Class 1', 'Class 2'], prop ={'size' : 15})
Similarly, percentages (state level, class level and overall) need to be plotted as well. Here's what I'm looking for:
Graph 1 : State on x axis and State level percentage of 'Size' on y axis with bars colored for each class (i.e., 3 bars per state)
Graph 2 : Class on x axis and Class level percentage of 'Size' on y axis with bars colored for each state (i.e., 51 bars per class)
Graph 3 : same as Graph 1 with Overall percentage of 'Size' on y axis.
Would you please help with how it can be done with an elegant approach ?
Below is my current solution. Need to plot StatePercent, ClassPercent and OverallPercent (Pic#3). My wish is to generate the 3 graphs without creating columns, like how it's done for 'Size' (Pic#2). (In the actual data frame, I have 100s of other columns; so looking for options not to create unnecessary columns if possible. These three columns are needed only for the stats, not for any of the processing)
Pic#1 - the dataframe
Pic#2 - Plotting 'Size' without creating a column in df
Pic#3 - Need to plot StatePercent, ClassPercent and OverallPercent values as calculated below
|
[
"I assume your terms are defined like these.\n\nState level percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for the class C and all states)\nClass level percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for the state S and all classes)\nOverall percentage of a state S and a class C = 100 * (count of records for the state S and the class C) / (count of records for all states and all classes)\n\nYou can use the apply() and sum() like the following example.\ndf0 = df.groupby(['State', 'Class']).size().to_frame('Size')\ndf1 = df0.unstack(level=1).apply(lambda row: 100*row/sum(row), axis=1)\ndf2 = df0.unstack(level=0).apply(lambda row: 100*row/sum(row), axis=1)\ndf3 = 100*df0.unstack(level=1)/df0.sum().sum()\n\nYou can plot df1, df2 and df3 for case 1, 2 and 3 respectively.\n"
] |
[
0
] |
[] |
[] |
[
"matplotlib",
"pandas",
"plot",
"python"
] |
stackoverflow_0074495984_matplotlib_pandas_plot_python.txt
|
Q:
How can I write an mltable artifact from python to a local folder?
I am using the mltable library on an AzureML notebook.
I can successufully load a local csv file as an mltable:
from mltable import from_delimited_files
paths = [{'file': "dati_estra_test.csv"}]
dati = from_delimited_files(paths)
And I can view it as a pandas dataframe:
Is there a way to write this artifact as an MLTable artifact?
Or to register it as an mltable AzureML dataset?
A:
Use the below code block to get the file downloaded.
from azureml.core import Workspace, Dataset
subscription_id = ‘subscription'
resource_group = ‘your RG’
workspace_name = 'nov21'
workspace = Workspace(subscription_id, resource_group, workspace_name)
dataset = Dataset.get_by_name(workspace, name='churn')
dataset.to_pandas_dataframe()
dataset.to_pandas_dataframe(on_error='null', out_of_range_datetime='null')
dataset.download('Churn', target_path='df.csv', overwrite=False, ignore_not_found=True)
This will download the file to the specific folder.
|
How can I write an mltable artifact from python to a local folder?
|
I am using the mltable library on an AzureML notebook.
I can successufully load a local csv file as an mltable:
from mltable import from_delimited_files
paths = [{'file': "dati_estra_test.csv"}]
dati = from_delimited_files(paths)
And I can view it as a pandas dataframe:
Is there a way to write this artifact as an MLTable artifact?
Or to register it as an mltable AzureML dataset?
|
[
"Use the below code block to get the file downloaded.\nfrom azureml.core import Workspace, Dataset\n\nsubscription_id = ‘subscription'\nresource_group = ‘your RG’\nworkspace_name = 'nov21'\n\nworkspace = Workspace(subscription_id, resource_group, workspace_name)\n\ndataset = Dataset.get_by_name(workspace, name='churn')\ndataset.to_pandas_dataframe()\n\ndataset.to_pandas_dataframe(on_error='null', out_of_range_datetime='null')\n\ndataset.download('Churn', target_path='df.csv', overwrite=False, ignore_not_found=True)\n\nThis will download the file to the specific folder.\n"
] |
[
0
] |
[] |
[] |
[
"azure",
"azure_machine_learning_service",
"azure_sdk",
"python"
] |
stackoverflow_0074507558_azure_azure_machine_learning_service_azure_sdk_python.txt
|
Q:
Python decode not converting to string
I am attempting to read a string from serial line using the code below, python keeps attaching the b' prefix and newline or return suffixes despite my telling it to convert to regular code and strip those out. Also, even if I send the text for 'FORWARD' to the device, it will not recognize the response.
Why wont python convert my text to regular format, and how do I get it to recognize my input.
#!/usr/bin/env python
import serial
ser = serial.Serial(port='/dev/ttyAMA0',baudrate = 9600,timeout=1)
while 1:
x=ser.readString()
x = x.decode()
x = x.strip()
print(x)
if x.find('FORWARD') >= 0:
print("FORWARD")
I expect it to show my serial input without the b' prefix or any \r\n suffixes, just the text I sent. I also expect it to recognize that the word "FORWARD" was in my input when I send that over the serial line. It dont do that, it shows b'FORWARD\r\n' and dont recognize that FORWARD is in the text
A:
Hello I think decode('UTF-8') might help. I am working with binary data as well and you should specify which form you want it to be decoded to.
b'test'.decode('utf-8') == 'test' -> True
If the problem roots in that your string is binary which contains binary string, such as b'b"test"' then you can solve it with:
b'b"test"'.decode('utf-8').strip('b"') == 'test' -> True
|
Python decode not converting to string
|
I am attempting to read a string from serial line using the code below, python keeps attaching the b' prefix and newline or return suffixes despite my telling it to convert to regular code and strip those out. Also, even if I send the text for 'FORWARD' to the device, it will not recognize the response.
Why wont python convert my text to regular format, and how do I get it to recognize my input.
#!/usr/bin/env python
import serial
ser = serial.Serial(port='/dev/ttyAMA0',baudrate = 9600,timeout=1)
while 1:
x=ser.readString()
x = x.decode()
x = x.strip()
print(x)
if x.find('FORWARD') >= 0:
print("FORWARD")
I expect it to show my serial input without the b' prefix or any \r\n suffixes, just the text I sent. I also expect it to recognize that the word "FORWARD" was in my input when I send that over the serial line. It dont do that, it shows b'FORWARD\r\n' and dont recognize that FORWARD is in the text
|
[
"Hello I think decode('UTF-8') might help. I am working with binary data as well and you should specify which form you want it to be decoded to.\nb'test'.decode('utf-8') == 'test' -> True\nIf the problem roots in that your string is binary which contains binary string, such as b'b\"test\"' then you can solve it with:\nb'b\"test\"'.decode('utf-8').strip('b\"') == 'test' -> True\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074511607_python_python_3.x.txt
|
Q:
How to submit an HTML dropdown list using FastAPI?
How do I submit the value selected from a dropdown list using FastAPI and HTML template?
Here is my code for the app thus far:
from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates/")
@app.get('/')
def read_form():
return 'hello world'
@app.get("/form")
def form_post(request: Request):
result = "Select your name"
return templates.TemplateResponse('form.html', context={'request': request, 'result': result})
@app.post("/form")
def form_post(request: Request, result = Form(...)):
return templates.TemplateResponse('form.html', context={'request': request, 'result': result})
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Form</title>
</head>
<body>
<form method="post">
<select name="names" id="names">
<option value="n1">Name 1</option>
<option value="n2">Name 2</option>
<option value="n3">Name 3</option>
<option value="n5">Name 4</option>
</select>
<input type="submit" value="Submit">
</form>
<p>Result: {{ result }}</p>
</body>
</html>
Here is the error message:
{"detail":[{"loc":["body","result"],"msg":"field required","type":"value_error.missing"}]}
The goal is to select a name, click submit, and then have it displayed below.
A:
You need to make sure to include the action attribute in the form, which specifies where to send the form-data when a form is submitted (see W3schools <form> tag docs as well). Also, in the <select> element that is used to create the drop-down list, make sure to use the same name used to define the Form parameter in your endpoint. As per W3schools <select> tag docs:
The name attribute is needed to reference the form data after the
form is submitted (if you omit the name attribute, no data from the
drop-down list will be submitted).
Each <option> element inside the <select> should have a value attribute containing the data value to submit to the server when that option is selected. If no value attribute is included, the value defaults to the text contained inside the element. You can include a selected attribute on an <option> element to make it selected by default when the page first loads.
Working Example
app.py
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')
@app.post('/submit')
def submit(car: str = Form(...)):
return car
@app.get('/', response_class=HTMLResponse)
def main(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
templates/index.html
<!DOCTYPE html>
<html>
<body>
<form method="POST" action="/submit">
<label for="cars">Choose a car:</label>
<select name="car" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
|
How to submit an HTML dropdown list using FastAPI?
|
How do I submit the value selected from a dropdown list using FastAPI and HTML template?
Here is my code for the app thus far:
from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates/")
@app.get('/')
def read_form():
return 'hello world'
@app.get("/form")
def form_post(request: Request):
result = "Select your name"
return templates.TemplateResponse('form.html', context={'request': request, 'result': result})
@app.post("/form")
def form_post(request: Request, result = Form(...)):
return templates.TemplateResponse('form.html', context={'request': request, 'result': result})
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Form</title>
</head>
<body>
<form method="post">
<select name="names" id="names">
<option value="n1">Name 1</option>
<option value="n2">Name 2</option>
<option value="n3">Name 3</option>
<option value="n5">Name 4</option>
</select>
<input type="submit" value="Submit">
</form>
<p>Result: {{ result }}</p>
</body>
</html>
Here is the error message:
{"detail":[{"loc":["body","result"],"msg":"field required","type":"value_error.missing"}]}
The goal is to select a name, click submit, and then have it displayed below.
|
[
"You need to make sure to include the action attribute in the form, which specifies where to send the form-data when a form is submitted (see W3schools <form> tag docs as well). Also, in the <select> element that is used to create the drop-down list, make sure to use the same name used to define the Form parameter in your endpoint. As per W3schools <select> tag docs:\n\nThe name attribute is needed to reference the form data after the\nform is submitted (if you omit the name attribute, no data from the\ndrop-down list will be submitted).\n\nEach <option> element inside the <select> should have a value attribute containing the data value to submit to the server when that option is selected. If no value attribute is included, the value defaults to the text contained inside the element. You can include a selected attribute on an <option> element to make it selected by default when the page first loads.\nWorking Example\napp.py\nfrom fastapi import FastAPI, Form, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating import Jinja2Templates\n\napp = FastAPI()\ntemplates = Jinja2Templates(directory='templates')\n\n@app.post('/submit')\ndef submit(car: str = Form(...)):\n return car\n\n@app.get('/', response_class=HTMLResponse)\ndef main(request: Request):\n return templates.TemplateResponse('index.html', {'request': request})\n\ntemplates/index.html\n<!DOCTYPE html>\n<html>\n <body>\n <form method=\"POST\" action=\"/submit\">\n <label for=\"cars\">Choose a car:</label>\n <select name=\"car\" id=\"cars\">\n <option value=\"volvo\">Volvo</option>\n <option value=\"saab\">Saab</option>\n <option value=\"opel\">Opel</option>\n <option value=\"audi\">Audi</option>\n </select>\n <br><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>\n\n"
] |
[
0
] |
[] |
[] |
[
"fastapi",
"python"
] |
stackoverflow_0074504161_fastapi_python.txt
|
Q:
Tensorboard scalar plotting with epoch number on the horizontal axis
I am new to TensorFlow, and I recently started to play around a little bit with data visualization using Tensorboard.
I was wondering if it is possible to convert the horizontal axis of the monitoring scalars (I monitor accuracy and loss on train and validation) to show epoch number instead of iteration number.
the only way I can think of how to do it is to change the sampling frequency to one per epoch, but I am interested in keeping the original sampling resolution.
is there a better way?
A:
Yes, you can do this by passing the epoch number to the global_step parameter of the add_summary() method:
summary_writer = tf.summary.FileWriter(log_dir)
my_summary = session.run(my_summary_op, feed_dict)
summary_writer.add_summary(my_summary, global_step=epoch_number)
A:
One workaround is using add_scalars().
writer = SummaryWriter()
for idx_epoch in range(epochs):
for idx_batch in range(batches):
# fetch data
data, target = None, None
# compute loss
loss = nn.L1Loss(data, target)
# backward propagation
global_step = idx_epoch*batches+idx_batch
writer.add_scalars('loss', {'batch':loss}, global_step)
writer.add_scalars('loss', {'epoch':loss}, global_step)
Note that these codes are actually pseudo codes, which means they cannot run.
Notice that there is a loss writing for every batch as well as every epoch.
Then the tensorboard result will look like this:
Red line records the loss every epoch, while blue line records batchly.
|
Tensorboard scalar plotting with epoch number on the horizontal axis
|
I am new to TensorFlow, and I recently started to play around a little bit with data visualization using Tensorboard.
I was wondering if it is possible to convert the horizontal axis of the monitoring scalars (I monitor accuracy and loss on train and validation) to show epoch number instead of iteration number.
the only way I can think of how to do it is to change the sampling frequency to one per epoch, but I am interested in keeping the original sampling resolution.
is there a better way?
|
[
"Yes, you can do this by passing the epoch number to the global_step parameter of the add_summary() method:\nsummary_writer = tf.summary.FileWriter(log_dir)\n\nmy_summary = session.run(my_summary_op, feed_dict)\nsummary_writer.add_summary(my_summary, global_step=epoch_number)\n\n",
"One workaround is using add_scalars().\nwriter = SummaryWriter()\nfor idx_epoch in range(epochs):\n for idx_batch in range(batches):\n # fetch data\n data, target = None, None\n # compute loss\n loss = nn.L1Loss(data, target)\n # backward propagation\n\n global_step = idx_epoch*batches+idx_batch\n writer.add_scalars('loss', {'batch':loss}, global_step)\n writer.add_scalars('loss', {'epoch':loss}, global_step)\n\n\nNote that these codes are actually pseudo codes, which means they cannot run.\nNotice that there is a loss writing for every batch as well as every epoch.\n\nThen the tensorboard result will look like this:\n\n\nRed line records the loss every epoch, while blue line records batchly.\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"python",
"tensorboard",
"tensorflow"
] |
stackoverflow_0046017070_python_tensorboard_tensorflow.txt
|
Q:
extracting all tables using tabula
While reading a pdf file using
df = tabula.read_pdf(pdf_file, pages=‘all’) —> displays all tables from all pages.
but when converting into a Pandas dataframe using
tables = pd.DataFrame(pdf_file, pages = ‘all’, lattice = ‘True’)[0])—> display only the table on the first page.
A:
The df that you receive from tabula should be in the form of a list.
I also think that if you want to use pandas and tabula together the syntax should be something like below,
df = pandas.DataFrame(tabula.read_pdf(pdffile, pages ='all')[0])
If you want to utilize what you've gotten from tabula, you can also concatenate it into a single df as shown below
dfs = tabula.read_pdf(pdf_file, pages=‘all’)
df = pd.concat(dfs)
If every table has it's own header, to skip the header for subsequent headers except for first header, try the following:
import numpy as np
dfFirstTable = tabula.read_pdf(pdffile)
df = pd.DataFrame(np.concatenate(tabula.read_pdf(pdffile, pages ='all')), columns=dfFirstTable.columns)
|
extracting all tables using tabula
|
While reading a pdf file using
df = tabula.read_pdf(pdf_file, pages=‘all’) —> displays all tables from all pages.
but when converting into a Pandas dataframe using
tables = pd.DataFrame(pdf_file, pages = ‘all’, lattice = ‘True’)[0])—> display only the table on the first page.
|
[
"The df that you receive from tabula should be in the form of a list.\nI also think that if you want to use pandas and tabula together the syntax should be something like below,\ndf = pandas.DataFrame(tabula.read_pdf(pdffile, pages ='all')[0])\n\nIf you want to utilize what you've gotten from tabula, you can also concatenate it into a single df as shown below\ndfs = tabula.read_pdf(pdf_file, pages=‘all’)\ndf = pd.concat(dfs)\n\nIf every table has it's own header, to skip the header for subsequent headers except for first header, try the following:\nimport numpy as np\n\ndfFirstTable = tabula.read_pdf(pdffile)\ndf = pd.DataFrame(np.concatenate(tabula.read_pdf(pdffile, pages ='all')), columns=dfFirstTable.columns)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tabula_py",
"text_extraction"
] |
stackoverflow_0074515191_python_tabula_py_text_extraction.txt
|
Q:
ScrapeTube package for Youtube is not Working?
I tried to extract all youtube videoid from a channel. It was working fine last week suddenly its not working from yesterday. In fact its not throwing any errors. Kindly help!
#scrape all the videos links
import scrapetube
link=[]
videos = scrapetube.get_channel("UCPXnayBvF7ynbG_I3VOTgIg")
for video in videos:
str1="https://www.youtube.com/watch?v="+str(video['videoId'])
link.append(str1)
When i tried to look at the list of link. Its showing empty link.
Input
link[:]
output
[]
A:
It was a bug in a consent line in youtube that is fixed in version 2.3.1 of scrapetube. I suggest you uninstall any version <= 2.3.0 and install the latest one. That should do it.
|
ScrapeTube package for Youtube is not Working?
|
I tried to extract all youtube videoid from a channel. It was working fine last week suddenly its not working from yesterday. In fact its not throwing any errors. Kindly help!
#scrape all the videos links
import scrapetube
link=[]
videos = scrapetube.get_channel("UCPXnayBvF7ynbG_I3VOTgIg")
for video in videos:
str1="https://www.youtube.com/watch?v="+str(video['videoId'])
link.append(str1)
When i tried to look at the list of link. Its showing empty link.
Input
link[:]
output
[]
|
[
"It was a bug in a consent line in youtube that is fixed in version 2.3.1 of scrapetube. I suggest you uninstall any version <= 2.3.0 and install the latest one. That should do it.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"scrape",
"youtube"
] |
stackoverflow_0074356652_python_scrape_youtube.txt
|
Q:
Keras models diferent results after loading pretrained weights
After successfully training a model, and saving the weights with a checkpoint, when I reload the weights with the load_weights function and run an evaluate, I get results as if the network was loaded with the original weights.
I have tried to run the eval on the train and valid sets, to rule out that it is a problem of the test set, and the same thing happens.
Here is the trainning code:
def create_inception(model_name, fold_path, model_path, optimizer=Adam(learning_rate=0.0001)):
inputs = tf.keras.Input(shape=(224, 224, 3))
head_model = InceptionV3(weights = 'imagenet', include_top = False, input_shape = (224,224,3))
head_model.trainable = True
head_model = head_model(inputs, training = True)
head_model = tf.keras.layers.Flatten()(head_model)
head_model = tf.keras.layers.Dense(256, activation='relu')(head_model)
output = Dense(3, activation='softmax')(head_model)
model4 = Model(inputs=inputs, outputs = output)
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
validation_datagen = ImageDataGenerator(rescale=1./255)
# Note that the validation data should not be augmented!
train_generator = train_datagen.flow_from_directory(fold_path + '/Train',
batch_size=8,
class_mode='categorical',
target_size=(224, 224))
validation_generator = validation_datagen.flow_from_directory(fold_path + '/Valid',
batch_size=8,
class_mode = 'categorical',
target_size = (224, 224))
# compilamos el modelo y lo entrenamos
model4.compile(loss="categorical_crossentropy",
optimizer=optimizer,
metrics=[tfa.metrics.F1Score(num_classes=3, average='micro'), 'accuracy'])
return model4, train_generator, validation_generator
def train_inception_model(model, train_generator, validation_generator, model_path, model_name, epochs=100):
batch_size = 8
steps_per_epoch = train_generator.n // batch_size
validation_steps = validation_generator.n // batch_size
# generamos un monitor para el earlystop cuando el modelo este entrenado
early_stop = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=10, min_delta=0.001)
# generamos el callback de guardado del modelo
filepath = model_path + model_name + "_best.hdf5"
checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath, monitor='val_f1_score', verbose=1, save_best_only=True, save_weights_only=True, mode='max')
model4_history = model.fit(
train_generator,
steps_per_epoch = steps_per_epoch,
epochs = epochs,
callbacks = [early_stop, checkpoint],
validation_data = validation_generator,
validation_steps = validation_steps
)
return model, model4_history
Here is the trainning result
Epoch 40: val_f1_score did not improve from 0.94413
99/99 [==============================] - 54s 540ms/step - loss: 0.0601 - f1_score: 0.9750 - accuracy: 0.9750 - val_loss: 0.1700 - val_f1_score: 0.9347 - val_accuracy: 0.9347
The evaluate code:
name = 'kfold_model_' + str(0)
print(name)
model4, _, _ = create_inception(name, '/content/Fold10', model_path4, opt['type'](learning_rate=lr))
model4.compile(loss="categorical_crossentropy",
optimizer=Adam(learning_rate=0.01),
metrics=[tfa.metrics.F1Score(num_classes=3, average='micro'), 'accuracy'])
model4.load_weights(model_path4 + "{}_best.hdf5".format(name))
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory('Fold{}/Test'.format(10),
batch_size=32,
class_mode = 'categorical',
target_size = (224, 224), shuffle=False)
test_lost, test_f1, test_acc = model4.evaluate(test_generator)
print ("Test f1:", test_f1)
print ("Test Accuracy:", test_acc)
The evaluate output:
Found 530 images belonging to 3 classes.
17/17 [==============================] - 45s 2s/step - loss: 5.2010 - f1_score: 0.5491 - accuracy: 0.5491
Test f1: 0.5490565896034241
Test Accuracy: 0.5490565896034241
This code works perfectly fine with the VGG16 network, but with inceptionV3 and resnet121 I have the same problem.
Any suggestions?
A:
If i remove the 'Shuffe = False' in the test data_generator works perfectly fine.
|
Keras models diferent results after loading pretrained weights
|
After successfully training a model, and saving the weights with a checkpoint, when I reload the weights with the load_weights function and run an evaluate, I get results as if the network was loaded with the original weights.
I have tried to run the eval on the train and valid sets, to rule out that it is a problem of the test set, and the same thing happens.
Here is the trainning code:
def create_inception(model_name, fold_path, model_path, optimizer=Adam(learning_rate=0.0001)):
inputs = tf.keras.Input(shape=(224, 224, 3))
head_model = InceptionV3(weights = 'imagenet', include_top = False, input_shape = (224,224,3))
head_model.trainable = True
head_model = head_model(inputs, training = True)
head_model = tf.keras.layers.Flatten()(head_model)
head_model = tf.keras.layers.Dense(256, activation='relu')(head_model)
output = Dense(3, activation='softmax')(head_model)
model4 = Model(inputs=inputs, outputs = output)
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
validation_datagen = ImageDataGenerator(rescale=1./255)
# Note that the validation data should not be augmented!
train_generator = train_datagen.flow_from_directory(fold_path + '/Train',
batch_size=8,
class_mode='categorical',
target_size=(224, 224))
validation_generator = validation_datagen.flow_from_directory(fold_path + '/Valid',
batch_size=8,
class_mode = 'categorical',
target_size = (224, 224))
# compilamos el modelo y lo entrenamos
model4.compile(loss="categorical_crossentropy",
optimizer=optimizer,
metrics=[tfa.metrics.F1Score(num_classes=3, average='micro'), 'accuracy'])
return model4, train_generator, validation_generator
def train_inception_model(model, train_generator, validation_generator, model_path, model_name, epochs=100):
batch_size = 8
steps_per_epoch = train_generator.n // batch_size
validation_steps = validation_generator.n // batch_size
# generamos un monitor para el earlystop cuando el modelo este entrenado
early_stop = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=10, min_delta=0.001)
# generamos el callback de guardado del modelo
filepath = model_path + model_name + "_best.hdf5"
checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath, monitor='val_f1_score', verbose=1, save_best_only=True, save_weights_only=True, mode='max')
model4_history = model.fit(
train_generator,
steps_per_epoch = steps_per_epoch,
epochs = epochs,
callbacks = [early_stop, checkpoint],
validation_data = validation_generator,
validation_steps = validation_steps
)
return model, model4_history
Here is the trainning result
Epoch 40: val_f1_score did not improve from 0.94413
99/99 [==============================] - 54s 540ms/step - loss: 0.0601 - f1_score: 0.9750 - accuracy: 0.9750 - val_loss: 0.1700 - val_f1_score: 0.9347 - val_accuracy: 0.9347
The evaluate code:
name = 'kfold_model_' + str(0)
print(name)
model4, _, _ = create_inception(name, '/content/Fold10', model_path4, opt['type'](learning_rate=lr))
model4.compile(loss="categorical_crossentropy",
optimizer=Adam(learning_rate=0.01),
metrics=[tfa.metrics.F1Score(num_classes=3, average='micro'), 'accuracy'])
model4.load_weights(model_path4 + "{}_best.hdf5".format(name))
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory('Fold{}/Test'.format(10),
batch_size=32,
class_mode = 'categorical',
target_size = (224, 224), shuffle=False)
test_lost, test_f1, test_acc = model4.evaluate(test_generator)
print ("Test f1:", test_f1)
print ("Test Accuracy:", test_acc)
The evaluate output:
Found 530 images belonging to 3 classes.
17/17 [==============================] - 45s 2s/step - loss: 5.2010 - f1_score: 0.5491 - accuracy: 0.5491
Test f1: 0.5490565896034241
Test Accuracy: 0.5490565896034241
This code works perfectly fine with the VGG16 network, but with inceptionV3 and resnet121 I have the same problem.
Any suggestions?
|
[
"If i remove the 'Shuffe = False' in the test data_generator works perfectly fine.\n"
] |
[
0
] |
[] |
[] |
[
"keras",
"python",
"tensorflow"
] |
stackoverflow_0074457385_keras_python_tensorflow.txt
|
Q:
pyspark filter the value of a column to assign a new column
In python, you can write A filter and assign a value to a new column by using df.loc[df["A"].isin([1,2,3]),"newColumn"] ="numberType". How does this work in pyspark?
A:
FYI, in Python there is no such thing as DataFrame. The code you showed above are Pandas syntax - a Python library written for data analysis and manipulation.
For your problem, you can use when, lit and col from pyspark.sql.functions to achieve this.
from pyspark.sql.functions import when, lit, col
df1 = df.withColumn("newColumn",
when(col("A").isin([1, 2, 3],
lit("numberType")).otherwise(lit("notNumberType")))
df1.show(truncate=False)
A:
Use when function to filter rows, and isin function to check existence in list:
pdf = pd.DataFrame(data=[[1,""],[2,""],[3,""],[4,""],[5,""]], columns=["A", "newColumn"])
pdf.loc[pdf["A"].isin([1,2,3]), "newColumn"] = "numberType"
print(pdf)
A newColumn
0 1 numberType
1 2 numberType
2 3 numberType
3 4
4 5
import pyspark.sql.functions as F
sdf = spark.createDataFrame(data=[[1,""],[2,""],[3,""],[4,""],[5,""]], schema=["A", "newColumn"])
sdf = sdf.withColumn("newColumn", F.when(F.col("A").isin([1,2,3]), F.lit("numberType")))
sdf.show()
+---+----------+
| A| newColumn|
+---+----------+
| 1|numberType|
| 2|numberType|
| 3|numberType|
| 4| null|
| 5| null|
+---+----------+
|
pyspark filter the value of a column to assign a new column
|
In python, you can write A filter and assign a value to a new column by using df.loc[df["A"].isin([1,2,3]),"newColumn"] ="numberType". How does this work in pyspark?
|
[
"FYI, in Python there is no such thing as DataFrame. The code you showed above are Pandas syntax - a Python library written for data analysis and manipulation.\nFor your problem, you can use when, lit and col from pyspark.sql.functions to achieve this.\nfrom pyspark.sql.functions import when, lit, col\n\ndf1 = df.withColumn(\"newColumn\", \n when(col(\"A\").isin([1, 2, 3], \n lit(\"numberType\")).otherwise(lit(\"notNumberType\")))\n\ndf1.show(truncate=False)\n\n",
"Use when function to filter rows, and isin function to check existence in list:\npdf = pd.DataFrame(data=[[1,\"\"],[2,\"\"],[3,\"\"],[4,\"\"],[5,\"\"]], columns=[\"A\", \"newColumn\"])\npdf.loc[pdf[\"A\"].isin([1,2,3]), \"newColumn\"] = \"numberType\"\nprint(pdf)\n\n A newColumn\n0 1 numberType\n1 2 numberType\n2 3 numberType\n3 4 \n4 5 \n\n\nimport pyspark.sql.functions as F\nsdf = spark.createDataFrame(data=[[1,\"\"],[2,\"\"],[3,\"\"],[4,\"\"],[5,\"\"]], schema=[\"A\", \"newColumn\"])\nsdf = sdf.withColumn(\"newColumn\", F.when(F.col(\"A\").isin([1,2,3]), F.lit(\"numberType\")))\nsdf.show()\n\n+---+----------+\n| A| newColumn|\n+---+----------+\n| 1|numberType|\n| 2|numberType|\n| 3|numberType|\n| 4| null|\n| 5| null|\n+---+----------+\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"pyspark",
"python"
] |
stackoverflow_0074515285_pyspark_python.txt
|
Q:
how can i do a variables in python
this is my problem and the photo of it
i have no idea why it didn't work
A:
Avoid this by selecting 'Auto Save' Option in File Menu of VS Code
A:
I think it's not just about saving files automatically.
Usually, we use CamelCase or _
For example, pythonVariables or python_variables.
|
how can i do a variables in python
|
this is my problem and the photo of it
i have no idea why it didn't work
|
[
"Avoid this by selecting 'Auto Save' Option in File Menu of VS Code\n",
"I think it's not just about saving files automatically.\nUsually, we use CamelCase or _\nFor example, pythonVariables or python_variables.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"variables",
"visual_studio_code"
] |
stackoverflow_0074513416_python_variables_visual_studio_code.txt
|
Q:
applying conditions basis the value in column to create new tag
Existing Dataframe :
Id created_by
A A
A 123
B X
B B
Expected Dataframe :
Id created_by status
A A category_1
A 123 category_2
B X category_3
B B category_1
I am looking to create a status tag basis the condition :
if Id == created_by >> category_1
if id != created_by >> category_2
if id != created_by & created_by == 'X' >> category_3
i am using below code :
conditions = [
df['Id'] == df['created_by'],
df['Id'] != df['created_by'],
(df['Id'] != df['created_by']) & (df['created_by'] == 'X')
]
# Creating Labels
result = ['category_1','category_2','category_3']
# Creating status column
df['status'] = np.select(conditions, result , default='REST')
somehow i am not getting correct number for third condition. what am i missing
A:
Problem is in second condition, there is necessary add filtering non X values in created_by:
conditions = [
df['Id'] == df['created_by'],
(df['Id'] != df['created_by']) & (df['created_by'] != 'X'),
(df['Id'] != df['created_by']) & (df['created_by'] == 'X')
]
# Creating Labels
result = ['category_1','category_2','category_3']
# Creating status column
df['status'] = np.select(conditions, result , default='REST')
print (df)
Id created_by status
0 A A category_1
1 A 123 category_2
2 B X category_3
3 B B category_1
For improve solution (call conditions only once) you can create helper masks and chain like:
m1 = df['Id'] == df['created_by']
m2 = df['created_by'] == 'X'
conditions = [m1, ~m1 & ~m2, ~m1 & m2]
# Creating Labels
result = ['category_1','category_2','category_3']
# Creating status column
df['status'] = np.select(conditions, result , default='REST')
|
applying conditions basis the value in column to create new tag
|
Existing Dataframe :
Id created_by
A A
A 123
B X
B B
Expected Dataframe :
Id created_by status
A A category_1
A 123 category_2
B X category_3
B B category_1
I am looking to create a status tag basis the condition :
if Id == created_by >> category_1
if id != created_by >> category_2
if id != created_by & created_by == 'X' >> category_3
i am using below code :
conditions = [
df['Id'] == df['created_by'],
df['Id'] != df['created_by'],
(df['Id'] != df['created_by']) & (df['created_by'] == 'X')
]
# Creating Labels
result = ['category_1','category_2','category_3']
# Creating status column
df['status'] = np.select(conditions, result , default='REST')
somehow i am not getting correct number for third condition. what am i missing
|
[
"Problem is in second condition, there is necessary add filtering non X values in created_by:\nconditions = [\n df['Id'] == df['created_by'], \n (df['Id'] != df['created_by']) & (df['created_by'] != 'X'),\n (df['Id'] != df['created_by']) & (df['created_by'] == 'X')\n\n ]\n\n# Creating Labels\nresult = ['category_1','category_2','category_3']\n\n# Creating status column\ndf['status'] = np.select(conditions, result , default='REST')\nprint (df)\n Id created_by status\n0 A A category_1\n1 A 123 category_2\n2 B X category_3\n3 B B category_1\n\nFor improve solution (call conditions only once) you can create helper masks and chain like:\nm1 = df['Id'] == df['created_by']\nm2 = df['created_by'] == 'X'\n\nconditions = [m1, ~m1 & ~m2, ~m1 & m2]\n\n# Creating Labels\nresult = ['category_1','category_2','category_3']\n\n# Creating status column\ndf['status'] = np.select(conditions, result , default='REST')\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074515519_dataframe_pandas_python.txt
|
Q:
How to access package level variable
Suppose i have package named src
src
- __init__.py
- app.py
__init__.py
___version__ = '0.1.0'
import os
ENTRY_DIR = os.path.dirname(__file__)
BASE_DIR = os path.dirname(ENTRY_DIR)
DATA_DIR = os.path.join(BASE_DIR, 'data')
how can i access the variable DATA_DIR in app.py
I tried like this,
app.py
from src import DATA_DIR
print(DATA_DIR)
It didn't worked, i got an error.
ModuleNotFoundError: No module named 'src'
How can i acces the variable inside the app module
A:
The __init__.py file is used to define how your package looks for an other one so you cannot do what you are trying to do since you are inside.
You can create a cfg.py like this :
# cfg.py
import os
ENTRY_DIR = os.path.dirname(__file__)
BASE_DIR = os path.dirname(ENTRY_DIR)
DATA_DIR = os.path.join(BASE_DIR, 'data')
So you can import DATA_DIR easily from app.py :
# app.py
from cfg import DATA_DIR
print(DATA_DIR)
If you need to use the variables defined in cfg.py outside of your package you can modified the __init__.py :
# __init__.py
___version__ = "0.1.0"
from .cfg import *
|
How to access package level variable
|
Suppose i have package named src
src
- __init__.py
- app.py
__init__.py
___version__ = '0.1.0'
import os
ENTRY_DIR = os.path.dirname(__file__)
BASE_DIR = os path.dirname(ENTRY_DIR)
DATA_DIR = os.path.join(BASE_DIR, 'data')
how can i access the variable DATA_DIR in app.py
I tried like this,
app.py
from src import DATA_DIR
print(DATA_DIR)
It didn't worked, i got an error.
ModuleNotFoundError: No module named 'src'
How can i acces the variable inside the app module
|
[
"The __init__.py file is used to define how your package looks for an other one so you cannot do what you are trying to do since you are inside.\nYou can create a cfg.py like this :\n# cfg.py\n\nimport os\n\nENTRY_DIR = os.path.dirname(__file__)\nBASE_DIR = os path.dirname(ENTRY_DIR)\nDATA_DIR = os.path.join(BASE_DIR, 'data')\n\nSo you can import DATA_DIR easily from app.py :\n# app.py\n\nfrom cfg import DATA_DIR\n\nprint(DATA_DIR)\n\nIf you need to use the variables defined in cfg.py outside of your package you can modified the __init__.py :\n# __init__.py\n\n___version__ = \"0.1.0\"\n\nfrom .cfg import *\n\n"
] |
[
2
] |
[
"it seems like you are referencing wrong path for that variable.\nimport the file in app.py\nthen you will be able to use variables from that file in same package.\nuse underscore with file name\nimport init\nprint(DATA_DIR)\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0074515105_python.txt
|
Q:
Looal Dynamo db insert validation exception error
I am learning to use dynamodb and am getting An error occurred (ValidationException) when calling the TransactWriteItems operation: One of the required keys was not given a value when trying to run my mock test to insert a value. I am trying to create a mock test. I am clearly missing something and don't understand. The code is largely based off of this link. I removed some of the data being inserted for simplicity.
Test data:
{
"email": "email@b.com"
}
Here is my table definition:
aws dynamodb create-table \
--table-name Profile \
--attribute-definitions \
AttributeName=email,AttributeType=S \
--key-schema AttributeName=email,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \
--table-class STANDARD \
--endpoint-url http://localhost:8000
It exists in my local dynamo db instance
aws dynamodb describe-table --table-name Profile --endpoint-url=http://localhost:8000
{
"Table": {
"AttributeDefinitions": [
{
"AttributeName": "email",
"AttributeType": "S"
}
],
"TableName": "Profile",
"KeySchema": [
{
"AttributeName": "email",
"KeyType": "HASH"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": "2022-11-20T00:39:06.505000-06:00",
"ProvisionedThroughput": {
"LastIncreaseDateTime": "1969-12-31T18:00:00-06:00",
"LastDecreaseDateTime": "1969-12-31T18:00:00-06:00",
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
},
"TableSizeBytes": 0,
"ItemCount": 0,
"TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/Profile"
This is my .env file
AWS_REGION=us-fake-1
DDB_ENDPOINT=http://localhost:8000
AWS_ACCESS_KEY_ID=fake
AWS_SECRET_ACCESS_KEY=fake
API_PROFILESAPI_PROFILETABLE_NAME=ProfileTable
This is my unit test
import json
import boto3
import os
import re
import logging
import unittest
from moto import mock_dynamodb
from http import HTTPStatus
# Seperate inserts are needed to support uniqueness in items other than pk
# use tranaction for rollback
@mock_dynamodb
class TestDatabaseFunctions(unittest.TestCase):
def validateProfile(self, event):
profile_data = {}
for x in self.re_dict.keys():
self.logging.info(f"Validating {x}")
if not re.search(self.re_dict[x], str(event[x])):
print(f"{event[x]} does not match {self.re_dict[x]}")
self.logging.debug(f"{event[x]} does not match {self.re_dict[x]}")
return False, profile_data
else:
profile_data[x] = event[x]
return True, profile_data
def setUp(self) -> None:
self.logging = logging.getLogger(__name__)
self.re_dict = {
"email": "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
}
self.testHandler()
def tearDown(self) -> None:
return super().tearDown()
def insertProfile(self, profile):
message = f"Profile was not created"
dynamodb = boto3.client('dynamodb', endpoint_url="http://localhost:8000")
response = dynamodb.transact_write_items(
TransactItems=[
{
'Put': {
'TableName': 'Profile',
'Item':{
'email' : {
'S': profile['email'],
}
},
'ConditionExpression':'attribute_not_exists(pk)'
},
'Put': {
'TableName': 'Profile',
'Item':{
'pk': {
'S': f"username#{profile['username']}"
}
},
'ConditionExpression':'attribute_not_exists(pk)'
}
}
]
)
return {
"status_code": response['ResponseMetadata']['HTTPStatusCode'],
"message": message
}
def testHandler(self) -> None:
response = {
"status_code": HTTPStatus.BAD_REQUEST,
"message": "Creation was not successful."
}
with open("../event.json", 'r') as f:
event = json.loads(f.read())
self.logging.info(event)
is_valid, profileData = self.validateProfile(event)
self.assertEqual(True, is_valid)
response = self.insertProfile(profileData)
self.assertEqual(HTTPStatus.OK, response)
if __name__ == "__main__":
unittest.main()
A:
Every one of the items you try to Put must have its key attributes - in your case that is the "email" attribute - set. But it seems one of your calls used the name "pk" instead of "email", I guess a copy-pasto.
You also mention "pk" in the ConditionExpression - that's a typo too?
|
Looal Dynamo db insert validation exception error
|
I am learning to use dynamodb and am getting An error occurred (ValidationException) when calling the TransactWriteItems operation: One of the required keys was not given a value when trying to run my mock test to insert a value. I am trying to create a mock test. I am clearly missing something and don't understand. The code is largely based off of this link. I removed some of the data being inserted for simplicity.
Test data:
{
"email": "email@b.com"
}
Here is my table definition:
aws dynamodb create-table \
--table-name Profile \
--attribute-definitions \
AttributeName=email,AttributeType=S \
--key-schema AttributeName=email,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \
--table-class STANDARD \
--endpoint-url http://localhost:8000
It exists in my local dynamo db instance
aws dynamodb describe-table --table-name Profile --endpoint-url=http://localhost:8000
{
"Table": {
"AttributeDefinitions": [
{
"AttributeName": "email",
"AttributeType": "S"
}
],
"TableName": "Profile",
"KeySchema": [
{
"AttributeName": "email",
"KeyType": "HASH"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": "2022-11-20T00:39:06.505000-06:00",
"ProvisionedThroughput": {
"LastIncreaseDateTime": "1969-12-31T18:00:00-06:00",
"LastDecreaseDateTime": "1969-12-31T18:00:00-06:00",
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
},
"TableSizeBytes": 0,
"ItemCount": 0,
"TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/Profile"
This is my .env file
AWS_REGION=us-fake-1
DDB_ENDPOINT=http://localhost:8000
AWS_ACCESS_KEY_ID=fake
AWS_SECRET_ACCESS_KEY=fake
API_PROFILESAPI_PROFILETABLE_NAME=ProfileTable
This is my unit test
import json
import boto3
import os
import re
import logging
import unittest
from moto import mock_dynamodb
from http import HTTPStatus
# Seperate inserts are needed to support uniqueness in items other than pk
# use tranaction for rollback
@mock_dynamodb
class TestDatabaseFunctions(unittest.TestCase):
def validateProfile(self, event):
profile_data = {}
for x in self.re_dict.keys():
self.logging.info(f"Validating {x}")
if not re.search(self.re_dict[x], str(event[x])):
print(f"{event[x]} does not match {self.re_dict[x]}")
self.logging.debug(f"{event[x]} does not match {self.re_dict[x]}")
return False, profile_data
else:
profile_data[x] = event[x]
return True, profile_data
def setUp(self) -> None:
self.logging = logging.getLogger(__name__)
self.re_dict = {
"email": "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
}
self.testHandler()
def tearDown(self) -> None:
return super().tearDown()
def insertProfile(self, profile):
message = f"Profile was not created"
dynamodb = boto3.client('dynamodb', endpoint_url="http://localhost:8000")
response = dynamodb.transact_write_items(
TransactItems=[
{
'Put': {
'TableName': 'Profile',
'Item':{
'email' : {
'S': profile['email'],
}
},
'ConditionExpression':'attribute_not_exists(pk)'
},
'Put': {
'TableName': 'Profile',
'Item':{
'pk': {
'S': f"username#{profile['username']}"
}
},
'ConditionExpression':'attribute_not_exists(pk)'
}
}
]
)
return {
"status_code": response['ResponseMetadata']['HTTPStatusCode'],
"message": message
}
def testHandler(self) -> None:
response = {
"status_code": HTTPStatus.BAD_REQUEST,
"message": "Creation was not successful."
}
with open("../event.json", 'r') as f:
event = json.loads(f.read())
self.logging.info(event)
is_valid, profileData = self.validateProfile(event)
self.assertEqual(True, is_valid)
response = self.insertProfile(profileData)
self.assertEqual(HTTPStatus.OK, response)
if __name__ == "__main__":
unittest.main()
|
[
"Every one of the items you try to Put must have its key attributes - in your case that is the \"email\" attribute - set. But it seems one of your calls used the name \"pk\" instead of \"email\", I guess a copy-pasto.\nYou also mention \"pk\" in the ConditionExpression - that's a typo too?\n"
] |
[
0
] |
[] |
[] |
[
"amazon_dynamodb",
"python"
] |
stackoverflow_0074514455_amazon_dynamodb_python.txt
|
Q:
error putting paths in the function () in python
im trying to run this code but I have an error when I put the path in the function the path turns grey and I have a red line under it, maybe someone can help me with that?
import shutil
from pathlib import Path
from xml.etree import ElementTree as ET
def contains_drone(path):
tree = ET.parse(path.as_posix())
root = tree.getroot()
for obj in root.findall('object'):
rank = obj.find('name').text
if rank == 'car':
return True
return False
def move_drone_files(src="D:\\TomProject\\Images\\",
dst="D:\\TomProject\\Done"):
src, dst = Path(src), Path(dst)
for path in src.iterdir():
if path.suffix == '.xml' and contains_drone(path):
print(f'Moving {path.as_posix()} to {dst.as_posix()}')
shutil.move(path, dst)
if __name__ == "__main__":
move_drone_files()
A:
Assuming the paths you define are your src and dst paths, your function definition should look like this, with corrected indentation and function definition:
def move_drone_files(src, dst):
src, dst = Path(src), Path(dst)
for path in src.iterdir():
if path.suffix == '.xml' and contains_drone(path):
print(f'Moving {path.as_posix()} to {dst.as_posix()}')
shutil.move(path, dst)
And in your program you call the function like this:
move_drone_files('D:\\TomProject\\Images', 'D:\\TomProject\\Images\\Done')
#or
move_drone_files(src='D:\\TomProject\\Images', dst='D:\\TomProject\\Images\\Done')
Or if you want to use the paths as the default arguments for the function, you should start the definition of the function like this:
def move_drone_files(src='D:\\TomProject\\Images', dst='D:\\TomProject\\Images\\Done'):
Check python docs (choose correct python version) of function definition and default argument values for more info: https://docs.python.org/3.10/tutorial/controlflow.html#defining-functions
|
error putting paths in the function () in python
|
im trying to run this code but I have an error when I put the path in the function the path turns grey and I have a red line under it, maybe someone can help me with that?
import shutil
from pathlib import Path
from xml.etree import ElementTree as ET
def contains_drone(path):
tree = ET.parse(path.as_posix())
root = tree.getroot()
for obj in root.findall('object'):
rank = obj.find('name').text
if rank == 'car':
return True
return False
def move_drone_files(src="D:\\TomProject\\Images\\",
dst="D:\\TomProject\\Done"):
src, dst = Path(src), Path(dst)
for path in src.iterdir():
if path.suffix == '.xml' and contains_drone(path):
print(f'Moving {path.as_posix()} to {dst.as_posix()}')
shutil.move(path, dst)
if __name__ == "__main__":
move_drone_files()
|
[
"Assuming the paths you define are your src and dst paths, your function definition should look like this, with corrected indentation and function definition:\ndef move_drone_files(src, dst):\n src, dst = Path(src), Path(dst)\n for path in src.iterdir():\n if path.suffix == '.xml' and contains_drone(path):\n print(f'Moving {path.as_posix()} to {dst.as_posix()}')\n shutil.move(path, dst)\n\nAnd in your program you call the function like this:\nmove_drone_files('D:\\\\TomProject\\\\Images', 'D:\\\\TomProject\\\\Images\\\\Done') \n#or \nmove_drone_files(src='D:\\\\TomProject\\\\Images', dst='D:\\\\TomProject\\\\Images\\\\Done') \n\nOr if you want to use the paths as the default arguments for the function, you should start the definition of the function like this:\ndef move_drone_files(src='D:\\\\TomProject\\\\Images', dst='D:\\\\TomProject\\\\Images\\\\Done'):\n\nCheck python docs (choose correct python version) of function definition and default argument values for more info: https://docs.python.org/3.10/tutorial/controlflow.html#defining-functions\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074515410_python.txt
|
Q:
Depth Estimation from Disparity Map
I'm trying estimate the depth of a point from the disparity map.
To start with, I did the stereo calibration and rectified the images, and proceeded to find the disparity map. I used the StereoSGBM in OpenCV. Since disparity refers to the distance between two corresponding points in the left and right image of a stereo pair then:
x_right = x_left + Disparity
From the calibration I obtained the extrinsic and intrinsic parameters and then computed the baseline and focal length.
Since z_cm = (baseline_cm * focal_pixels) / (disparity_pixels)
## Read image
img_left=cv.imread('images/testLeft/testL0.png')
img_right=cv.imread('images/testRight/testR0.png')
# Grayscale Images
frame_left = cv.cvtColor(img_left,cv.COLOR_BGR2GRAY)
frame_right = cv.cvtColor(img_right,cv.COLOR_BGR2GRAY)
# Undistort and rectify images
frame_left_rect = cv.remap(frame_left, stereoMapL_x, stereoMapL_y, cv.INTER_LANCZOS4, cv.BORDER_CONSTANT,0)
frame_right_rect = cv.remap(frame_right, stereoMapR_x, stereoMapR_y, cv.INTER_LANCZOS4, cv.BORDER_CONSTANT,0)
# Creating an object of StereoBM algorithm
Left_matcher = cv.StereoSGBM_create(
minDisparity=-1, numDisparities=16*3,
blockSize=5,
P1=8 * 2 * blockSize**2,
P2=32 * 2 * blockSize**2,
disp12MaxDiff=1,
uniquenessRatio=10,
speckleWindowSize=100,
speckleRange=32,
mode=cv.STEREO_SGBM_MODE_SGBM_3WAY
#===========================================================================
# Compute Disparity Map
#===========================================================================
disparity = Left_Matcher.compute(frame_left_rect, frame_right_rect)
# Convert to float32 and divide by 16 - read documentation for point cloud
disparity = np.float32(np.divide(disparity,16.0))
disp_test = cv.applyColorMap(np.uint8(disparity), cv.COLORMAP_PLASMA)
cv.imshow("Disparity Map",disp_test)
#==========================================================================
# Depth Map
#==========================================================================
depth_map = np.ones(disparity.shape)
# Focal Length - Pixels | Baseline -cm | Depth_map - cm
depth_map = focal_length * Baseline /disparity
My problem is that the depth is wrong. Can anyone help in how to use the disparity map to get to depth. I might use reprojectImageTo3D but i think i have problems in my disparity map.
A:
Check if your camera parameters fx, fy, Cx, Cy are in line with the spatial dimension of the images.
|
Depth Estimation from Disparity Map
|
I'm trying estimate the depth of a point from the disparity map.
To start with, I did the stereo calibration and rectified the images, and proceeded to find the disparity map. I used the StereoSGBM in OpenCV. Since disparity refers to the distance between two corresponding points in the left and right image of a stereo pair then:
x_right = x_left + Disparity
From the calibration I obtained the extrinsic and intrinsic parameters and then computed the baseline and focal length.
Since z_cm = (baseline_cm * focal_pixels) / (disparity_pixels)
## Read image
img_left=cv.imread('images/testLeft/testL0.png')
img_right=cv.imread('images/testRight/testR0.png')
# Grayscale Images
frame_left = cv.cvtColor(img_left,cv.COLOR_BGR2GRAY)
frame_right = cv.cvtColor(img_right,cv.COLOR_BGR2GRAY)
# Undistort and rectify images
frame_left_rect = cv.remap(frame_left, stereoMapL_x, stereoMapL_y, cv.INTER_LANCZOS4, cv.BORDER_CONSTANT,0)
frame_right_rect = cv.remap(frame_right, stereoMapR_x, stereoMapR_y, cv.INTER_LANCZOS4, cv.BORDER_CONSTANT,0)
# Creating an object of StereoBM algorithm
Left_matcher = cv.StereoSGBM_create(
minDisparity=-1, numDisparities=16*3,
blockSize=5,
P1=8 * 2 * blockSize**2,
P2=32 * 2 * blockSize**2,
disp12MaxDiff=1,
uniquenessRatio=10,
speckleWindowSize=100,
speckleRange=32,
mode=cv.STEREO_SGBM_MODE_SGBM_3WAY
#===========================================================================
# Compute Disparity Map
#===========================================================================
disparity = Left_Matcher.compute(frame_left_rect, frame_right_rect)
# Convert to float32 and divide by 16 - read documentation for point cloud
disparity = np.float32(np.divide(disparity,16.0))
disp_test = cv.applyColorMap(np.uint8(disparity), cv.COLORMAP_PLASMA)
cv.imshow("Disparity Map",disp_test)
#==========================================================================
# Depth Map
#==========================================================================
depth_map = np.ones(disparity.shape)
# Focal Length - Pixels | Baseline -cm | Depth_map - cm
depth_map = focal_length * Baseline /disparity
My problem is that the depth is wrong. Can anyone help in how to use the disparity map to get to depth. I might use reprojectImageTo3D but i think i have problems in my disparity map.
|
[
"Check if your camera parameters fx, fy, Cx, Cy are in line with the spatial dimension of the images.\n"
] |
[
0
] |
[] |
[] |
[
"depth",
"disparity_mapping",
"opencv",
"python"
] |
stackoverflow_0071134338_depth_disparity_mapping_opencv_python.txt
|
Q:
Excel data not sorting the type decimal.Decimal
I have a view where i export data the numerical data but when i sort the data it is not getting sorted as the excel is not considering the values as numerical data how can i convert them to numerical data in order to display the data in numerical format and make the sorting work.i have a function which gets the data here is how it looks.
def get_output_value(self, key, value, neutral=None):
display = value
if value is None and not user.is_active:
return '-', '-'
if value is None:
return f"${Decimal('.00')}", f"${Decimal('.00')}"
if isinstance(value, Decimal):
return f"${intcomma(value.quantize(Decimal('.00')))}",f"${intcomma(display.quantize(Decimal('.00')))}"
return value, display
def get_data(self):
data = []
for key in self.header_keys:
value = getattr(neutral, str(key), '-')
val, display = self.get_output_value(key, value, user)
values_list.append({'value': val, 'display': display})
data.append({'title': user.__str__(), 'value_row': values_list})
return data
A:
you should wrap the data in float or int class types
e.g.
def get_output_value(self, key, value, neutral=None):
display = value
if value is None and not user.is_active:
return 0, 0
if value is None:
return float(f"{Decimal('.00')}"), float(f"{Decimal('.00')}")
if isinstance(value, Decimal):
return float(f"{intcomma(value.quantize(Decimal('.00')))}"), float(f"{intcomma(display.quantize(Decimal('.00')))}")
return float(value), display
PROBABLY THE BETTER WAY:
def get_output_value(self, key, value, neutral=None):
display = value
if value is None and not user.is_active:
return 0, 0
if value is None:
return Decimal('.00'), Decimal('.00')
if isinstance(value, Decimal):
return intcomma(value.quantize(Decimal('.00'))), intcomma(display.quantize(Decimal('.00')))
return float(value), display
|
Excel data not sorting the type decimal.Decimal
|
I have a view where i export data the numerical data but when i sort the data it is not getting sorted as the excel is not considering the values as numerical data how can i convert them to numerical data in order to display the data in numerical format and make the sorting work.i have a function which gets the data here is how it looks.
def get_output_value(self, key, value, neutral=None):
display = value
if value is None and not user.is_active:
return '-', '-'
if value is None:
return f"${Decimal('.00')}", f"${Decimal('.00')}"
if isinstance(value, Decimal):
return f"${intcomma(value.quantize(Decimal('.00')))}",f"${intcomma(display.quantize(Decimal('.00')))}"
return value, display
def get_data(self):
data = []
for key in self.header_keys:
value = getattr(neutral, str(key), '-')
val, display = self.get_output_value(key, value, user)
values_list.append({'value': val, 'display': display})
data.append({'title': user.__str__(), 'value_row': values_list})
return data
|
[
"you should wrap the data in float or int class types\ne.g.\ndef get_output_value(self, key, value, neutral=None):\n display = value\n if value is None and not user.is_active:\n return 0, 0\n\n if value is None:\n return float(f\"{Decimal('.00')}\"), float(f\"{Decimal('.00')}\")\n\n if isinstance(value, Decimal):\n return float(f\"{intcomma(value.quantize(Decimal('.00')))}\"), float(f\"{intcomma(display.quantize(Decimal('.00')))}\")\n\n return float(value), display\n\nPROBABLY THE BETTER WAY:\ndef get_output_value(self, key, value, neutral=None):\n display = value\n if value is None and not user.is_active:\n return 0, 0\n\n if value is None:\n return Decimal('.00'), Decimal('.00')\n\n if isinstance(value, Decimal):\n return intcomma(value.quantize(Decimal('.00'))), intcomma(display.quantize(Decimal('.00')))\n\n return float(value), display\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"excel",
"python",
"python_3.x"
] |
stackoverflow_0074515592_django_excel_python_python_3.x.txt
|
Q:
Value returned by property method in django not getting stored in database. How to make this possible?
In my models.py file I have a property method which returns a value and I need to store that value in the database field.
`
class bug(models.Model):
......
.......
id_of_bug = models.CharField(max_length=20, blank= False, null= False)
@property
def bug_id(self):
bugid = "BUG{:03d}".format(self.pk)
self.id_of_bug = bugid
return bugid
Tried to store the value in database using self method, but not working.
A:
I would try use a property setter that updates the table value:
class bug(models.Model):
......
.......
id_of_bug = models.CharField(max_length=20, blank= False, null= False)
@property
def bug_id(self):
bugid = "BUG{:03d}".format(self.pk)
self.id_of_bug = bugid
return bugid
@bug_id.setter
def bug_id(self, value):
# value = some_transform(value)
self.id_of_bug = value
self.save(update_fields=['id_of_bug'])
A:
Try signals to store data
class bug(models.Model):
......
.......
id_of_bug = models.CharField(max_length=20, blank= False, null= False)
@property
def bug_id(self):
bugid = "BUG{:03d}".format(self.pk)
return bugid
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=bug)
def save_bugid(sender, instance,created, **kwargs):
if created:
instance.id_of_bug = instance.bug_id
instance.save()
|
Value returned by property method in django not getting stored in database. How to make this possible?
|
In my models.py file I have a property method which returns a value and I need to store that value in the database field.
`
class bug(models.Model):
......
.......
id_of_bug = models.CharField(max_length=20, blank= False, null= False)
@property
def bug_id(self):
bugid = "BUG{:03d}".format(self.pk)
self.id_of_bug = bugid
return bugid
Tried to store the value in database using self method, but not working.
|
[
"I would try use a property setter that updates the table value:\nclass bug(models.Model):\n ......\n .......\n id_of_bug = models.CharField(max_length=20, blank= False, null= False)\n \n @property\n def bug_id(self):\n bugid = \"BUG{:03d}\".format(self.pk)\n self.id_of_bug = bugid\n return bugid\n\n @bug_id.setter\n def bug_id(self, value):\n # value = some_transform(value)\n self.id_of_bug = value\n self.save(update_fields=['id_of_bug'])\n\n\n",
"Try signals to store data\nclass bug(models.Model):\n ......\n .......\n id_of_bug = models.CharField(max_length=20, blank= False, null= False)\n \n @property\n def bug_id(self):\n bugid = \"BUG{:03d}\".format(self.pk)\n return bugid\n\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\n@receiver(post_save, sender=bug)\ndef save_bugid(sender, instance,created, **kwargs):\n if created:\n instance.id_of_bug = instance.bug_id\n instance.save()\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"django_models",
"django_views",
"python"
] |
stackoverflow_0074515304_django_django_models_django_views_python.txt
|
Q:
Passing Arguments to Spyder for debugging file
I want to pass arguments in Spyder IDE with IPython to debug the file but the input arguments passing will be different
Driver.py -in "C:\Desktop\" -out "C:\Desktop\" -f 65 -f2 64
How can i pass the arguments, so that i can be able to debug the file.
A:
Go to run > configure
Tick command line options and type in the arguments in the space.
A:
I think I know what you are looking for.
For my function, I have several arguments, to pass multiple arguments on spyder to debug I pass debugfile('filePath', args='--argN1=argV1 --argN2=argV2', wdir='coreFolderPath')
|
Passing Arguments to Spyder for debugging file
|
I want to pass arguments in Spyder IDE with IPython to debug the file but the input arguments passing will be different
Driver.py -in "C:\Desktop\" -out "C:\Desktop\" -f 65 -f2 64
How can i pass the arguments, so that i can be able to debug the file.
|
[
"Go to run > configure \nTick command line options and type in the arguments in the space.\n",
"I think I know what you are looking for.\nFor my function, I have several arguments, to pass multiple arguments on spyder to debug I pass debugfile('filePath', args='--argN1=argV1 --argN2=argV2', wdir='coreFolderPath')\n"
] |
[
5,
0
] |
[] |
[] |
[
"python",
"spyder"
] |
stackoverflow_0053628850_python_spyder.txt
|
Q:
pandas.json_normalize sending Not Implemented Error
I have below line in my data pipeline code which takes json array and normalizes it using pandas.json_normalize
df = pd.json_normalize(reviews, sep='_')
Now when reviews is getting null or None, it has suddenly started failing. What should be done here?
I tried writing all the data that review receives in a for loop, and from that I understood, this failure occurs only when review receives null
A:
Which version of pandas are you using?
If you get the error AttributeError: module 'pandas' has oo attribute 'json_normalize' after inserting from pandas import json_normalize it may be due to the version you are using.
You have to downgrade the pandas to the version before 1.0.3. Since you need to import the json_normalize module from the pandas package directly into newer versions from pandas, import json_normalize instead.
After that you can try out something like:
from pandas.io.json import json_normalize
data = { "xy": ["1","2","3"] }
json = json_normalize(data)
|
pandas.json_normalize sending Not Implemented Error
|
I have below line in my data pipeline code which takes json array and normalizes it using pandas.json_normalize
df = pd.json_normalize(reviews, sep='_')
Now when reviews is getting null or None, it has suddenly started failing. What should be done here?
I tried writing all the data that review receives in a for loop, and from that I understood, this failure occurs only when review receives null
|
[
"Which version of pandas are you using?\nIf you get the error AttributeError: module 'pandas' has oo attribute 'json_normalize' after inserting from pandas import json_normalize it may be due to the version you are using.\nYou have to downgrade the pandas to the version before 1.0.3. Since you need to import the json_normalize module from the pandas package directly into newer versions from pandas, import json_normalize instead.\nAfter that you can try out something like:\nfrom pandas.io.json import json_normalize\ndata = { \"xy\": [\"1\",\"2\",\"3\"] }\njson = json_normalize(data)\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"json_normalize",
"pandas",
"python"
] |
stackoverflow_0074515659_dataframe_json_normalize_pandas_python.txt
|
Q:
Changing metadata when uploading file to s3 with python
I have an html file that I am uploading to s3 using python. For some reason, s3 adds a system defined metadata saying that the file Content-Type is "binary/octet-stream":
I need to change this value to "text/html". I can do it manually, but I want it to be done automatically when I upload the file.
I tried the following code:
metadata = {
"Content-Type": "text/html"
}
s3_file_key = str(Path("index.html"))
local_file_path = Path("~", "index.html").expanduser()
s3 = session.resource("s3")
bucket = s3.Bucket(bucket_name)
with open(local_file_path, READ_BINARY) as local_file:
bucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata)
but the result was that the file had 2 metadata keys:
I couldn't find any documentation about how to change a system defined metadata.
Thanks for the help
A:
Use MetadataDirective parameter:
bucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata, MetadataDirective='REPLACE')
MetadataDirective -- Specifies whether the metadata is copied from the source object or replaced with metadata provided in the request ('COPY' | 'REPLACE').
S3 - Boto3 Docs
A:
I was also having a similar problem and I found out you need to use the ContentType parameter for the put_object function.
bucket.put_object(Key=s3_file_key, Body=local_file, ContentType='text/html')
|
Changing metadata when uploading file to s3 with python
|
I have an html file that I am uploading to s3 using python. For some reason, s3 adds a system defined metadata saying that the file Content-Type is "binary/octet-stream":
I need to change this value to "text/html". I can do it manually, but I want it to be done automatically when I upload the file.
I tried the following code:
metadata = {
"Content-Type": "text/html"
}
s3_file_key = str(Path("index.html"))
local_file_path = Path("~", "index.html").expanduser()
s3 = session.resource("s3")
bucket = s3.Bucket(bucket_name)
with open(local_file_path, READ_BINARY) as local_file:
bucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata)
but the result was that the file had 2 metadata keys:
I couldn't find any documentation about how to change a system defined metadata.
Thanks for the help
|
[
"Use MetadataDirective parameter:\nbucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata, MetadataDirective='REPLACE')\n\nMetadataDirective -- Specifies whether the metadata is copied from the source object or replaced with metadata provided in the request ('COPY' | 'REPLACE').\nS3 - Boto3 Docs\n",
"I was also having a similar problem and I found out you need to use the ContentType parameter for the put_object function.\nbucket.put_object(Key=s3_file_key, Body=local_file, ContentType='text/html')\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"amazon_s3",
"bots",
"python",
"python_3.x"
] |
stackoverflow_0064911004_amazon_s3_bots_python_python_3.x.txt
|
Q:
Is there a prefab python function out there that turns only integer floats into ints?
I would like to turn float integers (123.0) into ints (123).
What I would like the function to do:
Input: 2.1
Output: Exception, cannot turn float into int
Input: 2.0
Output: 2
Using int() on a float seems to just be math.floor() and that is not what I'm looking for.
A:
You can check if after you use int() it the same value as the float
def convert(num):
if num == int(num):
return int(num)
raise Exception('Cannot turn float into int')
As a side note, using int() is not exactly as using math.floor(), try with negative numbers. What is the difference between int() and floor() in Python 3?
A:
I don't know of a built-in that does it directly, but it is easy to create your own function. You can use .is_integer() on the input-value to check if the float is directly castable to int:
def strict_int(value):
if value.is_integer():
return int(value)
raise ValueError("cannot turn uneven float into int")
print(strict_int(3.0))
print(strict_int(3.1))
Output:
3
...
ValueError: cannot turn uneven float into int
But be warned, that there may be some unexpected behavior resulting from the way floats are represented. Try this for example:
print(strict_int(0.3 + 0.3 + 0.3 + 0.1))
This "1.0" will fail when trying to strictly convert to an int as it is in fact 0.9999999999999999! If you use the standard int it will work in that it gives you a result, but the result for int(0.3 + 0.3 + 0.3 + 0.1) is 0, probably not what you'd expect. But this is a general issue with how floats are represented and not directly related to the used methods. So you'll encounter this anywhere floats are present.
Here is an interesting post that goes a bit more into detail about the potential issues.
A:
I guess i would just do
def convert(n):
return int(f"{n:g}")
|
Is there a prefab python function out there that turns only integer floats into ints?
|
I would like to turn float integers (123.0) into ints (123).
What I would like the function to do:
Input: 2.1
Output: Exception, cannot turn float into int
Input: 2.0
Output: 2
Using int() on a float seems to just be math.floor() and that is not what I'm looking for.
|
[
"You can check if after you use int() it the same value as the float\ndef convert(num):\n if num == int(num):\n return int(num)\n raise Exception('Cannot turn float into int')\n\nAs a side note, using int() is not exactly as using math.floor(), try with negative numbers. What is the difference between int() and floor() in Python 3?\n",
"I don't know of a built-in that does it directly, but it is easy to create your own function. You can use .is_integer() on the input-value to check if the float is directly castable to int:\ndef strict_int(value):\n if value.is_integer():\n return int(value)\n raise ValueError(\"cannot turn uneven float into int\")\n\n\nprint(strict_int(3.0))\nprint(strict_int(3.1))\n\nOutput:\n3\n...\nValueError: cannot turn uneven float into int\n\n\nBut be warned, that there may be some unexpected behavior resulting from the way floats are represented. Try this for example:\nprint(strict_int(0.3 + 0.3 + 0.3 + 0.1))\n\nThis \"1.0\" will fail when trying to strictly convert to an int as it is in fact 0.9999999999999999! If you use the standard int it will work in that it gives you a result, but the result for int(0.3 + 0.3 + 0.3 + 0.1) is 0, probably not what you'd expect. But this is a general issue with how floats are represented and not directly related to the used methods. So you'll encounter this anywhere floats are present.\nHere is an interesting post that goes a bit more into detail about the potential issues.\n",
"I guess i would just do\ndef convert(n):\n return int(f\"{n:g}\")\n\n"
] |
[
3,
3,
2
] |
[] |
[] |
[
"floating_point",
"python",
"python_3.x"
] |
stackoverflow_0074515645_floating_point_python_python_3.x.txt
|
Q:
Sending email with Sendgrid using data from a csv
I am trying to send out an email using Sendgrid and adding data from a csv into the body of the email. I can do this process with smtplib but now I need to do it using sendgrid.
import os
import pandas as pd
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
db = pd.read_csv('changes.csv', delimiter = ",", skiprows=6)
db["Email"] = "add@test.com"
db = db.drop_duplicates(subset = ["Employee Name"], keep = "first")
field1 = db["Field Desc"] == "Status"
field2 = db["Field Desc"] == "Default Cost Center 10 (Job)"
message = Mail(
from_email='test@test.com',
to_emails='test@test.com',
subject='{Employee} -- Kronos Change',
html_content='''\
We have received the change for {Employee}.
Title: {Title}
Old: {Old}
New: {New}
Profit Center: {PC}
Supervisor: {Supervisor}
''')
message.content = Content("text","changes.csv")
try:
sg=SendGridAPIClient(os.environ.get('API KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
I am not sure if message.content is the correct to call to read from a csv file. Some of this code is what worked for me when I used smtplib.
A:
Use following two functions:
def read_csv_for_email(final_path=None):
""" send_csv_email
Send final generated CSV file
:return:
"""
final_path = "sample/path/to.csv"
df = pd.read_csv(final_path, dtype=str, na_filter=True, index_col=False)
res = send_email_with_csv(
subject="Sending CSV with SendGrid is Fun",
content="<strong>CSV with Python</strong>",
dataframe=df,
filename=f"Any_Sample.csv",
filetype="text/csv",
)
return res
def send_email_with_csv(subject, content, dataframe, filename, filetype):
""" send_email_with_csv
:param subject:
:param content:
:param dataframe:
:param filename:
:param filetype:
:return:
"""
csv_message = Mail(
from_email=f"test+{MAIL_DOMAIN}",
to_emails="sample.email@gmail.com",
subject=subject,
html_content=content,
)
# Create buffered csv
buffer = BytesIO()
dataframe.to_csv(buffer)
buffer.seek(0)
data = buffer.read()
encoded = base64.b64encode(data).decode()
# Set as csv attachement
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType(filetype)
attachment.file_name = FileName(filename)
attachment.disposition = Disposition("attachment")
csv_message.attachment = attachment
try:
sendgrid_client = SendGridAPIClient(SENDGRID_API_KEY)
response = sendgrid_client.send(csv_message)
logger.info(response.status_code)
logger.info(response.body)
logger.info(response.headers)
return "CSV sent successfully"
except Exception as e:
logger.error(str(e))
Call function read_csv_email(csv_path)
|
Sending email with Sendgrid using data from a csv
|
I am trying to send out an email using Sendgrid and adding data from a csv into the body of the email. I can do this process with smtplib but now I need to do it using sendgrid.
import os
import pandas as pd
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
db = pd.read_csv('changes.csv', delimiter = ",", skiprows=6)
db["Email"] = "add@test.com"
db = db.drop_duplicates(subset = ["Employee Name"], keep = "first")
field1 = db["Field Desc"] == "Status"
field2 = db["Field Desc"] == "Default Cost Center 10 (Job)"
message = Mail(
from_email='test@test.com',
to_emails='test@test.com',
subject='{Employee} -- Kronos Change',
html_content='''\
We have received the change for {Employee}.
Title: {Title}
Old: {Old}
New: {New}
Profit Center: {PC}
Supervisor: {Supervisor}
''')
message.content = Content("text","changes.csv")
try:
sg=SendGridAPIClient(os.environ.get('API KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
I am not sure if message.content is the correct to call to read from a csv file. Some of this code is what worked for me when I used smtplib.
|
[
"Use following two functions:\n def read_csv_for_email(final_path=None):\n \"\"\" send_csv_email\n Send final generated CSV file\n :return:\n \"\"\"\n final_path = \"sample/path/to.csv\"\n df = pd.read_csv(final_path, dtype=str, na_filter=True, index_col=False)\n res = send_email_with_csv(\n subject=\"Sending CSV with SendGrid is Fun\",\n content=\"<strong>CSV with Python</strong>\",\n dataframe=df,\n filename=f\"Any_Sample.csv\",\n filetype=\"text/csv\",\n )\n return res\n\ndef send_email_with_csv(subject, content, dataframe, filename, filetype):\n \"\"\" send_email_with_csv\n :param subject:\n :param content:\n :param dataframe:\n :param filename:\n :param filetype:\n :return:\n \"\"\"\n csv_message = Mail(\n from_email=f\"test+{MAIL_DOMAIN}\",\n to_emails=\"sample.email@gmail.com\",\n subject=subject,\n html_content=content,\n )\n\n # Create buffered csv\n buffer = BytesIO()\n dataframe.to_csv(buffer)\n buffer.seek(0)\n data = buffer.read()\n encoded = base64.b64encode(data).decode()\n # Set as csv attachement\n attachment = Attachment()\n attachment.file_content = FileContent(encoded)\n attachment.file_type = FileType(filetype)\n attachment.file_name = FileName(filename)\n attachment.disposition = Disposition(\"attachment\")\n csv_message.attachment = attachment\n try:\n sendgrid_client = SendGridAPIClient(SENDGRID_API_KEY)\n response = sendgrid_client.send(csv_message)\n logger.info(response.status_code)\n logger.info(response.body)\n logger.info(response.headers)\n return \"CSV sent successfully\"\n except Exception as e:\n logger.error(str(e))\n\nCall function read_csv_email(csv_path)\n"
] |
[
0
] |
[] |
[] |
[
"csv",
"python",
"sendgrid"
] |
stackoverflow_0060011210_csv_python_sendgrid.txt
|
Q:
Groupby/aggregation shows groups which were supposed to be filtered out before
I have a pandas DataFrame with a column Size, on which I filter first and then group by and count records per group. The result contains also rows for the groups which were filtered out before, but with a count of 0:
(
df[df["Size"].isin(("XXS", "XS", "S", "M", "L", "XL", "XXL"))]
.groupby("Size")
.agg(
count=("OID", "count"),
)
.sort_values("count", ascending=False)
)
The result DataFrame is shown in the figure below. In my understanding of the groupby function, the groups which were filtered out (I double checked, they are really not anymore in the dataframe) should no longer occur in the aggregated dataframe. Even copying and resetting the index before grouping by does not change the output.
Unfortunately, I was not able to reproduce the issue with a simple example dataframe, so I assume that there is something strange happening. Does anybody have an idea why this could happen?
Result dataframe:
A:
Sometimes it helps to wait a weekend and think about on Monday again:
The behavior occurred due to categorical datatype of Size column:
>>> df.dtypes
Size category
...
>>> df["Size"].unique()
['S', 'M', 'L', 'XL', 'XXL', 'XS', 'XXS']
Categories (80, object): ['100 CM', '105 CM', '24', '25', ..., 'XS/S', 'XXL', 'XXS', 'XXS/XS']
|
Groupby/aggregation shows groups which were supposed to be filtered out before
|
I have a pandas DataFrame with a column Size, on which I filter first and then group by and count records per group. The result contains also rows for the groups which were filtered out before, but with a count of 0:
(
df[df["Size"].isin(("XXS", "XS", "S", "M", "L", "XL", "XXL"))]
.groupby("Size")
.agg(
count=("OID", "count"),
)
.sort_values("count", ascending=False)
)
The result DataFrame is shown in the figure below. In my understanding of the groupby function, the groups which were filtered out (I double checked, they are really not anymore in the dataframe) should no longer occur in the aggregated dataframe. Even copying and resetting the index before grouping by does not change the output.
Unfortunately, I was not able to reproduce the issue with a simple example dataframe, so I assume that there is something strange happening. Does anybody have an idea why this could happen?
Result dataframe:
|
[
"Sometimes it helps to wait a weekend and think about on Monday again:\nThe behavior occurred due to categorical datatype of Size column:\n>>> df.dtypes\n\nSize category\n...\n\n>>> df[\"Size\"].unique()\n\n['S', 'M', 'L', 'XL', 'XXL', 'XS', 'XXS']\nCategories (80, object): ['100 CM', '105 CM', '24', '25', ..., 'XS/S', 'XXL', 'XXS', 'XXS/XS']\n\n"
] |
[
1
] |
[
"df[df[\"Size\"].isin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])]\n .groupby(\"Size\")\n .agg(\n count=(\"OID\", \"count\"),\n )\n .sort_values(\"count\", ascending=False)\n\n====================================================\nisin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])\n\n"
] |
[
-3
] |
[
"group_by",
"pandas",
"python"
] |
stackoverflow_0074491161_group_by_pandas_python.txt
|
Q:
I tried to created dictionary in dictionary but I struggled
I tried to created a get_dict function that takes a parameter as a filename and then creates and returns a dictionary which contains
key is the number of the product code and has
value is a dictionary that contains
key is a string of sizes (S, M, L, or XL), and
value is the number of the product.
enter image description here
I tried this.
def get_dict(file_name):
d={}
e={}
with open(file_name) as f:
for line in f:
line = line.strip()
alist = line.split()
e[alist[1]] = alist[2]
d[alist[0]] = e
print (d)
the output is look like this
{'4125': {'M': '4', 'L': '7', 'XL': '3'}, '5645': {'M': '4', 'L': '7', 'XL': '3'}, '7845': {'M': '4', 'L': '7', 'XL': '3'}}
but I expect that output will be like this
{4125: {'S': 1, 'M': 4}, 5645: {'L': 7}, 9874: {'S': 8}, 9875: {'M': 8}, 7845: {'S': 10, 'XL': 3}}
Text file example
7845 XL 3
4125 S 1
5645 L 7
9874 S 3
4125 M 4
A:
def get_dict(file_name):
d={}
with open(file_name) as f:
for line in f:
line = line.strip()
alist = line.split()
if not alist[0] in d:
d[alist[0]] = {alist[1]: alist[2]}
else:
d[alist[0]].update({alist[1]: alist[2]})
print(d)
You have to update the dictionary instead of overwriting the same key value. The above solution should work.
Output -
{'7845': {'XL': '3'}, '4125': {'S': '1', 'M': '4'}, '5645': {'L': '7'}, '9874': {'S': '3'}}
|
I tried to created dictionary in dictionary but I struggled
|
I tried to created a get_dict function that takes a parameter as a filename and then creates and returns a dictionary which contains
key is the number of the product code and has
value is a dictionary that contains
key is a string of sizes (S, M, L, or XL), and
value is the number of the product.
enter image description here
I tried this.
def get_dict(file_name):
d={}
e={}
with open(file_name) as f:
for line in f:
line = line.strip()
alist = line.split()
e[alist[1]] = alist[2]
d[alist[0]] = e
print (d)
the output is look like this
{'4125': {'M': '4', 'L': '7', 'XL': '3'}, '5645': {'M': '4', 'L': '7', 'XL': '3'}, '7845': {'M': '4', 'L': '7', 'XL': '3'}}
but I expect that output will be like this
{4125: {'S': 1, 'M': 4}, 5645: {'L': 7}, 9874: {'S': 8}, 9875: {'M': 8}, 7845: {'S': 10, 'XL': 3}}
Text file example
7845 XL 3
4125 S 1
5645 L 7
9874 S 3
4125 M 4
|
[
"def get_dict(file_name): \n\nd={}\nwith open(file_name) as f:\n for line in f:\n line = line.strip()\n alist = line.split()\n if not alist[0] in d:\n d[alist[0]] = {alist[1]: alist[2]}\n else:\n d[alist[0]].update({alist[1]: alist[2]})\nprint(d)\n\nYou have to update the dictionary instead of overwriting the same key value. The above solution should work.\nOutput -\n{'7845': {'XL': '3'}, '4125': {'S': '1', 'M': '4'}, '5645': {'L': '7'}, '9874': {'S': '3'}}\n\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074515569_python.txt
|
Q:
What is the logical error for this Python program to generate all possible unique ways to represent n=3 as sum of positive integers?
Python program to generate all possible unique ways to represent n=3 as sum of positive integers:
def fun():
res=[]
a=[]
def backtracking(n):
if(n==0):
res.append(a)
print(res)
return
if(n<0):
return
for i in range(1,n+1):
a.append(i)
backtracking(n-i)
a.pop()
backtracking(3)
return res
print(fun())
Expecting res = [[1,1,1][1,2][2,1][3]] instead getting [ [] [] [] [] ]
A:
You are appending the list a directly to the res, you should be appending a copy of the list a instead. List is passed by reference, so in the end, your res has 4 references to the same list which is empty. To get a copy of the list you have different options - list.copy() , copy.copy() method, or just slicing list[:]
def fun():
res=[]
a=[]
def backtracking(n):
if(n==0):
res.append(a.copy()) # updated
# print(res)
return
if(n<0):
return
for i in range(1,n+1):
a.append(i)
backtracking(n-i)
a.pop()
backtracking(3)
return res
print(fun())
Output:
[[1, 1, 1], [1, 2], [2, 1], [3]]
|
What is the logical error for this Python program to generate all possible unique ways to represent n=3 as sum of positive integers?
|
Python program to generate all possible unique ways to represent n=3 as sum of positive integers:
def fun():
res=[]
a=[]
def backtracking(n):
if(n==0):
res.append(a)
print(res)
return
if(n<0):
return
for i in range(1,n+1):
a.append(i)
backtracking(n-i)
a.pop()
backtracking(3)
return res
print(fun())
Expecting res = [[1,1,1][1,2][2,1][3]] instead getting [ [] [] [] [] ]
|
[
"You are appending the list a directly to the res, you should be appending a copy of the list a instead. List is passed by reference, so in the end, your res has 4 references to the same list which is empty. To get a copy of the list you have different options - list.copy() , copy.copy() method, or just slicing list[:]\ndef fun():\n res=[]\n a=[]\n def backtracking(n):\n if(n==0):\n res.append(a.copy()) # updated\n # print(res)\n return\n if(n<0):\n return\n for i in range(1,n+1):\n a.append(i)\n backtracking(n-i)\n a.pop()\n backtracking(3)\n return res\n\nprint(fun())\n\nOutput:\n[[1, 1, 1], [1, 2], [2, 1], [3]]\n\n"
] |
[
0
] |
[] |
[] |
[
"dynamic_programming",
"python",
"recursive_backtracking"
] |
stackoverflow_0074515786_dynamic_programming_python_recursive_backtracking.txt
|
Q:
How can I set the time zone in Dockerfile using gliderlabs/alpine:3.3
My Dockerfile is:
FROM gliderlabs/alpine:3.3
RUN set -x \
&& buildDeps='\
python-dev \
py-pip \
build-base \
' \
&& apk --update add python py-lxml py-mysqldb $buildDeps \
&& rm -rf /var/cache/apk/* \
&& mkdir -p /app
ENV INSTALL_PATH /app
ENV TZ=Asia/Shanghai
WORKDIR $INSTALL_PATH
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY requirements-docker.txt ./
RUN pip install -r requirements-docker.txt
COPY . .
RUN apk del --purge $buildDeps
ENTRYPOINT ["celery", "-A", "tasks", "worker", "-l", "info", "-B"]
I setted the timezone as Asia/Shanghai, but it did not work and gave me the UTC which had 8 hours deviation, the result is :
2016-01-24 11:25:07:[2016-01-24 03:25:07,893: WARNING/Worker-2] 2016-01-24 03:25:07.892718
2016-01-24 11:25:08:[2016-01-24 03:25:08,339: INFO/MainProcess] Task tasks.crawl[98c9a9fc-0817-45cb-a2fc-40320d63c41a] succeeded in 0.447403368002s: None
2016-01-24 11:27:07:[2016-01-24 03:27:07,884: INFO/Beat] Scheduler: Sending due task spider (tasks.crawl)
Then I tried other methods like:
RUN echo "Asia/Shanghai" > /etc/timezone && dpkg-reconfigure -f noninteractive tzdata
and
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
none of them did work, how can set the timezone? Thanks very much.
A:
The usual workaround is to mount /etc/localtime, as in issue 3359
$ docker run --rm busybox date
Thu Mar 20 04:42:02 UTC 2014
$ docker run --rm -v /etc/localtime:/etc/localtime:ro busybox date
Thu Mar 20 14:42:20 EST 2014
$ FILE=$(mktemp) ; echo $FILE ; echo -e "Europe/Brussels" > $FILE ; docker run --rm -v $FILE:/etc/timezone -v /usr/share/zoneinfo/Europe/Brussels:/etc/localtime:ro busybox date
/tmp/tmp.JwL2A9c50i
Thu Mar 20 05:42:26 CET 2014
The same thread mentions (for ubuntu-based image though), but you already tried it.
RUN echo Europe/Berlin > /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata
(And I referred before to a similar solution)
Another option would be to build your own gliderlabs/docker-alpine image with builder/scripts/mkimage-alpine.bash.
That script allows you to set a timezone.
[[ "$TIMEZONE" ]] && \
cp "/usr/share/zoneinfo/$TIMEZONE" "$rootfs/etc/localtime"
You can see that image builder script used in Digital Ocean: Alpine Linux:
Generate Alpine root file system
Ensure Docker is running locally.
Download and unzip gliderlabs/docker-alpine.
wget -O docker-alpine-master.zip https://github.com/gliderlabs/docker-alpine/archive/master.zip
unzip docker-alpine-master.zip
Build the builder (export the right timezone first).
export TIMEZONE=xxx
docker build -t docker-alpine-builder docker-alpine-master/builder/
Build the root file system (change v3.3 to the Alpine version you want to build).
docker run --name alpine-builder docker-alpine-builder -r v3.4
Copy the root file system from the container.
docker cp alpine-builder:/rootfs.tar.gz .
Once you have the rootfs.tar.gz on your own filesystem, you can use it (as mentioned here) to build your own Alpine image, with the following Dockerfile:
FROM SCRATCH
ADD rootfs.tar.gz /
Once built, you can use that Alpine image with the right timezone.
A:
//dockerfile
RUN apk update && apk add tzdata \
&& cp -r -f /usr/share/zoneinfo/YOUR_TIMEZONE /etc/localtime
A:
I‘m running my Docker on Mac Mojave,
In Dockerfile, I added the following after many failed tries:
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone && \
apt-get install tzdata && \
dpkg-reconfigure --frontend noninteractive tzdata
And it's working fine.
A:
To Set timezone in Dockerfile you can use those lines
ENV TZ=Africa/Douala
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
How can I set the time zone in Dockerfile using gliderlabs/alpine:3.3
|
My Dockerfile is:
FROM gliderlabs/alpine:3.3
RUN set -x \
&& buildDeps='\
python-dev \
py-pip \
build-base \
' \
&& apk --update add python py-lxml py-mysqldb $buildDeps \
&& rm -rf /var/cache/apk/* \
&& mkdir -p /app
ENV INSTALL_PATH /app
ENV TZ=Asia/Shanghai
WORKDIR $INSTALL_PATH
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY requirements-docker.txt ./
RUN pip install -r requirements-docker.txt
COPY . .
RUN apk del --purge $buildDeps
ENTRYPOINT ["celery", "-A", "tasks", "worker", "-l", "info", "-B"]
I setted the timezone as Asia/Shanghai, but it did not work and gave me the UTC which had 8 hours deviation, the result is :
2016-01-24 11:25:07:[2016-01-24 03:25:07,893: WARNING/Worker-2] 2016-01-24 03:25:07.892718
2016-01-24 11:25:08:[2016-01-24 03:25:08,339: INFO/MainProcess] Task tasks.crawl[98c9a9fc-0817-45cb-a2fc-40320d63c41a] succeeded in 0.447403368002s: None
2016-01-24 11:27:07:[2016-01-24 03:27:07,884: INFO/Beat] Scheduler: Sending due task spider (tasks.crawl)
Then I tried other methods like:
RUN echo "Asia/Shanghai" > /etc/timezone && dpkg-reconfigure -f noninteractive tzdata
and
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
none of them did work, how can set the timezone? Thanks very much.
|
[
"The usual workaround is to mount /etc/localtime, as in issue 3359\n$ docker run --rm busybox date\nThu Mar 20 04:42:02 UTC 2014\n$ docker run --rm -v /etc/localtime:/etc/localtime:ro busybox date\nThu Mar 20 14:42:20 EST 2014\n$ FILE=$(mktemp) ; echo $FILE ; echo -e \"Europe/Brussels\" > $FILE ; docker run --rm -v $FILE:/etc/timezone -v /usr/share/zoneinfo/Europe/Brussels:/etc/localtime:ro busybox date\n/tmp/tmp.JwL2A9c50i \nThu Mar 20 05:42:26 CET 2014\n\nThe same thread mentions (for ubuntu-based image though), but you already tried it.\nRUN echo Europe/Berlin > /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata\n\n(And I referred before to a similar solution) \n\nAnother option would be to build your own gliderlabs/docker-alpine image with builder/scripts/mkimage-alpine.bash.\nThat script allows you to set a timezone.\n [[ \"$TIMEZONE\" ]] && \\\n cp \"/usr/share/zoneinfo/$TIMEZONE\" \"$rootfs/etc/localtime\"\n\nYou can see that image builder script used in Digital Ocean: Alpine Linux:\n\nGenerate Alpine root file system\n\n\nEnsure Docker is running locally.\nDownload and unzip gliderlabs/docker-alpine.\nwget -O docker-alpine-master.zip https://github.com/gliderlabs/docker-alpine/archive/master.zip\nunzip docker-alpine-master.zip\n\nBuild the builder (export the right timezone first).\nexport TIMEZONE=xxx\ndocker build -t docker-alpine-builder docker-alpine-master/builder/\n\nBuild the root file system (change v3.3 to the Alpine version you want to build).\ndocker run --name alpine-builder docker-alpine-builder -r v3.4\n\nCopy the root file system from the container.\ndocker cp alpine-builder:/rootfs.tar.gz .\n\n\nOnce you have the rootfs.tar.gz on your own filesystem, you can use it (as mentioned here) to build your own Alpine image, with the following Dockerfile:\nFROM SCRATCH\nADD rootfs.tar.gz /\n\nOnce built, you can use that Alpine image with the right timezone.\n",
"//dockerfile\nRUN apk update && apk add tzdata \\\n && cp -r -f /usr/share/zoneinfo/YOUR_TIMEZONE /etc/localtime\n\n",
"I‘m running my Docker on Mac Mojave,\nIn Dockerfile, I added the following after many failed tries: \nENV TZ=Asia/Shanghai\nRUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone && \\\n apt-get install tzdata && \\\n dpkg-reconfigure --frontend noninteractive tzdata \nAnd it's working fine.\n",
"To Set timezone in Dockerfile you can use those lines\nENV TZ=Africa/Douala\nRUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone\n\n"
] |
[
7,
6,
0,
0
] |
[] |
[] |
[
"docker",
"dockerfile",
"python"
] |
stackoverflow_0034972521_docker_dockerfile_python.txt
|
Q:
Return integer or string instead of None from a JMESPath query
Is there a way to return an integer or a string instead of None?
I know that I can do an additional check like:
item = {"SX": {"BX": 1}}
value = jmespath.search("SX.BX", item) if jmespath.search("SX.BX", item) else 0
but the condition is very long and I would like to make it easier.
A:
You can build that logic in your JMESPath query:
SX.BX || `0`
Given the empty JSON:
{}
Would yield you 0, as you are excepting it.
So, you Python code becomes:
value = jmespath.search("SX.BX || `0`", item)
|
Return integer or string instead of None from a JMESPath query
|
Is there a way to return an integer or a string instead of None?
I know that I can do an additional check like:
item = {"SX": {"BX": 1}}
value = jmespath.search("SX.BX", item) if jmespath.search("SX.BX", item) else 0
but the condition is very long and I would like to make it easier.
|
[
"You can build that logic in your JMESPath query:\nSX.BX || `0`\n\nGiven the empty JSON:\n{}\n\nWould yield you 0, as you are excepting it.\n\nSo, you Python code becomes:\nvalue = jmespath.search(\"SX.BX || `0`\", item)\n\n"
] |
[
1
] |
[] |
[] |
[
"jmespath",
"python"
] |
stackoverflow_0074514745_jmespath_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.