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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Trading.utc_to_market_time | (self, timestamp) | Converts a UTC timestamp to local market time. | Converts a UTC timestamp to local market time. | def utc_to_market_time(self, timestamp):
"""Converts a UTC timestamp to local market time."""
utc_time = utc.localize(timestamp)
market_time = utc_time.astimezone(MARKET_TIMEZONE)
return market_time | [
"def",
"utc_to_market_time",
"(",
"self",
",",
"timestamp",
")",
":",
"utc_time",
"=",
"utc",
".",
"localize",
"(",
"timestamp",
")",
"market_time",
"=",
"utc_time",
".",
"astimezone",
"(",
"MARKET_TIMEZONE",
")",
"return",
"market_time"
] | [
327,
4
] | [
333,
26
] | python | en | ['en', 'en', 'en'] | True |
Trading.market_time_to_utc | (self, timestamp) | Converts a timestamp in local market time to UTC. | Converts a timestamp in local market time to UTC. | def market_time_to_utc(self, timestamp):
"""Converts a timestamp in local market time to UTC."""
market_time = MARKET_TIMEZONE.localize(timestamp)
utc_time = market_time.astimezone(utc)
return utc_time | [
"def",
"market_time_to_utc",
"(",
"self",
",",
"timestamp",
")",
":",
"market_time",
"=",
"MARKET_TIMEZONE",
".",
"localize",
"(",
"timestamp",
")",
"utc_time",
"=",
"market_time",
".",
"astimezone",
"(",
"utc",
")",
"return",
"utc_time"
] | [
335,
4
] | [
341,
23
] | python | en | ['en', 'en', 'en'] | True |
Trading.as_market_time | (self, year, month, day, hour=0, minute=0, second=0) | Creates a timestamp in market time. | Creates a timestamp in market time. | def as_market_time(self, year, month, day, hour=0, minute=0, second=0):
"""Creates a timestamp in market time."""
market_time = datetime(year, month, day, hour, minute, second)
return MARKET_TIMEZONE.localize(market_time) | [
"def",
"as_market_time",
"(",
"self",
",",
"year",
",",
"month",
",",
"day",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
")",
":",
"market_time",
"=",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",... | [
343,
4
] | [
347,
52
] | python | en | ['en', 'en', 'en'] | True |
Trading.make_request | (self, url, method='GET', body='', headers=None) | Makes a request to the TradeKing API. | Makes a request to the TradeKing API. | def make_request(self, url, method='GET', body='', headers=None):
"""Makes a request to the TradeKing API."""
consumer = Consumer(key=TRADEKING_CONSUMER_KEY,
secret=TRADEKING_CONSUMER_SECRET)
token = Token(key=TRADEKING_ACCESS_TOKEN,
secret=TRAD... | [
"def",
"make_request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"body",
"=",
"''",
",",
"headers",
"=",
"None",
")",
":",
"consumer",
"=",
"Consumer",
"(",
"key",
"=",
"TRADEKING_CONSUMER_KEY",
",",
"secret",
"=",
"TRADEKING_CONSUMER_SECR... | [
349,
4
] | [
370,
23
] | python | en | ['en', 'en', 'en'] | True |
Trading.xml_tostring | (self, xml) | Generates a string representation of the XML. | Generates a string representation of the XML. | def xml_tostring(self, xml):
"""Generates a string representation of the XML."""
return tostring(xml, encoding='utf-8').decode('utf-8') | [
"def",
"xml_tostring",
"(",
"self",
",",
"xml",
")",
":",
"return",
"tostring",
"(",
"xml",
",",
"encoding",
"=",
"'utf-8'",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | [
372,
4
] | [
375,
62
] | python | en | ['en', 'en', 'en'] | True |
Trading.fixml_buy_now | (self, ticker, quantity, limit) | Generates the FIXML for a buy order. | Generates the FIXML for a buy order. | def fixml_buy_now(self, ticker, quantity, limit):
"""Generates the FIXML for a buy order."""
fixml = Element('FIXML')
fixml.set('xmlns', FIXML_NAMESPACE)
order = SubElement(fixml, 'Order')
order.set('TmInForce', '0') # Day order
order.set('Typ', '2') # Limit
or... | [
"def",
"fixml_buy_now",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
... | [
377,
4
] | [
394,
39
] | python | en | ['en', 'en', 'en'] | True |
Trading.fixml_sell_eod | (self, ticker, quantity, limit) | Generates the FIXML for a sell order. | Generates the FIXML for a sell order. | def fixml_sell_eod(self, ticker, quantity, limit):
"""Generates the FIXML for a sell order."""
fixml = Element('FIXML')
fixml.set('xmlns', FIXML_NAMESPACE)
order = SubElement(fixml, 'Order')
order.set('TmInForce', '7') # Market on close
order.set('Typ', '2') # Limit
... | [
"def",
"fixml_sell_eod",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
... | [
396,
4
] | [
413,
39
] | python | en | ['en', 'en', 'en'] | True |
Trading.fixml_short_now | (self, ticker, quantity, limit) | Generates the FIXML for a sell short order. | Generates the FIXML for a sell short order. | def fixml_short_now(self, ticker, quantity, limit):
"""Generates the FIXML for a sell short order."""
fixml = Element('FIXML')
fixml.set('xmlns', FIXML_NAMESPACE)
order = SubElement(fixml, 'Order')
order.set('TmInForce', '0') # Day order
order.set('Typ', '2') # Limit
... | [
"def",
"fixml_short_now",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
... | [
415,
4
] | [
432,
39
] | python | en | ['en', 'en', 'en'] | True |
Trading.fixml_cover_eod | (self, ticker, quantity, limit) | Generates the FIXML for a sell to cover order. | Generates the FIXML for a sell to cover order. | def fixml_cover_eod(self, ticker, quantity, limit):
"""Generates the FIXML for a sell to cover order."""
fixml = Element('FIXML')
fixml.set('xmlns', FIXML_NAMESPACE)
order = SubElement(fixml, 'Order')
order.set('TmInForce', '7') # Market on close
order.set('Typ', '2') ... | [
"def",
"fixml_cover_eod",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
... | [
434,
4
] | [
452,
39
] | python | en | ['en', 'en', 'en'] | True |
Trading.get_buy_limit | (self, price) | Calculates the limit price for a buy (or cover) order. | Calculates the limit price for a buy (or cover) order. | def get_buy_limit(self, price):
"""Calculates the limit price for a buy (or cover) order."""
return round((1 + LIMIT_FRACTION) * price, 2) | [
"def",
"get_buy_limit",
"(",
"self",
",",
"price",
")",
":",
"return",
"round",
"(",
"(",
"1",
"+",
"LIMIT_FRACTION",
")",
"*",
"price",
",",
"2",
")"
] | [
454,
4
] | [
457,
53
] | python | en | ['en', 'en', 'en'] | True |
Trading.get_sell_limit | (self, price) | Calculates the limit price for a sell (or short) order. | Calculates the limit price for a sell (or short) order. | def get_sell_limit(self, price):
"""Calculates the limit price for a sell (or short) order."""
return round((1 - LIMIT_FRACTION) * price, 2) | [
"def",
"get_sell_limit",
"(",
"self",
",",
"price",
")",
":",
"return",
"round",
"(",
"(",
"1",
"-",
"LIMIT_FRACTION",
")",
"*",
"price",
",",
"2",
")"
] | [
459,
4
] | [
462,
53
] | python | en | ['en', 'en', 'en'] | True |
Trading.get_balance | (self) | Finds the cash balance in dollars available to spend. | Finds the cash balance in dollars available to spend. | def get_balance(self):
"""Finds the cash balance in dollars available to spend."""
balances_url = TRADEKING_API_URL % (
'accounts/%s' % TRADEKING_ACCOUNT_NUMBER)
response = self.make_request(url=balances_url)
if not response:
self.logs.error('No balances respons... | [
"def",
"get_balance",
"(",
"self",
")",
":",
"balances_url",
"=",
"TRADEKING_API_URL",
"%",
"(",
"'accounts/%s'",
"%",
"TRADEKING_ACCOUNT_NUMBER",
")",
"response",
"=",
"self",
".",
"make_request",
"(",
"url",
"=",
"balances_url",
")",
"if",
"not",
"response",
... | [
464,
4
] | [
490,
20
] | python | en | ['en', 'en', 'en'] | True |
Trading.get_last_price | (self, ticker) | Finds the last trade price for the specified stock. | Finds the last trade price for the specified stock. | def get_last_price(self, ticker):
"""Finds the last trade price for the specified stock."""
quotes_url = TRADEKING_API_URL % 'market/ext/quotes'
quotes_url += '?symbols=%s' % ticker
quotes_url += '&fids=last,date,symbol,exch_desc,name'
response = self.make_request(url=quotes_ur... | [
"def",
"get_last_price",
"(",
"self",
",",
"ticker",
")",
":",
"quotes_url",
"=",
"TRADEKING_API_URL",
"%",
"'market/ext/quotes'",
"quotes_url",
"+=",
"'?symbols=%s'",
"%",
"ticker",
"quotes_url",
"+=",
"'&fids=last,date,symbol,exch_desc,name'",
"response",
"=",
"self",... | [
492,
4
] | [
526,
23
] | python | en | ['en', 'en', 'en'] | True |
Trading.get_order_url | (self) | Gets the TradeKing URL for placing orders. | Gets the TradeKing URL for placing orders. | def get_order_url(self):
"""Gets the TradeKing URL for placing orders."""
url_path = 'accounts/%s/orders' % TRADEKING_ACCOUNT_NUMBER
if not USE_REAL_MONEY:
url_path += '/preview'
return TRADEKING_API_URL % url_path | [
"def",
"get_order_url",
"(",
"self",
")",
":",
"url_path",
"=",
"'accounts/%s/orders'",
"%",
"TRADEKING_ACCOUNT_NUMBER",
"if",
"not",
"USE_REAL_MONEY",
":",
"url_path",
"+=",
"'/preview'",
"return",
"TRADEKING_API_URL",
"%",
"url_path"
] | [
528,
4
] | [
534,
43
] | python | en | ['en', 'en', 'en'] | True |
Trading.get_quantity | (self, ticker, budget) | Calculates the quantity of a stock based on the current market price
and a maximum budget.
| Calculates the quantity of a stock based on the current market price
and a maximum budget.
| def get_quantity(self, ticker, budget):
"""Calculates the quantity of a stock based on the current market price
and a maximum budget.
"""
# Calculate the quantity based on the current price and the budget.
price = self.get_last_price(ticker)
if not price:
sel... | [
"def",
"get_quantity",
"(",
"self",
",",
"ticker",
",",
"budget",
")",
":",
"# Calculate the quantity based on the current price and the budget.",
"price",
"=",
"self",
".",
"get_last_price",
"(",
"ticker",
")",
"if",
"not",
"price",
":",
"self",
".",
"logs",
".",... | [
536,
4
] | [
552,
32
] | python | en | ['en', 'en', 'en'] | True |
Trading.bull | (self, ticker, budget) | Executes the bullish strategy on the specified stock within the
specified budget: Buy now at market rate and sell at market rate at
close.
| Executes the bullish strategy on the specified stock within the
specified budget: Buy now at market rate and sell at market rate at
close.
| def bull(self, ticker, budget):
"""Executes the bullish strategy on the specified stock within the
specified budget: Buy now at market rate and sell at market rate at
close.
"""
# Calculate the quantity.
quantity, price = self.get_quantity(ticker, budget)
if not ... | [
"def",
"bull",
"(",
"self",
",",
"ticker",
",",
"budget",
")",
":",
"# Calculate the quantity.",
"quantity",
",",
"price",
"=",
"self",
".",
"get_quantity",
"(",
"ticker",
",",
"budget",
")",
"if",
"not",
"quantity",
":",
"self",
".",
"logs",
".",
"warn"... | [
554,
4
] | [
580,
19
] | python | en | ['en', 'en', 'en'] | True |
Trading.bear | (self, ticker, budget) | Executes the bearish strategy on the specified stock within the
specified budget: Sell short at market rate and buy to cover at market
rate at close.
| Executes the bearish strategy on the specified stock within the
specified budget: Sell short at market rate and buy to cover at market
rate at close.
| def bear(self, ticker, budget):
"""Executes the bearish strategy on the specified stock within the
specified budget: Sell short at market rate and buy to cover at market
rate at close.
"""
# Calculate the quantity.
quantity, price = self.get_quantity(ticker, budget)
... | [
"def",
"bear",
"(",
"self",
",",
"ticker",
",",
"budget",
")",
":",
"# Calculate the quantity.",
"quantity",
",",
"price",
"=",
"self",
".",
"get_quantity",
"(",
"ticker",
",",
"budget",
")",
"if",
"not",
"quantity",
":",
"self",
".",
"logs",
".",
"warn"... | [
582,
4
] | [
608,
19
] | python | en | ['en', 'en', 'en'] | True |
Trading.make_order_request | (self, fixml) | Executes an order defined by FIXML and verifies the response. | Executes an order defined by FIXML and verifies the response. | def make_order_request(self, fixml):
"""Executes an order defined by FIXML and verifies the response."""
response = self.make_request(url=self.get_order_url(), method='POST',
body=fixml, headers=FIXML_HEADERS)
if not response:
self.logs.error('N... | [
"def",
"make_order_request",
"(",
"self",
",",
"fixml",
")",
":",
"response",
"=",
"self",
".",
"make_request",
"(",
"url",
"=",
"self",
".",
"get_order_url",
"(",
")",
",",
"method",
"=",
"'POST'",
",",
"body",
"=",
"fixml",
",",
"headers",
"=",
"FIXM... | [
610,
4
] | [
634,
19
] | python | en | ['en', 'en', 'en'] | True |
InMemoryDocumentStore.__init__ | (
self,
index: str = "document",
label_index: str = "label",
embedding_field: Optional[str] = "embedding",
embedding_dim: int = 768,
return_embedding: bool = False,
similarity: str = "dot_product",
progress_bar: bool = True,
) |
:param index: The documents are scoped to an index attribute that can be used when writing, querying,
or deleting documents. This parameter sets the default value for document index.
:param label_index: The default value of index attribute for the labels.
:param embedding_... |
:param index: The documents are scoped to an index attribute that can be used when writing, querying,
or deleting documents. This parameter sets the default value for document index.
:param label_index: The default value of index attribute for the labels.
:param embedding_... | def __init__(
self,
index: str = "document",
label_index: str = "label",
embedding_field: Optional[str] = "embedding",
embedding_dim: int = 768,
return_embedding: bool = False,
similarity: str = "dot_product",
progress_bar: bool = True,
):
"""
... | [
"def",
"__init__",
"(",
"self",
",",
"index",
":",
"str",
"=",
"\"document\"",
",",
"label_index",
":",
"str",
"=",
"\"label\"",
",",
"embedding_field",
":",
"Optional",
"[",
"str",
"]",
"=",
"\"embedding\"",
",",
"embedding_dim",
":",
"int",
"=",
"768",
... | [
24,
4
] | [
53,
40
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.write_documents | (self, documents: Union[List[dict], List[Document]], index: Optional[str] = None) |
Indexes documents for later queries.
:param documents: a list of Python dictionaries or a list of Haystack Document objects.
For documents as dictionaries, the format is {"text": "<the-actual-text>"}.
Optionally: Include meta data via {"text": "<the-... |
Indexes documents for later queries. | def write_documents(self, documents: Union[List[dict], List[Document]], index: Optional[str] = None):
"""
Indexes documents for later queries.
:param documents: a list of Python dictionaries or a list of Haystack Document objects.
For documents as dictionaries, the for... | [
"def",
"write_documents",
"(",
"self",
",",
"documents",
":",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Document",
"]",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"index",
"=",
"index",
"or",
"self"... | [
55,
4
] | [
76,
55
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.write_labels | (self, labels: Union[List[dict], List[Label]], index: Optional[str] = None) | Write annotation labels into document store. | Write annotation labels into document store. | def write_labels(self, labels: Union[List[dict], List[Label]], index: Optional[str] = None):
"""Write annotation labels into document store."""
index = index or self.label_index
label_objects = [Label.from_dict(l) if isinstance(l, dict) else l for l in labels]
for label in label_objects... | [
"def",
"write_labels",
"(",
"self",
",",
"labels",
":",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Label",
"]",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"index",
"=",
"index",
"or",
"self",
".",
... | [
83,
4
] | [
95,
49
] | python | en | ['en', 'en', 'en'] | True |
InMemoryDocumentStore.get_document_by_id | (self, id: str, index: Optional[str] = None) | Fetch a document by specifying its text id string | Fetch a document by specifying its text id string | def get_document_by_id(self, id: str, index: Optional[str] = None) -> Optional[Document]:
"""Fetch a document by specifying its text id string"""
index = index or self.index
documents = self.get_documents_by_id([id], index=index)
if documents:
return documents[0]
else... | [
"def",
"get_document_by_id",
"(",
"self",
",",
"id",
":",
"str",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"Document",
"]",
":",
"index",
"=",
"index",
"or",
"self",
".",
"index",
"documents",
"=",
"self... | [
97,
4
] | [
104,
23
] | python | en | ['en', 'en', 'en'] | True |
InMemoryDocumentStore.get_documents_by_id | (self, ids: List[str], index: Optional[str] = None) | Fetch documents by specifying a list of text id strings | Fetch documents by specifying a list of text id strings | def get_documents_by_id(self, ids: List[str], index: Optional[str] = None) -> List[Document]:
"""Fetch documents by specifying a list of text id strings"""
index = index or self.index
documents = [self.indexes[index][id] for id in ids]
return documents | [
"def",
"get_documents_by_id",
"(",
"self",
",",
"ids",
":",
"List",
"[",
"str",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Document",
"]",
":",
"index",
"=",
"index",
"or",
"self",
".",
"index",
"docu... | [
106,
4
] | [
110,
24
] | python | en | ['en', 'en', 'en'] | True |
InMemoryDocumentStore.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... | [
"def",
"query_by_embedding",
"(",
"self",
",",
"query_emb",
":",
"np",
".",
"ndarray",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"top_k",
":",
"int",
"=",
"10",
",",
"index",... | [
112,
4
] | [
164,
115
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.update_embeddings | (
self,
retriever: BaseRetriever,
index: Optional[str] = None,
filters: Optional[Dict[str, List[str]]] = None,
update_existing_embeddings: bool = True,
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,
filters: Optional[Dict[str, List[str]]] = None,
update_existing_embeddings: bool = True,
batch_size: int = 10_000,
):
"""
Updates the embeddings in the the document sto... | [
"def",
"update_embeddings",
"(",
"self",
",",
"retriever",
":",
"BaseRetriever",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None... | [
166,
4
] | [
213,
63
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.get_document_count | (self, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None) |
Return the number of documents in the document store.
|
Return the number of documents in the document store.
| def get_document_count(self, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None) -> int:
"""
Return the number of documents in the document store.
"""
documents = self.get_all_documents(index=index, filters=filters)
return len(documents) | [
"def",
"get_document_count",
"(",
"self",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"int",
":",
"documents"... | [
215,
4
] | [
220,
29
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.get_label_count | (self, index: Optional[str] = None) |
Return the number of labels in the document store
|
Return the number of labels in the document store
| def get_label_count(self, index: Optional[str] = None) -> int:
"""
Return the number of labels in the document store
"""
index = index or self.label_index
return len(self.indexes[index].items()) | [
"def",
"get_label_count",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"int",
":",
"index",
"=",
"index",
"or",
"self",
".",
"label_index",
"return",
"len",
"(",
"self",
".",
"indexes",
"[",
"index",
"]",
".",
... | [
222,
4
] | [
227,
47
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.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. The methods returns a Python Generator that yields individual
documents.
:param index: Name of the index to get the documents from. If None, the
DocumentStore's default index (self.index) will be used.
:param filters: Opt... |
Get all documents from the document store. The methods returns a Python Generator that yields individual
documents. | 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",
":",... | [
277,
4
] | [
300,
25
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.get_all_labels | (self, index: str = None, filters: Optional[Dict[str, List[str]]] = None) |
Return all labels in the document store
|
Return all labels in the document store
| def get_all_labels(self, index: str = None, filters: Optional[Dict[str, List[str]]] = None) -> List[Label]:
"""
Return all labels in the document store
"""
index = index or self.label_index
if filters:
result = []
for label in self.indexes[index].values()... | [
"def",
"get_all_labels",
"(",
"self",
",",
"index",
":",
"str",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Label",
"]",
":",
"index",
"=",
... | [
302,
4
] | [
322,
21
] | python | en | ['en', 'error', 'th'] | False |
InMemoryDocumentStore.delete_all_documents | (self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None) |
Delete documents in an index. All documents are deleted if no filters are passed.
:param index: Index name to delete the document from.
:param filters: Optional filters to narrow down the documents to be deleted.
:return: None
|
Delete documents in an index. All documents are deleted if no filters are passed. | def delete_all_documents(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None):
"""
Delete documents in an index. All documents are deleted if no filters are passed.
:param index: Index name to delete the document from.
:param filters: Optional filters to na... | [
"def",
"delete_all_documents",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
")",
":",
"if",
"filters",
":",
... | [
324,
4
] | [
336,
32
] | python | en | ['en', 'error', 'th'] | False |
plot | (df, kind='gain', tmle=False, n=100, figsize=(8, 8), *args, **kwarg) | Plot one of the lift/gain/Qini charts of model estimates.
A factory method for `plot_lift()`, `plot_gain()`, `plot_qini()`, `plot_tmlegain()` and `plot_tmleqini()`.
For details, pleas see docstrings of each function.
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as... | Plot one of the lift/gain/Qini charts of model estimates. | def plot(df, kind='gain', tmle=False, n=100, figsize=(8, 8), *args, **kwarg):
"""Plot one of the lift/gain/Qini charts of model estimates.
A factory method for `plot_lift()`, `plot_gain()`, `plot_qini()`, `plot_tmlegain()` and `plot_tmleqini()`.
For details, pleas see docstrings of each function.
Args... | [
"def",
"plot",
"(",
"df",
",",
"kind",
"=",
"'gain'",
",",
"tmle",
"=",
"False",
",",
"n",
"=",
"100",
",",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"catalog",
"=",
"{",
"'lift'",
":",
"ge... | [
16,
0
] | [
47,
45
] | python | en | ['en', 'bg', 'en'] | True |
get_cumlift | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
random_seed=42) | Get average uplifts of model estimates in cumulative population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the mean of the true treatment effect in each of cumulative population.
Otherwise, it's calculated as the difference between the mean outcomes of the
tr... | Get average uplifts of model estimates in cumulative population. | def get_cumlift(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
random_seed=42):
"""Get average uplifts of model estimates in cumulative population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the mean of the true treatment effec... | [
"def",
"get_cumlift",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"random_seed",
"=",
"42",
")",
":",
"assert",
"(",
"(",
"outcome_col",
"in",
"df",
".",
"columns",
")",
"an... | [
50,
0
] | [
117,
15
] | python | en | ['en', 'da', 'en'] | True |
get_cumgain | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42) | Get cumulative gains of model estimates in population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it's calculated as the cumulative difference between the mean outcomes
of the trea... | Get cumulative gains of model estimates in population. | def get_cumgain(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42):
"""Get cumulative gains of model estimates in population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cumulative gain of the tr... | [
"def",
"get_cumgain",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"False",
",",
"random_seed",
"=",
"42",
")",
":",
"lift",
"=",
"get_cumlift",
"(",
"df",
... | [
120,
0
] | [
155,
15
] | python | en | ['en', 'la', 'en'] | True |
get_qini | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42) | Get Qini of model estimates in population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it's calculated as the cumulative difference between the mean outcomes
of the treatment and co... | Get Qini of model estimates in population. | def get_qini(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42):
"""Get Qini of model estimates in population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cumulative gain of the true treatment effec... | [
"def",
"get_qini",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"False",
",",
"random_seed",
"=",
"42",
")",
":",
"assert",
"(",
"(",
"outcome_col",
"in",
"... | [
158,
0
] | [
230,
15
] | python | en | ['en', 'la', 'en'] | True |
get_tmlegain | (df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='p', n_segment=5, cv=None,
calibrate_propensity=True, ci=False) | Get TMLE based average uplifts of model estimates of segments.
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
inferenece_col (list of str): a list of columns that used in learner for inference
learner (optional): a model used by TMLE to estimate th... | Get TMLE based average uplifts of model estimates of segments. | def get_tmlegain(df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='p', n_segment=5, cv=None,
calibrate_propensity=True, ci=False):
"""Get TMLE based average uplifts of model estimates of segments... | [
"def",
"get_tmlegain",
"(",
"df",
",",
"inference_col",
",",
"learner",
"=",
"LGBMRegressor",
"(",
"num_leaves",
"=",
"64",
",",
"learning_rate",
"=",
".05",
",",
"n_estimators",
"=",
"300",
")",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"... | [
233,
0
] | [
310,
15
] | python | en | ['en', 'zu', 'en'] | True |
get_tmleqini | (df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='p', n_segment=5, cv=None,
calibrate_propensity=True, ci=False, normalize=False) | Get TMLE based Qini of model estimates by segments.
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
inferenece_col (list of str): a list of columns that used in learner for inference
learner(optional): a model used by TMLE to estimate the outcome
... | Get TMLE based Qini of model estimates by segments. | def get_tmleqini(df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='p', n_segment=5, cv=None,
calibrate_propensity=True, ci=False, normalize=False):
"""Get TMLE based Qini of model estimates by se... | [
"def",
"get_tmleqini",
"(",
"df",
",",
"inference_col",
",",
"learner",
"=",
"LGBMRegressor",
"(",
"num_leaves",
"=",
"64",
",",
"learning_rate",
"=",
".05",
",",
"n_estimators",
"=",
"300",
")",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"... | [
313,
0
] | [
392,
15
] | python | en | ['en', 'zu', 'en'] | True |
plot_gain | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42, n=100, figsize=(8, 8)) | Plot the cumulative gain chart (or uplift curve) of model estimates.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it's calculated as the cumulative difference between the mean outcomes
... | Plot the cumulative gain chart (or uplift curve) of model estimates. | def plot_gain(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42, n=100, figsize=(8, 8)):
"""Plot the cumulative gain chart (or uplift curve) of model estimates.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
... | [
"def",
"plot_gain",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"False",
",",
"random_seed",
"=",
"42",
",",
"n",
"=",
"100",
",",
"figsize",
"=",
"(",
"... | [
395,
0
] | [
421,
97
] | python | en | ['en', 'ca', 'en'] | True |
plot_lift | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
random_seed=42, n=100, figsize=(8, 8)) | Plot the lift chart of model estimates in cumulative population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the mean of the true treatment effect in each of cumulative population.
Otherwise, it's calculated as the difference between the mean outcomes of the
tr... | Plot the lift chart of model estimates in cumulative population. | def plot_lift(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
random_seed=42, n=100, figsize=(8, 8)):
"""Plot the lift chart of model estimates in cumulative population.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the mean of the t... | [
"def",
"plot_lift",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"random_seed",
"=",
"42",
",",
"n",
"=",
"100",
",",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
")",
":",
... | [
424,
0
] | [
449,
76
] | python | en | ['en', 'ca', 'en'] | True |
plot_qini | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42, n=100, figsize=(8, 8)) | Plot the Qini chart (or uplift curve) of model estimates.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it's calculated as the cumulative difference between the mean outcomes
of the t... | Plot the Qini chart (or uplift curve) of model estimates. | def plot_qini(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau',
normalize=False, random_seed=42, n=100, figsize=(8, 8)):
"""Plot the Qini chart (or uplift curve) of model estimates.
If the true treatment effect is provided (e.g. in synthetic data), it's calculated
as the cum... | [
"def",
"plot_qini",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"False",
",",
"random_seed",
"=",
"42",
",",
"n",
"=",
"100",
",",
"figsize",
"=",
"(",
"... | [
452,
0
] | [
479,
97
] | python | en | ['en', 'sq', 'en'] | True |
plot_tmlegain | (df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='tau', n_segment=5, cv=None,
calibrate_propensity=True, ci=False, figsize=(8, 8)) | Plot the lift chart based of TMLE estimation
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
inferenece_col (list of str): a list of columns that used in learner for inference
learner (optional): a model used by TMLE to estimate the outcome
... | Plot the lift chart based of TMLE estimation | def plot_tmlegain(df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='tau', n_segment=5, cv=None,
calibrate_propensity=True, ci=False, figsize=(8, 8)):
"""Plot the lift chart based of TMLE estima... | [
"def",
"plot_tmlegain",
"(",
"df",
",",
"inference_col",
",",
"learner",
"=",
"LGBMRegressor",
"(",
"num_leaves",
"=",
"64",
",",
"learning_rate",
"=",
".05",
",",
"n_estimators",
"=",
"300",
")",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
... | [
482,
0
] | [
527,
14
] | python | en | ['en', 'zu', 'en'] | True |
plot_tmleqini | (df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='tau', n_segment=5, cv=None,
calibrate_propensity=True, ci=False, figsize=(8, 8)) | Plot the qini chart based of TMLE estimation
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
inferenece_col (list of str): a list of columns that used in learner for inference
learner (optional): a model used by TMLE to estimate the outcome
... | Plot the qini chart based of TMLE estimation | def plot_tmleqini(df, inference_col, learner=LGBMRegressor(num_leaves=64, learning_rate=.05, n_estimators=300),
outcome_col='y', treatment_col='w', p_col='tau', n_segment=5, cv=None,
calibrate_propensity=True, ci=False, figsize=(8, 8)):
"""Plot the qini chart based of TMLE estima... | [
"def",
"plot_tmleqini",
"(",
"df",
",",
"inference_col",
",",
"learner",
"=",
"LGBMRegressor",
"(",
"num_leaves",
"=",
"64",
",",
"learning_rate",
"=",
".05",
",",
"n_estimators",
"=",
"300",
")",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
... | [
530,
0
] | [
575,
14
] | python | en | ['en', 'zu', 'tr'] | False |
auuc_score | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=True,
tmle=False, *args, **kwarg) | Calculate the AUUC (Area Under the Uplift Curve) score.
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (... | Calculate the AUUC (Area Under the Uplift Curve) score. | def auuc_score(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=True,
tmle=False, *args, **kwarg):
"""Calculate the AUUC (Area Under the Uplift Curve) score.
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
ou... | [
"def",
"auuc_score",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"True",
",",
"tmle",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
... | [
578,
0
] | [
597,
43
] | python | en | ['en', 'en', 'en'] | True |
qini_score | (df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=True,
tmle=False, *args, **kwarg) | Calculate the Qini score: the area between the Qini curves of a model and random.
For details, see Radcliffe (2007), `Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models`
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
... | Calculate the Qini score: the area between the Qini curves of a model and random. | def qini_score(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=True,
tmle=False, *args, **kwarg):
"""Calculate the Qini score: the area between the Qini curves of a model and random.
For details, see Radcliffe (2007), `Using Control Group to Target on Predicted Lift... | [
"def",
"qini_score",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"True",
",",
"tmle",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
... | [
600,
0
] | [
622,
70
] | python | en | ['en', 'en', 'en'] | True |
plot_ps_diagnostics | (df, covariate_col, treatment_col='w', p_col='p') | Plot covariate balances (standardized differences between the treatment and the control)
before and after weighting the sample using the inverse probability of treatment weights.
Args:
df (pandas.DataFrame): a data frame containing the covariates and treatment indicator
covariate_col (list of ... | Plot covariate balances (standardized differences between the treatment and the control)
before and after weighting the sample using the inverse probability of treatment weights. | def plot_ps_diagnostics(df, covariate_col, treatment_col='w', p_col='p'):
"""Plot covariate balances (standardized differences between the treatment and the control)
before and after weighting the sample using the inverse probability of treatment weights.
Args:
df (pandas.DataFrame): a data frame ... | [
"def",
"plot_ps_diagnostics",
"(",
"df",
",",
"covariate_col",
",",
"treatment_col",
"=",
"'w'",
",",
"p_col",
"=",
"'p'",
")",
":",
"X",
"=",
"df",
"[",
"covariate_col",
"]",
"W",
"=",
"df",
"[",
"treatment_col",
"]",
"PS",
"=",
"df",
"[",
"p_col",
... | [
625,
0
] | [
652,
20
] | python | en | ['en', 'en', 'en'] | True |
get_std_diffs | (X, W, weight=None, weighted=False, numeric_threshold=5) | Calculate the inverse probability of treatment weighted standardized
differences in covariate means between the treatment and the control.
If weighting is set to 'False', calculate unweighted standardized
differences. Accepts only continuous and binary numerical variables.
| Calculate the inverse probability of treatment weighted standardized
differences in covariate means between the treatment and the control.
If weighting is set to 'False', calculate unweighted standardized
differences. Accepts only continuous and binary numerical variables.
| def get_std_diffs(X, W, weight=None, weighted=False, numeric_threshold=5):
"""Calculate the inverse probability of treatment weighted standardized
differences in covariate means between the treatment and the control.
If weighting is set to 'False', calculate unweighted standardized
differences. Accepts ... | [
"def",
"get_std_diffs",
"(",
"X",
",",
"W",
",",
"weight",
"=",
"None",
",",
"weighted",
"=",
"False",
",",
"numeric_threshold",
"=",
"5",
")",
":",
"cont_cols",
",",
"prop_cols",
"=",
"_get_numeric_vars",
"(",
"X",
",",
"threshold",
"=",
"numeric_threshol... | [
685,
0
] | [
742,
23
] | python | en | ['en', 'en', 'en'] | True |
_get_numeric_vars | (X, threshold=5) | Attempt to determine which variables are numeric and which
are categorical. The threshold for a 'continuous' variable
is set to 5 by default.
| Attempt to determine which variables are numeric and which
are categorical. The threshold for a 'continuous' variable
is set to 5 by default.
| def _get_numeric_vars(X, threshold=5):
"""Attempt to determine which variables are numeric and which
are categorical. The threshold for a 'continuous' variable
is set to 5 by default.
"""
cont = [(not hasattr(X.iloc[:, i], 'cat')) and (
X.iloc[:, i].nunique() >= threshold) for i in range(X.... | [
"def",
"_get_numeric_vars",
"(",
"X",
",",
"threshold",
"=",
"5",
")",
":",
"cont",
"=",
"[",
"(",
"not",
"hasattr",
"(",
"X",
".",
"iloc",
"[",
":",
",",
"i",
"]",
",",
"'cat'",
")",
")",
"and",
"(",
"X",
".",
"iloc",
"[",
":",
",",
"i",
"... | [
745,
0
] | [
766,
31
] | python | en | ['en', 'en', 'en'] | True |
_get_mean_var | (X) | Calculate the mean and variance of a variable.
| Calculate the mean and variance of a variable.
| def _get_mean_var(X):
"""Calculate the mean and variance of a variable.
"""
mean = X.mean()
var = X.var()
return [mean, var] | [
"def",
"_get_mean_var",
"(",
"X",
")",
":",
"mean",
"=",
"X",
".",
"mean",
"(",
")",
"var",
"=",
"X",
".",
"var",
"(",
")",
"return",
"[",
"mean",
",",
"var",
"]"
] | [
769,
0
] | [
775,
22
] | python | en | ['en', 'en', 'en'] | True |
_get_wmean_wvar | (X, weight) |
Calculate the weighted mean of a variable given an arbitrary
sample weight. Formulas from:
Austin, Peter C., and Elizabeth A. Stuart. 2015. Moving towards Best
Practice When Using Inverse Probability of Treatment Weighting (IPTW)
Using the Propensity Score to Estimate Causal Treatment Effects in
... |
Calculate the weighted mean of a variable given an arbitrary
sample weight. Formulas from: | def _get_wmean_wvar(X, weight):
'''
Calculate the weighted mean of a variable given an arbitrary
sample weight. Formulas from:
Austin, Peter C., and Elizabeth A. Stuart. 2015. Moving towards Best
Practice When Using Inverse Probability of Treatment Weighting (IPTW)
Using the Propensity Score to... | [
"def",
"_get_wmean_wvar",
"(",
"X",
",",
"weight",
")",
":",
"weighted_mean",
"=",
"np",
".",
"sum",
"(",
"weight",
"*",
"X",
")",
"/",
"np",
".",
"sum",
"(",
"weight",
")",
"weighted_var",
"=",
"(",
"np",
".",
"sum",
"(",
"weight",
")",
"/",
"("... | [
778,
0
] | [
793,
40
] | python | en | ['en', 'error', 'th'] | False |
dircmp.phase3 | (self) | Find out differences between common files. \
Ensure we are using content comparison with shallow=False. | Find out differences between common files. \
Ensure we are using content comparison with shallow=False. | def phase3(self):
"""Find out differences between common files. \
Ensure we are using content comparison with shallow=False."""
fcomp = filecmp.cmpfiles(self.left, self.right, self.common_files,
shallow=False)
self.same_files, self.diff_files, self.fu... | [
"def",
"phase3",
"(",
"self",
")",
":",
"fcomp",
"=",
"filecmp",
".",
"cmpfiles",
"(",
"self",
".",
"left",
",",
"self",
".",
"right",
",",
"self",
".",
"common_files",
",",
"shallow",
"=",
"False",
")",
"self",
".",
"same_files",
",",
"self",
".",
... | [
25,
4
] | [
30,
66
] | python | en | ['en', 'en', 'en'] | True |
Backend.fetch | (target: str) |
Fetch HTTP and HTTPS requests through URLLIB3, return request \
object, raises exception if status is not in 2XX or 301, 302.
:param target: HTTPS/HTTP address
:type target: str
:return: request
:rtype: object
|
Fetch HTTP and HTTPS requests through URLLIB3, return request \
object, raises exception if status is not in 2XX or 301, 302. | def fetch(target: str) -> object:
"""
Fetch HTTP and HTTPS requests through URLLIB3, return request \
object, raises exception if status is not in 2XX or 301, 302.
:param target: HTTPS/HTTP address
:type target: str
:return: request
:rtype: object
"""... | [
"def",
"fetch",
"(",
"target",
":",
"str",
")",
"->",
"object",
":",
"urllib3_pool_manager",
"=",
"urllib3",
".",
"PoolManager",
"(",
")",
"fetch_request",
"=",
"urllib3_pool_manager",
".",
"request",
"(",
"\"GET\"",
",",
"target",
")",
"if",
"str",
"(",
"... | [
37,
4
] | [
55,
32
] | python | en | ['en', 'error', 'th'] | False |
Backend.directory_split_recursive | (whole: str) |
Take path parameter and apply path.split recursively, dump \
spliced directory tree to return variable.
Produces segmented directories, i.e:
/path/to/somewhere/ -> /path/to -> /path/
...Which will be appended to the return list as mentioned previously.
:param whole... |
Take path parameter and apply path.split recursively, dump \
spliced directory tree to return variable. | def directory_split_recursive(whole: str) -> list:
"""
Take path parameter and apply path.split recursively, dump \
spliced directory tree to return variable.
Produces segmented directories, i.e:
/path/to/somewhere/ -> /path/to -> /path/
...Which will be appended to ... | [
"def",
"directory_split_recursive",
"(",
"whole",
":",
"str",
")",
"->",
"list",
":",
"# append components to this list, function return",
"dump",
"=",
"[",
"]",
"# remaining path after splitting previous component",
"previous",
"=",
"\"/INITIAL/INITIAL\"",
"while",
"path",
... | [
58,
4
] | [
83,
19
] | python | en | ['en', 'error', 'th'] | False |
Patcher.__init__ | (self, patch: str, target: str,
suppress_version_check: bool = False,
suppress_name_check: bool = False,
skip_keep_check: bool = False) |
Take patch file and target application directory, and apply \
changes after checking VERSION and NAME.
Inorganic and for robots.
:param patch: web address or path to patch file
:type patch: str
:param target: path to application directory for patching
:type... |
Take patch file and target application directory, and apply \
changes after checking VERSION and NAME. | def __init__(self, patch: str, target: str,
suppress_version_check: bool = False,
suppress_name_check: bool = False,
skip_keep_check: bool = False):
"""
Take patch file and target application directory, and apply \
changes after checking VER... | [
"def",
"__init__",
"(",
"self",
",",
"patch",
":",
"str",
",",
"target",
":",
"str",
",",
"suppress_version_check",
":",
"bool",
"=",
"False",
",",
"suppress_name_check",
":",
"bool",
"=",
"False",
",",
"skip_keep_check",
":",
"bool",
"=",
"False",
")",
... | [
121,
4
] | [
287,
44
] | python | en | ['en', 'error', 'th'] | False |
Patcher.create_work_directory | () |
Create directory under the OS temporary directory with a unique name \
to prevent conflicting instances.
:return: generated tempdir name
:rtype: str
|
Create directory under the OS temporary directory with a unique name \
to prevent conflicting instances. | def create_work_directory() -> str:
"""
Create directory under the OS temporary directory with a unique name \
to prevent conflicting instances.
:return: generated tempdir name
:rtype: str
"""
identifier = "/bandage_patcher_session_" + md5(
str(ti... | [
"def",
"create_work_directory",
"(",
")",
"->",
"str",
":",
"identifier",
"=",
"\"/bandage_patcher_session_\"",
"+",
"md5",
"(",
"str",
"(",
"time",
"(",
")",
")",
".",
"encode",
"(",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"replace\"",
")",
")... | [
290,
4
] | [
301,
25
] | python | en | ['en', 'error', 'th'] | False |
Weave.__init__ | (self, release_old: str, release_new: str, output_path: str,
set_name: Union[str, None] = None,
suppress_missing_versions: bool = False) |
Take two release files, and compare them for differences, then \
generate patch file to given output path.
Inorganic and for robots.
:param release_old: web address or path to old release file
:type release_old: str
:param release_new: web address or path to new re... |
Take two release files, and compare them for differences, then \
generate patch file to given output path. | def __init__(self, release_old: str, release_new: str, output_path: str,
set_name: Union[str, None] = None,
suppress_missing_versions: bool = False):
"""
Take two release files, and compare them for differences, then \
generate patch file to given output pat... | [
"def",
"__init__",
"(",
"self",
",",
"release_old",
":",
"str",
",",
"release_new",
":",
"str",
",",
"output_path",
":",
"str",
",",
"set_name",
":",
"Union",
"[",
"str",
",",
"None",
"]",
"=",
"None",
",",
"suppress_missing_versions",
":",
"bool",
"=",
... | [
307,
4
] | [
470,
44
] | python | en | ['en', 'error', 'th'] | False |
Weave.create_work_directory | () |
Create directory under the OS temporary directory with a unique name \
to prevent conflicting instances.
:return: generated tempdir name
:rtype: str
|
Create directory under the OS temporary directory with a unique name \
to prevent conflicting instances. | def create_work_directory() -> str:
"""
Create directory under the OS temporary directory with a unique name \
to prevent conflicting instances.
:return: generated tempdir name
:rtype: str
"""
identifier = "/bandage_weave_session_" + \
md5(str(tim... | [
"def",
"create_work_directory",
"(",
")",
"->",
"str",
":",
"identifier",
"=",
"\"/bandage_weave_session_\"",
"+",
"md5",
"(",
"str",
"(",
"time",
"(",
")",
")",
".",
"encode",
"(",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"replace\"",
")",
")",... | [
473,
4
] | [
490,
25
] | python | en | ['en', 'error', 'th'] | False |
Weave.comparison | (self) |
Compare old and new directories under self.WORK_DIR for differences, \
returns as list.
:return: contains release differences
:rtype: list
|
Compare old and new directories under self.WORK_DIR for differences, \
returns as list. | def comparison(self) -> list:
"""
Compare old and new directories under self.WORK_DIR for differences, \
returns as list.
:return: contains release differences
:rtype: list
"""
handle = StringIO()
with redirect_stdout(handle):
dircmp(gette... | [
"def",
"comparison",
"(",
"self",
")",
"->",
"list",
":",
"handle",
"=",
"StringIO",
"(",
")",
"with",
"redirect_stdout",
"(",
"handle",
")",
":",
"dircmp",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
",",
"gettempdir",
... | [
492,
4
] | [
555,
19
] | python | en | ['en', 'error', 'th'] | False |
Supply.__init__ | (self, remote: str, version_file: str) |
Check given remote HTTP endpoint for new patches. Inorganic and for \
robots. If no exception is thrown, dumps status and patch \
download URL to self.result and self.patch_web_source \
respectively, which can be retrieved as a list through \
... |
Check given remote HTTP endpoint for new patches. Inorganic and for \
robots. If no exception is thrown, dumps status and patch \
download URL to self.result and self.patch_web_source \
respectively, which can be retrieved as a list through \
... | def __init__(self, remote: str, version_file: str):
"""
Check given remote HTTP endpoint for new patches. Inorganic and for \
robots. If no exception is thrown, dumps status and patch \
download URL to self.result and self.patch_web_source \
respectively, ... | [
"def",
"__init__",
"(",
"self",
",",
"remote",
":",
"str",
",",
"version_file",
":",
"str",
")",
":",
"self",
".",
"patch_web_source",
"=",
"None",
"self",
".",
"result",
"=",
"1",
"self",
".",
"remote",
"=",
"remote",
"self",
".",
"version_file",
"=",... | [
562,
4
] | [
699,
70
] | python | en | ['en', 'error', 'th'] | False |
Supply.realize | (self) |
Return list containing self.result and self.patch_web_source.
:return: [self.result, self.patch_web_source]
:rtype: list
|
Return list containing self.result and self.patch_web_source. | def realize(self) -> list:
"""
Return list containing self.result and self.patch_web_source.
:return: [self.result, self.patch_web_source]
:rtype: list
"""
return [self.result, self.patch_web_source] | [
"def",
"realize",
"(",
"self",
")",
"->",
"list",
":",
"return",
"[",
"self",
".",
"result",
",",
"self",
".",
"patch_web_source",
"]"
] | [
701,
4
] | [
708,
51
] | python | en | ['en', 'error', 'th'] | False |
Supply.pre_collect_dump | (self) |
Return self.pre_collect_dump.
:return: pre_collect_dump
:rtype: list
|
Return self.pre_collect_dump. | def pre_collect_dump(self) -> list:
"""
Return self.pre_collect_dump.
:return: pre_collect_dump
:rtype: list
"""
return self.pre_collect | [
"def",
"pre_collect_dump",
"(",
"self",
")",
"->",
"list",
":",
"return",
"self",
".",
"pre_collect"
] | [
710,
4
] | [
717,
31
] | python | en | ['en', 'error', 'th'] | False |
render_animation | (keypoints, keypoints_metadata, poses, skeleton, fps, bitrate, azim, output, viewport,
limit=-1, downsample=1, size=6, input_video_path=None, input_video_skip=0) |
TODO
Render an animation. The supported output modes are:
-- 'interactive': display an interactive figure
(also works on notebooks if associated with %matplotlib inline)
-- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...).
-- 'fil... |
TODO
Render an animation. The supported output modes are:
-- 'interactive': display an interactive figure
(also works on notebooks if associated with %matplotlib inline)
-- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...).
-- 'fil... | def render_animation(keypoints, keypoints_metadata, poses, skeleton, fps, bitrate, azim, output, viewport,
limit=-1, downsample=1, size=6, input_video_path=None, input_video_skip=0):
"""
TODO
Render an animation. The supported output modes are:
-- 'interactive': display an interact... | [
"def",
"render_animation",
"(",
"keypoints",
",",
"keypoints_metadata",
",",
"poses",
",",
"skeleton",
",",
"fps",
",",
"bitrate",
",",
"azim",
",",
"output",
",",
"viewport",
",",
"limit",
"=",
"-",
"1",
",",
"downsample",
"=",
"1",
",",
"size",
"=",
... | [
123,
0
] | [
267,
15
] | python | en | ['en', 'error', 'th'] | False |
cat_group | (dfx, kpix, n_group=10) |
Category Reduction for Categorical Variables
Args
----
dfx : dataframe
The inputs data dataframe.
kpix : string
The column of the feature.
n_group : int, optional (default = 10)
The number of top category values to be remained, other category values will be put into ... |
Category Reduction for Categorical Variables | def cat_group(dfx, kpix, n_group=10):
'''
Category Reduction for Categorical Variables
Args
----
dfx : dataframe
The inputs data dataframe.
kpix : string
The column of the feature.
n_group : int, optional (default = 10)
The number of top category values to be rema... | [
"def",
"cat_group",
"(",
"dfx",
",",
"kpix",
",",
"n_group",
"=",
"10",
")",
":",
"if",
"dfx",
"[",
"kpix",
"]",
".",
"nunique",
"(",
")",
">",
"n_group",
":",
"# get the top categories",
"top",
"=",
"dfx",
"[",
"kpix",
"]",
".",
"isin",
"(",
"dfx"... | [
8,
0
] | [
34,
31
] | python | en | ['en', 'error', 'th'] | False |
cat_transform | (dfx, kpix, kpi1) |
Encoding string features.
Args
----
dfx : dataframe
The inputs data dataframe.
kpix : string
The column of the feature.
kpi1 : list
The list of feature names.
Returns
-------
dfx : DataFrame
The updated dataframe containing the encoded data.
... |
Encoding string features. | def cat_transform(dfx, kpix, kpi1):
'''
Encoding string features.
Args
----
dfx : dataframe
The inputs data dataframe.
kpix : string
The column of the feature.
kpi1 : list
The list of feature names.
Returns
-------
dfx : DataFrame
The updated ... | [
"def",
"cat_transform",
"(",
"dfx",
",",
"kpix",
",",
"kpi1",
")",
":",
"df_dummy",
"=",
"pd",
".",
"get_dummies",
"(",
"dfx",
"[",
"kpix",
"]",
".",
"values",
")",
"new_col_names",
"=",
"[",
"'%s_%s'",
"%",
"(",
"kpix",
",",
"x",
")",
"for",
"x",
... | [
37,
0
] | [
70,
20
] | python | en | ['en', 'error', 'th'] | False |
cv_fold_index | (n, i, k, random_seed=2018) |
Encoding string features.
Args
----
dfx : dataframe
The inputs data dataframe.
kpix : string
The column of the feature.
kpi1 : list
The list of feature names.
Returns
-------
dfx : DataFrame
The updated dataframe containing the encoded data.
... |
Encoding string features. | def cv_fold_index(n, i, k, random_seed=2018):
'''
Encoding string features.
Args
----
dfx : dataframe
The inputs data dataframe.
kpix : string
The column of the feature.
kpi1 : list
The list of feature names.
Returns
-------
dfx : DataFrame
Th... | [
"def",
"cv_fold_index",
"(",
"n",
",",
"i",
",",
"k",
",",
"random_seed",
"=",
"2018",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"rlist",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"a",
"=",
"range",
"(",
"k",
")",
... | [
73,
0
] | [
100,
23
] | python | en | ['en', 'error', 'th'] | False |
cat_continuous | (x, granularity='Medium') |
Categorize (bin) continuous variable based on percentile.
Args
----
x : list
Feature values.
granularity : string, optional, (default = 'Medium')
Control the granularity of the bins, optional values are: 'High', 'Medium', 'Low'.
Returns
-------
res : list
Lis... |
Categorize (bin) continuous variable based on percentile. | def cat_continuous(x, granularity='Medium'):
'''
Categorize (bin) continuous variable based on percentile.
Args
----
x : list
Feature values.
granularity : string, optional, (default = 'Medium')
Control the granularity of the bins, optional values are: 'High', 'Medium', 'Low'.... | [
"def",
"cat_continuous",
"(",
"x",
",",
"granularity",
"=",
"'Medium'",
")",
":",
"if",
"granularity",
"==",
"'High'",
":",
"lspercentile",
"=",
"[",
"np",
".",
"percentile",
"(",
"x",
",",
"5",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"10",... | [
104,
0
] | [
182,
14
] | python | en | ['en', 'error', 'th'] | False |
kpi_transform | (dfx, kpi_combo, kpi_combo_new) |
Feature transformation from continuous feature to binned features for a list of features
Args
----
dfx : DataFrame
DataFrame containing the features.
kpi_combo : list of string
List of feature names to be transformed
kpi_combo_new : list of string
List of new feature... |
Feature transformation from continuous feature to binned features for a list of features | def kpi_transform(dfx, kpi_combo, kpi_combo_new):
'''
Feature transformation from continuous feature to binned features for a list of features
Args
----
dfx : DataFrame
DataFrame containing the features.
kpi_combo : list of string
List of feature names to be transformed
k... | [
"def",
"kpi_transform",
"(",
"dfx",
",",
"kpi_combo",
",",
"kpi_combo_new",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"kpi_combo",
")",
")",
":",
"if",
"type",
"(",
"dfx",
"[",
"kpi_combo",
"[",
"j",
"]",
"]",
".",
"values",
"[",
"0",
... | [
185,
0
] | [
219,
14
] | python | en | ['en', 'error', 'th'] | False |
BaseDocumentStore.write_documents | (self, documents: Union[List[dict], List[Document]], index: Optional[str] = None) |
Indexes documents for later queries.
:param documents: a list of Python dictionaries or a list of Haystack Document objects.
For documents as dictionaries, the format is {"text": "<the-actual-text>"}.
Optionally: Include meta data via {"text": "<the-... |
Indexes documents for later queries. | def write_documents(self, documents: Union[List[dict], List[Document]], index: Optional[str] = None):
"""
Indexes documents for later queries.
:param documents: a list of Python dictionaries or a list of Haystack Document objects.
For documents as dictionaries, the for... | [
"def",
"write_documents",
"(",
"self",
",",
"documents",
":",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Document",
"]",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"pass"
] | [
23,
4
] | [
37,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDocumentStore.get_all_documents | (
self,
index: Optional[str] = None,
filters: Optional[Dict[str, List[str]]] = None,
return_embedding: Optional[bool] = None
) |
Get documents from the document store.
:param index: Name of the index to get the documents from. If None, the
DocumentStore's default index (self.index) will be used.
:param filters: Optional filters to narrow down the documents to return.
Example... |
Get documents from the document store. | def get_all_documents(
self,
index: Optional[str] = None,
filters: Optional[Dict[str, List[str]]] = None,
return_embedding: Optional[bool] = None
) -> List[Document]:
"""
Get documents from the document store.
:param index: Name of the index t... | [
"def",
"get_all_documents",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"return_embedding",
":",
"Option... | [
40,
4
] | [
55,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDocumentStore.add_eval_data | (self, filename: str, doc_index: str = "eval_document", label_index: str = "label",
batch_size: Optional[int] = None, preprocessor: Optional[PreProcessor] = None,
max_docs: Union[int, bool] = None) |
Adds a SQuAD-formatted file to the DocumentStore in order to be able to perform evaluation on it.
If a jsonl file and a batch_size is passed to the function, documents are loaded batchwise
from disk and also indexed batchwise to the DocumentStore in order to prevent out of memory errors.
... |
Adds a SQuAD-formatted file to the DocumentStore in order to be able to perform evaluation on it.
If a jsonl file and a batch_size is passed to the function, documents are loaded batchwise
from disk and also indexed batchwise to the DocumentStore in order to prevent out of memory errors. | def add_eval_data(self, filename: str, doc_index: str = "eval_document", label_index: str = "label",
batch_size: Optional[int] = None, preprocessor: Optional[PreProcessor] = None,
max_docs: Union[int, bool] = None):
"""
Adds a SQuAD-formatted file to the Docum... | [
"def",
"add_eval_data",
"(",
"self",
",",
"filename",
":",
"str",
",",
"doc_index",
":",
"str",
"=",
"\"eval_document\"",
",",
"label_index",
":",
"str",
"=",
"\"label\"",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"preprocessor... | [
144,
4
] | [
202,
69
] | python | en | ['en', 'error', 'th'] | False |
deepcopy | (x) | Deep copy operation on gyp objects such as strings, ints, dicts
and lists. More than twice as fast as copy.deepcopy but much less
generic. | Deep copy operation on gyp objects such as strings, ints, dicts
and lists. More than twice as fast as copy.deepcopy but much less
generic. | def deepcopy(x):
"""Deep copy operation on gyp objects such as strings, ints, dicts
and lists. More than twice as fast as copy.deepcopy but much less
generic."""
try:
return _deepcopy_dispatch[type(x)](x)
except KeyError:
raise Error('Unsupported type %s for deepcopy. Use copy.deepcopy ' +
... | [
"def",
"deepcopy",
"(",
"x",
")",
":",
"try",
":",
"return",
"_deepcopy_dispatch",
"[",
"type",
"(",
"x",
")",
"]",
"(",
"x",
")",
"except",
"KeyError",
":",
"raise",
"Error",
"(",
"'Unsupported type %s for deepcopy. Use copy.deepcopy '",
"+",
"'or expand simple... | [
14,
0
] | [
23,
59
] | python | en | ['en', 'en', 'en'] | True |
Writer.__init__ | (self, tool_file_path, name) | Initializes the tool file.
Args:
tool_file_path: Path to the tool file.
name: Name of the tool file.
| Initializes the tool file. | def __init__(self, tool_file_path, name):
"""Initializes the tool file.
Args:
tool_file_path: Path to the tool file.
name: Name of the tool file.
"""
self.tool_file_path = tool_file_path
self.name = name
self.rules_section = ['Rules'] | [
"def",
"__init__",
"(",
"self",
",",
"tool_file_path",
",",
"name",
")",
":",
"self",
".",
"tool_file_path",
"=",
"tool_file_path",
"self",
".",
"name",
"=",
"name",
"self",
".",
"rules_section",
"=",
"[",
"'Rules'",
"]"
] | [
13,
2
] | [
22,
34
] | python | en | ['en', 'en', 'en'] | True |
Writer.AddCustomBuildRule | (self, name, cmd, description,
additional_dependencies,
outputs, extensions) | Adds a rule to the tool file.
Args:
name: Name of the rule.
description: Description of the rule.
cmd: Command line of the rule.
additional_dependencies: other files which may trigger the rule.
outputs: outputs of the rule.
extensions: extensions handled by the rule.
| Adds a rule to the tool file. | def AddCustomBuildRule(self, name, cmd, description,
additional_dependencies,
outputs, extensions):
"""Adds a rule to the tool file.
Args:
name: Name of the rule.
description: Description of the rule.
cmd: Command line of the rule.
addit... | [
"def",
"AddCustomBuildRule",
"(",
"self",
",",
"name",
",",
"cmd",
",",
"description",
",",
"additional_dependencies",
",",
"outputs",
",",
"extensions",
")",
":",
"rule",
"=",
"[",
"'CustomBuildRule'",
",",
"{",
"'Name'",
":",
"name",
",",
"'ExecutionDescript... | [
24,
2
] | [
46,
35
] | python | en | ['en', 'en', 'en'] | True |
Writer.WriteIfChanged | (self) | Writes the tool file. | Writes the tool file. | def WriteIfChanged(self):
"""Writes the tool file."""
content = ['VisualStudioToolFile',
{'Version': '8.00',
'Name': self.name
},
self.rules_section
]
easy_xml.WriteXmlIfChanged(content, self.tool_file_path,
... | [
"def",
"WriteIfChanged",
"(",
"self",
")",
":",
"content",
"=",
"[",
"'VisualStudioToolFile'",
",",
"{",
"'Version'",
":",
"'8.00'",
",",
"'Name'",
":",
"self",
".",
"name",
"}",
",",
"self",
".",
"rules_section",
"]",
"easy_xml",
".",
"WriteXmlIfChanged",
... | [
48,
2
] | [
57,
55
] | python | en | ['en', 'mi', 'en'] | True |
activate_bootstrap | (driver) | Allows you to use Bootstrap Tours with SeleniumBase
http://bootstraptour.com/
| Allows you to use Bootstrap Tours with SeleniumBase
http://bootstraptour.com/
| def activate_bootstrap(driver):
""" Allows you to use Bootstrap Tours with SeleniumBase
http://bootstraptour.com/
"""
bootstrap_tour_css = constants.BootstrapTour.MIN_CSS
bootstrap_tour_js = constants.BootstrapTour.MIN_JS
verify_script = ("""// Verify Bootstrap Tour activated
... | [
"def",
"activate_bootstrap",
"(",
"driver",
")",
":",
"bootstrap_tour_css",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_CSS",
"bootstrap_tour_js",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_JS",
"verify_script",
"=",
"(",
"\"\"\"// Verify Bootstrap Tour act... | [
16,
0
] | [
44,
58
] | python | en | ['en', 'en', 'en'] | True |
activate_driverjs | (driver) | Allows you to use DriverJS Tours with SeleniumBase
https://kamranahmed.info/driver.js/
| Allows you to use DriverJS Tours with SeleniumBase
https://kamranahmed.info/driver.js/
| def activate_driverjs(driver):
""" Allows you to use DriverJS Tours with SeleniumBase
https://kamranahmed.info/driver.js/
"""
backdrop_style = style_sheet.dt_backdrop_style
driverjs_css = constants.DriverJS.MIN_CSS
driverjs_js = constants.DriverJS.MIN_JS
verify_script = ("""// Verify Dr... | [
"def",
"activate_driverjs",
"(",
"driver",
")",
":",
"backdrop_style",
"=",
"style_sheet",
".",
"dt_backdrop_style",
"driverjs_css",
"=",
"constants",
".",
"DriverJS",
".",
"MIN_CSS",
"driverjs_js",
"=",
"constants",
".",
"DriverJS",
".",
"MIN_JS",
"verify_script",
... | [
58,
0
] | [
89,
58
] | python | en | ['en', 'en', 'en'] | True |
activate_hopscotch | (driver) | Allows you to use Hopscotch Tours with SeleniumBase
http://linkedin.github.io/hopscotch/
| Allows you to use Hopscotch Tours with SeleniumBase
http://linkedin.github.io/hopscotch/
| def activate_hopscotch(driver):
""" Allows you to use Hopscotch Tours with SeleniumBase
http://linkedin.github.io/hopscotch/
"""
hopscotch_css = constants.Hopscotch.MIN_CSS
hopscotch_js = constants.Hopscotch.MIN_JS
backdrop_style = style_sheet.hops_backdrop_style
verify_script = ("""// ... | [
"def",
"activate_hopscotch",
"(",
"driver",
")",
":",
"hopscotch_css",
"=",
"constants",
".",
"Hopscotch",
".",
"MIN_CSS",
"hopscotch_js",
"=",
"constants",
".",
"Hopscotch",
".",
"MIN_JS",
"backdrop_style",
"=",
"style_sheet",
".",
"hops_backdrop_style",
"verify_sc... | [
103,
0
] | [
134,
58
] | python | en | ['en', 'en', 'en'] | True |
activate_introjs | (driver) | Allows you to use IntroJS Tours with SeleniumBase
https://introjs.com/
| Allows you to use IntroJS Tours with SeleniumBase
https://introjs.com/
| def activate_introjs(driver):
""" Allows you to use IntroJS Tours with SeleniumBase
https://introjs.com/
"""
intro_css = constants.IntroJS.MIN_CSS
intro_js = constants.IntroJS.MIN_JS
verify_script = ("""// Verify IntroJS activated
var intro2 = introJs();
... | [
"def",
"activate_introjs",
"(",
"driver",
")",
":",
"intro_css",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_CSS",
"intro_js",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_JS",
"verify_script",
"=",
"(",
"\"\"\"// Verify IntroJS activated\n var intro2... | [
148,
0
] | [
177,
58
] | python | en | ['en', 'en', 'en'] | True |
activate_shepherd | (driver) | Allows you to use Shepherd Tours with SeleniumBase
http://github.hubspot.com/shepherd/docs/welcome/
| Allows you to use Shepherd Tours with SeleniumBase
http://github.hubspot.com/shepherd/docs/welcome/
| def activate_shepherd(driver):
""" Allows you to use Shepherd Tours with SeleniumBase
http://github.hubspot.com/shepherd/docs/welcome/
"""
shepherd_js = constants.Shepherd.MIN_JS
sh_theme_arrows_css = constants.Shepherd.THEME_ARROWS_CSS
sh_theme_arrows_fix_css = constants.Shepherd.THEME_ARR_... | [
"def",
"activate_shepherd",
"(",
"driver",
")",
":",
"shepherd_js",
"=",
"constants",
".",
"Shepherd",
".",
"MIN_JS",
"sh_theme_arrows_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_ARROWS_CSS",
"sh_theme_arrows_fix_css",
"=",
"constants",
".",
"Shepherd",
"."... | [
191,
0
] | [
237,
58
] | python | en | ['en', 'el-Latn', 'en'] | True |
play_shepherd_tour | (driver, tour_steps, msg_dur, name=None, interval=0) | Plays a Shepherd tour on the current website. | Plays a Shepherd tour on the current website. | def play_shepherd_tour(driver, tour_steps, msg_dur, name=None, interval=0):
""" Plays a Shepherd tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += ("""
// Start the tour
tour.start();
$tour = to... | [
"def",
"play_shepherd_tour",
"(",
"driver",
",",
"tour_steps",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
... | [
249,
0
] | [
358,
31
] | python | en | ['en', 'en', 'en'] | True |
play_bootstrap_tour | (
driver, tour_steps, browser, msg_dur, name=None, interval=0) | Plays a Bootstrap tour on the current website. | Plays a Bootstrap tour on the current website. | def play_bootstrap_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays a Bootstrap tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]);
// Initialize the tour
... | [
"def",
"play_bootstrap_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"in... | [
361,
0
] | [
443,
31
] | python | en | ['en', 'en', 'en'] | True |
play_driverjs_tour | (
driver, tour_steps, browser, msg_dur, name=None, interval=0) | Plays a DriverJS tour on the current website. | Plays a DriverJS tour on the current website. | def play_driverjs_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays a DriverJS tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]
);
// Start the tour!
... | [
"def",
"play_driverjs_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"ins... | [
446,
0
] | [
555,
31
] | python | en | ['en', 'en', 'en'] | True |
play_hopscotch_tour | (
driver, tour_steps, browser, msg_dur, name=None, interval=0) | Plays a Hopscotch tour on the current website. | Plays a Hopscotch tour on the current website. | def play_hopscotch_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays a Hopscotch tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]
};
// Start the tour... | [
"def",
"play_hopscotch_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"in... | [
558,
0
] | [
663,
31
] | python | en | ['en', 'en', 'en'] | True |
play_introjs_tour | (
driver, tour_steps, browser, msg_dur, name=None, interval=0) | Plays an IntroJS tour on the current website. | Plays an IntroJS tour on the current website. | def play_introjs_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays an IntroJS tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]
});
intro.setOption("di... | [
"def",
"play_introjs_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"inst... | [
666,
0
] | [
784,
31
] | python | en | ['en', 'en', 'en'] | True |
export_tour | (tour_steps, name=None, filename="my_tour.js", url=None) | Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. | Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. | def export_tour(tour_steps, name=None, filename="my_tour.js", url=None):
""" Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. "... | [
"def",
"export_tour",
"(",
"tour_steps",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"\"my_tour.js\"",
",",
"url",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"\"default\"",
"if",
"name",
"not",
"in",
"tour_steps",
":",
"raise",
"... | [
787,
0
] | [
1007,
48
] | python | en | ['en', 'su', 'en'] | True |
test_expectation_configuration_equality | (config1, config2, config3, config4) | Equality should depend on all defined properties of a configuration object, but not on whether the *instances*
are the same. | Equality should depend on all defined properties of a configuration object, but not on whether the *instances*
are the same. | def test_expectation_configuration_equality(config1, config2, config3, config4):
"""Equality should depend on all defined properties of a configuration object, but not on whether the *instances*
are the same."""
assert config1 is config1 # no difference
assert config1 is not config2 # different instan... | [
"def",
"test_expectation_configuration_equality",
"(",
"config1",
",",
"config2",
",",
"config3",
",",
"config4",
")",
":",
"assert",
"config1",
"is",
"config1",
"# no difference",
"assert",
"config1",
"is",
"not",
"config2",
"# different instances, but same content",
"... | [
79,
0
] | [
88,
29
] | python | en | ['en', 'en', 'en'] | True |
test_expectation_configuration_equivalence | (
config1, config2, config3, config4, config5
) | Equivalence should depend only on properties that affect the result of the expectation. | Equivalence should depend only on properties that affect the result of the expectation. | def test_expectation_configuration_equivalence(
config1, config2, config3, config4, config5
):
"""Equivalence should depend only on properties that affect the result of the expectation."""
assert config1.isEquivalentTo(config2, match_type="runtime") # no difference
assert config2.isEquivalentTo(config1... | [
"def",
"test_expectation_configuration_equivalence",
"(",
"config1",
",",
"config2",
",",
"config3",
",",
"config4",
",",
"config5",
")",
":",
"assert",
"config1",
".",
"isEquivalentTo",
"(",
"config2",
",",
"match_type",
"=",
"\"runtime\"",
")",
"# no difference",
... | [
91,
0
] | [
106,
5
] | python | en | ['en', 'en', 'en'] | True |
format_ratio | (ratio) | Converts a ratio to a readable percentage gain. | Converts a ratio to a readable percentage gain. | def format_ratio(ratio):
"""Converts a ratio to a readable percentage gain."""
return '%.3f%%' % (100 * (ratio - 1)) | [
"def",
"format_ratio",
"(",
"ratio",
")",
":",
"return",
"'%.3f%%'",
"%",
"(",
"100",
"*",
"(",
"ratio",
"-",
"1",
")",
")"
] | [
14,
0
] | [
17,
41
] | python | en | ['en', 'en', 'en'] | True |
format_dollar | (amount) | Converts a dollar amount into a readable string. | Converts a dollar amount into a readable string. | def format_dollar(amount):
"""Converts a dollar amount into a readable string."""
return '${:,.2f}'.format(amount) | [
"def",
"format_dollar",
"(",
"amount",
")",
":",
"return",
"'${:,.2f}'",
".",
"format",
"(",
"amount",
")"
] | [
20,
0
] | [
23,
36
] | python | en | ['en', 'en', 'en'] | True |
format_timestamp | (timestamp, weekday=False) | Converts a timestamp into a readable string. | Converts a timestamp into a readable string. | def format_timestamp(timestamp, weekday=False):
"""Converts a timestamp into a readable string."""
date_format = '%-m/%-d/%Y %-I:%M %p'
if weekday:
date_format += ' (%A)'
return timestamp.strftime(date_format) | [
"def",
"format_timestamp",
"(",
"timestamp",
",",
"weekday",
"=",
"False",
")",
":",
"date_format",
"=",
"'%-m/%-d/%Y %-I:%M %p'",
"if",
"weekday",
":",
"date_format",
"+=",
"' (%A)'",
"return",
"timestamp",
".",
"strftime",
"(",
"date_format",
")"
] | [
26,
0
] | [
32,
42
] | python | en | ['en', 'en', 'en'] | True |
get_ratio | (strategy) | Calculates the profit ratio of a strategy. | Calculates the profit ratio of a strategy. | def get_ratio(strategy):
"""Calculates the profit ratio of a strategy."""
price_at = strategy['price_at']
price_eod = strategy['price_eod']
if price_at and price_eod:
action = strategy['action']
if action == 'bull':
return price_eod / price_at
elif action == 'bear':
... | [
"def",
"get_ratio",
"(",
"strategy",
")",
":",
"price_at",
"=",
"strategy",
"[",
"'price_at'",
"]",
"price_eod",
"=",
"strategy",
"[",
"'price_eod'",
"]",
"if",
"price_at",
"and",
"price_eod",
":",
"action",
"=",
"strategy",
"[",
"'action'",
"]",
"if",
"ac... | [
35,
0
] | [
49,
18
] | python | en | ['en', 'en', 'en'] | True |
get_sentiment_emoji | (sentiment) | Returns an emoji representing the sentiment score. | Returns an emoji representing the sentiment score. | def get_sentiment_emoji(sentiment):
"""Returns an emoji representing the sentiment score."""
if sentiment == 0:
return ':neutral_face:'
elif sentiment > 0:
return ':thumbsup:'
else: # sentiment < 0:
return ':thumbsdown:' | [
"def",
"get_sentiment_emoji",
"(",
"sentiment",
")",
":",
"if",
"sentiment",
"==",
"0",
":",
"return",
"':neutral_face:'",
"elif",
"sentiment",
">",
"0",
":",
"return",
"':thumbsup:'",
"else",
":",
"# sentiment < 0:",
"return",
"':thumbsdown:'"
] | [
52,
0
] | [
60,
29
] | python | en | ['en', 'co', 'en'] | True |
get_market_status | (timestamp) | Tries to infer the market status from a timestamp. | Tries to infer the market status from a timestamp. | def get_market_status(timestamp):
"""Tries to infer the market status from a timestamp."""
if not trading.is_trading_day(timestamp):
return 'closed'
# Calculate the market hours for the given day. These are the same for NYSE
# and NASDAQ and include TradeKing's extended hours.
pre_time = t... | [
"def",
"get_market_status",
"(",
"timestamp",
")",
":",
"if",
"not",
"trading",
".",
"is_trading_day",
"(",
"timestamp",
")",
":",
"return",
"'closed'",
"# Calculate the market hours for the given day. These are the same for NYSE",
"# and NASDAQ and include TradeKing's extended h... | [
63,
0
] | [
84,
23
] | python | en | ['en', 'en', 'en'] | True |
should_trade | (strategy, date, previous_trade_date) | Determines whether a trade is happening for the strategy. | Determines whether a trade is happening for the strategy. | def should_trade(strategy, date, previous_trade_date):
"""Determines whether a trade is happening for the strategy."""
# We invest the whole value, so we can only trade once a day.
if (previous_trade_date and
previous_trade_date.replace(hour=0, minute=0, second=0) ==
date.replace(hour=0... | [
"def",
"should_trade",
"(",
"strategy",
",",
"date",
",",
"previous_trade_date",
")",
":",
"# We invest the whole value, so we can only trade once a day.",
"if",
"(",
"previous_trade_date",
"and",
"previous_trade_date",
".",
"replace",
"(",
"hour",
"=",
"0",
",",
"minut... | [
88,
0
] | [
105,
15
] | python | en | ['en', 'en', 'en'] | True |
main | () | Run administrative tasks. | Run administrative tasks. | def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangobackend.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's ins... | [
"def",
"main",
"(",
")",
":",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'DJANGO_SETTINGS_MODULE'",
",",
"'djangobackend.settings'",
")",
"try",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"execute_from_command_line",
"except",
"ImportErro... | [
6,
0
] | [
17,
39
] | python | en | ['lv', 'gd', 'en'] | False |
extract_version | (txt) | This function tries to extract the version from the help text of any
program. | This function tries to extract the version from the help text of any
program. | def extract_version(txt):
"""This function tries to extract the version from the help text of any
program."""
words = txt.replace(',', ' ').split()
version = None
for x in reversed(words):
if len(x) > 2:
if x[0].lower() == 'v':
x = x[1:]
if '.' in x an... | [
"def",
"extract_version",
"(",
"txt",
")",
":",
"words",
"=",
"txt",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"version",
"=",
"None",
"for",
"x",
"in",
"reversed",
"(",
"words",
")",
":",
"if",
"len",
"(",
"x",
")",
... | [
415,
0
] | [
427,
18
] | python | en | ['en', 'en', 'en'] | True |
EasyProcess.pid | (self) |
PID (:attr:`subprocess.Popen.pid`)
:rtype: int
|
PID (:attr:`subprocess.Popen.pid`) | def pid(self):
'''
PID (:attr:`subprocess.Popen.pid`)
:rtype: int
'''
if self.popen:
return self.popen.pid | [
"def",
"pid",
"(",
"self",
")",
":",
"if",
"self",
".",
"popen",
":",
"return",
"self",
".",
"popen",
".",
"pid"
] | [
130,
4
] | [
137,
33
] | python | en | ['en', 'error', 'th'] | False |
EasyProcess.return_code | (self) |
returncode (:attr:`subprocess.Popen.returncode`)
:rtype: int
|
returncode (:attr:`subprocess.Popen.returncode`) | def return_code(self):
'''
returncode (:attr:`subprocess.Popen.returncode`)
:rtype: int
'''
if self.popen:
return self.popen.returncode | [
"def",
"return_code",
"(",
"self",
")",
":",
"if",
"self",
".",
"popen",
":",
"return",
"self",
".",
"popen",
".",
"returncode"
] | [
140,
4
] | [
147,
40
] | python | en | ['en', 'error', 'th'] | False |
EasyProcess.check | (self, return_code=0) | Run command with arguments. Wait for command to complete. If the
exit code was as expected and there is no exception then return,
otherwise raise EasyProcessError.
:param return_code: int, expected return code
:rtype: self
| Run command with arguments. Wait for command to complete. If the
exit code was as expected and there is no exception then return,
otherwise raise EasyProcessError. | def check(self, return_code=0):
"""Run command with arguments. Wait for command to complete. If the
exit code was as expected and there is no exception then return,
otherwise raise EasyProcessError.
:param return_code: int, expected return code
:rtype: self
"""
... | [
"def",
"check",
"(",
"self",
",",
"return_code",
"=",
"0",
")",
":",
"ret",
"=",
"self",
".",
"call",
"(",
")",
".",
"return_code",
"ok",
"=",
"ret",
"==",
"return_code",
"if",
"not",
"ok",
":",
"raise",
"EasyProcessError",
"(",
"self",
",",
"'check ... | [
149,
4
] | [
164,
19
] | python | en | ['en', 'en', 'en'] | True |
EasyProcess.check_installed | (self) | Used for testing if program is installed.
Run command with arguments. Wait for command to complete.
If OSError raised, then raise :class:`EasyProcessCheckInstalledError`
with information about program installation
:param return_code: int, expected return code
:rtype: self
... | Used for testing if program is installed. | def check_installed(self):
"""Used for testing if program is installed.
Run command with arguments. Wait for command to complete.
If OSError raised, then raise :class:`EasyProcessCheckInstalledError`
with information about program installation
:param return_code: int, expected ... | [
"def",
"check_installed",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"call",
"(",
")",
"except",
"Exception",
":",
"raise",
"EasyProcessCheckInstalledError",
"(",
"self",
")",
"return",
"self"
] | [
166,
4
] | [
181,
19
] | python | en | ['en', 'en', 'en'] | True |
EasyProcess.call | (self, timeout=None) | Run command with arguments. Wait for command to complete.
same as:
1. :meth:`start`
2. :meth:`wait`
3. :meth:`stop`
:rtype: self
| Run command with arguments. Wait for command to complete. | def call(self, timeout=None):
"""Run command with arguments. Wait for command to complete.
same as:
1. :meth:`start`
2. :meth:`wait`
3. :meth:`stop`
:rtype: self
"""
self.start().wait(timeout=timeout)
if self.is_alive():
self.stop... | [
"def",
"call",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"start",
"(",
")",
".",
"wait",
"(",
"timeout",
"=",
"timeout",
")",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"stop",
"(",
")",
"return",
"self"
] | [
183,
4
] | [
197,
19
] | python | en | ['en', 'en', 'en'] | True |
EasyProcess.start | (self) | start command in background and does not wait for it.
:rtype: self
| start command in background and does not wait for it. | def start(self):
"""start command in background and does not wait for it.
:rtype: self
"""
if self.is_started:
raise EasyProcessError(self, 'process was started twice!')
if self.use_temp_files:
self._stdout_file = tempfile.TemporaryFile(prefix='stdout_'... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_started",
":",
"raise",
"EasyProcessError",
"(",
"self",
",",
"'process was started twice!'",
")",
"if",
"self",
".",
"use_temp_files",
":",
"self",
".",
"_stdout_file",
"=",
"tempfile",
".",
"Tem... | [
199,
4
] | [
233,
19
] | 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.