_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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(
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` :param path: An additional path if we don't wish to query the\ bare endpoint. :type path: :obj:`string` :returns: A URL constructed from :func:`base_url` with the\ apropraite API version/prefix and the rest of the path added\ to it. :rtype: :obj:`string` """ log.debug('_url called with endpoint: {0} and path: {1}'.format( endpoint, path)) try: endpoint = ENDPOINTS[endpoint] except KeyError: # If we
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: (optional) include the node status in the\ returned nodes :type with_status: :bool: :param unreported: (optional) amount of hours when a node gets marked as unreported :type unreported: :obj:`None` or integer :param \*\*kwargs: The rest of the keyword arguments are passed to the _query function :returns: A generator yieling Nodes. :rtype: :class:`pypuppetdb.types.Node` """ nodes = self._query('nodes', **kwargs) now = datetime.datetime.utcnow() # If we happen to only get one node back it # won't be inside a list so iterating over it # goes boom. Therefor we wrap a list around it. if type(nodes) == dict: nodes = [nodes, ] if with_status: latest_events = self.event_counts( query=EqualsOperator("latest_report?", True), summarize_by='certname' ) for node in nodes: node['status_report'] = None node['events'] = None if with_status: status = [s for s in latest_events if s['subject']['title'] == node['certname']] try: node['status_report'] = node['latest_report_status'] if status: node['events'] = status[0] except KeyError: if status: node['events'] = status = status[0] if status['successes'] > 0: node['status_report'] = 'changed' if status['noops'] > 0: node['status_report'] = 'noop' if status['failures'] > 0: node['status_report'] = 'failed' else: node['status_report'] = 'unchanged' # node report age if node['report_timestamp'] is not None: try: last_report = json_to_datetime( node['report_timestamp']) last_report = last_report.replace(tzinfo=None) unreported_border = now - timedelta(hours=unreported) if last_report < unreported_border: delta = (now - last_report) node['unreported'] = True node['unreported_time'] = '{0}d {1}h {2}m'.format(
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
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` """ edges = self._query('edges', **kwargs) for edge in edges: identifier_source = edge['source_type'] + \ '[' + edge['source_title'] + ']' identifier_target = edge['target_type'] + \
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.
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 'containing_class', 'resource' and 'certname' or any comma-separated value thereof. :type summarize_by: :obj:`string` :param query: (Optional) The PuppetDB query to filter the results. This query is passed to the `events` endpoint. :type query: :obj:`string` :param count_by: (Optional) The object type that is counted when building the counts of 'successes', 'failures', 'noops' and 'skips'. Support values are 'certname' and 'resource' (default) :type count_by: :obj:`string` :param count_filter: (Optional) A JSON query that is applied to the
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 to the _query function. :returns: A generator yielding Inventory :rtype: :class:`pypuppetdb.types.Inventory` """ inventory = self._query('inventory', **kwargs)
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 host: (Default: 'localhost;) Hostname or IP of PuppetDB. :type host: :obj:`string` :param port: (Default: '8080') Port on which to talk to PuppetDB. :type port: :obj:`int` :param ssl_verify: (optional) Verify PuppetDB server certificate. :type ssl_verify: :obj:`bool` or :obj:`string` True, False or filesystem \ path to CA certificate. :param ssl_key: (optional) Path to our client secret key. :type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\ path. :param ssl_cert: (optional) Path to our client certificate. :type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\ path. :param timeout: (Default: 10) Number of seconds to wait for a response. :type timeout: :obj:`int` :param protocol: (optional) Explicitly specify the protocol to be used (especially handy when using HTTPS with ssl_verify=False and without certs) :type protocol: :obj:`None` or :obj:`string` :param url_path: (Default: '/') The URL path where PuppetDB is served :type url_path: :obj:`None` or :obj:`string` :param username:
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(),
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 command :param callback: callback that will be
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: callback that will be invoked upon completion or failure
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 of the command
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 callback: callback that will be invoked upon completion
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: VisitorIndexedBinary, opendnp3.ICollectionIndexedDoubleBitBinary: VisitorIndexedDoubleBitBinary, opendnp3.ICollectionIndexedCounter: VisitorIndexedCounter, opendnp3.ICollectionIndexedFrozenCounter: VisitorIndexedFrozenCounter, opendnp3.ICollectionIndexedAnalog: VisitorIndexedAnalog, opendnp3.ICollectionIndexedBinaryOutputStatus: VisitorIndexedBinaryOutputStatus,
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
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.analog[1].clazz = opendnp3.PointClass.Class2 db_config.analog[1].svariation = opendnp3.StaticAnalogVariation.Group30Var1 db_config.analog[1].evariation = opendnp3.EventAnalogVariation.Group32Var7 db_config.analog[2].clazz = opendnp3.PointClass.Class2 db_config.analog[2].svariation = opendnp3.StaticAnalogVariation.Group30Var1 db_config.analog[2].evariation = opendnp3.EventAnalogVariation.Group32Var7
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 # Just for testing purposes, convert it to an IINField and display the contents of the two bytes.
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
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
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,
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_] if (_CON_SYM_ in globals()) and (not restart): con
python
{ "resource": "" }
q257023
delete_connection
validation
def delete_connection(): """ Stop and destroy Bloomberg connection """
python
{ "resource": "" }
q257024
parse_markdown
validation
def parse_markdown(): """ Parse markdown as description """ readme_file = f'{PACKAGE_ROOT}/README.md'
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='A', Fill='B') [('nonTradingDayFillOption', 'ALL_CALENDAR_DAYS'), ('nonTradingDayFillMethod', 'NIL_VALUE')] >>> proc_elms(CshAdjNormal=False, CshAdjAbnormal=True) [('adjustmentNormal', False), ('adjustmentAbnormal', True)] >>> proc_elms(Per='W', Quote='Average', start_date='2018-01-10') [('periodicitySelection', 'WEEKLY'), ('overrideOption',
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( ... data=pd.read_pickle('xbbg/tests/data/sample_earning.pkl'), ... header=pd.read_pickle('xbbg/tests/data/sample_earning_header.pkl') ... ).round(2) level fy2017 fy2017_pct Asia-Pacific 1.0 3540.0 66.43    China 2.0 1747.0 49.35    Japan 2.0 1242.0 35.08    Singapore 2.0 551.0 15.56 United States 1.0 1364.0 25.60 Europe 1.0 263.0 4.94 Other Countries 1.0 162.0 3.04 """ if data.dropna(subset=['value']).empty: return pd.DataFrame() res = pd.concat([ grp.loc[:, ['value']].set_index(header.value) for _, grp in data.groupby(data.position) ], axis=1) res.index.name = None res.columns = res.iloc[0] res = res.iloc[1:].transpose().reset_index().apply( pd.to_numeric, downcast='float', errors='ignore' ) res.rename( columns=lambda vv: '_'.join(vv.lower().split()).replace('fy_', 'fy'), inplace=True, ) years = res.columns[res.columns.str.startswith('fy')] lvl_1 = res.level == 1 for yr in years: res.loc[:, yr] = res.loc[:, yr].round(1)
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: >>> format_output( ... data=pd.read_pickle('xbbg/tests/data/sample_bdp.pkl'), ... source='bdp' ... ).reset_index() ticker name 0 QQQ US Equity INVESCO QQQ TRUST SERIES 1 1 SPY US Equity SPDR S&P 500 ETF TRUST >>> format_output( ... data=pd.read_pickle('xbbg/tests/data/sample_dvd.pkl'), ... source='bds', col_maps={'Dividend Frequency': 'dvd_freq'} ... ).loc[:, ['ex_date', 'dividend_amount', 'dvd_freq']].reset_index() ticker ex_date dividend_amount dvd_freq 0 C US Equity 2018-02-02 0.32 Quarter """ if data.empty: return pd.DataFrame() if source == 'bdp': req_cols = ['ticker', 'field', 'value'] else: req_cols = ['ticker', 'field', 'name', 'value', 'position'] if any(col not in data for col in req_cols): return pd.DataFrame() if data.dropna(subset=['value']).empty: return pd.DataFrame() if source == 'bdp': res = pd.DataFrame(pd.concat([
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_bdib.parq'), ... ticker='SPY US Equity', ... ).xs('close', axis=1, level=1, drop_level=False) ticker SPY US Equity field close 2018-12-28 09:30:00-05:00 249.67 2018-12-28 09:31:00-05:00 249.54 2018-12-28 09:32:00-05:00 249.22 2018-12-28 09:33:00-05:00 249.01 2018-12-28 09:34:00-05:00 248.86 >>> format_intraday( ... data=pd.read_parquet('xbbg/tests/data/sample_bdib.parq'), ... ticker='SPY US Equity', price_only=True ... ) ticker SPY US Equity 2018-12-28 09:30:00-05:00 249.67 2018-12-28 09:31:00-05:00
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'] ... )) tickers: ['NVDA US Equity']
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 US Equity Crncy USD >>> bdp('IQ US Equity', 'Crncy').reset_index() ticker crncy 0 IQ US Equity USD """ logger = logs.get_logger(bdp, level=kwargs.pop('log', logs.LOG_LEVEL)) con, _ = create_connection() ovrds = assist.proc_ovrds(**kwargs) logger.info( f'loading reference data from Bloomberg:\n' f'{assist.info_qry(tickers=tickers, flds=flds)}' ) data = con.ref(tickers=tickers, flds=flds, ovrds=ovrds) if not kwargs.get('cache', False): return [data]
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 >>> >>> pd.options.display.width = 120 >>> s_dt, e_dt = '20180301', '20181031' >>> dvd = bds( ... 'NVDA US Equity', 'DVD_Hist_All', ... DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt, raw=True, ... ) >>> dvd.loc[:, ['ticker', 'name', 'value']].head(8) ticker name value 0 NVDA US Equity Declared Date 2018-08-16 1 NVDA US Equity Ex-Date 2018-08-29 2 NVDA US Equity Record Date 2018-08-30 3 NVDA US Equity Payable Date 2018-09-21 4 NVDA US Equity Dividend Amount 0.15 5 NVDA US Equity Dividend Frequency Quarter 6 NVDA US Equity Dividend Type Regular Cash 7 NVDA US Equity Declared Date 2018-05-10 >>> dvd = bds( ... 'NVDA US Equity', 'DVD_Hist_All', ... DVD_Start_Dt=s_dt, DVD_End_Dt=e_dt, ... ) >>> dvd.reset_index().loc[:, ['ticker', 'ex_date', 'dividend_amount']] ticker ex_date dividend_amount 0 NVDA US Equity 2018-08-29 0.15 1 NVDA US Equity 2018-05-23 0.15 >>> if not os.environ.get('BBG_ROOT', ''): ... os.environ['BBG_ROOT'] = f'{files.abspath(__file__, 1)}/tests/data' >>> idx_kw = dict(End_Dt='20181220', cache=True) >>> idx_wt = bds('DJI Index', 'Indx_MWeight_Hist', **idx_kw) >>> idx_wt.round(2).tail().reset_index(drop=True) index_member percent_weight 0 V UN 3.82 1 VZ UN 1.63 2 WBA UW 2.06 3 WMT UN 2.59
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`, `normal`, `abn` (=abnormal), `split`, `-` or None exact match of above words will adjust for corresponding events Case 0: `-` no adjustment for dividend or split Case 1: `dvd` or `normal|abn` will adjust for all dividends except splits Case 2: `adjust` will adjust for splits and ignore all dividends Case 3: `all` == `dvd|split` == adjust for all Case 4: None == Bloomberg default OR use kwargs **kwargs: overrides Returns: pd.DataFrame Examples: >>> res = bdh( ... tickers='VIX Index', flds=['High', 'Low', 'Last_Price'], ... start_date='2018-02-05', end_date='2018-02-07', ... ).round(2).transpose() >>> res.index.name = None >>> res.columns.name = None >>> res 2018-02-05 2018-02-06 2018-02-07 VIX Index High 38.80 50.30 31.64 Low 16.80 22.42 21.17 Last_Price 37.32 29.98 27.73 >>> bdh( ... tickers='AAPL US Equity', flds='Px_Last', ... start_date='20140605', end_date='20140610', adjust='-' ... ).round(2) ticker AAPL US Equity field Px_Last 2014-06-05 647.35 2014-06-06 645.57 2014-06-09 93.70 2014-06-10 94.25 >>> bdh( ... tickers='AAPL US Equity', flds='Px_Last', ... start_date='20140606', end_date='20140609', ... CshAdjNormal=False, CshAdjAbnormal=False, CapChg=False, ... ).round(2) ticker AAPL US Equity field Px_Last 2014-06-06 645.57 2014-06-09 93.70
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: ref: reference ticker or exchange for timezone keep_tz: if keep tz if reference ticker / exchange is given start_time: start time end_time: end time typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] Returns: pd.DataFrame """ from xbbg.core import intervals cur_data = bdib(ticker=ticker, dt=dt, typ=kwargs.get('typ', 'TRADE')) if cur_data.empty: return pd.DataFrame() fmt = '%H:%M:%S' ss = intervals.SessNA ref = kwargs.get('ref', None) exch = pd.Series() if ref is None else const.exch_info(ticker=ref) if session: ss = intervals.get_interval( ticker=kwargs.get('ref', ticker), session=session )
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: currency of earnings level: hierarchy level of earnings Returns: pd.DataFrame Examples: >>> data = earning('AMD US Equity', Eqy_Fund_Year=2017, Number_Of_Periods=1) >>> data.round(2) level fy2017 fy2017_pct Asia-Pacific 1.0 3540.0 66.43    China 2.0 1747.0 49.35    Japan 2.0 1242.0 35.08    Singapore 2.0 551.0 15.56
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] info = const.market_info(f'{prefix[:-1]}1 {asset}') f1, f2 = f'{prefix[:-1]}1 {asset}', f'{prefix[:-1]}2 {asset}' fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq=info['freq']) fut_1 = fut_ticker(gen_ticker=f1, dt=dt, freq=info['freq'])
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 """ logger = logs.get_logger(fut_ticker, level=log) dt = pd.Timestamp(dt) t_info = gen_ticker.split() asset = t_info[-1] if asset in ['Index', 'Curncy', 'Comdty']: ticker = ' '.join(t_info[:-1]) prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, asset elif asset == 'Equity': ticker = t_info[0] prefix, idx, postfix = ticker[:-1], int(ticker[-1]) - 1, ' '.join(t_info[1:]) else: logger.error(f'unkonwn asset type for ticker: {gen_ticker}') return '' month_ext = 4
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_EOD', 'Trading_Day_End_Time_EOD'] con, _ = create_connection() hours = con.ref(tickers=tickers, flds=cols) cur_dt = pd.Timestamp('today').strftime('%Y-%m-%d ') hours.loc[:, 'local'] = hours.value.astype(str).str[:-3] hours.loc[:, 'exch'] = pd.DatetimeIndex( cur_dt
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_ROOT'] = '' >>> hist_file(ticker='ES1 Index', dt='2018-08-01') == '' True >>> os.environ['BBG_ROOT'] = '/data/bbg' >>> hist_file(ticker='ES1 Index',
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, whether to load file from latest cached ext: file extension **kwargs: other overrides passed to ref function Returns: file location Examples: >>> import shutil >>> >>> os.environ['BBG_ROOT'] = '' >>> ref_file('BLT LN Equity', fld='Crncy') == '' True >>> os.environ['BBG_ROOT'] = '/data/bbg' >>> ref_file('BLT LN Equity', fld='Crncy', cache=True) '/data/bbg/Equity/BLT LN Equity/Crncy/ovrd=None.parq' >>> ref_file('BLT LN Equity', fld='Crncy') '' >>> cur_dt = utils.cur_time(tz=utils.DEFAULT_TZ) >>> ref_file( ... 'BLT LN Equity', fld='DVD_Hist_All', has_date=True, cache=True, ... ).replace(cur_dt, '[cur_date]') '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], ovrd=None.parq' >>> ref_file( ... 'BLT LN Equity', fld='DVD_Hist_All', has_date=True, ... cache=True, DVD_Start_Dt='20180101', ... ).replace(cur_dt, '[cur_date]')[:-5] '/data/bbg/Equity/BLT LN Equity/DVD_Hist_All/asof=[cur_date], DVD_Start_Dt=20180101' >>> sample = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl' >>> root_path = 'xbbg/tests/data' >>> sub_path = f'{root_path}/Equity/AAPL US Equity/DVD_Hist_All' >>> os.environ['BBG_ROOT'] = root_path >>> for tmp_file in files.all_files(sub_path): os.remove(tmp_file) >>> files.create_folder(sub_path) >>> sample in shutil.copy(f'{root_path}/{sample}', sub_path) True >>> new_file = ref_file( ... 'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101', ... has_date=True, cache=True, ext='pkl' ... ) >>> new_file.split('/')[-1] == f'asof={cur_dt}, DVD_Start_Dt=20180101.pkl' True >>> old_file = 'asof=2018-11-02, DVD_Start_Dt=20180101, DVD_End_Dt=20180501.pkl' >>> old_full = '/'.join(new_file.split('/')[:-1] + [old_file]) >>> updated_file = old_full.replace('2018-11-02', cur_dt) >>> updated_file in shutil.copy(old_full, updated_file) True >>> exist_file = ref_file( ... 'AAPL US Equity', 'DVD_Hist_All', DVD_Start_Dt='20180101', ... has_date=True, cache=True, ext='pkl' ... ) >>> exist_file == updated_file False >>> exist_file = ref_file(
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'] = 'xbbg/tests/data' >>> sample = pd.read_parquet('xbbg/tests/data/aapl.parq') >>> save_intraday(sample, 'AAPL US Equity', '2018-11-02') >>> # Invalid exchange >>> save_intraday(sample, 'AAPL XX Equity', '2018-11-02') >>> # Invalid empty data >>> save_intraday(pd.DataFrame(), 'AAPL US Equity', '2018-11-02') >>> # Invalid date - too close >>> cur_dt = utils.cur_time() >>> save_intraday(sample, 'AAPL US Equity', cur_dt) """ cur_dt = pd.Timestamp(dt).strftime('%Y-%m-%d') logger = logs.get_logger(save_intraday, level='debug') info = f'{ticker} / {cur_dt} / {typ}'
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] pre [04:00, 09:30] post [16:01, 20:00] dtype: object >>> exch_info('ES1 Index') tz America/New_York allday [18:00, 17:00] day [08:00, 17:00] dtype: object >>> exch_info('Z 1 Index') tz Europe/London allday [01:00, 21:00] day [01:00, 21:00] dtype: object >>> exch_info('TESTTICKER Corp').empty True >>> exch_info('US') tz America/New_York allday [04:00, 20:00] day [09:30, 16:00] pre [04:00, 09:30] post [16:01, 20: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') >>> info['freq'], info['is_fut'] ('M', True) >>> info = market_info('INT1 Curncy') >>> info['freq'], info['is_fut'] ('M', True) >>> info = market_info('CL1 Comdty') >>> info['freq'], info['is_fut'] ('M', True) >>> # Wrong tickers >>> market_info('C XX Equity') {} >>> market_info('XXX Comdty') {} >>> market_info('Bond_ISIN Corp') {} >>> market_info('XYZ Index') {} >>> market_info('XYZ Curncy') {} """ t_info = ticker.split() assets = param.load_info('assets') # ========================== # # Equity # # ========================== # if (t_info[-1] == 'Equity') and ('=' not in t_info[0]): exch = t_info[-2] for info in assets.get('Equity', [dict()]): if 'exch_codes' not in info: continue if exch in info['exch_codes']: return info return dict() # ============================ # # Currency # # ============================ # if t_info[-1] == 'Curncy': for info in assets.get('Curncy', [dict()]): if 'tickers' not in info: continue if (t_info[0].split('+')[0] in info['tickers']) or \ (t_info[0][-1].isdigit() and (t_info[0][:-1] in info['tickers'])): return info return dict() if t_info[-1] == 'Comdty': for info in assets.get('Comdty', [dict()]): if 'tickers' not in info: continue if t_info[0][:-1] in info['tickers']: return info return dict() # =================================== # # Index /
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) >>> ccy_pair(local='GBp') CurrencyPair(ticker='GBP Curncy', factor=100, power=-1) >>> ccy_pair(local='USD', base='GBp') CurrencyPair(ticker='GBP Curncy', factor=0.01, power=1) >>> ccy_pair(local='XYZ', base='USD') CurrencyPair(ticker='', factor=1.0, power=1) >>> ccy_pair(local='GBP', base='GBp') CurrencyPair(ticker='', factor=0.01, power=1) >>> ccy_pair(local='GBp', base='GBP') CurrencyPair(ticker='', factor=100.0, power=1) """ ccy_param = param.load_info(cat='ccy') if f'{local}{base}' in ccy_param: info = ccy_param[f'{local}{base}'] elif f'{base}{local}' in ccy_param: info
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 JT Equity', dt='2018-09-10') '2018-09-10 14:58' >>> market_timing('7267 JT Equity', dt='2018-09-10', tz=timezone.TimeZone.NY) '2018-09-10 01:58:00-04:00' >>> market_timing('7267 JT Equity', dt='2018-01-10', tz='NY') '2018-01-10 00:58:00-05:00' >>> market_timing('7267 JT Equity', dt='2018-09-10', tz='SPX Index') '2018-09-10 01:58:00-04:00' >>> market_timing('8035 JT Equity', dt='2018-09-10', timing='BOD') '2018-09-10 09:01' >>> market_timing('Z 1 Index', dt='2018-09-10', timing='FINISHED') '2018-09-10 21:00' >>> market_timing('TESTTICKER
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/40857703/1332656 Examples: >>> flatten('abc') ['abc'] >>> flatten(1) [1] >>> flatten(1.) [1.0] >>> flatten(['ab', 'cd', ['xy', 'zz']]) ['ab', 'cd', 'xy', 'zz']
python
{ "resource": "" }
q257046
_to_gen_
validation
def _to_gen_(iterable): """ Recursively iterate lists and tuples """ from collections import Iterable for elm in iterable: if
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 Returns: str: string representation of dict Examples: >>> test_dict = dict(b=1, a=0, c=2, _d=3) >>> to_str(test_dict) '{b=1, a=0, c=2}' >>> to_str(test_dict, sep='|') '{b=1|a=0|c=2}' >>> to_str(test_dict, public_only=False)
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 >>> os.environ['BBG_PATH'] = '' >>> exch = load_info(cat='exch') >>> pd.Series(exch['EquityUS']).allday [400, 2000] >>> test_root = f'{PKG_PATH}/tests' >>> os.environ['BBG_PATH'] = test_root >>> ovrd_exch = load_info(cat='exch') >>> # Somehow os.environ is not set properly in doctest environment >>> ovrd_exch.update(_load_yaml_(f'{test_root}/markets/exch.yml')) >>> pd.Series(ovrd_exch['EquityUS']).allday [300, 2100]
python
{ "resource": "" }
q257049
_load_yaml_
validation
def _load_yaml_(file_name): """ Load assets infomation from file Args: file_name: file name Returns: dict """
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'
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('\\',
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 extensions, split by ',' full_path: whether return full path (default True) has_date: whether has date in file name (default False) date_fmt: date format to check for has_date parameter Returns: list: all file names with criteria fulfilled """ if not os.path.exists(path=path_name): return [] path_name = path_name.replace('\\', '/') if keyword or ext: keyword = f'*{keyword}*' if keyword else '*' if not ext: ext = '*'
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 (default False) date_fmt: date format to check for has_date parameter Returns: list: all folder names fulfilled criteria """ if not os.path.exists(path=path_name): return [] path_name = path_name.replace('\\', '/') if keyword: folders = sort_by_modified([ f.replace('\\', '/') for f in glob.iglob(f'{path_name}/*{keyword}*') if
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
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 """
python
{ "resource": "" }
q257056
file_modified_time
validation
def file_modified_time(file_name) -> pd.Timestamp: """ File modified time in python Args:
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', end_time='09:30') >>> get_interval('005490 KS Equity', 'day_normal_30_20') Session(start_time='09:31', end_time='15:00') >>> get_interval('005490 KS Equity', 'day_close_20') Session(start_time='15:01', end_time='15:20') >>> get_interval('700 HK Equity', 'am_open_30') Session(start_time='09:30', end_time='10:00') >>> get_interval('700 HK Equity', 'am_normal_30_30') Session(start_time='10:01', end_time='11:30') >>> get_interval('700 HK Equity', 'am_close_30') Session(start_time='11:31', end_time='12:00') >>> get_interval('ES1 Index', 'day_exact_2130_2230') Session(start_time=None, end_time=None) >>> get_interval('ES1 Index', 'allday_exact_2130_2230') Session(start_time='21:30', end_time='22:30')
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 """
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
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
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_time and end_time """ logger = logs.get_logger(self.market_normal)
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 Returns: Session of start_time and end_time """ if session not in self.exch: return SessNA ss = self.exch[session] same_day = ss[0] < ss[-1] if not start_time: s_time = ss[0] else:
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') >>> tz_convert(dt_1, to_tz='NY') '2018-09-10 04:00:00-04:00'
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']
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('\\', '/')
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
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
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 ------- List of all messages received """ # flush event queue in case previous call errored out while(session.tryNextEvent()): pass print("Sending Request:\n %s" % request) session.sendRequest(request) messages = [] # Process received events while(True): # We provide timeout to give the chance for Ctrl+C
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
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_DICT[ev.eventType()] logger.info('Event Type: {!r}'.format(ev_name)) for msg in ev: logger.info('Message Received:\n{}'.format(msg)) if ev.eventType() != blpapi.Event.SESSION_STATUS: raise RuntimeError('Expected a "SESSION_STATUS" event but ' 'received a {!r}'.format(ev_name)) ev = self._session.nextEvent() ev_name = _EVENT_DICT[ev.eventType()] logger.info('Event Type: {!r}'.format(ev_name)) for msg in ev: logger.info('Message Received:\n{}'.format(msg)) if ev.eventType() != blpapi.Event.SESSION_STATUS:
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.eventType()] logger.info('Event Type: {!r}'.format(ev_name)) for msg in ev: logger.info('Message Received:\n{}'.format(msg)) if ev.eventType() != blpapi.Event.SERVICE_STATUS: raise RuntimeError('Expected a "SERVICE_STATUS" event but ' 'received a {!r}'.format(ev_name)) if not opened: logger.warning('Failed to open //blp/refdata') raise ConnectionError('Could not open a //blp/refdata service') self.refDataService = self._session.getService('//blp/refdata') opened = self._session.openService('//blp/exrsvc')
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 start_datetime: string UTC datetime in format YYYY-mm-ddTHH:MM:SS end_datetime: string UTC datetime in format YYYY-mm-ddTHH:MM:SS event_type: string {TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK} Requested data event type interval: int {1... 1440} Length of time bars elms: list of tuples List of tuples where each tuple corresponds to the other elements to be set. Refer to the IntradayBarRequest section in the 'Services & schemas reference guide' for more info on these values """ elms = [] if not elms else elms # flush event queue in case previous call errored out logger = _get_logger(self.debug) while(self._session.tryNextEvent()): pass # Create and fill the request for the historical data request = self.refDataService.createRequest('IntradayBarRequest') request.set('security', 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 name (optional) :type fork: str :return: An Instruction object :rtype: Instruction Example use:: >>> print assemble_one('LT') """ try: instruction_table = instruction_tables[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 :param fork: fork name (optional) :type fork: str :return: An generator of Instruction objects :rtype: generator[Instructions] Example use:: >>> assemble_one('''PUSH1 0x60\n \ PUSH1 0x40\n \ MSTORE\n \ PUSH1 0x2\n \
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 fork: fork name (optional) :type fork: str :return: an Instruction object :rtype: Instruction Example use:: >>> print disassemble_one('\x60\x10') """ instruction_table = instruction_tables[fork] if isinstance(bytecode, bytes): bytecode = bytearray(bytecode) if isinstance(bytecode, str): bytecode = bytearray(bytecode.encode('latin-1')) bytecode = iter(bytecode) try: opcode = next(bytecode)
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 :param fork: fork name (optional) :type fork: str :return: An generator of Instruction objects :rtype: list[Instruction] Example use:: >>> for inst in disassemble_all(bytecode): ... print(instr) ... PUSH1 0x60 PUSH1 0x40 MSTORE PUSH1 0x2 PUSH2 0x108 PUSH1 0x0
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_fork(4370000) ... "byzantium" >>> block_to_fork(4370001) ... "byzantium" """ forks_by_block = { 0: "frontier", 1150000: "homestead", # 1920000 Dao
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
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 = new_delay
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 elif 'member' not in text: return 0
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 =
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
python
{ "resource": "" }
q257083
capitalcase
validation
def capitalcase(string): """Convert string into capital case. First letters will be uppercase. Args: string: String to
python
{ "resource": "" }
q257084
pathcase
validation
def pathcase(string): """Convert string into path case. Join punctuation with slash. Args: string: String to convert.
python
{ "resource": "" }
q257085
backslashcase
validation
def backslashcase(string): """Convert string into spinal case. Join punctuation with backslash. Args: string: String to convert. Returns:
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)) if not 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:
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
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)}
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:]:
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.
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)]
python
{ "resource": "" }
q257093
STree._generalized_word_starts
validation
def _generalized_word_starts(self, xs): """Helper method returns the starting indexes of strings in GST"""
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. """ node = self.root while True:
python
{ "resource": "" }
q257095
STree._edgeLabel
validation
def _edgeLabel(self, node, parent): """Helper method, returns the edge label
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' UPPAs = list(list(range(0xE000,0xF8FF+1))
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
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) d[j].add(i) for (i, j) in ml: ml_graph[i].add(j) ml_graph[j].add(i) for (i, j) in cl: cl_graph[i].add(j) cl_graph[j].add(i) def dfs(i, graph, visited, component): visited[i] = True for j in graph[i]: if not visited[j]: dfs(j, graph, visited, component) component.append(i) # Run DFS from each node to get all the graph's components # and add an edge for each pair of nodes in the component (create a complete graph) # See http://www.techiedelight.com/transitive-closure-graph/ for more details visited = [False] * n neighborhoods = [] for i in range(n): if not visited[i] and ml_graph[i]: component = [] dfs(i, ml_graph, visited, component) for x1 in component: for x2 in component:
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,
python
{ "resource": "" }