_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q257000 | BaseAPI.base_url | validation | def base_url(self):
"""A base_url that will be used to construct the final
URL we're going to query against.
:returns: A URL of the form: ``proto://host:port``.
:rtype: :obj:`string`
"""
return '{proto}://{host}:{port}{url_path}'.format(
proto=self.protocol,
... | python | {
"resource": ""
} |
q257001 | BaseAPI._url | validation | def _url(self, endpoint, path=None):
"""The complete URL we will end up querying. Depending on the
endpoint we pass in this will result in different URL's with
different prefixes.
:param endpoint: The PuppetDB API endpoint we want to query.
:type endpoint: :obj:`string`
... | python | {
"resource": ""
} |
q257002 | BaseAPI.nodes | validation | def nodes(self, unreported=2, with_status=False, **kwargs):
"""Query for nodes by either name or query. If both aren't
provided this will return a list of all nodes. This method
also fetches the nodes status and event counts of the latest
report from puppetdb.
:param with_status... | python | {
"resource": ""
} |
q257003 | BaseAPI.node | validation | def node(self, name):
"""Gets a single node from PuppetDB.
:param name: The name of the node search.
:type name: :obj:`string`
:return: An instance of Node
:rtype: :class:`pypuppetdb.types.Node`
"""
nodes = self.nodes(path=name)
return next(node for node... | python | {
"resource": ""
} |
q257004 | BaseAPI.edges | validation | def edges(self, **kwargs):
"""Get the known catalog edges, formed between two resources.
:param \*\*kwargs: The rest of the keyword arguments are passed
to the _query function.
:returns: A generating yielding Edges.
:rtype: :class:`pypuppetdb.types.Edge`
... | python | {
"resource": ""
} |
q257005 | BaseAPI.catalog | validation | def catalog(self, node):
"""Get the available catalog for a given node.
:param node: (Required) The name of the PuppetDB node.
:type: :obj:`string`
:returns: An instance of Catalog
:rtype: :class:`pypuppetdb.types.Catalog`
"""
catalogs = self.catalogs(path=node)... | python | {
"resource": ""
} |
q257006 | BaseAPI.aggregate_event_counts | validation | def aggregate_event_counts(self, summarize_by, query=None,
count_by=None, count_filter=None):
"""Get event counts from puppetdb aggregated into a single map.
:param summarize_by: (Required) The object type to be counted on.
Valid values are 'c... | python | {
"resource": ""
} |
q257007 | BaseAPI.inventory | validation | def inventory(self, **kwargs):
"""Get Node and Fact information with an alternative query syntax
for structured facts instead of using the facts, fact-contents and
factsets endpoints for many fact-related queries.
:param \*\*kwargs: The rest of the keyword arguments are passed
... | python | {
"resource": ""
} |
q257008 | connect | validation | def connect(host='localhost', port=8080, ssl_verify=False, ssl_key=None,
ssl_cert=None, timeout=10, protocol=None, url_path='/',
username=None, password=None, token=None):
"""Connect with PuppetDB. This will return an object allowing you
to query the API through its methods.
:param ... | python | {
"resource": ""
} |
q257009 | main | validation | def main():
"""The Master has been started from the command line. Execute ad-hoc tests if desired."""
# app = MyMaster()
app = MyMaster(log_handler=MyLogger(),
listener=AppChannelListener(),
soe_handler=SOEHandler(),
master_application=MasterApplicati... | python | {
"resource": ""
} |
q257010 | MyMaster.send_direct_operate_command | validation | def send_direct_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
"""
Direct operate a single command
:param command: command to operate
:param index: index of the comma... | python | {
"resource": ""
} |
q257011 | MyMaster.send_direct_operate_command_set | validation | def send_direct_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
"""
Direct operate a set of commands
:param command_set: set of command headers
:param callback: c... | python | {
"resource": ""
} |
q257012 | MyMaster.send_select_and_operate_command | validation | def send_select_and_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
"""
Select and operate a single command
:param command: command to operate
:param index: index ... | python | {
"resource": ""
} |
q257013 | MyMaster.send_select_and_operate_command_set | validation | def send_select_and_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
"""
Select and operate a set of commands
:param command_set: set of command headers
:param... | python | {
"resource": ""
} |
q257014 | SOEHandler.Process | validation | def Process(self, info, values):
"""
Process measurement data.
:param info: HeaderInfo
:param values: A collection of values received from the Outstation (various data types are possible).
"""
visitor_class_types = {
opendnp3.ICollectionIndexedBinary: Vis... | python | {
"resource": ""
} |
q257015 | main | validation | def main():
"""The Outstation has been started from the command line. Execute ad-hoc tests if desired."""
app = OutstationApplication()
_log.debug('Initialization complete. In command loop.')
# Ad-hoc tests can be inserted here if desired. See outstation_cmd.py for examples.
app.shutdown()
_log.... | python | {
"resource": ""
} |
q257016 | OutstationApplication.configure_stack | validation | def configure_stack():
"""Set up the OpenDNP3 configuration."""
stack_config = asiodnp3.OutstationStackConfig(opendnp3.DatabaseSizes.AllTypes(10))
stack_config.outstation.eventBufferConfig = opendnp3.EventBufferConfig().AllTypes(10)
stack_config.outstation.params.allowUnsolicited = True
... | python | {
"resource": ""
} |
q257017 | OutstationApplication.configure_database | validation | def configure_database(db_config):
"""
Configure the Outstation's database of input point definitions.
Configure two Analog points (group/variation 30.1) at indexes 1 and 2.
Configure two Binary points (group/variation 1.2) at indexes 1 and 2.
"""
db_config.a... | python | {
"resource": ""
} |
q257018 | OutstationApplication.GetApplicationIIN | validation | def GetApplicationIIN(self):
"""Return the application-controlled IIN field."""
application_iin = opendnp3.ApplicationIIN()
application_iin.configCorrupt = False
application_iin.deviceTrouble = False
application_iin.localControl = False
application_iin.needTime = False
... | python | {
"resource": ""
} |
q257019 | OutstationApplication.process_point_value | validation | def process_point_value(cls, command_type, command, index, op_type):
"""
A PointValue was received from the Master. Process its payload.
:param command_type: (string) Either 'Select' or 'Operate'.
:param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputIn... | python | {
"resource": ""
} |
q257020 | OutstationCommandHandler.Select | validation | def Select(self, command, index):
"""
The Master sent a Select command to the Outstation. Handle it.
:param command: ControlRelayOutputBlock,
AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.
:param index: int
:return... | python | {
"resource": ""
} |
q257021 | OutstationCommandHandler.Operate | validation | def Operate(self, command, index, op_type):
"""
The Master sent an Operate command to the Outstation. Handle it.
:param command: ControlRelayOutputBlock,
AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64.
:param index: int
... | python | {
"resource": ""
} |
q257022 | create_connection | validation | def create_connection(port=_PORT_, timeout=_TIMEOUT_, restart=False):
"""
Create Bloomberg connection
Returns:
(Bloomberg connection, if connection is new)
"""
if _CON_SYM_ in globals():
if not isinstance(globals()[_CON_SYM_], pdblp.BCon):
del globals()[_CON_SYM_]
i... | python | {
"resource": ""
} |
q257023 | delete_connection | validation | def delete_connection():
"""
Stop and destroy Bloomberg connection
"""
if _CON_SYM_ in globals():
con = globals().pop(_CON_SYM_)
if not getattr(con, '_session').start(): con.stop() | python | {
"resource": ""
} |
q257024 | parse_markdown | validation | def parse_markdown():
"""
Parse markdown as description
"""
readme_file = f'{PACKAGE_ROOT}/README.md'
if path.exists(readme_file):
with open(readme_file, 'r', encoding='utf-8') as f:
long_description = f.read()
return long_description | python | {
"resource": ""
} |
q257025 | proc_elms | validation | def proc_elms(**kwargs) -> list:
"""
Bloomberg overrides for elements
Args:
**kwargs: overrides
Returns:
list of tuples
Examples:
>>> proc_elms(PerAdj='A', Per='W')
[('periodicityAdjustment', 'ACTUAL'), ('periodicitySelection', 'WEEKLY')]
>>> proc_elms(Days... | python | {
"resource": ""
} |
q257026 | format_earning | validation | def format_earning(data: pd.DataFrame, header: pd.DataFrame) -> pd.DataFrame:
"""
Standardized earning outputs and add percentage by each blocks
Args:
data: earning data block
header: earning headers
Returns:
pd.DataFrame
Examples:
>>> format_earning(
... ... | python | {
"resource": ""
} |
q257027 | format_output | validation | def format_output(data: pd.DataFrame, source, col_maps=None) -> pd.DataFrame:
"""
Format `pdblp` outputs to column-based results
Args:
data: `pdblp` result
source: `bdp` or `bds`
col_maps: rename columns with these mappings
Returns:
pd.DataFrame
Examples:
>... | python | {
"resource": ""
} |
q257028 | format_intraday | validation | def format_intraday(data: pd.DataFrame, ticker, **kwargs) -> pd.DataFrame:
"""
Format intraday data
Args:
data: pd.DataFrame from bdib
ticker: ticker
Returns:
pd.DataFrame
Examples:
>>> format_intraday(
... data=pd.read_parquet('xbbg/tests/data/sample_b... | python | {
"resource": ""
} |
q257029 | info_qry | validation | def info_qry(tickers, flds) -> str:
"""
Logging info for given tickers and fields
Args:
tickers: tickers
flds: fields
Returns:
str
Examples:
>>> print(info_qry(
... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name']
... ))
ticker... | python | {
"resource": ""
} |
q257030 | bdp | validation | def bdp(tickers, flds, **kwargs):
"""
Bloomberg reference data
Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides
Returns:
pd.DataFrame
Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker field value
0 IQ... | python | {
"resource": ""
} |
q257031 | bds | validation | def bds(tickers, flds, **kwargs):
"""
Bloomberg block data
Args:
tickers: ticker(s)
flds: field(s)
**kwargs: other overrides for query
-> raw: raw output from `pdbdp` library, default False
Returns:
pd.DataFrame: block data
Examples:
>>> import os... | python | {
"resource": ""
} |
q257032 | bdh | validation | def bdh(
tickers, flds=None, start_date=None, end_date='today', adjust=None, **kwargs
) -> pd.DataFrame:
"""
Bloomberg historical data
Args:
tickers: ticker(s)
flds: field(s)
start_date: start date
end_date: end date - default today
adjust: `all`, `dvd`, `nor... | python | {
"resource": ""
} |
q257033 | intraday | validation | def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame:
"""
Bloomberg intraday bar data within market session
Args:
ticker: ticker
dt: date
session: examples include
day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000
**kwargs:
... | python | {
"resource": ""
} |
q257034 | earning | validation | def earning(
ticker, by='Geo', typ='Revenue', ccy=None, level=None, **kwargs
) -> pd.DataFrame:
"""
Earning exposures by Geo or Products
Args:
ticker: ticker name
by: [G(eo), P(roduct)]
typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue`
ccy:... | python | {
"resource": ""
} |
q257035 | active_futures | validation | def active_futures(ticker: str, dt) -> str:
"""
Active futures contract
Args:
ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.
dt: date
Returns:
str: ticker name
"""
t_info = ticker.split()
prefix, asset = ' '.join(t_info[:-1]), t_info[-1]
in... | python | {
"resource": ""
} |
q257036 | fut_ticker | validation | def fut_ticker(gen_ticker: str, dt, freq: str, log=logs.LOG_LEVEL) -> str:
"""
Get proper ticker from generic ticker
Args:
gen_ticker: generic ticker
dt: date
freq: futures contract frequency
log: level of logs
Returns:
str: exact futures ticker
"""
logg... | python | {
"resource": ""
} |
q257037 | check_hours | validation | def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ) -> pd.DataFrame:
"""
Check exchange hours vs local hours
Args:
tickers: list of tickers
tz_exch: exchange timezone
tz_loc: local timezone
Returns:
Local and exchange hours
"""
cols = ['Trading_Day_Start_Time_E... | python | {
"resource": ""
} |
q257038 | hist_file | validation | def hist_file(ticker: str, dt, typ='TRADE') -> str:
"""
Data file location for Bloomberg historical data
Args:
ticker: ticker name
dt: date
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Returns:
file location
Examples:
>>> os.environ['BBG_R... | python | {
"resource": ""
} |
q257039 | ref_file | validation | def ref_file(
ticker: str, fld: str, has_date=False, cache=False, ext='parq', **kwargs
) -> str:
"""
Data file location for Bloomberg reference data
Args:
ticker: ticker name
fld: field
has_date: whether add current date to data file
cache: if has_date is True, wheth... | python | {
"resource": ""
} |
q257040 | save_intraday | validation | def save_intraday(data: pd.DataFrame, ticker: str, dt, typ='TRADE'):
"""
Check whether data is done for the day and save
Args:
data: data
ticker: ticker
dt: date
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Examples:
>>> os.environ['BBG_ROOT'] ... | python | {
"resource": ""
} |
q257041 | exch_info | validation | def exch_info(ticker: str) -> pd.Series:
"""
Exchange info for given ticker
Args:
ticker: ticker or exchange
Returns:
pd.Series
Examples:
>>> exch_info('SPY US Equity')
tz America/New_York
allday [04:00, 20:00]
day [09:30, 16:00]... | python | {
"resource": ""
} |
q257042 | market_info | validation | def market_info(ticker: str) -> dict:
"""
Get info for given market
Args:
ticker: Bloomberg full ticker
Returns:
dict
Examples:
>>> info = market_info('SHCOMP Index')
>>> info['exch']
'EquityChina'
>>> info = market_info('ICICIC=1 IS Equity')
... | python | {
"resource": ""
} |
q257043 | ccy_pair | validation | def ccy_pair(local, base='USD') -> CurrencyPair:
"""
Currency pair info
Args:
local: local currency
base: base currency
Returns:
CurrencyPair
Examples:
>>> ccy_pair(local='HKD', base='USD')
CurrencyPair(ticker='HKD Curncy', factor=1.0, power=1)
>>> ... | python | {
"resource": ""
} |
q257044 | market_timing | validation | def market_timing(ticker, dt, timing='EOD', tz='local') -> str:
"""
Market close time for ticker
Args:
ticker: ticker name
dt: date
timing: [EOD (default), BOD]
tz: conversion to timezone
Returns:
str: date & time
Examples:
>>> market_timing('7267 J... | python | {
"resource": ""
} |
q257045 | flatten | validation | def flatten(iterable, maps=None, unique=False) -> list:
"""
Flatten any array of items to list
Args:
iterable: any array or value
maps: map items to values
unique: drop duplicates
Returns:
list: flattened list
References:
https://stackoverflow.com/a/4085770... | python | {
"resource": ""
} |
q257046 | _to_gen_ | validation | def _to_gen_(iterable):
"""
Recursively iterate lists and tuples
"""
from collections import Iterable
for elm in iterable:
if isinstance(elm, Iterable) and not isinstance(elm, (str, bytes)):
yield from flatten(elm)
else: yield elm | python | {
"resource": ""
} |
q257047 | to_str | validation | def to_str(
data: dict, fmt='{key}={value}', sep=', ', public_only=True
) -> str:
"""
Convert dict to string
Args:
data: dict
fmt: how key and value being represented
sep: how pairs of key and value are seperated
public_only: if display public members only
Retur... | python | {
"resource": ""
} |
q257048 | load_info | validation | def load_info(cat):
"""
Load parameters for assets
Args:
cat: category
Returns:
dict
Examples:
>>> import pandas as pd
>>>
>>> assets = load_info(cat='assets')
>>> all(cat in assets for cat in ['Equity', 'Index', 'Curncy', 'Corp'])
True
... | python | {
"resource": ""
} |
q257049 | _load_yaml_ | validation | def _load_yaml_(file_name):
"""
Load assets infomation from file
Args:
file_name: file name
Returns:
dict
"""
if not os.path.exists(file_name): return dict()
with open(file_name, 'r', encoding='utf-8') as fp:
return YAML().load(stream=fp) | python | {
"resource": ""
} |
q257050 | to_hour | validation | def to_hour(num) -> str:
"""
Convert YAML input to hours
Args:
num: number in YMAL file, e.g., 900, 1700, etc.
Returns:
str
Examples:
>>> to_hour(900)
'09:00'
>>> to_hour(1700)
'17:00'
"""
to_str = str(int(num))
return pd.Timestamp(f'{to... | python | {
"resource": ""
} |
q257051 | create_folder | validation | def create_folder(path_name: str, is_file=False):
"""
Make folder as well as all parent folders if not exists
Args:
path_name: full path name
is_file: whether input is name of file
"""
path_sep = path_name.replace('\\', '/').split('/')
for i in range(1, len(path_sep) + (0 if is_... | python | {
"resource": ""
} |
q257052 | all_files | validation | def all_files(
path_name, keyword='', ext='', full_path=True,
has_date=False, date_fmt=DATE_FMT
) -> list:
"""
Search all files with criteria
Returned list will be sorted by last modified
Args:
path_name: full path name
keyword: keyword to search
ext: file extens... | python | {
"resource": ""
} |
q257053 | all_folders | validation | def all_folders(
path_name, keyword='', has_date=False, date_fmt=DATE_FMT
) -> list:
"""
Search all folders with criteria
Returned list will be sorted by last modified
Args:
path_name: full path name
keyword: keyword to search
has_date: whether has date in file name (def... | python | {
"resource": ""
} |
q257054 | sort_by_modified | validation | def sort_by_modified(files_or_folders: list) -> list:
"""
Sort files or folders by modified time
Args:
files_or_folders: list of files or folders
Returns:
list
"""
return sorted(files_or_folders, key=os.path.getmtime, reverse=True) | python | {
"resource": ""
} |
q257055 | filter_by_dates | validation | def filter_by_dates(files_or_folders: list, date_fmt=DATE_FMT) -> list:
"""
Filter files or dates by date patterns
Args:
files_or_folders: list of files or folders
date_fmt: date format
Returns:
list
"""
r = re.compile(f'.*{date_fmt}.*')
return list(filter(
... | python | {
"resource": ""
} |
q257056 | file_modified_time | validation | def file_modified_time(file_name) -> pd.Timestamp:
"""
File modified time in python
Args:
file_name: file name
Returns:
pd.Timestamp
"""
return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name))) | python | {
"resource": ""
} |
q257057 | get_interval | validation | def get_interval(ticker, session) -> Session:
"""
Get interval from defined session
Args:
ticker: ticker
session: session
Returns:
Session of start_time and end_time
Examples:
>>> get_interval('005490 KS Equity', 'day_open_30')
Session(start_time='09:00', e... | python | {
"resource": ""
} |
q257058 | shift_time | validation | def shift_time(start_time, mins) -> str:
"""
Shift start time by mins
Args:
start_time: start time in terms of HH:MM string
mins: number of minutes (+ / -)
Returns:
end time in terms of HH:MM string
"""
s_time = pd.Timestamp(start_time)
e_time = s_time + np.sign(min... | python | {
"resource": ""
} |
q257059 | Intervals.market_open | validation | def market_open(self, session, mins) -> Session:
"""
Time intervals for market open
Args:
session: [allday, day, am, pm, night]
mins: mintues after open
Returns:
Session of start_time and end_time
"""
if session not in self.exch: retu... | python | {
"resource": ""
} |
q257060 | Intervals.market_close | validation | def market_close(self, session, mins) -> Session:
"""
Time intervals for market close
Args:
session: [allday, day, am, pm, night]
mins: mintues before close
Returns:
Session of start_time and end_time
"""
if session not in self.exch: ... | python | {
"resource": ""
} |
q257061 | Intervals.market_normal | validation | def market_normal(self, session, after_open, before_close) -> Session:
"""
Time intervals between market
Args:
session: [allday, day, am, pm, night]
after_open: mins after open
before_close: mins before close
Returns:
Session of start_tim... | python | {
"resource": ""
} |
q257062 | Intervals.market_exact | validation | def market_exact(self, session, start_time: str, end_time: str) -> Session:
"""
Explicitly specify start time and end time
Args:
session: predefined session
start_time: start time in terms of HHMM string
end_time: end time in terms of HHMM string
Ret... | python | {
"resource": ""
} |
q257063 | tz_convert | validation | def tz_convert(dt, to_tz, from_tz=None) -> str:
"""
Convert to tz
Args:
dt: date time
to_tz: to tz
from_tz: from tz - will be ignored if tz from dt is given
Returns:
str: date & time
Examples:
>>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong')... | python | {
"resource": ""
} |
q257064 | missing_info | validation | def missing_info(**kwargs) -> str:
"""
Full infomation for missing query
"""
func = kwargs.pop('func', 'unknown')
if 'ticker' in kwargs: kwargs['ticker'] = kwargs['ticker'].replace('/', '_')
info = utils.to_str(kwargs, fmt='{value}', sep='/')[1:-1]
return f'{func}/{info}' | python | {
"resource": ""
} |
q257065 | current_missing | validation | def current_missing(**kwargs) -> int:
"""
Check number of trials for missing values
Returns:
int: number of trials already tried
"""
data_path = os.environ.get(BBG_ROOT, '').replace('\\', '/')
if not data_path: return 0
return len(files.all_files(f'{data_path}/Logs/{missing_info(**k... | python | {
"resource": ""
} |
q257066 | update_missing | validation | def update_missing(**kwargs):
"""
Update number of trials for missing values
"""
data_path = os.environ.get(BBG_ROOT, '').replace('\\', '/')
if not data_path: return
if len(kwargs) == 0: return
log_path = f'{data_path}/Logs/{missing_info(**kwargs)}'
cnt = len(files.all_files(log_path))... | python | {
"resource": ""
} |
q257067 | public | validation | def public(function):
"""
Decorator for public views that do not require authentication
Sets an attribute in the fuction STRONGHOLD_IS_PUBLIC to True
"""
orig_func = function
while isinstance(orig_func, partial):
orig_func = orig_func.func
set_view_func_public(orig_func)
return ... | python | {
"resource": ""
} |
q257068 | custom_req | validation | def custom_req(session, request):
"""
Utility for sending a predefined request and printing response as well
as storing messages in a list, useful for testing
Parameters
----------
session: blpapi.session.Session
request: blpapi.request.Request
Request to be sent
Returns
--... | python | {
"resource": ""
} |
q257069 | bopen | validation | def bopen(**kwargs):
"""
Open and manage a BCon wrapper to a Bloomberg API session
Parameters
----------
**kwargs:
Keyword arguments passed into pdblp.BCon initialization
"""
con = BCon(**kwargs)
con.start()
try:
yield con
finally:
con.stop() | python | {
"resource": ""
} |
q257070 | BCon.start | validation | def start(self):
"""
Start connection and initialize session services
"""
# flush event queue in defensive way
logger = _get_logger(self.debug)
started = self._session.start()
if started:
ev = self._session.nextEvent()
ev_name = _EVENT_DIC... | python | {
"resource": ""
} |
q257071 | BCon._init_services | validation | def _init_services(self):
"""
Initialize blpapi.Session services
"""
logger = _get_logger(self.debug)
# flush event queue in defensive way
opened = self._session.openService('//blp/refdata')
ev = self._session.nextEvent()
ev_name = _EVENT_DICT[ev.eventTyp... | python | {
"resource": ""
} |
q257072 | BCon.bdib | validation | def bdib(self, ticker, start_datetime, end_datetime, event_type, interval,
elms=None):
"""
Get Open, High, Low, Close, Volume, and numEvents for a ticker.
Return pandas DataFrame
Parameters
----------
ticker: string
String corresponding to ticker... | python | {
"resource": ""
} |
q257073 | assemble_one | validation | def assemble_one(asmcode, pc=0, fork=DEFAULT_FORK):
""" Assemble one EVM instruction from its textual representation.
:param asmcode: assembly code for one instruction
:type asmcode: str
:param pc: program counter of the instruction(optional)
:type pc: int
:param fork: fork ... | python | {
"resource": ""
} |
q257074 | assemble_all | validation | def assemble_all(asmcode, pc=0, fork=DEFAULT_FORK):
""" Assemble a sequence of textual representation of EVM instructions
:param asmcode: assembly code for any number of instructions
:type asmcode: str
:param pc: program counter of the first instruction(optional)
:type pc: int
... | python | {
"resource": ""
} |
q257075 | disassemble_one | validation | def disassemble_one(bytecode, pc=0, fork=DEFAULT_FORK):
""" Disassemble a single instruction from a bytecode
:param bytecode: the bytecode stream
:type bytecode: str | bytes | bytearray | iterator
:param pc: program counter of the instruction(optional)
:type pc: int
:param f... | python | {
"resource": ""
} |
q257076 | disassemble_all | validation | def disassemble_all(bytecode, pc=0, fork=DEFAULT_FORK):
""" Disassemble all instructions in bytecode
:param bytecode: an evm bytecode (binary)
:type bytecode: str | bytes | bytearray | iterator
:param pc: program counter of the first instruction(optional)
:type pc: int
:para... | python | {
"resource": ""
} |
q257077 | block_to_fork | validation | def block_to_fork(block_number):
""" Convert block number to fork name.
:param block_number: block number
:type block_number: int
:return: fork name
:rtype: str
Example use::
>>> block_to_fork(0)
...
"frontier"
>>> block_to_f... | python | {
"resource": ""
} |
q257078 | Instruction.parse_operand | validation | def parse_operand(self, buf):
""" Parses an operand from buf
:param buf: a buffer
:type buf: iterator/generator/string
"""
buf = iter(buf)
try:
operand = 0
for _ in range(self.operand_size):
operand <<= 8
op... | python | {
"resource": ""
} |
q257079 | PassiveThrottle._adjust_delay | validation | def _adjust_delay(self, slot, response):
"""Define delay adjustment policy"""
if response.status in self.retry_http_codes:
new_delay = max(slot.delay, 1) * 4
new_delay = max(new_delay, self.mindelay)
new_delay = min(new_delay, self.maxdelay)
slot.delay = n... | python | {
"resource": ""
} |
q257080 | memberness | validation | def memberness(context):
'''The likelihood that the context is a "member".'''
if context:
texts = context.xpath('.//*[local-name()="explicitMember"]/text()').extract()
text = str(texts).lower()
if len(texts) > 1:
return 2
elif 'country' in text:
return 2
... | python | {
"resource": ""
} |
q257081 | EdgarSpider.parse_10qk | validation | def parse_10qk(self, response):
'''Parse 10-Q or 10-K XML report.'''
loader = ReportItemLoader(response=response)
item = loader.load_item()
if 'doc_type' in item:
doc_type = item['doc_type']
if doc_type in ('10-Q', '10-K'):
return item
re... | python | {
"resource": ""
} |
q257082 | camelcase | validation | def camelcase(string):
""" Convert string into camel case.
Args:
string: String to convert.
Returns:
string: Camel case string.
"""
string = re.sub(r"^[\-_\.]", '', str(string))
if not string:
return string
return lowercase(string[0]) + re.sub(r"[\-_\.\s]([a-z])",... | python | {
"resource": ""
} |
q257083 | capitalcase | validation | def capitalcase(string):
"""Convert string into capital case.
First letters will be uppercase.
Args:
string: String to convert.
Returns:
string: Capital case string.
"""
string = str(string)
if not string:
return string
return uppercase(string[0]) + string[1:] | python | {
"resource": ""
} |
q257084 | pathcase | validation | def pathcase(string):
"""Convert string into path case.
Join punctuation with slash.
Args:
string: String to convert.
Returns:
string: Path cased string.
"""
string = snakecase(string)
if not string:
return string
return re.sub(r"_", "/", string) | python | {
"resource": ""
} |
q257085 | backslashcase | validation | def backslashcase(string):
"""Convert string into spinal case.
Join punctuation with backslash.
Args:
string: String to convert.
Returns:
string: Spinal cased string.
"""
str1 = re.sub(r"_", r"\\", snakecase(string))
return str1 | python | {
"resource": ""
} |
q257086 | sentencecase | validation | def sentencecase(string):
"""Convert string into sentence case.
First letter capped and each punctuations are joined with space.
Args:
string: String to convert.
Returns:
string: Sentence cased string.
"""
joiner = ' '
string = re.sub(r"[\-_\.\s]", joiner, str(string))
... | python | {
"resource": ""
} |
q257087 | snakecase | validation | def snakecase(string):
"""Convert string into snake case.
Join punctuation with underscore
Args:
string: String to convert.
Returns:
string: Snake cased string.
"""
string = re.sub(r"[\-\.\s]", '_', str(string))
if not string:
return string
return lowercase(st... | python | {
"resource": ""
} |
q257088 | STree._check_input | validation | def _check_input(self, input):
"""Checks the validity of the input.
In case of an invalid input throws ValueError.
"""
if isinstance(input, str):
return 'st'
elif isinstance(input, list):
if all(isinstance(item, str) for item in input):
re... | python | {
"resource": ""
} |
q257089 | STree._label_generalized | validation | def _label_generalized(self, node):
"""Helper method that labels the nodes of GST with indexes of strings
found in their descendants.
"""
if node.is_leaf():
x = {self._get_word_start_index(node.idx)}
else:
x = {n for ns in node.transition_links for n in ns... | python | {
"resource": ""
} |
q257090 | STree._get_word_start_index | validation | def _get_word_start_index(self, idx):
"""Helper method that returns the index of the string based on node's
starting index"""
i = 0
for _idx in self.word_starts[1:]:
if idx < _idx:
return i
else:
i+=1
return i | python | {
"resource": ""
} |
q257091 | STree.lcs | validation | def lcs(self, stringIdxs=-1):
"""Returns the Largest Common Substring of Strings provided in stringIdxs.
If stringIdxs is not provided, the LCS of all strings is returned.
::param stringIdxs: Optional: List of indexes of strings.
"""
if stringIdxs == -1 or not isinstance(stringI... | python | {
"resource": ""
} |
q257092 | STree._find_lcs | validation | def _find_lcs(self, node, stringIdxs):
"""Helper method that finds LCS by traversing the labeled GSD."""
nodes = [self._find_lcs(n, stringIdxs)
for (n,_) in node.transition_links
if n.generalized_idxs.issuperset(stringIdxs)]
if nodes == []:
return node
... | python | {
"resource": ""
} |
q257093 | STree._generalized_word_starts | validation | def _generalized_word_starts(self, xs):
"""Helper method returns the starting indexes of strings in GST"""
self.word_starts = []
i = 0
for n in range(len(xs)):
self.word_starts.append(i)
i += len(xs[n]) + 1 | python | {
"resource": ""
} |
q257094 | STree.find | validation | def find(self, y):
"""Returns starting position of the substring y in the string used for
building the Suffix tree.
:param y: String
:return: Index of the starting position of string y in the string used for building the Suffix tree
-1 if y is not a substring.
"... | python | {
"resource": ""
} |
q257095 | STree._edgeLabel | validation | def _edgeLabel(self, node, parent):
"""Helper method, returns the edge label between a node and it's parent"""
return self.word[node.idx + parent.depth : node.idx + node.depth] | python | {
"resource": ""
} |
q257096 | STree._terminalSymbolsGenerator | validation | def _terminalSymbolsGenerator(self):
"""Generator of unique terminal symbols used for building the Generalized Suffix Tree.
Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols
are not part of the input string.
"""
py2 = sys.version[0] < '3'
UPP... | python | {
"resource": ""
} |
q257097 | ExampleOracle.query | validation | def query(self, i, j):
"Query the oracle to find out whether i and j should be must-linked"
if self.queries_cnt < self.max_queries_cnt:
self.queries_cnt += 1
return self.labels[i] == self.labels[j]
else:
raise MaximumQueriesExceeded | python | {
"resource": ""
} |
q257098 | preprocess_constraints | validation | def preprocess_constraints(ml, cl, n):
"Create a graph of constraints for both must- and cannot-links"
# Represent the graphs using adjacency-lists
ml_graph, cl_graph = {}, {}
for i in range(n):
ml_graph[i] = set()
cl_graph[i] = set()
def add_both(d, i, j):
d[i].add(j)
... | python | {
"resource": ""
} |
q257099 | make_pmml_pipeline | validation | def make_pmml_pipeline(obj, active_fields = None, target_fields = None):
"""Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline.
Parameters:
----------
obj: BaseEstimator
The object.
active_fields: list of strings, optional
Feature names. If missing, "x1", "x2", .., "xn" are assumed.
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.