QuestionId int64 74.8M 79.8M | UserId int64 56 29.4M | QuestionTitle stringlengths 15 150 | QuestionBody stringlengths 40 40.3k | Tags stringlengths 8 101 | CreationDate stringdate 2022-12-10 09:42:47 2025-11-01 19:08:18 | AnswerCount int64 0 44 | UserExpertiseLevel int64 301 888k | UserDisplayName stringlengths 3 30 ⌀ |
|---|---|---|---|---|---|---|---|---|
77,009,197 | 5,470,144 | QSortFilterProxyModel - not updating | <p>I am trying to use <code>QTableView</code> with a custom model and <code>QSortFilterProxyModel</code>.</p>
<p>If I set the base model: <code>self.setModel(self._model)</code> the table displays correctly.</p>
<p>However, if I set the proxy model: <code>self.setModel(self._proxy_model)</code> no rows are displayed.</p>
<p>Not sure why. The docs <a href="https://doc.qt.io/qtforpython-5/PySide2/QtCore/QSortFilterProxyModel.html" rel="nofollow noreferrer">https://doc.qt.io/qtforpython-5/PySide2/QtCore/QSortFilterProxyModel.html</a> does not give a clue... Nor in general is it possible to find reasonable PyQt resources or examples on the internet.</p>
<p><strong>My code below (python3.9, PyQt5, Windows):</strong></p>
<pre><code>import sys
import typing
from PyQt5.QtCore import QModelIndex, Qt, QSortFilterProxyModel, QAbstractTableModel
from PyQt5.QtWidgets import QTableView, QWidget, QApplication
from typing import Any, List, Dict, Optional, Iterable, Tuple, Union
KeyType = Tuple[Any, ...]
class KeyedTableModel(QAbstractTableModel):
"""Keyed table model."""
def __init__(self, headers: Iterable[str], key_columns: Union[int, Iterable[int]]) -> None:
"""Initialize the class."""
super().__init__()
self._headers = list(headers)
self._key_columns = [key_columns] if isinstance(key_columns, int) else list(key_columns)
self._key_to_row_idx: Dict[KeyType, int] = {}
self._data: List[List[Any]] = []
def _get_row_key(self, row: List[str]) -> KeyType:
return tuple(row[c] for c in self._key_columns)
def columnCount(self, parent: QModelIndex = ...) -> int:
# The length of our headers.
return len(self._headers)
def rowCount(self, parent: QModelIndex = ...) -> int:
return len(self._data)
def insertRow(self, row: int, parent: QModelIndex = ...) -> bool:
self._data.insert(row, [None] * self.columnCount())
return True
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Any:
"""Get cell data."""
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def setData(self, index: QModelIndex, value: typing.Any, role: int = Qt.DisplayRole) -> bool:
"""Set cell data."""
if role == Qt.DisplayRole:
self._data[index.row()][index.column()] = value
return True
def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.DisplayRole) -> Any:
"""Get header data."""
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._headers[section])
if orientation == Qt.Vertical:
return str(section)
def add_or_update(self, rows: Union[Iterable[List[Any]], List[Any]]) -> None:
"""Add or update row in the model."""
if isinstance(rows, List) and rows and not isinstance(rows[0], List):
rows = [rows]
min_row_idx, max_row_idx = sys.maxsize, -sys.maxsize
for row in rows:
key = self._get_row_key(row)
row_idx = self._key_to_row_idx.get(key)
if row_idx is None:
row_idx = self.rowCount()
self.insertRow(row_idx)
self._key_to_row_idx[key] = row_idx
for c, val in enumerate(row):
self.setData(self.index(row_idx, c), val)
min_row_idx = min(min_row_idx, row_idx)
max_row_idx = max(max_row_idx, row_idx)
top_left = self.index(min_row_idx, 0)
bot_right = self.index(max_row_idx, self.columnCount() - 1)
self.dataChanged.emit(top_left, bot_right)
class TableWidgetPlus2(QTableView):
def __init__(self, headers: Iterable[str],
key_columns: Union[int, Iterable[int]],
parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self._model = KeyedTableModel(headers, key_columns)
self._proxy_model = QSortFilterProxyModel(self)
self._proxy_model.setSourceModel(self._model)
self.setModel(self._proxy_model)
def add_or_update(self, rows: Union[Iterable[List[Any]], List[Any]]) -> None:
"""Add or update row."""
self._model.add_or_update(rows)
self.repaint()
def table_widget_plus_2_demo_main() -> int:
"""Simulation main function."""
app = QApplication(sys.argv)
win = TableWidgetPlus2(['ID', 'Action', 'Repeat'], [0])
win.add_or_update(['A1', 'walk', 100])
win.add_or_update(['A1', 'stop', 200])
win.resize(1000, 500)
win.showMaximized()
res = app.exec_()
return res
if __name__ == '__main__':
table_widget_plus_2_demo_main()
</code></pre>
| <python><pyqt><pyqt5><qtableview><qabstracttablemodel> | 2023-08-30 14:58:20 | 0 | 4,082 | Elad Weiss |
77,009,176 | 1,583,083 | Pandas: ValueError parsing UNIX timestamp | <p>I have a CSV of OHLC data that is indexed by seconds since the epoch:
<a href="https://i.sstatic.net/iHUx1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iHUx1.png" alt="tabulated CSV data" /></a></p>
<p>I am parsing it thus:</p>
<pre><code>df = pd.read_csv(f"{CSV}/{filename}", sep=",", header=0, index_col=0, parse_dates=['time'], date_format='s')
</code></pre>
<p>However the timestamps are not being parsed to dates:</p>
<pre><code>df.index
Index([ 378943200, 379548000, 380152800, 380757600, 381362400, 381967200,
382572000, 383176800, 383781600, 384386400,
...
1687726800, 1688331600, 1688936400, 1689541200, 1690146000, 1690750800,
1691355600, 1691960400, 1692565200, 1693170000],
dtype='int64', name='time', length=2172)
</code></pre>
<p>Furthermore, if I manually try to convert the index to datetime, I get a ValueError:</p>
<pre><code>pd.to_datetime(df.index, format='s', utc=True)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[71], line 1
----> 1 pd.to_datetime(df.index, format='s', utc=True)
...
ValueError: time data "378943200" doesn't match format "s", at position 0. You might want to try:
- passing `format` if your strings have a consistent format;
- passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
- passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.
</code></pre>
<p>This is a value UNIX timestamp according to <a href="http://www.unixtimestamp.com" rel="nofollow noreferrer">www.unixtimestamp.com</a>, so what gives?</p>
| <python><pandas><datetime><datetime-format> | 2023-08-30 14:55:39 | 1 | 1,748 | ultra909 |
77,009,090 | 6,645,564 | How do I get the information in the hoverbox of my plotly figure to be reordered when I have hovermode set to 'x unified'? | <p>I have built a plotly figure that mostly consists of go.Scatter traces. Each of these traces have slightly different hovertemplates, but I want the information in the hoverbox to be consolidated, so I set the hovermode to 'x unified', which solves my main issue, but I have another small problem that I'd like to resolve.</p>
<p>A very basic reconstruction of my code looks like this:</p>
<pre><code>url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_df = pd.read_csv(url,header=None,encoding='utf-8')
iris_df.columns = ['sepal length','sepal width','petal length', 'petal width', 'class']
test_fig = go.Figure()
class_colors = {'Iris-setosa':'blue', 'Iris-versicolor':'green', 'Iris-virginica':'purple'}
for group in iris_df['class'].unique():
iris_df_class = iris_df[iris_df['class']==group]
test_fig.add_trace(go.Scatter(x=iris_df_class['sepal length'],
y= iris_df_class['petal length'],
mode='markers',
marker=dict(size=10, color=class_colors[group], symbol=1),
text= group,
hoverinfo='text',
hovertemplate = '<i>Sepal length</i>: %{x:.2f} <extra></extra>',
name= group,
showlegend=True,
legendgroup=group))
iris_df_class_over_6 = iris_df_class[iris_df_class['sepal length']>6]
test_fig.add_trace(go.Scatter(x=iris_df_class_over_6['sepal length'],
y= iris_df_class_over_6['petal length']+0.5,
mode='markers',
marker=dict(size=12, color=class_colors[group], symbol=5),
name='trace2',
meta=iris_df_class_over_6['petal width']/iris_df_class_over_6['sepal width'],
hovertemplate='<i>Petal length</i>: %{y:.2f} <br><i>Petal/sepal width ratio</i>: %{meta:0.2f} <extra></extra>',
showlegend=False,
legendgroup=group))
for s,p in zip(iris_df_class_over_6['sepal length'], iris_df_class_over_6['petal length']):
test_fig.add_trace(go.Scatter(x=[s,s],
y=[p,p+0.5],
mode='lines',
marker_line_width = 2,
line_color=class_colors[group],
name='trace-intermediate',
hoverinfo='skip',
showlegend=False,
legendgroup=group))
test_fig.update_layout(xaxis_title="sepal length", yaxis_title="petal length", hovermode='x unified')
test_fig.show()
</code></pre>
<p>Which produces a plot like this:
<a href="https://i.sstatic.net/O1bMG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/O1bMG.png" alt="plot example1" /></a></p>
<p>Upon looking at the hoverbox, one can see that the trace for Iris-setosa class (in blue) is placed at the top of the hoverbox, followed by Iris-versicolor (green) and then Iris-virginica (purple). If a given trace is not present at a certain point, the order is still maintained (minus the non-present trace)
<a href="https://i.sstatic.net/d70fh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/d70fh.png" alt="plot example2" /></a></p>
<p>Now what I would like to do is to organize this order so that the purple trace goes on top, followed by the green, and then the blue at the bottom. I have tried checking the documentation, but it's not clear what I can do to change the order of the information in the hover box. Does anybody know what could be done?</p>
| <python><plotly> | 2023-08-30 14:44:14 | 1 | 924 | Bob McBobson |
77,009,012 | 1,028,270 | How do I properly import RaisesContext from pytest for my type hints? | <p>I want to use type hints everywhere include my helper functions in my test suite.</p>
<p>A snippet of a function looks like this:</p>
<pre><code>def my_helper(
should_exit: RaisesContext = None,
):
# do stuff
</code></pre>
<p>And it is passed a RaisesContext like this:</p>
<pre><code>my_helper(pytest.raises(SystemExit))
</code></pre>
<p>Now <code>type(pytest.raises(SystemExit))</code> returns <code><class '_pytest.python_api.RaisesContext'></code></p>
<p>This is the only way I could figure out how to import the class:</p>
<pre><code>from _pytest.python_api import RaisesContext
</code></pre>
<p>Is this OK? <code>_pytest</code> indicates it should not be referenced directly like this. What is the right way to import this class explicitly so I can use it in my type hints?</p>
<p>Also, I know I don't <em>need</em> type hints, but I want to use them and be as explicit with them as I can.</p>
| <python><pytest> | 2023-08-30 14:35:24 | 1 | 32,280 | red888 |
77,008,905 | 6,849,045 | anaconda falls back to wrong python version on a local environment in vscode | <p>I'm trying to run an ipynb file in vscode and I'm stuck. The extension host keeps crashing and I think I might've found a culprit.</p>
<p>Some info about what I'm working with:</p>
<ul>
<li>I'm working on a relatively old macOS (10.13.6)</li>
<li>I have a completely fresh anaconda install (conda 23.7.2)</li>
</ul>
<p>The steps that I took to find the error:</p>
<ol>
<li>When I run <code>python --version</code> in my base environment in the terminal I get <code>Python 3.11.5</code>. <code>which python</code> gives me <code>/Users/myname/anaconda3/bin/python</code></li>
<li>When I run the same in the terminal from the environment <code>/Users/myname/Projects/myproject/.conda</code> I get <code>Python 3.11.5</code>. <code>which python</code> gives me <code>/Users/myname/Projects/myproject/.conda/bin/python</code></li>
<li>When I run the same from any environment in vscode I get <code>Python 2.7.16</code>. <code>which python</code> gives me <code>/usr/bin/python</code></li>
</ol>
<p>I think this might be the reason why the Jupyter extension keeps crashing. (the only code I'm trying to run is <code>print("hello")</code>)</p>
| <python><visual-studio-code><anaconda><anaconda3> | 2023-08-30 14:21:00 | 2 | 1,072 | Typhaon |
77,008,806 | 11,117,255 | Youtube-dl error message: Got error: HTTP Error 403: Forbidden | <p>I want to download a video with youtubedl</p>
<p>I have my options to set to:</p>
<pre><code>ydl_opts = {
'verbose': False,
'ignoreerrors': True,
'cachedir': None,
'outtmpl': "%(title)s.%(ext)s",
'format': 'm4a/bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'm4a',
}]
}
</code></pre>
<p>But the program gives me this error</p>
<pre><code>[download] Got error: HTTP Error 403: Forbidden
ERROR: fragment 1 not found, unable to continue
</code></pre>
<p>I am on the latest version youtube-dl available with pip.</p>
<p>I tried to add a referrer because I read that might work from a previous post, but that was unsuccessful.</p>
| <python><python-3.x><youtube><youtube-dl> | 2023-08-30 14:08:29 | 2 | 2,759 | Cauder |
77,008,766 | 7,484,093 | Trimming outliers in the pandas dataframe, using logical operators >= and <= | <p>I have a dataframe with 50+ (see an example with 2 only)</p>
<pre><code>data = {
"Blood": [26, 48, 41, 80, 66, 40, 7, 73, 60, 61, 52, 76, 40, 53, 2, 9, 100, 59, 99, 82, 100, 82, 62, 73],
"Urine": [76, None, 20, 84, 30, 60, 0, 46, 50, 58, None, 66, 40, 22, 66, 18, 0, 60, 1, 78, None, 80, 77, 83]}
df = pd.DataFrame(data)
</code></pre>
<p>I am trimming outliers in specific columns, using the function</p>
<pre><code>def trim_outliers_replace_with_nan(df, cols):
for col in cols:
lo = df[col].quantile(0.025)
hi = df[col].quantile(0.975)
df[col] = df[col].where((df[col] > lo) & (df[col] < hi), np.nan)
return df
</code></pre>
<p>The output is exactly what I need.</p>
<p>When I want to change operators <code>></code> and <code><</code> and use</p>
<pre><code>def trim_outliers_replace_with_nan(df, cols):
for col in cols:
lo = df[col].quantile(0.025)
hi = df[col].quantile(0.975)
df[col] = df[col].where((df[col] >= lo) & (df[col] <= hi), np.nan)
return df
</code></pre>
<p>it returns the full dataframe without trimming at all. I suspected that something is with types of columns. One was <code>int64</code> instead of <code>object</code> and I fixed it for have consistency.
What am I missing?</p>
| <python><numpy><operators><outliers> | 2023-08-30 14:03:09 | 0 | 2,520 | Anakin Skywalker |
77,008,586 | 4,113,031 | Detecting duplicates and managing documents in Redis | <p>Our team uses Redis as a vector store for our Langchain application. We store text chunks as hashes with indexed keys, and fields of metadata, content, and vector. The issue arises when we are trying to identify and remove duplicates from the vector store. Our current method requires retrieving all the keys into Python, then look into the metadata field and subset by the "source" item, in order to find all the keys related to a specific document. Then, we are going back to Redis and deleting the found keys.</p>
<p>Is there a way to achieve this natively utilizing Redis, without the Python intermediate step?</p>
<p>We seek advice from experienced Redis users for efficient alternatives.</p>
<p>Here is a working example of our insertion script:</p>
<pre class="lang-py prettyprint-override"><code>from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores.redis import Redis
from langchain.embeddings import OpenAIEmbeddings
## Load docs
loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size = 100, chunk_overlap = 30)
docs = text_splitter.split_documents(documents)[:5]
## Embeddings
embeddings = OpenAIEmbeddings()
## Redis
indx = "test"
url = "redis://localhost:6379/0"
for document in docs:
content = document.page_content
metadata = document.metadata
metadata["source"] = "a"
metadata["title"] = "b"
metadata["tags"] = "c"
document.metadata = metadata
rds = Redis.from_documents(
documents = docs + docs, # intentionally added to create duplications
embedding = embeddings,
redis_url = url,
index_name = indx
)
</code></pre>
<h3>Simplified literal Example:</h3>
<p>Imagine a library where books are stored in Redis as chunks of text. Each book is divided into sections, and each section is stored as a Redis hash with the following structure:</p>
<pre><code>Hash Key: indexname:hash_id
Fields:
- metadata: JSON containing book details (title, author, tags)
- content: Text content of the section
- vector: Vector representation for semantic search
</code></pre>
<p>Currently, when needing to update or remove a specific book, we first retrieve all keys (matching the index prefix) and match a certain book title (from the metadata dictionary), then iterate through those keys to perform the necessary actions. However, as the number of books grows, this approach seems less efficient. We are seeking advice on how to manage the Redis storage and retrieval process more effectively as our library scales.</p>
| <python><redis><chatbot><langchain><semantic-search> | 2023-08-30 13:38:46 | 0 | 1,178 | Niv Cohen |
77,008,560 | 16,428,425 | How to make Kivy app stay in the Task Bar on close | <p>How to make the Kivy app stay in the Task Bar on close and how to add a list to manage it as I showed in the following pictures,
Can anyone please show me where is that documented or I can read about it?</p>
<p>here is an example:</p>
<p><a href="https://i.sstatic.net/W7lpB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/W7lpB.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/AWAWc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AWAWc.png" alt="enter image description here" /></a></p>
| <python><kivy> | 2023-08-30 13:36:10 | 1 | 562 | Abdelrahman Khallaf |
77,008,517 | 2,622,368 | How to get object's value if key name contains dots in jsonpath | <p>The following code all returns False.</p>
<pre class="lang-py prettyprint-override"><code>import jsonpath
data = {'layers': {'urlencoded-form.key': ["1234"]}}
assert jsonpath.jsonpath(data, '$..urlencoded-form.key') == False
assert jsonpath.jsonpath(data, '$..[urlencoded-form.key]') == False
assert jsonpath.jsonpath(data, '$..["urlencoded-form.key"]') == False
assert jsonpath.jsonpath(data, '$.."urlencoded-form.key"') == False
</code></pre>
| <python><jsonpath> | 2023-08-30 13:30:44 | 0 | 829 | wgf4242 |
77,008,404 | 913,098 | Do I have to pass the dataset both to the loader and the RandomSampler? | <p>This is my code</p>
<pre><code> def train_dataloader(self):
if self._is_weighted_sampler:
weights = list(self.label_weight_by_name.values())
sampler = torch.utils.data.sampler.WeightedRandomSampler(
torch.tensor(weights), len(weights)
)
else:
sampler = torch.utils.data.RandomSampler(self._train_dataset)
return DataLoader(self._train_dataset, batch_size=self._batch_size, shuffle=True, sampler=sampler)
</code></pre>
<p>Notice in the case of Weighted sampler, it doesn't require the dataset, but RandomSampler does.</p>
<p>In the RandomSampler case, it means the dataset is passed twice.</p>
<p>I must be missing something about how this is to be used, please correct me.</p>
| <python><deep-learning><pytorch> | 2023-08-30 13:15:49 | 1 | 28,697 | Gulzar |
77,008,355 | 21,404,794 | Efficiently finding values in pandas dataframe filtering by different columns | <p>I'm doing some work with a pandas dataframe, and I need to filter the data according to different columns. This is easily done with pandas syntax, as shown in the Minimal Working Example below:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
#Create DataFrame
df = pd.DataFrame({'col1':['one','two','three','four', 'five'],'col2':[1,2,3,4,5],'col3':[0.3,0.4,0.5,0.6,0.7], 'col4':[0.4,0.5,0.6,0.7,0.8]})
print(df)
#Filter wanted values
print(df[(df['col1'] == 'one') & (df['col2'] == 1)])
</code></pre>
<p>The problem is, when the number of columns you have to filter by is large (more than 4), this syntax rapidly becomes a really long chain of <code>&</code> and <code>|</code> with a lot of redundant elements on it, and it's really hard to read afterwards. I'll leave an example of that happening here: <code>data_raw[(data_raw['Metales'] == 'MoO3') | (data_raw['Metales_0'] == 'MoO3') | (data_raw['Metales_1'] == 'MoO3')| (data_raw['Metales_2'] == 'MoO3')]</code>
(this is just to ilustrate how fast it becomes too long to read comfortably, in theory, I won't be needing to check the same column for 2 different values)</p>
<p>Is there a more pythonic and clean way to select values in a bunch of different columns?</p>
| <python><pandas><dataframe> | 2023-08-30 13:07:54 | 4 | 530 | David Siret Marqués |
77,008,280 | 4,935,114 | Numpy: convert xyzV table to a grid | <p>I have this text file I can read with <code>numpy.loadtxt</code> into a 2D array:</p>
<pre><code> X Y Z V
-30 -15 -25 2
-29 -15 -25 2.1
-28 -15 -25 2.2
. . . .
. . . .
+29 -15 -25 2.1
+30 -15 -25 -2.0
-30 -14 -25 2 # now iterating X values while Y=-14
-29 -14 -25 2.1
-28 . . 2.2
. . . .
. . . .
+29 -13 -25 2.1
+30 -13 -25 -2.0 # now iterating X values while Y=-13, and so on...
. . . .
. . . .
. . . .
. . . .
</code></pre>
<p>The ranges of X, Y and Z are not necessarily integers, and as illustrated above not the same in all axes. I want to create a grid out of this data, i.e to get arrays such that:</p>
<pre><code>>>> np.shape(V)
(61,31,51)
>>> np.shape(x)
(61,)
>>> np.shape(y)
(31,)
>>> np.shape(z)
(51,)
</code></pre>
<p>I saw an almost <a href="https://stackoverflow.com/questions/9114301/column-xyz-data-to-grid-for-plotting">identical question here</a>, but its clear to see that the answer there rely on the fact that the <code>X</code> & <code>Y</code> columns contain integers starting from a known, and positive number.</p>
| <python><numpy><reshape> | 2023-08-30 12:59:26 | 1 | 2,916 | Doron Behar |
77,008,194 | 5,300,978 | cannot import class ReduceDocumentsChain | <p>I am trying to import a library called <code>ReduceDocumentsChain</code>, I found out how to import <code>MapReduceDocumentsChain</code> but still no luck about the first one.</p>
<p><code>from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain</code></p>
<p>I am following this tutorial:</p>
<p><a href="https://python.langchain.com/docs/use_cases/summarization" rel="nofollow noreferrer">https://python.langchain.com/docs/use_cases/summarization</a></p>
<p>Anyone has any idea?</p>
<p>Thank you</p>
| <python><langchain> | 2023-08-30 12:48:13 | 2 | 1,324 | M. Mariscal |
77,008,178 | 5,576,083 | Fill a pandas dataframe with string values | <p>I have a pandas dataframe like this</p>
<pre><code>import pandas as pd
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [4, 24, 31, 2, 3]}
DF = pd.DataFrame(data)
</code></pre>
<p>I need to add a new column named "key" to be filled with new values, to produce a new dataframe like this</p>
<pre><code>data2 = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'year': [2012, 2012, 2013, 2014, 2014],
'reports': [4, 24, 31, 2, 3],
'keys': ["p1s4", "p1s24", "p1s31", "p1s2", "p1s3"]}
DF2 = pd.DataFrame(data2)
</code></pre>
<p>I wrote a code like this</p>
<pre><code>DF["key"] = "p" + str(1) + "s" + str(DF["reports"])
</code></pre>
<p>But it doesn't work</p>
| <python><pandas> | 2023-08-30 12:46:03 | 1 | 301 | ilFonta |
77,008,165 | 9,681,081 | Official API for typing.Generic.__orig_bases__ | <p>I have a generic type for which I'd like to retrieve at runtime the type of its type variable.</p>
<p>The following snippet runs well, but it uses <code>Generic.__orig_bases__</code> which is not an official API (its use is discouraged in <a href="https://peps.python.org/pep-0560/#mro-entries" rel="noreferrer">PEP 560</a> that defines it).</p>
<p>Is there an official API to retrieve it? And if not, is there another (officially supported) way for me to code <code>get_t</code> in this example?</p>
<pre class="lang-py prettyprint-override"><code>import typing
T = typing.TypeVar("T")
class MyGeneric(typing.Generic[T]):
@classmethod
def get_t(cls) -> type[T]:
for base in cls.__orig_bases__:
if typing.get_origin(base) is MyGeneric:
return typing.get_args(base)[0]
raise RuntimeError("didn't work :(")
class IntImplementation(MyGeneric[int]):
pass
assert IntImplementation.get_t() is int
</code></pre>
| <python><generics><python-typing> | 2023-08-30 12:42:47 | 1 | 2,273 | Roméo Després |
77,008,053 | 9,311,137 | Selective/Combined Type Hints (Literals etc.) | <p>Is it possible to combine (perhaps not the right word) two or more sets of type hints such that they are only valid in specific combinations?</p>
<p>I have a function that takes <code>value</code> and <code>value_type</code> arguments. (these later get fed into a graphQL API where I use both values to set up filtering in a query string i.e. <code>"endpoint(value_type: value) {...}"</code>so I need to separately know both items)</p>
<p><code>value_type</code> is already typed as <code>Literal["option1", "option2", "secret third option"]</code></p>
<p><code>value</code> could be either an <code>int</code> or a <code>str</code>, which currently I'm just typing as <code>Union[int, str]</code> which is fine for just me because I wrote it, obviously, but if others use this library I'd like it to be more clear:</p>
<p>What I want is more dynamic, e.g. a <code>value_type</code> of <code>"option1"</code> <strong>must</strong> have a value given as a <code>str</code>, whereas <code>"option2"</code> must come with an <code>int</code>, etc.</p>
<p>Currently I just use a match/case and some <code>assert</code>s to validate, but I'd prefer for the IDE to indicate there's a problem before you run it without writing some hefty documentation.</p>
<p>I'm against making two functions as the rest of the code is identical, it just adds some quote marks if its a string to satisfy graphQL query formatting.</p>
| <python><python-typing> | 2023-08-30 12:28:27 | 1 | 684 | ch4rl1e97 |
77,007,885 | 21,303,427 | Pydantic V2 `model_validator(mode="wrap")` - How to use `ModelWrapValidatorHandler` | <p>In short I want to implement a <code>model_validator(mode="wrap")</code> which takes a <code>ModelWrapValidatorHandler</code> as argument. I guess this validation handler just calls at least all before-validators.</p>
<pre class="lang-py prettyprint-override"><code>class A(BaseModel):
x: str
y: int
model_config = ConfigDict(frozen=True)
@model_validator(mode="wrap")
def something(cls, values: Any, handler: ModelWrapValidatorHandler["A"]):
# values seems to be a dict most of the cases
result = handler(values)
# result always seems to be an instance of A
result2 = handler(values, outer_location="x")
# Seems to do the same thing
# result3 = handler(values["x"], outer_location="x")
# Doesn't work because the value of x would get passed to model-before-validators
# which is obviously expected to be e.g. a dictionary of all fields.
return result
</code></pre>
<p>I can't get to it. I couldn't find any documentation of it. There is no example usage or similar documented on this ModelWrapValidator as well. With my debugger I can't even get into the implemented handler function. I guess it lives somewhere in the new Rust-core <a href="https://github.com/pydantic/pydantic-core" rel="nofollow noreferrer">pydantic-core</a>.</p>
<p>So essentially I have two questions: What does <code>outer_location</code> do? Or how do I get to the implementation - is there anyway to dig into it with the debugger?</p>
<p>Why do I need this:
I can't use before-validators due to execution ordering. After-validators doesn't suite my needs as well because my model is configured to be frozen and I need to mutate the values. That's why I cannot simply throw the handler on it since it returns instances of my class. Yes, I'm aware that I can use <code>object.__setattr__(result, field_name, new_field_value)</code> to circumvent the "frozen" state of the instance but that would be my last resort.</p>
| <python><pydantic> | 2023-08-30 12:08:13 | 1 | 493 | lord_haffi |
77,007,846 | 2,988,360 | Cannot open Edge with selenium on Ubuntu | <p>I am trying to open Edge from selenium with python selenium-4.11.2.</p>
<p>I have downloaded the msedgedriver (version 115.0.1901.203; same as installed Edge) and run the following code snippet:</p>
<pre><code>from selenium import webdriver
edgedriver = join(HOME, "webdrivers", "msedgedriver") # path to driver
service = webdriver.EdgeService(executable_path=edgedriver)
driver = webdriver.Edge(service=service)
driver.get("https://google.com") # Try google.com
</code></pre>
<p>So far so good. With the above snippet adjusted for Chrome, everything works as expected. However, with the presented snippet for Edge, selenium still runs Chrome. I am new to selenium, but could not find anyone else having this issue.</p>
| <python><selenium-webdriver><webdriver><microsoft-edge> | 2023-08-30 12:05:08 | 1 | 5,233 | PKlumpp |
77,007,440 | 14,282,714 | ValueError: Tokenizer class LlamaTokenizer does not exist or is not currently imported | <p>I am trying to run the code from this <a href="https://huggingface.co/blog/llama2" rel="noreferrer">Hugging Face blog</a>. At first, I had no access to the model so this error: <a href="https://stackoverflow.com/questions/77006745/oserror-meta-llama-llama-2-7b-chat-hf-is-not-a-local-folder">OSError: meta-llama/Llama-2-7b-chat-hf is not a local folder</a>, is now solved and I created an acces token from Hugging Face which works. Now I'm facing a different error when running the following code:</p>
<pre><code>from transformers import AutoTokenizer
import transformers
import torch
model = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True)
pipeline = transformers.pipeline(
"text-generation",
model=model,
torch_dtype=torch.float16,
device_map="auto",
)
sequences = pipeline(
'I liked "Breaking Bad" and "Band of Brothers". Do you have any recommendations of other shows I might like?\n',
do_sample=True,
top_k=10,
num_return_sequences=1,
eos_token_id=tokenizer.eos_token_id,
max_length=200,
)
for seq in sequences:
print(f"Result: {seq['generated_text']}")
</code></pre>
<p>Error:</p>
<pre><code>ValueError: Tokenizer class LlamaTokenizer does not exist or is not currently imported.
</code></pre>
<p>The error is not the same as this error: <a href="https://stackoverflow.com/questions/75907910/importerror-cannot-import-name-llamatokenizer-from-transformers">ImportError: cannot import name 'LLaMATokenizer' from 'transformers'</a>, because now it is a valuerror. To make sure I use the right version I run this code:</p>
<pre><code>pip install git+https://github.com/huggingface/transformers
</code></pre>
<p>After that I checked this issue <a href="https://github.com/huggingface/transformers/issues/22222" rel="noreferrer">ValueError: Tokenizer class LLaMATokenizer does not exist or is not currently imported. #22222
</a>. This suggests:</p>
<blockquote>
<p>Change the LLaMATokenizer in tokenizer_config.json into lowercase
LlamaTokenizer and it works like a charm.</p>
</blockquote>
<p>So, I checked the files if it is using <code>LLamaTokenizer</code> instead of <code>LlamaTokenizer</code> like for example here (This is the class in the file):</p>
<pre><code>class LlamaTokenizer(PreTrainedTokenizer):
</code></pre>
<p>So I was wondering if anyone knows how to fix this error?</p>
| <python><huggingface-transformers><huggingface><llama> | 2023-08-30 11:11:33 | 1 | 42,724 | Quinten |
77,007,331 | 1,801,242 | Not able to click a button with Selenium Python | <p>I am using Selenium to click a button but I am getting a <code>ElementNotInteractableException</code>.</p>
<p>Here is the Selenium Python snipit:</p>
<pre><code>b.driver.find_element(By.CLASS_NAME,"button-prm-light").click()
</code></pre>
<p>Here is the html:</p>
<pre><code><button class="button-prm-light button-height-40 button-padding-fill button-rounded"
ng-hide="vm.isBlockedOrBlockedByMe() || vm.isPrivateAndHidden() || vm.isOwnProfile"
talk-to="8d056f47-c680-e711-80c2-0003ff4668ed" talk-to-type="user"> <i class="icon-
speech-bubbles"></i> <span>Chat</span> </button>
</code></pre>
<p>Any ideas on how to do this?</p>
| <python><selenium-webdriver> | 2023-08-30 10:54:01 | 2 | 333 | Justin |
77,007,324 | 4,405,942 | os.path.getmtime() inconsistent with time.time() | <p>I'm trying to verify the time of most recent modification of a file and got to the following:</p>
<pre><code> print("before", time.time())
with open(file, "wb") as fh:
fh.write(b"12345")
print("after", time.time())
print("modified", os.path.getmtime(file))
</code></pre>
<p>I expect before < modified < after. But the output reads:</p>
<pre><code>before 1693392599.8838775
after 1693392599.8839073
modified 1693392599.8792782
</code></pre>
<p>What am I missing? Thank you.</p>
| <python><python-os> | 2023-08-30 10:52:51 | 1 | 2,180 | Gerry |
77,007,304 | 4,564,080 | Count of specific value of column in group | <p>I am trying to achieve the following:</p>
<pre class="lang-py prettyprint-override"><code>aggregate_commitment_df = commitment_df.group_by("sprint_start_date", "squad").agg(
stories_committed=pl.count(pl.col("issue_type") == "Story"),
spikes_committed=pl.count(pl.col("issue_type") == "Spike"),
bugs_committed=pl.count(pl.col("issue_type") == "Bug"),
story_points_committed=pl.sum("story_points"),
)
</code></pre>
<p>where, for example, <code>stories_committed</code> will be the count of all rows with <code>issue_type == "Story"</code> for each <code>sprint_start_date</code> and <code>squad</code>.</p>
| <python><python-polars> | 2023-08-30 10:49:54 | 1 | 4,635 | KOB |
77,007,211 | 1,714,692 | Scale only 2 axis in a 3d matplotlib | <p>Consider the case where a maplotlib 3d plot have 2 axis that represents the same kind of measurement (for example a length) and another one of a different kind (for example time). I would like to scale only 2 axis (the ones representing the length) but not the other one.
In a 2d plot I would do this with <code>ax.axis("equal")</code>, but this command scales all the axis.</p>
<p>Is there a way to do that?</p>
| <python><matplotlib> | 2023-08-30 10:36:13 | 1 | 9,606 | roschach |
77,007,186 | 392,041 | Apache beam python looking up value in other collection | <p>I am trying to lookup a value in a seperate big query table, i need to lookup the link_url in table one using the url in table 2. From table 1 i need just the link_id</p>
<p>table 1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>link_id</th>
<th>link_url</th>
</tr>
</thead>
<tbody>
<tr>
<td>id1</td>
<td><a href="https://link1.com" rel="nofollow noreferrer">https://link1.com</a></td>
</tr>
<tr>
<td>id2</td>
<td><a href="https://link2.com" rel="nofollow noreferrer">https://link2.com</a></td>
</tr>
<tr>
<td>id3</td>
<td><a href="https://link3.com" rel="nofollow noreferrer">https://link3.com</a></td>
</tr>
</tbody>
</table>
</div>
<p>table 2</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>url</th>
<th>app</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://link1.com" rel="nofollow noreferrer">https://link1.com</a></td>
<td>App1</td>
</tr>
<tr>
<td><a href="https://link2.com" rel="nofollow noreferrer">https://link2.com</a></td>
<td>App2</td>
</tr>
<tr>
<td><a href="https://link3.com" rel="nofollow noreferrer">https://link3.com</a></td>
<td>App3</td>
</tr>
<tr>
<td><a href="https://link4.com" rel="nofollow noreferrer">https://link4.com</a></td>
<td>App4</td>
</tr>
</tbody>
</table>
</div>
<p>desired output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>link_id</th>
<th>link_url</th>
<th>app</th>
</tr>
</thead>
<tbody>
<tr>
<td>id1</td>
<td><a href="https://link1.com" rel="nofollow noreferrer">https://link1.com</a></td>
<td>App1</td>
</tr>
<tr>
<td>id2</td>
<td><a href="https://link2.com" rel="nofollow noreferrer">https://link2.com</a></td>
<td>App2</td>
</tr>
<tr>
<td>id3</td>
<td><a href="https://link3.com" rel="nofollow noreferrer">https://link3.com</a></td>
<td>App3</td>
</tr>
<tr>
<td>null</td>
<td><a href="https://link4.com" rel="nofollow noreferrer">https://link4.com</a></td>
<td>App4</td>
</tr>
</tbody>
</table>
</div>
<p>What i have</p>
<pre><code>import logging
import apache_beam as beam
def use_side_input(main, side_input):
return side_input[main]
def run():
with beam.Pipeline() as p:
links = p | 'ReadLinks' >> beam.io.ReadFromBigQuery(table="table1", gcs_location="gs://bucket/tmp/")
linkviews = p | 'LinkViews' >> beam.io.ReadFromBigQuery(table="table2", gcs_location="gs://bucket/tmp/")
out | "use side input" >> beam.Map(use_side_input, side_input=beam.pvalue.AsDict(links))
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
run()
</code></pre>
<p>I know i should be using side inputs but i have no clue how to continue</p>
| <python><google-bigquery><apache-beam> | 2023-08-30 10:31:28 | 1 | 562 | Josh Fradley |
77,007,171 | 1,627,466 | Apply function with two arguments on same list and output only lower/upper triangular matrix without diagonal | <p>I want to compare strings without unecessary comparisons, so far I have:</p>
<p><code>[[[dice_coefficient(x,y) for x in ['a','a','b'][j]] for y in ['a','a','b'][0:j]] for j in [1,2]]</code></p>
<p>where <code>dice_coefficient</code> is defined <a href="https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Dice%27s_coefficient#Python" rel="nofollow noreferrer">here</a></p>
<p>which gives the expected output but look like it would be the right approach if those strings were the comments of an author in a column of a pandas dataframe.</p>
| <python><pandas><group-by><list-comprehension><apply> | 2023-08-30 10:29:38 | 2 | 423 | user1627466 |
77,006,962 | 10,291,435 | how to keep sources field in answer of langchain while having custom prompt | <p>I am trying to write a code to answer questions using langchain like this:</p>
<pre><code>db = ElasticVectorSearch(
elasticsearch_url=url,
index_name=index_name,
embedding=embeddings
)
qa_chain = RetrievalQAWithSourcesChain.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=db.as_retriever(),
return_source_documents=True,
verbose=True
)
qa_chain({"question": question})
</code></pre>
<p>and it works fine and retrieves the answer with the source field as exected.
However, when I try to add custom prompt like this, I get blank field of source:</p>
<pre><code> "QA_PROMPT" : "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. if answer wasn't found within the context say \"I don't know\"\n{summaries}\nQuestion: {question}Answer:",
PROMPT = PromptTemplate(
template=QA_PROMPT, input_variables=["summaries", "question"]
)
chain_type_kwargs = {"prompt": PROMPT}
qa_chain = RetrievalQAWithSourcesChain.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=db.as_retriever(),
chain_type_kwargs=chain_type_kwargs,
return_source_documents=True,
verbose=True
)
</code></pre>
<p>I get source field as blank. So, I thought maybe we need to change the prompt so I did the following:</p>
<pre><code>template = """Given the following extracted parts of a long document and a question, create a final answer with references ("SOURCES").
If you don't know the answer, just say that you don't know. Don't try to make up an answer.
ALWAYS return a "SOURCES" part in your answer.
QUESTION: {question}
=========
{summaries}
=========
FINAL ANSWER: {final_answer}
SOURCES: {sources}"""
PROMPT = PromptTemplate(template=template, input_variables=["summaries", "question", "final_answer", "sources"])
chain_type_kwargs = {"prompt": PROMPT}
qa_chain = RetrievalQAWithSourcesChain.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=db.as_retriever(),
chain_type_kwargs=chain_type_kwargs,
return_source_documents=True,
verbose=True
)
answer = qa_chain({"question": question})
</code></pre>
<p>I got this error:
<code>ValueError: Missing some input keys: {'final_answer', 'sources'}</code></p>
<p>what I am missing here? in the normal cases without passing the custom prompt, I get the expected source field, and I get the metadata has source inside it also.</p>
<p>Thanks in advance.</p>
| <python><elasticsearch><openai-api><langchain> | 2023-08-30 10:00:27 | 1 | 1,699 | Mee |
77,006,924 | 17,082,611 | Debugging autoencoder training (loss is low but reconstructed image is all black) | <p>I am implementing a (variational) autoencoder (VAE) in Keras following <a href="https://keras.io/examples/generative/vae/" rel="nofollow noreferrer">this guide</a>.</p>
<p>The VAE reads data from <code>topomaps</code> folder and labels from <code>labels</code> folder. They both contain <code>.npy</code> files, <a href="https://numpy.org/devdocs/reference/generated/numpy.lib.format.html" rel="nofollow noreferrer">which are essentially numpy arrays stored on disk</a>.</p>
<p>I split data set into 80% training data and 20% test data. Specifically:</p>
<ul>
<li><code>x_train</code> shape is <code>(245760, 40, 40, 1)</code></li>
<li><code>y_train</code> shape is <code>(245760,)</code></li>
<li><code>x_test</code> shape is <code>(61440, 40, 40, 1)</code></li>
<li><code>y_test</code> shape is <code>(61440,)</code></li>
</ul>
<p>Unfortunately even though the (training) <code>loss</code> and <code>val_loss</code> are pretty low (<code>2.9246e-04</code> and <code>-4.8249e-04</code>, respectively), if I visually check the "reconstruction skills" of my VAE, I can notice they are poor since reconstructed image is not similar at all to the original one:</p>
<p><a href="https://i.sstatic.net/p36yQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/p36yQ.png" alt="original" /></a></p>
<p><a href="https://i.sstatic.net/b2fWL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/b2fWL.png" alt="reconstructed" /></a></p>
<p>I ran the demo using this configuration:</p>
<ul>
<li><code>latent_dim=25</code>. This value must not be changed</li>
<li><code>epochs=2</code></li>
<li><code>batch_size=512</code></li>
<li><code>optimizer=Adam()</code></li>
<li><code>learning_rate=0.001</code></li>
</ul>
<p>I know <code>epochs</code> is very small, but it is only a demo. I aim to enlarge it when I figure out why my VAE won't work even though loss is very low.</p>
<p>This is the run output:</p>
<pre><code>Epoch 1/2
2023-08-30 11:35:49.408811: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.
384/384 [==============================] - ETA: 0s - loss: 60.0042 - reconstruction_loss: 11.0072 - kl_loss: 0.09892023-08-30 11:38:40.538661: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.
384/384 [==============================] - 190s 492ms/step - loss: 59.8772 - reconstruction_loss: 11.0072 - kl_loss: 0.0989 - val_loss: 5.5495e-04 - val_reconstruction_loss: 5.4875e-04 - val_kl_loss: 6.1989e-06
Epoch 2/2
384/384 [==============================] - 188s 490ms/step - loss: 3.0879e-04 - reconstruction_loss: 3.0472e-04 - kl_loss: 1.5222e-06 - val_loss: 3.4318e-04 - val_reconstruction_loss: 3.4303e-04 - val_kl_loss: 1.4901e-07
2023-08-30 11:42:17.049 Python[2419:58392] +[CATransaction synchronize] called within transaction
2023-08-30 11:42:26.493 Python[2419:58392] +[CATransaction synchronize] called within transaction
2023-08-30 11:42:37.200 Python[2419:58392] +[CATransaction synchronize] called within transaction
2023-08-30 11:42:41.800433: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.
1920/1920 [==============================] - 29s 15ms/step
2023-08-30 11:43:16.276 Python[2419:58392] +[CATransaction synchronize] called within transaction
Process finished with exit code 0
</code></pre>
<p>Learning curve:</p>
<p><a href="https://i.sstatic.net/PJ9Iv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PJ9Iv.png" alt="loss learning curve" /></a></p>
<p>These are three model classes:</p>
<pre><code>class VAE(keras.Model):
def __init__(self, encoder, decoder, **kwargs):
super().__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
self.total_loss_tracker = keras.metrics.Mean(name="total_loss")
self.reconstruction_loss_tracker = keras.metrics.Mean(name="reconstruction_loss")
self.kl_loss_tracker = keras.metrics.Mean(name="kl_loss")
def call(self, inputs, training=None, mask=None):
_, _, z = self.encoder(inputs)
outputs = self.decoder(z)
return outputs
@property
def metrics(self):
return [
self.total_loss_tracker,
self.reconstruction_loss_tracker,
self.kl_loss_tracker,
]
def train_step(self, data):
with tf.GradientTape() as tape:
# Forward pass
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
# Compute losses
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
keras.losses.binary_crossentropy(data, reconstruction), axis=(1, 2)
)
)
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
total_loss = reconstruction_loss + kl_loss
# Compute gradient
grads = tape.gradient(total_loss, self.trainable_weights)
# Update weights
self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
# Update my own metrics
self.total_loss_tracker.update_state(total_loss)
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
self.kl_loss_tracker.update_state(kl_loss)
return {
"loss": self.total_loss_tracker.result(),
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
"kl_loss": self.kl_loss_tracker.result(),
}
def test_step(self, data):
# Forward pass
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
# Compute losses
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
keras.losses.binary_crossentropy(data, reconstruction), axis=(1, 2)
)
)
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
total_loss = reconstruction_loss + kl_loss
# Update my own metrics
self.total_loss_tracker.update_state(total_loss)
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
self.kl_loss_tracker.update_state(kl_loss)
return {
"loss": self.total_loss_tracker.result(),
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
"kl_loss": self.kl_loss_tracker.result(),
}
class Encoder(keras.Model):
def __init__(self, latent_dimension, input_shape):
super(Encoder, self).__init__()
self.latent_dim = latent_dimension
self.conv_block1 = keras.Sequential([
layers.Input(shape=input_shape),
layers.Conv2D(filters=64, kernel_size=3, activation="relu", strides=2, padding="same"),
layers.BatchNormalization()
])
self.conv_block2 = keras.Sequential([
layers.Conv2D(filters=128, kernel_size=3, activation="relu", strides=2, padding="same"),
layers.BatchNormalization()
])
self.conv_block3 = keras.Sequential([
layers.Conv2D(filters=256, kernel_size=3, activation="relu", strides=2, padding="same"),
layers.BatchNormalization()
])
self.flatten = layers.Flatten()
self.dense = layers.Dense(units=100, activation="relu")
self.z_mean = layers.Dense(latent_dimension, name="z_mean")
self.z_log_var = layers.Dense(latent_dimension, name="z_log_var")
self.sampling = sample
def call(self, inputs, training=None, mask=None):
x = self.conv_block1(inputs)
x = self.conv_block2(x)
x = self.conv_block3(x)
x = self.flatten(x)
x = self.dense(x)
z_mean = self.z_mean(x)
z_log_var = self.z_log_var(x)
z = self.sampling(z_mean, z_log_var)
return z_mean, z_log_var, z
class Decoder(keras.Model):
def __init__(self, latent_dimension):
super(Decoder, self).__init__()
self.latent_dim = latent_dimension
self.dense1 = keras.Sequential([
layers.Dense(units=100, activation="relu"),
layers.BatchNormalization()
])
self.dense2 = keras.Sequential([
layers.Dense(units=1024, activation="relu"),
layers.BatchNormalization()
])
self.dense3 = keras.Sequential([
layers.Dense(units=4096, activation="relu"),
layers.BatchNormalization()
])
self.reshape = layers.Reshape((4, 4, 256))
self.deconv1 = keras.Sequential([
layers.Conv2DTranspose(filters=256, kernel_size=3, activation="relu", strides=2, padding="same"),
layers.BatchNormalization()
])
self.deconv2 = keras.Sequential([
layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=1, padding="same"),
layers.BatchNormalization()
])
self.deconv3 = keras.Sequential([
layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=2, padding="valid"),
layers.BatchNormalization()
])
self.deconv4 = keras.Sequential([
layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=1, padding="valid"),
layers.BatchNormalization()
])
self.deconv5 = keras.Sequential([
layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=2, padding="valid"),
layers.BatchNormalization()
])
self.deconv6 = layers.Conv2DTranspose(filters=1, kernel_size=2, activation="sigmoid", padding="valid")
def call(self, inputs, training=None, mask=None):
x = self.dense1(inputs)
x = self.dense2(x)
x = self.dense3(x)
x = self.reshape(x)
x = self.deconv1(x)
x = self.deconv2(x)
x = self.deconv3(x)
x = self.deconv4(x)
x = self.deconv5(x)
decoder_outputs = self.deconv6(x)
return decoder_outputs
</code></pre>
<p>Note that the implementation of the VAE belongs to the guide I already posted.</p>
<p>This is the main function:</p>
<pre><code>if __name__ == '__main__':
# Load data
x_train, x_test, y_train, y_test = load_data("topomaps", "labels", 0.2)
# Expand dimensions to (None, 40, 40, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
# Print data shapes
print("x_train shape:", x_train.shape)
print("y_train shape:", y_train.shape)
print("x_test shape:", x_test.shape)
print("y_test shape:", y_test.shape)
# Normalize the data
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
# Compiling the VAE
latent_dimension = 25 # Do not change
encoder = Encoder(latent_dimension, (40, 40, 1))
decoder = Decoder(latent_dimension)
vae = VAE(encoder, decoder)
vae.compile(Adam(learning_rate=0.001))
# Training
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2)
print("x_val shape:", x_val.shape)
print("y_val shape:", y_val.shape)
epochs = 2
batch_size = 512
history = vae.fit(x_train, epochs=epochs, batch_size=batch_size, validation_data=(x_val,))
# Plot learning curves
plot_metric(history, "loss")
# Check reconstruction skills against a random test sample
image_index = 5
plt.title(f"Original image {image_index}")
original_image = x_test[image_index]
plt.imshow(original_image, cmap="gray")
plt.show()
plt.title(f"Reconstructed image {image_index}, latent_dim = {latent_dimension}, epochs = {epochs}, "
f"batch_size = {batch_size}")
x_test_reconstructed = vae.predict(x_test)
reconstructed_image = x_test_reconstructed[image_index]
plt.imshow(reconstructed_image, cmap="gray")
plt.show()
</code></pre>
<p>These are some functions I used:</p>
<pre><code>def load_data(topomaps_folder: str, labels_folder: str, test_size):
x, y = _create_dataset(topomaps_folder, labels_folder)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size)
return x_train, x_test, y_train, y_test
def _create_dataset(topomaps_folder, labels_folder):
topomaps_files = os.listdir(topomaps_folder)
labels_files = os.listdir(labels_folder)
topomaps_files.sort()
labels_files.sort()
x = []
y = []
n_files = len(topomaps_files)
for topomaps_file, labels_file in tqdm(zip(topomaps_files, labels_files), total=n_files, desc="Loading data set"):
topomaps_array = np.load(f"{topomaps_folder}/{topomaps_file}")
labels_array = np.load(f"{labels_folder}/{labels_file}")
if topomaps_array.shape[0] != labels_array.shape[0]:
raise Exception("Shapes must be equal")
for i in range(topomaps_array.shape[0]):
x.append(topomaps_array[i])
y.append(labels_array[i])
x = np.array(x)
y = np.array(y)
return x, y
def sample(z_mean, z_log_var):
batch = tf.shape(z_mean)[0]
dim = tf.shape(z_mean)[1]
epsilon = tf.random.normal(shape=(batch, dim))
stddev = tf.exp(0.5 * z_log_var)
return z_mean + stddev * epsilon
def plot_metric(history, metric):
plt.plot(history.history[metric])
plt.plot(history.history['val_' + metric])
plt.title(metric)
plt.ylabel(metric)
plt.xlabel('epoch')
plt.legend(['train', 'validation'])
plt.show()
</code></pre>
<p><strong>EDIT</strong></p>
<p><strong>- Could you try with much lower training set to see if it overfits and reconstructs a known image?</strong> Okay, this is what I did in <code>main</code> function</p>
<pre><code># Reduce DS size
x_train = x_train[:500]
y_train = y_train[:500]
x_test = x_test[:500]
y_test = y_test[:500]
</code></pre>
<p>This is what I get:</p>
<p><a href="https://i.sstatic.net/dyAzB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dyAzB.png" alt="original" /></a></p>
<p><a href="https://i.sstatic.net/hxTYj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hxTYj.png" alt="reconstructed" /></a></p>
<p>and learning curve is:</p>
<p><a href="https://i.sstatic.net/Upvdz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Upvdz.png" alt="curve" /></a></p>
<p>If I run the same configuration but setting <code>epochs=100</code> I get:</p>
<p><a href="https://i.sstatic.net/FQ8eP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FQ8eP.png" alt="original" /></a></p>
<p><a href="https://i.sstatic.net/Tv94z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Tv94z.png" alt="reconstructed" /></a></p>
<p>and loss:</p>
<p><a href="https://i.sstatic.net/z2P4Y.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/z2P4Y.png" alt="loss" /></a></p>
<p><strong>- Not sure if you did it...but did you convert your output back to a non-normalized value when plotting?</strong> This is what I have done:</p>
<pre><code>plt.title(f"Reconstructed image {image_index}, latent_dim = {latent_dimension}, epochs = {epochs}, "
f"batch_size = {batch_size}")
x_test_reconstructed = vae.predict(x_test)
reconstructed_image = x_test_reconstructed[image_index]
reconstructed_image = reconstructed_image * 255
plt.imshow(reconstructed_image, cmap="gray")
plt.show()
</code></pre>
<p>But I still get:</p>
<p><a href="https://i.sstatic.net/mH8Sd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mH8Sd.png" alt="rec" /></a></p>
<p><strong>- What does the loss graph look like when the batch size is 4 and learning rate is 0.0002 for 100 epochs?</strong> Reconstructed image is all black and loss curve is:</p>
<p><a href="https://i.sstatic.net/SdSd8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SdSd8.png" alt="loss" /></a></p>
| <python><tensorflow><keras><deep-learning><autoencoder> | 2023-08-30 09:57:06 | 2 | 481 | tail |
77,006,856 | 6,999,569 | What is the best python data structure for the contents of jupyter notebook files? | <p>I want to convert jupyter notebooks to python files, but before doing so, I want to filter their contents, e.g. remove all markdown cells; therefore the gui export functionality or calling nbconvert from the command line doesn't exactly satisfy my needs.</p>
<p>What I want to do therefore is to first load the contents of the notebook into a python container, e.g. a list of dictionaries, and then do the filtering on the container, save the remaining contents as a jupyter notebook that is then exported to a python file.</p>
<p><strong>Question:</strong></p>
<ul>
<li>what data structure is most appropriate for holding the contents of a jupyter notebook?</li>
<li>Are there any libraries that already enable the manipulation of jupyter notebooks with python?</li>
</ul>
<p><strong>Remark:</strong><br />
Now that I'm not allowed to ask questions anymore on stackoverflow without being given any specific reason apart from a standard text I'll take the opportunity to say goodbye to stackoverflow and contribute to less chauvinistic forums for which the right of asking questions isn't seen as a privilege and can only be regained by scrubbing floors or polishing door knobs.</p>
| <python><jupyter-notebook> | 2023-08-30 09:49:26 | 1 | 846 | Manfred Weis |
77,006,745 | 14,282,714 | OSError: meta-llama/Llama-2-7b-chat-hf is not a local folder | <p>I'm trying to replied the code from this <a href="https://huggingface.co/blog/llama2" rel="nofollow noreferrer">Hugging Face blog</a>. At first I installed the transformers and created a token to login to hugging face hub:</p>
<pre><code>pip install transformers
huggingface-cli login
</code></pre>
<p>After that it is said to use <code>use_auth_token=True</code> when you have set a token. Unfortunately after running the code I get an error:</p>
<pre><code>from transformers import AutoTokenizer
import transformers
import torch
model = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True)
pipeline = transformers.pipeline(
"text-generation",
model=model,
torch_dtype=torch.float16,
device_map="auto",
)
sequences = pipeline(
'I liked "Breaking Bad" and "Band of Brothers". Do you have any recommendations of other shows I might like?\n',
do_sample=True,
top_k=10,
num_return_sequences=1,
eos_token_id=tokenizer.eos_token_id,
max_length=200,
)
for seq in sequences:
print(f"Result: {seq['generated_text']}")
</code></pre>
<p>Error:</p>
<pre><code>OSError: meta-llama/Llama-2-7b-chat-hf is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `use_auth_token` or log in with `huggingface-cli login` and pass `use_auth_token=True`.
</code></pre>
<p>It says that the model cannot be found, but you can find it in the list of models on hugging face <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf" rel="nofollow noreferrer">here</a>.</p>
<p>This is the version of the <code>transformers</code> package I'm using:</p>
<pre><code>> pip show transformers
Name: transformers
Version: 4.33.0.dev0
Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow
Home-page: https://github.com/huggingface/transformers
Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)
Author-email: transformers@huggingface.co
License: Apache 2.0 License
Location: /Users/quinten/opt/miniconda3/lib/python3.9/site-packages
Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm
Required-by: spacy-transformers
</code></pre>
<p>Does anyone know how to fix this error?</p>
| <python><huggingface-transformers><huggingface><llama> | 2023-08-30 09:34:39 | 2 | 42,724 | Quinten |
77,006,730 | 664,160 | How can I check what is the maximum python version that I can use with in my Django? | <p>I'm using Django with many pip modules; python version is 3.7.5.
I want to write a script that will tell me at any given moment what is the maximum python version that I can use without pip module changes.
Thank you.</p>
| <python><django><dependencies> | 2023-08-30 09:33:13 | 1 | 3,433 | kambi |
77,006,669 | 2,195,440 | how to install from the output of conda dependency export | <p>I generated <strong>dependency list</strong> using:</p>
<pre><code>conda list -e > requirements.txt
</code></pre>
<p>Here are some parts of the <code>depency</code> file:</p>
<pre><code>transformers=4.28.1=pypi_0
typing-extensions=4.7.1=py310hecd8cb5_0
typing_extensions=4.7.1=py310hecd8cb5_0
tzdata=2023.3=pypi_0
</code></pre>
<p>In a different conda environment, I am tryign to install a specific package with:</p>
<pre><code>conda install transformers=4.28.1=pypi_0
</code></pre>
<p>But I get thsi <strong>error</strong>:</p>
<pre><code>PackagesNotFoundError: The following packages are not available from current channels:
- transformers==4.28.1=pypi_0
Current channels:
- https://repo.anaconda.com/pkgs/main/osx-64
- https://repo.anaconda.com/pkgs/main/noarch
- https://repo.anaconda.com/pkgs/r/osx-64
- https://repo.anaconda.com/pkgs/r/noarch
To search for alternate channels that may provide the conda package you're
looking for, navigate to
https://anaconda.org
and use the search bar at the top of the page.
</code></pre>
| <python><anaconda><dependencies><conda><miniconda> | 2023-08-30 09:25:34 | 1 | 3,657 | Exploring |
77,006,611 | 16,383,578 | How to make all values in an array fall into a range? | <p>Say I have a NumPy array of <code>float</code>s, there are positive values and negative values. I have two numbers, say they are <code>a</code> and <code>b</code>, <code>a <= b</code> and <code>[a, b]</code> is a (closed) number range.</p>
<p>I want to make all of the array fall into the range <code>[a, b]</code>, more specifically I want to replace all values outside of the range with the corresponding terminal value.</p>
<p>I am not trying to scale values to fit numbers into a range, in Python that would be:</p>
<pre><code>mina = min(arr)
scale = (b - a) / (max(arr) - mina)
[a + (e - mina) * scale for e in arr]
</code></pre>
<p>Or in NumPy:</p>
<pre><code>mina = arr.min()
scale = (b - a) / (arr.max() - mina)
a + (arr - mina) * scale
</code></pre>
<p>I am trying to replace all values lower than <code>a</code> with <code>a</code> and all values higher than <code>b</code> with <code>b</code>, while leaving all other values unchanged, I can do it in a single list comprehension in Python:</p>
<pre><code>[e if a <= e <= b else (a if e < a else b) for e in arr]
</code></pre>
<p>I can do the same with two broadcasts:</p>
<pre><code>arr[arr < a] = a
arr[arr > b] = b
</code></pre>
<p>Even though NumPy is way faster than Python, the above is two loops, not one, the method is inefficient but compiled.</p>
<p>What is a faster way?</p>
<hr />
<p>I have done the measurement, multiple times, and Python is indeed much slower as expected:</p>
<pre><code>In [1]: import numpy as np
In [2]: numbers = np.random.random(4096) * 1024
In [3]: %timeit numbers[numbers < 256]
16.1 µs ± 219 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
In [4]: %timeit numbers[numbers > 512]
20.9 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
In [5]: %timeit [e if 256 <= e <= 512 else (256 if e < 256 else 512) for e in numbers]
927 µs ± 101 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [6]: %timeit [e if 256 <= e <= 512 else (256 if e < 256 else 512) for e in numbers.tolist()]
684 µs ± 38.2 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
</code></pre>
<hr />
<h2><em><strong>Edit</strong></em></h2>
<p>Fixed the code to scale a range of numbers into another range. When I asked the question I didn't think very much about it, because it wasn't relevant, but now I have given it a second thought and it was obviously wrong, so I corrected it.</p>
<hr />
<h2><em><strong>Another Edit</strong></em></h2>
<p>Just thought about it again, my original Python code isn't as efficient as it can be, it can be done with only two comparisons whereas the original used three:</p>
<pre><code>[a if e < a else (b if e > b else e) for e in arr]
</code></pre>
| <python><arrays><python-3.x><numpy> | 2023-08-30 09:17:53 | 1 | 3,930 | Ξένη Γήινος |
77,006,453 | 5,013,084 | Nested axis labels in altair plot? | <p>It it possible to create nested in altair, similar to this from the <code>ggh4x</code> package?</p>
<p><a href="https://i.sstatic.net/6D6Jb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6D6Jb.png" alt="enter image description here" /></a></p>
| <python><altair> | 2023-08-30 08:58:20 | 0 | 2,402 | Revan |
77,006,235 | 5,759,881 | Route modules import | <p>I want to route a module import in python dynamically. See the example</p>
<pre><code>src
├── main.py
├── module1
│ └── lib.py
└── module2
└── lib.py
</code></pre>
<p>in main.py</p>
<pre><code>import src.module.lib
(... use the module...)
</code></pre>
<p>Imagine I have an env var <strong>$MODULE</strong>, if $MODULE=1, it will import <strong>module1</strong> if $MODULE=2 it will import <strong>module2</strong>.</p>
<p><strong>I cannot change main.py code!</strong></p>
<p>I believe adding a src/__init__.py is the way to go. What to do from here?</p>
<p>EDIT:</p>
<p>I bit more context to give more clarity on what's the real problem. <code>main.py</code> is actually a huge code base that should remain unchanged also because it would be counter-productive to add conditional importing to all files in the codebase and maintain it.</p>
<p>Therefore, I would like to be able to configure (by an environment variable, by file, by whatever) the behavior of module importing within <code>src</code> without changing the rest of the Python files. I assumed I could do this routing in <code>src/__init__.py</code>.</p>
| <python><module> | 2023-08-30 08:32:44 | 0 | 1,646 | Montenegrodr |
77,006,133 | 2,195,440 | Issue with running Starcoder Model on Mac M2 with Transformers library in CPU environment | <p>I'm attempting to run the Starcoder model on a Mac M2 with 32GB of memory using the Transformers library in a CPU environment. Despite setting load_in_8bit=True, I'm encountering an error during execution. Below is the relevant code:</p>
<pre><code>from transformers import AutoModelForCausalLM, AutoTokenizer
checkpoint = "bigcode/starcoder"
device = "cpu"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint,
device_map="auto",
load_in_8bit=True)
print(f"Memory footprint: {model.get_memory_footprint() / 1e6:.2f} MB")
inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device)
outputs = model.generate(inputs)
print(tokenizer.decode(outputs[0], clean_up_tokenization_spaces=False))
</code></pre>
<p>While running the above, I receive the following warning and exception:</p>
<pre><code>Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated.
Overriding torch_dtype=None with `torch_dtype=torch.float16` due to requirements of `bitsandbytes` to enable model loading in mixed int8.
Warning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.
Error:
ValueError:
Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
these modules in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom
`device_map` to `from_pretrained`.
</code></pre>
| <python><pytorch><huggingface-transformers><huggingface> | 2023-08-30 08:18:32 | 0 | 3,657 | Exploring |
77,006,126 | 19,500,571 | Merging dataframes on one column while replacing values with another column | <p>I have two dataframes:</p>
<pre><code>mapping = pd.DataFrame({'idx': ['a','b','c'], 'val': [1, 2, 3]})
obs = pd.DataFrame({'obs': ['a','c','a','a','b','d']})
</code></pre>
<p>I would like for all observations in <code>obs</code>, that are present in <code>mapping</code>s <code>idx</code> column, to get the value of <code>mapping</code>s <code>val</code> column. If the value does not exist in <code>mapping</code>s <code>idx</code> column, it should be discarded.</p>
<p>That is, I would like to end up with the following dataframe:</p>
<pre><code>obs_mapped = pd.DataFrame({'obs': [1,3,1,1,2]})
</code></pre>
<p>Is there a handy way to do this with pandas?</p>
| <python><pandas> | 2023-08-30 08:17:49 | 2 | 469 | TylerD |
77,006,058 | 4,050,510 | Differences between Protocol.__call__ vs Callable? | <p>I have a function</p>
<pre class="lang-py prettyprint-override"><code>def run_thing(cb: Callback) -> Result:
w: Widget = make_widget()
res: Result = cb(w)
return res
</code></pre>
<p>I can imagine two ways to define the Callback type.</p>
<pre class="lang-py prettyprint-override"><code># Option 1: Callable
# https://docs.python.org/3/library/typing.html#annotating-callables
Callback = typing.Callable[[Widget],Result]
</code></pre>
<pre class="lang-py prettyprint-override"><code># Option 2: Protocol
# https://docs.python.org/3/library/typing.html#typing.Protocol
class Callback(typing.Protocol):
def __call__(self,w: Widget) -> Result:
...
</code></pre>
<p>What are the nuances to consider in the decision between the two above type definitions?</p>
| <python><python-typing><callable> | 2023-08-30 08:09:13 | 2 | 4,934 | LudvigH |
77,005,993 | 5,224,236 | in kedro / pyspark how to use MemoryDataset | <p>I am trying to use a MemoryDataset with kedro, in order to not save the intermeiate result to disk.</p>
<pre><code># nodes.py
def preprocess_format_tracksessions(tracksess: DataFrame, userid_profiles:pd.DataFrame , parameters: Dict) -> MemoryDataset:
</code></pre>
<p>In the pipeline I am defining the node output and inputs:</p>
<pre><code># pipeline.py
def create_pipeline(**kwargs) -> Pipeline:
return pipeline([
node(
func=preprocess_format_tracksessions,
inputs= ["track_sessions", "userid_profiles", "parameters"],
outputs="ts_formatted",
name="preprocess_format_tracksessions",
),
node(
func=process_tracksessions,
inputs= ["ts_formatted", "parameters"],
outputs="results_summary",
name="process_format_tracksessions",
),
])
</code></pre>
<p>And in the catalog I am defining</p>
<pre><code>ts_formatted:
type: MemoryDataSet
</code></pre>
<p>But every time I get this error, surely because of my misunderstanding on how to proceed. Any help much appreciated:</p>
<pre><code>DatasetError: Failed while saving data to data set MemoryDataset().
It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation.
SparkContext can only be used on the driver, not in code that it run on workers. For more information, see
SPARK-5063.
</code></pre>
| <python><pyspark><kedro> | 2023-08-30 07:58:37 | 1 | 6,028 | gaut |
77,005,980 | 1,864,294 | Extent in cartopy | <pre><code>import matplotlib.pyplot as plt
from cartopy import crs as ccrs, feature as cfeature
import cartopy.io.shapereader as shpreader
fig = plt.figure(figsize=(11, 11))
ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=0))
ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--')
extent = (-180, 0, 0, 60) # Define the extent as (min_lon, max_lon, min_lat, max_lat)
ax.set_extent(extent)
ax.add_feature(cfeature.LAND , linewidth=0.5, edgecolor='black')
</code></pre>
<p>returns (as I would expect)</p>
<p><a href="https://i.sstatic.net/4HBl4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4HBl4.png" alt="enter image description here" /></a></p>
<p>As far as I understand, the extent</p>
<pre><code>extent = (-180, 60, 0, 60)
</code></pre>
<p>should limit the scope to the 60 degree east (indicated by the red line) but it doesn't:</p>
<p><a href="https://i.sstatic.net/nGwQD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nGwQD.png" alt="enter image description here" /></a></p>
<p>What am I doing wrong?</p>
| <python><cartopy> | 2023-08-30 07:56:30 | 1 | 20,605 | Michael Dorner |
77,005,909 | 111,424 | How do I test that a given shell has been executed in Python? | <p>I want to test a Python function that executes a shell command.</p>
<p>According to <a href="https://testfixtures.readthedocs.io/en/latest/popen.html" rel="nofollow noreferrer">testfixtures</a> there are two approaches:</p>
<ul>
<li>execute a real process and check the result</li>
<li>mock the subprocess module and check the expected interactions</li>
</ul>
<p>My function is called <code>run_in_shell</code>. Although the subprocess module is the obvious way to implement it, my function doesn't explicitly depend on it, so I'm trying to do the "real" test.</p>
<pre class="lang-py prettyprint-override"><code>import subprocess
def run_in_shell(command, shell_name=None):
"""Run command in default shell. Use named shell instead if given."""
subprocess.run(command, shell=True, executable=shell_name)
</code></pre>
<p>This test shows that the function can execute a command with the default shell.</p>
<pre class="lang-py prettyprint-override"><code>import pytest
def test_with_command_string(capfd):
run_in_shell("echo 'hello'")
cap = capfd.readouterr()
assert cap.out.strip() == "hello"
assert cap.err.strip() == ""
</code></pre>
<p>I also want to show that it can execute in the user's chosen shell such as <code>/bin/bash</code>.</p>
<p>The invocation is simple enough. This prints <code>hello</code> to the terminal.</p>
<pre class="lang-py prettyprint-override"><code>run_in_shell("echo 'hello'", shell_name="/bin/bash")
</code></pre>
<p>Without mocking, how do I show that it executed <code>/bin/bash</code> to do so?</p>
<p>I tried <a href="https://ptracer.readthedocs.io/en/latest/" rel="nofollow noreferrer">ptracer</a> to trace the system calls, but the output disappointed me.</p>
<pre class="lang-py prettyprint-override"><code>def callback(syscall):
name = syscall.name
args = ",".join([str(a.value) for a in syscall.args])
print(f"{name}({args})")
with ptracer.context(callback):
run_in_shell("echo 'hello'")
with ptracer.context(callback):
run_in_shell("echo 'hello'", shell_name="/bin/bash")
</code></pre>
<p>I was hoping to see a <code>clone</code> or <code>fork</code> call with the name of the shell, but there is nothing so clear. I don't understand the strings in the <code>read</code> calls, and I don't see any <code>write</code> calls.</p>
<pre><code>hello
pipe2((23, 24),524288)
clone(18874385,0,None,261939,0)
close(24)
read(23,bytearray(b'U\r\r\n'),50000)
close(23)
wait4(262130,0,0,None)
hello
pipe2((24, 25),524288)
clone(18874385,0,None,261939,0)
futex(2,129,1,0,9693984,9694016)
futex(0,129,1,0,None,9694016)
close(25)
read(24,bytearray(b'\x1d'),50000)
close(24)
wait4(262308,0,0,None)
</code></pre>
<p>At this point I'm out of my depth. I've surely misunderstood what the system calls are really doing. What am I missing?</p>
<p>Is it possible and practical to test this using Python and PyTest? If not, I'll redefine my function to depend explicitly on one of the subprocess functions, and then I can use a mock to test that it sends the right messages to the function.</p>
| <python><linux><pytest><ptrace> | 2023-08-30 07:46:28 | 2 | 21,216 | Iain Samuel McLean Elder |
77,005,545 | 9,202,041 | Data subsets from multiyear timeseries data | <p>I have 15 mins multiyear timeseries data (a total of 16 years) from 2007 - 2022. Data looks like <a href="https://docs.google.com/spreadsheets/d/1FJ0n-hAPvtr62ZXwaVTHBhsDiRLxYyX_/edit#gid=1159949573" rel="nofollow noreferrer">this</a>. I want to make all possible subsets out of this data. Each subset should have one year of values. so basically it should be 4 (15 mins) x24 (hours) x 365 or 366 days(leap year) = 35,040 row data or 35,136 a for leap year.</p>
<p>The subset should be formed in a way that it has 12 months from different years. So for example:</p>
<p>Jan from 2021 (all the 15 mins from a month should come all together in the subset)
Feb from 2018
Mar from 2012
Apr from 2015
May from 2009
Jun from 2014
Jul from 2022
Aug from 2010
Sep from 2015
Oct from 2020
Nov from 2018
Dec from 2007
It's fine to have two months from same year as well.</p>
<p>Please help me how can I move forward.</p>
<p>here's my code for reading data so far:</p>
<pre><code>import pandas as pd
import numpy as np
columns_to_read = ['DateTime', 'PLANT ENERGY MWh']
df = pd.read_excel(r'C:/Users/97150/Data - 15 mins multiyear -R2.xlsx', skiprows=0, usecols=columns_to_read)
df['DateTime'] = pd.to_datetime(df['DateTime'])
df.dropna(subset=['DateTime'], inplace=True)
df['Month'] = df['DateTime'].dt.month.astype(int)
df['Year'] = df['DateTime'].dt.year.astype(int)
#df['Month'] = df['DateTime'].dt.month
#df['Year'] = df['DateTime'].dt.year
df.set_index('DateTime', inplace=True)
</code></pre>
| <python><dataframe><subset><permutation> | 2023-08-30 06:49:03 | 1 | 305 | Jawairia |
77,005,457 | 1,117,103 | PDFtron low level text extractore gly issue | <p>Base problem: The PDFTron lib font.MapToUnicode return wrong case character.</p>
<p>Details: This is happens in particular book the snap are attached below, there are few character are getting in lower case but char.char_code is for upper case. as per my knowledge the font character and gly mapping having a problem. please go through the code and file and let me help in this case</p>
<p><a href="https://drive.google.com/file/d/1woZv6vGH5Gub6uzwsCIC7Hf5iGQgiqJC/view?usp=sharing" rel="nofollow noreferrer">pdf_file_prob_char</a></p>
<p>environment:
PDFNetPython3 lib vr : 9.4.2</p>
<p>Original PDF has some capital letters, but we get small letter as character
PDF text is capital 'O' but PDFTron text-extractor gives small 'o'</p>
<p>snap of pdf :</p>
<p><a href="https://i.sstatic.net/BNUo5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BNUo5.png" alt="enter image description here" /></a></p>
<p>code :</p>
<pre><code>from PDFNetPython3.PDFNetPython import PDFNet, PDFDoc, ElementReader, Element, Point
from PDFNetPython3.PDFNetPython import Font, GState, ColorSpace, PatternColor, PathData
</code></pre>
<p>class CharFromPDF:</p>
<pre><code>def __init__(self):
pass
def print_char_from_pdf(self, pdf_file_path):
PDFNet.Initialize("demo:1691991990538:7c56930b030000000055aed6bf8e4eb6a00bb237070a3797ee21cafe95")
doc = PDFDoc(pdf_file_path)
doc.InitSecurityHandler()
page_begin = doc.GetPageIterator()
page_reader = ElementReader()
itr = page_begin
while itr.HasNext():
page_reader.Begin(itr.Current())
self.process_elements(page_reader)
page_reader.End()
itr.Next()
doc.Close()
PDFNet.Terminate()
print("Done.")
def process_path(self, reader, path):
gs = path.GetGState()
gs_itr = reader.GetChangesIterator()
while gs_itr.HasNext():
if gs_itr.Current() == GState.e_fill_color:
if (gs.GetFillColorSpace().GetType() == ColorSpace.e_pattern and
gs.GetFillPattern().GetType() != PatternColor.e_shading):
reader.PatternBegin(True)
self.process_elements(reader)
reader.End()
gs_itr.Next()
reader.ClearChangeList()
def process_text(self, page_reader):
# Begin text element
element = page_reader.Next()
while element is not None:
element_type = element.GetType()
if element_type == Element.e_text_end:
return
elif element_type == Element.e_text:
gs = element.GetGState()
font = gs.GetFont()
if font.GetType() == Font.e_Type3:
itr = element.GetCharIterator()
while itr.HasNext():
page_reader.Type3FontBegin(itr.Current())
self.process_elements(page_reader)
page_reader.End()
else:
itr = element.GetCharIterator()
while itr.HasNext():
char_code = itr.Current().char_code
a = font.MapToUnicode(char_code)
print("Char: ", a[0], " ascii code: ", ascii(a[0]), "char_code", char_code,
" Font Name: ", font.GetName())
itr.Next()
print("")
element = page_reader.Next()
def process_elements(self, reader):
element = reader.Next()
while element is not None:
element_type = element.GetType()
if element_type == Element.e_path:
self.process_path(reader, element)
elif element_type == Element.e_text_begin:
self.process_text(reader)
elif element_type == Element.e_form:
reader.FormBegin()
self.process_elements(reader)
reader.End()
element = reader.Next()
if __name__ == "__main__":
cfp = CharFromPDF()
input_file_path = "text_issue.pdf"
cfp.print_char_from_pdf(pdf_file_path=input_file_path)
</code></pre>
<p>In above example you find the font.MaptoUnicode the character code for "o" is capital case but function return small case letter</p>
<p>we try the textextracter as well from same lib but the return vise versa out but as text.</p>
| <python><pdf><pdfnet> | 2023-08-30 06:32:58 | 1 | 1,317 | Damodhar |
77,005,442 | 13,801,302 | Pass a word2vec model from gensim package to langchain FAISS vectorstore | <p>I want to pass my trained gensim word2vec model as an embedding model to <code>FAISS.from_documents()</code>. Thereby I get an error</p>
<blockquote>
<p>AttributeError: 'Word2Vec' object has no attribute 'embed_documents'</p>
</blockquote>
<p>My code:</p>
<pre class="lang-py prettyprint-override"><code>
w2v_model = Word2Vec(sentences=list_pre_word2vec)
# # #
# # # some training magic for Word2Vec
# # #
from langchain.vectorstores import FAISS
# storing embeddings in the vector store
vectorstore = FAISS.from_documents(clean, w2v_model)
</code></pre>
<p><code>clean</code> is list of langchain documents.</p>
<p>How can I pass my word2vec model as an embedding model to <code>FAISS.from_documents()</code>, how can I use the model in langchain? Is this an recommended approach or is there a better (easier, more efficient) way?</p>
<p>Thanks in forward.</p>
| <python><gensim><word2vec><langchain> | 2023-08-30 06:30:54 | 1 | 621 | Christian01 |
77,005,242 | 2,988,730 | Combining use of `choices` and `action='extend'` in argparse | <p>I ran into a corner case with <code>choice</code> in <code>argparse</code>, when used in conjunction with <code>action='extend'</code>, introduced in python 3.8:</p>
<pre><code>from argparse import ArgumentParser
parser = ArgumentParser('test')
parser.add_argument('-x', '--x', action='extend', choices=list('XYZ'), type=list)
parser.parse_args(['-x', 'XXYYZZ'])
</code></pre>
<p>My expectation (perhaps desire) is that each element of <code>['X', 'X', 'X', 'Y', 'Y', 'Z', 'Z']</code> get checked (successfully) against <code>choices</code>. Instead, the following error message is printed:</p>
<pre><code>usage: test [-h] [-x {X,Y,Z}]
test: error: argument -x/--x: invalid choice: ['X', 'X', 'Y', 'Y', 'Z', 'Z'] (choose from 'X', 'Y', 'Z')
</code></pre>
<p>Is there a way to apply <code>choices</code> to each element of an iterable with <code>action='extend'</code> instead of the entire thing? FWIW, this works fine if I allow multiple instances of <code>-x</code> and use <code>action='append'</code> instead...</p>
| <python><argparse> | 2023-08-30 05:48:23 | 2 | 115,659 | Mad Physicist |
77,004,987 | 736,662 | Setting a random value from a list in Python | <p>Basic question, but how do I pick random values from this list:</p>
<pre><code>TS_IDs = {
'69397': 30,
'10259': 30,
'87104': 30
}
</code></pre>
<p>Using this function:</p>
<pre><code>def set_ts_id_random():
ts_id_random = <here I want to pick a random value>
print("random_ts_id:", ts_id_random)
return ts_id_random
</code></pre>
| <python><locust> | 2023-08-30 04:27:40 | 1 | 1,003 | Magnus Jensen |
77,004,983 | 1,657,457 | How to remove text from image (not inpainting but just solid color over the text) | <p>I have the following Python code that finds the text in a image, and uses cv2.inpaint to remove that text by covering with generated background, but I just want to put solid color over the text instead generating the background.</p>
<pre><code>import matplotlib.pyplot as plt
import keras_ocr
import cv2
import math
import numpy as np
def inpaint_text(img_path, pipeline):
img = keras_ocr.tools.read(img_path)
prediction_groups = pipeline.recognize([img])
inpainted_img = ""
mask = np.zeros(img.shape[:2], dtype="uint8")
for box in prediction_groups[0]:
x0, y0 = box[1][0]
x1, y1 = box[1][1]
x2, y2 = box[1][2]
x3, y3 = box[1][3]
points = np.array([[x0, y0], [x1, y1], [x2, y2],[x3, y3]])
cv2.fillPoly(mask,np.int32([points]), 255)
inpainted_img = cv2.inpaint(img, mask, 0, cv2.INPAINT_NS)
return(inpainted_img)
pipeline = keras_ocr.pipeline.Pipeline()
img_text_removed = inpaint_text('image.png', pipeline)
plt.imshow(img_text_removed)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('result.png', cv2.cvtColor(img_text_removed, cv2.COLOR_BGR2RGB))
</code></pre>
<p>This is what I want to achieve (put solid color over the text):</p>
<p><a href="https://i.sstatic.net/1n8AG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1n8AG.png" alt="enter image description here" /></a></p>
| <python><opencv><keras><ocr> | 2023-08-30 04:26:44 | 0 | 968 | dexter00x |
77,004,957 | 4,212,875 | What datatype is considered 'list-like' in Python? | <p>In the Pandas documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="noreferrer">here</a> for <code>Series.isin(values)</code>, they state:</p>
<blockquote>
<p>values : set or list-like</p>
</blockquote>
<p>What is considered list-like? For a Python dictionary <code>temp_dict</code>, would <code>temp_dict.keys()</code> and <code>temp_dict.values()</code> be considered list-like?</p>
| <python><python-3.x><pandas><dictionary> | 2023-08-30 04:17:01 | 2 | 411 | Yandle |
77,004,459 | 1,914,781 | find duplicates and list values as columns | <p>I would like to find duplicates and list values as columns.</p>
<p>Example,</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
[
['A',1],
['B',2],
['C',3],
['D',4],
['E',5],
['C',6],
['D',7],
['E',8],
['F',9],
['G',10]
],columns=['name','value'])
df = df[df.duplicated(['name'], keep=False)]
print(df)
</code></pre>
<p>Current output is:
:</p>
<pre><code> name value
: 2 C 3
: 3 D 4
: 4 E 5
: 5 C 6
: 6 D 7
: 7 E 8
</code></pre>
<p>expected output:</p>
<pre><code>: name value1 value2
: 2 C 3 6
: 3 D 4 7
: 4 E 5 8
</code></pre>
| <python><pandas> | 2023-08-30 01:23:57 | 5 | 9,011 | lucky1928 |
77,004,443 | 5,374,289 | Timers and user events (PyGame) | <p>My game is essentially flappy bird but with enemies, ammo (goatee's), and also flies instead of flaps (That part isn't necessary). I'm trying to figure out how to spawn the pipes in, the goatee's (ammo for the player to collect), and also the enemies. I've just learned about <code>pygame.time.set_timer()</code> today and I set it up with my pipes and it worked perfectly! That was until I created the goatee timer and then quickly found out that it won't set 2 separate timers. After looking over PyGames documentation I found this -</p>
<blockquote>
<p>It is also worth mentioning that a particular event type can only be put on a timer once. In other words, there cannot be two timers for the same event type. Setting an event timer for a particular event discards the old one for that event type.</p>
</blockquote>
<p>I've looked around and have not been able to find a way around this. Is there a way to create another event type? Is there a different way I should be using timers? Code listed below shows how I'm creating them:</p>
<p>Creating the timers:</p>
<pre><code> SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, 3000)
SPAWNGOATEE = pygame.USEREVENT
pygame.time.set_timer(SPAWNGOATEE, 6000)
</code></pre>
<p>Event handling inside the while loop:</p>
<pre><code>#All game events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not time_started:
is_playing = True
time_started = True
start_time = time.time()
if event.type == SPAWNPIPE:
spawn_pipe = True
if event.type == SPAWNGOATEE:
spawn_goatee = True
</code></pre>
<p>Even though pipe timer is set to 3000 milliseconds, they spawn at 6000 milliseconds because USEREVENT can only be used for one timer so the second one created overrides the first</p>
| <python><events><timer><pygame> | 2023-08-30 01:20:17 | 1 | 333 | Trevn Jones |
77,004,157 | 2,981,639 | Use of poetry dynamic version with non-package project for idempotent build | <p>I'm using poetry to manage a python project that's not a package (it's a machine learning model). I have a bash <code>build.sh</code> script that contains multiple stages (train, test, package, install).</p>
<p>I added <code>poetry-dynamic-version</code> in order to add a version to the assets that are created when I run the build script. The problem is it generates the version from the latest git tag and any commits since the last tag, updates the <code>pyproject.toml</code> and because this file is tracked it needs to be committed which changes the generated version (i.e. the build script is not idempotent).</p>
<p>How do I use <code>poetry-dynamic-version</code> so this doesn't happen, my <code>pyproject.toml</code> looks like:</p>
<pre><code>[tool.poetry]
name = "warpspeed-multiclass-model"
version = "0.5.dev25+0263834"
[build-system]
requires = ["poetry-core", "poetry-dynamic-versioning"]
build-backend = "poetry_dynamic_versioning.backend"
[tool.poetry-dynamic-versioning]
enable = true
vcs = "git"
style = "pep440"
</code></pre>
<p>In my script</p>
<pre class="lang-bash prettyprint-override"><code># Update version
poetry dynamic-versioning
MODEL_VERSION=$(poetry version --short --ansi)
export MODEL_VERSION
</code></pre>
<p>Previously I used <code>setuptools-scm</code> which tracks the version in a separate (untracked) file so this issue didn't occur.</p>
| <python><version><python-poetry> | 2023-08-29 23:35:22 | 0 | 2,963 | David Waterworth |
77,004,048 | 1,484,601 | how to use the H264 video encoder with ffmpeg / opencv2? | <p>I am on ubuntu 22.04.</p>
<p>I installed ffmpeg with apt.</p>
<p>I am creating a video from some image files using python/opencv2 (installed via pip)</p>
<p>When I use:</p>
<pre class="lang-py prettyprint-override"><code>cv2.VideoWriter_fourcc(*"mp4v")
</code></pre>
<p>the video is successfully created, but is not supported by firefox.</p>
<p>I read online that the H264 encoder would be a better fit for web-browsers supports.</p>
<pre><code>ffmpeg -codecs | grep h264
</code></pre>
<p>shows:</p>
<blockquote>
<p>DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_v4l2m2m h264_qsv h264_cuvid ) (encoders: libx264 libx264rgb h264_nvenc h264_omx h264_qsv h264_v4l2m2m h264_vaapi nvenc nvenc_h264 )</p>
</blockquote>
<p>but</p>
<pre><code>cv2.VideoWriter_fourcc(*"h264")
</code></pre>
<p>results in:</p>
<blockquote>
<p>OpenCV: FFMPEG: tag 0x34363268/'h264' is not supported with codec id 27 and format 'mp4 / MP4 (MPEG-4 Part 14)'</p>
</blockquote>
<p>I could not find online what was wrong (h264 is not installed, how to install it? the 'fourcc' of h264 is not 'h264' ? I should not create a *.mp4 file ?)</p>
| <python><opencv><ffmpeg><h.264><codec> | 2023-08-29 22:57:51 | 1 | 4,521 | Vince |
77,003,982 | 3,973,175 | How to plot color of line segments according to a 3rd value | <p>I've gotten the following python3 code that generates line segments</p>
<pre><code>import numpy as np
import pylab as pl
from matplotlib import collections as mc
from matplotlib.colors import to_rgba # https://matplotlib.org/2.0.2/api/colors_api.html#matplotlib.colors.to_rgba
#https://stackoverflow.com/questions/21352580/matplotlib-plotting-numerous-disconnected-line-segments-with-different-colors
# to_rgba('violet')
lines = [
[(0, 1), (1, 1)],
[(2, 3), (3, 3)],
[(1, 2), (1, 3)]
]
colors = [
(1,0,0,1), # red
(0,1,0,1), # green
(0,0,1,1), # blue
]
z = [1,2,3]
c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])
lc = mc.LineCollection(lines, colors=('r','g','b'), linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
fig.savefig('line.segments.svg', bbox_inches='tight', pad_inches = 0.05)
</code></pre>
<p>I've been reading through <a href="https://stackoverflow.com/questions/21352580/matplotlib-plotting-numerous-disconnected-line-segments-with-different-colors">Matplotlib: Plotting numerous disconnected line segments with different colors</a> and <a href="https://stackoverflow.com/questions/9283988/matplotlib-assign-colors-to-lines">Matplotlib: Assign Colors to Lines</a> as well as documentation.</p>
<p>However, I would like to color the line segments according to the index of <code>z</code>. Line at element <code>e</code> would have the color set by the value of <code>z[e]</code>. This is like how a scatterplot would be plotted with color as a 3rd dimension. Similar to this page, <a href="https://www.statology.org/matplotlib-scatterplot-color-by-value/" rel="nofollow noreferrer">https://www.statology.org/matplotlib-scatterplot-color-by-value/</a>, but with line segments, not a scatterplot.</p>
<p>The idea is to set a scale, so that the minimum of <code>z</code> would count as one end of the <code>coolwarm</code> colormap, and that the maximum of <code>z</code> would count as the max. And a colorbar would be plotted on the right side of the plot, so that the color could be mapped to <code>z</code>.</p>
<p>How can I do so?</p>
| <python><matplotlib> | 2023-08-29 22:38:22 | 1 | 6,227 | con |
77,003,904 | 8,028,576 | How to add stacked x-axis labels to stacked bar chart | <p>Given the following code:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
from itertools import groupby
import pandas as pd
percent_EVs = [0, 8, 21, 26, 37, 39, 41, 75, 95, 97]
percent_DVs = [100, 92, 79, 74, 63, 61, 59, 25, 5, 3]
num_buses = [1423, 1489, 1613, 1606, 1710, 1684, 1694, 2153, 2202, 2195]
veh_range = ['DV only', 60, 120, 150, 60, 120, 150, 60, 120, 150]
deployment = ['DV only', 'Low', 'Medium', 'High', 'Low', 'Medium', 'High', 'Low', 'Medium', 'High']
df = pd.DataFrame({'Percent EVs': percent_EVs, 'Percent DVs': percent_DVs,
'# Buses': num_buses, 'Range (mi)':veh_range,
'Deployment target': deployment})
df.set_index('Range (mi)', inplace=True)
def add_line(ax, xpos, ypos):
line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
transform=ax.transAxes, color='black')
line.set_clip_on(False)
ax.add_line(line)
def label_len(my_index,level):
labels = my_index.get_level_values(level)
return [(k, sum(1 for i in g)) for k,g in groupby(labels)]
def label_group_bar_table(ax, df):
ypos = -.1
scale = 1./df.index.size
for level in range(df.index.nlevels)[::-1]:
pos = 0
for label, rpos in label_len(df.index,level):
lxpos = (pos + .5 * rpos)*scale
ax.text(lxpos, ypos, label, ha='center', transform=ax.transAxes)
add_line(ax, pos*scale, ypos)
pos += rpos
add_line(ax, pos*scale , ypos)
ypos -= .1
fig = plt.figure()
ax = fig.add_subplot(111)
#Your df.plot code with ax parameter here
df.plot.bar(stacked=True, rot=0, alpha=0.5, legend=False, ax=fig.gca())
labels = ['' for item in ax.get_xticklabels()]
ax.set_xticklabels(labels)
ax.set_xlabel('')
label_group_bar_table(ax, df)
fig.subplots_adjust(bottom=.2*df.index.nlevels, left=0.1*df.index.nlevels)
plt.show()
</code></pre>
<h3>Current</h3>
<p>The resulting plot is nothing nearby the desired output. How can I at least change the x-axis labels to imitate the desired output?</p>
<p><a href="https://i.sstatic.net/j70z5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/j70z5.png" alt="enter image description here" /></a></p>
<h3>Desired x-axis</h3>
<p>Looking <a href="https://stackoverflow.com/questions/19184484/how-to-add-group-labels-for-bar-charts/39502106#39502106">here</a>, I tried to create the following chart:</p>
<p><a href="https://i.sstatic.net/Nb1ag.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Nb1ag.png" alt="enter image description here" /></a></p>
| <python><matplotlib><x-axis> | 2023-08-29 22:09:50 | 1 | 592 | tcokyasar |
77,003,897 | 6,440,589 | How to automatically adjust the position of a layout image using plotly? | <p>I am trying to add a logo to a <strong>plotly</strong> figure that I then save as a <strong>html</strong> file.</p>
<p>I adjusted the x and y coordinates to display the logo in the top left corner of my html page.</p>
<p><a href="https://i.sstatic.net/V8DdK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/V8DdK.png" alt="enter image description here" /></a></p>
<p>However, when I open the same html file from a computer whose screen has a higher resolution, the logo is cropped:</p>
<p><a href="https://i.sstatic.net/go26s.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/go26s.png" alt="enter image description here" /></a></p>
<p>Here is a MRE:</p>
<pre><code>from PIL import Image
import plotly.graph_objects as go
def create_report():
WeylandLogo = Image.open("Weyland.jpg")
fig = go.Figure()
fig.add_layout_image(
dict(
source=WeylandLogo,
xref="paper", yref="paper",
x=0, y=1.05,
sizex=0.2, sizey=0.2,
xanchor="left", yanchor="bottom"
)
)
fig.write_html("cornbread.html")
create_report()
</code></pre>
<p>According to <a href="https://plotly.com/python/reference/layout/annotations/#layout-annotations-items-annotation-xref" rel="nofollow noreferrer">plotly's website</a>, setting <code>xref</code> and <code>yref</code> to <code>paper</code> allows to use "normalized" coordinates.</p>
<blockquote>
<p>If set to "paper", the <code>x</code> position refers to the distance from the
left of the plotting area in normalized coordinates where "0" ("1")
corresponds to the left (right).</p>
</blockquote>
<p>I thought that this would automatically adjust the position of the logo, but apparently this is not the case. What parameters should I use?</p>
| <python><html><plotly><graphical-logo> | 2023-08-29 22:08:19 | 0 | 4,770 | Sheldon |
77,003,629 | 13,801,302 | How to train gensim word2vec and check if the training was succesful? | <p>I want to train a word2vec model with gensim package. There are several approaches online how to train the model. In my case I have 500 finance reports as pdf-file with about 300 pages per file in german language.</p>
<p>Currently, my codes looks like this:</p>
<pre class="lang-py prettyprint-override"><code>w2v_model = Word2Vec(sentences=list_pre_word2vec,
min_count=20,
window=2,
vector_size=100,
sample=6e-5,
alpha=0.03,
min_alpha=0.0007,
negative=20,
workers=cores-1)
w2v_model.build_vocab(list_pre_word2vec, progress_per=10000)
w2v_model.train(list_pre_word2vec, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)
</code></pre>
<p>This code create some questions:</p>
<ol>
<li>Is that the right approach? I don't understand in depth what is going on in this code and I'm a bit unconfident if it is works. Maybe you can explain what's going.</li>
<li>How do I know if the training was successful? Are there some attributes, metrics or something else to confirm it?</li>
</ol>
| <python><word2vec><word-embedding> | 2023-08-29 21:02:22 | 1 | 621 | Christian01 |
77,003,563 | 308,827 | Isinstance returning incorrect answer | <p>I have the following variable:</p>
<p><code>ar</code> with the value <code>datetime.date(2000, 3, 1)</code></p>
<p>However when I try to check if it is datetime, like so <code>isinstance(ar, datetime)</code> it returns False.</p>
<p>How is that possible? When I try <code>type(ar)</code>, I get <code><class 'datetime.date'></code></p>
| <python><datetime> | 2023-08-29 20:50:36 | 1 | 22,341 | user308827 |
77,003,423 | 11,686,518 | Class error, using __new__ , instead of __init__, trying to return value | <p><strong>Description</strong>:</p>
<p>I am trying to return a value from a class when I call it.</p>
<p>I want the result of an object's method call upon creating the object.</p>
<p>I want to get the value of:</p>
<pre class="lang-py prettyprint-override"><code>A().get_result()
# by just calling"
A()
</code></pre>
<p><strong>My Question</strong>:</p>
<p>Why does <code>A.get_result()</code> require the argument <code>self</code>?</p>
<p><strong>Minimal Reproducible Example</strong>:</p>
<p>Using the following class definition:</p>
<pre class="lang-py prettyprint-override"><code>class A():
_arg_list = None
def __new__(self, my_args):
self._arg_list = my_args
return self.get_result()
def get_result(self):
return self._args_list[0]
</code></pre>
<p><strong>Current Result</strong>:</p>
<pre><code>A(['arg1','arg2'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 1
----> 1 A(['arg1','arg2'])
Cell In[5], line 9, in A.__new__(self, my_args)
5 def __new__(self, my_args):
7 self._arg_list = my_args
----> 9 return self.get_result()
TypeError: A.get_result() missing 1 required positional argument: 'self'
</code></pre>
<p><strong>Desired Result</strong>:</p>
<pre><code>A(['arg1','arg2'])
>> 'arg1'
</code></pre>
| <python><python-3.x><class> | 2023-08-29 20:21:40 | 2 | 1,633 | Jesse Sealand |
77,003,345 | 10,994,166 | Pick n random records with same index from 2 different list column pyspark | <p>Hi I have dataframe like this:</p>
<pre><code>cc doc_1 doc_2
4 [a, b,..] [1, 6,..]
9 [t, s,..] [4, 5,..]
4 [q, f,..] [6, 7,..]
</code></pre>
<p>I want to pick <code>n(1/2 of cc col)</code> random records from both the col <code>doc_1</code> <code>doc_2</code> with same index value. I can use <code>f.rand()</code> to pick 1 record from column but I'm not sure how I'll pick multiple records with same index from different column as well</p>
<p>Expected Output has randomly picked value in column</p>
<pre><code>doc_1 doc_2
</code></pre>
<pre><code>cc doc_1 doc_2
4 [c, f] [5, 3]
9 [s, g,..](4 records) [6, 5,..](4 records)
4 [r, g] [7, 9]
</code></pre>
| <python><pyspark><random><apache-spark-sql> | 2023-08-29 20:05:22 | 1 | 923 | Chris_007 |
77,003,220 | 9,749,124 | Add text and image to MultiColumnLayout in borb library | <p>I am new to this library.
I want to create "newspaper lookalike" page with this library.</p>
<p>I want to add headline, lead, text and image to the pdf file. Text is very long so i want to use MultiColumnLayout.
I also want to set up the margins and spacing between the columns.
Are there any explanations, code snippets for this?
When every I copy/paste the code that I find on the internet, I get some kind of error, like code is updated.</p>
<p>I have this code, but I do not have a clue how to add text, margins, column spacing or even image:</p>
<pre><code>from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import PageLayout
from borb.pdf import MultiColumnLayout
# create an empty PDF
Document = Document()
# create an empty Page
Page = Page()
doc.add_page(page)
# set a PageLayout
PageLayout = MultiColumnLayout(page,
column_widths=[w - Decimal(100)],
margin_top=Decimal(50),
margin_right=Decimal(50),
margin_bottom=Decimal(50),
margin_left=Decimal(50),
)
</code></pre>
| <python><borb> | 2023-08-29 19:41:13 | 1 | 3,923 | taga |
77,003,180 | 14,555,505 | Numpy assignment on *1D* chained indices like `arr[mask][range:]` | <p>As an <a href="https://stackoverflow.com/help/minimal-reproducible-example">MRE</a>, let's say I have an array of numbers <code>arr</code>. I then want to extract certain elements from <code>arr</code> (based on a boolean mask), and set only the first <code>n</code> of those extracted elements to zero.</p>
<p>I'd expect to be able to do this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
# Just an example array of numbers [20, 21, ..., 40]
arr = np.linspace(20, 40, 21)
# A mask selecting all numbers less than 25
mask = arr < 25
# As an example, only take the first 5 values
n = 5
# Attempt to set the first `n` values matching the `mask` to zero
arr[mask][:n] = 0
# It doesn't work
print(arr)
# array([20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32.,
# 33., 34., 35., 36., 37., 38., 39., 40.])
</code></pre>
<p>It doesn't work, none of the values have been set to zero. I'm guessing this is related/similar to the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-view-versus-copy" rel="nofollow noreferrer">pandas chained indices and assignment issue</a>.</p>
<p>In this particular example, it's easy-ish to get around the problem with <code>np.nonzero</code>:</p>
<pre class="lang-py prettyprint-override"><code>indices = np.nonzero(mask)[0]
arr[indices[:n]] = 0
print(arr)
# array([ 0., 0., 0., 0., 0., 25., 26., 27., 28., 29., 30., 31., 32.,
# 33., 34., 35., 36., 37., 38., 39., 40.])
</code></pre>
<p>But I couldn't actually find anything about numpy not allowing/not working with chained indices and assignments, so I wanted to see if there was a better way? Or if I was making a mistake and these sorts of chained-indices-and-assignments are actually possible.</p>
| <python><numpy><indexing><variable-assignment> | 2023-08-29 19:34:48 | 0 | 1,163 | beyarkay |
77,002,897 | 223,960 | How do I use flask_sqlalchemy and a GCP TLS protected DB connector? | <p>I'd like to use flask_sqlalchemy with GCP's db connector which does automatic TLS setup as described here: <a href="https://cloud.google.com/sql/docs/postgres/connect-connectors#python_1" rel="nofollow noreferrer">https://cloud.google.com/sql/docs/postgres/connect-connectors#python_1</a></p>
<p>I tried their example code on my laptop with credentials set via GOOGLE_APPLICATION_CREDENTIALS and it worked. It was able to connect to the remote DB on GCP, I checked that it was TLS encrypted with wireshark, it successfully queried data from the DB. I ran that with sqlalchemy 1.4.47.</p>
<p>I want to use the GCP connector with a flask + flask_sqlalchemy app that uses SQLALCHEMY_BINDS. Using sqlalchemy 1.4.47 flask_sqlalcehmy 2.5.1 and code like this:</p>
<pre><code>...
from flask_sqlalchemy import SQLAlchemy
from google.cloud.sql.connector import Connector, IPTypes
import pg8000
...
db: SQLAlchemy = SQLAlchemy()
def create_web_app():
app = Flask('ex')
...
ip_type = IPTypes.PUBLIC
connector = Connector()
def getconn() -> pg8000.dbapi.Connection:
conn: pg8000.dbapi.Connection = connector.connect(
app.config["GCPTSLPROTECTED_INSTANCE_CONNECTION_NAME"],
"pg8000",
user=app.config["GCPTSLPROTECTED_DB_USER"],
password=app.config["GCPTSLPROTECTED_DB_PASS"],
db=app.config["GCPTSLPROTECTED_DB_NAME"],
ip_type=ip_type,
)
return conn
app.config["SQLALCHEMY_BINDS"] = {
"gcptslprotected": {
# This URI looks funny but is what GCP docs request and works in the test script
"url": make_url("postgresql+pg8000://"),
"creator": getconn }
}
...
# SQLALCHEMY_URI for a default db connection also gets created and works fine
app.config['SQLALCHEMY_URI'] = "sqlite:///./tests/data/test.db"
db.init_app(app)
...
</code></pre>
<p>The above code runs fine but then a route in the flask app uses the DB this this error is raised:</p>
<pre><code>File "/home/bdc34/.pyenv/versions/browse310/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 516, in create_engine
u, plugins, kwargs = u._instantiate_plugins(kwargs)
AttributeError: 'dict' object has no attribute '_instantiate_plugins'
</code></pre>
<p>You might notice that I use make_url() where as the GCP example script does not have that. I did that to get around an exception raised by flask_sqlalchemy function <code>apply_driver_hacks()</code> which is not the most confidence inspiring name.</p>
| <python><google-cloud-platform><sqlalchemy><flask-sqlalchemy> | 2023-08-29 18:48:49 | 2 | 8,190 | Brian C. |
77,002,854 | 4,876,561 | Formatting hierarchical matches - Pandas | <p>(Note, I have not set the requirements for this)</p>
<p>I have two dataframes, here is a sample of <code>dataframe1</code>:</p>
<pre><code>| Key | Description | Type |
|------|-------------|-----------------------------|
| 0 | No Dept | No Dept |
| 1110 | RSF | Real Scripting Fairness |
| 1160 | JSA | Job Security Administration |
</code></pre>
<p>Here is a sample of <code>dataframe2</code>:</p>
<pre><code>| Level 5 | Level 4 | Level 3 | Level 2 | Level 1 | Description2 |
|---------|---------|---------|---------|---------|-------------|
| | | | | | All Dept |
| | 0000 | | | | No Dept |
| | 1000 | | | | P AND P |
| | | 1100 | | | rsf |
| | | | 1110 | | RSF |
| | | 1150 | | | JSA |
| | | | 1160 | | JSA |
| | | 1200 | | | MLF |
</code></pre>
<p>The idea is as follows:</p>
<ol>
<li>For each key in <code>dataframe1</code>, search for it in Levels 1-4 of <code>dataframe2</code></li>
<li>If there is a match, copy over the corresponding <code>Description2</code>, <strong>as well as the other levels in the hierarchy</strong></li>
</ol>
<p>So for example, using the entirety of the first dataframe:</p>
<pre><code>| | Key | Desc | Type | Description2 | Level 1 | Level 2 | Level 3 | Level 4 | |
|---|--------|--------|-----------------------------|----------------|-----------|-----------|-----------|------------|---|
| | ------ | ------ | ------------------------- | -------------- | --------- | --------- | --------- | ---------- | |
| | 1110 | RSF | Real Scripting Fairness | RSF | | 1110 | | | |
| | | | | rsf | | | 1100 | | |
| | | | | P AND P | | | | 1000 | |
| | 1160 | JSA | Job Security Administration | JSA | | 1160 | 1150 | | |
</code></pre>
<p>Then, repeat this logic for each key in <code>dataframe1</code>.</p>
<p>How can I accomplish this?</p>
<p>For testing:</p>
<pre><code>dataframe1 = [
{"Key": 0, "Description": "No Dept", "Type": "No Dept"},
{"Key": 1110, "Description": "RSF", "Type": "Real Scripting Fairness"},
{"Key": 1160, "Description": "JSA", "Type": "Job Security Administration"}
]
dataframe2 = [
{"Level 5": None, "Level 4": None, "Level 3": None, "Level 2": None, "Level 1": None, "Description2": "All Dept"},
{"Level 5": None, "Level 4": "0000", "Level 3": None, "Level 2": None, "Level 1": None, "Description2": "No Dept"},
{"Level 5": None, "Level 4": "1000", "Level 3": None, "Level 2": None, "Level 1": None, "Description2": "P AND P"},
{"Level 5": None, "Level 4": None, "Level 3": "1100", "Level 2": None, "Level 1": None, "Description2": "rsf"},
{"Level 5": None, "Level 4": None, "Level 3": None, "Level 2": "1110", "Level 1": None, "Description2": "RSF"},
{"Level 5": None, "Level 4": None, "Level 3": "1150", "Level 2": None, "Level 1": None, "Description2": "JSA"},
{"Level 5": None, "Level 4": None, "Level 3": None, "Level 2": "1160", "Level 1": None, "Description2": "JSA"},
{"Level 5": None, "Level 4": None, "Level 3": "1200", "Level 2": None, "Level 1": None, "Description2": "MLF"}
]
resulting_df = [
{'Key': '1110', 'Desc': 'RSF', 'Type': 'Real Scripting Fairness', 'Description2': 'RSF', 'Level 1': nan, 'Level 2': '1110', 'Level 3': nan, 'Level 4': nan},
{'Key': nan, 'Desc': nan, 'Type': nan, 'Description2': 'rsf', 'Level 1': nan, 'Level 2': nan, 'Level 3': '1100', 'Level 4': nan},
{'Key': nan, 'Desc': nan, 'Type': nan, 'Description2': 'P AND P', 'Level 1': nan, 'Level 2': nan, 'Level 3': nan, 'Level 4': '1000'},
{'Key': '1160', 'Desc': 'JSA', 'Type': 'Job Security Administration', 'Description2': 'JSA', 'Level 1': nan, 'Level 2': '1160', 'Level 3': '1150', 'Level 4': nan}
]
</code></pre>
| <python><pandas><format><hierarchy> | 2023-08-29 18:41:35 | 0 | 7,351 | artemis |
77,002,768 | 2,514,130 | How to filter a Polars DataFrame with list type columns? | <p>My Polars DataFrame contains columns with list type values:</p>
<pre><code>df = pl.DataFrame({
'a': [['1', '3'], ['3'], ['1'], ['2']],
'b':[['8'],['6'],['6', '7'],['7']]
})
</code></pre>
<p>I want to filter this DataFrame based on the 'a' column containing the list ['1']. I tried using:</p>
<pre><code>df.filter(pl.col('a') == ['1'])
</code></pre>
<p>But I get this error:</p>
<blockquote>
<p>ComputeError: cannot cast List type (inner: 'Utf8', to: 'Utf8')</p>
</blockquote>
<p>The filter works when the DataFrame has non-list type values, as in:</p>
<pre><code>df = pl.DataFrame({'a': ['3', '3', '1', '2'], 'b':['8','6','7','7']})
df.filter(pl.col('a') == '1')
</code></pre>
<p>How can I apply filtering to list type columns using Polars? I'm not interested in solutions using Pandas, only Polars.</p>
| <python><python-polars> | 2023-08-29 18:25:37 | 2 | 5,573 | jss367 |
77,002,763 | 8,173,981 | why doesn't pygments discover my custom lexer after installation | <p>i've developed and tested a custom pygments lexer, as described <a href="https://pygments.org/docs/lexerdevelopment/" rel="nofollow noreferrer">here</a>... i then prepared a <code>pyproject.toml</code> file whose contents are as follows:</p>
<pre><code>[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "my-lexer"
version = "0.0.1"
dependencies = ["Pygments"]
[pygments.lexers]
dummy = "pkg.mylexer:MyLexer"
</code></pre>
<p>i then <code>python -m build</code> the project and <code>pip install dist/*.tar.gz</code> the generated output.... using <code>pip list</code>, i can see both pygments and my own package installed in the same environment....</p>
<p>as a test, i'll run <code>pygmentize -L</code> but don't see my custom language listed; attempts to force use of the lexer through the <code>-l</code> option likewise fail....</p>
<p>is there some obvious step i'm missing???? when/how does pygments discover my plugin??? is there some way i can trace that discovery process???</p>
| <python><plugins><setuptools><lexer><pygments> | 2023-08-29 18:24:24 | 1 | 331 | biosbob |
77,002,719 | 3,156,300 | Add SortFilterProxyModel to my QTreeView crashes | <p>When i insert the QSortFilterProxyModel to my QTreeview. It appears to crash and my buttons for adding, editing no longer appear to work reliably. Where did I go wrong here? My goal here is to add the Sort model so i can add a search bar which is simple to do.</p>
<p><a href="https://i.sstatic.net/uprH2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uprH2.png" alt="enter image description here" /></a></p>
<p>Here is the working version...</p>
<pre><code>import sys
import os
import random
from enum import IntEnum
from PySide2 import QtWidgets, QtGui, QtCore
class Person:
def __init__(self, name, job, thumbnail=''):
self.name = name
self.job = job
self.thumbnail = thumbnail
class Family:
def __init__(self, name, people, thumbnail=''):
self.name = name
self.people = people
self.thumbnail = thumbnail
self.isExpanded = False
class FamilyModel(QtCore.QAbstractItemModel):
class Roles(IntEnum):
ItemRole = QtCore.Qt.UserRole + 10
def __init__(self, items, parent=None):
super().__init__(parent)
self.items = items
self.columnNames = ['Last Name/First Name', 'Job']
# subclass methods
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.columnNames[section]
return None
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.columnNames)
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.column() > 0:
return 0
if not parent.isValid():
return len(self.items)
item = parent.internalPointer()
if isinstance(item, Family):
return len(item.people)
return 0
def index(self, row, column, parent=QtCore.QModelIndex()):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
return self.createIndex(row, column, self.items[row])
parent_item = parent.internalPointer()
return self.createIndex(row, column, parent_item.people[row])
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
item = index.internalPointer()
if isinstance(item, Person):
family = next((x for x in self.items if item in x.people), None)
if family:
return self.createIndex(self.items.index(family), 0, family)
return QtCore.QModelIndex()
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
item = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
if isinstance(item, Family):
if index.column() == 0:
return item.name
elif isinstance(item, Person):
if index.column() == 0:
return item.name
elif index.column() == 1:
return item.job
else:
return None
elif role == self.Roles.ItemRole:
return item
return None
def removeRows(self, row, count, index):
self.beginRemoveRows(index, row, row+count-1)
for i in reversed(range(row, row+count)):
if not index.isValid():
self.items.pop(i)
else:
self.items[index.row()].people.pop(i)
self.endRemoveRows()
return True
# extended methods
def itemFromIndex(self, index):
if index.isValid():
return index.internalPointer()
return None
def clear_items(self):
'''
Removes all items
'''
self.beginResetModel()
self.items.clear()
self.endResetModel()
def set_families(self, families):
'''
Directly set the items
'''
self.beginResetModel()
self.items = families
self.endResetModel()
def append_families(self, items):
'''
Add new families
'''
first = self.rowCount()
last = first + len(items)
self.beginInsertRows(QtCore.QModelIndex(), first, last)
self.items.extend(items)
self.endInsertRows()
class FamilyViewer(QtWidgets.QWidget):
def __init__(self, families):
super().__init__()
self.treeview = QtWidgets.QTreeView(self)
self.treeview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.treeview.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.itemModel = FamilyModel(families)
self.treeview.setModel(self.itemModel)
self.treeview.expandAll()
self.treeview.header().setStretchLastSection(True)
self.treeview.collapsed.connect(self.on_collapsed_state)
self.treeview.expanded.connect(self.on_expanded_state)
self.set_families_button = QtWidgets.QPushButton("Set Families")
self.set_families_button.clicked.connect(self.set_families)
self.add_family_button = QtWidgets.QPushButton("Add Family")
self.add_family_button.clicked.connect(self.add_family)
self.clear_all_button = QtWidgets.QPushButton("Clear All")
self.clear_all_button.clicked.connect(self.clear_all)
self.print_selected_button = QtWidgets.QPushButton("Print Selected")
self.print_selected_button.clicked.connect(self.print_selected)
self.remove_selected_button = QtWidgets.QPushButton("Remove Selected")
self.remove_selected_button.clicked.connect(self.remove_selected)
self.add_person_button = QtWidgets.QPushButton("Add Person")
self.add_person_button.clicked.connect(self.add_person)
self.update_selected_button = QtWidgets.QPushButton("Change/Update Selected")
self.update_selected_button.clicked.connect(self.update_selected)
button_layout = QtWidgets.QHBoxLayout()
button_layout.addWidget(self.set_families_button)
button_layout.addWidget(self.add_family_button)
button_layout.addWidget(self.add_person_button)
button_layout.addWidget(self.remove_selected_button)
button_layout.addWidget(self.clear_all_button)
button_layout.addWidget(self.update_selected_button)
button_layout.addWidget(self.print_selected_button)
main_layout = QtWidgets.QVBoxLayout()
main_layout.addWidget(self.treeview)
main_layout.addLayout(button_layout)
self.setLayout(main_layout)
def random_person(self):
first_names = ['Zephyr', 'Seraphina', 'Thaddeus', 'Evadne', 'Oberon', 'Isolde', 'Leif', 'Eulalia', 'Caius', 'Xanthe']
jobs = ['Ethnobotanist', 'Cryptographer', 'Geotechnical Engineer', 'Aquaculturist', 'Medical Illustrator', 'Flavor Chemist', 'Music Therapist', 'Renewable Energy Analyst', 'Cybersecurity Consultant', 'Wilderness Guide']
return Person(random.choice(first_names), random.choice(jobs))
def random_family(self):
last_names = ['Abernathy', 'Calhoun', 'Dempsey', 'Ellington', 'Farraday', 'Granger', 'Haverford', 'Inglewood', 'Jamison', 'Kensington']
new_family = Family(random.choice(last_names), [])
new_family.isExpanded = random.choice([True, False])
for i in range(random.randint(1, 5)):
new_family.people.append(self.random_person())
return new_family
def set_families(self):
families = []
for i in range(random.randint(1, 5)):
families.append(self.random_family())
self.itemModel.set_families(families)
for i in range(self.itemModel.rowCount()):
item = self.itemModel.itemFromIndex(self.itemModel.index(i, 0))
if item and item.isExpanded:
self.treeview.expand(self.itemModel.index(i, 0))
def add_family(self):
self.itemModel.append_families([self.random_family()])
def clear_all(self):
self.itemModel.clear_items()
def print_selected(self):
selected = self.treeview.selectionModel().selectedRows()
for mindex in selected:
item = mindex.data(FamilyModel.Roles.ItemRole)
print(vars(item))
def remove_selected(self):
selectionModel = self.treeview.selectionModel()
while len(selectionModel.selectedIndexes()):
mindex = selectionModel.selectedIndexes()[0]
self.itemModel.removeRow(mindex.row(), mindex.parent())
def on_collapsed_state(self, modelIndex):
item = modelIndex.data(FamilyModel.Roles.ItemRole)
item.isExpanded = False
def on_expanded_state(self, modelIndex):
item = modelIndex.data(FamilyModel.Roles.ItemRole)
item.isExpanded = True
def add_person(self):
selected = self.treeview.selectionModel().selectedRows()
for mindex in selected:
item = mindex.data(FamilyModel.Roles.ItemRole)
if isinstance(item, Family):
item.people.append(self.random_person())
self.itemModel.layoutChanged.emit()
def update_selected(self):
selected = self.treeview.selectionModel().selectedRows()
for mindex in selected:
item = mindex.data(FamilyModel.Roles.ItemRole)
item.name = random.choice(['A','B','C','D'])
self.itemModel.layoutChanged.emit()
def main():
# Create sample data
familyA = Family(
'Roberston',
[
Person('Kevin', 'Nurse'),
Person('Ashley', 'Lifeguard'),
Person('Michael', 'Unemployed'),
]
)
familyB = Family(
'Grainger',
[
Person('Emily', 'Clerk'),
Person('Emma', 'Security'),
Person('Ron', 'Teacher'),
Person('Jerry', 'Wizard'),
]
)
families = [familyA, familyB]
app = QtWidgets.QApplication(sys.argv)
viewer = FamilyViewer(families)
viewer.setWindowTitle('Family Viewer')
viewer.resize(500, 600)
viewer.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
</code></pre>
<p>Here is the broken one...</p>
<pre><code>import sys
import os
import random
from enum import IntEnum
from PySide2 import QtWidgets, QtGui, QtCore
class Person:
def __init__(self, name, job, thumbnail=''):
self.name = name
self.job = job
self.thumbnail = thumbnail
class Family:
def __init__(self, name, people, thumbnail=''):
self.name = name
self.people = people
self.thumbnail = thumbnail
self.isExpanded = False
class FamilyModel(QtCore.QAbstractItemModel):
class Roles(IntEnum):
ItemRole = QtCore.Qt.UserRole + 10
def __init__(self, items, parent=None):
super().__init__(parent)
self.items = items
self.columnNames = ['Last Name/First Name', 'Job']
# subclass methods
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.columnNames[section]
return None
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.columnNames)
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.column() > 0:
return 0
if not parent.isValid():
return len(self.items)
item = parent.internalPointer()
if isinstance(item, Family):
return len(item.people)
return 0
def index(self, row, column, parent=QtCore.QModelIndex()):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
return self.createIndex(row, column, self.items[row])
parent_item = parent.internalPointer()
return self.createIndex(row, column, parent_item.people[row])
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
item = index.internalPointer()
if isinstance(item, Person):
family = next((x for x in self.items if item in x.people), None)
if family:
return self.createIndex(self.items.index(family), 0, family)
return QtCore.QModelIndex()
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
item = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
if isinstance(item, Family):
if index.column() == 0:
return item.name
elif isinstance(item, Person):
if index.column() == 0:
return item.name
elif index.column() == 1:
return item.job
else:
return None
elif role == self.Roles.ItemRole:
return item
return None
def removeRows(self, row, count, index):
self.beginRemoveRows(index, row, row+count-1)
for i in reversed(range(row, row+count)):
if not index.isValid():
self.items.pop(i)
else:
self.items[index.row()].people.pop(i)
self.endRemoveRows()
return True
# extended methods
def itemFromIndex(self, index):
if index.isValid():
return index.internalPointer()
return None
def clear_items(self):
'''
Removes all items
'''
self.beginResetModel()
self.items.clear()
self.endResetModel()
def set_families(self, families):
'''
Directly set the items
'''
self.beginResetModel()
self.items = families
self.endResetModel()
def append_families(self, items):
'''
Add new families
'''
first = self.rowCount()
last = first + len(items)
self.beginInsertRows(QtCore.QModelIndex(), first, last)
self.items.extend(items)
self.endInsertRows()
class FamilyViewer(QtWidgets.QWidget):
def __init__(self, families):
super().__init__()
self.itemModel = FamilyModel(families)
self.proxyModel = QtCore.QSortFilterProxyModel()
self.proxyModel.setSourceModel(self.itemModel)
self.proxyModel.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.proxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.proxyModel.setDynamicSortFilter(True)
self.proxyModel.setFilterKeyColumn(0)
self.proxyModel.sort(0, QtCore.Qt.AscendingOrder)
self.treeview = QtWidgets.QTreeView(self)
self.treeview.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.treeview.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.treeview.setSortingEnabled(True)
self.treeview.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.treeview.setModel(self.proxyModel)
self.treeview.expandAll()
self.treeview.header().setStretchLastSection(True)
self.treeview.collapsed.connect(self.on_collapsed_state)
self.treeview.expanded.connect(self.on_expanded_state)
self.set_families_button = QtWidgets.QPushButton("Set Families")
self.set_families_button.clicked.connect(self.set_families)
self.add_family_button = QtWidgets.QPushButton("Add Family")
self.add_family_button.clicked.connect(self.add_family)
self.clear_all_button = QtWidgets.QPushButton("Clear All")
self.clear_all_button.clicked.connect(self.clear_all)
self.print_selected_button = QtWidgets.QPushButton("Print Selected")
self.print_selected_button.clicked.connect(self.print_selected)
self.remove_selected_button = QtWidgets.QPushButton("Remove Selected")
self.remove_selected_button.clicked.connect(self.remove_selected)
self.add_person_button = QtWidgets.QPushButton("Add Person")
self.add_person_button.clicked.connect(self.add_person)
self.update_selected_button = QtWidgets.QPushButton("Change/Update Selected")
self.update_selected_button.clicked.connect(self.update_selected)
button_layout = QtWidgets.QHBoxLayout()
button_layout.addWidget(self.set_families_button)
button_layout.addWidget(self.add_family_button)
button_layout.addWidget(self.add_person_button)
button_layout.addWidget(self.remove_selected_button)
button_layout.addWidget(self.clear_all_button)
button_layout.addWidget(self.update_selected_button)
button_layout.addWidget(self.print_selected_button)
main_layout = QtWidgets.QVBoxLayout()
main_layout.addWidget(self.treeview)
main_layout.addLayout(button_layout)
self.setLayout(main_layout)
def random_person(self):
first_names = ['Zephyr', 'Seraphina', 'Thaddeus', 'Evadne', 'Oberon', 'Isolde', 'Leif', 'Eulalia', 'Caius', 'Xanthe']
jobs = ['Ethnobotanist', 'Cryptographer', 'Geotechnical Engineer', 'Aquaculturist', 'Medical Illustrator', 'Flavor Chemist', 'Music Therapist', 'Renewable Energy Analyst', 'Cybersecurity Consultant', 'Wilderness Guide']
return Person(random.choice(first_names), random.choice(jobs))
def random_family(self):
last_names = ['Abernathy', 'Calhoun', 'Dempsey', 'Ellington', 'Farraday', 'Granger', 'Haverford', 'Inglewood', 'Jamison', 'Kensington']
new_family = Family(random.choice(last_names), [])
new_family.isExpanded = random.choice([True, False])
for i in range(random.randint(1, 5)):
new_family.people.append(self.random_person())
return new_family
def set_families(self):
families = []
for i in range(random.randint(1, 5)):
families.append(self.random_family())
self.itemModel.set_families(families)
for i in range(self.itemModel.rowCount()):
item = self.itemModel.itemFromIndex(self.itemModel.index(i, 0))
if item and item.isExpanded:
self.treeview.expand(self.itemModel.index(i, 0))
def add_family(self):
self.itemModel.append_families([self.random_family()])
def clear_all(self):
self.itemModel.clear_items()
def print_selected(self):
selected = self.treeview.selectionModel().selectedRows()
for mindex in selected:
item = mindex.data(FamilyModel.Roles.ItemRole)
print(vars(item))
def remove_selected(self):
selectionModel = self.treeview.selectionModel()
while len(selectionModel.selectedIndexes()):
mindex = selectionModel.selectedIndexes()[0]
self.itemModel.removeRow(mindex.row(), mindex.parent())
def on_collapsed_state(self, modelIndex):
item = modelIndex.data(FamilyModel.Roles.ItemRole)
item.isExpanded = False
def on_expanded_state(self, modelIndex):
item = modelIndex.data(FamilyModel.Roles.ItemRole)
item.isExpanded = True
def add_person(self):
selected = self.treeview.selectionModel().selectedRows()
for mindex in selected:
item = mindex.data(FamilyModel.Roles.ItemRole)
if isinstance(item, Family):
item.people.append(self.random_person())
self.itemModel.layoutChanged.emit()
def update_selected(self):
selected = self.treeview.selectionModel().selectedRows()
for mindex in selected:
item = mindex.data(FamilyModel.Roles.ItemRole)
item.name = random.choice(['A','B','C','D'])
self.itemModel.layoutChanged.emit()
def main():
# Create sample data
familyA = Family(
'Roberston',
[
Person('Kevin', 'Nurse'),
Person('Ashley', 'Lifeguard'),
Person('Michael', 'Unemployed'),
]
)
familyB = Family(
'Grainger',
[
Person('Emily', 'Clerk'),
Person('Emma', 'Security'),
Person('Ron', 'Teacher'),
Person('Jerry', 'Wizard'),
]
)
families = [familyA, familyB]
app = QtWidgets.QApplication(sys.argv)
viewer = FamilyViewer(families)
viewer.setWindowTitle('Family Viewer')
viewer.resize(500, 600)
viewer.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
</code></pre>
| <python><python-3.x><pyside2> | 2023-08-29 18:18:47 | 1 | 6,178 | JokerMartini |
77,002,659 | 806,392 | Efficient "bandmax" function in pyvips? | <p>I'm looking for a way to efficiently find the band that has the maximum value in a large multi-band image.</p>
<p>For example if we had an image that looked like</p>
<pre><code>band 1 band 2 band 3
[1 2 3] [3 4 5] [0 1 2]
[3 2 1] [1 2 3] [1 0 1]
[4 5 6] [6 7 5] [0 0 7]
</code></pre>
<p>I'd like to make something like</p>
<pre><code>bandFind = A.bandmax()
</code></pre>
<p>Where <code>bandFind</code> would look like</p>
<pre><code>band 1 band 2 band 3
[0 0 0] [1 1 1] [0 0 0]
[1 1 0] [0 0 1] [0 0 0]
[0 0 0] [1 1 0] [0 0 1]
</code></pre>
<p>Alternatively if I can get an index image I can pretty easily convert it to what I want.</p>
<p>I wrote a function in python that iterates through the bands, accumulating the max value and the index in a buffer, and the converts it to the kind of map shown above, but it doesn't seem very performant on large images.</p>
<pre><code> def pickMax(inImg):
imBandSelect = pyvips.Image.black(inImg.width, inImg.height, bands=1)
imBandMax = pyvips.Image.black(inImg.width, inImg.height, bands=1)
for bandIndex, band in enumerate(inImg.bandsplit()):
runningSelect = band > imBandMax
imBandMax = runningSelect.ifthenelse(band, imBandMax)
imBandSelect = runningSelect.ifthenelse(bandIndex, imBandSelect)
bandList = [ (imBandSelect == bi) / 255.0 for bi in range(inImg.bands) ]
return bandList[0].bandjoin(bandList[1:])
</code></pre>
<p>Update:</p>
<p>Thanks to @jcupitt I tried this version of the code using <code>bandrank</code>:</p>
<pre><code> def pickMaxUchar(inImg):
short = (inImg.cast(pyvips.enums.BandFormat.USHORT)) << 8
index = pyvips.Image.black(short.width, short.height, bands=1).bandjoin_const([b for b in range(1, inImg.bands)]).cast(pyvips.enums.BandFormat.UCHAR)
combo = short | index
list = combo.bandsplit()
ranked = list[0].bandrank(list[1:], index=inImg.bands-1)
rankedindex = (ranked & 255).cast(pyvips.enums.BandFormat.UCHAR)
bandList = [ (rankedindex == bi) / 255.0 for bi in range(inImg.bands) ]
return bandList[0].bandjoin(bandList[1:])
</code></pre>
<p>This now assumes the input is a char, where in my original function the input was float. Maybe there's a way to do this without re-casting the data but as I've implemented it there's zero speedup relative to my "naive" code above, so perhaps this just can't be accelerated any further.</p>
| <python><vips><libvips> | 2023-08-29 18:05:02 | 1 | 583 | matth |
77,002,544 | 17,082,611 | Change Conv2DTranspose output from (None, 39, 39, 1) to (None, 40, 40, 1) | <p>I am implementing a Decoder (a type of Artificial Neural Network) using keras:</p>
<pre><code>latent_dim = 25
latent_inputs = keras.Input(shape=(latent_dim,))
x = layers.Dense(units=100, activation="relu")(latent_inputs)
x = layers.Dense(units=1024, activation="relu")(x)
x = layers.Dense(units=4096, activation="relu")(x)
x = layers.Reshape((4, 4, 256))(x)
x = layers.Conv2DTranspose(filters=256, kernel_size=3, activation="relu", strides=2, padding="same")(x)
x = layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=1, padding="same")(x)
x = layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=2, padding="same")(x)
x = layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=1, padding="same")(x)
x = layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=2, padding="same")(x)
decoder_outputs = layers.Conv2DTranspose(filters=1, kernel_size=3, activation="sigmoid", padding="same")(x)
decoder = keras.Model(latent_inputs, decoder_outputs, name="decoder")
decoder.summary()
</code></pre>
<p>whose output is:</p>
<pre><code>Model: "decoder"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 25)] 0
dense (Dense) (None, 100) 2600
dense_1 (Dense) (None, 1024) 103424
dense_2 (Dense) (None, 4096) 4198400
reshape (Reshape) (None, 4, 4, 256) 0
conv2d_transpose (Conv2DTr (None, 8, 8, 256) 590080
anspose)
conv2d_transpose_1 (Conv2D (None, 8, 8, 128) 295040
Transpose)
conv2d_transpose_2 (Conv2D (None, 16, 16, 128) 147584
Transpose)
conv2d_transpose_3 (Conv2D (None, 16, 16, 64) 73792
Transpose)
conv2d_transpose_4 (Conv2D (None, 32, 32, 64) 36928
Transpose)
conv2d_transpose_5 (Conv2D (None, 32, 32, 1) 577
Transpose)
</code></pre>
<p>I want to adjust my model so that <code>decoder_outputs</code> shape is <code>(None, 40, 40, 1)</code> instead of <code>(None, 32, 32, 1)</code>. This is what I tried to do:</p>
<pre><code>latent_dim = 25
latent_inputs = keras.Input(shape=(latent_dim,))
x = layers.Dense(units=100, activation="relu")(latent_inputs)
x = layers.Dense(units=1024, activation="relu")(x)
x = layers.Dense(units=1600, activation="relu")(x) # Adjusted units to match 40*40*1
x = layers.Reshape((40, 40, 1))(x) # Reshaped to (40, 40, 1)
x = layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=2, padding="same")(x)
x = layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=1, padding="same")(x)
x = layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=2, padding="same")(x)
decoder_outputs = layers.Conv2DTranspose(filters=1, kernel_size=3, activation="sigmoid", padding="same")(x)
decoder = keras.Model(latent_inputs, decoder_outputs, name="decoder")
decoder.summary()
</code></pre>
<p>but unfortunately <code>decoder_outputs</code> shape is <code>(None, 160, 160, 1)</code>.</p>
<p>Can you help me, please?</p>
<p><strong>EDIT</strong></p>
<p>I tried the following solution:</p>
<pre><code>latent_dim = 25
latent_inputs = keras.Input(shape=(latent_dim,))
x = layers.Dense(units=100, activation="relu")(latent_inputs)
x = layers.Dense(units=1024, activation="relu")(x)
x = layers.Dense(units=4096, activation="relu")(x)
x = layers.Reshape((4, 4, 256))(x)
x = layers.Conv2DTranspose(filters=256, kernel_size=3, activation="relu", strides=2, padding="same")(x)
x = layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=1, padding="same")(x)
x = layers.Conv2DTranspose(filters=128, kernel_size=3, activation="relu", strides=2, padding="valid")(x)
x = layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=1, padding="valid")(x)
x = layers.Conv2DTranspose(filters=64, kernel_size=3, activation="relu", strides=2, padding="valid")(x)
decoder_outputs = layers.Conv2DTranspose(filters=1, kernel_size=3, activation="sigmoid", padding="valid")(x)
decoder = keras.Model(latent_inputs, decoder_outputs, name="decoder")
decoder.summary()
</code></pre>
<p>that is using <code>padding="same"</code> for some layers, but this is the output I get:</p>
<pre><code>Model: "decoder"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 25)] 0
dense (Dense) (None, 100) 2600
dense_1 (Dense) (None, 1024) 103424
dense_2 (Dense) (None, 4096) 4198400
reshape (Reshape) (None, 4, 4, 256) 0
conv2d_transpose (Conv2DTr (None, 8, 8, 256) 590080
anspose)
conv2d_transpose_1 (Conv2D (None, 8, 8, 128) 295040
Transpose)
conv2d_transpose_2 (Conv2D (None, 16, 16, 128) 147584
Transpose)
conv2d_transpose_3 (Conv2D (None, 18, 18, 64) 73792
Transpose)
conv2d_transpose_4 (Conv2D (None, 37, 37, 64) 36928
Transpose)
conv2d_transpose_5 (Conv2D (None, 39, 39, 1) 577
Transpose)
</code></pre>
<p>As you can see <code>decoder_outputs</code> shape is now <code>(None, 39, 39, 1)</code>. I want it to be <code>(None, 40, 40, 1)</code>. How may I fix?</p>
| <python><tensorflow><keras><deep-learning> | 2023-08-29 17:46:42 | 2 | 481 | tail |
77,002,525 | 12,468,387 | Google chrome can't detect profiles | <p>I ran selenium python and the profiles in the browser disappeared:
<a href="https://i.sstatic.net/c13kx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c13kx.png" alt="enter image description here" /></a></p>
<p>However, the profiles are still located in the \AppData\Local\Google\Chrome\User Data folder:
<a href="https://i.sstatic.net/fXmUK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fXmUK.png" alt="enter image description here" /></a></p>
<p>why they were removed from the browser?
How can I make the browser detect them again?</p>
<p>UPD:
here's my code</p>
<pre><code>chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument(r'user-data-dir=C:\Users\Qwert\AppData\Local\Google\Chrome\User Data')
chrome_options.add_argument(r'profile-directory=Profile 3')
chrome_options.add_argument("--remote-debugging-port=9222") # this
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_argument('--disable-web-security')
chrome_options.add_argument('--disable-setuid-sandbox')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(),chrome_options=chrome_options)
</code></pre>
| <python><google-chrome><selenium-webdriver><browser> | 2023-08-29 17:42:32 | 1 | 449 | Denzel |
77,002,345 | 20,200,927 | Wierd GUI behaviour with pyinstaller | <p>I made a simple file organizer in Python with a GUI. When I run mu <code>app.py</code> with <code>conda</code> it works just as I intended it to, but when I run the executable that I made with <code>pyinstaller</code> it prints out the custom error message that I wrapped inside a try-catch block.</p>
<p>Here is the code in <code>app.py</code>, <code>organize_files()</code> is the brain of the script and <code>establish_current_dir()</code> is a simple function that uses <code>os.scandir()</code> and returns the files as a list of strings</p>
<pre><code>from tkinter import *
import os
from ttkthemes import ThemedTk
from tkinter import filedialog, messagebox, ttk
from constants import *
from main import establish_current_dir, organize_files, TARGET_DIR_
BG_COLOR_ = "#252629"
def browse_folder(folder_label: str):
global target_folder
target_folder = filedialog.askdirectory()
folder_name = os.path.basename(target_folder)
folder_label.config(text=f"Selected Folder: {folder_name}")
def organize_files_gui():
if not target_folder:
messagebox.showerror("Error", "Please select a folder.")
return
files = establish_current_dir()
organize_files(files)
messagebox.showinfo("Success", "Files organized.")
def main():
root = ThemedTk(theme="Adapta")
root.title("File Organizer")
root.geometry("400x200")
root.configure(bg=BG_COLOR_)
folder_label_frame = Frame(root)
folder_label_frame.pack(side="top", fill="x", pady=0)
folder_label = Label(folder_label_frame, text="Selected Folder: ")
folder_label = Label(folder_label_frame, text="Selected Folder: ", foreground="#FFFFFF")
folder_label.pack(side="top", anchor="center")
made_by_label = Label(root, text="Made by Jakob™", fg = "#9d9ea3", bg = BG_COLOR_, font=("Helvetica", 32))
made_by_label.place(relx=0.5, rely=0.5, anchor="center")
style = ttk.Style()
style.configure("Custom.TButton", foreground="#FFFFFF", background="#FFFDD0",
borderwidth=0, relief="groove")
button_frame = Frame(root, bg= BG_COLOR_)
button_frame.pack(side="bottom")
select_folder_button = ttk.Button(button_frame, text="Select Folder", command=lambda: browse_folder(folder_label), style="Custom.TButton")
select_folder_button.pack(side="left", padx=10, pady=20)
organize_button = ttk.Button(button_frame, text="Organize Files", command=organize_files_gui, style="Custom.TButton")
organize_button.pack(side="right", padx=10, pady=20)
root.mainloop()
if __name__ == "__main__":
target_folder = ""
main()
</code></pre>
<p>I am running MacOS and used <code>pyinstaller --onefile app.py</code> to build my executable. After reviewing <a href="https://stackoverflow.com/questions/66385159/after-pyinstaller-code-does-not-work-as-expected">this question</a> I used <code>pyinsatller --onedir app.py</code> since I was assuming there might be some errors with the library linkage, but it did in fact not work again.</p>
<p>Am I overlooking something in the process? Any guidance would be greatly appreciated.</p>
<p><strong>Edit:</strong></p>
<pre><code>#main.py
def establish_current_dir() -> List[str]:
try:
with os.scandir(TARGET_DIR_) as entries:
files = [entry.name for entry in entries] # if entry.is_file()
return files
except FileNotFoundError:
print(ERROR_MSG_)
sys.exit()
</code></pre>
| <python><pyinstaller> | 2023-08-29 17:12:44 | 0 | 320 | i_hate_F_sharp |
77,002,343 | 22,407,544 | com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None) | <p>I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I sometimes get a <code>com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None)</code>. Here is the full error message:</p>
<pre><code>Exception Location: C:\Users\John\tutorial-env\Lib\site-packages\win32com\client\dynamic.py, line 86, in _GetGoodDispatch
Raised during: translator_upload.views.translateFile
Python Executable: C:\Users\John\tutorial-env\Scripts\python.exe
Python Version: 3.11.4
Python Path:
['C:\\djangoProjects\\mysite',
'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip',
'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\DLLs',
'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\Lib',
'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311',
'C:\\Users\\John\\tutorial-env',
'C:\\Users\\John\\tutorial-env\\Lib\\site-packages',
'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32',
'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32\\lib',
'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\Pythonwin']
</code></pre>
<p>Here is my code:</p>
<pre><code>from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from .models import TranslatedDocument
from .forms import UploadFileForm
from django.core.files.storage import FileSystemStorage
import docx
from pdf2docx import parse
from docx2pdf import convert
import time #remove
# Create your views here.
@csrf_protect
def translateFile(request) :
file = ''
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(uploaded_file.name, uploaded_file)
uploaded_file_path = fs.path(filename)
file = (converter(uploaded_file_path))
response = HttpResponse(file, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
return response
else:
form = UploadFileForm()
return render(request, 'translator_upload/upload.html', {'form': form})
def reConverter(inputDocxPath):
return convert(inputDocxPath)
def translateDocx(aDocx, stringOfDocPath):
docx_file = stringOfDocPath
myDoc = docx.Document(docx_file)
#translation logic
myDoc.save(stringOfDocPath)
return reConverter(stringOfDocPath)
#stringOfDocPath is used as convert() requires file path, not file object(myDoc)
def converter(inputPdfPath):
# convert pdf to docx
pdf_file = inputPdfPath
docx_file = inputPdfPath + '.docx'
parse(pdf_file, docx_file) #, start=0, end=3)
myDoc = docx.Document(docx_file)
return translateDocx(myDoc, docx_file)
</code></pre>
<p>I tried adding</p>
<pre><code>
pythoncom.CoInitialize()
# Use the COM object here
pythoncom.CoUninitialize()
</code></pre>
<p>But that did not work. Note that I only get this error sometimes and never after retrying(so not twice in a row).</p>
| <python><django><pdf><ms-word><pywin32> | 2023-08-29 17:12:09 | 0 | 359 | tthheemmaannii |
77,002,321 | 8,769,865 | multiline string of values to a pandas dataframe | <p>I have a string of values from a file</p>
<pre><code>my_list = ["col1: va11 \n col2: val2 \n col3:va13" , "col1: k11 \n col2: k12 \n col3:k13" ]
</code></pre>
<p>I wanted to convert these strings into a pandas dataFrame.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
</tr>
<tr>
<td>k11</td>
<td>k12</td>
<td>k13</td>
</tr>
</tbody>
</table>
</div>
<p>my python script works but it is complex with multiple for loop iterations.</p>
<p>I tried with <code>import csv</code> and <code>csv.CSVDictReader()</code> that did not work for me. I also tried <code>import io; io.StringIO()</code>. Even this as well, did not convert to a data frame.</p>
<pre><code>my_list = ["col1: va11 \n col2: val2 \n col3:va13" , "col1: k11 \n col2: k12 \n col3:k13" ]
data = [[j.split(":")[1].strip() for j in my_list[i].split("\n")] for i in range(2)]
df = pd.DataFrame(data,columns=['col1','col2','col3'])
df.head()
</code></pre>
<pre><code>
col1 col2 col3
0 va11 val12 val3
1 k11 k12 k13
</code></pre>
<p>I am looking for some existing APIs that can reduce the complexity in converting the "col1:val \ncol2:val2" string to data frame table format. for example, CSV to JSON</p>
| <python><pandas><string> | 2023-08-29 17:08:21 | 1 | 763 | IndPythCoder |
77,002,315 | 1,084,875 | Get 2D Gauss–Legendre quadrature points and weights using NumPy | <p>NumPy provides the <code>np.polynomial.legendre.leggauss()</code> function to compute the sample points and weights for Gauss-Legendre quadrature. I'm trying to use this function to get the 2D points and weights for a quadrilateral. I am able to use the function as shown here:</p>
<pre class="lang-py prettyprint-override"><code>def gauss2D(n):
x, w = np.polynomial.legendre.leggauss(n)
weights = []
gauss_pts = []
for i in range(n):
for j in range(n):
wts = w[i] * w[j]
weights.append(wts)
g = [x[i], x[j]]
gauss_pts.append(g)
return np.array(weights), np.array(gauss_pts)
</code></pre>
<p>Which outputs the following for <code>n=2</code> integration points:</p>
<pre><code>weights
[1. 1. 1. 1.]
points
[[-0.57735027 -0.57735027]
[-0.57735027 0.57735027]
[ 0.57735027 -0.57735027]
[ 0.57735027 0.57735027]]
</code></pre>
<p>If it's possible, I would like to get rid of the for-loops by using NumPy arrays but my attempt (see function below) does not generate the correct results.</p>
<pre class="lang-py prettyprint-override"><code>def gauss2Dnumpy(n):
x, w = np.polynomial.legendre.leggauss(n)
weights = np.concatenate((w, w))
gauss_pts = np.zeros((n*2, n))
for i in range(n*2):
for j in range(n):
gauss_pts[i] = x[j], x[j]
return weights, gauss_pts
</code></pre>
<p>Is there a way to accomplish this without the for-loops?</p>
| <python><numpy><scipy> | 2023-08-29 17:07:24 | 1 | 9,246 | wigging |
77,002,301 | 850,781 | How to merge two `value_counts` results without data loss? | <p>I want to accumulate value counts, but the simple addition does not do the trick.</p>
<p>Suppose I have many many <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.html" rel="nofollow noreferrer">Series</a>, e.g., :</p>
<pre><code>a = pd.Series([1,2,2,None], dtype=object)
b = pd.Series([3,2,2,None], dtype=object)
...
</code></pre>
<p>and I want to produce</p>
<pre><code>pd.concat([a,b,...]).value_counts(dropna=False)
2 4
None 2
1 1
3 1
Name: count, dtype: int64
</code></pre>
<p><em>incrementally</em>, i.e., from</p>
<pre><code>vc_a = a.value_counts(dropna=False)
vc_b = b.value_counts(dropna=False)
...
</code></pre>
<p>Alas, the simple <code>vc_a + vc_b</code> produces</p>
<pre><code>1 NaN
2 4.0
3 NaN
None 2.0
</code></pre>
<p>i.e., the objects that are present in only one of the series are not counted correctly.</p>
<p>So, how do I merge a bunch of counting series?</p>
| <python><pandas><dataframe><series> | 2023-08-29 17:04:20 | 1 | 60,468 | sds |
77,002,135 | 22,466,650 | How to manually forward-fill values to make a boolean slice? | <p>That's a simple question to explain but the solution is not easy for me. I can't figure it out.</p>
<p>I have a dataframe with two columns as input :</p>
<pre><code>df = pd.DataFrame({'start': [True, False, False, False, False, True, False, False, False, False, False, False],
'stop': [False, False, False, True, False, False, True, False, False, False, False, False]})
</code></pre>
<p>
And I need to create a third one that will hold <code>True</code> values from the start to the stop.</p>
<p>PS : I made the <code>False</code> values as empty strings just for clarity, guys !</p>
<pre><code> start stop ===(expected_column)==> slice
0 True True
1 True
2 True
3 True True
4
5 True True
6 True True
7
8
9
10
11
</code></pre>
<p>I desperately tried below but the row with the index 6 gives <code>False</code> instead of <code>True</code>.</p>
<pre><code>df['slice'] = (df['start'] | df.index.isin(range(df['start'].idxmax(), df['stop'].idxmax() + 1)))
</code></pre>
<p>Is there a solution, please ? Feels like we need to use <code>groupby</code> with some custom ops but I wonder if there is a differernt approach.</p>
<p>In case you wonder, the dataset will always have one single <code>True</code> per row.</p>
| <python><pandas> | 2023-08-29 16:41:22 | 2 | 1,085 | VERBOSE |
77,002,087 | 13,250,589 | Get `scrapy` to produce a nested datastructure | <p>I am using <code>scrapy</code> to crawl <a href="https://savings.gov.pk/download-draws/" rel="nofollow noreferrer">this</a> website and scrape data</p>
<p>I want the scraped data to have a nested structure. something like this</p>
<pre class="lang-js prettyprint-override"><code>{
denomination1: {
date1: {
bondNumbers: [...] },
date2: {
bondNumbers: [...] },
... },
denomination2: {
date1: {
bondNumbers: [...] },
date2: {
bondNumbers: [...] },
... },
...
}
</code></pre>
<p>here is the <code>spider</code> I wrote.</p>
<pre class="lang-py prettyprint-override"><code>import scrapy
class Savings(scrapy.Spider):
name = 'savings'
start_urls = [
'https://savings.gov.pk/download-draws/',
]
def parse(self, response):
for option in response.css('select option'):
denomination = option.css('::text').get()
url = option.css('::attr(value)').get()
yield {
denomination: response.follow(url, self.parseDrawList)
}
def parseDrawList(self, response):
for a in response.css('select option'):
date = a.css('::text').get()
url = a.css('::attr(value)').get()
yield {
date: response.follow(url, self.parseDraw)
}
def parseDraw(self, response):
yield {
'bondNumbers': response.selector.re(r'\d{6}'),
}
</code></pre>
<p>each function is scraping a different page in the web-page hierarchy (if we could call it that), so as a result each level of the nested data-structure would be populated by data from a page of different level.</p>
<p>this code is not working and is giving me an error.</p>
<p>from all the tutorials and documentations i have seen, none have ever used <code>scrapy</code> to generate a nested data-structure.</p>
<p>is there any way to get nested data from <code>scrapy</code>?. I would also like if the solution does not sacrifice <code>scrapy</code>'s concurrent execution of requests</p>
| <python><web-scraping><scrapy><web-crawler><generator> | 2023-08-29 16:34:56 | 1 | 885 | Hammad Ahmed |
77,002,035 | 2,031,993 | Can I use Python Numba on Google App Engine? | <p>Is it possible to use the Python package Numba in web-apps that are running on Google App Engine?</p>
<p>Is it possible to use the caching feature of Numba, so the functions don't have to be JIT-compiled every time they are run on Google App Engine? Or is there another way of achieving the same effect, e.g. by somehow building the Numba cache on my own computer and including it when deploying the app to Google's servers?</p>
<p>Are there any other limitations or requirements to be aware of?</p>
<p>Thanks!</p>
| <python><google-app-engine><numba> | 2023-08-29 16:26:46 | 1 | 822 | questiondude |
77,001,962 | 7,254,576 | Luxonis OAK-D S2 PoE: how do I use the SDK and flash a standalone application? | <p>I am unable to flash a standalone application if it is based on the SDK.</p>
<p>It seems there might be a conflict between using the SDK <code>OakCamera()</code> and the API <code>dai.DeviceBootloader()</code> but I don't know why the conflict is there or how to resolve it. It does seem that each of these 2 calls results in some kind of device state that does not allow the other call to proceed.</p>
<h1>Flashing works for API-based applications</h1>
<p>By following the Luxonis documentation under API heading, when I try the <a href="https://docs.luxonis.com/projects/api/en/latest/tutorials/standalone_mode/#standalone-mode" rel="nofollow noreferrer">Standalone mode</a>,
I'm able to flash any application which is based on the API, for example, this webserver code works (both when <code>STAND_ALONE=True</code> and when <code>STAND_ALONE=False</code>):</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3
STAND_ALONE = True
# STAND_ALONE = False
import depthai as dai
import time
# Start defining a pipeline
pipeline = dai.Pipeline()
# Define a source - color camera
cam = pipeline.create(dai.node.ColorCamera)
# VideoEncoder
jpeg = pipeline.create(dai.node.VideoEncoder)
jpeg.setDefaultProfilePreset(cam.getFps(), dai.VideoEncoderProperties.Profile.MJPEG)
# Script node
script = pipeline.create(dai.node.Script)
script.setProcessor(dai.ProcessorType.LEON_CSS)
script.setScript("""
from http.server import BaseHTTPRequestHandler
import socketserver
import socket
import fcntl
import struct
PORT = 8080
ctrl = CameraControl()
ctrl.setCaptureStill(True)
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
-1071617759, # SIOCGIFADDR
struct.pack('256s', ifname[:15].encode())
)[20:24])
class HTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.end_headers()
self.wfile.write(b'<h1>[DepthAI] Hello, world of STANDALONE!</h1><p>Click <a href="img">here</a> for an image</p>')
elif self.path == '/img':
node.io['out'].send(ctrl)
jpegImage = node.io['jpeg'].get()
self.send_response(200)
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', str(len(jpegImage.getData())))
self.end_headers()
self.wfile.write(jpegImage.getData())
else:
self.send_response(404)
self.end_headers()
self.wfile.write(b'Url not found...')
with socketserver.TCPServer(("", PORT), HTTPHandler) as httpd:
node.warn(f"Serving at {get_ip_address('re0')}:{PORT}")
httpd.serve_forever()
""")
# Connections
cam.still.link(jpeg.input)
script.outputs['out'].link(cam.inputControl)
jpeg.bitstream.link(script.inputs['jpeg'])
if STAND_ALONE:
# Flash the pipeline
(f, bl) = dai.DeviceBootloader.getFirstAvailableDevice()
bootloader = dai.DeviceBootloader(bl)
progress = lambda p : print(f'Flashing progress: {p*100:.1f}%')
bootloader.flash(progress, pipeline)
else:
# Connect to device with pipeline
with dai.Device(pipeline) as device:
while not device.isClosed():
time.sleep(1)
</code></pre>
<h1>Need help flashing SDK-based applications</h1>
<p>However, the Luxonis documentation under SDK heading does not have a Standalone mode section. So, I tried to combine the <a href="https://docs.luxonis.com/projects/sdk/en/latest/samples/mixed/sdk_api_interop/?highlight=interoperability" rel="nofollow noreferrer">interoperability example</a>, and the <a href="https://docs.luxonis.com/projects/api/en/latest/tutorials/standalone_mode/#flash-the-pipeline" rel="nofollow noreferrer">Flash the pipeline</a> example. Both examples work well on their own. Just to clarify, the interoperability example explains how to use the SDK to create <code>oak=OakCamera()</code>, get the pipline using <code>pipeline=oak.build()</code>, then run the pipeline using <code>oak.start()</code>. Also, following the docs about standalone, we need to remove all XLinkOut nodes because we don't have a host to communicate to. So, I tried to use the principle of getting <code>pipeline</code> from the SDK and passing it to <code>bootloader.flash()</code> as in this code:</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3
# SDK version
STAND_ALONE = True
# STAND_ALONE = False
from depthai_sdk import OakCamera
import depthai as dai
import time
# Try putting bootloader in location #1
# (f, bl) = dai.DeviceBootloader.getFirstAvailableDevice()
# bootloader = dai.DeviceBootloader(bl)
# progress = lambda p : print(f'Flashing progress: {p*100:.1f}%')
with OakCamera() as oak:
color = oak.create_camera('color')
# nn = oak.create_nn('mobilenet-ssd', color)
# oak.visualize([nn.out.passthrough, nn], fps=True)
# Build the pipeline, connect to the oak, update components. Place interop logic AFTER oak.build()
pipeline = oak.build()
# nn.node.setNumInferenceThreads(2) # Configure components' nodes
# features = pipeline.create(dai.node.FeatureTracker) # Create new pipeline nodes
# color.node.video.link(features.inputImage)
# out = pipeline.create(dai.node.XLinkOut)
# out.setStreamName('features')
# features.outputFeatures.link(out.input)
if STAND_ALONE:
# # Flash the pipeline
# Try putting bootloader in location #2
(f, bl) = dai.DeviceBootloader.getFirstAvailableDevice()
bootloader = dai.DeviceBootloader(bl)
progress = lambda p : print(f'Flashing progress: {p*100:.1f}%')
bootloader.flash(progress, pipeline)
else:
oak.start() # Start the pipeline (upload it to the OAK)
q = oak.device.getOutputQueue('features') # Create output queue after calling start()
while oak.running():
if q.has():
result = q.get()
print(result)
# Since we are not in blocking mode, we have to poll oak camera to
# visualize frames, call callbacks, process keyboard keys, etc.
oak.poll()
</code></pre>
<p>but I'm getting the following error:</p>
<pre><code>Closing OAK camera
Traceback (most recent call last):
File "/Users/user/try/4-luxonis/3-http-server-standalone/oak-sdk.py", line 38, in <module>
bootloader = dai.DeviceBootloader(bl)
RuntimeError: Device not in UNBOOTED, BOOTLOADER or FLASH_BOOTED state
</code></pre>
<p>There is no explanation in the docs about these device states and how to get to one of them: UNBOOTED, BOOTLOADER or FLASH_BOOTED</p>
<p>So, I tried moving the 3 lines of code from <code>location #2</code> to <code>location #1</code>, but now I get the error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/user/try/4-luxonis/3-http-server-standalone/oak-sdk.py", line 17, in <module>
with OakCamera() as oak:
File "/Users/user/try/4-luxonis/1-baby-steps/.venv/lib/python3.10/site-packages/depthai_sdk/oak_camera.py", line 71, in __init__
self._init_device()
File "/Users/user/try/4-luxonis/1-baby-steps/.venv/lib/python3.10/site-packages/depthai_sdk/oak_camera.py", line 229, in _init_device
self._oak.device = dai.Device(
RuntimeError: Failed to connect to device, error message: X_LINK_DEVICE_NOT_FOUND
</code></pre>
<p>So, it seems there might be a conflict between using the SDK <code>OakCamera()</code> and the API <code>dai.DeviceBootloader()</code> but I don't know why the conflict is there or how to resolve it. It does seem that each of these 2 calls results in some kind of device state that does not allow the other call to proceed.</p>
| <python><sdk><luxonis> | 2023-08-29 16:17:29 | 0 | 420 | Craftonix - AA |
77,001,956 | 14,385,814 | Check duplicate data in database using Django | <p>I have a problem which I want to check if data is duplicate based on name and date_travel, let say I add an item name Lebron James and choose multiple date <code>flatpickr</code> like <code>24-08-2023, 25-08-2023</code> and the expected result should return a <code>JsonResponse</code> says Duplicate date travel since In the image below the date 24-08-2023 already exist under the name of Lebron james but my problem it always return to else statement evein it has duplicate travel, hope someone helps me thanks in advance</p>
<p><a href="https://i.sstatic.net/jYBsh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jYBsh.png" alt="enter image description here" /></a></p>
<p><strong>Here's what I've Tried</strong> I've plan to split and used loop in every date and return in if existed/duplicate in database but it won't work</p>
<pre><code>@csrf_exempt
def item_add(request):
employeename = request.POST.get('EmployeeName')
travel_date = request.POST.get('DateTravel')
# Split the date string into individual dates
individual_dates = travel_date.split(',')
for date in individual_dates:
cleaned_date = date.strip()
query = """
SELECT date_travel FROM tev_incoming
WHERE name = %s
AND date_travel LIKE %s;
"""
with connection.cursor() as cursor:
cursor.execute(query, [employeename, cleaned_date])
results = cursor.fetchall()
if results:
return JsonResponse({'data': 'error', 'Duplcate date travel':results})
else:
return JsonResponse({'data': 'success', 'message': "Unique travel and name"})
</code></pre>
<p><strong>Html input</strong></p>
<pre><code><input type="text" class="form-control" name="DateTravel" placeholder="DD-MM-YYYY" id="dateField"/>
</code></pre>
<p><strong>script</strong></p>
<pre><code> $('#dateField').flatpickr({
mode: 'multiple',
allowInput: true,
dateFormat: 'd-m-Y',
locale: {
firstDayOfWeek': 1 // start week on Monday
},
});
</code></pre>
| <python><html><django><flatpickr> | 2023-08-29 16:16:55 | 2 | 464 | BootCamp |
77,001,954 | 5,924,264 | What is "dynamic assignment of an attribute" in python? | <p>I've used Python sparingly, so maybe I'm just not privy to some verbiage. Someone at a talk today said that they want to avoid "dynamic assignment of an attribute" and didn't provide an example.</p>
<p>I know what dynamically creating an attribute of a class means, but what does dynamic assignment mean? This seems to imply that there's static assignment in python, but python is a dynamically typed language.</p>
| <python><terminology> | 2023-08-29 16:16:38 | 1 | 2,502 | roulette01 |
77,001,932 | 10,200,497 | How to trigger a command when an inline button is pressed? | <p>I want to initiate a command when an inline button is pressed.
This is the code:</p>
<pre><code>from telegram import (
ReplyKeyboardMarkup, ReplyKeyboardRemove, Update,
InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton
)
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
ConversationHandler,
CallbackQueryHandler,
MessageHandler,
filters,
)
# ---------------------------------------------------------------------------------------------
token = 'abc'
# ---------------------------------------------------------------------------------------------
async def start_func(update, context):
home_btn = [
[
InlineKeyboardButton('home', callback_data='/home'),
InlineKeyboardButton('profile', callback_data='executive_menu'),
]
]
reply_markup = InlineKeyboardMarkup(home_btn)
await update.message.reply_text('start_message', reply_markup=reply_markup)
async def thanks_func(update, context):
await update.message.reply_text('thanks_message')
async def home_func(update, context):
await update.message.reply_text('testing home 0')
await update.message.reply_text('testing home 1')
async def query_func(update, context):
query = update.callback_query
home_func(update, context)
await query.answer()
def main() -> None:
application = Application.builder().token(token).build()
# handlers /////////////////////////////////////////////////////////////
start_handler = CommandHandler('start', start_func)
thanks_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), thanks_func)
home_handler = CommandHandler('home', home_func)
query_handler = CallbackQueryHandler(query_func)
# ///////////////////////////////////////////////////////////////////////
application.add_handler(start_handler)
application.add_handler(thanks_handler)
application.add_handler(home_handler)
application.add_handler(query_handler)
# ///////////////////////////////////////////////////////////////////////
application.run_polling()
if __name__ == "__main__":
main()
</code></pre>
<p>I am using <code>python-telegram-bot == 20.4</code>. When I run <code>/start</code> it gave me home inline button. I want to run the command <code>/home</code> by pressing that button. When I type <code>/home</code> manually it worked ok. However I want to achieve exact same behavior when i press home inline button.</p>
<p>I tried to await it as can be seen in <code>query_func</code> but it didn't work. I also tried this <a href="https://stackoverflow.com/questions/62404218/send-a-command-using-inlinekeyboardbutton-python-telegram-bot">answer</a>.</p>
| <python><telegram-bot><python-telegram-bot> | 2023-08-29 16:14:52 | 1 | 2,679 | AmirX |
77,001,834 | 5,437,090 | Pandas Dataframe with dictionary cells | accumulate by values | inefficient apply method | <p><strong>Given</strong>:</p>
<p>Sample Pandas Dataframe with dictionaries in each cell:</p>
<pre><code>user_token_df = pd.DataFrame(
{
"usr": ["u1", "u2", "u3", "u4", "u7", "u9", "u5", "u8"],
"colA": [
{'a': 7, 'b': 0,'c': 1, 'd':0.1, 'e': 0.8},
{'a': 0, 'b': 1,'c': 0.1, 'd':0, 'e': 7},
{'a': 5, 'b': 2,'c': 0, 'd':0.1, 'e': 0.3},
np.nan,
{'a': 1.2, 'b': 2.6,'c': 2.2, 'd':0.3, 'e': 5.3},
{'a': 1, 'b': 0,'c': 0, 'd':0.5, 'e': 2.1},
{'a': .1, 'b': 0.7,'c': 3, 'd':1.9, 'e': 0.4},
np.nan,
],
"colB": [
{'a': 1, 'b': 2,'c': .8, 'd':0, 'e': 0.6},
np.nan,
{'a': 0.6, 'b': 5.2,'c': 0.1, 'd':0, 'e': 2.7},
{'a': 0, 'b': 2,'c': 3.0, 'd':0.1, 'e': 6.3},
{'a': 1.2, 'b': 2.6,'c': 2.2, 'd':0.3, 'e': 5.3},
np.nan,
{'a': 1, 'b': 0.3,'c': 0, 'd':0.5, 'e': 2.1},
{'a': 0, 'b': 0.5,'c': 0.6, 'd':0.9, 'e': 0},
],
"colC": [
np.nan,
{'a': 1.2, 'b': 12,'c': 1.2, 'd':0.6, 'e': 0},
{'a': 0.6, 'b': 5.2,'c': 0.1, 'd':0, 'e': 2.7},
{'a': 0.3, 'b': 2,'c': 3.0, 'd':0.1, 'e': 0.3},
{'a': 0, 'b': .6,'c': .2, 'd':.3, 'e': 5},
np.nan,
{'a': 1, 'b': 0.3,'c': 0, 'd':0.5, 'e': 2.1},
{'a': 4.3, 'b': 0.5,'c': 0.6, 'd':0.9, 'e': 0},
],
}
)
</code></pre>
<p><a href="https://i.sstatic.net/15ebm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/15ebm.png" alt="enter image description here" /></a></p>
<p><strong>Goal</strong>:</p>
<p>I'd like to create a new column <code>col_result</code> which contains dictionaries with values as accumulated values from other columns.</p>
<p><strong>Working but <em>Inefficient</em> Solution</strong>:</p>
<p>Right now, I have a working solution for small sample <code>Dataframe</code> using <code>apply</code> method and <code>Counter</code> from <code>collections</code> modules:</p>
<pre><code>from typing import Dict
from collections import Counter
import pandas as pd
import functools
def sum_dict_values(df: pd.DataFrame, vb: Dict[str, int]):
df = df.dropna()
dict_colA = dict(Counter(df.colA)) if "colA" in df else dict.fromkeys(vb.keys(), 0.0)
dict_colB = dict(Counter(df.colB)) if "colB" in df else dict.fromkeys(vb.keys(), 0.0)
dict_colC = dict(Counter(df.colC)) if "colC" in df else dict.fromkeys(vb.keys(), 0.0)
res = dict(functools.reduce(lambda a, b: a.update(b) or a, [dict_colA, dict_colB, dict_colC], Counter()))
return res
init_bow = {'a': 0, 'b': 1,'c': 2, 'd':3, 'e': 4} # to deal with columns with NaN cells
%timeit -r 10 -n 10000 user_token_df["col_result"] = user_token_df.apply(lambda row: sum_dict_values(df=row, vb=init_bow), axis=1)
# 2.12 ms ± 145 µs per loop (mean ± std. dev. of 10 runs, 10000 loops each)
</code></pre>
<p><a href="https://i.sstatic.net/J4BZb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/J4BZb.png" alt="enter image description here" /></a>
Is there any better and more efficient approach dealing with bigger size of <code>dict</code> (<code>len()>100K</code>) and <code>DataFrame</code> (<code>.shape > 20K</code>) ?</p>
<p>Cheers,</p>
| <python><pandas><performance><coding-efficiency> | 2023-08-29 16:01:21 | 1 | 1,621 | farid |
77,001,723 | 1,141,818 | Abstract class parameter in intermediary class | <p>I'm trying to define an abstract class with a mandatory argument. It works fine, but if I add an intermediary class, it may raise an exception at some point. Here is a dummy code to replicate the issue:</p>
<pre><code>from abc import ABC, abstractmethod
from typing import Dict
class AbcClass(ABC):
@classmethod
@property
@abstractmethod
def MAP(cls) -> Dict[str, str]:
raise NotImplementedError
@property
def map(self) -> Dict[str, str]:
return self.MAP
class InterClass(AbcClass):
MAP = None # NotImplementedError if not provided
@property
def text(self) -> str:
return "text"
class ConcreteClass(InterClass):
MAP = {
"a": "b"
}
c = ConcreteClass()
print(c.map)
</code></pre>
<p>With this implementation, everything's working well, but if I remove the line with the comment in the <code>InterClass</code> it raises an <code>NotImplementedError</code> exception. The point I don't understand is, I know the <code>MAP</code> parameter is mandatory, but as long as I define it in the <code>ConcreteClass</code>, why do I have to also implement it in the <code>InterClass</code> ?</p>
| <python><abstract-class> | 2023-08-29 15:47:37 | 0 | 3,575 | GuillaumeA |
77,001,599 | 16,611,809 | What's the proper way to add Python modules via PyInstaller | <p>I am using <code>PyInstaller</code> to make my Python script an macOS .app file. It all works, but after building, I need to make some manual <code>codesign</code> steps that I want to get rid of. Currently, I add some of my Python modules via <code>--add-data</code> and this seems to be the reason, why they are not properly signed. For example:</p>
<pre><code>--add-data "/abs/path/to/lib/python3.9/site-packages/numpy:numpy/"
</code></pre>
<p>If, I now change this to</p>
<pre><code>--add-binary "/abs/path/to/lib/python3.9/site-packages/numpy:numpy/"
</code></pre>
<p>I get the following error:</p>
<pre><code>ValueError: Unknown Mach-O header: 0x436f7079 in <_io.BufferedReader name='/abs/path/to/lib/python3.9/site-packages/numpy/LICENSE.txt'>
</code></pre>
<p>Looks like I'm not supposed to add Python modules via <code>--add-binary</code>. There are several options now and I'm a bit lost, on what's the correct one to use. Maybe someone could help me out there. The options, that would make sense to me would be:</p>
<pre><code>--hidden-import
--collect-binaries #(is this the pendant to --add-binaries, since there also is an --collect-data?)
--collect-all
</code></pre>
<p>Which one is it, or is it a completely different :D?</p>
| <python><pyinstaller> | 2023-08-29 15:31:45 | 0 | 627 | gernophil |
77,001,530 | 3,656,916 | Extract field in rows in array to columns | <p>I am struggling with extracting values from array of rows into columns on the highest level.
Short version of the spark dataframe is as follows</p>
<pre><code>root
|-- data: struct (nullable = true)
| |-- date: string (nullable = true)
| |-- id: string (nullable = true)
| |-- specifications: array (nullable = true) ## lots of specs here, ~20, they must go to columns
| | |-- element: struct (containsNull = true)
| | | |-- speccode: long (nullable = true) # to ignore
| | | |-- specdecryption: string (nullable = true) # to ignore
| | | |-- specname: string (nullable = true) # column name
| | | |-- specvalue: string (nullable = true) # to value in that column
| |-- begin: long (nullable = true)
| |-- end: long (nullable = true)
|-- kafka_offset: long (nullable = true) # to ignore
</code></pre>
<p>Field "specifications" is array and contains approx. 20 Rows each of them has its own keys and values. Keys are the same for all rows. Value in specname must become column name, specvalue must go into value in that column.</p>
<pre><code>'specifications':
[Row(speccode=123, specdecryption=None, specname='Color', specvalue='red'),
Row(speccode=234, specdecryption=None, specname='Power', specvalue='155'),
Row(speccode=134, specdecryption=None, specname='Speed', specvalue='198'),
Row(speccode=229, specdecryption=None, specname='Length',specvalue='4658'),...]
</code></pre>
<p>I need to convert it into a dataframe columns</p>
<pre><code>| date |id | spec_color| spec_power| spec_speed| spec_length| begin | end |
-------------------------------------------------------------------------------------------------
| 2023-08-29| 1 | red | 155 | 198 | 4698 |2023-08-29|2023-08-30|
| 2023-08-29| 2 | blue | 199 | 220 | 4540 |2023-08-29|2023-08-30|
</code></pre>
| <python><pyspark> | 2023-08-29 15:22:31 | 1 | 507 | DDR |
77,001,525 | 7,648 | Problem in migrating from PyTorch to fastai | <p>I am trying to migrate my code from PyTorch to fastai. I have the following migrated code:</p>
<pre><code> train_loader = self.init_train_dl(self.df, self.train_subjects)
test_loader = self.init_val_dl(self.df, self.val_subjects)
data = DataLoaders(train_loader, test_loader)
learn = Learner(data, AlexNet3D(4608), loss_func=F.mse_loss, opt_func=Adam, metrics=accuracy)
# learn = Learner(data, Net())
learn.fit_one_cycle(self.cli_args.epochs, self.cli_args.lr)
</code></pre>
<p>However, I am getting the exception below. What is causing this and how do I fix it?</p>
<pre><code>epoch train_loss valid_loss accuracy time
Epoch 1/1 : |----------------------------------------| 0.00% [0/135 00:00<?]python-BaseException
Traceback (most recent call last):
File "/home/faird/shared/code/external/envs/miniconda3/mini3/envs/cabinet/lib/python3.9/contextlib.py", line 137, in __exit__
self.gen.throw(typ, value, traceback)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 162, in added_cbs
try: yield
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 264, in fit
self._with_events(self._do_fit, 'fit', CancelFitException, self._end_cleanup)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 199, in _with_events
try: self(f'before_{event_type}'); f()
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 253, in _do_fit
self._with_events(self._do_epoch, 'epoch', CancelEpochException)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 199, in _with_events
try: self(f'before_{event_type}'); f()
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 247, in _do_epoch
self._do_epoch_train()
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 239, in _do_epoch_train
self._with_events(self.all_batches, 'train', CancelTrainException)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 199, in _with_events
try: self(f'before_{event_type}'); f()
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 205, in all_batches
for o in enumerate(self.dl): self.one_batch(*o)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 235, in one_batch
self._with_events(self._do_one_batch, 'batch', CancelBatchException)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 199, in _with_events
try: self(f'before_{event_type}'); f()
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/fastai/learner.py", line 219, in _do_one_batch
self.loss_grad = self.loss_func(self.pred, *self.yb)
File "/home/miran045/reine097/projects/AlexNet_Abrol2021/venv/lib/python3.9/site-packages/torch/nn/functional.py", line 3101, in mse_loss
if not (target.size() == input.size()):
AttributeError: 'list' object has no attribute 'size'
</code></pre>
| <python><pytorch><fast-ai> | 2023-08-29 15:21:40 | 1 | 7,944 | Paul Reiners |
77,001,472 | 12,730,406 | how to backwards fill in pandas with group and split dataframes by group? | <p>I have this dataframe:</p>
<pre><code>df = pd.DataFrame(data = {'genre': ['sci-fi','sci-fi','sci-fi','sci-fi','sci-fi', 'comedy',
'comedy', 'comedy', 'comedy', 'comedy', 'comedy', 'comedy'],
'score': [5,5,4,3,2,9,10,8,4,7,5,6],
'id': ["","","","stop","", "", "stop", "", "", "", "", ""]})
</code></pre>
<p>I would like to group by the different genres and backwards fill upto the id value of <strong>stop</strong></p>
<p>So my final dataframe should look like this:</p>
<pre><code>df = pd.DataFrame(data = {'genre': ['sci-fi','sci-fi','sci-fi','sci-fi','sci-fi', 'comedy',
'comedy', 'comedy', 'comedy', 'comedy', 'comedy', 'comedy'],
'score': [5,5,4,3,2,9,10,8,4,7,5,6],
'id': ["stop","stop","stop","stop","", "stop", "stop", "", "", "", "", ""]})
</code></pre>
<p>So the backwards filling only occurs from the word <strong>stop</strong> and does not go past this.</p>
<p>After this is there a way to split the dataframes into individual groups more easily than a for loop? I would like to make smaller dataframes based on the genre column e.g. a dataframe for sci-fi values only.</p>
| <python><pandas> | 2023-08-29 15:13:58 | 4 | 1,121 | Beans On Toast |
77,001,425 | 2,164,384 | Can not get correction response from Flask server when sending data by a proxy | <p>I created a simple Flask application on my tiny VPS, and started by Gunicorn with a simple command <code>gunicorn -w 2 -b 0.0.0.0:8888 app:app --access-logfile=- --proxy-protocol</code>.</p>
<p>I tried the code below on my local PC with Python requests</p>
<pre><code>import requests
url= 'http://124.202.218.128:5000/new/'
resp = requests.post(url, data=data)
proxies = {'http': 'http://127.0.0.1:7890'}
resp2 = requests.post(url, data=data, proxies=proxies)
</code></pre>
<p>The <code>resp</code> returned a correct data with HTTP code 200, the <code>resp2</code> with a proxy get a 502 error code. This proxy <code>http://127.0.0.1:7890</code> is valid when I use it in my browser.</p>
<p>How can I update flask or gunicord to receive data from proxied post?</p>
| <python><flask><proxy><gunicorn> | 2023-08-29 15:08:13 | 0 | 783 | l0o0 |
77,001,309 | 11,329,736 | Snakemake: wildcard restriction | <p>I have the following <code>Snakemake</code> rules (I have only shown the relevant parts):</p>
<pre><code>SAMPLE_IP = ['control_1_hif1a_hyp', 'control_2_hif1a_hyp']
SAMPLE_INPUT = ['control_1_input_hyp', 'control_2_input_hyp']
rule all:
input:
expand("bigwig/compare/{sample_ip}_vs_{sample_input}.bw", sample_ip=SAMPLE_IP, sample_input=SAMPLE_INPUT),]
rule bigwig_sample_vs_input:
input:
ip="mapped/{sample_ip}_dedup.bam",
inpt="mapped/{sample_input}_dedup.bam",
output:
"bigwig/compare/{sample_ip}_vs_{sample_input}.bw",
params:
bs=config["general"]["bigwig"]["binSize"],
threads: config["resources"]["deeptools"]["cpu"]
resources:
runtime=config["resources"]["deeptools"]["time"]
conda:
"envs/chipseq.yaml"
shell:
"bamCompare -p {threads} -bs {params.bs} -b1 {input.ip} -b2 {input.inpt} "
</code></pre>
<p>The rule works but <code>Snakemake</code> creates four <code>.bw</code> files with these values:</p>
<pre><code>sample_input: control_1_input_hyp
sample_ip: control_1_hif1a_hyp
sample_input: control_2_input_hyp
sample_ip: control_1_hif1a_hyp
sample_input: control_1_input_hyp
sample_ip: control_2_hif1a_hyp
sample_input: control_2_input_hyp
sample_ip: control_2_hif1a_hyp
</code></pre>
<p>But I only want to use:</p>
<pre><code>sample_input: control_1_input_hyp
sample_ip: control_1_hif1a_hyp
sample_input: control_2_input_hyp
sample_ip: control_2_hif1a_hyp
</code></pre>
<p>How can I tell <code>Snakemake</code> to only combine the elements from <code>SAMPLE_IP</code> and <code>SAMPLE_INPUT</code> that have the same position in these lists?</p>
| <python><python-3.x><wildcard><snakemake><expansion> | 2023-08-29 14:55:16 | 1 | 1,095 | justinian482 |
77,001,239 | 4,118,462 | pytest: How to use temporary folders in a class-scoped fixture? | <p>Is there a way to share a temporary folder just across the tests in class?</p>
<p>This <a href="https://docs.pytest.org/en/7.1.x/how-to/tmp_path.html" rel="nofollow noreferrer">pytest doc</a> mentions the function-scoped tmp_path and session-scoped tmp_path_factory fixtures. Didn't say anything about class scope.<br />
The code below, as expected, does not work because it attempts to scope tmp_path fixture at the class level. Is there a way to make it work?</p>
<pre><code>import pytest
class TestMyClass:
@pytest.fixture(scope='class')
def new_path(self, tmp_path):
return tmp_path / 'subdir'
def test_this(self, new_path):
assert True
def test_that(self, new_path):
assert True
</code></pre>
<p>The error message is:</p>
<blockquote>
<p>test setup failed<br />
ScopeMismatch: You tried to access the function scoped fixture tmp_path with a class scoped request object, involved factories:</p>
</blockquote>
| <python><python-3.x><pytest><fixtures> | 2023-08-29 14:46:34 | 2 | 395 | MCornejo |
77,001,206 | 11,426,624 | How to add a background color from a dataframe to segments of a line plot | <p>I have a dataframe as below and would like to get a plot with a line and background colour either red or white (depending on the value of color_var).</p>
<pre><code> line_var color_var
datetime
2023-04-20 13:45 3 1
2023-04-20 14:00 4 0
2023-04-20 15:00 5 0
2023-04-20 15:15 4 1
2023-04-20 15:45 3 1
2023-04-20 16:00 5 1
2023-04-20 16:45 6 0
2023-04-20 17:45 7 0
2023-04-20 18:00 5 0
2023-04-20 18:45 6 1
2023-04-20 19:45 8 1
2023-04-21 13:45 9 0
</code></pre>
<p>The below code</p>
<pre><code>import pandas as pd
import numpy as np
from matplotlib import dates as mdates
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
df = pd.DataFrame({'datetime':['2023-04-20 13:45','2023-04-20 14:00','2023-04-20 15:00',
'2023-04-20 15:15','2023-04-20 15:45','2023-04-20 16:00','2023-04-20 16:45','2023-04-20 17:45','2023-04-20 18:00','2023-04-20 18:45','2023-04-20 19:45','2023-04-21 13:45'],
'line_var':[3,4,5,4,3,5,6,7,5,6,8,9],
'color_var':[1,0,0,1,1,1,0,0,0,1,1,0]})
df = df.assign(datetime=pd.to_datetime(df.datetime))
df = df.set_index('datetime')
cmap = ListedColormap(['white','red'])
fig = plt.figure(figsize=(50,10))
ax = fig.add_subplot()
ax.plot(df['line_var'])
ax.set_xlabel('')
plt.xticks(rotation = 30)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
#this gives an error
ax.pcolor(df.index, ax.get_ylim(),
df['color_var'].values[np.newaxis].T,
cmap = cmap, alpha = 0.4,
linewidth=0, antialiased=True, shading='nearest')
plt.axhline(y = 0, color = 'black')
plt.tight_layout()
</code></pre>
<p>throws the error</p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[21], line 21
18 ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
20 #this gives an error
---> 21 ax.pcolor(df.index, ax.get_ylim(),
22 df['color_var'].values[np.newaxis].T,
23 cmap = cmap, alpha = 0.4,
24 linewidth=0, antialiased=True, shading='nearest')
25 plt.axhline(y = 0, color = 'black')
26 plt.tight_layout()
File ~\anaconda3\envs\py11\Lib\site-packages\matplotlib\__init__.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1439 @functools.wraps(func)
1440 def inner(ax, *args, data=None, **kwargs):
1441 if data is None:
-> 1442 return func(ax, *map(sanitize_sequence, args), **kwargs)
1444 bound = new_sig.bind(ax, *args, **kwargs)
1445 auto_label = (bound.arguments.get(label_namer)
1446 or bound.kwargs.get(label_namer))
File ~\anaconda3\envs\py11\Lib\site-packages\matplotlib\axes\_axes.py:5946, in Axes.pcolor(self, shading, alpha, norm, cmap, vmin, vmax, *args, **kwargs)
5944 shading = mpl.rcParams['pcolor.shading']
5945 shading = shading.lower()
-> 5946 X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading,
5947 kwargs=kwargs)
5948 Ny, Nx = X.shape
5950 # convert to MA, if necessary.
File ~\anaconda3\envs\py11\Lib\site-packages\matplotlib\axes\_axes.py:5757, in Axes._pcolorargs(self, funcname, shading, *args, **kwargs)
5755 else: # ['nearest', 'gouraud']:
5756 if (Nx, Ny) != (ncols, nrows):
-> 5757 raise TypeError('Dimensions of C %s are incompatible with'
5758 ' X (%d) and/or Y (%d); see help(%s)' % (
5759 C.shape, Nx, Ny, funcname))
5760 if shading == 'nearest':
5761 # grid is specified at the center, so define corners
5762 # at the midpoints between the grid centers and then use the
5763 # flat algorithm.
5764 def _interp_grid(X):
5765 # helper for below
TypeError: Dimensions of C (12, 1) are incompatible with X (12) and/or Y (2); see help(pcolor)
</code></pre>
<p>I read here <a href="https://stackoverflow.com/questions/24791614/numpy-pcolormesh-typeerror-dimensions-of-c-are-incompatible-with-x-and-or-y">Numpy pcolormesh: TypeError: Dimensions of C are incompatible with X and/or Y</a> that I should transpose my array but it doesn't work or I'm not doing it correctly.</p>
| <python><pandas><matplotlib> | 2023-08-29 14:42:36 | 1 | 734 | corianne1234 |
77,001,193 | 2,836,172 | Recursive loop unpacking too many values in Jinja2 | <p>I try to display a dict, which depth is unknown and represents a file tree, with a recursive loop. This is my simple example data:</p>
<pre><code>{
"smartphone":{
"upload_1693308862":{
"image1.png":{
"url":"<url comes here>"
},
"image2.png":{
"url":"<url comes here>"
},
"image3.png":{
"url":"<url comes here>"
},
"image4.png":{
"url":"<url comes here>"
}
}
}
}
</code></pre>
<p>And this is my jinja code:</p>
<pre><code>{%- for level, subdict in file_structure.items() recursive %}
<li>
{%- if level.url -%}
<a href="{{ level.url }}">{{ level }}</a>
{% elif subdict is iterable and subdict is not string %}
{{ level }}
<ul class="submenu">{{ loop(subdict) }}</ul>
{% else %}
{{ level }}
{% endif %}
</li>
{%- endfor %}
</ul>
</code></pre>
<p>The exception I get is this one:</p>
<pre><code>2023-08-29T14:25:56.480784300Z {%- for level, subdict in file_structure.items() recursive %}
2023-08-29T14:25:56.480785800Z ValueError: too many values to unpack (expected 2)
</code></pre>
<p>Shouldn't <code>items()</code> always return exactly two values? What's wrong here?</p>
| <python><jinja2> | 2023-08-29 14:40:38 | 0 | 1,522 | Standard |
77,001,129 | 127,508 | How to configure FastAPI logging so that it works both with Uvicorn locally and in production? | <p>I have the following FastAPI application:</p>
<pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI
import logging
import uvicorn
app = FastAPI(title="api")
LOG = logging.getLogger(__name__)
LOG.info("API is starting up")
LOG.info(uvicorn.Config.asgi_version)
@app.get("/")
async def get_index():
LOG.info("GET /")
return {"Hello": "Api"}
</code></pre>
<p>The application locally is run with:</p>
<pre class="lang-bash prettyprint-override"><code>uvicorn api:app --reload
</code></pre>
<pre class="lang-py prettyprint-override"><code>INFO: Will watch for changes in these directories: ['/Users/user/code/backend/api']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [44258] using StatReload
INFO: Started server process [44260]
INFO: Waiting for application startup.
INFO: Application startup complete.
</code></pre>
<p>It is not logging any of the startup messages. Later on when sending an HTTP request to the API:</p>
<pre class="lang-bash prettyprint-override"><code>INFO: 127.0.0.1:50538 - "POST /api/v1/endpoint HTTP/1.1" 200 OK
</code></pre>
<p>in the function body, there is <code>LOG.info("example")</code> that does not get logged either. Is there a way to make FastAPI logging work with Uvicorn and also in production (independently of the execution environments like Uvicorn)?</p>
| <python><logging><fastapi><uvicorn> | 2023-08-29 14:32:37 | 3 | 8,822 | Istvan |
77,001,053 | 2,876,079 | How to update pip and keep the new version of pip portable (=use relative path to python.exe)? | <p>I use WinPython as portable app on Windows and get following hint:</p>
<pre><code>A new release of pip is available: 23.1.2 -> 23.2.1
[notice] To update, run: python.exe -m pip install --upgrade pip
</code></pre>
<p>If I run the command as suggested, the new version of pip stores the absolute path to python.exe.</p>
<p>If I <strong>move my IDE folder to another location</strong>, <strong>pip does not work any more</strong>:</p>
<pre><code>pip list
Fatal error in launcher: Unable to create process using '"C:\python_env\App\WinPython\python-3.11.1.amd64\python.exe" "D:\eis\python_env\App\WinPython\python-3.11.1.amd64\Scripts\pip.exe" list': The system cannot find the file specified.
</code></pre>
<p>=> Is there a way to tell pip to store a relative path to python.exe instead of an absolute one, so that pip remains portable?</p>
<p>=> Or is there some configuration file that I could fix after installing pip, for example some pip._pth file? Where to put it?</p>
| <python><pip><portable-applications> | 2023-08-29 14:21:32 | 2 | 12,756 | Stefan |
77,000,845 | 7,486,038 | XGBOOST Model predicting, with nan Input values | <p>I am facing a weird behavior in the xgboost classifier. Reproducing the code from a response to <a href="https://stackoverflow.com/questions/61082381/xgboost-produce-prediction-result-and-probability">this</a> post</p>
<pre><code>import xgboost as xgb
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
X, y = make_moons(noise=0.3, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)
xgb_clf = xgb.XGBClassifier()
xgb_clf = xgb_clf.fit(X_train, y_train)
print(xgb_clf.predict(X_test))
print(xgb_clf.predict_proba(X_test))
>>[0 0 1 0 0 1 0 0 1 1]
[[0.97378635 0.02621362]
[0.97106457 0.0289354 ]
[0.45146966 0.54853034]
[0.9181994 0.08180059]
[0.97378635 0.02621362]
[0.4264453 0.5735547 ]
[0.6279408 0.37205923]
[0.991474 0.00852604]
[0.06204838 0.9379516 ]
[0.08833408 0.9116659 ]]
</code></pre>
<p>So far so good. However , when the input contains all nan values, even then the model makes a prediction.</p>
<pre><code>b = np.empty([3,2])
b[:] = np.nan
xgb_clf.predict_proba(b)
>>array([[0.8939177 , 0.10608231],
[0.8939177 , 0.10608231],
[0.8939177 , 0.10608231]], dtype=float32)
</code></pre>
<p>This caught me completely off-guard. Am I missing some parameter , that can make the classifier prediction output also nan</p>
| <python><classification><xgboost> | 2023-08-29 13:53:53 | 2 | 326 | Arindam |
77,000,806 | 11,317,776 | Clearing cache of aiocache from unit test | <p>In FastAPI I have an endpoint:</p>
<pre><code>from aiocache import Cache, cached
@router.get("/id/{user_id}/permissions")
@cached(ttl=30, cache=Cache.MEMORY)
async def get_permissions(user_id: UUID4) -> list[Permissions]:
</code></pre>
<p>And then in my unit test, I want to clear the cache.</p>
<p>I have tried recreating the cache with a namespace, key. Currently I have:</p>
<pre><code>from my_module import get_permissions
my_cache = get_permissions.cache
await my_cache.clear()
</code></pre>
<p>I have tried every imaginable combination. But I cannot get this asynchronous test to clear my cache. Any ideas? What am I doing wrong? Could it be there are in different processes?</p>
| <python><asynchronous><caching><fastapi><aio> | 2023-08-29 13:48:27 | 2 | 3,048 | DUDANF |
77,000,608 | 16,883,182 | How to prevent race conditions between the UI thread and a different one who both access the same list without blocking the UI thread? | <p>I'm currently working on a GUI toolkit from the ground up in Pygame just for the learning experience, and I'm running into a problem while working on the directory-tree widget. Let me explain the multi-threading system I'm using.</p>
<p>All node objects are stored in a flat list. When a node is expanded, the UI thread adds a node which displays <code>Loading...</code> as a child-node to the expanded node, and it starts a background thread which will load the directory structure that the expanded node represents, and push the result into a queue that the UI thread and loader thread share. There's no limit to how many "loader threads" can run at the same time, as they will all dump the loaded data into a tuple in the same queue. The UI thread will empty the queue every frame and create all child-nodes needed to represent the newly loaded directories under the correct parent nodes. And if a node is un-expanded, the UI thread simply deletes all nodes after the index of the un-expanded node which have a nested level greater than it. Also, when a specific node is expanded for the first time, a cache file which stores the sub-directory data of the directory that the node represents is created. If the exact same node is expanded again in the future, directory data will be read from the cache instead of from the filesystem to optimize the loading speed.</p>
<p>Everything works up to here, but then I realized that with the current design, the treeview only checks the filesystem the first time each node is expanded. So once a node is expanded, changes to the filesystem would not be reflected even if the node is re-expanded (since it would read from the cache). So I wrote a 'refresh' function which simply deletes the entire cache directory using <code>shutil.rmtree</code>. That way, when a node is expanded/re-expanded after the refresh, it will read from the filesystem and re-create the cache for that directory. But the problem is, removing the cache directory won't affect nodes that are already expanded. The changes for those won't be reflected until they are re-expanded. Therefore, I wrote an algorithm that checks through the entire node-list and updates it to match the filesystem (it will detech directories that exist in the filesystem but not the treeview and add them, and will also remove nodes that no longer exist in the filesystem). And of course, to prevent blocking the UI thread, the program spawns a new thread when the 'refresh' button is clicked. And here's where the problem began: what do I do if the user collapses a node while the 'refresh thread' is running? I've already added code to stop the user from expanding nodes by making newly spawned 'loading threads' detect if the 'refresh thread' is running, and suspend itself if it is (which would make the expanded node display <code>Loading...</code> below it until the 'loading thread' in charge of it is allowed to proceed and finishes loading), but what do I do about collapsing? It wouldn't make sense to make collapsing a node say 'loading'. But if I don't stop the user from collapsing nodes, the main thread would modify the node-list while the 'refresh thread' is actively reading and writing to it. This would both mess up the algorithm in the 'refresh thread' and (probably) corrupt data in the node-list.</p>
<p>After some thinking, I thought of three faint ideas, but they all aren't very good... My first idea is to use a 'threading.Lock' object in both the main thread and the 'refresh thread', and (in both threads) lock it every time right before making a change to the list, and unlock it right after the statement which modifies the list. But although this would make sure the data in the list won't be left corrupted due to being written to by two threads at the same time, it won't stop the main thread from changing the length and content of the list while the algorithm in the 'refresh thread' is working (which would mess it up). I could also make the thread lock the lock at the beginning and keep it locked until just before the thread ends. But then that would mean if the user collapses a node after clicking refresh, the UI thread would freeze until the 'refresh thread' is done...</p>
<p>My other idea is to modify the 'refresh thread' so that it makes a copy of the node-list when it starts, and modifies <em>that</em> instead of the real node-list. Then when the thread is done, I'll assign that copy of the list to <code>self.nodes</code> (the variable used to store the list), which would replace it. But the problem with this plan is that this would mean all changes made to the list by the user during the time the 'refresh thread' is running will be overwritten.</p>
<p>My third idea is to modify the 'refresh thread' so that instead of actually modifying the node-list, it adds multiple items to a queue to tell the main thread which indexes in the node-list to remove, and what items to add at which index. But this probably would be really hard to implement, since every time the user collapses a node, the indexes of the same items would change...</p>
<p>I'm simply out of ideas on how to proceed at this point, unless I really stop the user from collapsing nodes while the 'refresh thread' is running. So I would really appreciate a suggestion on what to do.</p>
| <python><multithreading><user-interface><concurrency><race-condition> | 2023-08-29 13:20:19 | 1 | 315 | I Like Python |
77,000,525 | 9,190,503 | Apify Scrapy template returns Attribute error | <p>I install the Scrapy template from Apify CLI and run it as <a href="https://blog.apify.com/web-scraping-with-scrapy/#creating-a-new-actor" rel="nofollow noreferrer">intructed</a>. I don't do any changes.</p>
<p>When I deploy it to Apify, the same problem occurs. Even when I used the same template from Apify console and create a new one, the same error happens again.</p>
<p>Error:</p>
<pre><code>AttributeError: 'AsyncioSelectorReactor' object has no attribute '_handleSignals'
</code></pre>
<p>I'm using Python 3.11 on M1 Macbook.
How can I solve it?</p>
| <python><web-scraping><apify> | 2023-08-29 13:09:24 | 1 | 1,041 | Ulvi |
77,000,439 | 20,762,114 | Cumulative Max Sum in Polars | <p>In the following dataframe, I want to populate the column <code>cum_max_sum</code> using the columns <code>minimum</code> and <code>to_add</code>. How can I achieve this using Polars operations?</p>
<pre><code>┌──────────────────┬─────────┬────────┬─────────────┐
│ prev_cum_max_sum ┆ minimum ┆ to_add ┆ cum_max_sum │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞══════════════════╪═════════╪════════╪═════════════╡
│ null ┆ 1 ┆ 5 ┆ 6 │
│ 6 ┆ 4 ┆ 6 ┆ 12 │
│ 12 ┆ 13 ┆ 7 ┆ 20 │
└──────────────────┴─────────┴────────┴─────────────┘
</code></pre>
<p>Explanation:</p>
<p><code>max(null, 1) + 5 = 6</code></p>
<p><code>max(6, 4) + 6 = 12</code></p>
<p><code>max(12, 13) + 7 = 20</code></p>
| <python><dataframe><python-polars> | 2023-08-29 12:58:12 | 2 | 317 | T.H Rice |
77,000,400 | 11,399,142 | List and download files in a folder in a blob with blob level SAS token | <p>I got a SAS token which was created for a specific folder on my Azure Datalake Gen2. The goal is, to download the folder with all its contents.</p>
<p>I understand, that I can create a DataLakeServiceClient, a FileSystemClient, or a DataLakeDirectoryClient as follows:</p>
<pre><code># configuration
url = 'https://my-account.blob.core.windows.net'
sas_token = '<sas-token>'
file_system_name = 'file_system_1'
subfolder_path = 'subfolder_1'
# service client
data_lake_service_client = DataLakeServiceClient(account_url=url, credential=sas_token)
# directory client and file system client
file_system_client = data_lake_service_client.get_file_system_client(file_system=file_system_name)
data_lake_directory_client = data_lake_service_client.get_directory_client(file_system=file_system_name, directory=subfolder_path)
</code></pre>
<p>Now to download specific files, I need to know what files exist:</p>
<ul>
<li><p>Unfortunately, the <code>DataLakeDirectoryClient</code> does not have a function to get all paths of the files inside that directory.</p>
</li>
<li><p>On the other hand, the <code>FileSystemClient</code> has that function but is searching on the file system level, where my SAS token does not have access.</p>
</li>
</ul>
<p>How do I list and download all files in my directory?</p>
| <python><azure><azure-data-lake-gen2> | 2023-08-29 12:52:58 | 3 | 1,148 | elyptikus |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.