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
sequence | start_point
sequence | end_point
sequence | 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",
",",
"minute",
",",
"second",
")",
"return",
"MARKET_TIMEZONE",
".",
"localize",
"(",
"market_time",
")"
] | [
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=TRADEKING_ACCESS_TOKEN_SECRET)
client = Client(consumer, token)
body_bytes = body.encode('utf-8')
self.logs.debug('TradeKing request: %s %s %s %s' %
(url, method, body_bytes, headers))
response, content = client.request(url, method=method,
body=body_bytes,
headers=headers)
self.logs.debug('TradeKing response: %s %s' % (response, content))
try:
return loads(content)
except ValueError:
self.logs.error('Failed to decode JSON response: %s' % content)
return None | [
"def",
"make_request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"body",
"=",
"''",
",",
"headers",
"=",
"None",
")",
":",
"consumer",
"=",
"Consumer",
"(",
"key",
"=",
"TRADEKING_CONSUMER_KEY",
",",
"secret",
"=",
"TRADEKING_CONSUMER_SECRET",
")",
"token",
"=",
"Token",
"(",
"key",
"=",
"TRADEKING_ACCESS_TOKEN",
",",
"secret",
"=",
"TRADEKING_ACCESS_TOKEN_SECRET",
")",
"client",
"=",
"Client",
"(",
"consumer",
",",
"token",
")",
"body_bytes",
"=",
"body",
".",
"encode",
"(",
"'utf-8'",
")",
"self",
".",
"logs",
".",
"debug",
"(",
"'TradeKing request: %s %s %s %s'",
"%",
"(",
"url",
",",
"method",
",",
"body_bytes",
",",
"headers",
")",
")",
"response",
",",
"content",
"=",
"client",
".",
"request",
"(",
"url",
",",
"method",
"=",
"method",
",",
"body",
"=",
"body_bytes",
",",
"headers",
"=",
"headers",
")",
"self",
".",
"logs",
".",
"debug",
"(",
"'TradeKing response: %s %s'",
"%",
"(",
"response",
",",
"content",
")",
")",
"try",
":",
"return",
"loads",
"(",
"content",
")",
"except",
"ValueError",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Failed to decode JSON response: %s'",
"%",
"content",
")",
"return",
"None"
] | [
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
order.set('Side', '1') # Buy
order.set('Px', '%.2f' % limit) # Limit price
order.set('Acct', TRADEKING_ACCOUNT_NUMBER)
instrmt = SubElement(order, 'Instrmt')
instrmt.set('SecTyp', 'CS') # Common stock
instrmt.set('Sym', ticker)
ord_qty = SubElement(order, 'OrdQty')
ord_qty.set('Qty', str(quantity))
return self.xml_tostring(fixml) | [
"def",
"fixml_buy_now",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
"'Order'",
")",
"order",
".",
"set",
"(",
"'TmInForce'",
",",
"'0'",
")",
"# Day order",
"order",
".",
"set",
"(",
"'Typ'",
",",
"'2'",
")",
"# Limit",
"order",
".",
"set",
"(",
"'Side'",
",",
"'1'",
")",
"# Buy",
"order",
".",
"set",
"(",
"'Px'",
",",
"'%.2f'",
"%",
"limit",
")",
"# Limit price",
"order",
".",
"set",
"(",
"'Acct'",
",",
"TRADEKING_ACCOUNT_NUMBER",
")",
"instrmt",
"=",
"SubElement",
"(",
"order",
",",
"'Instrmt'",
")",
"instrmt",
".",
"set",
"(",
"'SecTyp'",
",",
"'CS'",
")",
"# Common stock",
"instrmt",
".",
"set",
"(",
"'Sym'",
",",
"ticker",
")",
"ord_qty",
"=",
"SubElement",
"(",
"order",
",",
"'OrdQty'",
")",
"ord_qty",
".",
"set",
"(",
"'Qty'",
",",
"str",
"(",
"quantity",
")",
")",
"return",
"self",
".",
"xml_tostring",
"(",
"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
order.set('Side', '2') # Sell
order.set('Px', '%.2f' % limit) # Limit price
order.set('Acct', TRADEKING_ACCOUNT_NUMBER)
instrmt = SubElement(order, 'Instrmt')
instrmt.set('SecTyp', 'CS') # Common stock
instrmt.set('Sym', ticker)
ord_qty = SubElement(order, 'OrdQty')
ord_qty.set('Qty', str(quantity))
return self.xml_tostring(fixml) | [
"def",
"fixml_sell_eod",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
"'Order'",
")",
"order",
".",
"set",
"(",
"'TmInForce'",
",",
"'7'",
")",
"# Market on close",
"order",
".",
"set",
"(",
"'Typ'",
",",
"'2'",
")",
"# Limit",
"order",
".",
"set",
"(",
"'Side'",
",",
"'2'",
")",
"# Sell",
"order",
".",
"set",
"(",
"'Px'",
",",
"'%.2f'",
"%",
"limit",
")",
"# Limit price",
"order",
".",
"set",
"(",
"'Acct'",
",",
"TRADEKING_ACCOUNT_NUMBER",
")",
"instrmt",
"=",
"SubElement",
"(",
"order",
",",
"'Instrmt'",
")",
"instrmt",
".",
"set",
"(",
"'SecTyp'",
",",
"'CS'",
")",
"# Common stock",
"instrmt",
".",
"set",
"(",
"'Sym'",
",",
"ticker",
")",
"ord_qty",
"=",
"SubElement",
"(",
"order",
",",
"'OrdQty'",
")",
"ord_qty",
".",
"set",
"(",
"'Qty'",
",",
"str",
"(",
"quantity",
")",
")",
"return",
"self",
".",
"xml_tostring",
"(",
"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
order.set('Side', '5') # Sell short
order.set('Px', '%.2f' % limit) # Limit price
order.set('Acct', TRADEKING_ACCOUNT_NUMBER)
instrmt = SubElement(order, 'Instrmt')
instrmt.set('SecTyp', 'CS') # Common stock
instrmt.set('Sym', ticker)
ord_qty = SubElement(order, 'OrdQty')
ord_qty.set('Qty', str(quantity))
return self.xml_tostring(fixml) | [
"def",
"fixml_short_now",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
"'Order'",
")",
"order",
".",
"set",
"(",
"'TmInForce'",
",",
"'0'",
")",
"# Day order",
"order",
".",
"set",
"(",
"'Typ'",
",",
"'2'",
")",
"# Limit",
"order",
".",
"set",
"(",
"'Side'",
",",
"'5'",
")",
"# Sell short",
"order",
".",
"set",
"(",
"'Px'",
",",
"'%.2f'",
"%",
"limit",
")",
"# Limit price",
"order",
".",
"set",
"(",
"'Acct'",
",",
"TRADEKING_ACCOUNT_NUMBER",
")",
"instrmt",
"=",
"SubElement",
"(",
"order",
",",
"'Instrmt'",
")",
"instrmt",
".",
"set",
"(",
"'SecTyp'",
",",
"'CS'",
")",
"# Common stock",
"instrmt",
".",
"set",
"(",
"'Sym'",
",",
"ticker",
")",
"ord_qty",
"=",
"SubElement",
"(",
"order",
",",
"'OrdQty'",
")",
"ord_qty",
".",
"set",
"(",
"'Qty'",
",",
"str",
"(",
"quantity",
")",
")",
"return",
"self",
".",
"xml_tostring",
"(",
"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') # Limit
order.set('Side', '1') # Buy
order.set('Px', '%.2f' % limit) # Limit price
order.set('AcctTyp', '5') # Cover
order.set('Acct', TRADEKING_ACCOUNT_NUMBER)
instrmt = SubElement(order, 'Instrmt')
instrmt.set('SecTyp', 'CS') # Common stock
instrmt.set('Sym', ticker)
ord_qty = SubElement(order, 'OrdQty')
ord_qty.set('Qty', str(quantity))
return self.xml_tostring(fixml) | [
"def",
"fixml_cover_eod",
"(",
"self",
",",
"ticker",
",",
"quantity",
",",
"limit",
")",
":",
"fixml",
"=",
"Element",
"(",
"'FIXML'",
")",
"fixml",
".",
"set",
"(",
"'xmlns'",
",",
"FIXML_NAMESPACE",
")",
"order",
"=",
"SubElement",
"(",
"fixml",
",",
"'Order'",
")",
"order",
".",
"set",
"(",
"'TmInForce'",
",",
"'7'",
")",
"# Market on close",
"order",
".",
"set",
"(",
"'Typ'",
",",
"'2'",
")",
"# Limit",
"order",
".",
"set",
"(",
"'Side'",
",",
"'1'",
")",
"# Buy",
"order",
".",
"set",
"(",
"'Px'",
",",
"'%.2f'",
"%",
"limit",
")",
"# Limit price",
"order",
".",
"set",
"(",
"'AcctTyp'",
",",
"'5'",
")",
"# Cover",
"order",
".",
"set",
"(",
"'Acct'",
",",
"TRADEKING_ACCOUNT_NUMBER",
")",
"instrmt",
"=",
"SubElement",
"(",
"order",
",",
"'Instrmt'",
")",
"instrmt",
".",
"set",
"(",
"'SecTyp'",
",",
"'CS'",
")",
"# Common stock",
"instrmt",
".",
"set",
"(",
"'Sym'",
",",
"ticker",
")",
"ord_qty",
"=",
"SubElement",
"(",
"order",
",",
"'OrdQty'",
")",
"ord_qty",
".",
"set",
"(",
"'Qty'",
",",
"str",
"(",
"quantity",
")",
")",
"return",
"self",
".",
"xml_tostring",
"(",
"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 response.')
return 0
try:
balances = response['response']
money = balances['accountbalance']['money']
cash_str = money['cash']
uncleareddeposits_str = money['uncleareddeposits']
except KeyError:
self.logs.error('Malformed balances response: %s' % response)
return 0
try:
cash = float(cash_str)
uncleareddeposits = float(uncleareddeposits_str)
return cash - uncleareddeposits
except ValueError:
self.logs.error('Malformed number in response: %s' % money)
return 0 | [
"def",
"get_balance",
"(",
"self",
")",
":",
"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 response.'",
")",
"return",
"0",
"try",
":",
"balances",
"=",
"response",
"[",
"'response'",
"]",
"money",
"=",
"balances",
"[",
"'accountbalance'",
"]",
"[",
"'money'",
"]",
"cash_str",
"=",
"money",
"[",
"'cash'",
"]",
"uncleareddeposits_str",
"=",
"money",
"[",
"'uncleareddeposits'",
"]",
"except",
"KeyError",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Malformed balances response: %s'",
"%",
"response",
")",
"return",
"0",
"try",
":",
"cash",
"=",
"float",
"(",
"cash_str",
")",
"uncleareddeposits",
"=",
"float",
"(",
"uncleareddeposits_str",
")",
"return",
"cash",
"-",
"uncleareddeposits",
"except",
"ValueError",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Malformed number in response: %s'",
"%",
"money",
")",
"return",
"0"
] | [
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_url)
if not response:
self.logs.error('No quotes response for %s: %s' %
(ticker, response))
return None
try:
quotes = response['response']
quote = quotes['quotes']['quote']
last_str = quote['last']
except KeyError:
self.logs.error('Malformed quotes response: %s' % response)
return None
self.logs.debug('Quote for %s: %s' % (ticker, quote))
try:
last = float(last_str)
except ValueError:
self.logs.error('Malformed last for %s: %s' % (ticker, last_str))
return None
if last > 0:
return last
else:
self.logs.error('Bad quote for: %s' % ticker)
return None | [
"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",
".",
"make_request",
"(",
"url",
"=",
"quotes_url",
")",
"if",
"not",
"response",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'No quotes response for %s: %s'",
"%",
"(",
"ticker",
",",
"response",
")",
")",
"return",
"None",
"try",
":",
"quotes",
"=",
"response",
"[",
"'response'",
"]",
"quote",
"=",
"quotes",
"[",
"'quotes'",
"]",
"[",
"'quote'",
"]",
"last_str",
"=",
"quote",
"[",
"'last'",
"]",
"except",
"KeyError",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Malformed quotes response: %s'",
"%",
"response",
")",
"return",
"None",
"self",
".",
"logs",
".",
"debug",
"(",
"'Quote for %s: %s'",
"%",
"(",
"ticker",
",",
"quote",
")",
")",
"try",
":",
"last",
"=",
"float",
"(",
"last_str",
")",
"except",
"ValueError",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Malformed last for %s: %s'",
"%",
"(",
"ticker",
",",
"last_str",
")",
")",
"return",
"None",
"if",
"last",
">",
"0",
":",
"return",
"last",
"else",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Bad quote for: %s'",
"%",
"ticker",
")",
"return",
"None"
] | [
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:
self.logs.error('Failed to determine price for: %s' % ticker)
return (None, None)
# Use maximum possible quantity within the budget.
quantity = int(budget // price)
self.logs.debug('Determined quantity %s for %s at $%s within $%s.' %
(quantity, ticker, price, budget))
return (quantity, price) | [
"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",
".",
"error",
"(",
"'Failed to determine price for: %s'",
"%",
"ticker",
")",
"return",
"(",
"None",
",",
"None",
")",
"# Use maximum possible quantity within the budget.",
"quantity",
"=",
"int",
"(",
"budget",
"//",
"price",
")",
"self",
".",
"logs",
".",
"debug",
"(",
"'Determined quantity %s for %s at $%s within $%s.'",
"%",
"(",
"quantity",
",",
"ticker",
",",
"price",
",",
"budget",
")",
")",
"return",
"(",
"quantity",
",",
"price",
")"
] | [
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 quantity:
self.logs.warn('Not trading without quantity.')
return False
# Buy the stock now.
buy_limit = self.get_buy_limit(price)
buy_fixml = self.fixml_buy_now(ticker, quantity, buy_limit)
if not self.make_order_request(buy_fixml):
return False
# Sell the stock at close.
sell_limit = self.get_sell_limit(price)
sell_fixml = self.fixml_sell_eod(ticker, quantity, sell_limit)
# TODO: Do this properly by checking the order status API and using
# retries with exponential backoff.
# Wait until the previous order has been executed.
Timer(ORDER_DELAY_S, self.make_order_request, [sell_fixml]).start()
return True | [
"def",
"bull",
"(",
"self",
",",
"ticker",
",",
"budget",
")",
":",
"# Calculate the quantity.",
"quantity",
",",
"price",
"=",
"self",
".",
"get_quantity",
"(",
"ticker",
",",
"budget",
")",
"if",
"not",
"quantity",
":",
"self",
".",
"logs",
".",
"warn",
"(",
"'Not trading without quantity.'",
")",
"return",
"False",
"# Buy the stock now.",
"buy_limit",
"=",
"self",
".",
"get_buy_limit",
"(",
"price",
")",
"buy_fixml",
"=",
"self",
".",
"fixml_buy_now",
"(",
"ticker",
",",
"quantity",
",",
"buy_limit",
")",
"if",
"not",
"self",
".",
"make_order_request",
"(",
"buy_fixml",
")",
":",
"return",
"False",
"# Sell the stock at close.",
"sell_limit",
"=",
"self",
".",
"get_sell_limit",
"(",
"price",
")",
"sell_fixml",
"=",
"self",
".",
"fixml_sell_eod",
"(",
"ticker",
",",
"quantity",
",",
"sell_limit",
")",
"# TODO: Do this properly by checking the order status API and using",
"# retries with exponential backoff.",
"# Wait until the previous order has been executed.",
"Timer",
"(",
"ORDER_DELAY_S",
",",
"self",
".",
"make_order_request",
",",
"[",
"sell_fixml",
"]",
")",
".",
"start",
"(",
")",
"return",
"True"
] | [
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)
if not quantity:
self.logs.warn('Not trading without quantity.')
return False
# Short the stock now.
short_limit = self.get_sell_limit(price)
short_fixml = self.fixml_short_now(ticker, quantity, short_limit)
if not self.make_order_request(short_fixml):
return False
# Cover the short at close.
cover_limit = self.get_buy_limit(price)
cover_fixml = self.fixml_cover_eod(ticker, quantity, cover_limit)
# TODO: Do this properly by checking the order status API and using
# retries with exponential backoff.
# Wait until the previous order has been executed.
Timer(ORDER_DELAY_S, self.make_order_request, [cover_fixml]).start()
return True | [
"def",
"bear",
"(",
"self",
",",
"ticker",
",",
"budget",
")",
":",
"# Calculate the quantity.",
"quantity",
",",
"price",
"=",
"self",
".",
"get_quantity",
"(",
"ticker",
",",
"budget",
")",
"if",
"not",
"quantity",
":",
"self",
".",
"logs",
".",
"warn",
"(",
"'Not trading without quantity.'",
")",
"return",
"False",
"# Short the stock now.",
"short_limit",
"=",
"self",
".",
"get_sell_limit",
"(",
"price",
")",
"short_fixml",
"=",
"self",
".",
"fixml_short_now",
"(",
"ticker",
",",
"quantity",
",",
"short_limit",
")",
"if",
"not",
"self",
".",
"make_order_request",
"(",
"short_fixml",
")",
":",
"return",
"False",
"# Cover the short at close.",
"cover_limit",
"=",
"self",
".",
"get_buy_limit",
"(",
"price",
")",
"cover_fixml",
"=",
"self",
".",
"fixml_cover_eod",
"(",
"ticker",
",",
"quantity",
",",
"cover_limit",
")",
"# TODO: Do this properly by checking the order status API and using",
"# retries with exponential backoff.",
"# Wait until the previous order has been executed.",
"Timer",
"(",
"ORDER_DELAY_S",
",",
"self",
".",
"make_order_request",
",",
"[",
"cover_fixml",
"]",
")",
".",
"start",
"(",
")",
"return",
"True"
] | [
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('No order response for: %s' % fixml)
return False
try:
order_response = response['response']
error = order_response['error']
except KeyError:
self.logs.error('Malformed order response: %s' % response)
return False
# The error field indicates whether the order succeeded.
error = order_response['error']
if error != 'Success':
self.logs.error('Error in order response: %s %s' %
(error, order_response))
return False
return True | [
"def",
"make_order_request",
"(",
"self",
",",
"fixml",
")",
":",
"response",
"=",
"self",
".",
"make_request",
"(",
"url",
"=",
"self",
".",
"get_order_url",
"(",
")",
",",
"method",
"=",
"'POST'",
",",
"body",
"=",
"fixml",
",",
"headers",
"=",
"FIXML_HEADERS",
")",
"if",
"not",
"response",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'No order response for: %s'",
"%",
"fixml",
")",
"return",
"False",
"try",
":",
"order_response",
"=",
"response",
"[",
"'response'",
"]",
"error",
"=",
"order_response",
"[",
"'error'",
"]",
"except",
"KeyError",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Malformed order response: %s'",
"%",
"response",
")",
"return",
"False",
"# The error field indicates whether the order succeeded.",
"error",
"=",
"order_response",
"[",
"'error'",
"]",
"if",
"error",
"!=",
"'Success'",
":",
"self",
".",
"logs",
".",
"error",
"(",
"'Error in order response: %s %s'",
"%",
"(",
"error",
",",
"order_response",
")",
")",
"return",
"False",
"return",
"True"
] | [
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_field: Name of field containing an embedding vector (Only needed when using a dense retriever (e.g. DensePassageRetriever, EmbeddingRetriever) on top)
:param embedding_dim: The size of the embedding vector.
:param return_embedding: To return document embedding
:param similarity: The similarity function used to compare document vectors. 'dot_product' is the default sine it is
more performant with DPR embeddings. 'cosine' is recommended if you are using a Sentence BERT model.
:param progress_bar: Whether to show a tqdm progress bar or not.
Can be helpful to disable in production deployments to keep the logs clean.
|
: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_field: Name of field containing an embedding vector (Only needed when using a dense retriever (e.g. DensePassageRetriever, EmbeddingRetriever) on top)
:param embedding_dim: The size of the embedding vector.
:param return_embedding: To return document embedding
:param similarity: The similarity function used to compare document vectors. 'dot_product' is the default sine it is
more performant with DPR embeddings. 'cosine' is recommended if you are using a Sentence BERT model.
:param progress_bar: Whether to show a tqdm progress bar or not.
Can be helpful to disable in production deployments to keep the logs clean.
| 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,
):
"""
: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_field: Name of field containing an embedding vector (Only needed when using a dense retriever (e.g. DensePassageRetriever, EmbeddingRetriever) on top)
:param embedding_dim: The size of the embedding vector.
:param return_embedding: To return document embedding
:param similarity: The similarity function used to compare document vectors. 'dot_product' is the default sine it is
more performant with DPR embeddings. 'cosine' is recommended if you are using a Sentence BERT model.
:param progress_bar: Whether to show a tqdm progress bar or not.
Can be helpful to disable in production deployments to keep the logs clean.
"""
self.indexes: Dict[str, Dict] = defaultdict(dict)
self.index: str = index
self.label_index: str = label_index
self.embedding_field = embedding_field
self.embedding_dim = embedding_dim
self.return_embedding = return_embedding
self.similarity = similarity
self.progress_bar = progress_bar | [
"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",
",",
")",
":",
"self",
".",
"indexes",
":",
"Dict",
"[",
"str",
",",
"Dict",
"]",
"=",
"defaultdict",
"(",
"dict",
")",
"self",
".",
"index",
":",
"str",
"=",
"index",
"self",
".",
"label_index",
":",
"str",
"=",
"label_index",
"self",
".",
"embedding_field",
"=",
"embedding_field",
"self",
".",
"embedding_dim",
"=",
"embedding_dim",
"self",
".",
"return_embedding",
"=",
"return_embedding",
"self",
".",
"similarity",
"=",
"similarity",
"self",
".",
"progress_bar",
"=",
"progress_bar"
] | [
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-actual-text>",
"meta": {"name": "<some-document-name>, "author": "somebody", ...}}
It can be used for filtering and is accessible in the responses of the Finder.
:param index: write documents to a custom namespace. For instance, documents for evaluation can be indexed in a
separate index than the documents for search.
:return: None
|
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 format is {"text": "<the-actual-text>"}.
Optionally: Include meta data via {"text": "<the-actual-text>",
"meta": {"name": "<some-document-name>, "author": "somebody", ...}}
It can be used for filtering and is accessible in the responses of the Finder.
:param index: write documents to a custom namespace. For instance, documents for evaluation can be indexed in a
separate index than the documents for search.
:return: None
"""
index = index or self.index
field_map = self._create_document_field_map()
documents = deepcopy(documents)
documents_objects = [Document.from_dict(d, field_map=field_map) if isinstance(d, dict) else d for d in documents]
for document in documents_objects:
self.indexes[index][document.id] = document | [
"def",
"write_documents",
"(",
"self",
",",
"documents",
":",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Document",
"]",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"index",
"=",
"index",
"or",
"self",
".",
"index",
"field_map",
"=",
"self",
".",
"_create_document_field_map",
"(",
")",
"documents",
"=",
"deepcopy",
"(",
"documents",
")",
"documents_objects",
"=",
"[",
"Document",
".",
"from_dict",
"(",
"d",
",",
"field_map",
"=",
"field_map",
")",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
"else",
"d",
"for",
"d",
"in",
"documents",
"]",
"for",
"document",
"in",
"documents_objects",
":",
"self",
".",
"indexes",
"[",
"index",
"]",
"[",
"document",
".",
"id",
"]",
"=",
"document"
] | [
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:
label_id = str(uuid4())
# create timestamps if not available yet
if not label.created_at:
label.created_at = time.strftime("%Y-%m-%d %H:%M:%S")
if not label.updated_at:
label.updated_at = label.created_at
self.indexes[index][label_id] = label | [
"def",
"write_labels",
"(",
"self",
",",
"labels",
":",
"Union",
"[",
"List",
"[",
"dict",
"]",
",",
"List",
"[",
"Label",
"]",
"]",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"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",
":",
"label_id",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"# create timestamps if not available yet",
"if",
"not",
"label",
".",
"created_at",
":",
"label",
".",
"created_at",
"=",
"time",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"if",
"not",
"label",
".",
"updated_at",
":",
"label",
".",
"updated_at",
"=",
"label",
".",
"created_at",
"self",
".",
"indexes",
"[",
"index",
"]",
"[",
"label_id",
"]",
"=",
"label"
] | [
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:
return None | [
"def",
"get_document_by_id",
"(",
"self",
",",
"id",
":",
"str",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"Document",
"]",
":",
"index",
"=",
"index",
"or",
"self",
".",
"index",
"documents",
"=",
"self",
".",
"get_documents_by_id",
"(",
"[",
"id",
"]",
",",
"index",
"=",
"index",
")",
"if",
"documents",
":",
"return",
"documents",
"[",
"0",
"]",
"else",
":",
"return",
"None"
] | [
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",
"documents",
"=",
"[",
"self",
".",
"indexes",
"[",
"index",
"]",
"[",
"id",
"]",
"for",
"id",
"in",
"ids",
"]",
"return",
"documents"
] | [
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"], "category": ["only_one"]}
:param top_k: How many documents to return
:param index: Index name for storing the docs and metadata
:param return_embedding: To return document embedding
:return:
|
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 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"], "category": ["only_one"]}
:param top_k: How many documents to return
:param index: Index name for storing the docs and metadata
:param return_embedding: To return document embedding
:return:
"""
from numpy import dot
from numpy.linalg import norm
index = index or self.index
if return_embedding is None:
return_embedding = self.return_embedding
if query_emb is None:
return []
document_to_search = self.get_all_documents(index=index, filters=filters, return_embedding=True)
candidate_docs = []
for doc in document_to_search:
curr_meta = deepcopy(doc.meta)
new_document = Document(
id=doc.id,
text=doc.text,
meta=curr_meta,
embedding=doc.embedding
)
new_document.embedding = doc.embedding if return_embedding is True else None
if self.similarity == "dot_product":
score = dot(query_emb, doc.embedding) / (
norm(query_emb) * norm(doc.embedding)
)
elif self.similarity == "cosine":
# cosine similarity score = 1 - cosine distance
score = 1 - cosine(query_emb, doc.embedding)
new_document.score = score
new_document.probability = (score + 1) / 2
candidate_docs.append(new_document)
return sorted(candidate_docs, key=lambda x: x.score if x.score is not None else 0.0, reverse=True)[0:top_k] | [
"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",
"]",
":",
"from",
"numpy",
"import",
"dot",
"from",
"numpy",
".",
"linalg",
"import",
"norm",
"index",
"=",
"index",
"or",
"self",
".",
"index",
"if",
"return_embedding",
"is",
"None",
":",
"return_embedding",
"=",
"self",
".",
"return_embedding",
"if",
"query_emb",
"is",
"None",
":",
"return",
"[",
"]",
"document_to_search",
"=",
"self",
".",
"get_all_documents",
"(",
"index",
"=",
"index",
",",
"filters",
"=",
"filters",
",",
"return_embedding",
"=",
"True",
")",
"candidate_docs",
"=",
"[",
"]",
"for",
"doc",
"in",
"document_to_search",
":",
"curr_meta",
"=",
"deepcopy",
"(",
"doc",
".",
"meta",
")",
"new_document",
"=",
"Document",
"(",
"id",
"=",
"doc",
".",
"id",
",",
"text",
"=",
"doc",
".",
"text",
",",
"meta",
"=",
"curr_meta",
",",
"embedding",
"=",
"doc",
".",
"embedding",
")",
"new_document",
".",
"embedding",
"=",
"doc",
".",
"embedding",
"if",
"return_embedding",
"is",
"True",
"else",
"None",
"if",
"self",
".",
"similarity",
"==",
"\"dot_product\"",
":",
"score",
"=",
"dot",
"(",
"query_emb",
",",
"doc",
".",
"embedding",
")",
"/",
"(",
"norm",
"(",
"query_emb",
")",
"*",
"norm",
"(",
"doc",
".",
"embedding",
")",
")",
"elif",
"self",
".",
"similarity",
"==",
"\"cosine\"",
":",
"# cosine similarity score = 1 - cosine distance",
"score",
"=",
"1",
"-",
"cosine",
"(",
"query_emb",
",",
"doc",
".",
"embedding",
")",
"new_document",
".",
"score",
"=",
"score",
"new_document",
".",
"probability",
"=",
"(",
"score",
"+",
"1",
")",
"/",
"2",
"candidate_docs",
".",
"append",
"(",
"new_document",
")",
"return",
"sorted",
"(",
"candidate_docs",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"score",
"if",
"x",
".",
"score",
"is",
"not",
"None",
"else",
"0.0",
",",
"reverse",
"=",
"True",
")",
"[",
"0",
":",
"top_k",
"]"
] | [
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
:param index: Index name for which embeddings are to be updated. If set to None, the default self.index is used.
:param update_existing_embeddings: Whether to update existing embeddings of the documents. If set to False,
only documents without embeddings are processed. This mode can be used for
incremental updating of embeddings, wherein, only newly indexed documents
get processed.
:param filters: Optional filters to narrow down the documents for which embeddings are to be updated.
Example: {"name": ["some", "more"], "category": ["only_one"]}
:param batch_size: When working with large number of documents, batching can help reduce memory footprint.
:return: None
|
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 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
:param index: Index name for which embeddings are to be updated. If set to None, the default self.index is used.
:param update_existing_embeddings: Whether to update existing embeddings of the documents. If set to False,
only documents without embeddings are processed. This mode can be used for
incremental updating of embeddings, wherein, only newly indexed documents
get processed.
:param filters: Optional filters to narrow down the documents for which embeddings are to be updated.
Example: {"name": ["some", "more"], "category": ["only_one"]}
:param batch_size: When working with large number of documents, batching can help reduce memory footprint.
:return: None
"""
if index is None:
index = self.index
if not self.embedding_field:
raise RuntimeError("Specify the arg embedding_field when initializing InMemoryDocumentStore()")
# TODO Index embeddings every X batches to avoid OOM for huge document collections
result = self._query(
index=index, filters=filters, only_documents_without_embedding=not update_existing_embeddings
)
document_count = len(result)
logger.info(f"Updating embeddings for {document_count} docs ...")
batched_documents = get_batches_from_generator(result, batch_size)
with tqdm(total=document_count, disable=not self.progress_bar) as progress_bar:
for document_batch in batched_documents:
embeddings = retriever.embed_passages(document_batch) # type: ignore
assert len(document_batch) == len(embeddings)
if embeddings[0].shape[0] != self.embedding_dim:
raise RuntimeError(f"Embedding dim. of model ({embeddings[0].shape[0]})"
f" doesn't match embedding dim. in DocumentStore ({self.embedding_dim})."
"Specify the arg `embedding_dim` when initializing InMemoryDocumentStore()")
for doc, emb in zip(document_batch, embeddings):
self.indexes[index][doc.id].embedding = emb | [
"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",
",",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"self",
".",
"index",
"if",
"not",
"self",
".",
"embedding_field",
":",
"raise",
"RuntimeError",
"(",
"\"Specify the arg embedding_field when initializing InMemoryDocumentStore()\"",
")",
"# TODO Index embeddings every X batches to avoid OOM for huge document collections",
"result",
"=",
"self",
".",
"_query",
"(",
"index",
"=",
"index",
",",
"filters",
"=",
"filters",
",",
"only_documents_without_embedding",
"=",
"not",
"update_existing_embeddings",
")",
"document_count",
"=",
"len",
"(",
"result",
")",
"logger",
".",
"info",
"(",
"f\"Updating embeddings for {document_count} docs ...\"",
")",
"batched_documents",
"=",
"get_batches_from_generator",
"(",
"result",
",",
"batch_size",
")",
"with",
"tqdm",
"(",
"total",
"=",
"document_count",
",",
"disable",
"=",
"not",
"self",
".",
"progress_bar",
")",
"as",
"progress_bar",
":",
"for",
"document_batch",
"in",
"batched_documents",
":",
"embeddings",
"=",
"retriever",
".",
"embed_passages",
"(",
"document_batch",
")",
"# type: ignore",
"assert",
"len",
"(",
"document_batch",
")",
"==",
"len",
"(",
"embeddings",
")",
"if",
"embeddings",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"embedding_dim",
":",
"raise",
"RuntimeError",
"(",
"f\"Embedding dim. of model ({embeddings[0].shape[0]})\"",
"f\" doesn't match embedding dim. in DocumentStore ({self.embedding_dim}).\"",
"\"Specify the arg `embedding_dim` when initializing InMemoryDocumentStore()\"",
")",
"for",
"doc",
",",
"emb",
"in",
"zip",
"(",
"document_batch",
",",
"embeddings",
")",
":",
"self",
".",
"indexes",
"[",
"index",
"]",
"[",
"doc",
".",
"id",
"]",
".",
"embedding",
"=",
"emb"
] | [
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",
"=",
"self",
".",
"get_all_documents",
"(",
"index",
"=",
"index",
",",
"filters",
"=",
"filters",
")",
"return",
"len",
"(",
"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",
"]",
".",
"items",
"(",
")",
")"
] | [
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: Optional filters to narrow down the documents to return.
Example: {"name": ["some", "more"], "category": ["only_one"]}
:param return_embedding: Whether to return the document embeddings.
|
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 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: Optional filters to narrow down the documents to return.
Example: {"name": ["some", "more"], "category": ["only_one"]}
:param return_embedding: Whether to return the document embeddings.
"""
result = self._query(
index=index,
filters=filters,
return_embedding=return_embedding,
batch_size=batch_size
)
yield from result | [
"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",
"]",
":",
"result",
"=",
"self",
".",
"_query",
"(",
"index",
"=",
"index",
",",
"filters",
"=",
"filters",
",",
"return_embedding",
"=",
"return_embedding",
",",
"batch_size",
"=",
"batch_size",
")",
"yield",
"from",
"result"
] | [
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():
label_dict = label.to_dict()
is_hit = True
for key, values in filters.items():
if label_dict[key] not in values:
is_hit = False
break
if is_hit:
result.append(label)
else:
result = list(self.indexes[index].values())
return result | [
"def",
"get_all_labels",
"(",
"self",
",",
"index",
":",
"str",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Label",
"]",
":",
"index",
"=",
"index",
"or",
"self",
".",
"label_index",
"if",
"filters",
":",
"result",
"=",
"[",
"]",
"for",
"label",
"in",
"self",
".",
"indexes",
"[",
"index",
"]",
".",
"values",
"(",
")",
":",
"label_dict",
"=",
"label",
".",
"to_dict",
"(",
")",
"is_hit",
"=",
"True",
"for",
"key",
",",
"values",
"in",
"filters",
".",
"items",
"(",
")",
":",
"if",
"label_dict",
"[",
"key",
"]",
"not",
"in",
"values",
":",
"is_hit",
"=",
"False",
"break",
"if",
"is_hit",
":",
"result",
".",
"append",
"(",
"label",
")",
"else",
":",
"result",
"=",
"list",
"(",
"self",
".",
"indexes",
"[",
"index",
"]",
".",
"values",
"(",
")",
")",
"return",
"result"
] | [
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 narrow down the documents to be deleted.
:return: None
"""
if filters:
raise NotImplementedError("Delete by filters is not implemented for InMemoryDocumentStore.")
index = index or self.index
self.indexes[index] = {} | [
"def",
"delete_all_documents",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
")",
":",
"if",
"filters",
":",
"raise",
"NotImplementedError",
"(",
"\"Delete by filters is not implemented for InMemoryDocumentStore.\"",
")",
"index",
"=",
"index",
"or",
"self",
".",
"index",
"self",
".",
"indexes",
"[",
"index",
"]",
"=",
"{",
"}"
] | [
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 columns.
kind (str, optional): the kind of plot to draw. 'lift', 'gain', and 'qini' are supported.
n (int, optional): the number of samples to be used for plotting.
| 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:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns.
kind (str, optional): the kind of plot to draw. 'lift', 'gain', and 'qini' are supported.
n (int, optional): the number of samples to be used for plotting.
"""
catalog = {'lift': get_cumlift,
'gain': get_cumgain,
'qini': get_qini}
assert kind in catalog.keys(), '{} plot is not implemented. Select one of {}'.format(kind, catalog.keys())
if tmle:
ci_catalog = {'gain': plot_tmlegain,
'qini': plot_tmleqini}
assert kind in ci_catalog.keys(), '{} plot is not implemented. Select one of {}'.format(kind, ci_catalog.keys())
ci_catalog[kind](df, *args, **kwarg)
else:
df = catalog[kind](df, *args, **kwarg)
if (n is not None) and (n < df.shape[0]):
df = df.iloc[np.linspace(0, df.index[-1], n, endpoint=True)]
df.plot(figsize=figsize)
plt.xlabel('Population')
plt.ylabel('{}'.format(kind.title())) | [
"def",
"plot",
"(",
"df",
",",
"kind",
"=",
"'gain'",
",",
"tmle",
"=",
"False",
",",
"n",
"=",
"100",
",",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"catalog",
"=",
"{",
"'lift'",
":",
"get_cumlift",
",",
"'gain'",
":",
"get_cumgain",
",",
"'qini'",
":",
"get_qini",
"}",
"assert",
"kind",
"in",
"catalog",
".",
"keys",
"(",
")",
",",
"'{} plot is not implemented. Select one of {}'",
".",
"format",
"(",
"kind",
",",
"catalog",
".",
"keys",
"(",
")",
")",
"if",
"tmle",
":",
"ci_catalog",
"=",
"{",
"'gain'",
":",
"plot_tmlegain",
",",
"'qini'",
":",
"plot_tmleqini",
"}",
"assert",
"kind",
"in",
"ci_catalog",
".",
"keys",
"(",
")",
",",
"'{} plot is not implemented. Select one of {}'",
".",
"format",
"(",
"kind",
",",
"ci_catalog",
".",
"keys",
"(",
")",
")",
"ci_catalog",
"[",
"kind",
"]",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
"else",
":",
"df",
"=",
"catalog",
"[",
"kind",
"]",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
"if",
"(",
"n",
"is",
"not",
"None",
")",
"and",
"(",
"n",
"<",
"df",
".",
"shape",
"[",
"0",
"]",
")",
":",
"df",
"=",
"df",
".",
"iloc",
"[",
"np",
".",
"linspace",
"(",
"0",
",",
"df",
".",
"index",
"[",
"-",
"1",
"]",
",",
"n",
",",
"endpoint",
"=",
"True",
")",
"]",
"df",
".",
"plot",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"xlabel",
"(",
"'Population'",
")",
"plt",
".",
"ylabel",
"(",
"'{}'",
".",
"format",
"(",
"kind",
".",
"title",
"(",
")",
")",
")"
] | [
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
treatment and control groups in each of cumulative population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
random_seed (int, optional): random seed for numpy.random.rand()
Returns:
(pandas.DataFrame): average uplifts of model estimates in cumulative population
| 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 effect in each of cumulative population.
Otherwise, it's calculated as the difference between the mean outcomes of the
treatment and control groups in each of cumulative population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
random_seed (int, optional): random seed for numpy.random.rand()
Returns:
(pandas.DataFrame): average uplifts of model estimates in cumulative population
"""
assert ((outcome_col in df.columns) and (treatment_col in df.columns) or
treatment_effect_col in df.columns)
df = df.copy()
np.random.seed(random_seed)
random_cols = []
for i in range(10):
random_col = '__random_{}__'.format(i)
df[random_col] = np.random.rand(df.shape[0])
random_cols.append(random_col)
model_names = [x for x in df.columns if x not in [outcome_col, treatment_col,
treatment_effect_col]]
lift = []
for i, col in enumerate(model_names):
sorted_df = df.sort_values(col, ascending=False).reset_index(drop=True)
sorted_df.index = sorted_df.index + 1
if treatment_effect_col in sorted_df.columns:
# When treatment_effect_col is given, use it to calculate the average treatment effects
# of cumulative population.
lift.append(sorted_df[treatment_effect_col].cumsum() / sorted_df.index)
else:
# When treatment_effect_col is not given, use outcome_col and treatment_col
# to calculate the average treatment_effects of cumulative population.
sorted_df['cumsum_tr'] = sorted_df[treatment_col].cumsum()
sorted_df['cumsum_ct'] = sorted_df.index.values - sorted_df['cumsum_tr']
sorted_df['cumsum_y_tr'] = (sorted_df[outcome_col] * sorted_df[treatment_col]).cumsum()
sorted_df['cumsum_y_ct'] = (sorted_df[outcome_col] * (1 - sorted_df[treatment_col])).cumsum()
lift.append(sorted_df['cumsum_y_tr'] / sorted_df['cumsum_tr'] - sorted_df['cumsum_y_ct'] / sorted_df['cumsum_ct'])
lift = pd.concat(lift, join='inner', axis=1)
lift.loc[0] = np.zeros((lift.shape[1], ))
lift = lift.sort_index().interpolate()
lift.columns = model_names
lift[RANDOM_COL] = lift[random_cols].mean(axis=1)
lift.drop(random_cols, axis=1, inplace=True)
return lift | [
"def",
"get_cumlift",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"random_seed",
"=",
"42",
")",
":",
"assert",
"(",
"(",
"outcome_col",
"in",
"df",
".",
"columns",
")",
"and",
"(",
"treatment_col",
"in",
"df",
".",
"columns",
")",
"or",
"treatment_effect_col",
"in",
"df",
".",
"columns",
")",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"random_cols",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"random_col",
"=",
"'__random_{}__'",
".",
"format",
"(",
"i",
")",
"df",
"[",
"random_col",
"]",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"df",
".",
"shape",
"[",
"0",
"]",
")",
"random_cols",
".",
"append",
"(",
"random_col",
")",
"model_names",
"=",
"[",
"x",
"for",
"x",
"in",
"df",
".",
"columns",
"if",
"x",
"not",
"in",
"[",
"outcome_col",
",",
"treatment_col",
",",
"treatment_effect_col",
"]",
"]",
"lift",
"=",
"[",
"]",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"model_names",
")",
":",
"sorted_df",
"=",
"df",
".",
"sort_values",
"(",
"col",
",",
"ascending",
"=",
"False",
")",
".",
"reset_index",
"(",
"drop",
"=",
"True",
")",
"sorted_df",
".",
"index",
"=",
"sorted_df",
".",
"index",
"+",
"1",
"if",
"treatment_effect_col",
"in",
"sorted_df",
".",
"columns",
":",
"# When treatment_effect_col is given, use it to calculate the average treatment effects",
"# of cumulative population.",
"lift",
".",
"append",
"(",
"sorted_df",
"[",
"treatment_effect_col",
"]",
".",
"cumsum",
"(",
")",
"/",
"sorted_df",
".",
"index",
")",
"else",
":",
"# When treatment_effect_col is not given, use outcome_col and treatment_col",
"# to calculate the average treatment_effects of cumulative population.",
"sorted_df",
"[",
"'cumsum_tr'",
"]",
"=",
"sorted_df",
"[",
"treatment_col",
"]",
".",
"cumsum",
"(",
")",
"sorted_df",
"[",
"'cumsum_ct'",
"]",
"=",
"sorted_df",
".",
"index",
".",
"values",
"-",
"sorted_df",
"[",
"'cumsum_tr'",
"]",
"sorted_df",
"[",
"'cumsum_y_tr'",
"]",
"=",
"(",
"sorted_df",
"[",
"outcome_col",
"]",
"*",
"sorted_df",
"[",
"treatment_col",
"]",
")",
".",
"cumsum",
"(",
")",
"sorted_df",
"[",
"'cumsum_y_ct'",
"]",
"=",
"(",
"sorted_df",
"[",
"outcome_col",
"]",
"*",
"(",
"1",
"-",
"sorted_df",
"[",
"treatment_col",
"]",
")",
")",
".",
"cumsum",
"(",
")",
"lift",
".",
"append",
"(",
"sorted_df",
"[",
"'cumsum_y_tr'",
"]",
"/",
"sorted_df",
"[",
"'cumsum_tr'",
"]",
"-",
"sorted_df",
"[",
"'cumsum_y_ct'",
"]",
"/",
"sorted_df",
"[",
"'cumsum_ct'",
"]",
")",
"lift",
"=",
"pd",
".",
"concat",
"(",
"lift",
",",
"join",
"=",
"'inner'",
",",
"axis",
"=",
"1",
")",
"lift",
".",
"loc",
"[",
"0",
"]",
"=",
"np",
".",
"zeros",
"(",
"(",
"lift",
".",
"shape",
"[",
"1",
"]",
",",
")",
")",
"lift",
"=",
"lift",
".",
"sort_index",
"(",
")",
".",
"interpolate",
"(",
")",
"lift",
".",
"columns",
"=",
"model_names",
"lift",
"[",
"RANDOM_COL",
"]",
"=",
"lift",
"[",
"random_cols",
"]",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
"lift",
".",
"drop",
"(",
"random_cols",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"return",
"lift"
] | [
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 treatment and control groups in each population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
Returns:
(pandas.DataFrame): cumulative gains of model estimates in population
| 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 true treatment effect in each population.
Otherwise, it's calculated as the cumulative difference between the mean outcomes
of the treatment and control groups in each population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
Returns:
(pandas.DataFrame): cumulative gains of model estimates in population
"""
lift = get_cumlift(df, outcome_col, treatment_col, treatment_effect_col, random_seed)
# cumulative gain = cumulative lift x (# of population)
gain = lift.mul(lift.index.values, axis=0)
if normalize:
gain = gain.div(np.abs(gain.iloc[-1, :]), axis=1)
return gain | [
"def",
"get_cumgain",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"False",
",",
"random_seed",
"=",
"42",
")",
":",
"lift",
"=",
"get_cumlift",
"(",
"df",
",",
"outcome_col",
",",
"treatment_col",
",",
"treatment_effect_col",
",",
"random_seed",
")",
"# cumulative gain = cumulative lift x (# of population)",
"gain",
"=",
"lift",
".",
"mul",
"(",
"lift",
".",
"index",
".",
"values",
",",
"axis",
"=",
"0",
")",
"if",
"normalize",
":",
"gain",
"=",
"gain",
".",
"div",
"(",
"np",
".",
"abs",
"(",
"gain",
".",
"iloc",
"[",
"-",
"1",
",",
":",
"]",
")",
",",
"axis",
"=",
"1",
")",
"return",
"gain"
] | [
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 control groups in each population.
For details, see Radcliffe (2007), `Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models`
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
Returns:
(pandas.DataFrame): cumulative gains of model estimates in population
| 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 effect in each population.
Otherwise, it's calculated as the cumulative difference between the mean outcomes
of the treatment and control groups in each population.
For details, see Radcliffe (2007), `Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models`
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
Returns:
(pandas.DataFrame): cumulative gains of model estimates in population
"""
assert ((outcome_col in df.columns) and (treatment_col in df.columns) or
treatment_effect_col in df.columns)
df = df.copy()
np.random.seed(random_seed)
random_cols = []
for i in range(10):
random_col = '__random_{}__'.format(i)
df[random_col] = np.random.rand(df.shape[0])
random_cols.append(random_col)
model_names = [x for x in df.columns if x not in [outcome_col, treatment_col,
treatment_effect_col]]
qini = []
for i, col in enumerate(model_names):
df = df.sort_values(col, ascending=False).reset_index(drop=True)
df.index = df.index + 1
df['cumsum_tr'] = df[treatment_col].cumsum()
if treatment_effect_col in df.columns:
# When treatment_effect_col is given, use it to calculate the average treatment effects
# of cumulative population.
l = df[treatment_effect_col].cumsum() / df.index * df['cumsum_tr']
else:
# When treatment_effect_col is not given, use outcome_col and treatment_col
# to calculate the average treatment_effects of cumulative population.
df['cumsum_ct'] = df.index.values - df['cumsum_tr']
df['cumsum_y_tr'] = (df[outcome_col] * df[treatment_col]).cumsum()
df['cumsum_y_ct'] = (df[outcome_col] * (1 - df[treatment_col])).cumsum()
l = df['cumsum_y_tr'] - df['cumsum_y_ct'] * df['cumsum_tr'] / df['cumsum_ct']
qini.append(l)
qini = pd.concat(qini, join='inner', axis=1)
qini.loc[0] = np.zeros((qini.shape[1], ))
qini = qini.sort_index().interpolate()
qini.columns = model_names
qini[RANDOM_COL] = qini[random_cols].mean(axis=1)
qini.drop(random_cols, axis=1, inplace=True)
if normalize:
qini = qini.div(np.abs(qini.iloc[-1, :]), axis=1)
return qini | [
"def",
"get_qini",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"False",
",",
"random_seed",
"=",
"42",
")",
":",
"assert",
"(",
"(",
"outcome_col",
"in",
"df",
".",
"columns",
")",
"and",
"(",
"treatment_col",
"in",
"df",
".",
"columns",
")",
"or",
"treatment_effect_col",
"in",
"df",
".",
"columns",
")",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"random_cols",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"random_col",
"=",
"'__random_{}__'",
".",
"format",
"(",
"i",
")",
"df",
"[",
"random_col",
"]",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"df",
".",
"shape",
"[",
"0",
"]",
")",
"random_cols",
".",
"append",
"(",
"random_col",
")",
"model_names",
"=",
"[",
"x",
"for",
"x",
"in",
"df",
".",
"columns",
"if",
"x",
"not",
"in",
"[",
"outcome_col",
",",
"treatment_col",
",",
"treatment_effect_col",
"]",
"]",
"qini",
"=",
"[",
"]",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"model_names",
")",
":",
"df",
"=",
"df",
".",
"sort_values",
"(",
"col",
",",
"ascending",
"=",
"False",
")",
".",
"reset_index",
"(",
"drop",
"=",
"True",
")",
"df",
".",
"index",
"=",
"df",
".",
"index",
"+",
"1",
"df",
"[",
"'cumsum_tr'",
"]",
"=",
"df",
"[",
"treatment_col",
"]",
".",
"cumsum",
"(",
")",
"if",
"treatment_effect_col",
"in",
"df",
".",
"columns",
":",
"# When treatment_effect_col is given, use it to calculate the average treatment effects",
"# of cumulative population.",
"l",
"=",
"df",
"[",
"treatment_effect_col",
"]",
".",
"cumsum",
"(",
")",
"/",
"df",
".",
"index",
"*",
"df",
"[",
"'cumsum_tr'",
"]",
"else",
":",
"# When treatment_effect_col is not given, use outcome_col and treatment_col",
"# to calculate the average treatment_effects of cumulative population.",
"df",
"[",
"'cumsum_ct'",
"]",
"=",
"df",
".",
"index",
".",
"values",
"-",
"df",
"[",
"'cumsum_tr'",
"]",
"df",
"[",
"'cumsum_y_tr'",
"]",
"=",
"(",
"df",
"[",
"outcome_col",
"]",
"*",
"df",
"[",
"treatment_col",
"]",
")",
".",
"cumsum",
"(",
")",
"df",
"[",
"'cumsum_y_ct'",
"]",
"=",
"(",
"df",
"[",
"outcome_col",
"]",
"*",
"(",
"1",
"-",
"df",
"[",
"treatment_col",
"]",
")",
")",
".",
"cumsum",
"(",
")",
"l",
"=",
"df",
"[",
"'cumsum_y_tr'",
"]",
"-",
"df",
"[",
"'cumsum_y_ct'",
"]",
"*",
"df",
"[",
"'cumsum_tr'",
"]",
"/",
"df",
"[",
"'cumsum_ct'",
"]",
"qini",
".",
"append",
"(",
"l",
")",
"qini",
"=",
"pd",
".",
"concat",
"(",
"qini",
",",
"join",
"=",
"'inner'",
",",
"axis",
"=",
"1",
")",
"qini",
".",
"loc",
"[",
"0",
"]",
"=",
"np",
".",
"zeros",
"(",
"(",
"qini",
".",
"shape",
"[",
"1",
"]",
",",
")",
")",
"qini",
"=",
"qini",
".",
"sort_index",
"(",
")",
".",
"interpolate",
"(",
")",
"qini",
".",
"columns",
"=",
"model_names",
"qini",
"[",
"RANDOM_COL",
"]",
"=",
"qini",
"[",
"random_cols",
"]",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
"qini",
".",
"drop",
"(",
"random_cols",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"if",
"normalize",
":",
"qini",
"=",
"qini",
".",
"div",
"(",
"np",
".",
"abs",
"(",
"qini",
".",
"iloc",
"[",
"-",
"1",
",",
":",
"]",
")",
",",
"axis",
"=",
"1",
")",
"return",
"qini"
] | [
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 the outcome
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
Returns:
(pandas.DataFrame): cumulative gains of model estimates based of TMLE
| 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.
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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
Returns:
(pandas.DataFrame): cumulative gains of model estimates based of TMLE
"""
assert ((outcome_col in df.columns) and (treatment_col in df.columns) or
p_col in df.columns)
inference_col = [x for x in inference_col if x in df.columns]
# Initialize TMLE
tmle = TMLELearner(learner, cv=cv, calibrate_propensity=calibrate_propensity)
ate_all, ate_all_lb, ate_all_ub = tmle.estimate_ate(X=df[inference_col],
p=df[p_col],
treatment=df[treatment_col],
y=df[outcome_col])
df = df.copy()
model_names = [x for x in df.columns if x not in [outcome_col, treatment_col, p_col] + inference_col]
lift = []
lift_lb = []
lift_ub = []
for col in model_names:
ate_model, ate_model_lb, ate_model_ub = tmle.estimate_ate(X=df[inference_col],
p=df[p_col],
treatment=df[treatment_col],
y=df[outcome_col],
segment=pd.qcut(df[col], n_segment, labels=False))
lift_model = [0.] * (n_segment + 1)
lift_model[n_segment] = ate_all[0]
for i in range(1, n_segment):
lift_model[i] = ate_model[0][n_segment - i] * (1/n_segment) + lift_model[i - 1]
lift.append(lift_model)
if ci:
lift_lb_model = [0.] * (n_segment + 1)
lift_lb_model[n_segment] = ate_all_lb[0]
lift_ub_model = [0.] * (n_segment + 1)
lift_ub_model[n_segment] = ate_all_ub[0]
for i in range(1, n_segment):
lift_lb_model[i] = ate_model_lb[0][n_segment - i] * (1/n_segment) + lift_lb_model[i - 1]
lift_ub_model[i] = ate_model_ub[0][n_segment - i] * (1/n_segment) + lift_ub_model[i - 1]
lift_lb.append(lift_lb_model)
lift_ub.append(lift_ub_model)
lift = pd.DataFrame(lift).T
lift.columns = model_names
if ci:
lift_lb = pd.DataFrame(lift_lb).T
lift_lb.columns = [x + " LB" for x in model_names]
lift_ub = pd.DataFrame(lift_ub).T
lift_ub.columns = [x + " UB" for x in model_names]
lift = pd.concat([lift, lift_lb, lift_ub], axis=1)
lift.index = lift.index/n_segment
lift[RANDOM_COL] = np.linspace(0, 1, n_segment + 1)*ate_all[0]
return lift | [
"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",
")",
":",
"assert",
"(",
"(",
"outcome_col",
"in",
"df",
".",
"columns",
")",
"and",
"(",
"treatment_col",
"in",
"df",
".",
"columns",
")",
"or",
"p_col",
"in",
"df",
".",
"columns",
")",
"inference_col",
"=",
"[",
"x",
"for",
"x",
"in",
"inference_col",
"if",
"x",
"in",
"df",
".",
"columns",
"]",
"# Initialize TMLE",
"tmle",
"=",
"TMLELearner",
"(",
"learner",
",",
"cv",
"=",
"cv",
",",
"calibrate_propensity",
"=",
"calibrate_propensity",
")",
"ate_all",
",",
"ate_all_lb",
",",
"ate_all_ub",
"=",
"tmle",
".",
"estimate_ate",
"(",
"X",
"=",
"df",
"[",
"inference_col",
"]",
",",
"p",
"=",
"df",
"[",
"p_col",
"]",
",",
"treatment",
"=",
"df",
"[",
"treatment_col",
"]",
",",
"y",
"=",
"df",
"[",
"outcome_col",
"]",
")",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"model_names",
"=",
"[",
"x",
"for",
"x",
"in",
"df",
".",
"columns",
"if",
"x",
"not",
"in",
"[",
"outcome_col",
",",
"treatment_col",
",",
"p_col",
"]",
"+",
"inference_col",
"]",
"lift",
"=",
"[",
"]",
"lift_lb",
"=",
"[",
"]",
"lift_ub",
"=",
"[",
"]",
"for",
"col",
"in",
"model_names",
":",
"ate_model",
",",
"ate_model_lb",
",",
"ate_model_ub",
"=",
"tmle",
".",
"estimate_ate",
"(",
"X",
"=",
"df",
"[",
"inference_col",
"]",
",",
"p",
"=",
"df",
"[",
"p_col",
"]",
",",
"treatment",
"=",
"df",
"[",
"treatment_col",
"]",
",",
"y",
"=",
"df",
"[",
"outcome_col",
"]",
",",
"segment",
"=",
"pd",
".",
"qcut",
"(",
"df",
"[",
"col",
"]",
",",
"n_segment",
",",
"labels",
"=",
"False",
")",
")",
"lift_model",
"=",
"[",
"0.",
"]",
"*",
"(",
"n_segment",
"+",
"1",
")",
"lift_model",
"[",
"n_segment",
"]",
"=",
"ate_all",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n_segment",
")",
":",
"lift_model",
"[",
"i",
"]",
"=",
"ate_model",
"[",
"0",
"]",
"[",
"n_segment",
"-",
"i",
"]",
"*",
"(",
"1",
"/",
"n_segment",
")",
"+",
"lift_model",
"[",
"i",
"-",
"1",
"]",
"lift",
".",
"append",
"(",
"lift_model",
")",
"if",
"ci",
":",
"lift_lb_model",
"=",
"[",
"0.",
"]",
"*",
"(",
"n_segment",
"+",
"1",
")",
"lift_lb_model",
"[",
"n_segment",
"]",
"=",
"ate_all_lb",
"[",
"0",
"]",
"lift_ub_model",
"=",
"[",
"0.",
"]",
"*",
"(",
"n_segment",
"+",
"1",
")",
"lift_ub_model",
"[",
"n_segment",
"]",
"=",
"ate_all_ub",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n_segment",
")",
":",
"lift_lb_model",
"[",
"i",
"]",
"=",
"ate_model_lb",
"[",
"0",
"]",
"[",
"n_segment",
"-",
"i",
"]",
"*",
"(",
"1",
"/",
"n_segment",
")",
"+",
"lift_lb_model",
"[",
"i",
"-",
"1",
"]",
"lift_ub_model",
"[",
"i",
"]",
"=",
"ate_model_ub",
"[",
"0",
"]",
"[",
"n_segment",
"-",
"i",
"]",
"*",
"(",
"1",
"/",
"n_segment",
")",
"+",
"lift_ub_model",
"[",
"i",
"-",
"1",
"]",
"lift_lb",
".",
"append",
"(",
"lift_lb_model",
")",
"lift_ub",
".",
"append",
"(",
"lift_ub_model",
")",
"lift",
"=",
"pd",
".",
"DataFrame",
"(",
"lift",
")",
".",
"T",
"lift",
".",
"columns",
"=",
"model_names",
"if",
"ci",
":",
"lift_lb",
"=",
"pd",
".",
"DataFrame",
"(",
"lift_lb",
")",
".",
"T",
"lift_lb",
".",
"columns",
"=",
"[",
"x",
"+",
"\" LB\"",
"for",
"x",
"in",
"model_names",
"]",
"lift_ub",
"=",
"pd",
".",
"DataFrame",
"(",
"lift_ub",
")",
".",
"T",
"lift_ub",
".",
"columns",
"=",
"[",
"x",
"+",
"\" UB\"",
"for",
"x",
"in",
"model_names",
"]",
"lift",
"=",
"pd",
".",
"concat",
"(",
"[",
"lift",
",",
"lift_lb",
",",
"lift_ub",
"]",
",",
"axis",
"=",
"1",
")",
"lift",
".",
"index",
"=",
"lift",
".",
"index",
"/",
"n_segment",
"lift",
"[",
"RANDOM_COL",
"]",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"n_segment",
"+",
"1",
")",
"*",
"ate_all",
"[",
"0",
"]",
"return",
"lift"
] | [
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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
Returns:
(pandas.DataFrame): cumulative gains of model estimates based of TMLE
| 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 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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
Returns:
(pandas.DataFrame): cumulative gains of model estimates based of TMLE
"""
assert ((outcome_col in df.columns) and (treatment_col in df.columns) or
p_col in df.columns)
inference_col = [x for x in inference_col if x in df.columns]
# Initialize TMLE
tmle = TMLELearner(learner, cv=cv, calibrate_propensity=calibrate_propensity)
ate_all, ate_all_lb, ate_all_ub = tmle.estimate_ate(X=df[inference_col],
p=df[p_col],
treatment=df[treatment_col],
y=df[outcome_col])
df = df.copy()
model_names = [x for x in df.columns if x not in [outcome_col, treatment_col, p_col] + inference_col]
qini = []
qini_lb = []
qini_ub = []
for col in model_names:
ate_model, ate_model_lb, ate_model_ub = tmle.estimate_ate(X=df[inference_col],
p=df[p_col],
treatment=df[treatment_col],
y=df[outcome_col],
segment=pd.qcut(df[col], n_segment, labels=False))
qini_model = [0]
for i in range(1, n_segment):
n_tr = df[pd.qcut(df[col], n_segment, labels=False) == (n_segment - i)][treatment_col].sum()
qini_model.append(ate_model[0][n_segment - i] * n_tr)
qini.append(qini_model)
if ci:
qini_lb_model = [0]
qini_ub_model = [0]
for i in range(1, n_segment):
n_tr = df[pd.qcut(df[col], n_segment, labels=False) == (n_segment - i)][treatment_col].sum()
qini_lb_model.append(ate_model_lb[0][n_segment - i] * n_tr)
qini_ub_model.append(ate_model_ub[0][n_segment - i] * n_tr)
qini_lb.append(qini_lb_model)
qini_ub.append(qini_ub_model)
qini = pd.DataFrame(qini).T
qini.columns = model_names
if ci:
qini_lb = pd.DataFrame(qini_lb).T
qini_lb.columns = [x + " LB" for x in model_names]
qini_ub = pd.DataFrame(qini_ub).T
qini_ub.columns = [x + " UB" for x in model_names]
qini = pd.concat([qini, qini_lb, qini_ub], axis=1)
qini = qini.cumsum()
qini.loc[n_segment] = ate_all[0] * df[treatment_col].sum()
qini[RANDOM_COL] = np.linspace(0, 1, n_segment + 1) * ate_all[0] * df[treatment_col].sum()
qini.index = np.linspace(0, 1, n_segment + 1) * df.shape[0]
return qini | [
"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",
")",
":",
"assert",
"(",
"(",
"outcome_col",
"in",
"df",
".",
"columns",
")",
"and",
"(",
"treatment_col",
"in",
"df",
".",
"columns",
")",
"or",
"p_col",
"in",
"df",
".",
"columns",
")",
"inference_col",
"=",
"[",
"x",
"for",
"x",
"in",
"inference_col",
"if",
"x",
"in",
"df",
".",
"columns",
"]",
"# Initialize TMLE",
"tmle",
"=",
"TMLELearner",
"(",
"learner",
",",
"cv",
"=",
"cv",
",",
"calibrate_propensity",
"=",
"calibrate_propensity",
")",
"ate_all",
",",
"ate_all_lb",
",",
"ate_all_ub",
"=",
"tmle",
".",
"estimate_ate",
"(",
"X",
"=",
"df",
"[",
"inference_col",
"]",
",",
"p",
"=",
"df",
"[",
"p_col",
"]",
",",
"treatment",
"=",
"df",
"[",
"treatment_col",
"]",
",",
"y",
"=",
"df",
"[",
"outcome_col",
"]",
")",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"model_names",
"=",
"[",
"x",
"for",
"x",
"in",
"df",
".",
"columns",
"if",
"x",
"not",
"in",
"[",
"outcome_col",
",",
"treatment_col",
",",
"p_col",
"]",
"+",
"inference_col",
"]",
"qini",
"=",
"[",
"]",
"qini_lb",
"=",
"[",
"]",
"qini_ub",
"=",
"[",
"]",
"for",
"col",
"in",
"model_names",
":",
"ate_model",
",",
"ate_model_lb",
",",
"ate_model_ub",
"=",
"tmle",
".",
"estimate_ate",
"(",
"X",
"=",
"df",
"[",
"inference_col",
"]",
",",
"p",
"=",
"df",
"[",
"p_col",
"]",
",",
"treatment",
"=",
"df",
"[",
"treatment_col",
"]",
",",
"y",
"=",
"df",
"[",
"outcome_col",
"]",
",",
"segment",
"=",
"pd",
".",
"qcut",
"(",
"df",
"[",
"col",
"]",
",",
"n_segment",
",",
"labels",
"=",
"False",
")",
")",
"qini_model",
"=",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n_segment",
")",
":",
"n_tr",
"=",
"df",
"[",
"pd",
".",
"qcut",
"(",
"df",
"[",
"col",
"]",
",",
"n_segment",
",",
"labels",
"=",
"False",
")",
"==",
"(",
"n_segment",
"-",
"i",
")",
"]",
"[",
"treatment_col",
"]",
".",
"sum",
"(",
")",
"qini_model",
".",
"append",
"(",
"ate_model",
"[",
"0",
"]",
"[",
"n_segment",
"-",
"i",
"]",
"*",
"n_tr",
")",
"qini",
".",
"append",
"(",
"qini_model",
")",
"if",
"ci",
":",
"qini_lb_model",
"=",
"[",
"0",
"]",
"qini_ub_model",
"=",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n_segment",
")",
":",
"n_tr",
"=",
"df",
"[",
"pd",
".",
"qcut",
"(",
"df",
"[",
"col",
"]",
",",
"n_segment",
",",
"labels",
"=",
"False",
")",
"==",
"(",
"n_segment",
"-",
"i",
")",
"]",
"[",
"treatment_col",
"]",
".",
"sum",
"(",
")",
"qini_lb_model",
".",
"append",
"(",
"ate_model_lb",
"[",
"0",
"]",
"[",
"n_segment",
"-",
"i",
"]",
"*",
"n_tr",
")",
"qini_ub_model",
".",
"append",
"(",
"ate_model_ub",
"[",
"0",
"]",
"[",
"n_segment",
"-",
"i",
"]",
"*",
"n_tr",
")",
"qini_lb",
".",
"append",
"(",
"qini_lb_model",
")",
"qini_ub",
".",
"append",
"(",
"qini_ub_model",
")",
"qini",
"=",
"pd",
".",
"DataFrame",
"(",
"qini",
")",
".",
"T",
"qini",
".",
"columns",
"=",
"model_names",
"if",
"ci",
":",
"qini_lb",
"=",
"pd",
".",
"DataFrame",
"(",
"qini_lb",
")",
".",
"T",
"qini_lb",
".",
"columns",
"=",
"[",
"x",
"+",
"\" LB\"",
"for",
"x",
"in",
"model_names",
"]",
"qini_ub",
"=",
"pd",
".",
"DataFrame",
"(",
"qini_ub",
")",
".",
"T",
"qini_ub",
".",
"columns",
"=",
"[",
"x",
"+",
"\" UB\"",
"for",
"x",
"in",
"model_names",
"]",
"qini",
"=",
"pd",
".",
"concat",
"(",
"[",
"qini",
",",
"qini_lb",
",",
"qini_ub",
"]",
",",
"axis",
"=",
"1",
")",
"qini",
"=",
"qini",
".",
"cumsum",
"(",
")",
"qini",
".",
"loc",
"[",
"n_segment",
"]",
"=",
"ate_all",
"[",
"0",
"]",
"*",
"df",
"[",
"treatment_col",
"]",
".",
"sum",
"(",
")",
"qini",
"[",
"RANDOM_COL",
"]",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"n_segment",
"+",
"1",
")",
"*",
"ate_all",
"[",
"0",
"]",
"*",
"df",
"[",
"treatment_col",
"]",
".",
"sum",
"(",
")",
"qini",
".",
"index",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"n_segment",
"+",
"1",
")",
"*",
"df",
".",
"shape",
"[",
"0",
"]",
"return",
"qini"
] | [
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
of the treatment and control groups in each population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
n (int, optional): the number of samples to be used for plotting
| 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
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 control groups in each population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
n (int, optional): the number of samples to be used for plotting
"""
plot(df, kind='gain', n=n, figsize=figsize, outcome_col=outcome_col, treatment_col=treatment_col,
treatment_effect_col=treatment_effect_col, normalize=normalize, random_seed=random_seed) | [
"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",
"(",
"df",
",",
"kind",
"=",
"'gain'",
",",
"n",
"=",
"n",
",",
"figsize",
"=",
"figsize",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"treatment_effect_col",
"=",
"treatment_effect_col",
",",
"normalize",
"=",
"normalize",
",",
"random_seed",
"=",
"random_seed",
")"
] | [
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
treatment and control groups in each of cumulative population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
random_seed (int, optional): random seed for numpy.random.rand()
n (int, optional): the number of samples to be used for plotting
| 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 true treatment effect in each of cumulative population.
Otherwise, it's calculated as the difference between the mean outcomes of the
treatment and control groups in each of cumulative population.
For details, see Section 4.1 of Gutierrez and G{\'e}rardy (2016), `Causal Inference
and Uplift Modeling: A review of the literature`.
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
random_seed (int, optional): random seed for numpy.random.rand()
n (int, optional): the number of samples to be used for plotting
"""
plot(df, kind='lift', n=n, figsize=figsize, outcome_col=outcome_col, treatment_col=treatment_col,
treatment_effect_col=treatment_effect_col, random_seed=random_seed) | [
"def",
"plot_lift",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"random_seed",
"=",
"42",
",",
"n",
"=",
"100",
",",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
")",
":",
"plot",
"(",
"df",
",",
"kind",
"=",
"'lift'",
",",
"n",
"=",
"n",
",",
"figsize",
"=",
"figsize",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"treatment_effect_col",
"=",
"treatment_effect_col",
",",
"random_seed",
"=",
"random_seed",
")"
] | [
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 treatment and control groups in each population.
For details, see Radcliffe (2007), `Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models`
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
n (int, optional): the number of samples to be used for plotting
ci (bool, optional): whether return confidence intervals for ATE or not
| 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 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 control groups in each population.
For details, see Radcliffe (2007), `Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models`
For the former, `treatment_effect_col` should be provided. For the latter, both
`outcome_col` and `treatment_col` should be provided.
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
random_seed (int, optional): random seed for numpy.random.rand()
n (int, optional): the number of samples to be used for plotting
ci (bool, optional): whether return confidence intervals for ATE or not
"""
plot(df, kind='qini', n=n, figsize=figsize, outcome_col=outcome_col, treatment_col=treatment_col,
treatment_effect_col=treatment_effect_col, normalize=normalize, random_seed=random_seed) | [
"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",
"(",
"df",
",",
"kind",
"=",
"'qini'",
",",
"n",
"=",
"n",
",",
"figsize",
"=",
"figsize",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"treatment_effect_col",
"=",
"treatment_effect_col",
",",
"normalize",
"=",
"normalize",
",",
"random_seed",
"=",
"random_seed",
")"
] | [
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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
| 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 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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
"""
plot_df = get_tmlegain(df, learner=learner, inference_col=inference_col, outcome_col=outcome_col,
treatment_col=treatment_col, p_col=p_col, n_segment=n_segment, cv=cv,
calibrate_propensity=calibrate_propensity, ci=ci)
if ci:
model_names = [x.replace(" LB", "") for x in plot_df.columns]
model_names = list(set([x.replace(" UB", "") for x in model_names]))
fig, ax = plt.subplots(figsize=figsize)
cmap = plt.get_cmap("tab10")
cindex = 0
for col in model_names:
lb_col = col + " LB"
up_col = col + " UB"
if col != 'Random':
ax.plot(plot_df.index, plot_df[col], color=cmap(cindex))
ax.fill_between(plot_df.index, plot_df[lb_col], plot_df[up_col], color=cmap(cindex), alpha=0.25)
else:
ax.plot(plot_df.index, plot_df[col], color=cmap(cindex))
cindex += 1
ax.legend()
else:
plot_df.plot(figsize=figsize)
plt.xlabel('Population')
plt.ylabel('Gain')
plt.show() | [
"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_df",
"=",
"get_tmlegain",
"(",
"df",
",",
"learner",
"=",
"learner",
",",
"inference_col",
"=",
"inference_col",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"p_col",
"=",
"p_col",
",",
"n_segment",
"=",
"n_segment",
",",
"cv",
"=",
"cv",
",",
"calibrate_propensity",
"=",
"calibrate_propensity",
",",
"ci",
"=",
"ci",
")",
"if",
"ci",
":",
"model_names",
"=",
"[",
"x",
".",
"replace",
"(",
"\" LB\"",
",",
"\"\"",
")",
"for",
"x",
"in",
"plot_df",
".",
"columns",
"]",
"model_names",
"=",
"list",
"(",
"set",
"(",
"[",
"x",
".",
"replace",
"(",
"\" UB\"",
",",
"\"\"",
")",
"for",
"x",
"in",
"model_names",
"]",
")",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figsize",
")",
"cmap",
"=",
"plt",
".",
"get_cmap",
"(",
"\"tab10\"",
")",
"cindex",
"=",
"0",
"for",
"col",
"in",
"model_names",
":",
"lb_col",
"=",
"col",
"+",
"\" LB\"",
"up_col",
"=",
"col",
"+",
"\" UB\"",
"if",
"col",
"!=",
"'Random'",
":",
"ax",
".",
"plot",
"(",
"plot_df",
".",
"index",
",",
"plot_df",
"[",
"col",
"]",
",",
"color",
"=",
"cmap",
"(",
"cindex",
")",
")",
"ax",
".",
"fill_between",
"(",
"plot_df",
".",
"index",
",",
"plot_df",
"[",
"lb_col",
"]",
",",
"plot_df",
"[",
"up_col",
"]",
",",
"color",
"=",
"cmap",
"(",
"cindex",
")",
",",
"alpha",
"=",
"0.25",
")",
"else",
":",
"ax",
".",
"plot",
"(",
"plot_df",
".",
"index",
",",
"plot_df",
"[",
"col",
"]",
",",
"color",
"=",
"cmap",
"(",
"cindex",
")",
")",
"cindex",
"+=",
"1",
"ax",
".",
"legend",
"(",
")",
"else",
":",
"plot_df",
".",
"plot",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"xlabel",
"(",
"'Population'",
")",
"plt",
".",
"ylabel",
"(",
"'Gain'",
")",
"plt",
".",
"show",
"(",
")"
] | [
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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
| 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 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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
n_segment (int, optional): number of segment that TMLE will estimated for each
cv (sklearn.model_selection._BaseKFold, optional): sklearn CV object
calibrate_propensity (bool, optional): whether calibrate propensity score or not
ci (bool, optional): whether return confidence intervals for ATE or not
"""
plot_df = get_tmleqini(df, learner=learner, inference_col=inference_col, outcome_col=outcome_col,
treatment_col=treatment_col, p_col=p_col, n_segment=n_segment, cv=cv,
calibrate_propensity=calibrate_propensity, ci=ci)
if ci:
model_names = [x.replace(" LB", "") for x in plot_df.columns]
model_names = list(set([x.replace(" UB", "") for x in model_names]))
fig, ax = plt.subplots(figsize=figsize)
cmap = plt.get_cmap("tab10")
cindex = 0
for col in model_names:
lb_col = col + " LB"
up_col = col + " UB"
if col != 'Random':
ax.plot(plot_df.index, plot_df[col], color=cmap(cindex))
ax.fill_between(plot_df.index, plot_df[lb_col], plot_df[up_col], color=cmap(cindex), alpha=0.25)
else:
ax.plot(plot_df.index, plot_df[col], color=cmap(cindex))
cindex += 1
ax.legend()
else:
plot_df.plot(figsize=figsize)
plt.xlabel('Population')
plt.ylabel('Qini')
plt.show() | [
"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_df",
"=",
"get_tmleqini",
"(",
"df",
",",
"learner",
"=",
"learner",
",",
"inference_col",
"=",
"inference_col",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"p_col",
"=",
"p_col",
",",
"n_segment",
"=",
"n_segment",
",",
"cv",
"=",
"cv",
",",
"calibrate_propensity",
"=",
"calibrate_propensity",
",",
"ci",
"=",
"ci",
")",
"if",
"ci",
":",
"model_names",
"=",
"[",
"x",
".",
"replace",
"(",
"\" LB\"",
",",
"\"\"",
")",
"for",
"x",
"in",
"plot_df",
".",
"columns",
"]",
"model_names",
"=",
"list",
"(",
"set",
"(",
"[",
"x",
".",
"replace",
"(",
"\" UB\"",
",",
"\"\"",
")",
"for",
"x",
"in",
"model_names",
"]",
")",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figsize",
")",
"cmap",
"=",
"plt",
".",
"get_cmap",
"(",
"\"tab10\"",
")",
"cindex",
"=",
"0",
"for",
"col",
"in",
"model_names",
":",
"lb_col",
"=",
"col",
"+",
"\" LB\"",
"up_col",
"=",
"col",
"+",
"\" UB\"",
"if",
"col",
"!=",
"'Random'",
":",
"ax",
".",
"plot",
"(",
"plot_df",
".",
"index",
",",
"plot_df",
"[",
"col",
"]",
",",
"color",
"=",
"cmap",
"(",
"cindex",
")",
")",
"ax",
".",
"fill_between",
"(",
"plot_df",
".",
"index",
",",
"plot_df",
"[",
"lb_col",
"]",
",",
"plot_df",
"[",
"up_col",
"]",
",",
"color",
"=",
"cmap",
"(",
"cindex",
")",
",",
"alpha",
"=",
"0.25",
")",
"else",
":",
"ax",
".",
"plot",
"(",
"plot_df",
".",
"index",
",",
"plot_df",
"[",
"col",
"]",
",",
"color",
"=",
"cmap",
"(",
"cindex",
")",
")",
"cindex",
"+=",
"1",
"ax",
".",
"legend",
"(",
")",
"else",
":",
"plot_df",
".",
"plot",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"xlabel",
"(",
"'Population'",
")",
"plt",
".",
"ylabel",
"(",
"'Qini'",
")",
"plt",
".",
"show",
"(",
")"
] | [
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
Returns:
(float): the AUUC score
| 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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
Returns:
(float): the AUUC score
"""
if not tmle:
cumgain = get_cumgain(df, outcome_col, treatment_col, treatment_effect_col, normalize)
else:
cumgain = get_tmlegain(df, outcome_col=outcome_col, treatment_col=treatment_col, *args, **kwarg)
return cumgain.sum() / cumgain.shape[0] | [
"def",
"auuc_score",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"True",
",",
"tmle",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"not",
"tmle",
":",
"cumgain",
"=",
"get_cumgain",
"(",
"df",
",",
"outcome_col",
",",
"treatment_col",
",",
"treatment_effect_col",
",",
"normalize",
")",
"else",
":",
"cumgain",
"=",
"get_tmlegain",
"(",
"df",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
"return",
"cumgain",
".",
"sum",
"(",
")",
"/",
"cumgain",
".",
"shape",
"[",
"0",
"]"
] | [
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
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
Returns:
(float): the Qini score
| 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:
Building and Assessing Uplift Models`
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 (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
Returns:
(float): the Qini score
"""
if not tmle:
qini = get_qini(df, outcome_col, treatment_col, treatment_effect_col, normalize)
else:
qini = get_tmleqini(df, outcome_col=outcome_col, treatment_col=treatment_col, *args, **kwarg)
return (qini.sum(axis=0) - qini[RANDOM_COL].sum()) / qini.shape[0] | [
"def",
"qini_score",
"(",
"df",
",",
"outcome_col",
"=",
"'y'",
",",
"treatment_col",
"=",
"'w'",
",",
"treatment_effect_col",
"=",
"'tau'",
",",
"normalize",
"=",
"True",
",",
"tmle",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"not",
"tmle",
":",
"qini",
"=",
"get_qini",
"(",
"df",
",",
"outcome_col",
",",
"treatment_col",
",",
"treatment_effect_col",
",",
"normalize",
")",
"else",
":",
"qini",
"=",
"get_tmleqini",
"(",
"df",
",",
"outcome_col",
"=",
"outcome_col",
",",
"treatment_col",
"=",
"treatment_col",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
"return",
"(",
"qini",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"-",
"qini",
"[",
"RANDOM_COL",
"]",
".",
"sum",
"(",
")",
")",
"/",
"qini",
".",
"shape",
"[",
"0",
"]"
] | [
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 str): a list of columns that are used a covariates
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
| 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 containing the covariates and treatment indicator
covariate_col (list of str): a list of columns that are used a covariates
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
p_col (str, optional): the column name for propensity score
"""
X = df[covariate_col]
W = df[treatment_col]
PS = df[p_col]
IPTW = get_simple_iptw(W, PS)
diffs_pre = get_std_diffs(X, W, weighted=False)
num_unbal_pre = (np.abs(diffs_pre) > 0.1).sum()[0]
diffs_post = get_std_diffs(X, W, IPTW, weighted=True)
num_unbal_post = (np.abs(diffs_post) > 0.1).sum()[0]
diff_plot = _plot_std_diffs(diffs_pre,
num_unbal_pre,
diffs_post,
num_unbal_post)
return diff_plot | [
"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",
"]",
"IPTW",
"=",
"get_simple_iptw",
"(",
"W",
",",
"PS",
")",
"diffs_pre",
"=",
"get_std_diffs",
"(",
"X",
",",
"W",
",",
"weighted",
"=",
"False",
")",
"num_unbal_pre",
"=",
"(",
"np",
".",
"abs",
"(",
"diffs_pre",
")",
">",
"0.1",
")",
".",
"sum",
"(",
")",
"[",
"0",
"]",
"diffs_post",
"=",
"get_std_diffs",
"(",
"X",
",",
"W",
",",
"IPTW",
",",
"weighted",
"=",
"True",
")",
"num_unbal_post",
"=",
"(",
"np",
".",
"abs",
"(",
"diffs_post",
")",
">",
"0.1",
")",
".",
"sum",
"(",
")",
"[",
"0",
"]",
"diff_plot",
"=",
"_plot_std_diffs",
"(",
"diffs_pre",
",",
"num_unbal_pre",
",",
"diffs_post",
",",
"num_unbal_post",
")",
"return",
"diff_plot"
] | [
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 only continuous and binary numerical variables.
"""
cont_cols, prop_cols = _get_numeric_vars(X, threshold=numeric_threshold)
cols = cont_cols + prop_cols
if len(cols) == 0:
raise ValueError(
"No variable passed the test for continuous or binary variables.")
treat = (W == 1)
contr = (W == 0)
X_1 = X.loc[treat, cols]
X_0 = X.loc[contr, cols]
cont_index = np.array([col in cont_cols for col in cols])
prop_index = np.array([col in prop_cols for col in cols])
std_diffs_cont = np.empty(sum(cont_index))
std_diffs_prop = np.empty(sum(prop_index))
if weighted:
assert weight is not None, 'weight should be provided when weighting is set to "True"'
weight_1 = weight[treat]
weight_0 = weight[contr]
X_1_mean, X_1_var = np.apply_along_axis(
lambda x: _get_wmean_wvar(x, weight_1), 0, X_1)
X_0_mean, X_0_var = np.apply_along_axis(
lambda x: _get_wmean_wvar(x, weight_0), 0, X_0)
elif not weighted:
X_1_mean, X_1_var = np.apply_along_axis(
lambda x: _get_mean_var(x), 0, X_1)
X_0_mean, X_0_var = np.apply_along_axis(
lambda x: _get_mean_var(x), 0, X_0)
X_1_mean_cont, X_1_var_cont = X_1_mean[cont_index], X_1_var[cont_index]
X_0_mean_cont, X_0_var_cont = X_0_mean[cont_index], X_0_var[cont_index]
std_diffs_cont = ((X_1_mean_cont - X_0_mean_cont) /
np.sqrt((X_1_var_cont + X_0_var_cont) / 2))
X_1_mean_prop = X_1_mean[prop_index]
X_0_mean_prop = X_0_mean[prop_index]
std_diffs_prop = ((X_1_mean_prop - X_0_mean_prop) /
np.sqrt(((X_1_mean_prop * (1 - X_1_mean_prop)) + (X_0_mean_prop * (1 - X_0_mean_prop))) / 2))
std_diffs = np.concatenate([std_diffs_cont, std_diffs_prop], axis=0)
std_diffs_df = pd.DataFrame(std_diffs, index=cols)
return std_diffs_df | [
"def",
"get_std_diffs",
"(",
"X",
",",
"W",
",",
"weight",
"=",
"None",
",",
"weighted",
"=",
"False",
",",
"numeric_threshold",
"=",
"5",
")",
":",
"cont_cols",
",",
"prop_cols",
"=",
"_get_numeric_vars",
"(",
"X",
",",
"threshold",
"=",
"numeric_threshold",
")",
"cols",
"=",
"cont_cols",
"+",
"prop_cols",
"if",
"len",
"(",
"cols",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"No variable passed the test for continuous or binary variables.\"",
")",
"treat",
"=",
"(",
"W",
"==",
"1",
")",
"contr",
"=",
"(",
"W",
"==",
"0",
")",
"X_1",
"=",
"X",
".",
"loc",
"[",
"treat",
",",
"cols",
"]",
"X_0",
"=",
"X",
".",
"loc",
"[",
"contr",
",",
"cols",
"]",
"cont_index",
"=",
"np",
".",
"array",
"(",
"[",
"col",
"in",
"cont_cols",
"for",
"col",
"in",
"cols",
"]",
")",
"prop_index",
"=",
"np",
".",
"array",
"(",
"[",
"col",
"in",
"prop_cols",
"for",
"col",
"in",
"cols",
"]",
")",
"std_diffs_cont",
"=",
"np",
".",
"empty",
"(",
"sum",
"(",
"cont_index",
")",
")",
"std_diffs_prop",
"=",
"np",
".",
"empty",
"(",
"sum",
"(",
"prop_index",
")",
")",
"if",
"weighted",
":",
"assert",
"weight",
"is",
"not",
"None",
",",
"'weight should be provided when weighting is set to \"True\"'",
"weight_1",
"=",
"weight",
"[",
"treat",
"]",
"weight_0",
"=",
"weight",
"[",
"contr",
"]",
"X_1_mean",
",",
"X_1_var",
"=",
"np",
".",
"apply_along_axis",
"(",
"lambda",
"x",
":",
"_get_wmean_wvar",
"(",
"x",
",",
"weight_1",
")",
",",
"0",
",",
"X_1",
")",
"X_0_mean",
",",
"X_0_var",
"=",
"np",
".",
"apply_along_axis",
"(",
"lambda",
"x",
":",
"_get_wmean_wvar",
"(",
"x",
",",
"weight_0",
")",
",",
"0",
",",
"X_0",
")",
"elif",
"not",
"weighted",
":",
"X_1_mean",
",",
"X_1_var",
"=",
"np",
".",
"apply_along_axis",
"(",
"lambda",
"x",
":",
"_get_mean_var",
"(",
"x",
")",
",",
"0",
",",
"X_1",
")",
"X_0_mean",
",",
"X_0_var",
"=",
"np",
".",
"apply_along_axis",
"(",
"lambda",
"x",
":",
"_get_mean_var",
"(",
"x",
")",
",",
"0",
",",
"X_0",
")",
"X_1_mean_cont",
",",
"X_1_var_cont",
"=",
"X_1_mean",
"[",
"cont_index",
"]",
",",
"X_1_var",
"[",
"cont_index",
"]",
"X_0_mean_cont",
",",
"X_0_var_cont",
"=",
"X_0_mean",
"[",
"cont_index",
"]",
",",
"X_0_var",
"[",
"cont_index",
"]",
"std_diffs_cont",
"=",
"(",
"(",
"X_1_mean_cont",
"-",
"X_0_mean_cont",
")",
"/",
"np",
".",
"sqrt",
"(",
"(",
"X_1_var_cont",
"+",
"X_0_var_cont",
")",
"/",
"2",
")",
")",
"X_1_mean_prop",
"=",
"X_1_mean",
"[",
"prop_index",
"]",
"X_0_mean_prop",
"=",
"X_0_mean",
"[",
"prop_index",
"]",
"std_diffs_prop",
"=",
"(",
"(",
"X_1_mean_prop",
"-",
"X_0_mean_prop",
")",
"/",
"np",
".",
"sqrt",
"(",
"(",
"(",
"X_1_mean_prop",
"*",
"(",
"1",
"-",
"X_1_mean_prop",
")",
")",
"+",
"(",
"X_0_mean_prop",
"*",
"(",
"1",
"-",
"X_0_mean_prop",
")",
")",
")",
"/",
"2",
")",
")",
"std_diffs",
"=",
"np",
".",
"concatenate",
"(",
"[",
"std_diffs_cont",
",",
"std_diffs_prop",
"]",
",",
"axis",
"=",
"0",
")",
"std_diffs_df",
"=",
"pd",
".",
"DataFrame",
"(",
"std_diffs",
",",
"index",
"=",
"cols",
")",
"return",
"std_diffs_df"
] | [
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.shape[1])]
prop = [X.iloc[:, i].nunique(
) == 2 for i in range(X.shape[1])]
cont_cols = list(X.loc[:, cont].columns)
prop_cols = list(X.loc[:, prop].columns)
dropped = set(X.columns) - set(cont_cols + prop_cols)
if dropped:
logger.info('Some non-binary variables were dropped because they had fewer than {} unique values or were of the \
dtype "cat". The dropped variables are: {}'.format(threshold, dropped))
return cont_cols, prop_cols | [
"def",
"_get_numeric_vars",
"(",
"X",
",",
"threshold",
"=",
"5",
")",
":",
"cont",
"=",
"[",
"(",
"not",
"hasattr",
"(",
"X",
".",
"iloc",
"[",
":",
",",
"i",
"]",
",",
"'cat'",
")",
")",
"and",
"(",
"X",
".",
"iloc",
"[",
":",
",",
"i",
"]",
".",
"nunique",
"(",
")",
">=",
"threshold",
")",
"for",
"i",
"in",
"range",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"prop",
"=",
"[",
"X",
".",
"iloc",
"[",
":",
",",
"i",
"]",
".",
"nunique",
"(",
")",
"==",
"2",
"for",
"i",
"in",
"range",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"cont_cols",
"=",
"list",
"(",
"X",
".",
"loc",
"[",
":",
",",
"cont",
"]",
".",
"columns",
")",
"prop_cols",
"=",
"list",
"(",
"X",
".",
"loc",
"[",
":",
",",
"prop",
"]",
".",
"columns",
")",
"dropped",
"=",
"set",
"(",
"X",
".",
"columns",
")",
"-",
"set",
"(",
"cont_cols",
"+",
"prop_cols",
")",
"if",
"dropped",
":",
"logger",
".",
"info",
"(",
"'Some non-binary variables were dropped because they had fewer than {} unique values or were of the \\\n dtype \"cat\". The dropped variables are: {}'",
".",
"format",
"(",
"threshold",
",",
"dropped",
")",
")",
"return",
"cont_cols",
",",
"prop_cols"
] | [
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
Observational Studies.
Statistics in Medicine 34 (28): 3661 79. https://doi.org/10.1002/sim.6607.
|
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 Estimate Causal Treatment Effects in
Observational Studies.
Statistics in Medicine 34 (28): 3661 79. https://doi.org/10.1002/sim.6607.
'''
weighted_mean = np.sum(weight * X) / np.sum(weight)
weighted_var = (np.sum(weight) / (np.power(np.sum(weight), 2) - np.sum(
np.power(weight, 2)))) * (np.sum(weight * np.power((X - weighted_mean), 2)))
return [weighted_mean, weighted_var] | [
"def",
"_get_wmean_wvar",
"(",
"X",
",",
"weight",
")",
":",
"weighted_mean",
"=",
"np",
".",
"sum",
"(",
"weight",
"*",
"X",
")",
"/",
"np",
".",
"sum",
"(",
"weight",
")",
"weighted_var",
"=",
"(",
"np",
".",
"sum",
"(",
"weight",
")",
"/",
"(",
"np",
".",
"power",
"(",
"np",
".",
"sum",
"(",
"weight",
")",
",",
"2",
")",
"-",
"np",
".",
"sum",
"(",
"np",
".",
"power",
"(",
"weight",
",",
"2",
")",
")",
")",
")",
"*",
"(",
"np",
".",
"sum",
"(",
"weight",
"*",
"np",
".",
"power",
"(",
"(",
"X",
"-",
"weighted_mean",
")",
",",
"2",
")",
")",
")",
"return",
"[",
"weighted_mean",
",",
"weighted_var",
"]"
] | [
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.funny_files = fcomp | [
"def",
"phase3",
"(",
"self",
")",
":",
"fcomp",
"=",
"filecmp",
".",
"cmpfiles",
"(",
"self",
".",
"left",
",",
"self",
".",
"right",
",",
"self",
".",
"common_files",
",",
"shallow",
"=",
"False",
")",
"self",
".",
"same_files",
",",
"self",
".",
"diff_files",
",",
"self",
".",
"funny_files",
"=",
"fcomp"
] | [
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
"""
urllib3_pool_manager = urllib3.PoolManager()
fetch_request = urllib3_pool_manager.request("GET", target)
if str(fetch_request.status)[:1] != "2" and fetch_request.status \
not in [301, 302]:
raise Exceptions.FetchError(
"Failed to fetch resource, returned HTTP status code " +
str(fetch_request.status) + ".") from None
else:
return fetch_request | [
"def",
"fetch",
"(",
"target",
":",
"str",
")",
"->",
"object",
":",
"urllib3_pool_manager",
"=",
"urllib3",
".",
"PoolManager",
"(",
")",
"fetch_request",
"=",
"urllib3_pool_manager",
".",
"request",
"(",
"\"GET\"",
",",
"target",
")",
"if",
"str",
"(",
"fetch_request",
".",
"status",
")",
"[",
":",
"1",
"]",
"!=",
"\"2\"",
"and",
"fetch_request",
".",
"status",
"not",
"in",
"[",
"301",
",",
"302",
"]",
":",
"raise",
"Exceptions",
".",
"FetchError",
"(",
"\"Failed to fetch resource, returned HTTP status code \"",
"+",
"str",
"(",
"fetch_request",
".",
"status",
")",
"+",
"\".\"",
")",
"from",
"None",
"else",
":",
"return",
"fetch_request"
] | [
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: path for splitting into component directories
:type whole: str
:return: contains components
:rtype: list
|
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 the return list as mentioned previously.
:param whole: path for splitting into component directories
:type whole: str
:return: contains components
:rtype: list
"""
# append components to this list, function return
dump = []
# remaining path after splitting previous component
previous = "/INITIAL/INITIAL"
while path.split(previous)[1] != "":
if previous == "/INITIAL/INITIAL":
previous = path.split(whole)[0]
else:
previous = path.split(previous)[0]
if previous != "/":
dump.append(previous)
return dump | [
"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",
".",
"split",
"(",
"previous",
")",
"[",
"1",
"]",
"!=",
"\"\"",
":",
"if",
"previous",
"==",
"\"/INITIAL/INITIAL\"",
":",
"previous",
"=",
"path",
".",
"split",
"(",
"whole",
")",
"[",
"0",
"]",
"else",
":",
"previous",
"=",
"path",
".",
"split",
"(",
"previous",
")",
"[",
"0",
"]",
"if",
"previous",
"!=",
"\"/\"",
":",
"dump",
".",
"append",
"(",
"previous",
")",
"return",
"dump"
] | [
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 target: str
:param suppress_version_check: if True VERSION/VERSIONS check is
ignored, unsafe, default is False
:type suppress_version_check: bool
:param suppress_name_check: if True NAME check is ignored, unsafe,
default is False
:type suppress_name_check: bool
:param skip_keep_check: if True Patcher does not check if files
listed under Keep exist, default is False
:type skip_keep_check: bool
|
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 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 target: str
:param suppress_version_check: if True VERSION/VERSIONS check is
ignored, unsafe, default is False
:type suppress_version_check: bool
:param suppress_name_check: if True NAME check is ignored, unsafe,
default is False
:type suppress_name_check: bool
:param skip_keep_check: if True Patcher does not check if files
listed under Keep exist, default is False
:type skip_keep_check: bool
"""
self.WORK_DIR = Patcher.create_work_directory()
self.patch = patch
self.target = target
if "https://" in patch[:8] or "http://" in patch[:8]:
patch_grab = Backend.fetch(patch)
with open(gettempdir() + self.WORK_DIR +
path.splitext(self.patch)[1], "w") as patch_data_dump:
patch_data_dump.write(patch_grab.data)
self.patch = gettempdir() + self.WORK_DIR + \
path.splitext(self.patch)[1]
else:
if path.isfile(self.patch) is False:
raise Exceptions.PatchError("Patch file with path " +
self.patch + " does not exist.")
if path.isdir(self.target) is False or not listdir(self.target):
raise Exceptions.TargetError("Target directory " + self.target +
" does not exist or is empty.")
unpack_archive(self.patch, gettempdir() + self.WORK_DIR)
try:
if suppress_name_check is False:
with open(gettempdir() + self.WORK_DIR + "/NAME") as \
patch_name_handle:
patch_name = patch_name_handle.read()
with open(self.target + "/NAME") as target_name_handle:
if target_name_handle.read() != patch_name:
raise Exceptions.PatchError(
"NAME files of target and patch are different. " +
"Target is " + target_name_handle.read() +
" and patch " + patch_name + ".")
except FileNotFoundError as ParentException:
raise Exceptions.PatchError("Missing NAME file(s).") from \
ParentException
try:
if suppress_version_check is False:
with open(gettempdir() + self.WORK_DIR + "/VERSIONS") as \
versions_handle:
patch_versions = versions_handle.read()
self.patch_versions = patch_versions.split(" -> ")
with open(path.join(target, "VERSION")) as version_handle:
current_version = version_handle.read()
if current_version != self.patch_versions[0]:
raise Exceptions.VersionError(
"VERSIONS file specifies a different upgrade-from " +
"version compared to the target VERSION file. " +
"Target is on " + current_version +
", and patch supporting " + self.patch_versions[0] +
".")
except FileNotFoundError as ParentException:
raise Exceptions.VersionError("Missing VERSION(S) file(s).") from \
ParentException
try:
with open(gettempdir() + self.WORK_DIR + "/CHANGE.json") as \
changelog_handle:
self.change = jsonload(changelog_handle)
except FileNotFoundError as ParentException:
raise Exceptions.PatchError(
"CHANGE.json file of patch archive is missing.") from \
ParentException
for x in self.change:
self.change[x] = self.change[x].strip("[]").split(", ")
for y in range(0, len(self.change[x])):
self.change[x][y] = self.change[x][y].strip("'")
if skip_keep_check is False:
for x in range(0, len(self.change["keep"])):
if path.isdir(path.join(self.target, self.change["keep"][x])) \
is not True and path.isfile(
path.join(self.target, self.change["keep"][x])) \
is not True:
raise Exceptions.TargetError(
"Target missing item(s) that should exist, listed " +
"under the keep operation. Raised on " +
self.change["keep"][x] + ".")
for x in range(0, len(self.change["add"])):
if path.isdir(gettempdir() + self.WORK_DIR + "/add/" +
self.change["add"][x]) is not True and path.isfile(
gettempdir() + self.WORK_DIR + "/add/" +
self.change["add"][x]) is not True:
raise Exceptions.PatchError(
"Missing item(s) for addition. Raised on " +
self.change["add"][x] + ".")
for x in range(0, len(self.change["replace"])):
if path.isdir(gettempdir() + self.WORK_DIR + "/replace/" +
self.change["replace"][x]) is not True and \
path.isfile(gettempdir() + self.WORK_DIR +
"/replace/" + self.change["replace"]
[x]) is not True:
raise Exceptions.PatchError(
"Missing item(s) for replacement. Raised on " +
self.change["replace"][x] + ".")
for x in range(0, len(self.change["add"])):
component = \
Backend.directory_split_recursive(self.change["add"][x])
for a in component:
if path.isdir(path.join(self.target, a)) is False:
mkdir(path.join(self.target, a))
if path.isfile(gettempdir() + self.WORK_DIR + "/add/" +
self.change["add"][x]):
copyfile(gettempdir() + self.WORK_DIR + "/add/" +
self.change["add"][x],
path.join(self.target, self.change["add"][x]))
if path.isdir(gettempdir() + self.WORK_DIR + "/add/" +
self.change["add"][x]):
copytree(gettempdir() + self.WORK_DIR + "/add/" +
self.change["add"][x],
path.join(self.target, self.change["add"][x]))
for x in range(0, len(self.change["replace"])):
if path.isfile(path.join(self.target,
self.change["replace"][x])) is True:
remove(path.join(self.target, self.change["replace"][x]))
copyfile(gettempdir() + self.WORK_DIR + "/replace/" +
self.change["replace"][x],
path.join(self.target, self.change["replace"][x]))
elif path.isdir(path.join(self.target,
self.change["replace"][x])) is True:
rmtree(path.join(self.target, self.change["replace"][x]))
copytree(gettempdir() + self.WORK_DIR + "/replace/" +
self.change["replace"][x],
path.join(self.target, self.change["replace"][x]))
else:
raise Exceptions.TargetError(
"Target " + self.change["replace"][x] +
" for replacement does not exist.")
for x in range(0, len(self.change["remove"])):
if path.isdir(path.join(self.target,
self.change["remove"][x])) is True:
rmtree(path.join(self.target,
self.change["remove"][x]))
elif path.isfile(path.join(self.target,
self.change["remove"][x])) is True:
remove(path.join(self.target, self.change["remove"][x]))
else:
raise Exceptions.TargetError(
"Target " + self.change["remove"][x] +
" for removal does not exist, or is not a file or" +
" directory.")
with open(self.target + "/VERSION", "w") as version_overwrite_handle:
# this is redundant, VERSION gets overwritten by replace anyways,
# since Weave detects two different version files automatically
# if one day this module needed to be slimmed down, remove this
# for a slight amount of I/O performance gain
version_overwrite_handle.truncate(0)
version_overwrite_handle.write(self.patch_versions[1])
rmtree(gettempdir() + self.WORK_DIR) | [
"def",
"__init__",
"(",
"self",
",",
"patch",
":",
"str",
",",
"target",
":",
"str",
",",
"suppress_version_check",
":",
"bool",
"=",
"False",
",",
"suppress_name_check",
":",
"bool",
"=",
"False",
",",
"skip_keep_check",
":",
"bool",
"=",
"False",
")",
":",
"self",
".",
"WORK_DIR",
"=",
"Patcher",
".",
"create_work_directory",
"(",
")",
"self",
".",
"patch",
"=",
"patch",
"self",
".",
"target",
"=",
"target",
"if",
"\"https://\"",
"in",
"patch",
"[",
":",
"8",
"]",
"or",
"\"http://\"",
"in",
"patch",
"[",
":",
"8",
"]",
":",
"patch_grab",
"=",
"Backend",
".",
"fetch",
"(",
"patch",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"path",
".",
"splitext",
"(",
"self",
".",
"patch",
")",
"[",
"1",
"]",
",",
"\"w\"",
")",
"as",
"patch_data_dump",
":",
"patch_data_dump",
".",
"write",
"(",
"patch_grab",
".",
"data",
")",
"self",
".",
"patch",
"=",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"path",
".",
"splitext",
"(",
"self",
".",
"patch",
")",
"[",
"1",
"]",
"else",
":",
"if",
"path",
".",
"isfile",
"(",
"self",
".",
"patch",
")",
"is",
"False",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"Patch file with path \"",
"+",
"self",
".",
"patch",
"+",
"\" does not exist.\"",
")",
"if",
"path",
".",
"isdir",
"(",
"self",
".",
"target",
")",
"is",
"False",
"or",
"not",
"listdir",
"(",
"self",
".",
"target",
")",
":",
"raise",
"Exceptions",
".",
"TargetError",
"(",
"\"Target directory \"",
"+",
"self",
".",
"target",
"+",
"\" does not exist or is empty.\"",
")",
"unpack_archive",
"(",
"self",
".",
"patch",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
")",
"try",
":",
"if",
"suppress_name_check",
"is",
"False",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/NAME\"",
")",
"as",
"patch_name_handle",
":",
"patch_name",
"=",
"patch_name_handle",
".",
"read",
"(",
")",
"with",
"open",
"(",
"self",
".",
"target",
"+",
"\"/NAME\"",
")",
"as",
"target_name_handle",
":",
"if",
"target_name_handle",
".",
"read",
"(",
")",
"!=",
"patch_name",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"NAME files of target and patch are different. \"",
"+",
"\"Target is \"",
"+",
"target_name_handle",
".",
"read",
"(",
")",
"+",
"\" and patch \"",
"+",
"patch_name",
"+",
"\".\"",
")",
"except",
"FileNotFoundError",
"as",
"ParentException",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"Missing NAME file(s).\"",
")",
"from",
"ParentException",
"try",
":",
"if",
"suppress_version_check",
"is",
"False",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/VERSIONS\"",
")",
"as",
"versions_handle",
":",
"patch_versions",
"=",
"versions_handle",
".",
"read",
"(",
")",
"self",
".",
"patch_versions",
"=",
"patch_versions",
".",
"split",
"(",
"\" -> \"",
")",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"target",
",",
"\"VERSION\"",
")",
")",
"as",
"version_handle",
":",
"current_version",
"=",
"version_handle",
".",
"read",
"(",
")",
"if",
"current_version",
"!=",
"self",
".",
"patch_versions",
"[",
"0",
"]",
":",
"raise",
"Exceptions",
".",
"VersionError",
"(",
"\"VERSIONS file specifies a different upgrade-from \"",
"+",
"\"version compared to the target VERSION file. \"",
"+",
"\"Target is on \"",
"+",
"current_version",
"+",
"\", and patch supporting \"",
"+",
"self",
".",
"patch_versions",
"[",
"0",
"]",
"+",
"\".\"",
")",
"except",
"FileNotFoundError",
"as",
"ParentException",
":",
"raise",
"Exceptions",
".",
"VersionError",
"(",
"\"Missing VERSION(S) file(s).\"",
")",
"from",
"ParentException",
"try",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/CHANGE.json\"",
")",
"as",
"changelog_handle",
":",
"self",
".",
"change",
"=",
"jsonload",
"(",
"changelog_handle",
")",
"except",
"FileNotFoundError",
"as",
"ParentException",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"CHANGE.json file of patch archive is missing.\"",
")",
"from",
"ParentException",
"for",
"x",
"in",
"self",
".",
"change",
":",
"self",
".",
"change",
"[",
"x",
"]",
"=",
"self",
".",
"change",
"[",
"x",
"]",
".",
"strip",
"(",
"\"[]\"",
")",
".",
"split",
"(",
"\", \"",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"x",
"]",
")",
")",
":",
"self",
".",
"change",
"[",
"x",
"]",
"[",
"y",
"]",
"=",
"self",
".",
"change",
"[",
"x",
"]",
"[",
"y",
"]",
".",
"strip",
"(",
"\"'\"",
")",
"if",
"skip_keep_check",
"is",
"False",
":",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"\"keep\"",
"]",
")",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"keep\"",
"]",
"[",
"x",
"]",
")",
")",
"is",
"not",
"True",
"and",
"path",
".",
"isfile",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"keep\"",
"]",
"[",
"x",
"]",
")",
")",
"is",
"not",
"True",
":",
"raise",
"Exceptions",
".",
"TargetError",
"(",
"\"Target missing item(s) that should exist, listed \"",
"+",
"\"under the keep operation. Raised on \"",
"+",
"self",
".",
"change",
"[",
"\"keep\"",
"]",
"[",
"x",
"]",
"+",
"\".\"",
")",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"\"add\"",
"]",
")",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/add/\"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
"is",
"not",
"True",
"and",
"path",
".",
"isfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/add/\"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
"is",
"not",
"True",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"Missing item(s) for addition. Raised on \"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
"+",
"\".\"",
")",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
")",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/replace/\"",
"+",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
"is",
"not",
"True",
"and",
"path",
".",
"isfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/replace/\"",
"+",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
"is",
"not",
"True",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"Missing item(s) for replacement. Raised on \"",
"+",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
"+",
"\".\"",
")",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"\"add\"",
"]",
")",
")",
":",
"component",
"=",
"Backend",
".",
"directory_split_recursive",
"(",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
"for",
"a",
"in",
"component",
":",
"if",
"path",
".",
"isdir",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"a",
")",
")",
"is",
"False",
":",
"mkdir",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"a",
")",
")",
"if",
"path",
".",
"isfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/add/\"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
":",
"copyfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/add/\"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
",",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
")",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/add/\"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
":",
"copytree",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/add/\"",
"+",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
",",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"add\"",
"]",
"[",
"x",
"]",
")",
")",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
")",
")",
":",
"if",
"path",
".",
"isfile",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
")",
"is",
"True",
":",
"remove",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
")",
"copyfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/replace/\"",
"+",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
",",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
")",
"elif",
"path",
".",
"isdir",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
")",
"is",
"True",
":",
"rmtree",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
")",
"copytree",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/replace/\"",
"+",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
",",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
")",
")",
"else",
":",
"raise",
"Exceptions",
".",
"TargetError",
"(",
"\"Target \"",
"+",
"self",
".",
"change",
"[",
"\"replace\"",
"]",
"[",
"x",
"]",
"+",
"\" for replacement does not exist.\"",
")",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"change",
"[",
"\"remove\"",
"]",
")",
")",
":",
"if",
"path",
".",
"isdir",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"remove\"",
"]",
"[",
"x",
"]",
")",
")",
"is",
"True",
":",
"rmtree",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"remove\"",
"]",
"[",
"x",
"]",
")",
")",
"elif",
"path",
".",
"isfile",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"remove\"",
"]",
"[",
"x",
"]",
")",
")",
"is",
"True",
":",
"remove",
"(",
"path",
".",
"join",
"(",
"self",
".",
"target",
",",
"self",
".",
"change",
"[",
"\"remove\"",
"]",
"[",
"x",
"]",
")",
")",
"else",
":",
"raise",
"Exceptions",
".",
"TargetError",
"(",
"\"Target \"",
"+",
"self",
".",
"change",
"[",
"\"remove\"",
"]",
"[",
"x",
"]",
"+",
"\" for removal does not exist, or is not a file or\"",
"+",
"\" directory.\"",
")",
"with",
"open",
"(",
"self",
".",
"target",
"+",
"\"/VERSION\"",
",",
"\"w\"",
")",
"as",
"version_overwrite_handle",
":",
"# this is redundant, VERSION gets overwritten by replace anyways,",
"# since Weave detects two different version files automatically",
"# if one day this module needed to be slimmed down, remove this",
"# for a slight amount of I/O performance gain",
"version_overwrite_handle",
".",
"truncate",
"(",
"0",
")",
"version_overwrite_handle",
".",
"write",
"(",
"self",
".",
"patch_versions",
"[",
"1",
"]",
")",
"rmtree",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
")"
] | [
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(time()).encode(encoding="ascii", errors="replace")).hexdigest()
mkdir(gettempdir() + identifier)
return identifier | [
"def",
"create_work_directory",
"(",
")",
"->",
"str",
":",
"identifier",
"=",
"\"/bandage_patcher_session_\"",
"+",
"md5",
"(",
"str",
"(",
"time",
"(",
")",
")",
".",
"encode",
"(",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"replace\"",
")",
")",
".",
"hexdigest",
"(",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
")",
"return",
"identifier"
] | [
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 release file
:type release_new: str
:param output_path: path to output archive, if archive already exists,
deletes archive and "overwrites" it with the new archive file
:type output_path: str
:param set_name: new patch NAME file, if not None,
NAME check is ignored, default None
:type set_name: Union[str, None]
:param suppress_missing_versions: if True missing versions error is
ignored, Supply class cannot detect the release automatically,
Patcher must be directed to the patch archive manually, default
False
:type suppress_missing_versions: bool
|
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 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 release file
:type release_new: str
:param output_path: path to output archive, if archive already exists,
deletes archive and "overwrites" it with the new archive file
:type output_path: str
:param set_name: new patch NAME file, if not None,
NAME check is ignored, default None
:type set_name: Union[str, None]
:param suppress_missing_versions: if True missing versions error is
ignored, Supply class cannot detect the release automatically,
Patcher must be directed to the patch archive manually, default
False
:type suppress_missing_versions: bool
"""
self.WORK_DIR = Weave.create_work_directory()
self.release_old = release_old
self.release_new = release_new
if path.isdir(output_path) is False:
raise Exceptions.PatchError("Specified output directory " +
output_path + " is not a directory.")
if "https://" in self.release_old[:8] or "http://" in \
self.release_old[:8]:
release_old_grab = Backend.fetch(self.release_old)
with open(gettempdir() + self.WORK_DIR + "/old/" +
path.splitext(self.release_old)[1], "w") as \
release_old_data_dump:
release_old_data_dump.write(release_old_grab.data)
self.release_old = gettempdir() + self.WORK_DIR + "/old/" + \
path.splitext(self.release_old)[1]
else:
if path.isfile(self.release_old) is False:
raise Exceptions.ReleaseError(
"Old release file " + self.release_old +
" does not exist.")
if "https://" in self.release_new[:8] or "http://" in \
self.release_new[:8]:
release_new_grab = Backend.fetch(self.release_new)
with open(gettempdir() + self.WORK_DIR + "/new/" +
path.splitext(self.release_new)[1], "w") as \
release_new_data_dump:
release_new_data_dump.write(release_new_grab.data)
self.release_new = gettempdir() + self.WORK_DIR + "/new/" + \
path.splitext(self.release_new)[1]
else:
if path.isfile(self.release_new) is False:
raise Exceptions.ReleaseError(
"New release file " + self.release_new +
" does not exist.")
unpack_archive(self.release_old, gettempdir() +
self.WORK_DIR + "/old/")
unpack_archive(self.release_new, gettempdir() +
self.WORK_DIR + "/new/")
try:
with open(gettempdir() + self.WORK_DIR + "/old/NAME") as \
release_name_handle:
self.release_name_old = release_name_handle.read()
with open(gettempdir() + self.WORK_DIR + "/new/NAME") as \
release_name_handle:
self.release_name_new = release_name_handle.read()
if self.release_name_new != self.release_name_old and \
set_name is None:
raise Exceptions.ReleaseError(
"NAME files of old and new releases do not match." +
" Old is " + self.release_name_old + " and new " +
self.release_name_new + ".")
except FileNotFoundError as ParentException:
if set_name is not None:
raise Exceptions.ReleaseError(
"NAME files of old and new releases are missing.") from \
ParentException
try:
with open(gettempdir() + self.WORK_DIR + "/old/VERSION") as \
release_version_handle:
self.release_version_old = release_version_handle.read()
with open(gettempdir() + self.WORK_DIR + "/new/VERSION") as \
release_version_handle:
self.release_version_new = release_version_handle.read()
except FileNotFoundError as ParentException:
if suppress_missing_versions is False:
raise Exceptions.VersionError(
"VERSION files of old and new releases are missing.") \
from ParentException
else:
self.release_version_old = "NaN"
self.release_version_new = "NaN"
if suppress_missing_versions is False and \
len(self.release_version_old.split(" -> ")) != 1 or \
len(self.release_version_new.split(" -> ")) != 1:
raise Exceptions.UnableToParseError(
'Release versions contain " -> " which will disrupt Patcher ' +
'when trying to read the VERSIONS header.')
self.index = Weave.comparison(self)
with open(gettempdir() + self.WORK_DIR + "/patch/CHANGE.json", "w") \
as changelog_dump_handle:
jsondump({"remove": str(self.index[0]), "add": str(self.index[1]),
"keep": str(self.index[2]),
"replace": str(self.index[3])}, changelog_dump_handle)
for x in range(0, len(self.index[1])):
component = Backend.directory_split_recursive(self.index[1][x])
for a in component:
if path.isdir(gettempdir() +
self.WORK_DIR + "/patch/add/" + a) is False:
mkdir(gettempdir() + self.WORK_DIR + "/patch/add/" + a)
if path.isfile(gettempdir() +
self.WORK_DIR + "/new/" + self.index[1][x]) is True:
copyfile(gettempdir() + self.WORK_DIR + "/new/" +
self.index[1][x], gettempdir() + self.WORK_DIR +
"/patch/add/" + self.index[1][x])
if path.isdir(gettempdir() +
self.WORK_DIR + "/new/" + self.index[1][x]) is True:
copytree(gettempdir() + self.WORK_DIR + "/new/" +
self.index[1][x], gettempdir() + self.WORK_DIR +
"/patch/add/" + self.index[1][x])
for y in range(0, len(self.index[3])):
component = Backend.directory_split_recursive(self.index[3][y])
for b in component:
if path.isdir(gettempdir() +
self.WORK_DIR + "/patch/replace/" + b) is False:
mkdir(gettempdir() + self.WORK_DIR + "/patch/replace/" + b)
if path.isfile(gettempdir() +
self.WORK_DIR + "/new/" + self.index[3][y]) is True:
copyfile(gettempdir() + self.WORK_DIR + "/new/" +
self.index[3][y], gettempdir() + self.WORK_DIR +
"/patch/replace/" + self.index[3][y])
if path.isdir(gettempdir() +
self.WORK_DIR + "/new/" + self.index[3][y]) is True:
copytree(gettempdir() + self.WORK_DIR + "/new/" +
self.index[3][y], gettempdir() + self.WORK_DIR +
"/patch/replace/" + self.index[3][y])
with open(gettempdir() + self.WORK_DIR + "/patch/VERSIONS", "w") as \
release_version_handle:
release_version_handle.write(self.release_version_old + " -> " +
self.release_version_new)
if set_name is None:
with open(gettempdir() + self.WORK_DIR + "/patch/NAME", "w") as \
release_name_handle:
release_name_handle.write(self.release_name_new)
base_name = output_path + self.release_name_new + "_" + \
self.release_version_old + "_to_" + \
self.release_version_new + "_bandage_patch"
make_archive(root_dir=gettempdir() + self.WORK_DIR + "/patch/",
base_name=base_name, format="zip")
else:
with open(gettempdir() + self.WORK_DIR + "/patch/NAME", "w") as \
release_name_handle:
release_name_handle.write(set_name)
base_name = (output_path + set_name + "_" +
self.release_version_old + "_to_" +
self.release_version_new + "_bandage_patch")
make_archive(root_dir=gettempdir() + self.WORK_DIR + "/patch/",
base_name=base_name, format="zip")
# TODO archive checksum generation
rmtree(gettempdir() + self.WORK_DIR) | [
"def",
"__init__",
"(",
"self",
",",
"release_old",
":",
"str",
",",
"release_new",
":",
"str",
",",
"output_path",
":",
"str",
",",
"set_name",
":",
"Union",
"[",
"str",
",",
"None",
"]",
"=",
"None",
",",
"suppress_missing_versions",
":",
"bool",
"=",
"False",
")",
":",
"self",
".",
"WORK_DIR",
"=",
"Weave",
".",
"create_work_directory",
"(",
")",
"self",
".",
"release_old",
"=",
"release_old",
"self",
".",
"release_new",
"=",
"release_new",
"if",
"path",
".",
"isdir",
"(",
"output_path",
")",
"is",
"False",
":",
"raise",
"Exceptions",
".",
"PatchError",
"(",
"\"Specified output directory \"",
"+",
"output_path",
"+",
"\" is not a directory.\"",
")",
"if",
"\"https://\"",
"in",
"self",
".",
"release_old",
"[",
":",
"8",
"]",
"or",
"\"http://\"",
"in",
"self",
".",
"release_old",
"[",
":",
"8",
"]",
":",
"release_old_grab",
"=",
"Backend",
".",
"fetch",
"(",
"self",
".",
"release_old",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
"+",
"path",
".",
"splitext",
"(",
"self",
".",
"release_old",
")",
"[",
"1",
"]",
",",
"\"w\"",
")",
"as",
"release_old_data_dump",
":",
"release_old_data_dump",
".",
"write",
"(",
"release_old_grab",
".",
"data",
")",
"self",
".",
"release_old",
"=",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
"+",
"path",
".",
"splitext",
"(",
"self",
".",
"release_old",
")",
"[",
"1",
"]",
"else",
":",
"if",
"path",
".",
"isfile",
"(",
"self",
".",
"release_old",
")",
"is",
"False",
":",
"raise",
"Exceptions",
".",
"ReleaseError",
"(",
"\"Old release file \"",
"+",
"self",
".",
"release_old",
"+",
"\" does not exist.\"",
")",
"if",
"\"https://\"",
"in",
"self",
".",
"release_new",
"[",
":",
"8",
"]",
"or",
"\"http://\"",
"in",
"self",
".",
"release_new",
"[",
":",
"8",
"]",
":",
"release_new_grab",
"=",
"Backend",
".",
"fetch",
"(",
"self",
".",
"release_new",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"path",
".",
"splitext",
"(",
"self",
".",
"release_new",
")",
"[",
"1",
"]",
",",
"\"w\"",
")",
"as",
"release_new_data_dump",
":",
"release_new_data_dump",
".",
"write",
"(",
"release_new_grab",
".",
"data",
")",
"self",
".",
"release_new",
"=",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"path",
".",
"splitext",
"(",
"self",
".",
"release_new",
")",
"[",
"1",
"]",
"else",
":",
"if",
"path",
".",
"isfile",
"(",
"self",
".",
"release_new",
")",
"is",
"False",
":",
"raise",
"Exceptions",
".",
"ReleaseError",
"(",
"\"New release file \"",
"+",
"self",
".",
"release_new",
"+",
"\" does not exist.\"",
")",
"unpack_archive",
"(",
"self",
".",
"release_old",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
")",
"unpack_archive",
"(",
"self",
".",
"release_new",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
")",
"try",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/NAME\"",
")",
"as",
"release_name_handle",
":",
"self",
".",
"release_name_old",
"=",
"release_name_handle",
".",
"read",
"(",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/NAME\"",
")",
"as",
"release_name_handle",
":",
"self",
".",
"release_name_new",
"=",
"release_name_handle",
".",
"read",
"(",
")",
"if",
"self",
".",
"release_name_new",
"!=",
"self",
".",
"release_name_old",
"and",
"set_name",
"is",
"None",
":",
"raise",
"Exceptions",
".",
"ReleaseError",
"(",
"\"NAME files of old and new releases do not match.\"",
"+",
"\" Old is \"",
"+",
"self",
".",
"release_name_old",
"+",
"\" and new \"",
"+",
"self",
".",
"release_name_new",
"+",
"\".\"",
")",
"except",
"FileNotFoundError",
"as",
"ParentException",
":",
"if",
"set_name",
"is",
"not",
"None",
":",
"raise",
"Exceptions",
".",
"ReleaseError",
"(",
"\"NAME files of old and new releases are missing.\"",
")",
"from",
"ParentException",
"try",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/VERSION\"",
")",
"as",
"release_version_handle",
":",
"self",
".",
"release_version_old",
"=",
"release_version_handle",
".",
"read",
"(",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/VERSION\"",
")",
"as",
"release_version_handle",
":",
"self",
".",
"release_version_new",
"=",
"release_version_handle",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
"as",
"ParentException",
":",
"if",
"suppress_missing_versions",
"is",
"False",
":",
"raise",
"Exceptions",
".",
"VersionError",
"(",
"\"VERSION files of old and new releases are missing.\"",
")",
"from",
"ParentException",
"else",
":",
"self",
".",
"release_version_old",
"=",
"\"NaN\"",
"self",
".",
"release_version_new",
"=",
"\"NaN\"",
"if",
"suppress_missing_versions",
"is",
"False",
"and",
"len",
"(",
"self",
".",
"release_version_old",
".",
"split",
"(",
"\" -> \"",
")",
")",
"!=",
"1",
"or",
"len",
"(",
"self",
".",
"release_version_new",
".",
"split",
"(",
"\" -> \"",
")",
")",
"!=",
"1",
":",
"raise",
"Exceptions",
".",
"UnableToParseError",
"(",
"'Release versions contain \" -> \" which will disrupt Patcher '",
"+",
"'when trying to read the VERSIONS header.'",
")",
"self",
".",
"index",
"=",
"Weave",
".",
"comparison",
"(",
"self",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/CHANGE.json\"",
",",
"\"w\"",
")",
"as",
"changelog_dump_handle",
":",
"jsondump",
"(",
"{",
"\"remove\"",
":",
"str",
"(",
"self",
".",
"index",
"[",
"0",
"]",
")",
",",
"\"add\"",
":",
"str",
"(",
"self",
".",
"index",
"[",
"1",
"]",
")",
",",
"\"keep\"",
":",
"str",
"(",
"self",
".",
"index",
"[",
"2",
"]",
")",
",",
"\"replace\"",
":",
"str",
"(",
"self",
".",
"index",
"[",
"3",
"]",
")",
"}",
",",
"changelog_dump_handle",
")",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"index",
"[",
"1",
"]",
")",
")",
":",
"component",
"=",
"Backend",
".",
"directory_split_recursive",
"(",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
")",
"for",
"a",
"in",
"component",
":",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/add/\"",
"+",
"a",
")",
"is",
"False",
":",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/add/\"",
"+",
"a",
")",
"if",
"path",
".",
"isfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
")",
"is",
"True",
":",
"copyfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/add/\"",
"+",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
")",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
")",
"is",
"True",
":",
"copytree",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/add/\"",
"+",
"self",
".",
"index",
"[",
"1",
"]",
"[",
"x",
"]",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"index",
"[",
"3",
"]",
")",
")",
":",
"component",
"=",
"Backend",
".",
"directory_split_recursive",
"(",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
")",
"for",
"b",
"in",
"component",
":",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/replace/\"",
"+",
"b",
")",
"is",
"False",
":",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/replace/\"",
"+",
"b",
")",
"if",
"path",
".",
"isfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
")",
"is",
"True",
":",
"copyfile",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/replace/\"",
"+",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
")",
"if",
"path",
".",
"isdir",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
")",
"is",
"True",
":",
"copytree",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/replace/\"",
"+",
"self",
".",
"index",
"[",
"3",
"]",
"[",
"y",
"]",
")",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/VERSIONS\"",
",",
"\"w\"",
")",
"as",
"release_version_handle",
":",
"release_version_handle",
".",
"write",
"(",
"self",
".",
"release_version_old",
"+",
"\" -> \"",
"+",
"self",
".",
"release_version_new",
")",
"if",
"set_name",
"is",
"None",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/NAME\"",
",",
"\"w\"",
")",
"as",
"release_name_handle",
":",
"release_name_handle",
".",
"write",
"(",
"self",
".",
"release_name_new",
")",
"base_name",
"=",
"output_path",
"+",
"self",
".",
"release_name_new",
"+",
"\"_\"",
"+",
"self",
".",
"release_version_old",
"+",
"\"_to_\"",
"+",
"self",
".",
"release_version_new",
"+",
"\"_bandage_patch\"",
"make_archive",
"(",
"root_dir",
"=",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/\"",
",",
"base_name",
"=",
"base_name",
",",
"format",
"=",
"\"zip\"",
")",
"else",
":",
"with",
"open",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/NAME\"",
",",
"\"w\"",
")",
"as",
"release_name_handle",
":",
"release_name_handle",
".",
"write",
"(",
"set_name",
")",
"base_name",
"=",
"(",
"output_path",
"+",
"set_name",
"+",
"\"_\"",
"+",
"self",
".",
"release_version_old",
"+",
"\"_to_\"",
"+",
"self",
".",
"release_version_new",
"+",
"\"_bandage_patch\"",
")",
"make_archive",
"(",
"root_dir",
"=",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/patch/\"",
",",
"base_name",
"=",
"base_name",
",",
"format",
"=",
"\"zip\"",
")",
"# TODO archive checksum generation",
"rmtree",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
")"
] | [
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(time()).encode(encoding="ascii", errors="replace")
).hexdigest()
mkdir(gettempdir() + identifier)
mkdir(gettempdir() + identifier + "/old")
mkdir(gettempdir() + identifier + "/new")
mkdir(gettempdir() + identifier + "/patch")
mkdir(gettempdir() + identifier + "/patch/add")
mkdir(gettempdir() + identifier + "/patch/replace")
return identifier | [
"def",
"create_work_directory",
"(",
")",
"->",
"str",
":",
"identifier",
"=",
"\"/bandage_weave_session_\"",
"+",
"md5",
"(",
"str",
"(",
"time",
"(",
")",
")",
".",
"encode",
"(",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"replace\"",
")",
")",
".",
"hexdigest",
"(",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
"+",
"\"/old\"",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
"+",
"\"/new\"",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
"+",
"\"/patch\"",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
"+",
"\"/patch/add\"",
")",
"mkdir",
"(",
"gettempdir",
"(",
")",
"+",
"identifier",
"+",
"\"/patch/replace\"",
")",
"return",
"identifier"
] | [
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(gettempdir() + self.WORK_DIR + "/old/", gettempdir() +
self.WORK_DIR + "/new/").report_full_closure()
raw = handle.getvalue().split("\n")
dump = [[], [], [], []]
# directory path appends for old and new archive,
# allows for handling of sub-directories.
parsing_directory = ""
for x in range(0, len(raw)):
if raw[x][:4] == "diff":
if len(raw[x].split(" ")) != 3:
raise Exceptions.UnableToParseError(
"Release archives contain directories with spaces" +
" in their names. This breaks comparison " +
"interpretation.") from None
parsing_directory = \
raw[x].split(" ")[1].lstrip(gettempdir()).lstrip(
self.WORK_DIR).lstrip("/old/")
if parsing_directory != "":
parsing_directory += "/"
if raw[x][:(8 + len(
gettempdir() + self.WORK_DIR + "/old/"))] == "Only in " + \
gettempdir() + self.WORK_DIR + "/old/":
for_extend = raw[x].lstrip(
"Only in " + gettempdir() + self.WORK_DIR + "/old/" +
parsing_directory).strip("[]").split(", ")
for y in range(0, len(for_extend)):
for_extend[y] = parsing_directory + \
for_extend[y].strip("'")
dump[0].extend(for_extend)
if raw[x][:(8 + len(
gettempdir() + self.WORK_DIR + "/new/"))] == "Only in " + \
gettempdir() + self.WORK_DIR + "/new/":
for_extend = raw[x].lstrip(
"Only in " + gettempdir() + self.WORK_DIR + "/new/" +
parsing_directory).strip("[]").split(", ")
for y in range(0, len(for_extend)):
for_extend[y] = parsing_directory + \
for_extend[y].strip("'")
dump[1].extend(for_extend)
if raw[x][:18] == "Identical files : ":
for_extend = \
raw[x].lstrip("Identical files : ").strip("[]").split(", ")
for y in range(0, len(for_extend)):
for_extend[y] = \
parsing_directory + for_extend[y].strip("'")
dump[2].extend(for_extend)
if raw[x][:18] == "Differing files : ":
for_extend = \
raw[x].lstrip("Differing files : ").strip("[]").split(", ")
for y in range(0, len(for_extend)):
for_extend[y] = \
parsing_directory + for_extend[y].strip("'")
dump[3].extend(for_extend)
return dump | [
"def",
"comparison",
"(",
"self",
")",
"->",
"list",
":",
"handle",
"=",
"StringIO",
"(",
")",
"with",
"redirect_stdout",
"(",
"handle",
")",
":",
"dircmp",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
",",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
")",
".",
"report_full_closure",
"(",
")",
"raw",
"=",
"handle",
".",
"getvalue",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"dump",
"=",
"[",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"]",
"# directory path appends for old and new archive,",
"# allows for handling of sub-directories.",
"parsing_directory",
"=",
"\"\"",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"raw",
")",
")",
":",
"if",
"raw",
"[",
"x",
"]",
"[",
":",
"4",
"]",
"==",
"\"diff\"",
":",
"if",
"len",
"(",
"raw",
"[",
"x",
"]",
".",
"split",
"(",
"\" \"",
")",
")",
"!=",
"3",
":",
"raise",
"Exceptions",
".",
"UnableToParseError",
"(",
"\"Release archives contain directories with spaces\"",
"+",
"\" in their names. This breaks comparison \"",
"+",
"\"interpretation.\"",
")",
"from",
"None",
"parsing_directory",
"=",
"raw",
"[",
"x",
"]",
".",
"split",
"(",
"\" \"",
")",
"[",
"1",
"]",
".",
"lstrip",
"(",
"gettempdir",
"(",
")",
")",
".",
"lstrip",
"(",
"self",
".",
"WORK_DIR",
")",
".",
"lstrip",
"(",
"\"/old/\"",
")",
"if",
"parsing_directory",
"!=",
"\"\"",
":",
"parsing_directory",
"+=",
"\"/\"",
"if",
"raw",
"[",
"x",
"]",
"[",
":",
"(",
"8",
"+",
"len",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
")",
")",
"]",
"==",
"\"Only in \"",
"+",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
":",
"for_extend",
"=",
"raw",
"[",
"x",
"]",
".",
"lstrip",
"(",
"\"Only in \"",
"+",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/old/\"",
"+",
"parsing_directory",
")",
".",
"strip",
"(",
"\"[]\"",
")",
".",
"split",
"(",
"\", \"",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"for_extend",
")",
")",
":",
"for_extend",
"[",
"y",
"]",
"=",
"parsing_directory",
"+",
"for_extend",
"[",
"y",
"]",
".",
"strip",
"(",
"\"'\"",
")",
"dump",
"[",
"0",
"]",
".",
"extend",
"(",
"for_extend",
")",
"if",
"raw",
"[",
"x",
"]",
"[",
":",
"(",
"8",
"+",
"len",
"(",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
")",
")",
"]",
"==",
"\"Only in \"",
"+",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
":",
"for_extend",
"=",
"raw",
"[",
"x",
"]",
".",
"lstrip",
"(",
"\"Only in \"",
"+",
"gettempdir",
"(",
")",
"+",
"self",
".",
"WORK_DIR",
"+",
"\"/new/\"",
"+",
"parsing_directory",
")",
".",
"strip",
"(",
"\"[]\"",
")",
".",
"split",
"(",
"\", \"",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"for_extend",
")",
")",
":",
"for_extend",
"[",
"y",
"]",
"=",
"parsing_directory",
"+",
"for_extend",
"[",
"y",
"]",
".",
"strip",
"(",
"\"'\"",
")",
"dump",
"[",
"1",
"]",
".",
"extend",
"(",
"for_extend",
")",
"if",
"raw",
"[",
"x",
"]",
"[",
":",
"18",
"]",
"==",
"\"Identical files : \"",
":",
"for_extend",
"=",
"raw",
"[",
"x",
"]",
".",
"lstrip",
"(",
"\"Identical files : \"",
")",
".",
"strip",
"(",
"\"[]\"",
")",
".",
"split",
"(",
"\", \"",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"for_extend",
")",
")",
":",
"for_extend",
"[",
"y",
"]",
"=",
"parsing_directory",
"+",
"for_extend",
"[",
"y",
"]",
".",
"strip",
"(",
"\"'\"",
")",
"dump",
"[",
"2",
"]",
".",
"extend",
"(",
"for_extend",
")",
"if",
"raw",
"[",
"x",
"]",
"[",
":",
"18",
"]",
"==",
"\"Differing files : \"",
":",
"for_extend",
"=",
"raw",
"[",
"x",
"]",
".",
"lstrip",
"(",
"\"Differing files : \"",
")",
".",
"strip",
"(",
"\"[]\"",
")",
".",
"split",
"(",
"\", \"",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"for_extend",
")",
")",
":",
"for_extend",
"[",
"y",
"]",
"=",
"parsing_directory",
"+",
"for_extend",
"[",
"y",
"]",
".",
"strip",
"(",
"\"'\"",
")",
"dump",
"[",
"3",
"]",
".",
"extend",
"(",
"for_extend",
")",
"return",
"dump"
] | [
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 \
method bandage.Supply.realize.
The remote parameter should be an HTTPS/HTTP address pointing to a web
server, or a Github release tagged BANDAGE.
For pointing to a Github repository's contents, use
raw.githubusercontent.com.
If bandage.Supply succeeded in finding headers and looking up lineage
series, however finds the current version to be the latest, self.result
is 0.
If bandage.Supply succeeded in finding headers and looking up lineage
series, and finds a patch to be applied for updating, self.result is -1
with self.patch_web_source as web address to patch file.
If bandage.Supply succeeded in finding headers and looking up lineage
series, however finds no patch available to upgrade with, self.result
is 1.
If bandage.Supply raised an exception, self.result and
self.patch_web_source are None.
Preliminary information if obtained is dumped into self.pre_collect.
Contains version list and patchesc available, as list object.
Retrieved through bandage.Supply.pre_collect_dump.
See documentation for more information.
:param remote: web address of patch host
:type remote: str
:param version_file: path to version file
:type 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 \
method bandage.Supply.realize. | 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, which can be retrieved as a list through \
method bandage.Supply.realize.
The remote parameter should be an HTTPS/HTTP address pointing to a web
server, or a Github release tagged BANDAGE.
For pointing to a Github repository's contents, use
raw.githubusercontent.com.
If bandage.Supply succeeded in finding headers and looking up lineage
series, however finds the current version to be the latest, self.result
is 0.
If bandage.Supply succeeded in finding headers and looking up lineage
series, and finds a patch to be applied for updating, self.result is -1
with self.patch_web_source as web address to patch file.
If bandage.Supply succeeded in finding headers and looking up lineage
series, however finds no patch available to upgrade with, self.result
is 1.
If bandage.Supply raised an exception, self.result and
self.patch_web_source are None.
Preliminary information if obtained is dumped into self.pre_collect.
Contains version list and patchesc available, as list object.
Retrieved through bandage.Supply.pre_collect_dump.
See documentation for more information.
:param remote: web address of patch host
:type remote: str
:param version_file: path to version file
:type version_file: str
"""
self.patch_web_source = None
self.result = 1
self.remote = remote
self.version_file = version_file
try:
with open(version_file) as version_handle:
self.version = version_handle.read()
except FileNotFoundError as ParentException:
raise Exceptions.VersionError(
"VERSION file directed by path " + self.version_file +
" does not exist.") from ParentException
if "https://" not in self.remote[:8] and "http://" not in \
self.remote[:8]:
raise Exceptions.RemoteError(
"Supplied remote " + self.remote +
" is not a HTTP/HTTPS web address.")
if self.remote[-1:] != "/":
self.remote += "/"
if "https://github.com" == self.remote[:18] or "http://github.com" == \
self.remote[:18]:
if self.remote[-22:] == "/releases/tag/BANDAGE/":
self.pre_collect = [Backend.fetch(
self.remote.rstrip("/tag/BANDAGE/") +
"/download/BANDAGE/BANDAGE_PATCHES").data.decode(
encoding="utf-8", errors="replace").split("\n"),
Backend.fetch(
self.remote.rstrip("/tag/BANDAGE/") +
"/download/BANDAGE/BANDAGE_LINEAGE").data.decode(
encoding="utf-8", errors="replace").split("\n")]
for x in range(0, len(self.pre_collect[1])):
if self.version == self.pre_collect[1][x].rstrip("\r"):
self.version_gap = x
break
if self.version_gap is None:
raise Exceptions.VersionError(
"Version " + self.version +
" does not exist in remote's lineage header.")
elif self.version_gap == 0:
self.result = 0
else:
compatible_sources = []
for x in range(0, len(self.pre_collect[0])):
if self.pre_collect[0][x].split(
"||")[0].split(" -> ")[0] == self.version:
compatible_sources.append(
self.pre_collect[0][x].split("||")[0])
if not compatible_sources:
self.result = 1
else:
for x in self.pre_collect[0]:
for y in compatible_sources:
if y.split(" -> ")[1] == \
x.split("||")[0].split(" -> ")[1]:
self.result = -1
self.patch_web_source = \
self.remote.rstrip("/BANDAGE/") + \
path.join("/download/BANDAGE/",
x.split("||")[1])
else:
raise Exceptions.RemoteError(
"Remote defined as " + self.remote + " is not supported.")
else:
self.pre_collect = [
Backend.fetch(
self.remote + "BANDAGE_PATCHES"
).data.decode(encoding="utf-8", errors="replace").split(
"\n"),
Backend.fetch(
self.remote + "BANDAGE_LINEAGE"
).data.decode(encoding="utf-8", errors="replace").split(
"\n")]
for x in range(0, len(self.pre_collect[1])):
if self.version == self.pre_collect[1][x]:
self.version_gap = x
break
if self.version_gap is None:
raise Exceptions.VersionError(
"Version " + self.version +
" does not exist in remote's lineage header.")
elif self.version_gap == 0:
self.result = 0
else:
compatible_sources = []
for x in range(0, len(self.pre_collect[0])):
if self.pre_collect[0][x].split(
"||")[0].split(" -> ")[0] == self.version:
compatible_sources.append(
self.pre_collect[0][x].split("||")[0])
if not compatible_sources:
self.result = 1
else:
for x in self.pre_collect[0]:
for y in compatible_sources:
if y.split(" -> ")[1] == \
x.split("||")[0].split(" -> ")[1]:
self.result = -1
if x.split("||")[1][:8] == "https://" or \
"http://" in x.split("||")[1][:8]:
self.patch_web_source = x.split("||")[1]
else:
self.patch_web_source = path.join(
self.remote, x.split("||")[1]) | [
"def",
"__init__",
"(",
"self",
",",
"remote",
":",
"str",
",",
"version_file",
":",
"str",
")",
":",
"self",
".",
"patch_web_source",
"=",
"None",
"self",
".",
"result",
"=",
"1",
"self",
".",
"remote",
"=",
"remote",
"self",
".",
"version_file",
"=",
"version_file",
"try",
":",
"with",
"open",
"(",
"version_file",
")",
"as",
"version_handle",
":",
"self",
".",
"version",
"=",
"version_handle",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
"as",
"ParentException",
":",
"raise",
"Exceptions",
".",
"VersionError",
"(",
"\"VERSION file directed by path \"",
"+",
"self",
".",
"version_file",
"+",
"\" does not exist.\"",
")",
"from",
"ParentException",
"if",
"\"https://\"",
"not",
"in",
"self",
".",
"remote",
"[",
":",
"8",
"]",
"and",
"\"http://\"",
"not",
"in",
"self",
".",
"remote",
"[",
":",
"8",
"]",
":",
"raise",
"Exceptions",
".",
"RemoteError",
"(",
"\"Supplied remote \"",
"+",
"self",
".",
"remote",
"+",
"\" is not a HTTP/HTTPS web address.\"",
")",
"if",
"self",
".",
"remote",
"[",
"-",
"1",
":",
"]",
"!=",
"\"/\"",
":",
"self",
".",
"remote",
"+=",
"\"/\"",
"if",
"\"https://github.com\"",
"==",
"self",
".",
"remote",
"[",
":",
"18",
"]",
"or",
"\"http://github.com\"",
"==",
"self",
".",
"remote",
"[",
":",
"18",
"]",
":",
"if",
"self",
".",
"remote",
"[",
"-",
"22",
":",
"]",
"==",
"\"/releases/tag/BANDAGE/\"",
":",
"self",
".",
"pre_collect",
"=",
"[",
"Backend",
".",
"fetch",
"(",
"self",
".",
"remote",
".",
"rstrip",
"(",
"\"/tag/BANDAGE/\"",
")",
"+",
"\"/download/BANDAGE/BANDAGE_PATCHES\"",
")",
".",
"data",
".",
"decode",
"(",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"replace\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
",",
"Backend",
".",
"fetch",
"(",
"self",
".",
"remote",
".",
"rstrip",
"(",
"\"/tag/BANDAGE/\"",
")",
"+",
"\"/download/BANDAGE/BANDAGE_LINEAGE\"",
")",
".",
"data",
".",
"decode",
"(",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"replace\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"pre_collect",
"[",
"1",
"]",
")",
")",
":",
"if",
"self",
".",
"version",
"==",
"self",
".",
"pre_collect",
"[",
"1",
"]",
"[",
"x",
"]",
".",
"rstrip",
"(",
"\"\\r\"",
")",
":",
"self",
".",
"version_gap",
"=",
"x",
"break",
"if",
"self",
".",
"version_gap",
"is",
"None",
":",
"raise",
"Exceptions",
".",
"VersionError",
"(",
"\"Version \"",
"+",
"self",
".",
"version",
"+",
"\" does not exist in remote's lineage header.\"",
")",
"elif",
"self",
".",
"version_gap",
"==",
"0",
":",
"self",
".",
"result",
"=",
"0",
"else",
":",
"compatible_sources",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"pre_collect",
"[",
"0",
"]",
")",
")",
":",
"if",
"self",
".",
"pre_collect",
"[",
"0",
"]",
"[",
"x",
"]",
".",
"split",
"(",
"\"||\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\" -> \"",
")",
"[",
"0",
"]",
"==",
"self",
".",
"version",
":",
"compatible_sources",
".",
"append",
"(",
"self",
".",
"pre_collect",
"[",
"0",
"]",
"[",
"x",
"]",
".",
"split",
"(",
"\"||\"",
")",
"[",
"0",
"]",
")",
"if",
"not",
"compatible_sources",
":",
"self",
".",
"result",
"=",
"1",
"else",
":",
"for",
"x",
"in",
"self",
".",
"pre_collect",
"[",
"0",
"]",
":",
"for",
"y",
"in",
"compatible_sources",
":",
"if",
"y",
".",
"split",
"(",
"\" -> \"",
")",
"[",
"1",
"]",
"==",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\" -> \"",
")",
"[",
"1",
"]",
":",
"self",
".",
"result",
"=",
"-",
"1",
"self",
".",
"patch_web_source",
"=",
"self",
".",
"remote",
".",
"rstrip",
"(",
"\"/BANDAGE/\"",
")",
"+",
"path",
".",
"join",
"(",
"\"/download/BANDAGE/\"",
",",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"Exceptions",
".",
"RemoteError",
"(",
"\"Remote defined as \"",
"+",
"self",
".",
"remote",
"+",
"\" is not supported.\"",
")",
"else",
":",
"self",
".",
"pre_collect",
"=",
"[",
"Backend",
".",
"fetch",
"(",
"self",
".",
"remote",
"+",
"\"BANDAGE_PATCHES\"",
")",
".",
"data",
".",
"decode",
"(",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"replace\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
",",
"Backend",
".",
"fetch",
"(",
"self",
".",
"remote",
"+",
"\"BANDAGE_LINEAGE\"",
")",
".",
"data",
".",
"decode",
"(",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"replace\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"pre_collect",
"[",
"1",
"]",
")",
")",
":",
"if",
"self",
".",
"version",
"==",
"self",
".",
"pre_collect",
"[",
"1",
"]",
"[",
"x",
"]",
":",
"self",
".",
"version_gap",
"=",
"x",
"break",
"if",
"self",
".",
"version_gap",
"is",
"None",
":",
"raise",
"Exceptions",
".",
"VersionError",
"(",
"\"Version \"",
"+",
"self",
".",
"version",
"+",
"\" does not exist in remote's lineage header.\"",
")",
"elif",
"self",
".",
"version_gap",
"==",
"0",
":",
"self",
".",
"result",
"=",
"0",
"else",
":",
"compatible_sources",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"pre_collect",
"[",
"0",
"]",
")",
")",
":",
"if",
"self",
".",
"pre_collect",
"[",
"0",
"]",
"[",
"x",
"]",
".",
"split",
"(",
"\"||\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\" -> \"",
")",
"[",
"0",
"]",
"==",
"self",
".",
"version",
":",
"compatible_sources",
".",
"append",
"(",
"self",
".",
"pre_collect",
"[",
"0",
"]",
"[",
"x",
"]",
".",
"split",
"(",
"\"||\"",
")",
"[",
"0",
"]",
")",
"if",
"not",
"compatible_sources",
":",
"self",
".",
"result",
"=",
"1",
"else",
":",
"for",
"x",
"in",
"self",
".",
"pre_collect",
"[",
"0",
"]",
":",
"for",
"y",
"in",
"compatible_sources",
":",
"if",
"y",
".",
"split",
"(",
"\" -> \"",
")",
"[",
"1",
"]",
"==",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\" -> \"",
")",
"[",
"1",
"]",
":",
"self",
".",
"result",
"=",
"-",
"1",
"if",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"1",
"]",
"[",
":",
"8",
"]",
"==",
"\"https://\"",
"or",
"\"http://\"",
"in",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"1",
"]",
"[",
":",
"8",
"]",
":",
"self",
".",
"patch_web_source",
"=",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"1",
"]",
"else",
":",
"self",
".",
"patch_web_source",
"=",
"path",
".",
"join",
"(",
"self",
".",
"remote",
",",
"x",
".",
"split",
"(",
"\"||\"",
")",
"[",
"1",
"]",
")"
] | [
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(...).
-- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg).
-- 'filename.gif': render and export the animation a gif file (requires imagemagick).
|
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(...).
-- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg).
-- 'filename.gif': render and export the animation a gif file (requires imagemagick).
| 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 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(...).
-- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg).
-- 'filename.gif': render and export the animation a gif file (requires imagemagick).
"""
plt.ioff()
fig = plt.figure(figsize=(size * (1 + len(poses)), size))
ax_in = fig.add_subplot(1, 1 + len(poses), 1)
ax_in.get_xaxis().set_visible(False)
ax_in.get_yaxis().set_visible(False)
ax_in.set_axis_off()
ax_in.set_title('Input')
ax_3d = []
lines_3d = []
trajectories = []
radius = 1.7
for index, (title, data) in enumerate(poses.items()):
ax = fig.add_subplot(1, 1 + len(poses), index + 2, projection='3d')
ax.view_init(elev=15., azim=azim)
ax.set_xlim3d([-radius / 2, radius / 2])
ax.set_zlim3d([0, radius])
ax.set_ylim3d([-radius / 2, radius / 2])
ax.set_aspect('equal')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
ax.dist = 7.5
ax.set_title(title) # , pad=35
ax_3d.append(ax)
lines_3d.append([])
trajectories.append(data[:, 0, [0, 1]])
poses = list(poses.values())
# Decode video
if input_video_path is None:
# Black background
all_frames = np.zeros((keypoints.shape[0], viewport[1], viewport[0]), dtype='uint8')
else:
# Load video using ffmpeg
all_frames = []
for f in read_video(input_video_path, skip=input_video_skip, limit=limit):
all_frames.append(f)
effective_length = min(keypoints.shape[0], len(all_frames))
all_frames = all_frames[:effective_length]
keypoints = keypoints[input_video_skip:] # todo remove
for idx in range(len(poses)):
poses[idx] = poses[idx][input_video_skip:]
if fps is None:
fps = get_fps(input_video_path)
if downsample > 1:
keypoints = downsample_tensor(keypoints, downsample)
all_frames = downsample_tensor(np.array(all_frames), downsample).astype('uint8')
for idx in range(len(poses)):
poses[idx] = downsample_tensor(poses[idx], downsample)
trajectories[idx] = downsample_tensor(trajectories[idx], downsample)
fps /= downsample
initialized = False
image = None
lines = []
points = None
if limit < 1:
limit = len(all_frames)
else:
limit = min(limit, len(all_frames))
parents = skeleton.parents()
def update_video(i):
nonlocal initialized, image, lines, points
for n, ax in enumerate(ax_3d):
ax.set_xlim3d([-radius / 2 + trajectories[n][i, 0], radius / 2 + trajectories[n][i, 0]])
ax.set_ylim3d([-radius / 2 + trajectories[n][i, 1], radius / 2 + trajectories[n][i, 1]])
# Update 2D poses
joints_right_2d = keypoints_metadata['keypoints_symmetry'][1]
colors_2d = np.full(keypoints.shape[1], 'black')
colors_2d[joints_right_2d] = 'red'
if not initialized:
image = ax_in.imshow(all_frames[i], aspect='equal')
for j, j_parent in enumerate(parents):
if j_parent == -1:
continue
if len(parents) == keypoints.shape[1]:
# Draw skeleton only if keypoints match (otherwise we don't have the parents definition)
lines.append(ax_in.plot([keypoints[i, j, 0], keypoints[i, j_parent, 0]],
[keypoints[i, j, 1], keypoints[i, j_parent, 1]], color='pink'))
col = 'red' if j in skeleton.joints_right() else 'black'
for n, ax in enumerate(ax_3d):
pos = poses[n][i]
lines_3d[n].append(ax.plot([pos[j, 0], pos[j_parent, 0]],
[pos[j, 1], pos[j_parent, 1]],
[pos[j, 2], pos[j_parent, 2]], zdir='z', c=col))
points = ax_in.scatter(*keypoints[i].T, 10, color=colors_2d, edgecolors='white', zorder=10)
initialized = True
else:
image.set_data(all_frames[i])
for j, j_parent in enumerate(parents):
if j_parent == -1:
continue
if len(parents) == keypoints.shape[1]:
lines[j - 1][0].set_data([keypoints[i, j, 0], keypoints[i, j_parent, 0]],
[keypoints[i, j, 1], keypoints[i, j_parent, 1]])
for n, ax in enumerate(ax_3d):
pos = poses[n][i]
lines_3d[n][j - 1][0].set_xdata([pos[j, 0], pos[j_parent, 0]])
lines_3d[n][j - 1][0].set_ydata([pos[j, 1], pos[j_parent, 1]])
lines_3d[n][j - 1][0].set_3d_properties([pos[j, 2], pos[j_parent, 2]], zdir='z')
points.set_offsets(keypoints[i])
print('{}/{} '.format(i, limit), end='\r')
fig.tight_layout()
anim = FuncAnimation(fig, update_video, frames=np.arange(0, limit), interval=1000 / fps, repeat=False)
if output.endswith('.mp4'):
Writer = writers['ffmpeg']
writer = Writer(fps=fps, metadata={}, bitrate=bitrate)
anim.save(output, writer=writer)
elif output.endswith('.gif'):
anim.save(output, dpi=80, writer='imagemagick')
else:
raise ValueError('Unsupported output format (only .mp4 and .gif are supported)')
plt.close() | [
"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",
")",
":",
"plt",
".",
"ioff",
"(",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"size",
"*",
"(",
"1",
"+",
"len",
"(",
"poses",
")",
")",
",",
"size",
")",
")",
"ax_in",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"1",
"+",
"len",
"(",
"poses",
")",
",",
"1",
")",
"ax_in",
".",
"get_xaxis",
"(",
")",
".",
"set_visible",
"(",
"False",
")",
"ax_in",
".",
"get_yaxis",
"(",
")",
".",
"set_visible",
"(",
"False",
")",
"ax_in",
".",
"set_axis_off",
"(",
")",
"ax_in",
".",
"set_title",
"(",
"'Input'",
")",
"ax_3d",
"=",
"[",
"]",
"lines_3d",
"=",
"[",
"]",
"trajectories",
"=",
"[",
"]",
"radius",
"=",
"1.7",
"for",
"index",
",",
"(",
"title",
",",
"data",
")",
"in",
"enumerate",
"(",
"poses",
".",
"items",
"(",
")",
")",
":",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"1",
"+",
"len",
"(",
"poses",
")",
",",
"index",
"+",
"2",
",",
"projection",
"=",
"'3d'",
")",
"ax",
".",
"view_init",
"(",
"elev",
"=",
"15.",
",",
"azim",
"=",
"azim",
")",
"ax",
".",
"set_xlim3d",
"(",
"[",
"-",
"radius",
"/",
"2",
",",
"radius",
"/",
"2",
"]",
")",
"ax",
".",
"set_zlim3d",
"(",
"[",
"0",
",",
"radius",
"]",
")",
"ax",
".",
"set_ylim3d",
"(",
"[",
"-",
"radius",
"/",
"2",
",",
"radius",
"/",
"2",
"]",
")",
"ax",
".",
"set_aspect",
"(",
"'equal'",
")",
"ax",
".",
"set_xticklabels",
"(",
"[",
"]",
")",
"ax",
".",
"set_yticklabels",
"(",
"[",
"]",
")",
"ax",
".",
"set_zticklabels",
"(",
"[",
"]",
")",
"ax",
".",
"dist",
"=",
"7.5",
"ax",
".",
"set_title",
"(",
"title",
")",
"# , pad=35",
"ax_3d",
".",
"append",
"(",
"ax",
")",
"lines_3d",
".",
"append",
"(",
"[",
"]",
")",
"trajectories",
".",
"append",
"(",
"data",
"[",
":",
",",
"0",
",",
"[",
"0",
",",
"1",
"]",
"]",
")",
"poses",
"=",
"list",
"(",
"poses",
".",
"values",
"(",
")",
")",
"# Decode video",
"if",
"input_video_path",
"is",
"None",
":",
"# Black background",
"all_frames",
"=",
"np",
".",
"zeros",
"(",
"(",
"keypoints",
".",
"shape",
"[",
"0",
"]",
",",
"viewport",
"[",
"1",
"]",
",",
"viewport",
"[",
"0",
"]",
")",
",",
"dtype",
"=",
"'uint8'",
")",
"else",
":",
"# Load video using ffmpeg",
"all_frames",
"=",
"[",
"]",
"for",
"f",
"in",
"read_video",
"(",
"input_video_path",
",",
"skip",
"=",
"input_video_skip",
",",
"limit",
"=",
"limit",
")",
":",
"all_frames",
".",
"append",
"(",
"f",
")",
"effective_length",
"=",
"min",
"(",
"keypoints",
".",
"shape",
"[",
"0",
"]",
",",
"len",
"(",
"all_frames",
")",
")",
"all_frames",
"=",
"all_frames",
"[",
":",
"effective_length",
"]",
"keypoints",
"=",
"keypoints",
"[",
"input_video_skip",
":",
"]",
"# todo remove",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"poses",
")",
")",
":",
"poses",
"[",
"idx",
"]",
"=",
"poses",
"[",
"idx",
"]",
"[",
"input_video_skip",
":",
"]",
"if",
"fps",
"is",
"None",
":",
"fps",
"=",
"get_fps",
"(",
"input_video_path",
")",
"if",
"downsample",
">",
"1",
":",
"keypoints",
"=",
"downsample_tensor",
"(",
"keypoints",
",",
"downsample",
")",
"all_frames",
"=",
"downsample_tensor",
"(",
"np",
".",
"array",
"(",
"all_frames",
")",
",",
"downsample",
")",
".",
"astype",
"(",
"'uint8'",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"poses",
")",
")",
":",
"poses",
"[",
"idx",
"]",
"=",
"downsample_tensor",
"(",
"poses",
"[",
"idx",
"]",
",",
"downsample",
")",
"trajectories",
"[",
"idx",
"]",
"=",
"downsample_tensor",
"(",
"trajectories",
"[",
"idx",
"]",
",",
"downsample",
")",
"fps",
"/=",
"downsample",
"initialized",
"=",
"False",
"image",
"=",
"None",
"lines",
"=",
"[",
"]",
"points",
"=",
"None",
"if",
"limit",
"<",
"1",
":",
"limit",
"=",
"len",
"(",
"all_frames",
")",
"else",
":",
"limit",
"=",
"min",
"(",
"limit",
",",
"len",
"(",
"all_frames",
")",
")",
"parents",
"=",
"skeleton",
".",
"parents",
"(",
")",
"def",
"update_video",
"(",
"i",
")",
":",
"nonlocal",
"initialized",
",",
"image",
",",
"lines",
",",
"points",
"for",
"n",
",",
"ax",
"in",
"enumerate",
"(",
"ax_3d",
")",
":",
"ax",
".",
"set_xlim3d",
"(",
"[",
"-",
"radius",
"/",
"2",
"+",
"trajectories",
"[",
"n",
"]",
"[",
"i",
",",
"0",
"]",
",",
"radius",
"/",
"2",
"+",
"trajectories",
"[",
"n",
"]",
"[",
"i",
",",
"0",
"]",
"]",
")",
"ax",
".",
"set_ylim3d",
"(",
"[",
"-",
"radius",
"/",
"2",
"+",
"trajectories",
"[",
"n",
"]",
"[",
"i",
",",
"1",
"]",
",",
"radius",
"/",
"2",
"+",
"trajectories",
"[",
"n",
"]",
"[",
"i",
",",
"1",
"]",
"]",
")",
"# Update 2D poses",
"joints_right_2d",
"=",
"keypoints_metadata",
"[",
"'keypoints_symmetry'",
"]",
"[",
"1",
"]",
"colors_2d",
"=",
"np",
".",
"full",
"(",
"keypoints",
".",
"shape",
"[",
"1",
"]",
",",
"'black'",
")",
"colors_2d",
"[",
"joints_right_2d",
"]",
"=",
"'red'",
"if",
"not",
"initialized",
":",
"image",
"=",
"ax_in",
".",
"imshow",
"(",
"all_frames",
"[",
"i",
"]",
",",
"aspect",
"=",
"'equal'",
")",
"for",
"j",
",",
"j_parent",
"in",
"enumerate",
"(",
"parents",
")",
":",
"if",
"j_parent",
"==",
"-",
"1",
":",
"continue",
"if",
"len",
"(",
"parents",
")",
"==",
"keypoints",
".",
"shape",
"[",
"1",
"]",
":",
"# Draw skeleton only if keypoints match (otherwise we don't have the parents definition)",
"lines",
".",
"append",
"(",
"ax_in",
".",
"plot",
"(",
"[",
"keypoints",
"[",
"i",
",",
"j",
",",
"0",
"]",
",",
"keypoints",
"[",
"i",
",",
"j_parent",
",",
"0",
"]",
"]",
",",
"[",
"keypoints",
"[",
"i",
",",
"j",
",",
"1",
"]",
",",
"keypoints",
"[",
"i",
",",
"j_parent",
",",
"1",
"]",
"]",
",",
"color",
"=",
"'pink'",
")",
")",
"col",
"=",
"'red'",
"if",
"j",
"in",
"skeleton",
".",
"joints_right",
"(",
")",
"else",
"'black'",
"for",
"n",
",",
"ax",
"in",
"enumerate",
"(",
"ax_3d",
")",
":",
"pos",
"=",
"poses",
"[",
"n",
"]",
"[",
"i",
"]",
"lines_3d",
"[",
"n",
"]",
".",
"append",
"(",
"ax",
".",
"plot",
"(",
"[",
"pos",
"[",
"j",
",",
"0",
"]",
",",
"pos",
"[",
"j_parent",
",",
"0",
"]",
"]",
",",
"[",
"pos",
"[",
"j",
",",
"1",
"]",
",",
"pos",
"[",
"j_parent",
",",
"1",
"]",
"]",
",",
"[",
"pos",
"[",
"j",
",",
"2",
"]",
",",
"pos",
"[",
"j_parent",
",",
"2",
"]",
"]",
",",
"zdir",
"=",
"'z'",
",",
"c",
"=",
"col",
")",
")",
"points",
"=",
"ax_in",
".",
"scatter",
"(",
"*",
"keypoints",
"[",
"i",
"]",
".",
"T",
",",
"10",
",",
"color",
"=",
"colors_2d",
",",
"edgecolors",
"=",
"'white'",
",",
"zorder",
"=",
"10",
")",
"initialized",
"=",
"True",
"else",
":",
"image",
".",
"set_data",
"(",
"all_frames",
"[",
"i",
"]",
")",
"for",
"j",
",",
"j_parent",
"in",
"enumerate",
"(",
"parents",
")",
":",
"if",
"j_parent",
"==",
"-",
"1",
":",
"continue",
"if",
"len",
"(",
"parents",
")",
"==",
"keypoints",
".",
"shape",
"[",
"1",
"]",
":",
"lines",
"[",
"j",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"set_data",
"(",
"[",
"keypoints",
"[",
"i",
",",
"j",
",",
"0",
"]",
",",
"keypoints",
"[",
"i",
",",
"j_parent",
",",
"0",
"]",
"]",
",",
"[",
"keypoints",
"[",
"i",
",",
"j",
",",
"1",
"]",
",",
"keypoints",
"[",
"i",
",",
"j_parent",
",",
"1",
"]",
"]",
")",
"for",
"n",
",",
"ax",
"in",
"enumerate",
"(",
"ax_3d",
")",
":",
"pos",
"=",
"poses",
"[",
"n",
"]",
"[",
"i",
"]",
"lines_3d",
"[",
"n",
"]",
"[",
"j",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"set_xdata",
"(",
"[",
"pos",
"[",
"j",
",",
"0",
"]",
",",
"pos",
"[",
"j_parent",
",",
"0",
"]",
"]",
")",
"lines_3d",
"[",
"n",
"]",
"[",
"j",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"set_ydata",
"(",
"[",
"pos",
"[",
"j",
",",
"1",
"]",
",",
"pos",
"[",
"j_parent",
",",
"1",
"]",
"]",
")",
"lines_3d",
"[",
"n",
"]",
"[",
"j",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"set_3d_properties",
"(",
"[",
"pos",
"[",
"j",
",",
"2",
"]",
",",
"pos",
"[",
"j_parent",
",",
"2",
"]",
"]",
",",
"zdir",
"=",
"'z'",
")",
"points",
".",
"set_offsets",
"(",
"keypoints",
"[",
"i",
"]",
")",
"print",
"(",
"'{}/{} '",
".",
"format",
"(",
"i",
",",
"limit",
")",
",",
"end",
"=",
"'\\r'",
")",
"fig",
".",
"tight_layout",
"(",
")",
"anim",
"=",
"FuncAnimation",
"(",
"fig",
",",
"update_video",
",",
"frames",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"limit",
")",
",",
"interval",
"=",
"1000",
"/",
"fps",
",",
"repeat",
"=",
"False",
")",
"if",
"output",
".",
"endswith",
"(",
"'.mp4'",
")",
":",
"Writer",
"=",
"writers",
"[",
"'ffmpeg'",
"]",
"writer",
"=",
"Writer",
"(",
"fps",
"=",
"fps",
",",
"metadata",
"=",
"{",
"}",
",",
"bitrate",
"=",
"bitrate",
")",
"anim",
".",
"save",
"(",
"output",
",",
"writer",
"=",
"writer",
")",
"elif",
"output",
".",
"endswith",
"(",
"'.gif'",
")",
":",
"anim",
".",
"save",
"(",
"output",
",",
"dpi",
"=",
"80",
",",
"writer",
"=",
"'imagemagick'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unsupported output format (only .mp4 and .gif are supported)'",
")",
"plt",
".",
"close",
"(",
")"
] | [
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 "Other".
Returns
-------
The transformed categorical feature value list.
|
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 remained, other category values will be put into "Other".
Returns
-------
The transformed categorical feature value list.
'''
if dfx[kpix].nunique() > n_group:
# get the top categories
top = dfx[kpix].isin(dfx[kpix].value_counts().index[:n_group])
dfx.loc[~top, kpix] = "Other"
return dfx[kpix].values
else:
return dfx[kpix].values | [
"def",
"cat_group",
"(",
"dfx",
",",
"kpix",
",",
"n_group",
"=",
"10",
")",
":",
"if",
"dfx",
"[",
"kpix",
"]",
".",
"nunique",
"(",
")",
">",
"n_group",
":",
"# get the top categories",
"top",
"=",
"dfx",
"[",
"kpix",
"]",
".",
"isin",
"(",
"dfx",
"[",
"kpix",
"]",
".",
"value_counts",
"(",
")",
".",
"index",
"[",
":",
"n_group",
"]",
")",
"dfx",
".",
"loc",
"[",
"~",
"top",
",",
"kpix",
"]",
"=",
"\"Other\"",
"return",
"dfx",
"[",
"kpix",
"]",
".",
"values",
"else",
":",
"return",
"dfx",
"[",
"kpix",
"]",
".",
"values"
] | [
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.
kpi1 : list
The updated feature names containing the new dummy feature names.
|
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 dataframe containing the encoded data.
kpi1 : list
The updated feature names containing the new dummy feature names.
'''
df_dummy = pd.get_dummies(dfx[kpix].values)
new_col_names = ['%s_%s' % (kpix, x) for x in df_dummy.columns]
df_dummy.columns = new_col_names
dfx = pd.concat([dfx, df_dummy], axis=1)
for new_col in new_col_names:
if new_col not in kpi1:
kpi1.append(new_col)
if kpix in kpi1:
kpi1.remove(kpix)
return dfx, kpi1 | [
"def",
"cat_transform",
"(",
"dfx",
",",
"kpix",
",",
"kpi1",
")",
":",
"df_dummy",
"=",
"pd",
".",
"get_dummies",
"(",
"dfx",
"[",
"kpix",
"]",
".",
"values",
")",
"new_col_names",
"=",
"[",
"'%s_%s'",
"%",
"(",
"kpix",
",",
"x",
")",
"for",
"x",
"in",
"df_dummy",
".",
"columns",
"]",
"df_dummy",
".",
"columns",
"=",
"new_col_names",
"dfx",
"=",
"pd",
".",
"concat",
"(",
"[",
"dfx",
",",
"df_dummy",
"]",
",",
"axis",
"=",
"1",
")",
"for",
"new_col",
"in",
"new_col_names",
":",
"if",
"new_col",
"not",
"in",
"kpi1",
":",
"kpi1",
".",
"append",
"(",
"new_col",
")",
"if",
"kpix",
"in",
"kpi1",
":",
"kpi1",
".",
"remove",
"(",
"kpix",
")",
"return",
"dfx",
",",
"kpi1"
] | [
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.
kpi1 : list
The updated feature names containing the new dummy feature names.
|
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
The updated dataframe containing the encoded data.
kpi1 : list
The updated feature names containing the new dummy feature names.
'''
np.random.seed(random_seed)
rlist = np.random.choice(a=range(k), size=n, replace=True)
fold_i_index = np.where(rlist == i)[0]
return fold_i_index | [
"def",
"cv_fold_index",
"(",
"n",
",",
"i",
",",
"k",
",",
"random_seed",
"=",
"2018",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"rlist",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"a",
"=",
"range",
"(",
"k",
")",
",",
"size",
"=",
"n",
",",
"replace",
"=",
"True",
")",
"fold_i_index",
"=",
"np",
".",
"where",
"(",
"rlist",
"==",
"i",
")",
"[",
"0",
"]",
"return",
"fold_i_index"
] | [
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
List of percentile bins for the feature value.
|
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'.
Returns
-------
res : list
List of percentile bins for the feature value.
'''
if granularity == 'High':
lspercentile = [np.percentile(x, 5),
np.percentile(x, 10),
np.percentile(x, 15),
np.percentile(x, 20),
np.percentile(x, 25),
np.percentile(x, 30),
np.percentile(x, 35),
np.percentile(x, 40),
np.percentile(x, 45),
np.percentile(x, 50),
np.percentile(x, 55),
np.percentile(x, 60),
np.percentile(x, 65),
np.percentile(x, 70),
np.percentile(x, 75),
np.percentile(x, 80),
np.percentile(x, 85),
np.percentile(x, 90),
np.percentile(x, 95),
np.percentile(x, 99)
]
res = ['> p90 (%s)' % (lspercentile[8]) if z > lspercentile[8] else
'<= p10 (%s)' % (lspercentile[0]) if z <= lspercentile[0] else
'<= p20 (%s)' % (lspercentile[1]) if z <= lspercentile[1] else
'<= p30 (%s)' % (lspercentile[2]) if z <= lspercentile[2] else
'<= p40 (%s)' % (lspercentile[3]) if z <= lspercentile[3] else
'<= p50 (%s)' % (lspercentile[4]) if z <= lspercentile[4] else
'<= p60 (%s)' % (lspercentile[5]) if z <= lspercentile[5] else
'<= p70 (%s)' % (lspercentile[6]) if z <= lspercentile[6] else
'<= p80 (%s)' % (lspercentile[7]) if z <= lspercentile[7] else
'<= p90 (%s)' % (lspercentile[8]) if z <= lspercentile[8] else
'> p90 (%s)' % (lspercentile[8]) for z in x]
elif granularity == 'Medium':
lspercentile = [np.percentile(x, 10),
np.percentile(x, 20),
np.percentile(x, 30),
np.percentile(x, 40),
np.percentile(x, 50),
np.percentile(x, 60),
np.percentile(x, 70),
np.percentile(x, 80),
np.percentile(x, 90)
]
res = ['<= p10 (%s)' % (lspercentile[0]) if z <= lspercentile[0] else
'<= p20 (%s)' % (lspercentile[1]) if z <= lspercentile[1] else
'<= p30 (%s)' % (lspercentile[2]) if z <= lspercentile[2] else
'<= p40 (%s)' % (lspercentile[3]) if z <= lspercentile[3] else
'<= p50 (%s)' % (lspercentile[4]) if z <= lspercentile[4] else
'<= p60 (%s)' % (lspercentile[5]) if z <= lspercentile[5] else
'<= p70 (%s)' % (lspercentile[6]) if z <= lspercentile[6] else
'<= p80 (%s)' % (lspercentile[7]) if z <= lspercentile[7] else
'<= p90 (%s)' % (lspercentile[8]) if z <= lspercentile[8] else
'> p90 (%s)' % (lspercentile[8]) for z in x]
else:
lspercentile = [np.percentile(x, 15), np.percentile(x, 50), np.percentile(x, 85)]
res = ['1-Very Low' if z < lspercentile[0] else
'2-Low' if z < lspercentile[1] else
'3-High' if z < lspercentile[2] else
'4-Very High' for z in x]
return res | [
"def",
"cat_continuous",
"(",
"x",
",",
"granularity",
"=",
"'Medium'",
")",
":",
"if",
"granularity",
"==",
"'High'",
":",
"lspercentile",
"=",
"[",
"np",
".",
"percentile",
"(",
"x",
",",
"5",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"10",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"15",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"20",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"25",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"30",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"35",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"40",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"45",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"50",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"55",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"60",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"65",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"70",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"75",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"80",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"85",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"90",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"95",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"99",
")",
"]",
"res",
"=",
"[",
"'> p90 (%s)'",
"%",
"(",
"lspercentile",
"[",
"8",
"]",
")",
"if",
"z",
">",
"lspercentile",
"[",
"8",
"]",
"else",
"'<= p10 (%s)'",
"%",
"(",
"lspercentile",
"[",
"0",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"0",
"]",
"else",
"'<= p20 (%s)'",
"%",
"(",
"lspercentile",
"[",
"1",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"1",
"]",
"else",
"'<= p30 (%s)'",
"%",
"(",
"lspercentile",
"[",
"2",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"2",
"]",
"else",
"'<= p40 (%s)'",
"%",
"(",
"lspercentile",
"[",
"3",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"3",
"]",
"else",
"'<= p50 (%s)'",
"%",
"(",
"lspercentile",
"[",
"4",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"4",
"]",
"else",
"'<= p60 (%s)'",
"%",
"(",
"lspercentile",
"[",
"5",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"5",
"]",
"else",
"'<= p70 (%s)'",
"%",
"(",
"lspercentile",
"[",
"6",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"6",
"]",
"else",
"'<= p80 (%s)'",
"%",
"(",
"lspercentile",
"[",
"7",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"7",
"]",
"else",
"'<= p90 (%s)'",
"%",
"(",
"lspercentile",
"[",
"8",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"8",
"]",
"else",
"'> p90 (%s)'",
"%",
"(",
"lspercentile",
"[",
"8",
"]",
")",
"for",
"z",
"in",
"x",
"]",
"elif",
"granularity",
"==",
"'Medium'",
":",
"lspercentile",
"=",
"[",
"np",
".",
"percentile",
"(",
"x",
",",
"10",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"20",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"30",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"40",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"50",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"60",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"70",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"80",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"90",
")",
"]",
"res",
"=",
"[",
"'<= p10 (%s)'",
"%",
"(",
"lspercentile",
"[",
"0",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"0",
"]",
"else",
"'<= p20 (%s)'",
"%",
"(",
"lspercentile",
"[",
"1",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"1",
"]",
"else",
"'<= p30 (%s)'",
"%",
"(",
"lspercentile",
"[",
"2",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"2",
"]",
"else",
"'<= p40 (%s)'",
"%",
"(",
"lspercentile",
"[",
"3",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"3",
"]",
"else",
"'<= p50 (%s)'",
"%",
"(",
"lspercentile",
"[",
"4",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"4",
"]",
"else",
"'<= p60 (%s)'",
"%",
"(",
"lspercentile",
"[",
"5",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"5",
"]",
"else",
"'<= p70 (%s)'",
"%",
"(",
"lspercentile",
"[",
"6",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"6",
"]",
"else",
"'<= p80 (%s)'",
"%",
"(",
"lspercentile",
"[",
"7",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"7",
"]",
"else",
"'<= p90 (%s)'",
"%",
"(",
"lspercentile",
"[",
"8",
"]",
")",
"if",
"z",
"<=",
"lspercentile",
"[",
"8",
"]",
"else",
"'> p90 (%s)'",
"%",
"(",
"lspercentile",
"[",
"8",
"]",
")",
"for",
"z",
"in",
"x",
"]",
"else",
":",
"lspercentile",
"=",
"[",
"np",
".",
"percentile",
"(",
"x",
",",
"15",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"50",
")",
",",
"np",
".",
"percentile",
"(",
"x",
",",
"85",
")",
"]",
"res",
"=",
"[",
"'1-Very Low'",
"if",
"z",
"<",
"lspercentile",
"[",
"0",
"]",
"else",
"'2-Low'",
"if",
"z",
"<",
"lspercentile",
"[",
"1",
"]",
"else",
"'3-High'",
"if",
"z",
"<",
"lspercentile",
"[",
"2",
"]",
"else",
"'4-Very High'",
"for",
"z",
"in",
"x",
"]",
"return",
"res"
] | [
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 names to be assigned to the transformed features.
Returns
-------
dfx : DataFrame
Updated DataFrame containing the new features.
|
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
kpi_combo_new : list of string
List of new feature names to be assigned to the transformed features.
Returns
-------
dfx : DataFrame
Updated DataFrame containing the new features.
'''
for j in range(len(kpi_combo)):
if type(dfx[kpi_combo[j]].values[0]) is str:
dfx[kpi_combo_new[j]] = dfx[kpi_combo[j]].values
dfx[kpi_combo_new[j]] = cat_group(dfx=dfx, kpix=kpi_combo_new[j])
else:
if len(kpi_combo) > 1:
dfx[kpi_combo_new[j]] = cat_continuous(
dfx[kpi_combo[j]].values, granularity='Low'
)
else:
dfx[kpi_combo_new[j]] = cat_continuous(
dfx[kpi_combo[j]].values, granularity='High'
)
return dfx | [
"def",
"kpi_transform",
"(",
"dfx",
",",
"kpi_combo",
",",
"kpi_combo_new",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"kpi_combo",
")",
")",
":",
"if",
"type",
"(",
"dfx",
"[",
"kpi_combo",
"[",
"j",
"]",
"]",
".",
"values",
"[",
"0",
"]",
")",
"is",
"str",
":",
"dfx",
"[",
"kpi_combo_new",
"[",
"j",
"]",
"]",
"=",
"dfx",
"[",
"kpi_combo",
"[",
"j",
"]",
"]",
".",
"values",
"dfx",
"[",
"kpi_combo_new",
"[",
"j",
"]",
"]",
"=",
"cat_group",
"(",
"dfx",
"=",
"dfx",
",",
"kpix",
"=",
"kpi_combo_new",
"[",
"j",
"]",
")",
"else",
":",
"if",
"len",
"(",
"kpi_combo",
")",
">",
"1",
":",
"dfx",
"[",
"kpi_combo_new",
"[",
"j",
"]",
"]",
"=",
"cat_continuous",
"(",
"dfx",
"[",
"kpi_combo",
"[",
"j",
"]",
"]",
".",
"values",
",",
"granularity",
"=",
"'Low'",
")",
"else",
":",
"dfx",
"[",
"kpi_combo_new",
"[",
"j",
"]",
"]",
"=",
"cat_continuous",
"(",
"dfx",
"[",
"kpi_combo",
"[",
"j",
"]",
"]",
".",
"values",
",",
"granularity",
"=",
"'High'",
")",
"return",
"dfx"
] | [
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-actual-text>",
"meta":{"name": "<some-document-name>, "author": "somebody", ...}}
It can be used for filtering and is accessible in the responses of the Finder.
:param index: Optional name of index where the documents shall be written to.
If None, the DocumentStore's default index (self.index) will be used.
:return: None
|
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 format is {"text": "<the-actual-text>"}.
Optionally: Include meta data via {"text": "<the-actual-text>",
"meta":{"name": "<some-document-name>, "author": "somebody", ...}}
It can be used for filtering and is accessible in the responses of the Finder.
:param index: Optional name of index where the documents shall be written to.
If None, the DocumentStore's default index (self.index) will be used.
:return: None
"""
pass | [
"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: {"name": ["some", "more"], "category": ["only_one"]}
:param return_embedding: Whether to return the document embeddings.
|
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 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: {"name": ["some", "more"], "category": ["only_one"]}
:param return_embedding: Whether to return the document embeddings.
"""
pass | [
"def",
"get_all_documents",
"(",
"self",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"return_embedding",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Document",
"]",
":",
"pass"
] | [
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.
:param filename: Name of the file containing evaluation data (json or jsonl)
:param doc_index: Elasticsearch index where evaluation documents should be stored
:param label_index: Elasticsearch index where labeled questions should be stored
:param batch_size: Optional number of documents that are loaded and processed at a time.
When set to None (default) all documents are processed at once.
:param preprocessor: Optional PreProcessor to preprocess evaluation documents.
It can be used for splitting documents into passages (and assigning labels to corresponding passages).
Currently the PreProcessor does not support split_by sentence, cleaning nor split_overlap != 0.
When set to None (default) preprocessing is disabled.
:param max_docs: Optional number of documents that will be loaded.
When set to None (default) all available eval documents are used.
|
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 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.
:param filename: Name of the file containing evaluation data (json or jsonl)
:param doc_index: Elasticsearch index where evaluation documents should be stored
:param label_index: Elasticsearch index where labeled questions should be stored
:param batch_size: Optional number of documents that are loaded and processed at a time.
When set to None (default) all documents are processed at once.
:param preprocessor: Optional PreProcessor to preprocess evaluation documents.
It can be used for splitting documents into passages (and assigning labels to corresponding passages).
Currently the PreProcessor does not support split_by sentence, cleaning nor split_overlap != 0.
When set to None (default) preprocessing is disabled.
:param max_docs: Optional number of documents that will be loaded.
When set to None (default) all available eval documents are used.
"""
# TODO improve support for PreProcessor when adding eval data
if preprocessor is not None:
assert preprocessor.split_by != "sentence", f"Split by sentence not supported.\n" \
f"Please set 'split_by' to either 'word' or 'passage' in the supplied PreProcessor."
assert preprocessor.split_respect_sentence_boundary == False, \
f"split_respect_sentence_boundary not supported yet.\n" \
f"Please set 'split_respect_sentence_boundary' to False in the supplied PreProcessor."
assert preprocessor.split_overlap == 0, f"Overlapping documents are currently not supported when adding eval data.\n" \
f"Please set 'split_overlap=0' in the supplied PreProcessor."
assert preprocessor.clean_empty_lines == False, f"clean_empty_lines currently not supported when adding eval data.\n" \
f"Please set 'clean_empty_lines=False' in the supplied PreProcessor."
assert preprocessor.clean_whitespace == False, f"clean_whitespace is currently not supported when adding eval data.\n" \
f"Please set 'clean_whitespace=False' in the supplied PreProcessor."
assert preprocessor.clean_header_footer == False, f"clean_header_footer is currently not supported when adding eval data.\n" \
f"Please set 'clean_header_footer=False' in the supplied PreProcessor."
file_path = Path(filename)
if file_path.suffix == ".json":
if batch_size is None:
docs, labels = eval_data_from_json(filename, max_docs=max_docs, preprocessor=preprocessor)
self.write_documents(docs, index=doc_index)
self.write_labels(labels, index=label_index)
else:
jsonl_filename = (file_path.parent / (file_path.stem + '.jsonl')).as_posix()
logger.info(f"Adding evaluation data batch-wise is not compatible with json-formatted SQuAD files. "
f"Converting json to jsonl to: {jsonl_filename}")
squad_json_to_jsonl(filename, jsonl_filename)
self.add_eval_data(jsonl_filename, doc_index, label_index, batch_size)
elif file_path.suffix == ".jsonl":
for docs, labels in eval_data_from_jsonl(filename, batch_size, max_docs=max_docs, preprocessor=preprocessor):
if docs:
self.write_documents(docs, index=doc_index)
if labels:
self.write_labels(labels, index=label_index)
else:
logger.error("File needs to be in json or jsonl format.") | [
"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",
")",
":",
"# TODO improve support for PreProcessor when adding eval data",
"if",
"preprocessor",
"is",
"not",
"None",
":",
"assert",
"preprocessor",
".",
"split_by",
"!=",
"\"sentence\"",
",",
"f\"Split by sentence not supported.\\n\"",
"f\"Please set 'split_by' to either 'word' or 'passage' in the supplied PreProcessor.\"",
"assert",
"preprocessor",
".",
"split_respect_sentence_boundary",
"==",
"False",
",",
"f\"split_respect_sentence_boundary not supported yet.\\n\"",
"f\"Please set 'split_respect_sentence_boundary' to False in the supplied PreProcessor.\"",
"assert",
"preprocessor",
".",
"split_overlap",
"==",
"0",
",",
"f\"Overlapping documents are currently not supported when adding eval data.\\n\"",
"f\"Please set 'split_overlap=0' in the supplied PreProcessor.\"",
"assert",
"preprocessor",
".",
"clean_empty_lines",
"==",
"False",
",",
"f\"clean_empty_lines currently not supported when adding eval data.\\n\"",
"f\"Please set 'clean_empty_lines=False' in the supplied PreProcessor.\"",
"assert",
"preprocessor",
".",
"clean_whitespace",
"==",
"False",
",",
"f\"clean_whitespace is currently not supported when adding eval data.\\n\"",
"f\"Please set 'clean_whitespace=False' in the supplied PreProcessor.\"",
"assert",
"preprocessor",
".",
"clean_header_footer",
"==",
"False",
",",
"f\"clean_header_footer is currently not supported when adding eval data.\\n\"",
"f\"Please set 'clean_header_footer=False' in the supplied PreProcessor.\"",
"file_path",
"=",
"Path",
"(",
"filename",
")",
"if",
"file_path",
".",
"suffix",
"==",
"\".json\"",
":",
"if",
"batch_size",
"is",
"None",
":",
"docs",
",",
"labels",
"=",
"eval_data_from_json",
"(",
"filename",
",",
"max_docs",
"=",
"max_docs",
",",
"preprocessor",
"=",
"preprocessor",
")",
"self",
".",
"write_documents",
"(",
"docs",
",",
"index",
"=",
"doc_index",
")",
"self",
".",
"write_labels",
"(",
"labels",
",",
"index",
"=",
"label_index",
")",
"else",
":",
"jsonl_filename",
"=",
"(",
"file_path",
".",
"parent",
"/",
"(",
"file_path",
".",
"stem",
"+",
"'.jsonl'",
")",
")",
".",
"as_posix",
"(",
")",
"logger",
".",
"info",
"(",
"f\"Adding evaluation data batch-wise is not compatible with json-formatted SQuAD files. \"",
"f\"Converting json to jsonl to: {jsonl_filename}\"",
")",
"squad_json_to_jsonl",
"(",
"filename",
",",
"jsonl_filename",
")",
"self",
".",
"add_eval_data",
"(",
"jsonl_filename",
",",
"doc_index",
",",
"label_index",
",",
"batch_size",
")",
"elif",
"file_path",
".",
"suffix",
"==",
"\".jsonl\"",
":",
"for",
"docs",
",",
"labels",
"in",
"eval_data_from_jsonl",
"(",
"filename",
",",
"batch_size",
",",
"max_docs",
"=",
"max_docs",
",",
"preprocessor",
"=",
"preprocessor",
")",
":",
"if",
"docs",
":",
"self",
".",
"write_documents",
"(",
"docs",
",",
"index",
"=",
"doc_index",
")",
"if",
"labels",
":",
"self",
".",
"write_labels",
"(",
"labels",
",",
"index",
"=",
"label_index",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"File needs to be in json or jsonl format.\"",
")"
] | [
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 ' +
'or expand simple_copy support.' % type(x)) | [
"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_copy support.'",
"%",
"type",
"(",
"x",
")",
")"
] | [
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.
additional_dependencies: other files which may trigger the rule.
outputs: outputs of the rule.
extensions: extensions handled by the rule.
"""
rule = ['CustomBuildRule',
{'Name': name,
'ExecutionDescription': description,
'CommandLine': cmd,
'Outputs': ';'.join(outputs),
'FileExtensions': ';'.join(extensions),
'AdditionalDependencies':
';'.join(additional_dependencies)
}]
self.rules_section.append(rule) | [
"def",
"AddCustomBuildRule",
"(",
"self",
",",
"name",
",",
"cmd",
",",
"description",
",",
"additional_dependencies",
",",
"outputs",
",",
"extensions",
")",
":",
"rule",
"=",
"[",
"'CustomBuildRule'",
",",
"{",
"'Name'",
":",
"name",
",",
"'ExecutionDescription'",
":",
"description",
",",
"'CommandLine'",
":",
"cmd",
",",
"'Outputs'",
":",
"';'",
".",
"join",
"(",
"outputs",
")",
",",
"'FileExtensions'",
":",
"';'",
".",
"join",
"(",
"extensions",
")",
",",
"'AdditionalDependencies'",
":",
"';'",
".",
"join",
"(",
"additional_dependencies",
")",
"}",
"]",
"self",
".",
"rules_section",
".",
"append",
"(",
"rule",
")"
] | [
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,
encoding="Windows-1252") | [
"def",
"WriteIfChanged",
"(",
"self",
")",
":",
"content",
"=",
"[",
"'VisualStudioToolFile'",
",",
"{",
"'Version'",
":",
"'8.00'",
",",
"'Name'",
":",
"self",
".",
"name",
"}",
",",
"self",
".",
"rules_section",
"]",
"easy_xml",
".",
"WriteXmlIfChanged",
"(",
"content",
",",
"self",
".",
"tool_file_path",
",",
"encoding",
"=",
"\"Windows-1252\"",
")"
] | [
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
var tour2 = new Tour({
});""")
backdrop_style = style_sheet.bt_backdrop_style
js_utils.add_css_style(driver, backdrop_style)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
for x in range(4):
js_utils.activate_jquery(driver)
js_utils.add_css_link(driver, bootstrap_tour_css)
js_utils.add_js_link(driver, bootstrap_tour_js)
time.sleep(0.1)
for x in range(int(settings.MINI_TIMEOUT * 2.0)):
# Bootstrap needs a small amount of time to load & activate.
try:
driver.execute_script(verify_script)
time.sleep(0.05)
return
except Exception:
time.sleep(0.15)
js_utils.raise_unable_to_load_jquery_exception(driver) | [
"def",
"activate_bootstrap",
"(",
"driver",
")",
":",
"bootstrap_tour_css",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_CSS",
"bootstrap_tour_js",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_JS",
"verify_script",
"=",
"(",
"\"\"\"// Verify Bootstrap Tour activated\n var tour2 = new Tour({\n });\"\"\"",
")",
"backdrop_style",
"=",
"style_sheet",
".",
"bt_backdrop_style",
"js_utils",
".",
"add_css_style",
"(",
"driver",
",",
"backdrop_style",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"js_utils",
".",
"activate_jquery",
"(",
"driver",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"bootstrap_tour_css",
")",
"js_utils",
".",
"add_js_link",
"(",
"driver",
",",
"bootstrap_tour_js",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"settings",
".",
"MINI_TIMEOUT",
"*",
"2.0",
")",
")",
":",
"# Bootstrap needs a small amount of time to load & activate.",
"try",
":",
"driver",
".",
"execute_script",
"(",
"verify_script",
")",
"time",
".",
"sleep",
"(",
"0.05",
")",
"return",
"except",
"Exception",
":",
"time",
".",
"sleep",
"(",
"0.15",
")",
"js_utils",
".",
"raise_unable_to_load_jquery_exception",
"(",
"driver",
")"
] | [
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 DriverJS activated
var driverjs2 = Driver.name;
""")
activate_bootstrap(driver)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
js_utils.add_css_style(driver, backdrop_style)
for x in range(4):
js_utils.activate_jquery(driver)
js_utils.add_css_link(driver, driverjs_css)
js_utils.add_js_link(driver, driverjs_js)
time.sleep(0.1)
for x in range(int(settings.MINI_TIMEOUT * 2.0)):
# DriverJS needs a small amount of time to load & activate.
try:
driver.execute_script(verify_script)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
time.sleep(0.05)
return
except Exception:
time.sleep(0.15)
js_utils.raise_unable_to_load_jquery_exception(driver) | [
"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",
"=",
"(",
"\"\"\"// Verify DriverJS activated\n var driverjs2 = Driver.name;\n \"\"\"",
")",
"activate_bootstrap",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"js_utils",
".",
"add_css_style",
"(",
"driver",
",",
"backdrop_style",
")",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"js_utils",
".",
"activate_jquery",
"(",
"driver",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"driverjs_css",
")",
"js_utils",
".",
"add_js_link",
"(",
"driver",
",",
"driverjs_js",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"settings",
".",
"MINI_TIMEOUT",
"*",
"2.0",
")",
")",
":",
"# DriverJS needs a small amount of time to load & activate.",
"try",
":",
"driver",
".",
"execute_script",
"(",
"verify_script",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"time",
".",
"sleep",
"(",
"0.05",
")",
"return",
"except",
"Exception",
":",
"time",
".",
"sleep",
"(",
"0.15",
")",
"js_utils",
".",
"raise_unable_to_load_jquery_exception",
"(",
"driver",
")"
] | [
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 = ("""// Verify Hopscotch activated
var hops = hopscotch.isActive;
""")
activate_bootstrap(driver)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
js_utils.add_css_style(driver, backdrop_style)
for x in range(4):
js_utils.activate_jquery(driver)
js_utils.add_css_link(driver, hopscotch_css)
js_utils.add_js_link(driver, hopscotch_js)
time.sleep(0.1)
for x in range(int(settings.MINI_TIMEOUT * 2.0)):
# Hopscotch needs a small amount of time to load & activate.
try:
driver.execute_script(verify_script)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
time.sleep(0.05)
return
except Exception:
time.sleep(0.15)
js_utils.raise_unable_to_load_jquery_exception(driver) | [
"def",
"activate_hopscotch",
"(",
"driver",
")",
":",
"hopscotch_css",
"=",
"constants",
".",
"Hopscotch",
".",
"MIN_CSS",
"hopscotch_js",
"=",
"constants",
".",
"Hopscotch",
".",
"MIN_JS",
"backdrop_style",
"=",
"style_sheet",
".",
"hops_backdrop_style",
"verify_script",
"=",
"(",
"\"\"\"// Verify Hopscotch activated\n var hops = hopscotch.isActive;\n \"\"\"",
")",
"activate_bootstrap",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"js_utils",
".",
"add_css_style",
"(",
"driver",
",",
"backdrop_style",
")",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"js_utils",
".",
"activate_jquery",
"(",
"driver",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"hopscotch_css",
")",
"js_utils",
".",
"add_js_link",
"(",
"driver",
",",
"hopscotch_js",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"settings",
".",
"MINI_TIMEOUT",
"*",
"2.0",
")",
")",
":",
"# Hopscotch needs a small amount of time to load & activate.",
"try",
":",
"driver",
".",
"execute_script",
"(",
"verify_script",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"time",
".",
"sleep",
"(",
"0.05",
")",
"return",
"except",
"Exception",
":",
"time",
".",
"sleep",
"(",
"0.15",
")",
"js_utils",
".",
"raise_unable_to_load_jquery_exception",
"(",
"driver",
")"
] | [
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();
""")
activate_bootstrap(driver)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
for x in range(4):
js_utils.activate_jquery(driver)
js_utils.add_css_link(driver, intro_css)
js_utils.add_js_link(driver, intro_js)
time.sleep(0.1)
for x in range(int(settings.MINI_TIMEOUT * 2.0)):
# IntroJS needs a small amount of time to load & activate.
try:
driver.execute_script(verify_script)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
time.sleep(0.05)
return
except Exception:
time.sleep(0.15)
js_utils.raise_unable_to_load_jquery_exception(driver) | [
"def",
"activate_introjs",
"(",
"driver",
")",
":",
"intro_css",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_CSS",
"intro_js",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_JS",
"verify_script",
"=",
"(",
"\"\"\"// Verify IntroJS activated\n var intro2 = introJs();\n \"\"\"",
")",
"activate_bootstrap",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"js_utils",
".",
"activate_jquery",
"(",
"driver",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"intro_css",
")",
"js_utils",
".",
"add_js_link",
"(",
"driver",
",",
"intro_js",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"settings",
".",
"MINI_TIMEOUT",
"*",
"2.0",
")",
")",
":",
"# IntroJS needs a small amount of time to load & activate.",
"try",
":",
"driver",
".",
"execute_script",
"(",
"verify_script",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"time",
".",
"sleep",
"(",
"0.05",
")",
"return",
"except",
"Exception",
":",
"time",
".",
"sleep",
"(",
"0.15",
")",
"js_utils",
".",
"raise_unable_to_load_jquery_exception",
"(",
"driver",
")"
] | [
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_FIX_CSS
sh_theme_default_css = constants.Shepherd.THEME_DEFAULT_CSS
sh_theme_dark_css = constants.Shepherd.THEME_DARK_CSS
sh_theme_sq_css = constants.Shepherd.THEME_SQ_CSS
sh_theme_sq_dark_css = constants.Shepherd.THEME_SQ_DK_CSS
tether_js = constants.Tether.MIN_JS
spinner_css = constants.Messenger.SPINNER_CSS
sh_style = style_sheet.sh_style_test
backdrop_style = style_sheet.sh_backdrop_style
activate_bootstrap(driver)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
js_utils.add_css_style(driver, backdrop_style)
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
for x in range(4):
js_utils.add_css_link(driver, spinner_css)
js_utils.add_css_link(driver, sh_theme_arrows_css)
js_utils.add_css_link(driver, sh_theme_arrows_fix_css)
js_utils.add_css_link(driver, sh_theme_default_css)
js_utils.add_css_link(driver, sh_theme_dark_css)
js_utils.add_css_link(driver, sh_theme_sq_css)
js_utils.add_css_link(driver, sh_theme_sq_dark_css)
js_utils.add_js_link(driver, tether_js)
js_utils.add_js_link(driver, shepherd_js)
time.sleep(0.1)
for x in range(int(settings.MINI_TIMEOUT * 2.0)):
# Shepherd needs a small amount of time to load & activate.
try:
driver.execute_script(sh_style) # Verify Shepherd has loaded
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
driver.execute_script(sh_style) # Need it twice for ordering
js_utils.wait_for_ready_state_complete(driver)
js_utils.wait_for_angularjs(driver)
time.sleep(0.05)
return
except Exception:
time.sleep(0.15)
js_utils.raise_unable_to_load_jquery_exception(driver) | [
"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",
".",
"THEME_ARR_FIX_CSS",
"sh_theme_default_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_DEFAULT_CSS",
"sh_theme_dark_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_DARK_CSS",
"sh_theme_sq_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_SQ_CSS",
"sh_theme_sq_dark_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_SQ_DK_CSS",
"tether_js",
"=",
"constants",
".",
"Tether",
".",
"MIN_JS",
"spinner_css",
"=",
"constants",
".",
"Messenger",
".",
"SPINNER_CSS",
"sh_style",
"=",
"style_sheet",
".",
"sh_style_test",
"backdrop_style",
"=",
"style_sheet",
".",
"sh_backdrop_style",
"activate_bootstrap",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"js_utils",
".",
"add_css_style",
"(",
"driver",
",",
"backdrop_style",
")",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"spinner_css",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"sh_theme_arrows_css",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"sh_theme_arrows_fix_css",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"sh_theme_default_css",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"sh_theme_dark_css",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"sh_theme_sq_css",
")",
"js_utils",
".",
"add_css_link",
"(",
"driver",
",",
"sh_theme_sq_dark_css",
")",
"js_utils",
".",
"add_js_link",
"(",
"driver",
",",
"tether_js",
")",
"js_utils",
".",
"add_js_link",
"(",
"driver",
",",
"shepherd_js",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"settings",
".",
"MINI_TIMEOUT",
"*",
"2.0",
")",
")",
":",
"# Shepherd needs a small amount of time to load & activate.",
"try",
":",
"driver",
".",
"execute_script",
"(",
"sh_style",
")",
"# Verify Shepherd has loaded",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"driver",
".",
"execute_script",
"(",
"sh_style",
")",
"# Need it twice for ordering",
"js_utils",
".",
"wait_for_ready_state_complete",
"(",
"driver",
")",
"js_utils",
".",
"wait_for_angularjs",
"(",
"driver",
")",
"time",
".",
"sleep",
"(",
"0.05",
")",
"return",
"except",
"Exception",
":",
"time",
".",
"sleep",
"(",
"0.15",
")",
"js_utils",
".",
"raise_unable_to_load_jquery_exception",
"(",
"driver",
")"
] | [
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 = tour;""")
autoplay = False
if interval and interval > 0:
autoplay = True
interval = float(interval)
if interval < 0.5:
interval = 0.5
if not is_shepherd_activated(driver):
activate_shepherd(driver)
if len(tour_steps[name]) > 1:
try:
selector = re.search(
r"[\S\s]+{element: '([\S\s]+)', on: [\S\s]+",
tour_steps[name][1]).group(1)
selector = selector.replace('\\', '')
page_actions.wait_for_element_present(
driver, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT)
except Exception:
js_utils.post_messenger_error_message(
driver, "Tour Error: {'%s'} was not found!" % selector,
msg_dur)
raise Exception(
"Tour Error: {'%s'} was not found! "
"Exiting due to failure on first tour step!"
"" % selector)
driver.execute_script(instructions)
tour_on = True
if autoplay:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
latest_element = None
latest_text = None
while tour_on:
try:
time.sleep(0.01)
result = driver.execute_script(
"return Shepherd.activeTour.currentStep.isOpen()")
except Exception:
tour_on = False
result = None
if result:
tour_on = True
if autoplay:
try:
element = driver.execute_script(
"return Shepherd.activeTour.currentStep"
".options.attachTo.element")
shep_text = driver.execute_script(
"return Shepherd.activeTour.currentStep"
".options.text")
except Exception:
continue
if element != latest_element or shep_text != latest_text:
latest_element = element
latest_text = shep_text
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
if ((element == latest_element) and (
shep_text == latest_text)):
driver.execute_script("Shepherd.activeTour.next()")
try:
latest_element = driver.execute_script(
"return Shepherd.activeTour.currentStep"
".options.attachTo.element")
latest_text = driver.execute_script(
"return Shepherd.activeTour.currentStep"
".options.text")
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
except Exception:
pass
continue
else:
try:
time.sleep(0.01)
selector = driver.execute_script(
"return Shepherd.activeTour"
".currentStep.options.attachTo.element")
try:
js_utils.wait_for_css_query_selector(
driver, selector, timeout=settings.SMALL_TIMEOUT)
except Exception:
remove_script = (
"jQuery('%s').remove()" % "div.shepherd-content")
driver.execute_script(remove_script)
js_utils.post_messenger_error_message(
driver, "Tour Error: {'%s'} was not found!" % selector,
msg_dur)
time.sleep(0.1)
driver.execute_script("Shepherd.activeTour.next()")
if autoplay:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
tour_on = True
except Exception:
tour_on = False
time.sleep(0.1) | [
"def",
"play_shepherd_tour",
"(",
"driver",
",",
"tour_steps",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
"tour_step",
"instructions",
"+=",
"(",
"\"\"\"\n // Start the tour\n tour.start();\n $tour = tour;\"\"\"",
")",
"autoplay",
"=",
"False",
"if",
"interval",
"and",
"interval",
">",
"0",
":",
"autoplay",
"=",
"True",
"interval",
"=",
"float",
"(",
"interval",
")",
"if",
"interval",
"<",
"0.5",
":",
"interval",
"=",
"0.5",
"if",
"not",
"is_shepherd_activated",
"(",
"driver",
")",
":",
"activate_shepherd",
"(",
"driver",
")",
"if",
"len",
"(",
"tour_steps",
"[",
"name",
"]",
")",
">",
"1",
":",
"try",
":",
"selector",
"=",
"re",
".",
"search",
"(",
"r\"[\\S\\s]+{element: '([\\S\\s]+)', on: [\\S\\s]+\"",
",",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
")",
".",
"group",
"(",
"1",
")",
"selector",
"=",
"selector",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
"except",
"Exception",
":",
"js_utils",
".",
"post_messenger_error_message",
"(",
"driver",
",",
"\"Tour Error: {'%s'} was not found!\"",
"%",
"selector",
",",
"msg_dur",
")",
"raise",
"Exception",
"(",
"\"Tour Error: {'%s'} was not found! \"",
"\"Exiting due to failure on first tour step!\"",
"\"\"",
"%",
"selector",
")",
"driver",
".",
"execute_script",
"(",
"instructions",
")",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"latest_element",
"=",
"None",
"latest_text",
"=",
"None",
"while",
"tour_on",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"result",
"=",
"driver",
".",
"execute_script",
"(",
"\"return Shepherd.activeTour.currentStep.isOpen()\"",
")",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"result",
"=",
"None",
"if",
"result",
":",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"try",
":",
"element",
"=",
"driver",
".",
"execute_script",
"(",
"\"return Shepherd.activeTour.currentStep\"",
"\".options.attachTo.element\"",
")",
"shep_text",
"=",
"driver",
".",
"execute_script",
"(",
"\"return Shepherd.activeTour.currentStep\"",
"\".options.text\"",
")",
"except",
"Exception",
":",
"continue",
"if",
"element",
"!=",
"latest_element",
"or",
"shep_text",
"!=",
"latest_text",
":",
"latest_element",
"=",
"element",
"latest_text",
"=",
"shep_text",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"if",
"(",
"(",
"element",
"==",
"latest_element",
")",
"and",
"(",
"shep_text",
"==",
"latest_text",
")",
")",
":",
"driver",
".",
"execute_script",
"(",
"\"Shepherd.activeTour.next()\"",
")",
"try",
":",
"latest_element",
"=",
"driver",
".",
"execute_script",
"(",
"\"return Shepherd.activeTour.currentStep\"",
"\".options.attachTo.element\"",
")",
"latest_text",
"=",
"driver",
".",
"execute_script",
"(",
"\"return Shepherd.activeTour.currentStep\"",
"\".options.text\"",
")",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"except",
"Exception",
":",
"pass",
"continue",
"else",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"selector",
"=",
"driver",
".",
"execute_script",
"(",
"\"return Shepherd.activeTour\"",
"\".currentStep.options.attachTo.element\"",
")",
"try",
":",
"js_utils",
".",
"wait_for_css_query_selector",
"(",
"driver",
",",
"selector",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
"except",
"Exception",
":",
"remove_script",
"=",
"(",
"\"jQuery('%s').remove()\"",
"%",
"\"div.shepherd-content\"",
")",
"driver",
".",
"execute_script",
"(",
"remove_script",
")",
"js_utils",
".",
"post_messenger_error_message",
"(",
"driver",
",",
"\"Tour Error: {'%s'} was not found!\"",
"%",
"selector",
",",
"msg_dur",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"driver",
".",
"execute_script",
"(",
"\"Shepherd.activeTour.next()\"",
")",
"if",
"autoplay",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"tour_on",
"=",
"True",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | [
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
tour.init();
// Start the tour
tour.start();
// Fix timing issue by restarting tour immediately
tour.restart();
// Save for later
$tour = tour;""")
if interval and interval > 0:
if interval < 1:
interval = 1
interval = str(float(interval) * 1000.0)
instructions = instructions.replace(
'duration: 0,', 'duration: %s,' % interval)
if not is_bootstrap_activated(driver):
activate_bootstrap(driver)
if len(tour_steps[name]) > 1:
try:
if "element: " in tour_steps[name][1]:
selector = re.search(
r"[\S\s]+element: '([\S\s]+)',[\S\s]+title: '",
tour_steps[name][1]).group(1)
selector = selector.replace('\\', '').replace(':first', '')
page_actions.wait_for_element_present(
driver, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT)
else:
selector = "html"
except Exception:
js_utils.post_messenger_error_message(
driver, "Tour Error: {'%s'} was not found!" % selector,
msg_dur)
raise Exception(
"Tour Error: {'%s'} was not found! "
"Exiting due to failure on first tour step!"
"" % selector)
driver.execute_script(instructions)
tour_on = True
while tour_on:
try:
time.sleep(0.01)
if browser != "firefox":
result = driver.execute_script(
"return $tour.ended()")
else:
page_actions.wait_for_element_present(
driver, ".tour-tour", by=By.CSS_SELECTOR, timeout=0.4)
result = False
except Exception:
tour_on = False
result = None
if result is False:
tour_on = True
else:
try:
time.sleep(0.01)
if browser != "firefox":
result = driver.execute_script(
"return $tour.ended()")
else:
page_actions.wait_for_element_present(
driver, ".tour-tour", by=By.CSS_SELECTOR, timeout=0.4)
result = False
if result is False:
time.sleep(0.1)
continue
else:
return
except Exception:
tour_on = False
time.sleep(0.1) | [
"def",
"play_bootstrap_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
"tour_step",
"instructions",
"+=",
"(",
"\"\"\"]);\n // Initialize the tour\n tour.init();\n // Start the tour\n tour.start();\n // Fix timing issue by restarting tour immediately\n tour.restart();\n // Save for later\n $tour = tour;\"\"\"",
")",
"if",
"interval",
"and",
"interval",
">",
"0",
":",
"if",
"interval",
"<",
"1",
":",
"interval",
"=",
"1",
"interval",
"=",
"str",
"(",
"float",
"(",
"interval",
")",
"*",
"1000.0",
")",
"instructions",
"=",
"instructions",
".",
"replace",
"(",
"'duration: 0,'",
",",
"'duration: %s,'",
"%",
"interval",
")",
"if",
"not",
"is_bootstrap_activated",
"(",
"driver",
")",
":",
"activate_bootstrap",
"(",
"driver",
")",
"if",
"len",
"(",
"tour_steps",
"[",
"name",
"]",
")",
">",
"1",
":",
"try",
":",
"if",
"\"element: \"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
":",
"selector",
"=",
"re",
".",
"search",
"(",
"r\"[\\S\\s]+element: '([\\S\\s]+)',[\\S\\s]+title: '\"",
",",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
")",
".",
"group",
"(",
"1",
")",
"selector",
"=",
"selector",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
".",
"replace",
"(",
"':first'",
",",
"''",
")",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
"else",
":",
"selector",
"=",
"\"html\"",
"except",
"Exception",
":",
"js_utils",
".",
"post_messenger_error_message",
"(",
"driver",
",",
"\"Tour Error: {'%s'} was not found!\"",
"%",
"selector",
",",
"msg_dur",
")",
"raise",
"Exception",
"(",
"\"Tour Error: {'%s'} was not found! \"",
"\"Exiting due to failure on first tour step!\"",
"\"\"",
"%",
"selector",
")",
"driver",
".",
"execute_script",
"(",
"instructions",
")",
"tour_on",
"=",
"True",
"while",
"tour_on",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour.ended()\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\".tour-tour\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"False",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"result",
"=",
"None",
"if",
"result",
"is",
"False",
":",
"tour_on",
"=",
"True",
"else",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour.ended()\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\".tour-tour\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"False",
"if",
"result",
"is",
"False",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"continue",
"else",
":",
"return",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | [
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!
tour.start();
$tour = tour;""")
autoplay = False
if interval and interval > 0:
autoplay = True
interval = float(interval)
if interval < 0.5:
interval = 0.5
if not is_driverjs_activated(driver):
activate_driverjs(driver)
if len(tour_steps[name]) > 1:
try:
if "element: " in tour_steps[name][1]:
selector = re.search(
r"[\S\s]+element: '([\S\s]+)',[\S\s]+popover: {",
tour_steps[name][1]).group(1)
selector = selector.replace('\\', '').replace(':first', '')
page_actions.wait_for_element_present(
driver, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT)
else:
selector = "html"
except Exception:
js_utils.post_messenger_error_message(
driver, "Tour Error: {'%s'} was not found!" % selector,
msg_dur)
raise Exception(
"Tour Error: {'%s'} was not found! "
"Exiting due to failure on first tour step!"
"" % selector)
driver.execute_script(instructions)
driver.execute_script(
'document.querySelector(".driver-next-btn").focus();')
tour_on = True
if autoplay:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
latest_step = 0
while tour_on:
try:
time.sleep(0.01)
if browser != "firefox":
result = not driver.execute_script(
"return $tour.isActivated")
else:
page_actions.wait_for_element_present(
driver, "#driver-popover-item",
by=By.CSS_SELECTOR, timeout=0.4)
result = False
except Exception:
tour_on = False
result = None
if result is False:
tour_on = True
driver.execute_script(
'document.querySelector(".driver-next-btn").focus();')
if autoplay:
try:
current_step = driver.execute_script(
"return $tour.currentStep")
except Exception:
continue
if current_step != latest_step:
latest_step = current_step
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
if current_step == latest_step:
driver.execute_script("$tour.moveNext()")
try:
latest_step = driver.execute_script(
"return $tour.currentStep")
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
except Exception:
pass
continue
else:
try:
time.sleep(0.01)
if browser != "firefox":
result = not driver.execute_script(
"return $tour.isActivated")
else:
page_actions.wait_for_element_present(
driver, "#driver-popover-item",
by=By.CSS_SELECTOR, timeout=0.4)
result = False
if result is False:
time.sleep(0.1)
continue
else:
return
except Exception:
tour_on = False
time.sleep(0.1) | [
"def",
"play_driverjs_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
"tour_step",
"instructions",
"+=",
"(",
"\"\"\"]\n );\n // Start the tour!\n tour.start();\n $tour = tour;\"\"\"",
")",
"autoplay",
"=",
"False",
"if",
"interval",
"and",
"interval",
">",
"0",
":",
"autoplay",
"=",
"True",
"interval",
"=",
"float",
"(",
"interval",
")",
"if",
"interval",
"<",
"0.5",
":",
"interval",
"=",
"0.5",
"if",
"not",
"is_driverjs_activated",
"(",
"driver",
")",
":",
"activate_driverjs",
"(",
"driver",
")",
"if",
"len",
"(",
"tour_steps",
"[",
"name",
"]",
")",
">",
"1",
":",
"try",
":",
"if",
"\"element: \"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
":",
"selector",
"=",
"re",
".",
"search",
"(",
"r\"[\\S\\s]+element: '([\\S\\s]+)',[\\S\\s]+popover: {\"",
",",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
")",
".",
"group",
"(",
"1",
")",
"selector",
"=",
"selector",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
".",
"replace",
"(",
"':first'",
",",
"''",
")",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
"else",
":",
"selector",
"=",
"\"html\"",
"except",
"Exception",
":",
"js_utils",
".",
"post_messenger_error_message",
"(",
"driver",
",",
"\"Tour Error: {'%s'} was not found!\"",
"%",
"selector",
",",
"msg_dur",
")",
"raise",
"Exception",
"(",
"\"Tour Error: {'%s'} was not found! \"",
"\"Exiting due to failure on first tour step!\"",
"\"\"",
"%",
"selector",
")",
"driver",
".",
"execute_script",
"(",
"instructions",
")",
"driver",
".",
"execute_script",
"(",
"'document.querySelector(\".driver-next-btn\").focus();'",
")",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"latest_step",
"=",
"0",
"while",
"tour_on",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"not",
"driver",
".",
"execute_script",
"(",
"\"return $tour.isActivated\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\"#driver-popover-item\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"False",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"result",
"=",
"None",
"if",
"result",
"is",
"False",
":",
"tour_on",
"=",
"True",
"driver",
".",
"execute_script",
"(",
"'document.querySelector(\".driver-next-btn\").focus();'",
")",
"if",
"autoplay",
":",
"try",
":",
"current_step",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour.currentStep\"",
")",
"except",
"Exception",
":",
"continue",
"if",
"current_step",
"!=",
"latest_step",
":",
"latest_step",
"=",
"current_step",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"if",
"current_step",
"==",
"latest_step",
":",
"driver",
".",
"execute_script",
"(",
"\"$tour.moveNext()\"",
")",
"try",
":",
"latest_step",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour.currentStep\"",
")",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"except",
"Exception",
":",
"pass",
"continue",
"else",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"not",
"driver",
".",
"execute_script",
"(",
"\"return $tour.isActivated\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\"#driver-popover-item\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"False",
"if",
"result",
"is",
"False",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"continue",
"else",
":",
"return",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | [
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!
hopscotch.startTour(tour);
$tour = hopscotch;""")
autoplay = False
if interval and interval > 0:
autoplay = True
interval = float(interval)
if interval < 0.5:
interval = 0.5
if not is_hopscotch_activated(driver):
activate_hopscotch(driver)
if len(tour_steps[name]) > 1:
try:
if "target: " in tour_steps[name][1]:
selector = re.search(
r"[\S\s]+target: '([\S\s]+)',[\S\s]+title: '",
tour_steps[name][1]).group(1)
selector = selector.replace('\\', '').replace(':first', '')
page_actions.wait_for_element_present(
driver, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT)
else:
selector = "html"
except Exception:
js_utils.post_messenger_error_message(
driver, "Tour Error: {'%s'} was not found!" % selector,
msg_dur)
raise Exception(
"Tour Error: {'%s'} was not found! "
"Exiting due to failure on first tour step!"
"" % selector)
driver.execute_script(instructions)
tour_on = True
if autoplay:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
latest_step = 0
while tour_on:
try:
time.sleep(0.01)
if browser != "firefox":
result = not driver.execute_script(
"return $tour.isActive")
else:
page_actions.wait_for_element_present(
driver, ".hopscotch-bubble",
by=By.CSS_SELECTOR, timeout=0.4)
result = False
except Exception:
tour_on = False
result = None
if result is False:
tour_on = True
if autoplay:
try:
current_step = driver.execute_script(
"return $tour.getCurrStepNum()")
except Exception:
continue
if current_step != latest_step:
latest_step = current_step
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
if current_step == latest_step:
driver.execute_script("$tour.nextStep()")
try:
latest_step = driver.execute_script(
"return $tour.getCurrStepNum()")
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
except Exception:
pass
continue
else:
try:
time.sleep(0.01)
if browser != "firefox":
result = not driver.execute_script(
"return $tour.isActive")
else:
page_actions.wait_for_element_present(
driver, ".hopscotch-bubble",
by=By.CSS_SELECTOR, timeout=0.4)
result = False
if result is False:
time.sleep(0.1)
continue
else:
return
except Exception:
tour_on = False
time.sleep(0.1) | [
"def",
"play_hopscotch_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
"tour_step",
"instructions",
"+=",
"(",
"\"\"\"]\n };\n // Start the tour!\n hopscotch.startTour(tour);\n $tour = hopscotch;\"\"\"",
")",
"autoplay",
"=",
"False",
"if",
"interval",
"and",
"interval",
">",
"0",
":",
"autoplay",
"=",
"True",
"interval",
"=",
"float",
"(",
"interval",
")",
"if",
"interval",
"<",
"0.5",
":",
"interval",
"=",
"0.5",
"if",
"not",
"is_hopscotch_activated",
"(",
"driver",
")",
":",
"activate_hopscotch",
"(",
"driver",
")",
"if",
"len",
"(",
"tour_steps",
"[",
"name",
"]",
")",
">",
"1",
":",
"try",
":",
"if",
"\"target: \"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
":",
"selector",
"=",
"re",
".",
"search",
"(",
"r\"[\\S\\s]+target: '([\\S\\s]+)',[\\S\\s]+title: '\"",
",",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
")",
".",
"group",
"(",
"1",
")",
"selector",
"=",
"selector",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
".",
"replace",
"(",
"':first'",
",",
"''",
")",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
"else",
":",
"selector",
"=",
"\"html\"",
"except",
"Exception",
":",
"js_utils",
".",
"post_messenger_error_message",
"(",
"driver",
",",
"\"Tour Error: {'%s'} was not found!\"",
"%",
"selector",
",",
"msg_dur",
")",
"raise",
"Exception",
"(",
"\"Tour Error: {'%s'} was not found! \"",
"\"Exiting due to failure on first tour step!\"",
"\"\"",
"%",
"selector",
")",
"driver",
".",
"execute_script",
"(",
"instructions",
")",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"latest_step",
"=",
"0",
"while",
"tour_on",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"not",
"driver",
".",
"execute_script",
"(",
"\"return $tour.isActive\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\".hopscotch-bubble\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"False",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"result",
"=",
"None",
"if",
"result",
"is",
"False",
":",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"try",
":",
"current_step",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour.getCurrStepNum()\"",
")",
"except",
"Exception",
":",
"continue",
"if",
"current_step",
"!=",
"latest_step",
":",
"latest_step",
"=",
"current_step",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"if",
"current_step",
"==",
"latest_step",
":",
"driver",
".",
"execute_script",
"(",
"\"$tour.nextStep()\"",
")",
"try",
":",
"latest_step",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour.getCurrStepNum()\"",
")",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"except",
"Exception",
":",
"pass",
"continue",
"else",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"not",
"driver",
".",
"execute_script",
"(",
"\"return $tour.isActive\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\".hopscotch-bubble\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"False",
"if",
"result",
"is",
"False",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"continue",
"else",
":",
"return",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | [
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("disableInteraction", true);
intro.setOption("overlayOpacity", .29);
intro.setOption("scrollToElement", true);
intro.setOption("keyboardNavigation", true);
intro.setOption("exitOnEsc", false);
intro.setOption("exitOnOverlayClick", false);
intro.setOption("showStepNumbers", false);
intro.setOption("showProgress", false);
intro.start();
$tour = intro;
};
// Start the tour
startIntro();
""")
autoplay = False
if interval and interval > 0:
autoplay = True
interval = float(interval)
if interval < 0.5:
interval = 0.5
if not is_introjs_activated(driver):
activate_introjs(driver)
if len(tour_steps[name]) > 1:
try:
if "element: " in tour_steps[name][1]:
selector = re.search(
r"[\S\s]+element: '([\S\s]+)',[\S\s]+intro: '",
tour_steps[name][1]).group(1)
selector = selector.replace('\\', '')
page_actions.wait_for_element_present(
driver, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT)
else:
selector = "html"
except Exception:
js_utils.post_messenger_error_message(
driver, "Tour Error: {'%s'} was not found!" % selector,
msg_dur)
raise Exception(
"Tour Error: {'%s'} was not found! "
"Exiting due to failure on first tour step!"
"" % selector)
driver.execute_script(instructions)
tour_on = True
if autoplay:
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
latest_step = 0
while tour_on:
try:
time.sleep(0.01)
if browser != "firefox":
result = driver.execute_script(
"return $tour._currentStep")
else:
page_actions.wait_for_element_present(
driver, ".introjs-tooltip",
by=By.CSS_SELECTOR, timeout=0.4)
result = True
except Exception:
tour_on = False
result = None
if result is not None:
tour_on = True
if autoplay:
try:
current_step = driver.execute_script(
"return $tour._currentStep")
except Exception:
continue
if current_step != latest_step:
latest_step = current_step
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
if current_step == latest_step:
try:
driver.execute_script("$tour.nextStep()")
except Exception:
driver.execute_script("$tour.exit()")
try:
latest_step = driver.execute_script(
"return $tour._currentStep")
start_ms = time.time() * 1000.0
stop_ms = start_ms + (interval * 1000.0)
except Exception:
pass
continue
else:
try:
time.sleep(0.01)
if browser != "firefox":
result = driver.execute_script(
"return $tour._currentStep")
else:
page_actions.wait_for_element_present(
driver, ".introjs-tooltip",
by=By.CSS_SELECTOR, timeout=0.4)
result = True
if result is not None:
time.sleep(0.1)
continue
else:
return
except Exception:
tour_on = False
time.sleep(0.1) | [
"def",
"play_introjs_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
"tour_step",
"instructions",
"+=",
"(",
"\"\"\"]\n });\n intro.setOption(\"disableInteraction\", true);\n intro.setOption(\"overlayOpacity\", .29);\n intro.setOption(\"scrollToElement\", true);\n intro.setOption(\"keyboardNavigation\", true);\n intro.setOption(\"exitOnEsc\", false);\n intro.setOption(\"exitOnOverlayClick\", false);\n intro.setOption(\"showStepNumbers\", false);\n intro.setOption(\"showProgress\", false);\n intro.start();\n $tour = intro;\n };\n // Start the tour\n startIntro();\n \"\"\"",
")",
"autoplay",
"=",
"False",
"if",
"interval",
"and",
"interval",
">",
"0",
":",
"autoplay",
"=",
"True",
"interval",
"=",
"float",
"(",
"interval",
")",
"if",
"interval",
"<",
"0.5",
":",
"interval",
"=",
"0.5",
"if",
"not",
"is_introjs_activated",
"(",
"driver",
")",
":",
"activate_introjs",
"(",
"driver",
")",
"if",
"len",
"(",
"tour_steps",
"[",
"name",
"]",
")",
">",
"1",
":",
"try",
":",
"if",
"\"element: \"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
":",
"selector",
"=",
"re",
".",
"search",
"(",
"r\"[\\S\\s]+element: '([\\S\\s]+)',[\\S\\s]+intro: '\"",
",",
"tour_steps",
"[",
"name",
"]",
"[",
"1",
"]",
")",
".",
"group",
"(",
"1",
")",
"selector",
"=",
"selector",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
"else",
":",
"selector",
"=",
"\"html\"",
"except",
"Exception",
":",
"js_utils",
".",
"post_messenger_error_message",
"(",
"driver",
",",
"\"Tour Error: {'%s'} was not found!\"",
"%",
"selector",
",",
"msg_dur",
")",
"raise",
"Exception",
"(",
"\"Tour Error: {'%s'} was not found! \"",
"\"Exiting due to failure on first tour step!\"",
"\"\"",
"%",
"selector",
")",
"driver",
".",
"execute_script",
"(",
"instructions",
")",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"latest_step",
"=",
"0",
"while",
"tour_on",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour._currentStep\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\".introjs-tooltip\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"True",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"result",
"=",
"None",
"if",
"result",
"is",
"not",
"None",
":",
"tour_on",
"=",
"True",
"if",
"autoplay",
":",
"try",
":",
"current_step",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour._currentStep\"",
")",
"except",
"Exception",
":",
"continue",
"if",
"current_step",
"!=",
"latest_step",
":",
"latest_step",
"=",
"current_step",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"if",
"current_step",
"==",
"latest_step",
":",
"try",
":",
"driver",
".",
"execute_script",
"(",
"\"$tour.nextStep()\"",
")",
"except",
"Exception",
":",
"driver",
".",
"execute_script",
"(",
"\"$tour.exit()\"",
")",
"try",
":",
"latest_step",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour._currentStep\"",
")",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"interval",
"*",
"1000.0",
")",
"except",
"Exception",
":",
"pass",
"continue",
"else",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"browser",
"!=",
"\"firefox\"",
":",
"result",
"=",
"driver",
".",
"execute_script",
"(",
"\"return $tour._currentStep\"",
")",
"else",
":",
"page_actions",
".",
"wait_for_element_present",
"(",
"driver",
",",
"\".introjs-tooltip\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"0.4",
")",
"result",
"=",
"True",
"if",
"result",
"is",
"not",
"None",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"continue",
"else",
":",
"return",
"except",
"Exception",
":",
"tour_on",
"=",
"False",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | [
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. """
if not name:
name = "default"
if name not in tour_steps:
raise Exception("Tour {%s} does not exist!" % name)
if not filename.endswith('.js'):
raise Exception('Tour file must end in ".js"!')
if not url:
url = "data:,"
tour_type = None
if "Bootstrap" in tour_steps[name][0]:
tour_type = "bootstrap"
elif "DriverJS" in tour_steps[name][0]:
tour_type = "driverjs"
elif "Hopscotch" in tour_steps[name][0]:
tour_type = "hopscotch"
elif "IntroJS" in tour_steps[name][0]:
tour_type = "introjs"
elif "Shepherd" in tour_steps[name][0]:
tour_type = "shepherd"
else:
raise Exception('Unknown tour type!')
instructions = (
'''//////// Load Tour Start Page (if not there now) ////////\n\n'''
'''if (window.location.href != "%s") {\n'''
''' window.location.href="%s";\n'''
'''}\n\n'''
'''//////// Resources ////////\n\n'''
'''function injectCSS(css_link) {'''
'''var head = document.getElementsByTagName("head")[0];'''
'''var link = document.createElement("link");'''
'''link.rel = "stylesheet";'''
'''link.type = "text/css";'''
'''link.href = css_link;'''
'''link.crossorigin = "anonymous";'''
'''head.appendChild(link);'''
'''};\n'''
'''function injectJS(js_link) {'''
'''var head = document.getElementsByTagName("head")[0];'''
'''var script = document.createElement("script");'''
'''script.src = js_link;'''
'''script.defer;'''
'''script.type="text/javascript";'''
'''script.crossorigin = "anonymous";'''
'''script.onload = function() { null };'''
'''head.appendChild(script);'''
'''};\n'''
'''function injectStyle(css) {'''
'''var head = document.getElementsByTagName("head")[0];'''
'''var style = document.createElement("style");'''
'''style.type = "text/css";'''
'''style.appendChild(document.createTextNode(css));'''
'''head.appendChild(style);'''
'''};\n''' % (url, url))
if tour_type == "bootstrap":
jquery_js = constants.JQuery.MIN_JS
bootstrap_tour_css = constants.BootstrapTour.MIN_CSS
bootstrap_tour_js = constants.BootstrapTour.MIN_JS
backdrop_style = style_sheet.bt_backdrop_style
backdrop_style = backdrop_style.replace('\n', '')
backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style)
instructions += 'injectJS("%s");\n' % jquery_js
instructions += '\n'
instructions += 'function loadResources() { '
instructions += 'if ( typeof jQuery !== "undefined" ) {\n'
instructions += 'injectCSS("%s");\n' % bootstrap_tour_css
instructions += 'injectStyle("%s");\n' % backdrop_style
instructions += 'injectJS("%s");' % bootstrap_tour_js
instructions += '} else { window.setTimeout("loadResources();",100); '
instructions += '} }\n'
instructions += 'loadResources()'
elif tour_type == "driverjs":
driverjs_css = constants.DriverJS.MIN_CSS
driverjs_js = constants.DriverJS.MIN_JS
backdrop_style = style_sheet.dt_backdrop_style
backdrop_style = backdrop_style.replace('\n', '')
backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style)
instructions += 'injectCSS("%s");\n' % driverjs_css
instructions += 'injectStyle("%s");\n' % backdrop_style
instructions += 'injectJS("%s");' % driverjs_js
elif tour_type == "hopscotch":
hopscotch_css = constants.Hopscotch.MIN_CSS
hopscotch_js = constants.Hopscotch.MIN_JS
backdrop_style = style_sheet.hops_backdrop_style
backdrop_style = backdrop_style.replace('\n', '')
backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style)
instructions += 'injectCSS("%s");\n' % hopscotch_css
instructions += 'injectStyle("%s");\n' % backdrop_style
instructions += 'injectJS("%s");' % hopscotch_js
elif tour_type == "introjs":
intro_css = constants.IntroJS.MIN_CSS
intro_js = constants.IntroJS.MIN_JS
instructions += 'injectCSS("%s");\n' % intro_css
instructions += 'injectJS("%s");' % intro_js
elif tour_type == "shepherd":
jquery_js = constants.JQuery.MIN_JS
shepherd_js = constants.Shepherd.MIN_JS
sh_theme_arrows_css = constants.Shepherd.THEME_ARROWS_CSS
sh_theme_arrows_fix_css = constants.Shepherd.THEME_ARR_FIX_CSS
sh_theme_default_css = constants.Shepherd.THEME_DEFAULT_CSS
sh_theme_dark_css = constants.Shepherd.THEME_DARK_CSS
sh_theme_sq_css = constants.Shepherd.THEME_SQ_CSS
sh_theme_sq_dark_css = constants.Shepherd.THEME_SQ_DK_CSS
tether_js = constants.Tether.MIN_JS
spinner_css = constants.Messenger.SPINNER_CSS
backdrop_style = style_sheet.sh_backdrop_style
backdrop_style = backdrop_style.replace('\n', '')
backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style)
instructions += 'injectCSS("%s");\n' % spinner_css
instructions += 'injectJS("%s");\n' % jquery_js
instructions += 'injectJS("%s");\n' % tether_js
instructions += '\n'
instructions += 'function loadResources() { '
instructions += 'if ( typeof jQuery !== "undefined" ) {\n'
instructions += 'injectCSS("%s");' % sh_theme_arrows_css
instructions += 'injectCSS("%s");' % sh_theme_arrows_fix_css
instructions += 'injectCSS("%s");' % sh_theme_default_css
instructions += 'injectCSS("%s");' % sh_theme_dark_css
instructions += 'injectCSS("%s");' % sh_theme_sq_css
instructions += 'injectCSS("%s");\n' % sh_theme_sq_dark_css
instructions += 'injectStyle("%s");\n' % backdrop_style
instructions += 'injectJS("%s");\n' % shepherd_js
instructions += '} else { window.setTimeout("loadResources();",100); '
instructions += '} }\n'
instructions += 'loadResources()'
instructions += '\n\n//////// Tour Code ////////\n\n'
if tour_type == "bootstrap":
instructions += 'function loadTour() { '
instructions += 'if ( typeof Tour !== "undefined" ) {\n'
elif tour_type == "driverjs":
instructions += 'function loadTour() { '
instructions += 'if ( typeof Driver !== "undefined" ) {\n'
elif tour_type == "hopscotch":
instructions += 'function loadTour() { '
instructions += 'if ( typeof hopscotch !== "undefined" ) {\n'
elif tour_type == "introjs":
instructions += 'function loadTour() { '
instructions += 'if ( typeof introJs !== "undefined" ) {\n'
elif tour_type == "shepherd":
instructions += 'function loadTour() { '
instructions += 'if ( typeof Shepherd !== "undefined" ) {\n'
for tour_step in tour_steps[name]:
instructions += tour_step
if tour_type == "bootstrap":
instructions += (
"""]);
// Initialize the tour
tour.init();
// Start the tour
tour.start();
$tour = tour;
$tour.restart();\n""")
elif tour_type == "driverjs":
instructions += (
"""]
);
// Start the tour!
tour.start();
$tour = tour;\n""")
elif tour_type == "hopscotch":
instructions += (
"""]
};
// Start the tour!
hopscotch.startTour(tour);
$tour = hopscotch;\n""")
elif tour_type == "introjs":
instructions += (
"""]
});
intro.setOption("disableInteraction", true);
intro.setOption("overlayOpacity", .29);
intro.setOption("scrollToElement", true);
intro.setOption("keyboardNavigation", true);
intro.setOption("exitOnEsc", false);
intro.setOption("exitOnOverlayClick", false);
intro.setOption("showStepNumbers", false);
intro.setOption("showProgress", false);
intro.start();
$tour = intro;
};
startIntro();\n""")
elif tour_type == "shepherd":
instructions += (
"""
tour.start();
$tour = tour;\n""")
else:
pass
instructions += '\n} else { window.setTimeout("loadTour();",100); } '
instructions += '}\n'
instructions += 'loadTour()\n'
exported_tours_folder = EXPORTED_TOURS_FOLDER
if exported_tours_folder.endswith("/"):
exported_tours_folder = exported_tours_folder[:-1]
if not os.path.exists(exported_tours_folder):
try:
os.makedirs(exported_tours_folder)
except Exception:
pass
import codecs
file_path = exported_tours_folder + "/" + filename
out_file = codecs.open(file_path, "w+")
out_file.writelines(instructions)
out_file.close()
print('\n>>> [%s] was saved!\n' % file_path) | [
"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",
"Exception",
"(",
"\"Tour {%s} does not exist!\"",
"%",
"name",
")",
"if",
"not",
"filename",
".",
"endswith",
"(",
"'.js'",
")",
":",
"raise",
"Exception",
"(",
"'Tour file must end in \".js\"!'",
")",
"if",
"not",
"url",
":",
"url",
"=",
"\"data:,\"",
"tour_type",
"=",
"None",
"if",
"\"Bootstrap\"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"0",
"]",
":",
"tour_type",
"=",
"\"bootstrap\"",
"elif",
"\"DriverJS\"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"0",
"]",
":",
"tour_type",
"=",
"\"driverjs\"",
"elif",
"\"Hopscotch\"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"0",
"]",
":",
"tour_type",
"=",
"\"hopscotch\"",
"elif",
"\"IntroJS\"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"0",
"]",
":",
"tour_type",
"=",
"\"introjs\"",
"elif",
"\"Shepherd\"",
"in",
"tour_steps",
"[",
"name",
"]",
"[",
"0",
"]",
":",
"tour_type",
"=",
"\"shepherd\"",
"else",
":",
"raise",
"Exception",
"(",
"'Unknown tour type!'",
")",
"instructions",
"=",
"(",
"'''//////// Load Tour Start Page (if not there now) ////////\\n\\n'''",
"'''if (window.location.href != \"%s\") {\\n'''",
"''' window.location.href=\"%s\";\\n'''",
"'''}\\n\\n'''",
"'''//////// Resources ////////\\n\\n'''",
"'''function injectCSS(css_link) {'''",
"'''var head = document.getElementsByTagName(\"head\")[0];'''",
"'''var link = document.createElement(\"link\");'''",
"'''link.rel = \"stylesheet\";'''",
"'''link.type = \"text/css\";'''",
"'''link.href = css_link;'''",
"'''link.crossorigin = \"anonymous\";'''",
"'''head.appendChild(link);'''",
"'''};\\n'''",
"'''function injectJS(js_link) {'''",
"'''var head = document.getElementsByTagName(\"head\")[0];'''",
"'''var script = document.createElement(\"script\");'''",
"'''script.src = js_link;'''",
"'''script.defer;'''",
"'''script.type=\"text/javascript\";'''",
"'''script.crossorigin = \"anonymous\";'''",
"'''script.onload = function() { null };'''",
"'''head.appendChild(script);'''",
"'''};\\n'''",
"'''function injectStyle(css) {'''",
"'''var head = document.getElementsByTagName(\"head\")[0];'''",
"'''var style = document.createElement(\"style\");'''",
"'''style.type = \"text/css\";'''",
"'''style.appendChild(document.createTextNode(css));'''",
"'''head.appendChild(style);'''",
"'''};\\n'''",
"%",
"(",
"url",
",",
"url",
")",
")",
"if",
"tour_type",
"==",
"\"bootstrap\"",
":",
"jquery_js",
"=",
"constants",
".",
"JQuery",
".",
"MIN_JS",
"bootstrap_tour_css",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_CSS",
"bootstrap_tour_js",
"=",
"constants",
".",
"BootstrapTour",
".",
"MIN_JS",
"backdrop_style",
"=",
"style_sheet",
".",
"bt_backdrop_style",
"backdrop_style",
"=",
"backdrop_style",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"backdrop_style",
"=",
"js_utils",
".",
"escape_quotes_if_needed",
"(",
"backdrop_style",
")",
"instructions",
"+=",
"'injectJS(\"%s\");\\n'",
"%",
"jquery_js",
"instructions",
"+=",
"'\\n'",
"instructions",
"+=",
"'function loadResources() { '",
"instructions",
"+=",
"'if ( typeof jQuery !== \"undefined\" ) {\\n'",
"instructions",
"+=",
"'injectCSS(\"%s\");\\n'",
"%",
"bootstrap_tour_css",
"instructions",
"+=",
"'injectStyle(\"%s\");\\n'",
"%",
"backdrop_style",
"instructions",
"+=",
"'injectJS(\"%s\");'",
"%",
"bootstrap_tour_js",
"instructions",
"+=",
"'} else { window.setTimeout(\"loadResources();\",100); '",
"instructions",
"+=",
"'} }\\n'",
"instructions",
"+=",
"'loadResources()'",
"elif",
"tour_type",
"==",
"\"driverjs\"",
":",
"driverjs_css",
"=",
"constants",
".",
"DriverJS",
".",
"MIN_CSS",
"driverjs_js",
"=",
"constants",
".",
"DriverJS",
".",
"MIN_JS",
"backdrop_style",
"=",
"style_sheet",
".",
"dt_backdrop_style",
"backdrop_style",
"=",
"backdrop_style",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"backdrop_style",
"=",
"js_utils",
".",
"escape_quotes_if_needed",
"(",
"backdrop_style",
")",
"instructions",
"+=",
"'injectCSS(\"%s\");\\n'",
"%",
"driverjs_css",
"instructions",
"+=",
"'injectStyle(\"%s\");\\n'",
"%",
"backdrop_style",
"instructions",
"+=",
"'injectJS(\"%s\");'",
"%",
"driverjs_js",
"elif",
"tour_type",
"==",
"\"hopscotch\"",
":",
"hopscotch_css",
"=",
"constants",
".",
"Hopscotch",
".",
"MIN_CSS",
"hopscotch_js",
"=",
"constants",
".",
"Hopscotch",
".",
"MIN_JS",
"backdrop_style",
"=",
"style_sheet",
".",
"hops_backdrop_style",
"backdrop_style",
"=",
"backdrop_style",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"backdrop_style",
"=",
"js_utils",
".",
"escape_quotes_if_needed",
"(",
"backdrop_style",
")",
"instructions",
"+=",
"'injectCSS(\"%s\");\\n'",
"%",
"hopscotch_css",
"instructions",
"+=",
"'injectStyle(\"%s\");\\n'",
"%",
"backdrop_style",
"instructions",
"+=",
"'injectJS(\"%s\");'",
"%",
"hopscotch_js",
"elif",
"tour_type",
"==",
"\"introjs\"",
":",
"intro_css",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_CSS",
"intro_js",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_JS",
"instructions",
"+=",
"'injectCSS(\"%s\");\\n'",
"%",
"intro_css",
"instructions",
"+=",
"'injectJS(\"%s\");'",
"%",
"intro_js",
"elif",
"tour_type",
"==",
"\"shepherd\"",
":",
"jquery_js",
"=",
"constants",
".",
"JQuery",
".",
"MIN_JS",
"shepherd_js",
"=",
"constants",
".",
"Shepherd",
".",
"MIN_JS",
"sh_theme_arrows_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_ARROWS_CSS",
"sh_theme_arrows_fix_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_ARR_FIX_CSS",
"sh_theme_default_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_DEFAULT_CSS",
"sh_theme_dark_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_DARK_CSS",
"sh_theme_sq_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_SQ_CSS",
"sh_theme_sq_dark_css",
"=",
"constants",
".",
"Shepherd",
".",
"THEME_SQ_DK_CSS",
"tether_js",
"=",
"constants",
".",
"Tether",
".",
"MIN_JS",
"spinner_css",
"=",
"constants",
".",
"Messenger",
".",
"SPINNER_CSS",
"backdrop_style",
"=",
"style_sheet",
".",
"sh_backdrop_style",
"backdrop_style",
"=",
"backdrop_style",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"backdrop_style",
"=",
"js_utils",
".",
"escape_quotes_if_needed",
"(",
"backdrop_style",
")",
"instructions",
"+=",
"'injectCSS(\"%s\");\\n'",
"%",
"spinner_css",
"instructions",
"+=",
"'injectJS(\"%s\");\\n'",
"%",
"jquery_js",
"instructions",
"+=",
"'injectJS(\"%s\");\\n'",
"%",
"tether_js",
"instructions",
"+=",
"'\\n'",
"instructions",
"+=",
"'function loadResources() { '",
"instructions",
"+=",
"'if ( typeof jQuery !== \"undefined\" ) {\\n'",
"instructions",
"+=",
"'injectCSS(\"%s\");'",
"%",
"sh_theme_arrows_css",
"instructions",
"+=",
"'injectCSS(\"%s\");'",
"%",
"sh_theme_arrows_fix_css",
"instructions",
"+=",
"'injectCSS(\"%s\");'",
"%",
"sh_theme_default_css",
"instructions",
"+=",
"'injectCSS(\"%s\");'",
"%",
"sh_theme_dark_css",
"instructions",
"+=",
"'injectCSS(\"%s\");'",
"%",
"sh_theme_sq_css",
"instructions",
"+=",
"'injectCSS(\"%s\");\\n'",
"%",
"sh_theme_sq_dark_css",
"instructions",
"+=",
"'injectStyle(\"%s\");\\n'",
"%",
"backdrop_style",
"instructions",
"+=",
"'injectJS(\"%s\");\\n'",
"%",
"shepherd_js",
"instructions",
"+=",
"'} else { window.setTimeout(\"loadResources();\",100); '",
"instructions",
"+=",
"'} }\\n'",
"instructions",
"+=",
"'loadResources()'",
"instructions",
"+=",
"'\\n\\n//////// Tour Code ////////\\n\\n'",
"if",
"tour_type",
"==",
"\"bootstrap\"",
":",
"instructions",
"+=",
"'function loadTour() { '",
"instructions",
"+=",
"'if ( typeof Tour !== \"undefined\" ) {\\n'",
"elif",
"tour_type",
"==",
"\"driverjs\"",
":",
"instructions",
"+=",
"'function loadTour() { '",
"instructions",
"+=",
"'if ( typeof Driver !== \"undefined\" ) {\\n'",
"elif",
"tour_type",
"==",
"\"hopscotch\"",
":",
"instructions",
"+=",
"'function loadTour() { '",
"instructions",
"+=",
"'if ( typeof hopscotch !== \"undefined\" ) {\\n'",
"elif",
"tour_type",
"==",
"\"introjs\"",
":",
"instructions",
"+=",
"'function loadTour() { '",
"instructions",
"+=",
"'if ( typeof introJs !== \"undefined\" ) {\\n'",
"elif",
"tour_type",
"==",
"\"shepherd\"",
":",
"instructions",
"+=",
"'function loadTour() { '",
"instructions",
"+=",
"'if ( typeof Shepherd !== \"undefined\" ) {\\n'",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"instructions",
"+=",
"tour_step",
"if",
"tour_type",
"==",
"\"bootstrap\"",
":",
"instructions",
"+=",
"(",
"\"\"\"]);\n // Initialize the tour\n tour.init();\n // Start the tour\n tour.start();\n $tour = tour;\n $tour.restart();\\n\"\"\"",
")",
"elif",
"tour_type",
"==",
"\"driverjs\"",
":",
"instructions",
"+=",
"(",
"\"\"\"]\n );\n // Start the tour!\n tour.start();\n $tour = tour;\\n\"\"\"",
")",
"elif",
"tour_type",
"==",
"\"hopscotch\"",
":",
"instructions",
"+=",
"(",
"\"\"\"]\n };\n // Start the tour!\n hopscotch.startTour(tour);\n $tour = hopscotch;\\n\"\"\"",
")",
"elif",
"tour_type",
"==",
"\"introjs\"",
":",
"instructions",
"+=",
"(",
"\"\"\"]\n });\n intro.setOption(\"disableInteraction\", true);\n intro.setOption(\"overlayOpacity\", .29);\n intro.setOption(\"scrollToElement\", true);\n intro.setOption(\"keyboardNavigation\", true);\n intro.setOption(\"exitOnEsc\", false);\n intro.setOption(\"exitOnOverlayClick\", false);\n intro.setOption(\"showStepNumbers\", false);\n intro.setOption(\"showProgress\", false);\n intro.start();\n $tour = intro;\n };\n startIntro();\\n\"\"\"",
")",
"elif",
"tour_type",
"==",
"\"shepherd\"",
":",
"instructions",
"+=",
"(",
"\"\"\"\n tour.start();\n $tour = tour;\\n\"\"\"",
")",
"else",
":",
"pass",
"instructions",
"+=",
"'\\n} else { window.setTimeout(\"loadTour();\",100); } '",
"instructions",
"+=",
"'}\\n'",
"instructions",
"+=",
"'loadTour()\\n'",
"exported_tours_folder",
"=",
"EXPORTED_TOURS_FOLDER",
"if",
"exported_tours_folder",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"exported_tours_folder",
"=",
"exported_tours_folder",
"[",
":",
"-",
"1",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"exported_tours_folder",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"exported_tours_folder",
")",
"except",
"Exception",
":",
"pass",
"import",
"codecs",
"file_path",
"=",
"exported_tours_folder",
"+",
"\"/\"",
"+",
"filename",
"out_file",
"=",
"codecs",
".",
"open",
"(",
"file_path",
",",
"\"w+\"",
")",
"out_file",
".",
"writelines",
"(",
"instructions",
")",
"out_file",
".",
"close",
"(",
")",
"print",
"(",
"'\\n>>> [%s] was saved!\\n'",
"%",
"file_path",
")"
] | [
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 instances, but same content
assert config1 == config2 # different instances, but same content
assert not (config1 != config2) # ne works properly
assert not (config1 == config3) # different meta
assert config1 != config3 # ne works properly
assert config3 != config4 | [
"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",
"assert",
"config1",
"==",
"config2",
"# different instances, but same content",
"assert",
"not",
"(",
"config1",
"!=",
"config2",
")",
"# ne works properly",
"assert",
"not",
"(",
"config1",
"==",
"config3",
")",
"# different meta",
"assert",
"config1",
"!=",
"config3",
"# ne works properly",
"assert",
"config3",
"!=",
"config4"
] | [
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, match_type="runtime")
assert config1.isEquivalentTo(config3, match_type="runtime") # different meta
assert config1.isEquivalentTo(
config4, match_type="success"
) # different result format
assert not config1.isEquivalentTo(
config5, match_type="success"
) # different value_set
assert config1.isEquivalentTo(
config5, match_type="domain"
) | [
"def",
"test_expectation_configuration_equivalence",
"(",
"config1",
",",
"config2",
",",
"config3",
",",
"config4",
",",
"config5",
")",
":",
"assert",
"config1",
".",
"isEquivalentTo",
"(",
"config2",
",",
"match_type",
"=",
"\"runtime\"",
")",
"# no difference",
"assert",
"config2",
".",
"isEquivalentTo",
"(",
"config1",
",",
"match_type",
"=",
"\"runtime\"",
")",
"assert",
"config1",
".",
"isEquivalentTo",
"(",
"config3",
",",
"match_type",
"=",
"\"runtime\"",
")",
"# different meta",
"assert",
"config1",
".",
"isEquivalentTo",
"(",
"config4",
",",
"match_type",
"=",
"\"success\"",
")",
"# different result format",
"assert",
"not",
"config1",
".",
"isEquivalentTo",
"(",
"config5",
",",
"match_type",
"=",
"\"success\"",
")",
"# different value_set",
"assert",
"config1",
".",
"isEquivalentTo",
"(",
"config5",
",",
"match_type",
"=",
"\"domain\"",
")"
] | [
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':
return price_at / price_eod
else:
return 1.0
else:
return 1.0 | [
"def",
"get_ratio",
"(",
"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'",
":",
"return",
"price_at",
"/",
"price_eod",
"else",
":",
"return",
"1.0",
"else",
":",
"return",
"1.0"
] | [
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 = timestamp.replace(hour=8)
open_time = timestamp.replace(hour=9, minute=30)
close_time = timestamp.replace(hour=16)
after_time = timestamp.replace(hour=17)
# Return the market status for each bucket.
if timestamp >= pre_time and timestamp < open_time:
return 'pre'
elif timestamp >= open_time and timestamp < close_time:
return 'open'
elif timestamp >= close_time and timestamp < after_time:
return 'after'
else:
return 'closed' | [
"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 hours.",
"pre_time",
"=",
"timestamp",
".",
"replace",
"(",
"hour",
"=",
"8",
")",
"open_time",
"=",
"timestamp",
".",
"replace",
"(",
"hour",
"=",
"9",
",",
"minute",
"=",
"30",
")",
"close_time",
"=",
"timestamp",
".",
"replace",
"(",
"hour",
"=",
"16",
")",
"after_time",
"=",
"timestamp",
".",
"replace",
"(",
"hour",
"=",
"17",
")",
"# Return the market status for each bucket.",
"if",
"timestamp",
">=",
"pre_time",
"and",
"timestamp",
"<",
"open_time",
":",
"return",
"'pre'",
"elif",
"timestamp",
">=",
"open_time",
"and",
"timestamp",
"<",
"close_time",
":",
"return",
"'open'",
"elif",
"timestamp",
">=",
"close_time",
"and",
"timestamp",
"<",
"after_time",
":",
"return",
"'after'",
"else",
":",
"return",
"'closed'"
] | [
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, minute=0, second=0)):
return False
# The strategy needs to be active.
if strategy['action'] == 'hold':
return False
# We need to know the stock price.
if not strategy['price_at'] or not strategy['price_eod']:
return False
return True | [
"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",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
")",
"==",
"date",
".",
"replace",
"(",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
")",
")",
":",
"return",
"False",
"# The strategy needs to be active.",
"if",
"strategy",
"[",
"'action'",
"]",
"==",
"'hold'",
":",
"return",
"False",
"# We need to know the stock price.",
"if",
"not",
"strategy",
"[",
"'price_at'",
"]",
"or",
"not",
"strategy",
"[",
"'price_eod'",
"]",
":",
"return",
"False",
"return",
"True"
] | [
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 installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv) | [
"def",
"main",
"(",
")",
":",
"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 installed and \"",
"\"available on your PYTHONPATH environment variable? Did you \"",
"\"forget to activate a virtual environment?\"",
")",
"from",
"exc",
"execute_from_command_line",
"(",
"sys",
".",
"argv",
")"
] | [
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 and x[0].isdigit():
version = x
break
return version | [
"def",
"extract_version",
"(",
"txt",
")",
":",
"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",
"and",
"x",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"version",
"=",
"x",
"break",
"return",
"version"
] | [
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
"""
ret = self.call().return_code
ok = ret == return_code
if not ok:
raise EasyProcessError(
self, 'check error, return code is not {0}!'.format(
return_code))
return self | [
"def",
"check",
"(",
"self",
",",
"return_code",
"=",
"0",
")",
":",
"ret",
"=",
"self",
".",
"call",
"(",
")",
".",
"return_code",
"ok",
"=",
"ret",
"==",
"return_code",
"if",
"not",
"ok",
":",
"raise",
"EasyProcessError",
"(",
"self",
",",
"'check error, return code is not {0}!'",
".",
"format",
"(",
"return_code",
")",
")",
"return",
"self"
] | [
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 return code
:rtype: self
"""
try:
self.call()
except Exception:
raise EasyProcessCheckInstalledError(self)
return self | [
"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()
return self | [
"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_')
self._stderr_file = tempfile.TemporaryFile(prefix='stderr_')
stdout = self._stdout_file
stderr = self._stderr_file
else:
stdout = subprocess.PIPE
stderr = subprocess.PIPE
cmd = list(map(uniencode, self.cmd))
try:
self.popen = subprocess.Popen(cmd,
stdout=stdout,
stderr=stderr,
cwd=self.cwd,
env=self.env,
)
except OSError as oserror:
log.debug('OSError exception: %s', oserror)
self.oserror = oserror
raise EasyProcessError(self, 'start error')
self.is_started = True
log.debug('process was started (pid=%s)', self.pid)
return self | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_started",
":",
"raise",
"EasyProcessError",
"(",
"self",
",",
"'process was started twice!'",
")",
"if",
"self",
".",
"use_temp_files",
":",
"self",
".",
"_stdout_file",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"prefix",
"=",
"'stdout_'",
")",
"self",
".",
"_stderr_file",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"prefix",
"=",
"'stderr_'",
")",
"stdout",
"=",
"self",
".",
"_stdout_file",
"stderr",
"=",
"self",
".",
"_stderr_file",
"else",
":",
"stdout",
"=",
"subprocess",
".",
"PIPE",
"stderr",
"=",
"subprocess",
".",
"PIPE",
"cmd",
"=",
"list",
"(",
"map",
"(",
"uniencode",
",",
"self",
".",
"cmd",
")",
")",
"try",
":",
"self",
".",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
",",
"cwd",
"=",
"self",
".",
"cwd",
",",
"env",
"=",
"self",
".",
"env",
",",
")",
"except",
"OSError",
"as",
"oserror",
":",
"log",
".",
"debug",
"(",
"'OSError exception: %s'",
",",
"oserror",
")",
"self",
".",
"oserror",
"=",
"oserror",
"raise",
"EasyProcessError",
"(",
"self",
",",
"'start error'",
")",
"self",
".",
"is_started",
"=",
"True",
"log",
".",
"debug",
"(",
"'process was started (pid=%s)'",
",",
"self",
".",
"pid",
")",
"return",
"self"
] | [
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.