Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
from_pandas_points_labels | (df) | Convert point ``pandas.DataFrame`` to list of tuples.
Convert a ``pandas.DataFrame`` of labeled data where each
timestamp is labeled by either 0 or 1 to a list of tuples
marking the start and end interval of anomalies; make it
contextually defined.
Args:
df (DataFrame):
anomal... | Convert point ``pandas.DataFrame`` to list of tuples. | def from_pandas_points_labels(df):
""" Convert point ``pandas.DataFrame`` to list of tuples.
Convert a ``pandas.DataFrame`` of labeled data where each
timestamp is labeled by either 0 or 1 to a list of tuples
marking the start and end interval of anomalies; make it
contextually defined.
Args:
... | [
"def",
"from_pandas_points_labels",
"(",
"df",
")",
":",
"require",
"=",
"[",
"'timestamp'",
",",
"'label'",
"]",
"columns",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"if",
"not",
"all",
"(",
"x",
"in",
"columns",
"for",
"x",
"in",
"require",... | [
99,
0
] | [
127,
33
] | python | en | ['en', 'lb', 'en'] | True |
from_list_points_labels | (labels) | Convert list of labels to list of tuples.
Convert a list of labels to a list of tuples
marking the start and end interval of anomalies by
defining a dummy timestamp range for usage.
Args:
labels (list): contains binary labels [0, 1].
Returns:
list:
tuple (start, end) ... | Convert list of labels to list of tuples. | def from_list_points_labels(labels):
""" Convert list of labels to list of tuples.
Convert a list of labels to a list of tuples
marking the start and end interval of anomalies by
defining a dummy timestamp range for usage.
Args:
labels (list): contains binary labels [0, 1].
Returns:
... | [
"def",
"from_list_points_labels",
"(",
"labels",
")",
":",
"timestamps",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"labels",
")",
")",
"return",
"from_pandas_points_labels",
"(",
"pd",
".",
"DataFrame",
"(",
"{",
"\"timestamp\"",
":",
"timestamps",
",",
"\"... | [
130,
0
] | [
146,
94
] | python | en | ['en', 'en', 'en'] | True |
memory_stream_pump | (memory_send_stream, memory_receive_stream, *, max_bytes=None) | Take data out of the given :class:`MemorySendStream`'s internal buffer,
and put it into the given :class:`MemoryReceiveStream`'s internal buffer.
Args:
memory_send_stream (MemorySendStream): The stream to get data from.
memory_receive_stream (MemoryReceiveStream): The stream to put data into.
... | Take data out of the given :class:`MemorySendStream`'s internal buffer,
and put it into the given :class:`MemoryReceiveStream`'s internal buffer. | def memory_stream_pump(memory_send_stream, memory_receive_stream, *, max_bytes=None):
"""Take data out of the given :class:`MemorySendStream`'s internal buffer,
and put it into the given :class:`MemoryReceiveStream`'s internal buffer.
Args:
memory_send_stream (MemorySendStream): The stream to get dat... | [
"def",
"memory_stream_pump",
"(",
"memory_send_stream",
",",
"memory_receive_stream",
",",
"*",
",",
"max_bytes",
"=",
"None",
")",
":",
"try",
":",
"data",
"=",
"memory_send_stream",
".",
"get_data_nowait",
"(",
"max_bytes",
")",
"except",
"_core",
".",
"WouldB... | [
262,
0
] | [
292,
15
] | python | en | ['en', 'en', 'en'] | True |
memory_stream_one_way_pair | () | Create a connected, pure-Python, unidirectional stream with infinite
buffering and flexible configuration options.
You can think of this as being a no-operating-system-involved
Trio-streamsified version of :func:`os.pipe` (except that :func:`os.pipe`
returns the streams in the wrong order – we follow t... | Create a connected, pure-Python, unidirectional stream with infinite
buffering and flexible configuration options. | def memory_stream_one_way_pair():
"""Create a connected, pure-Python, unidirectional stream with infinite
buffering and flexible configuration options.
You can think of this as being a no-operating-system-involved
Trio-streamsified version of :func:`os.pipe` (except that :func:`os.pipe`
returns the... | [
"def",
"memory_stream_one_way_pair",
"(",
")",
":",
"send_stream",
"=",
"MemorySendStream",
"(",
")",
"recv_stream",
"=",
"MemoryReceiveStream",
"(",
")",
"def",
"pump_from_send_stream_to_recv_stream",
"(",
")",
":",
"memory_stream_pump",
"(",
"send_stream",
",",
"rec... | [
295,
0
] | [
330,
35
] | python | en | ['en', 'en', 'en'] | True |
memory_stream_pair | () | Create a connected, pure-Python, bidirectional stream with infinite
buffering and flexible configuration options.
This is a convenience function that creates two one-way streams using
:func:`memory_stream_one_way_pair`, and then uses
:class:`~trio.StapledStream` to combine them into a single bidirectio... | Create a connected, pure-Python, bidirectional stream with infinite
buffering and flexible configuration options. | def memory_stream_pair():
"""Create a connected, pure-Python, bidirectional stream with infinite
buffering and flexible configuration options.
This is a convenience function that creates two one-way streams using
:func:`memory_stream_one_way_pair`, and then uses
:class:`~trio.StapledStream` to comb... | [
"def",
"memory_stream_pair",
"(",
")",
":",
"return",
"_make_stapled_pair",
"(",
"memory_stream_one_way_pair",
")"
] | [
341,
0
] | [
415,
57
] | python | en | ['en', 'en', 'en'] | True |
lockstep_stream_one_way_pair | () | Create a connected, pure Python, unidirectional stream where data flows
in lockstep.
Returns:
A tuple
(:class:`~trio.abc.SendStream`, :class:`~trio.abc.ReceiveStream`).
This stream has *absolutely no* buffering. Each call to
:meth:`~trio.abc.SendStream.send_all` will block until all the gi... | Create a connected, pure Python, unidirectional stream where data flows
in lockstep. | def lockstep_stream_one_way_pair():
"""Create a connected, pure Python, unidirectional stream where data flows
in lockstep.
Returns:
A tuple
(:class:`~trio.abc.SendStream`, :class:`~trio.abc.ReceiveStream`).
This stream has *absolutely no* buffering. Each call to
:meth:`~trio.abc.SendS... | [
"def",
"lockstep_stream_one_way_pair",
"(",
")",
":",
"lbq",
"=",
"_LockstepByteQueue",
"(",
")",
"return",
"_LockstepSendStream",
"(",
"lbq",
")",
",",
"_LockstepReceiveStream",
"(",
"lbq",
")"
] | [
550,
0
] | [
574,
64
] | python | en | ['en', 'en', 'en'] | True |
lockstep_stream_pair | () | Create a connected, pure-Python, bidirectional stream where data flows
in lockstep.
Returns:
A tuple (:class:`~trio.StapledStream`, :class:`~trio.StapledStream`).
This is a convenience function that creates two one-way streams using
:func:`lockstep_stream_one_way_pair`, and then uses
:class:... | Create a connected, pure-Python, bidirectional stream where data flows
in lockstep. | def lockstep_stream_pair():
"""Create a connected, pure-Python, bidirectional stream where data flows
in lockstep.
Returns:
A tuple (:class:`~trio.StapledStream`, :class:`~trio.StapledStream`).
This is a convenience function that creates two one-way streams using
:func:`lockstep_stream_one_w... | [
"def",
"lockstep_stream_pair",
"(",
")",
":",
"return",
"_make_stapled_pair",
"(",
"lockstep_stream_one_way_pair",
")"
] | [
577,
0
] | [
590,
59
] | python | en | ['en', 'en', 'en'] | True |
MemorySendStream.send_all | (self, data) | Places the given data into the object's internal buffer, and then
calls the :attr:`send_all_hook` (if any).
| Places the given data into the object's internal buffer, and then
calls the :attr:`send_all_hook` (if any). | async def send_all(self, data):
"""Places the given data into the object's internal buffer, and then
calls the :attr:`send_all_hook` (if any).
"""
# Execute two checkpoints so we have more of a chance to detect
# buggy user code that calls this twice at the same time.
wi... | [
"async",
"def",
"send_all",
"(",
"self",
",",
"data",
")",
":",
"# Execute two checkpoints so we have more of a chance to detect",
"# buggy user code that calls this twice at the same time.",
"with",
"self",
".",
"_conflict_detector",
":",
"await",
"_core",
".",
"checkpoint",
... | [
110,
4
] | [
122,
42
] | python | en | ['en', 'en', 'en'] | True |
MemorySendStream.wait_send_all_might_not_block | (self) | Calls the :attr:`wait_send_all_might_not_block_hook` (if any), and
then returns immediately.
| Calls the :attr:`wait_send_all_might_not_block_hook` (if any), and
then returns immediately. | async def wait_send_all_might_not_block(self):
"""Calls the :attr:`wait_send_all_might_not_block_hook` (if any), and
then returns immediately.
"""
# Execute two checkpoints so we have more of a chance to detect
# buggy user code that calls this twice at the same time.
wi... | [
"async",
"def",
"wait_send_all_might_not_block",
"(",
"self",
")",
":",
"# Execute two checkpoints so we have more of a chance to detect",
"# buggy user code that calls this twice at the same time.",
"with",
"self",
".",
"_conflict_detector",
":",
"await",
"_core",
".",
"checkpoint... | [
124,
4
] | [
137,
63
] | python | en | ['en', 'en', 'en'] | True |
MemorySendStream.close | (self) | Marks this stream as closed, and then calls the :attr:`close_hook`
(if any).
| Marks this stream as closed, and then calls the :attr:`close_hook`
(if any). | def close(self):
"""Marks this stream as closed, and then calls the :attr:`close_hook`
(if any).
"""
# XXX should this cancel any pending calls to the send_all_hook and
# wait_send_all_might_not_block_hook? Those are the only places where
# send_all and wait_send_all_mig... | [
"def",
"close",
"(",
"self",
")",
":",
"# XXX should this cancel any pending calls to the send_all_hook and",
"# wait_send_all_might_not_block_hook? Those are the only places where",
"# send_all and wait_send_all_might_not_block can be blocked.",
"#",
"# The way we set things up, send_all_hook i... | [
139,
4
] | [
154,
29
] | python | en | ['en', 'en', 'en'] | True |
MemorySendStream.aclose | (self) | Same as :meth:`close`, but async. | Same as :meth:`close`, but async. | async def aclose(self):
"""Same as :meth:`close`, but async."""
self.close()
await _core.checkpoint() | [
"async",
"def",
"aclose",
"(",
"self",
")",
":",
"self",
".",
"close",
"(",
")",
"await",
"_core",
".",
"checkpoint",
"(",
")"
] | [
156,
4
] | [
159,
32
] | python | en | ['en', 'gd', 'en'] | True |
MemorySendStream.get_data | (self, max_bytes=None) | Retrieves data from the internal buffer, blocking if necessary.
Args:
max_bytes (int or None): The maximum amount of data to
retrieve. None (the default) means to retrieve all the data
that's present (but still blocks until at least one byte is
available).
... | Retrieves data from the internal buffer, blocking if necessary. | async def get_data(self, max_bytes=None):
"""Retrieves data from the internal buffer, blocking if necessary.
Args:
max_bytes (int or None): The maximum amount of data to
retrieve. None (the default) means to retrieve all the data
that's present (but still blocks un... | [
"async",
"def",
"get_data",
"(",
"self",
",",
"max_bytes",
"=",
"None",
")",
":",
"return",
"await",
"self",
".",
"_outgoing",
".",
"get",
"(",
"max_bytes",
")"
] | [
161,
4
] | [
175,
50
] | python | en | ['en', 'en', 'en'] | True |
MemorySendStream.get_data_nowait | (self, max_bytes=None) | Retrieves data from the internal buffer, but doesn't block.
See :meth:`get_data` for details.
Raises:
trio.WouldBlock: if no data is available to retrieve.
| Retrieves data from the internal buffer, but doesn't block. | def get_data_nowait(self, max_bytes=None):
"""Retrieves data from the internal buffer, but doesn't block.
See :meth:`get_data` for details.
Raises:
trio.WouldBlock: if no data is available to retrieve.
"""
return self._outgoing.get_nowait(max_bytes) | [
"def",
"get_data_nowait",
"(",
"self",
",",
"max_bytes",
"=",
"None",
")",
":",
"return",
"self",
".",
"_outgoing",
".",
"get_nowait",
"(",
"max_bytes",
")"
] | [
177,
4
] | [
186,
51
] | python | en | ['en', 'lb', 'en'] | True |
MemoryReceiveStream.receive_some | (self, max_bytes=None) | Calls the :attr:`receive_some_hook` (if any), and then retrieves
data from the internal buffer, blocking if necessary.
| Calls the :attr:`receive_some_hook` (if any), and then retrieves
data from the internal buffer, blocking if necessary. | async def receive_some(self, max_bytes=None):
"""Calls the :attr:`receive_some_hook` (if any), and then retrieves
data from the internal buffer, blocking if necessary.
"""
# Execute two checkpoints so we have more of a chance to detect
# buggy user code that calls this twice at ... | [
"async",
"def",
"receive_some",
"(",
"self",
",",
"max_bytes",
"=",
"None",
")",
":",
"# Execute two checkpoints so we have more of a chance to detect",
"# buggy user code that calls this twice at the same time.",
"with",
"self",
".",
"_conflict_detector",
":",
"await",
"_core"... | [
215,
4
] | [
236,
23
] | python | en | ['en', 'en', 'en'] | True |
MemoryReceiveStream.close | (self) | Discards any pending data from the internal buffer, and marks this
stream as closed.
| Discards any pending data from the internal buffer, and marks this
stream as closed. | def close(self):
"""Discards any pending data from the internal buffer, and marks this
stream as closed.
"""
self._closed = True
self._incoming.close_and_wipe()
if self.close_hook is not None:
self.close_hook() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"_incoming",
".",
"close_and_wipe",
"(",
")",
"if",
"self",
".",
"close_hook",
"is",
"not",
"None",
":",
"self",
".",
"close_hook",
"(",
")"
] | [
238,
4
] | [
246,
29
] | python | en | ['en', 'en', 'en'] | True |
MemoryReceiveStream.aclose | (self) | Same as :meth:`close`, but async. | Same as :meth:`close`, but async. | async def aclose(self):
"""Same as :meth:`close`, but async."""
self.close()
await _core.checkpoint() | [
"async",
"def",
"aclose",
"(",
"self",
")",
":",
"self",
".",
"close",
"(",
")",
"await",
"_core",
".",
"checkpoint",
"(",
")"
] | [
248,
4
] | [
251,
32
] | python | en | ['en', 'gd', 'en'] | True |
MemoryReceiveStream.put_data | (self, data) | Appends the given data to the internal buffer. | Appends the given data to the internal buffer. | def put_data(self, data):
"""Appends the given data to the internal buffer."""
self._incoming.put(data) | [
"def",
"put_data",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_incoming",
".",
"put",
"(",
"data",
")"
] | [
253,
4
] | [
255,
32
] | python | en | ['en', 'en', 'en'] | True |
MemoryReceiveStream.put_eof | (self) | Adds an end-of-file marker to the internal buffer. | Adds an end-of-file marker to the internal buffer. | def put_eof(self):
"""Adds an end-of-file marker to the internal buffer."""
self._incoming.close() | [
"def",
"put_eof",
"(",
"self",
")",
":",
"self",
".",
"_incoming",
".",
"close",
"(",
")"
] | [
257,
4
] | [
259,
30
] | python | en | ['en', 'en', 'en'] | True |
unformat_pytest_explanation | (s) |
Undo _pytest.assertion.util.format_explanation
|
Undo _pytest.assertion.util.format_explanation
| def unformat_pytest_explanation(s):
"""
Undo _pytest.assertion.util.format_explanation
"""
return s.replace("\\n", "\n") | [
"def",
"unformat_pytest_explanation",
"(",
"s",
")",
":",
"return",
"s",
".",
"replace",
"(",
"\"\\\\n\"",
",",
"\"\\n\"",
")"
] | [
28,
0
] | [
32,
33
] | python | en | ['en', 'error', 'th'] | False |
_is_bool_supported | () |
Type "bool" is not supported before 2.9
|
Type "bool" is not supported before 2.9
| def _is_bool_supported():
"""
Type "bool" is not supported before 2.9
"""
try:
from pytest import __version__
from distutils import version
return version.LooseVersion(str(__version__)) >= version.LooseVersion("2.9")
except ImportError:
return False | [
"def",
"_is_bool_supported",
"(",
")",
":",
"try",
":",
"from",
"pytest",
"import",
"__version__",
"from",
"distutils",
"import",
"version",
"return",
"version",
".",
"LooseVersion",
"(",
"str",
"(",
"__version__",
")",
")",
">=",
"version",
".",
"LooseVersion... | [
64,
0
] | [
73,
20
] | python | en | ['en', 'error', 'th'] | False |
EchoTeamCityMessages.pytest_runtest_logreport | (self, report) |
:type report: _pytest.runner.TestReport
|
:type report: _pytest.runner.TestReport
| def pytest_runtest_logreport(self, report):
"""
:type report: _pytest.runner.TestReport
"""
test_id = self.format_test_id(report.nodeid, report.location)
duration = timedelta(seconds=report.duration)
if report.passed:
# Do not report passed setup/teardown if... | [
"def",
"pytest_runtest_logreport",
"(",
"self",
",",
"report",
")",
":",
"test_id",
"=",
"self",
".",
"format_test_id",
"(",
"report",
".",
"nodeid",
",",
"report",
".",
"location",
")",
"duration",
"=",
"timedelta",
"(",
"seconds",
"=",
"report",
".",
"du... | [
332,
4
] | [
367,
50
] | python | en | ['en', 'error', 'th'] | False |
test_notebook_execution_with_pandas_backend | (
titanic_data_context_no_data_docs_no_checkpoint_store,
) |
This tests that the notebook is written to disk and executes without error.
To set this test up we:
- create a scaffold notebook
- verify that no validations have happened
We then:
- execute that notebook (Note this will raise various errors like
CellExecutionError if any cell in the note... |
This tests that the notebook is written to disk and executes without error. | def test_notebook_execution_with_pandas_backend(
titanic_data_context_no_data_docs_no_checkpoint_store,
):
"""
This tests that the notebook is written to disk and executes without error.
To set this test up we:
- create a scaffold notebook
- verify that no validations have happened
We then... | [
"def",
"test_notebook_execution_with_pandas_backend",
"(",
"titanic_data_context_no_data_docs_no_checkpoint_store",
",",
")",
":",
"# Since we'll run the notebook, we use a context with no data docs to avoid",
"# the renderer's default behavior of building and opening docs, which is not",
"# part ... | [
12,
0
] | [
104,
59
] | python | en | ['en', 'error', 'th'] | False |
adjustData | (img,mask) |
Pre-
:param img:
:param mask:
:return:
|
Pre-
:param img:
:param mask:
:return:
| def adjustData(img,mask):
"""
Pre-
:param img:
:param mask:
:return:
"""
if np.max(img) > 1:
img = img / 255
mask = mask / 255
mask[mask > 0.5] = 1
mask[mask <= 0.5] = 0
mask = to_categorical(mask, num_classes=2)
return img,mask | [
"def",
"adjustData",
"(",
"img",
",",
"mask",
")",
":",
"if",
"np",
".",
"max",
"(",
"img",
")",
">",
"1",
":",
"img",
"=",
"img",
"/",
"255",
"mask",
"=",
"mask",
"/",
"255",
"mask",
"[",
"mask",
">",
"0.5",
"]",
"=",
"1",
"mask",
"[",
"ma... | [
13,
0
] | [
26,
19
] | python | en | ['en', 'error', 'th'] | False |
library_install_load_check | (
python_import_name: str, pip_library_name: str
) |
Dynamically load a module from strings, attempt a pip install or raise a helpful error.
:return: True if the library was loaded successfully, False otherwise
Args:
pip_library_name: name of the library to load
python_import_name (str): a module to import to verify installation
|
Dynamically load a module from strings, attempt a pip install or raise a helpful error. | def library_install_load_check(
python_import_name: str, pip_library_name: str
) -> Optional[int]:
"""
Dynamically load a module from strings, attempt a pip install or raise a helpful error.
:return: True if the library was loaded successfully, False otherwise
Args:
pip_library_name: name ... | [
"def",
"library_install_load_check",
"(",
"python_import_name",
":",
"str",
",",
"pip_library_name",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"is_library_loadable",
"(",
"library_name",
"=",
"python_import_name",
")",
":",
"return",
"None",
... | [
43,
0
] | [
102,
22
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.__init__ | (
self,
sql_url: str = "sqlite:///",
vector_dim: int = 768,
faiss_index_factory_str: str = "Flat",
faiss_index: Optional[faiss.swigfaiss.Index] = None,
return_embedding: bool = False,
update_existing_documents: bool = False,
index: str = "document",
... |
:param sql_url: SQL connection URL for database. It defaults to local file based SQLite DB. For large scale
deployment, Postgres is recommended.
:param vector_dim: the embedding vector size.
:param faiss_index_factory_str: Create a new FAISS index of the specified type.
... |
:param sql_url: SQL connection URL for database. It defaults to local file based SQLite DB. For large scale
deployment, Postgres is recommended.
:param vector_dim: the embedding vector size.
:param faiss_index_factory_str: Create a new FAISS index of the specified type.
... | def __init__(
self,
sql_url: str = "sqlite:///",
vector_dim: int = 768,
faiss_index_factory_str: str = "Flat",
faiss_index: Optional[faiss.swigfaiss.Index] = None,
return_embedding: bool = False,
update_existing_documents: bool = False,
index: str = "docum... | [
"def",
"__init__",
"(",
"self",
",",
"sql_url",
":",
"str",
"=",
"\"sqlite:///\"",
",",
"vector_dim",
":",
"int",
"=",
"768",
",",
"faiss_index_factory_str",
":",
"str",
"=",
"\"Flat\"",
",",
"faiss_index",
":",
"Optional",
"[",
"faiss",
".",
"swigfaiss",
... | [
29,
4
] | [
99,
9
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.write_documents | (
self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000
) |
Add new documents to the DocumentStore.
:param documents: List of `Dicts` or List of `Documents`. If they already contain the embeddings, we'll index
them right away in FAISS. If not, you can later call update_embeddings() to create & index them.
:param index: (SQL) i... |
Add new documents to the DocumentStore. | def write_documents(
self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000
):
"""
Add new documents to the DocumentStore.
:param documents: List of `Dicts` or List of `Documents`. If they already contain the embeddings, we'll index... | [
"def",
"write_documents",
"(",
"self",
",",
"documents",
":",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Document",
"]",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"batch_size",
":",
"int",
"=",
"10_000",
... | [
117,
4
] | [
161,
94
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.update_embeddings | (
self,
retriever: BaseRetriever,
index: Optional[str] = None,
update_existing_embeddings: bool = True,
filters: Optional[Dict[str, List[str]]] = None,
batch_size: int = 10_000
) |
Updates the embeddings in the the document store using the encoding model specified in the retriever.
This can be useful if want to add or change the embeddings for your documents (e.g. after changing the retriever config).
:param retriever: Retriever to use to get embeddings for text
... |
Updates the embeddings in the the document store using the encoding model specified in the retriever.
This can be useful if want to add or change the embeddings for your documents (e.g. after changing the retriever config). | def update_embeddings(
self,
retriever: BaseRetriever,
index: Optional[str] = None,
update_existing_embeddings: bool = True,
filters: Optional[Dict[str, List[str]]] = None,
batch_size: int = 10_000
):
"""
Updates the embeddings in the the document stor... | [
"def",
"update_embeddings",
"(",
"self",
",",
"retriever",
":",
"BaseRetriever",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"update_existing_embeddings",
":",
"bool",
"=",
"True",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"s... | [
168,
4
] | [
226,
28
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.get_all_documents_generator | (
self,
index: Optional[str] = None,
filters: Optional[Dict[str, List[str]]] = None,
return_embedding: Optional[bool] = None,
batch_size: int = 10_000,
) |
Get all documents from the document store. Under-the-hood, documents are fetched in batches from the
document store and yielded as individual documents. This method can be used to iteratively process
a large number of documents without having to load all documents in memory.
:param ind... |
Get all documents from the document store. Under-the-hood, documents are fetched in batches from the
document store and yielded as individual documents. This method can be used to iteratively process
a large number of documents without having to load all documents in memory. | def get_all_documents_generator(
self,
index: Optional[str] = None,
filters: Optional[Dict[str, List[str]]] = None,
return_embedding: Optional[bool] = None,
batch_size: int = 10_000,
) -> Generator[Document, None, None]:
"""
Get all documents from the document... | [
"def",
"get_all_documents_generator",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"return_embedding",
":",... | [
241,
4
] | [
271,
21
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.train_index | (
self,
documents: Optional[Union[List[dict], List[Document]]],
embeddings: Optional[np.ndarray] = None,
index: Optional[str] = None,
) |
Some FAISS indices (e.g. IVF) require initial "training" on a sample of vectors before you can add your final vectors.
The train vectors should come from the same distribution as your final ones.
You can pass either documents (incl. embeddings) or just the plain embeddings that the index shall ... |
Some FAISS indices (e.g. IVF) require initial "training" on a sample of vectors before you can add your final vectors.
The train vectors should come from the same distribution as your final ones.
You can pass either documents (incl. embeddings) or just the plain embeddings that the index shall ... | def train_index(
self,
documents: Optional[Union[List[dict], List[Document]]],
embeddings: Optional[np.ndarray] = None,
index: Optional[str] = None,
):
"""
Some FAISS indices (e.g. IVF) require initial "training" on a sample of vectors before you can add your final ve... | [
"def",
"train_index",
"(",
"self",
",",
"documents",
":",
"Optional",
"[",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Document",
"]",
"]",
"]",
",",
"embeddings",
":",
"Optional",
"[",
"np",
".",
"ndarray",
"]",
"=",
"None",
",",
"i... | [
284,
4
] | [
310,
55
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.delete_all_documents | (self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None) |
Delete all documents from the document store.
|
Delete all documents from the document store.
| def delete_all_documents(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None):
"""
Delete all documents from the document store.
"""
if filters:
raise Exception("filters are supported for deleting documents in FAISSDocumentStore.")
index ... | [
"def",
"delete_all_documents",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
")",
":",
"if",
"filters",
":",
... | [
312,
4
] | [
321,
49
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.query_by_embedding | (
self,
query_emb: np.ndarray,
filters: Optional[Dict[str, List[str]]] = None,
top_k: int = 10,
index: Optional[str] = None,
return_embedding: Optional[bool] = None
) |
Find the document that is most similar to the provided `query_emb` by using a vector similarity metric.
:param query_emb: Embedding of the query (e.g. gathered from DPR)
:param filters: Optional filters to narrow down the search space.
Example: {"name": ["some", "more"]... |
Find the document that is most similar to the provided `query_emb` by using a vector similarity metric. | def query_by_embedding(
self,
query_emb: np.ndarray,
filters: Optional[Dict[str, List[str]]] = None,
top_k: int = 10,
index: Optional[str] = None,
return_embedding: Optional[bool] = None
) -> List[Document]:
"""
Find the document that is most similar t... | [
"def",
"query_by_embedding",
"(",
"self",
",",
"query_emb",
":",
"np",
".",
"ndarray",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"top_k",
":",
"int",
"=",
"10",
",",
"index",... | [
323,
4
] | [
366,
24
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.save | (self, file_path: Union[str, Path]) |
Save FAISS Index to the specified file.
:param file_path: Path to save to.
:return: None
|
Save FAISS Index to the specified file. | def save(self, file_path: Union[str, Path]):
"""
Save FAISS Index to the specified file.
:param file_path: Path to save to.
:return: None
"""
faiss.write_index(self.faiss_indexes[self.index], str(file_path)) | [
"def",
"save",
"(",
"self",
",",
"file_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
")",
":",
"faiss",
".",
"write_index",
"(",
"self",
".",
"faiss_indexes",
"[",
"self",
".",
"index",
"]",
",",
"str",
"(",
"file_path",
")",
")"
] | [
368,
4
] | [
375,
73
] | python | en | ['en', 'error', 'th'] | False |
FAISSDocumentStore.load | (
cls,
faiss_file_path: Union[str, Path],
sql_url: str,
index: str,
) |
Load a saved FAISS index from a file and connect to the SQL database.
Note: In order to have a correct mapping from FAISS to SQL,
make sure to use the same SQL DB that you used when calling `save()`.
:param faiss_file_path: Stored FAISS index file. Can be created via calling `sav... |
Load a saved FAISS index from a file and connect to the SQL database.
Note: In order to have a correct mapping from FAISS to SQL,
make sure to use the same SQL DB that you used when calling `save()`. | def load(
cls,
faiss_file_path: Union[str, Path],
sql_url: str,
index: str,
):
"""
Load a saved FAISS index from a file and connect to the SQL database.
Note: In order to have a correct mapping from FAISS to SQL,
make sure to use the same SQL DB ... | [
"def",
"load",
"(",
"cls",
",",
"faiss_file_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"sql_url",
":",
"str",
",",
"index",
":",
"str",
",",
")",
":",
"\"\"\"\n \"\"\"",
"faiss_index",
"=",
"faiss",
".",
"read_index",
"(",
"str",
"(... | [
378,
4
] | [
403,
9
] | python | en | ['en', 'error', 'th'] | False |
PublicUserApiTests.test_create_valid_user_seccess | (self) | Test creating user with valid payload is successful | Test creating user with valid payload is successful | def test_create_valid_user_seccess(self):
"""Test creating user with valid payload is successful"""
payload = {
'email': 'test@testmail.com',
'password': 'testpass',
'name': 'Test name',
}
res = self.client.post(CREATE_USER_URL, payload)
self.... | [
"def",
"test_create_valid_user_seccess",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'test@testmail.com'",
",",
"'password'",
":",
"'testpass'",
",",
"'name'",
":",
"'Test name'",
",",
"}",
"res",
"=",
"self",
".",
"client",
".",
"post",
"("... | [
23,
4
] | [
35,
46
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_user_exists | (self) | Test creating a user that already exists fails | Test creating a user that already exists fails | def test_user_exists(self):
"""Test creating a user that already exists fails"""
payload = {
'email': 'test@testmail.com',
'password': 'testpass',
'name': 'Test name',
}
create_user(**payload)
res = self.client.post(CREATE_USER_URL, payload)
... | [
"def",
"test_user_exists",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'test@testmail.com'",
",",
"'password'",
":",
"'testpass'",
",",
"'name'",
":",
"'Test name'",
",",
"}",
"create_user",
"(",
"*",
"*",
"payload",
")",
"res",
"=",
"self... | [
37,
4
] | [
48,
70
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_password_too_short | (self) | Test that the password must be more than 5 characters | Test that the password must be more than 5 characters | def test_password_too_short(self):
"""Test that the password must be more than 5 characters"""
payload = {
'email': 'test@testmail.com',
'password': 'pw',
'name': 'Test name',
}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual... | [
"def",
"test_password_too_short",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'test@testmail.com'",
",",
"'password'",
":",
"'pw'",
",",
"'name'",
":",
"'Test name'",
",",
"}",
"res",
"=",
"self",
".",
"client",
".",
"post",
"(",
"CREATE_U... | [
50,
4
] | [
63,
37
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_create_token_for_user | (self) | Test that a token is created for the user | Test that a token is created for the user | def test_create_token_for_user(self):
"""Test that a token is created for the user"""
payload = {
'email': 'test@testmail.com',
'password': 'testpass',
}
create_user(**payload)
res = self.client.post(TOKEN_URL, payload)
self.assertIn('token', res.... | [
"def",
"test_create_token_for_user",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'test@testmail.com'",
",",
"'password'",
":",
"'testpass'",
",",
"}",
"create_user",
"(",
"*",
"*",
"payload",
")",
"res",
"=",
"self",
".",
"client",
".",
"p... | [
65,
4
] | [
75,
61
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_create_token_invalid_credentials | (self) | Test that token is not created if invalid credentials are given | Test that token is not created if invalid credentials are given | def test_create_token_invalid_credentials(self):
"""Test that token is not created if invalid credentials are given"""
create_user(email='test@testmail.com', password='testpass')
payload = {
'email': 'test@testmail.com',
'password': 'wrong',
}
res = self.c... | [
"def",
"test_create_token_invalid_credentials",
"(",
"self",
")",
":",
"create_user",
"(",
"email",
"=",
"'test@testmail.com'",
",",
"password",
"=",
"'testpass'",
")",
"payload",
"=",
"{",
"'email'",
":",
"'test@testmail.com'",
",",
"'password'",
":",
"'wrong'",
... | [
77,
4
] | [
87,
70
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_create_token_no_user | (self) | Test that token is not created is user doesn't exist | Test that token is not created is user doesn't exist | def test_create_token_no_user(self):
"""Test that token is not created is user doesn't exist"""
payload = {
'email': 'test@testmail.com',
'password': 'wrong',
}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.as... | [
"def",
"test_create_token_no_user",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'test@testmail.com'",
",",
"'password'",
":",
"'wrong'",
",",
"}",
"res",
"=",
"self",
".",
"client",
".",
"post",
"(",
"TOKEN_URL",
",",
"payload",
")",
"self... | [
89,
4
] | [
98,
70
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_create_token_missing_field | (self) | Test that email and password are required | Test that email and password are required | def test_create_token_missing_field(self):
"""Test that email and password are required"""
payload = {
'email': 'test',
'password': '',
}
res = self.client.post(TOKEN_URL, payload)
self.assertNotIn('token', res.data)
self.assertEqual(res.status_co... | [
"def",
"test_create_token_missing_field",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'test'",
",",
"'password'",
":",
"''",
",",
"}",
"res",
"=",
"self",
".",
"client",
".",
"post",
"(",
"TOKEN_URL",
",",
"payload",
")",
"self",
".",
... | [
100,
4
] | [
109,
70
] | python | en | ['en', 'en', 'en'] | True |
PublicUserApiTests.test_retrieve_user_unauthorized | (self) | Test that authentication is required for users | Test that authentication is required for users | def test_retrieve_user_unauthorized(self):
"""Test that authentication is required for users"""
res = self.client.get(ME_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | [
"def",
"test_retrieve_user_unauthorized",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"get",
"(",
"ME_URL",
")",
"self",
".",
"assertEqual",
"(",
"res",
".",
"status_code",
",",
"status",
".",
"HTTP_401_UNAUTHORIZED",
")"
] | [
111,
4
] | [
115,
71
] | python | en | ['en', 'en', 'en'] | True |
PrivateUserApiTests.test_retrieve_profile_success | (self) | Test retrieving profile for logged in used | Test retrieving profile for logged in used | def test_retrieve_profile_success(self):
"""Test retrieving profile for logged in used"""
res = self.client.get(ME_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, {
'name': self.user.name,
'email': self.user.email
}) | [
"def",
"test_retrieve_profile_success",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"get",
"(",
"ME_URL",
")",
"self",
".",
"assertEqual",
"(",
"res",
".",
"status_code",
",",
"status",
".",
"HTTP_200_OK",
")",
"self",
".",
"assertEqual"... | [
130,
4
] | [
138,
10
] | python | en | ['en', 'en', 'en'] | True |
PrivateUserApiTests.test_post_me_not_allowed | (self) | Test that POST is not allowed on the me url | Test that POST is not allowed on the me url | def test_post_me_not_allowed(self):
"""Test that POST is not allowed on the me url"""
res = self.client.post(ME_URL, {})
self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) | [
"def",
"test_post_me_not_allowed",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"post",
"(",
"ME_URL",
",",
"{",
"}",
")",
"self",
".",
"assertEqual",
"(",
"res",
".",
"status_code",
",",
"status",
".",
"HTTP_405_METHOD_NOT_ALLOWED",
")"
... | [
140,
4
] | [
144,
77
] | python | en | ['en', 'en', 'en'] | True |
PrivateUserApiTests.test_update_user_profile | (self) | Test updating the user profile for authenticated user | Test updating the user profile for authenticated user | def test_update_user_profile(self):
"""Test updating the user profile for authenticated user"""
payload = {
'name': 'new name',
'password': 'newpass'
}
res = self.client.patch(ME_URL, payload)
self.user.refresh_from_db()
self.assertEqual(self.user... | [
"def",
"test_update_user_profile",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'name'",
":",
"'new name'",
",",
"'password'",
":",
"'newpass'",
"}",
"res",
"=",
"self",
".",
"client",
".",
"patch",
"(",
"ME_URL",
",",
"payload",
")",
"self",
".",
"user"... | [
146,
4
] | [
157,
61
] | python | en | ['en', 'en', 'en'] | True |
SSLStream.do_handshake | (self) | Ensure that the initial handshake has completed.
The SSL protocol requires an initial handshake to exchange
certificates, select cryptographic keys, and so forth, before any
actual data can be sent or received. You don't have to call this
method; if you don't, then :class:`SSLStream` wi... | Ensure that the initial handshake has completed. | async def do_handshake(self):
"""Ensure that the initial handshake has completed.
The SSL protocol requires an initial handshake to exchange
certificates, select cryptographic keys, and so forth, before any
actual data can be sent or received. You don't have to call this
method;... | [
"async",
"def",
"do_handshake",
"(",
"self",
")",
":",
"self",
".",
"_check_status",
"(",
")",
"await",
"self",
".",
"_handshook",
".",
"ensure",
"(",
"checkpoint",
"=",
"True",
")"
] | [
608,
4
] | [
633,
53
] | python | en | ['en', 'en', 'en'] | True |
SSLStream.receive_some | (self, max_bytes=None) | Read some data from the underlying transport, decrypt it, and
return it.
See :meth:`trio.abc.ReceiveStream.receive_some` for details.
.. warning:: If this method is cancelled while the initial handshake
or a renegotiation are in progress, then it may leave the
:class:`SSL... | Read some data from the underlying transport, decrypt it, and
return it. | async def receive_some(self, max_bytes=None):
"""Read some data from the underlying transport, decrypt it, and
return it.
See :meth:`trio.abc.ReceiveStream.receive_some` for details.
.. warning:: If this method is cancelled while the initial handshake
or a renegotiation are ... | [
"async",
"def",
"receive_some",
"(",
"self",
",",
"max_bytes",
"=",
"None",
")",
":",
"with",
"self",
".",
"_outer_recv_conflict_detector",
":",
"self",
".",
"_check_status",
"(",
")",
"try",
":",
"await",
"self",
".",
"_handshook",
".",
"ensure",
"(",
"ch... | [
643,
4
] | [
695,
25
] | python | en | ['en', 'en', 'en'] | True |
SSLStream.send_all | (self, data) | Encrypt some data and then send it on the underlying transport.
See :meth:`trio.abc.SendStream.send_all` for details.
.. warning:: If this method is cancelled, then it may leave the
:class:`SSLStream` in an unusable state. If this happens then any
attempt to use the object will r... | Encrypt some data and then send it on the underlying transport. | async def send_all(self, data):
"""Encrypt some data and then send it on the underlying transport.
See :meth:`trio.abc.SendStream.send_all` for details.
.. warning:: If this method is cancelled, then it may leave the
:class:`SSLStream` in an unusable state. If this happens then any
... | [
"async",
"def",
"send_all",
"(",
"self",
",",
"data",
")",
":",
"with",
"self",
".",
"_outer_send_conflict_detector",
":",
"self",
".",
"_check_status",
"(",
")",
"await",
"self",
".",
"_handshook",
".",
"ensure",
"(",
"checkpoint",
"=",
"False",
")",
"# S... | [
697,
4
] | [
716,
59
] | python | en | ['en', 'en', 'en'] | True |
SSLStream.unwrap | (self) | Cleanly close down the SSL/TLS encryption layer, allowing the
underlying stream to be used for unencrypted communication.
You almost certainly don't need this.
Returns:
A pair ``(transport_stream, trailing_bytes)``, where
``transport_stream`` is the underlying transport str... | Cleanly close down the SSL/TLS encryption layer, allowing the
underlying stream to be used for unencrypted communication. | async def unwrap(self):
"""Cleanly close down the SSL/TLS encryption layer, allowing the
underlying stream to be used for unencrypted communication.
You almost certainly don't need this.
Returns:
A pair ``(transport_stream, trailing_bytes)``, where
``transport_strea... | [
"async",
"def",
"unwrap",
"(",
"self",
")",
":",
"with",
"self",
".",
"_outer_recv_conflict_detector",
",",
"self",
".",
"_outer_send_conflict_detector",
":",
"self",
".",
"_check_status",
"(",
")",
"await",
"self",
".",
"_handshook",
".",
"ensure",
"(",
"chec... | [
718,
4
] | [
742,
60
] | python | en | ['en', 'en', 'en'] | True |
SSLStream.aclose | (self) | Gracefully shut down this connection, and close the underlying
transport.
If ``https_compatible`` is False (the default), then this attempts to
first send a ``close_notify`` and then close the underlying stream by
calling its :meth:`~trio.abc.AsyncResource.aclose` method.
If ``... | Gracefully shut down this connection, and close the underlying
transport. | async def aclose(self):
"""Gracefully shut down this connection, and close the underlying
transport.
If ``https_compatible`` is False (the default), then this attempts to
first send a ``close_notify`` and then close the underlying stream by
calling its :meth:`~trio.abc.AsyncReso... | [
"async",
"def",
"aclose",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"is",
"_State",
".",
"CLOSED",
":",
"await",
"trio",
".",
"lowlevel",
".",
"checkpoint",
"(",
")",
"return",
"if",
"self",
".",
"_state",
"is",
"_State",
".",
"BROKEN",
"or... | [
744,
4
] | [
829,
39
] | python | en | ['en', 'en', 'en'] | True |
SSLStream.wait_send_all_might_not_block | (self) | See :meth:`trio.abc.SendStream.wait_send_all_might_not_block`. | See :meth:`trio.abc.SendStream.wait_send_all_might_not_block`. | async def wait_send_all_might_not_block(self):
"""See :meth:`trio.abc.SendStream.wait_send_all_might_not_block`."""
# This method's implementation is deceptively simple.
#
# First, we take the outer send lock, because of Trio's standard
# semantics that wait_send_all_might_not_bl... | [
"async",
"def",
"wait_send_all_might_not_block",
"(",
"self",
")",
":",
"# This method's implementation is deceptively simple.",
"#",
"# First, we take the outer send lock, because of Trio's standard",
"# semantics that wait_send_all_might_not_block and send_all",
"# conflict.",
"with",
"s... | [
831,
4
] | [
869,
75
] | python | en | ['en', 'en', 'en'] | False |
SSLListener.accept | (self) | Accept the next connection and wrap it in an :class:`SSLStream`.
See :meth:`trio.abc.Listener.accept` for details.
| Accept the next connection and wrap it in an :class:`SSLStream`. | async def accept(self):
"""Accept the next connection and wrap it in an :class:`SSLStream`.
See :meth:`trio.abc.Listener.accept` for details.
"""
transport_stream = await self.transport_listener.accept()
return SSLStream(
transport_stream,
self._ssl_cont... | [
"async",
"def",
"accept",
"(",
"self",
")",
":",
"transport_stream",
"=",
"await",
"self",
".",
"transport_listener",
".",
"accept",
"(",
")",
"return",
"SSLStream",
"(",
"transport_stream",
",",
"self",
".",
"_ssl_context",
",",
"server_side",
"=",
"True",
... | [
908,
4
] | [
920,
9
] | python | en | ['en', 'en', 'en'] | True |
SSLListener.aclose | (self) | Close the transport listener. | Close the transport listener. | async def aclose(self):
"""Close the transport listener."""
await self.transport_listener.aclose() | [
"async",
"def",
"aclose",
"(",
"self",
")",
":",
"await",
"self",
".",
"transport_listener",
".",
"aclose",
"(",
")"
] | [
922,
4
] | [
924,
46
] | python | en | ['en', 'sd', 'en'] | True |
PDFToTextConverter.__init__ | (self, remove_numeric_tables: bool = False, valid_languages: Optional[List[str]] = None) |
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers.... |
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers.... | def __init__(self, remove_numeric_tables: bool = False, valid_languages: Optional[List[str]] = None):
"""
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the rea... | [
"def",
"__init__",
"(",
"self",
",",
"remove_numeric_tables",
":",
"bool",
"=",
"False",
",",
"valid_languages",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
":",
"verify_installation",
"=",
"subprocess",
".",
"run",
"(",
"[",
"\... | [
11,
4
] | [
40,
102
] | python | en | ['en', 'error', 'th'] | False |
PDFToTextConverter.convert | (
self,
file_path: Path,
meta: Optional[Dict[str, str]] = None,
remove_numeric_tables: Optional[bool] = None,
valid_languages: Optional[List[str]] = None,
encoding: str = "Latin1",
) |
Extract text from a .pdf file using the pdftotext library (https://www.xpdfreader.com/pdftotext-man.html)
:param file_path: Path to the .pdf file you want to convert
:param meta: Optional dictionary with metadata that shall be attached to all resulting documents.
Can be an... |
Extract text from a .pdf file using the pdftotext library (https://www.xpdfreader.com/pdftotext-man.html) | def convert(
self,
file_path: Path,
meta: Optional[Dict[str, str]] = None,
remove_numeric_tables: Optional[bool] = None,
valid_languages: Optional[List[str]] = None,
encoding: str = "Latin1",
) -> Dict[str, Any]:
"""
Extract text from a .pdf file using... | [
"def",
"convert",
"(",
"self",
",",
"file_path",
":",
"Path",
",",
"meta",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
",",
"remove_numeric_tables",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"valid_languages"... | [
42,
4
] | [
118,
23
] | python | en | ['en', 'error', 'th'] | False |
PDFToTextConverter._read_pdf | (self, file_path: Path, layout: bool, encoding: str) |
Extract pages from the pdf file at file_path.
:param file_path: path of the pdf file
:param layout: whether to retain the original physical layout for a page. If disabled, PDF pages are read in
the content stream order.
|
Extract pages from the pdf file at file_path. | def _read_pdf(self, file_path: Path, layout: bool, encoding: str) -> List[str]:
"""
Extract pages from the pdf file at file_path.
:param file_path: path of the pdf file
:param layout: whether to retain the original physical layout for a page. If disabled, PDF pages are read in
... | [
"def",
"_read_pdf",
"(",
"self",
",",
"file_path",
":",
"Path",
",",
"layout",
":",
"bool",
",",
"encoding",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"layout",
":",
"command",
"=",
"[",
"\"pdftotext\"",
",",
"\"-enc\"",
",",
"encodi... | [
120,
4
] | [
136,
20
] | python | en | ['en', 'error', 'th'] | False |
foo | () | ur"""unicode-raw | ur"""unicode-raw | def foo():
ur"""unicode-raw""" | [
"def",
"foo",
"(",
")",
":"
] | [
0,
0
] | [
1,
23
] | python | it | ['pl', 'sn', 'it'] | False |
bar | () | u"""unicode | u"""unicode | def bar():
u"""unicode""" | [
"def",
"bar",
"(",
")",
":"
] | [
3,
0
] | [
4,
18
] | python | en | ['en', 'hr', 'it'] | False |
_clean_check | (cmd, target) |
Run the command to download target. If the command fails, clean up before
re-raising the error.
|
Run the command to download target. If the command fails, clean up before
re-raising the error.
| def _clean_check(cmd, target):
"""
Run the command to download target. If the command fails, clean up before
re-raising the error.
"""
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
if os.access(target, os.F_OK):
os.unlink(target)
raise | [
"def",
"_clean_check",
"(",
"cmd",
",",
"target",
")",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"cmd",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"if",
"os",
".",
"access",
"(",
"target",
",",
"os",
".",
"F_OK",
")",
":"... | [
153,
0
] | [
163,
13
] | python | en | ['en', 'error', 'th'] | False |
download_file_powershell | (url, target) |
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
|
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
| def download_file_powershell(url, target):
"""
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
"""
target = os.path.abspath(target)
cmd = [
'powershell',
'-Command',
"(new-object System.Ne... | [
"def",
"download_file_powershell",
"(",
"url",
",",
"target",
")",
":",
"target",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"target",
")",
"cmd",
"=",
"[",
"'powershell'",
",",
"'-Command'",
",",
"\"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target... | [
165,
0
] | [
176,
29
] | python | en | ['en', 'error', 'th'] | False |
download_file_insecure | (url, target) |
Use Python to download the file, even though it cannot authenticate the
connection.
|
Use Python to download the file, even though it cannot authenticate the
connection.
| def download_file_insecure(url, target):
"""
Use Python to download the file, even though it cannot authenticate the
connection.
"""
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
src = dst = None
try:
src = urlopen(url)
... | [
"def",
"download_file_insecure",
"(",
"url",
",",
"target",
")",
":",
"try",
":",
"from",
"urllib",
".",
"request",
"import",
"urlopen",
"except",
"ImportError",
":",
"from",
"urllib2",
"import",
"urlopen",
"src",
"=",
"dst",
"=",
"None",
"try",
":",
"src"... | [
230,
0
] | [
251,
23
] | python | en | ['en', 'error', 'th'] | False |
download_setuptools | (version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15,
downloader_factory=get_best_downloader) | Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the nu... | Download setuptools from a specified location and return its filename | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15,
downloader_factory=get_best_downloader):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools versio... | [
"def",
"download_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"os",
".",
"curdir",
",",
"delay",
"=",
"15",
",",
"downloader_factory",
"=",
"get_best_downloader",
")",
":",
"# making sure we use... | [
267,
0
] | [
290,
35
] | python | en | ['en', 'en', 'en'] | True |
_extractall | (self, path=".", members=None) | Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
| Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
| def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of... | [
"def",
"_extractall",
"(",
"self",
",",
"path",
"=",
"\".\"",
",",
"members",
"=",
"None",
")",
":",
"import",
"copy",
"import",
"operator",
"from",
"tarfile",
"import",
"ExtractError",
"directories",
"=",
"[",
"]",
"if",
"members",
"is",
"None",
":",
"m... | [
293,
0
] | [
337,
47
] | python | en | ['en', 'en', 'en'] | True |
_build_install_args | (options) |
Build the arguments to 'python setup.py install' on the setuptools package
|
Build the arguments to 'python setup.py install' on the setuptools package
| def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the setuptools package
"""
install_args = []
if options.user_install:
if sys.version_info < (2, 6):
log.warn("--user requires Python 2.6 or later")
raise SystemExit(1)
in... | [
"def",
"_build_install_args",
"(",
"options",
")",
":",
"install_args",
"=",
"[",
"]",
"if",
"options",
".",
"user_install",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"6",
")",
":",
"log",
".",
"warn",
"(",
"\"--user requires Python 2.6 or... | [
340,
0
] | [
350,
23
] | python | en | ['en', 'error', 'th'] | False |
_parse_args | () |
Parse the command line for options
|
Parse the command line for options
| def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--d... | [
"def",
"_parse_args",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"'--user'",
",",
"dest",
"=",
"'user_install'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
... | [
352,
0
] | [
371,
18
] | python | en | ['en', 'error', 'th'] | False |
main | (version=DEFAULT_VERSION) | Install or upgrade setuptools and EasyInstall | Install or upgrade setuptools and EasyInstall | def main(version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
tarball = download_setuptools(download_base=options.download_base,
downloader_factory=options.downloader_factory)
return _install(tarball, _build_install_args(options)) | [
"def",
"main",
"(",
"version",
"=",
"DEFAULT_VERSION",
")",
":",
"options",
"=",
"_parse_args",
"(",
")",
"tarball",
"=",
"download_setuptools",
"(",
"download_base",
"=",
"options",
".",
"download_base",
",",
"downloader_factory",
"=",
"options",
".",
"download... | [
373,
0
] | [
378,
58
] | python | en | ['en', 'et', 'en'] | True |
ExpectTableRowCountToEqual.validate_configuration | (self, configuration: Optional[ExpectationConfiguration]) |
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An opt... |
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation. | def validate_configuration(self, configuration: Optional[ExpectationConfiguration]):
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
... | [
"def",
"validate_configuration",
"(",
"self",
",",
"configuration",
":",
"Optional",
"[",
"ExpectationConfiguration",
"]",
")",
":",
"# Setting up a configuration",
"super",
"(",
")",
".",
"validate_configuration",
"(",
"configuration",
")",
"value",
"=",
"configurati... | [
77,
4
] | [
107,
19
] | python | en | ['en', 'error', 'th'] | False |
MultiError.filter | (cls, handler, root_exc) | Apply the given ``handler`` to all the exceptions in ``root_exc``.
Args:
handler: A callable that takes an atomic (non-MultiError) exception
as input, and returns either a new exception object or None.
root_exc: An exception, often (though not necessarily) a
:exc... | Apply the given ``handler`` to all the exceptions in ``root_exc``. | def filter(cls, handler, root_exc):
"""Apply the given ``handler`` to all the exceptions in ``root_exc``.
Args:
handler: A callable that takes an atomic (non-MultiError) exception
as input, and returns either a new exception object or None.
root_exc: An exception, ofte... | [
"def",
"filter",
"(",
"cls",
",",
"handler",
",",
"root_exc",
")",
":",
"return",
"_filter_impl",
"(",
"handler",
",",
"root_exc",
")"
] | [
211,
4
] | [
227,
46
] | python | en | ['en', 'en', 'en'] | True |
MultiError.catch | (cls, handler) | Return a context manager that catches and re-throws exceptions
after running :meth:`filter` on them.
Args:
handler: as for :meth:`filter`
| Return a context manager that catches and re-throws exceptions
after running :meth:`filter` on them. | def catch(cls, handler):
"""Return a context manager that catches and re-throws exceptions
after running :meth:`filter` on them.
Args:
handler: as for :meth:`filter`
"""
return MultiErrorCatcher(handler) | [
"def",
"catch",
"(",
"cls",
",",
"handler",
")",
":",
"return",
"MultiErrorCatcher",
"(",
"handler",
")"
] | [
230,
4
] | [
239,
41
] | python | en | ['en', 'en', 'en'] | True |
get_parameter_value_and_validate_return_type | (
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = None,
variables: Optional[ParameterContainer] = None,
parameters: Optional[Dict[str, ParameterContainer]] = None,
) |
This method allows for the parameter_reference to be specified as an object (literal, dict, any typed object, etc.)
or as a fully-qualified parameter name. In either case, it can optionally validate the type of the return value.
|
This method allows for the parameter_reference to be specified as an object (literal, dict, any typed object, etc.)
or as a fully-qualified parameter name. In either case, it can optionally validate the type of the return value.
| def get_parameter_value_and_validate_return_type(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
expected_return_type: Optional[Union[type, tuple]] = None,
variables: Optional[ParameterContainer] = None,
parameters: Optional[Dict[str, ParameterContainer]] = N... | [
"def",
"get_parameter_value_and_validate_return_type",
"(",
"domain",
":",
"Optional",
"[",
"Domain",
"]",
"=",
"None",
",",
"parameter_reference",
":",
"Optional",
"[",
"Union",
"[",
"Any",
",",
"str",
"]",
"]",
"=",
"None",
",",
"expected_return_type",
":",
... | [
130,
0
] | [
156,
30
] | python | en | ['en', 'error', 'th'] | False |
get_parameter_value | (
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
variables: Optional[ParameterContainer] = None,
parameters: Optional[Dict[str, ParameterContainer]] = None,
) |
This method allows for the parameter_reference to be specified as an object (literal, dict, any typed object, etc.)
or as a fully-qualified parameter name. Moreover, if the parameter_reference argument is an object of type "dict",
it will recursively detect values using the fully-qualified parameter name ... |
This method allows for the parameter_reference to be specified as an object (literal, dict, any typed object, etc.)
or as a fully-qualified parameter name. Moreover, if the parameter_reference argument is an object of type "dict",
it will recursively detect values using the fully-qualified parameter name ... | def get_parameter_value(
domain: Optional[Domain] = None,
parameter_reference: Optional[Union[Any, str]] = None,
variables: Optional[ParameterContainer] = None,
parameters: Optional[Dict[str, ParameterContainer]] = None,
) -> Optional[Any]:
"""
This method allows for the parameter_reference to b... | [
"def",
"get_parameter_value",
"(",
"domain",
":",
"Optional",
"[",
"Domain",
"]",
"=",
"None",
",",
"parameter_reference",
":",
"Optional",
"[",
"Union",
"[",
"Any",
",",
"str",
"]",
"]",
"=",
"None",
",",
"variables",
":",
"Optional",
"[",
"ParameterConta... | [
159,
0
] | [
193,
30
] | python | en | ['en', 'error', 'th'] | False |
impute_missing_data_1D | (data1D) |
This function returns the data in the same format as it was
passed in, but with missing values either masked out or imputed with appropriate values
(currently only using a linear trend). Many linear plotting functions for 1D data often
(and should) only connect contiguous, non-nan data points. This le... |
This function returns the data in the same format as it was
passed in, but with missing values either masked out or imputed with appropriate values
(currently only using a linear trend). Many linear plotting functions for 1D data often
(and should) only connect contiguous, non-nan data points. This le... | def impute_missing_data_1D(data1D):
"""
This function returns the data in the same format as it was
passed in, but with missing values either masked out or imputed with appropriate values
(currently only using a linear trend). Many linear plotting functions for 1D data often
(and should) only connec... | [
"def",
"impute_missing_data_1D",
"(",
"data1D",
")",
":",
"nan_mask",
"=",
"~",
"np",
".",
"isnan",
"(",
"data1D",
")",
"x",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"data1D",
")",
")",
"x_no_nan",
"=",
"x",
"[",
"nan_mask",
"]",
"data_no_nan",
"="... | [
33,
0
] | [
64,
21
] | python | en | ['en', 'error', 'th'] | False |
np_dt64_to_str | (np_datetime, fmt='%Y-%m-%d') | Converts a NumPy datetime64 object to a string based on a format string supplied to pandas strftime. | Converts a NumPy datetime64 object to a string based on a format string supplied to pandas strftime. | def np_dt64_to_str(np_datetime, fmt='%Y-%m-%d'):
"""Converts a NumPy datetime64 object to a string based on a format string supplied to pandas strftime."""
return pd.to_datetime(str(np_datetime)).strftime(fmt) | [
"def",
"np_dt64_to_str",
"(",
"np_datetime",
",",
"fmt",
"=",
"'%Y-%m-%d'",
")",
":",
"return",
"pd",
".",
"to_datetime",
"(",
"str",
"(",
"np_datetime",
")",
")",
".",
"strftime",
"(",
"fmt",
")"
] | [
77,
0
] | [
79,
57
] | python | en | ['en', 'en', 'en'] | True |
xarray_plot_data_vars_over_time | (dataset, colors=['orange', 'blue']) |
Plot a line plot of all data variables in an xarray.Dataset on a shared set of axes.
Parameters
----------
dataset: xarray.Dataset
The Dataset containing data variables to plot. The only dimension and coordinate must be 'time'.
colors: list
A list of strings denoting colors for eac... |
Plot a line plot of all data variables in an xarray.Dataset on a shared set of axes. | def xarray_plot_data_vars_over_time(dataset, colors=['orange', 'blue']):
"""
Plot a line plot of all data variables in an xarray.Dataset on a shared set of axes.
Parameters
----------
dataset: xarray.Dataset
The Dataset containing data variables to plot. The only dimension and coordinate mu... | [
"def",
"xarray_plot_data_vars_over_time",
"(",
"dataset",
",",
"colors",
"=",
"[",
"'orange'",
",",
"'blue'",
"]",
")",
":",
"data_var_names",
"=",
"sorted",
"(",
"list",
"(",
"dataset",
".",
"data_vars",
")",
")",
"len_dataset",
"=",
"dataset",
".",
"time",... | [
119,
0
] | [
146,
14
] | python | en | ['en', 'error', 'th'] | False |
xarray_scatterplot_data_vars | (dataset, figure_kwargs={'figsize': (12, 6)}, colors=['blue', 'orange'], markersize=5) |
Plot a scatterplot of all data variables in an xarray.Dataset on a shared set of axes.
Currently requires a 'time' coordinate, which constitutes the x-axis.
Parameters
----------
dataset: xarray.Dataset
The Dataset containing data variables to plot.
frac_dates: float
The fracti... |
Plot a scatterplot of all data variables in an xarray.Dataset on a shared set of axes.
Currently requires a 'time' coordinate, which constitutes the x-axis. | def xarray_scatterplot_data_vars(dataset, figure_kwargs={'figsize': (12, 6)}, colors=['blue', 'orange'], markersize=5):
"""
Plot a scatterplot of all data variables in an xarray.Dataset on a shared set of axes.
Currently requires a 'time' coordinate, which constitutes the x-axis.
Parameters
-------... | [
"def",
"xarray_scatterplot_data_vars",
"(",
"dataset",
",",
"figure_kwargs",
"=",
"{",
"'figsize'",
":",
"(",
"12",
",",
"6",
")",
"}",
",",
"colors",
"=",
"[",
"'blue'",
",",
"'orange'",
"]",
",",
"markersize",
"=",
"5",
")",
":",
"plt",
".",
"figure"... | [
149,
0
] | [
189,
14
] | python | en | ['en', 'error', 'th'] | False |
xarray_plot_ndvi_boxplot_wofs_lineplot_over_time | (dataset, resolution=None, colors=['orange', 'blue']) |
For an xarray.Dataset, plot a boxplot of NDVI and line plot of WOFS across time.
Parameters
----------
dataset: xarray.Dataset
A Dataset formatted as follows:
coordinates: time, latitude, longitude.
data variables: ndvi, wofs
resolution: str
Denotes the reso... |
For an xarray.Dataset, plot a boxplot of NDVI and line plot of WOFS across time. | def xarray_plot_ndvi_boxplot_wofs_lineplot_over_time(dataset, resolution=None, colors=['orange', 'blue']):
"""
For an xarray.Dataset, plot a boxplot of NDVI and line plot of WOFS across time.
Parameters
----------
dataset: xarray.Dataset
A Dataset formatted as follows:
coordinat... | [
"def",
"xarray_plot_ndvi_boxplot_wofs_lineplot_over_time",
"(",
"dataset",
",",
"resolution",
"=",
"None",
",",
"colors",
"=",
"[",
"'orange'",
",",
"'blue'",
"]",
")",
":",
"plotting_data",
"=",
"dataset",
".",
"stack",
"(",
"lat_lon",
"=",
"(",
"'latitude'",
... | [
192,
0
] | [
255,
14
] | python | en | ['en', 'error', 'th'] | False |
xarray_time_series_plot | (dataset, plot_descs, x_coord='longitude',
y_coord='latitude', fig_params=None,
fig=None, ax=None, show_legend=True, title=None,
max_times_per_plot=None, max_cols=1) |
Plot data variables in an xarray.Dataset together in one figure, with different
plot types for each (e.g. box-and-whisker plot, line plot, scatter plot), and
optional curve fitting to aggregations along time. Handles data binned with
xarray.Dataset methods resample() and groupby(). That is, it handles ... |
Plot data variables in an xarray.Dataset together in one figure, with different
plot types for each (e.g. box-and-whisker plot, line plot, scatter plot), and
optional curve fitting to aggregations along time. Handles data binned with
xarray.Dataset methods resample() and groupby(). That is, it handles ... | def xarray_time_series_plot(dataset, plot_descs, x_coord='longitude',
y_coord='latitude', fig_params=None,
fig=None, ax=None, show_legend=True, title=None,
max_times_per_plot=None, max_cols=1):
"""
Plot data variables in an xarr... | [
"def",
"xarray_time_series_plot",
"(",
"dataset",
",",
"plot_descs",
",",
"x_coord",
"=",
"'longitude'",
",",
"y_coord",
"=",
"'latitude'",
",",
"fig_params",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"show_legend",
"=",
"True",
",... | [
258,
0
] | [
777,
48
] | python | en | ['en', 'error', 'th'] | False |
get_curvefit | (x, y, fit_type, x_smooth=None, n_pts=n_pts_smooth, fit_kwargs=None) |
Gets a curve fit given x values, y values, a type of curve, and parameters for that curve.
Parameters
----------
x: np.ndarray
A 1D NumPy array. The x values to fit to.
y: np.ndarray
A 1D NumPy array. The y values to fit to.
fit_type: str
The type of curve to fit. One o... |
Gets a curve fit given x values, y values, a type of curve, and parameters for that curve. | def get_curvefit(x, y, fit_type, x_smooth=None, n_pts=n_pts_smooth, fit_kwargs=None):
"""
Gets a curve fit given x values, y values, a type of curve, and parameters for that curve.
Parameters
----------
x: np.ndarray
A 1D NumPy array. The x values to fit to.
y: np.ndarray
A 1D N... | [
"def",
"get_curvefit",
"(",
"x",
",",
"y",
",",
"fit_type",
",",
"x_smooth",
"=",
"None",
",",
"n_pts",
"=",
"n_pts_smooth",
",",
"fit_kwargs",
"=",
"None",
")",
":",
"interpolation_curve_fits",
"=",
"[",
"'gaussian'",
",",
"'gaussian_filter'",
",",
"'poly'"... | [
782,
0
] | [
874,
29
] | python | en | ['en', 'error', 'th'] | False |
plot_curvefit | (x, y, fit_type, x_smooth=None, n_pts=n_pts_smooth, fig_params={}, plot_kwargs={}, fig=None, ax=None) |
**This function is DEPRECATED.**
Plots a curve fit given x values, y values, a type of curve to plot, and parameters for that curve.
Parameters
----------
x: np.ndarray
A 1D NumPy array. The x values to fit to.
y: np.ndarray
A 1D NumPy array. The y values to fit to.
fit_typ... |
**This function is DEPRECATED.**
Plots a curve fit given x values, y values, a type of curve to plot, and parameters for that curve. | def plot_curvefit(x, y, fit_type, x_smooth=None, n_pts=n_pts_smooth, fig_params={}, plot_kwargs={}, fig=None, ax=None):
"""
**This function is DEPRECATED.**
Plots a curve fit given x values, y values, a type of curve to plot, and parameters for that curve.
Parameters
----------
x: np.ndarray
... | [
"def",
"plot_curvefit",
"(",
"x",
",",
"y",
",",
"fit_type",
",",
"x_smooth",
"=",
"None",
",",
"n_pts",
"=",
"n_pts_smooth",
",",
"fig_params",
"=",
"{",
"}",
",",
"plot_kwargs",
"=",
"{",
"}",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
")",... | [
877,
0
] | [
942,
56
] | python | en | ['en', 'error', 'th'] | False |
plot_band | (dataset, figsize=(20, 15), fontsize=24, legend_fontsize=24) |
Plots several statistics over time - including mean, median, linear regression of the
means, Gaussian smoothed curve of means, and the band enclosing the 25th and 75th percentiles.
This is very similar to the output of the Comet Time Series Toolset (https://github.com/CosmiQ/CometTS).
Parameters
-... |
Plots several statistics over time - including mean, median, linear regression of the
means, Gaussian smoothed curve of means, and the band enclosing the 25th and 75th percentiles.
This is very similar to the output of the Comet Time Series Toolset (https://github.com/CosmiQ/CometTS). | def plot_band(dataset, figsize=(20, 15), fontsize=24, legend_fontsize=24):
"""
Plots several statistics over time - including mean, median, linear regression of the
means, Gaussian smoothed curve of means, and the band enclosing the 25th and 75th percentiles.
This is very similar to the output of the Co... | [
"def",
"plot_band",
"(",
"dataset",
",",
"figsize",
"=",
"(",
"20",
",",
"15",
")",
",",
"fontsize",
"=",
"24",
",",
"legend_fontsize",
"=",
"24",
")",
":",
"# Calculations",
"times",
"=",
"dataset",
".",
"time",
".",
"values",
"epochs",
"=",
"np",
"... | [
947,
0
] | [
1023,
14
] | python | en | ['en', 'error', 'th'] | False |
convert_name_rgb_255 | (color) |
Converts a name of a matplotlib color to a list of rgb values in the range [0,255].
Else, returns the original argument.
Parameters
----------
color: str
The color name to convert to an rgb list.
|
Converts a name of a matplotlib color to a list of rgb values in the range [0,255].
Else, returns the original argument. | def convert_name_rgb_255(color):
"""
Converts a name of a matplotlib color to a list of rgb values in the range [0,255].
Else, returns the original argument.
Parameters
----------
color: str
The color name to convert to an rgb list.
"""
return [int(255 * rgb) for rgb in mpl.colo... | [
"def",
"convert_name_rgb_255",
"(",
"color",
")",
":",
"return",
"[",
"int",
"(",
"255",
"*",
"rgb",
")",
"for",
"rgb",
"in",
"mpl",
".",
"colors",
".",
"to_rgb",
"(",
"color",
")",
"]",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
"else",
"c... | [
1028,
0
] | [
1038,
100
] | python | en | ['en', 'error', 'th'] | False |
convert_name_rgba_255 | (color) |
Converts a name of a matplotlib color to a list of rgba values in the range [0,255].
Else, returns the original argument.
Parameters
----------
color: str
The color name to convert to an rgba list.
|
Converts a name of a matplotlib color to a list of rgba values in the range [0,255].
Else, returns the original argument. | def convert_name_rgba_255(color):
"""
Converts a name of a matplotlib color to a list of rgba values in the range [0,255].
Else, returns the original argument.
Parameters
----------
color: str
The color name to convert to an rgba list.
"""
return [*convert_name_rgb_255(color), 2... | [
"def",
"convert_name_rgba_255",
"(",
"color",
")",
":",
"return",
"[",
"*",
"convert_name_rgb_255",
"(",
"color",
")",
",",
"255",
"]",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
"else",
"color"
] | [
1041,
0
] | [
1051,
83
] | python | en | ['en', 'error', 'th'] | False |
norm_color | (color) |
Converts either a string name of a matplotlib color or a 3-tuple of rgb values
in the range [0,255] to a 3-tuple of rgb values in the range [0,1].
Parameters
----------
color: str or list-like of numeric
The name of a matplolib color or a .
|
Converts either a string name of a matplotlib color or a 3-tuple of rgb values
in the range [0,255] to a 3-tuple of rgb values in the range [0,1]. | def norm_color(color):
"""
Converts either a string name of a matplotlib color or a 3-tuple of rgb values
in the range [0,255] to a 3-tuple of rgb values in the range [0,1].
Parameters
----------
color: str or list-like of numeric
The name of a matplolib color or a .
"""
color =... | [
"def",
"norm_color",
"(",
"color",
")",
":",
"color",
"=",
"convert_name_rgb_255",
"(",
"color",
")",
"if",
"len",
"(",
"color",
")",
"==",
"3",
":",
"color",
"=",
"[",
"rgb",
"/",
"255",
"for",
"rgb",
"in",
"color",
"]",
"return",
"color"
] | [
1054,
0
] | [
1067,
16
] | python | en | ['en', 'error', 'th'] | False |
create_discrete_color_map | (data_range=None, colors=None, cmap=None,
th=None, pts=None, cmap_name='my_cmap',
data_range_fmt=None, pts_fmt=None) |
Creates a discrete matplotlib LinearSegmentedColormap with thresholds for color changes.
Exclusively either `colors` or `cmap` must be specified (i.e. one and only one).
At least one of the parameters `th` or `pts` may be specified, but not both.
Parameters
----------
data_range: list
... |
Creates a discrete matplotlib LinearSegmentedColormap with thresholds for color changes.
Exclusively either `colors` or `cmap` must be specified (i.e. one and only one).
At least one of the parameters `th` or `pts` may be specified, but not both. | def create_discrete_color_map(data_range=None, colors=None, cmap=None,
th=None, pts=None, cmap_name='my_cmap',
data_range_fmt=None, pts_fmt=None):
"""
Creates a discrete matplotlib LinearSegmentedColormap with thresholds for color changes.
Exclusiv... | [
"def",
"create_discrete_color_map",
"(",
"data_range",
"=",
"None",
",",
"colors",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"th",
"=",
"None",
",",
"pts",
"=",
"None",
",",
"cmap_name",
"=",
"'my_cmap'",
",",
"data_range_fmt",
"=",
"None",
",",
"pts_f... | [
1074,
0
] | [
1184,
15
] | python | en | ['en', 'error', 'th'] | False |
create_gradient_color_map | (data_range, colors, positions=None, cmap_name='my_cmap') |
Creates a gradient colormap with a LinearSegmentedColormap. Currently only creates linear gradients.
Parameters
----------
data_range: list-like
A 2-tuple of the minimum and maximum values the data may take.
colors: list of str or list of tuple
Colors can be string names of matplot... |
Creates a gradient colormap with a LinearSegmentedColormap. Currently only creates linear gradients. | def create_gradient_color_map(data_range, colors, positions=None, cmap_name='my_cmap'):
"""
Creates a gradient colormap with a LinearSegmentedColormap. Currently only creates linear gradients.
Parameters
----------
data_range: list-like
A 2-tuple of the minimum and maximum values the data m... | [
"def",
"create_gradient_color_map",
"(",
"data_range",
",",
"colors",
",",
"positions",
"=",
"None",
",",
"cmap_name",
"=",
"'my_cmap'",
")",
":",
"# Normalize position values based on the data range.",
"if",
"positions",
"is",
"None",
":",
"range_size",
"=",
"data_ra... | [
1187,
0
] | [
1234,
52
] | python | en | ['en', 'error', 'th'] | False |
binary_class_change_plot | (dataarrays, clean_masks=None, x_coord='longitude', y_coord='latitude',
colors=None, override_mask=None, override_color=None,
neg_trans=False, pos_trans=False,
class_legend_label=None, width=10, fig=None, ax=None,
... |
Creates a figure showing one of the following, depending on the format of arguments:
1. The change in the extents of a binary pixel classification in a region over time.
Pixels are colored based on never, sometimes, or always being a member of the class.
In this case, there are 3 regi... |
Creates a figure showing one of the following, depending on the format of arguments:
1. The change in the extents of a binary pixel classification in a region over time.
Pixels are colored based on never, sometimes, or always being a member of the class.
In this case, there are 3 regi... | def binary_class_change_plot(dataarrays, clean_masks=None, x_coord='longitude', y_coord='latitude',
colors=None, override_mask=None, override_color=None,
neg_trans=False, pos_trans=False,
class_legend_label=None, width=10, fig=None, ... | [
"def",
"binary_class_change_plot",
"(",
"dataarrays",
",",
"clean_masks",
"=",
"None",
",",
"x_coord",
"=",
"'longitude'",
",",
"y_coord",
"=",
"'latitude'",
",",
"colors",
"=",
"None",
",",
"override_mask",
"=",
"None",
",",
"override_color",
"=",
"None",
","... | [
1241,
0
] | [
1526,
24
] | python | en | ['en', 'error', 'th'] | False |
intersection_threshold_plot | (first, second, th, mask=None,
color_none='black', color_first='green',
color_second='red', color_both='white',
color_mask='gray',
width=10, fig=None, ax=None,
... |
Given two dataarrays, create a threshold plot showing where zero, one, or both are within a threshold.
Parameters
----------
first, second: xarray.DataArray
The DataArrays to compare.
th: tuple
A 2-tuple of the minimum (inclusive) and maximum (exclusive) threshold values, respectiv... |
Given two dataarrays, create a threshold plot showing where zero, one, or both are within a threshold. | def intersection_threshold_plot(first, second, th, mask=None,
color_none='black', color_first='green',
color_second='red', color_both='white',
color_mask='gray',
width=10, fig=None, ax=None,
... | [
"def",
"intersection_threshold_plot",
"(",
"first",
",",
"second",
",",
"th",
",",
"mask",
"=",
"None",
",",
"color_none",
"=",
"'black'",
",",
"color_first",
"=",
"'green'",
",",
"color_second",
"=",
"'red'",
",",
"color_both",
"=",
"'white'",
",",
"color_m... | [
1531,
0
] | [
1629,
18
] | python | en | ['en', 'error', 'th'] | False |
print_matrix | (cell_value_mtx, cell_label_mtx=None, row_labels=None, col_labels=None,
show_row_labels=True, show_col_labels=True, show_cell_labels=True,
cmap=None, cell_val_fmt='2g', annot_kwargs={}, tick_fontsize=14,
x_axis_tick_kwargs=None, y_axis_tick_kwargs=None,
... |
Prints a matrix as a heatmap.
Inspired by https://gist.github.com/shaypal5/94c53d765083101efc0240d776a23823.
Arguments
---------
cell_value_mtx: numpy.ndarray
A 2D NumPy array to be used as the cell values when coloring with the colormap.
cell_label_mtx: numpy.ndarray
A 2D NumP... |
Prints a matrix as a heatmap.
Inspired by https://gist.github.com/shaypal5/94c53d765083101efc0240d776a23823. | def print_matrix(cell_value_mtx, cell_label_mtx=None, row_labels=None, col_labels=None,
show_row_labels=True, show_col_labels=True, show_cell_labels=True,
cmap=None, cell_val_fmt='2g', annot_kwargs={}, tick_fontsize=14,
x_axis_tick_kwargs=None, y_axis_tick_kwargs=None,... | [
"def",
"print_matrix",
"(",
"cell_value_mtx",
",",
"cell_label_mtx",
"=",
"None",
",",
"row_labels",
"=",
"None",
",",
"col_labels",
"=",
"None",
",",
"show_row_labels",
"=",
"True",
",",
"show_col_labels",
"=",
"True",
",",
"show_cell_labels",
"=",
"True",
",... | [
1638,
0
] | [
1724,
18
] | python | en | ['en', 'error', 'th'] | False |
get_ax_size | (fig, ax) |
Given matplotlib Figure (fig) and Axes (ax) objects, return
the width and height of the Axes object in inches as a list.
|
Given matplotlib Figure (fig) and Axes (ax) objects, return
the width and height of the Axes object in inches as a list.
| def get_ax_size(fig, ax):
"""
Given matplotlib Figure (fig) and Axes (ax) objects, return
the width and height of the Axes object in inches as a list.
"""
# Credit goes to https://stackoverflow.com/a/19306776/5449970.
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
... | [
"def",
"get_ax_size",
"(",
"fig",
",",
"ax",
")",
":",
"# Credit goes to https://stackoverflow.com/a/19306776/5449970.",
"bbox",
"=",
"ax",
".",
"get_window_extent",
"(",
")",
".",
"transformed",
"(",
"fig",
".",
"dpi_scale_trans",
".",
"inverted",
"(",
")",
")",
... | [
1727,
0
] | [
1734,
36
] | python | en | ['en', 'error', 'th'] | False |
xarray_imshow | (data, x_coord='longitude', y_coord='latitude', width=10,
fig=None, ax=None, use_colorbar=True, cbar_labels=None,
use_legend=False, legend_labels=None, fig_kwargs=None,
imshow_kwargs=None, x_label_kwargs=None, y_label_kwargs=None,
cbar_kwargs=None,... |
Shows a heatmap of an xarray DataArray with only latitude and longitude dimensions.
Unlike matplotlib `imshow()` or `data.plot.imshow()`, this sets axes ticks and labels.
It also simplifies creating a colorbar and legend.
Parameters
----------
data: xarray.DataArray
The xarray.DataArra... |
Shows a heatmap of an xarray DataArray with only latitude and longitude dimensions.
Unlike matplotlib `imshow()` or `data.plot.imshow()`, this sets axes ticks and labels.
It also simplifies creating a colorbar and legend. | def xarray_imshow(data, x_coord='longitude', y_coord='latitude', width=10,
fig=None, ax=None, use_colorbar=True, cbar_labels=None,
use_legend=False, legend_labels=None, fig_kwargs=None,
imshow_kwargs=None, x_label_kwargs=None, y_label_kwargs=None,
... | [
"def",
"xarray_imshow",
"(",
"data",
",",
"x_coord",
"=",
"'longitude'",
",",
"y_coord",
"=",
"'latitude'",
",",
"width",
"=",
"10",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"use_colorbar",
"=",
"True",
",",
"cbar_labels",
"=",
"None",
","... | [
1737,
0
] | [
1901,
28
] | python | en | ['en', 'error', 'th'] | False |
convert_coords | (data) |
Takes in the dataframe of all WSC stations
and converts lat/lon/elevation to xyz for
more accurate distance measurements between
stations.
|
Takes in the dataframe of all WSC stations
and converts lat/lon/elevation to xyz for
more accurate distance measurements between
stations.
| def convert_coords(data):
"""
Takes in the dataframe of all WSC stations
and converts lat/lon/elevation to xyz for
more accurate distance measurements between
stations.
"""
data['Latitude'].dropna(inplace=True)
data['Longitude'].dropna(inplace=True)
data['Latitude'] = data['Latitud... | [
"def",
"convert_coords",
"(",
"data",
")",
":",
"data",
"[",
"'Latitude'",
"]",
".",
"dropna",
"(",
"inplace",
"=",
"True",
")",
"data",
"[",
"'Longitude'",
"]",
".",
"dropna",
"(",
"inplace",
"=",
"True",
")",
"data",
"[",
"'Latitude'",
"]",
"=",
"d... | [
22,
0
] | [
61,
15
] | python | en | ['en', 'error', 'th'] | False |
BaseTLearner.__init__ | (self, learner=None, control_learner=None, treatment_learner=None, ate_alpha=.05, control_name=0) | Initialize a T-learner.
Args:
learner (model): a model to estimate control and treatment outcomes.
control_learner (model, optional): a model to estimate control outcomes
treatment_learner (model, optional): a model to estimate treatment outcomes
ate_alpha (float... | Initialize a T-learner. | def __init__(self, learner=None, control_learner=None, treatment_learner=None, ate_alpha=.05, control_name=0):
"""Initialize a T-learner.
Args:
learner (model): a model to estimate control and treatment outcomes.
control_learner (model, optional): a model to estimate control out... | [
"def",
"__init__",
"(",
"self",
",",
"learner",
"=",
"None",
",",
"control_learner",
"=",
"None",
",",
"treatment_learner",
"=",
"None",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
")",
":",
"assert",
"(",
"learner",
"is",
"not",
"None",... | [
32,
4
] | [
55,
40
] | python | en | ['en', 'en', 'it'] | True |
BaseTLearner.fit | (self, X, treatment, y, p=None) | Fit the inference model
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
| Fit the inference model | def fit(self, X, treatment, y, p=None):
"""Fit the inference model
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
"""
X, treatment, y... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_to_np",
"(",
"X",
",",
"treatment",
",",
"y",
")",
"check_treatment_vector",
"(",
"treatment",
",",
... | [
63,
4
] | [
87,
68
] | python | en | ['en', 'en', 'en'] | True |
BaseTLearner.predict | (self, X, treatment=None, y=None, p=None, return_components=False, verbose=True) | Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series, optional): a treatment vector
y (np.array or pd.Series, optional): an outcome vector
return_components (bool, optional): whether to retu... | Predict treatment effects. | def predict(self, X, treatment=None, y=None, p=None, return_components=False, verbose=True):
"""Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series, optional): a treatment vector
y (np.array or... | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"treatment",
"=",
"None",
",",
"y",
"=",
"None",
",",
"p",
"=",
"None",
",",
"return_components",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_t... | [
89,
4
] | [
131,
39
] | python | en | ['fr', 'en', 'en'] | True |
BaseTLearner.fit_predict | (self, X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000,
return_components=False, verbose=True) | Fit the inference model of the T learner and predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
return_ci (bool): whether ... | Fit the inference model of the T learner and predict treatment effects. | def fit_predict(self, X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000,
return_components=False, verbose=True):
"""Fit the inference model of the T learner and predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a ... | [
"def",
"fit_predict",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"return_ci",
"=",
"False",
",",
"n_bootstraps",
"=",
"1000",
",",
"bootstrap_size",
"=",
"10000",
",",
"return_components",
"=",
"False",
",",
"verbose",... | [
133,
4
] | [
178,
43
] | python | en | ['en', 'en', 'en'] | True |
BaseTLearner.estimate_ate | (self, X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000) | Estimate the Average Treatment Effect (ATE).
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
bootstrap_ci (bool): whether to return confidence int... | Estimate the Average Treatment Effect (ATE). | def estimate_ate(self, X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000):
"""Estimate the Average Treatment Effect (ATE).
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
... | [
"def",
"estimate_ate",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"bootstrap_ci",
"=",
"False",
",",
"n_bootstraps",
"=",
"1000",
",",
"bootstrap_size",
"=",
"10000",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",... | [
180,
4
] | [
251,
44
] | python | en | ['en', 'it', 'en'] | True |
BaseTRegressor.__init__ | (self,
learner=None,
control_learner=None,
treatment_learner=None,
ate_alpha=.05,
control_name=0) | Initialize a T-learner regressor.
Args:
learner (model): a model to estimate control and treatment outcomes.
control_learner (model, optional): a model to estimate control outcomes
treatment_learner (model, optional): a model to estimate treatment outcomes
ate_al... | Initialize a T-learner regressor. | def __init__(self,
learner=None,
control_learner=None,
treatment_learner=None,
ate_alpha=.05,
control_name=0):
"""Initialize a T-learner regressor.
Args:
learner (model): a model to estimate control and tre... | [
"def",
"__init__",
"(",
"self",
",",
"learner",
"=",
"None",
",",
"control_learner",
"=",
"None",
",",
"treatment_learner",
"=",
"None",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"le... | [
259,
4
] | [
279,
38
] | python | co | ['en', 'co', 'it'] | False |
BaseTClassifier.__init__ | (self,
learner=None,
control_learner=None,
treatment_learner=None,
ate_alpha=.05,
control_name=0) | Initialize a T-learner classifier.
Args:
learner (model): a model to estimate control and treatment outcomes.
control_learner (model, optional): a model to estimate control outcomes
treatment_learner (model, optional): a model to estimate treatment outcomes
ate_a... | Initialize a T-learner classifier. | def __init__(self,
learner=None,
control_learner=None,
treatment_learner=None,
ate_alpha=.05,
control_name=0):
"""Initialize a T-learner classifier.
Args:
learner (model): a model to estimate control and tr... | [
"def",
"__init__",
"(",
"self",
",",
"learner",
"=",
"None",
",",
"control_learner",
"=",
"None",
",",
"treatment_learner",
"=",
"None",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"le... | [
287,
4
] | [
307,
38
] | python | en | ['en', 'fy', 'en'] | True |
BaseTClassifier.predict | (self, X, treatment=None, y=None, p=None, return_components=False, verbose=True) | Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series, optional): a treatment vector
y (np.array or pd.Series, optional): an outcome vector
verbose (bool, optional): whether to output progres... | Predict treatment effects. | def predict(self, X, treatment=None, y=None, p=None, return_components=False, verbose=True):
"""Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series, optional): a treatment vector
y (np.array or... | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"treatment",
"=",
"None",
",",
"y",
"=",
"None",
",",
"p",
"=",
"None",
",",
"return_components",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"yhat_cs",
"=",
"{",
"}",
"yhat_ts",
"=",
"{",
"}... | [
309,
4
] | [
349,
39
] | python | en | ['fr', 'en', 'en'] | True |
XGBTRegressor.__init__ | (self, ate_alpha=.05, control_name=0, *args, **kwargs) | Initialize a T-learner with two XGBoost models. | Initialize a T-learner with two XGBoost models. | def __init__(self, ate_alpha=.05, control_name=0, *args, **kwargs):
"""Initialize a T-learner with two XGBoost models."""
super().__init__(learner=XGBRegressor(*args, **kwargs),
ate_alpha=ate_alpha,
control_name=control_name) | [
"def",
"__init__",
"(",
"self",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"learner",
"=",
"XGBRegressor",
"(",
"*",
"args",
",",
"*",
... | [
353,
4
] | [
357,
51
] | python | en | ['en', 'en', 'en'] | True |
MLPTRegressor.__init__ | (self, ate_alpha=.05, control_name=0, *args, **kwargs) | Initialize a T-learner with two MLP models. | Initialize a T-learner with two MLP models. | def __init__(self, ate_alpha=.05, control_name=0, *args, **kwargs):
"""Initialize a T-learner with two MLP models."""
super().__init__(learner=MLPRegressor(*args, **kwargs),
ate_alpha=ate_alpha,
control_name=control_name) | [
"def",
"__init__",
"(",
"self",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"learner",
"=",
"MLPRegressor",
"(",
"*",
"args",
",",
"*",
... | [
361,
4
] | [
365,
51
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.