_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q241800 | Controller.revoke | train | async def revoke(self, username, acl='login'):
"""Removes some or all access of a user to from a controller
If 'login' access is revoked, the user will no longer have any
permissions on the controller. Revoking a higher privilege from
a user without that privilege will have no effect.
... | python | {
"resource": ""
} |
q241801 | FileJujuData.current_model | train | def current_model(self, controller_name=None, model_only=False):
'''Return the current model, qualified by its controller name.
If controller_name is specified, the current model for
that controller will be returned.
If model_only is true, only the model name, not qualified by
i... | python | {
"resource": ""
} |
q241802 | FileJujuData.load_credential | train | def load_credential(self, cloud, name=None):
"""Load a local credential.
:param str cloud: Name of cloud to load credentials from.
:param str name: Name of credential. If None, the default credential
will be used, if available.
:return: A CloudCredential instance, or None.
... | python | {
"resource": ""
} |
q241803 | _macaroons_for_domain | train | def _macaroons_for_domain(cookies, domain):
'''Return any macaroons from the given cookie jar that
apply to the given domain name.'''
req = urllib.request.Request('https://' + domain + '/')
cookies.add_cookie_header(req)
return httpbakery.extract_macaroons(req) | python | {
"resource": ""
} |
q241804 | Monitor.status | train | def status(self):
"""
Determine the status of the connection and receiver, and return
ERROR, CONNECTED, or DISCONNECTED as appropriate.
For simplicity, we only consider ourselves to be connected
after the Connection class has setup a receiver task. This
only happens afte... | python | {
"resource": ""
} |
q241805 | Connection._pinger | train | async def _pinger(self):
'''
A Controller can time us out if we are silent for too long. This
is especially true in JaaS, which has a fairly strict timeout.
To prevent timing out, we send a ping every ten seconds.
'''
async def _do_ping():
try:
... | python | {
"resource": ""
} |
q241806 | Connection._http_headers | train | def _http_headers(self):
"""Return dictionary of http headers necessary for making an http
connection to the endpoint of this Connection.
:return: Dictionary of headers
"""
if not self.usertag:
return {}
creds = u'{}:{}'.format(
self.usertag,
... | python | {
"resource": ""
} |
q241807 | Connection.https_connection | train | def https_connection(self):
"""Return an https connection to this Connection's endpoint.
Returns a 3-tuple containing::
1. The :class:`HTTPSConnection` instance
2. Dictionary of auth headers to be used with the connection
3. The root url path (str) to be used for re... | python | {
"resource": ""
} |
q241808 | Connection.connect_params | train | def connect_params(self):
"""Return a tuple of parameters suitable for passing to
Connection.connect that can be used to make a new connection
to the same controller (and model if specified. The first
element in the returned tuple holds the endpoint argument;
the other holds a di... | python | {
"resource": ""
} |
q241809 | Connection.controller | train | async def controller(self):
"""Return a Connection to the controller at self.endpoint
"""
return await Connection.connect(
self.endpoint,
username=self.username,
password=self.password,
cacert=self.cacert,
bakery_client=self.bakery_clie... | python | {
"resource": ""
} |
q241810 | Connection.reconnect | train | async def reconnect(self):
""" Force a reconnection.
"""
monitor = self.monitor
if monitor.reconnecting.locked() or monitor.close_called.is_set():
return
async with monitor.reconnecting:
await self.close()
await self._connect_with_login([(self.... | python | {
"resource": ""
} |
q241811 | Connector.connect | train | async def connect(self, **kwargs):
"""Connect to an arbitrary Juju model.
kwargs are passed through to Connection.connect()
"""
kwargs.setdefault('loop', self.loop)
kwargs.setdefault('max_frame_size', self.max_frame_size)
kwargs.setdefault('bakery_client', self.bakery_cl... | python | {
"resource": ""
} |
q241812 | Connector.connect_controller | train | async def connect_controller(self, controller_name=None):
"""Connect to a controller by name. If the name is empty, it
connect to the current controller.
"""
if not controller_name:
controller_name = self.jujudata.current_controller()
if not controller_name:
... | python | {
"resource": ""
} |
q241813 | Connector.bakery_client_for_controller | train | def bakery_client_for_controller(self, controller_name):
'''Make a copy of the bakery client with a the appropriate controller's
cookiejar in it.
'''
bakery_client = self.bakery_client
if bakery_client:
bakery_client = copy.copy(bakery_client)
else:
... | python | {
"resource": ""
} |
q241814 | SSHProvisioner._get_ssh_client | train | def _get_ssh_client(self, host, user, key):
"""Return a connected Paramiko ssh object.
:param str host: The host to connect to.
:param str user: The user to connect as.
:param str key: The private key to authenticate with.
:return: object: A paramiko.SSHClient
:raises: ... | python | {
"resource": ""
} |
q241815 | SSHProvisioner._run_command | train | def _run_command(self, ssh, cmd, pty=True):
"""Run a command remotely via SSH.
:param object ssh: The SSHClient
:param str cmd: The command to execute
:param list cmd: The `shlex.split` command to execute
:param bool pty: Whether to allocate a pty
:return: tuple: The st... | python | {
"resource": ""
} |
q241816 | SSHProvisioner._init_ubuntu_user | train | def _init_ubuntu_user(self):
"""Initialize the ubuntu user.
:return: bool: If the initialization was successful
:raises: :class:`paramiko.ssh_exception.AuthenticationException`
if the authentication fails
"""
# TODO: Test this on an image without the ubuntu user set... | python | {
"resource": ""
} |
q241817 | SSHProvisioner._detect_hardware_and_os | train | def _detect_hardware_and_os(self, ssh):
"""Detect the target hardware capabilities and OS series.
:param object ssh: The SSHClient
:return: str: A raw string containing OS and hardware information.
"""
info = {
'series': '',
'arch': '',
'cpu-... | python | {
"resource": ""
} |
q241818 | SSHProvisioner.provision_machine | train | def provision_machine(self):
"""Perform the initial provisioning of the target machine.
:return: bool: The client.AddMachineParams
:raises: :class:`paramiko.ssh_exception.AuthenticationException`
if the upload fails
"""
params = client.AddMachineParams()
if ... | python | {
"resource": ""
} |
q241819 | SSHProvisioner._run_configure_script | train | def _run_configure_script(self, script):
"""Run the script to install the Juju agent on the target machine.
:param str script: The script returned by the ProvisioningScript API
:raises: :class:`paramiko.ssh_exception.AuthenticationException`
if the upload fails
"""
... | python | {
"resource": ""
} |
q241820 | _get_annotations | train | async def _get_annotations(entity_tag, connection):
"""Get annotations for the specified entity
:return dict: The annotations for the entity
"""
facade = client.AnnotationsFacade.from_connection(connection)
result = (await facade.Get([{"tag": entity_tag}])).results[0]
if result.error is not Non... | python | {
"resource": ""
} |
q241821 | _set_annotations | train | async def _set_annotations(entity_tag, annotations, connection):
"""Set annotations on the specified entity.
:param annotations map[string]string: the annotations as key/value
pairs.
"""
# TODO: ensure annotations is dict with only string keys
# and values.
log.debug('Updating annotatio... | python | {
"resource": ""
} |
q241822 | Relation.matches | train | def matches(self, *specs):
"""
Check if this relation matches relationship specs.
Relation specs are strings that would be given to Juju to establish a
relation, and should be in the form ``<application>[:<endpoint_name>]``
where the ``:<endpoint_name>`` suffix is optional. If ... | python | {
"resource": ""
} |
q241823 | ResourcesFacade.AddPendingResources | train | async def AddPendingResources(self, application_tag, charm_url, resources):
"""Fix the calling signature of AddPendingResources.
The ResourcesFacade doesn't conform to the standard facade pattern in
the Juju source, which leads to the schemagened code not matching up
properly with the a... | python | {
"resource": ""
} |
q241824 | Cloud.bootstrap | train | def bootstrap(
self, controller_name, region=None, agent_version=None,
auto_upgrade=False, bootstrap_constraints=None,
bootstrap_series=None, config=None, constraints=None,
credential=None, default_model=None, keep_broken=False,
metadata_source=None, no_gui=Fa... | python | {
"resource": ""
} |
q241825 | Unit.machine | train | def machine(self):
"""Get the machine object for this unit.
"""
machine_id = self.safe_data['machine-id']
if machine_id:
return self.model.machines.get(machine_id, None)
else:
return None | python | {
"resource": ""
} |
q241826 | Unit.run | train | async def run(self, command, timeout=None):
"""Run command on this unit.
:param str command: The command to run
:param int timeout: Time, in seconds, to wait before command is
considered failed
:returns: A :class:`juju.action.Action` instance.
"""
action = clien... | python | {
"resource": ""
} |
q241827 | Unit.run_action | train | async def run_action(self, action_name, **params):
"""Run an action on this unit.
:param str action_name: Name of action to run
:param **params: Action parameters
:returns: A :class:`juju.action.Action` instance.
Note that this only enqueues the action. You will need to call
... | python | {
"resource": ""
} |
q241828 | Unit.scp_to | train | async def scp_to(self, source, destination, user='ubuntu', proxy=False,
scp_opts=''):
"""Transfer files to this unit.
:param str source: Local path of file(s) to transfer
:param str destination: Remote destination of transferred files
:param str user: Remote usernam... | python | {
"resource": ""
} |
q241829 | Unit.get_metrics | train | async def get_metrics(self):
"""Get metrics for the unit.
:return: Dictionary of metrics for this unit.
"""
metrics = await self.model.get_metrics(self.tag)
return metrics[self.name] | python | {
"resource": ""
} |
q241830 | parse | train | def parse(constraints):
"""
Constraints must be expressed as a string containing only spaces
and key value pairs joined by an '='.
"""
if not constraints:
return None
if type(constraints) is dict:
# Fowards compatibilty: already parsed
return constraints
constraint... | python | {
"resource": ""
} |
q241831 | Application.add_relation | train | async def add_relation(self, local_relation, remote_relation):
"""Add a relation to another application.
:param str local_relation: Name of relation on this application
:param str remote_relation: Name of relation on the other
application in the form '<application>[:<relation_name>]... | python | {
"resource": ""
} |
q241832 | Application.add_unit | train | async def add_unit(self, count=1, to=None):
"""Add one or more units to this application.
:param int count: Number of units to add
:param str to: Placement directive, e.g.::
'23' - machine 23
'lxc:7' - new lxc container on machine 7
'24/lxc/3' - lxc container... | python | {
"resource": ""
} |
q241833 | Application.destroy_relation | train | async def destroy_relation(self, local_relation, remote_relation):
"""Remove a relation to another application.
:param str local_relation: Name of relation on this application
:param str remote_relation: Name of relation on the other
application in the form '<application>[:<relation... | python | {
"resource": ""
} |
q241834 | Application.destroy | train | async def destroy(self):
"""Remove this application from the model.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Destroying %s', self.name)
return await app_facade.Destroy(self.name) | python | {
"resource": ""
} |
q241835 | Application.expose | train | async def expose(self):
"""Make this application publicly available over the network.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Exposing %s', self.name)
return await app_facade.Expose(self.name) | python | {
"resource": ""
} |
q241836 | Application.get_config | train | async def get_config(self):
"""Return the configuration settings dict for this application.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Getting config for %s', self.name)
return (await app_facade.Get(self.name)).config | python | {
"resource": ""
} |
q241837 | Application.get_constraints | train | async def get_constraints(self):
"""Return the machine constraints dict for this application.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Getting constraints for %s', self.name)
result = (await app_facade.Get(self.name)).c... | python | {
"resource": ""
} |
q241838 | Application.get_actions | train | async def get_actions(self, schema=False):
"""Get actions defined for this application.
:param bool schema: Return the full action schema
:return dict: The charms actions, empty dict if none are defined.
"""
actions = {}
entity = [{"tag": self.tag}]
action_facade... | python | {
"resource": ""
} |
q241839 | Application.get_resources | train | async def get_resources(self):
"""Return resources for this application.
Returns a dict mapping resource name to
:class:`~juju._definitions.CharmResource` instances.
"""
facade = client.ResourcesFacade.from_connection(self.connection)
response = await facade.ListResource... | python | {
"resource": ""
} |
q241840 | Application.run | train | async def run(self, command, timeout=None):
"""Run command on all units for this application.
:param str command: The command to run
:param int timeout: Time to wait before command is considered failed
"""
action = client.ActionFacade.from_connection(self.connection)
l... | python | {
"resource": ""
} |
q241841 | Application.set_config | train | async def set_config(self, config):
"""Set configuration options for this application.
:param config: Dict of configuration to set
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Setting config for %s: %s', self.name, config)
... | python | {
"resource": ""
} |
q241842 | Application.reset_config | train | async def reset_config(self, to_default):
"""
Restore application config to default values.
:param list to_default: A list of config options to be reset to their
default value.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(... | python | {
"resource": ""
} |
q241843 | Application.set_constraints | train | async def set_constraints(self, constraints):
"""Set machine constraints for this application.
:param dict constraints: Dict of machine constraints
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Setting constraints for %s: %s... | python | {
"resource": ""
} |
q241844 | Application.unexpose | train | async def unexpose(self):
"""Remove public availability over the network for this application.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Unexposing %s', self.name)
return await app_facade.Unexpose(self.name) | python | {
"resource": ""
} |
q241845 | write_client | train | def write_client(captures, options):
"""
Write the TypeFactory classes to _client.py, along with some
imports and tables so that we can look up versioned Facades.
"""
with open("{}/_client.py".format(options.output_dir), "w") as f:
f.write(HEADER)
f.write("from juju.client._definiti... | python | {
"resource": ""
} |
q241846 | KindRegistry.lookup | train | def lookup(self, name, version=None):
"""If version is omitted, max version is used"""
versions = self.get(name)
if not versions:
return None
if version:
return versions[version]
return versions[max(versions)] | python | {
"resource": ""
} |
q241847 | install_package | train | def install_package(package,
wheels_path,
venv=None,
requirement_files=None,
upgrade=False,
install_args=None):
"""Install a Python package.
Can specify a specific version.
Can specify a prerelease.
Can ... | python | {
"resource": ""
} |
q241848 | _get_platform_for_set_of_wheels | train | def _get_platform_for_set_of_wheels(wheels_path):
"""For any set of wheel files, extracts a single platform.
Since a set of wheels created or downloaded on one machine can only
be for a single platform, if any wheel in the set has a platform
which is not `any`, it will be used with one exception:
... | python | {
"resource": ""
} |
q241849 | _get_os_properties | train | def _get_os_properties():
"""Retrieve distribution properties.
**Note that platform.linux_distribution and platform.dist are deprecated
and will be removed in Python 3.7. By that time, distro will become
mandatory.
"""
if IS_DISTRO_INSTALLED:
return distro.linux_distribution(full_distri... | python | {
"resource": ""
} |
q241850 | _get_env_bin_path | train | def _get_env_bin_path(env_path):
"""Return the bin path for a virtualenv
This provides a fallback for a situation in which you're trying
to use the script and create a virtualenv from within
a virtualenv in which virtualenv isn't installed and so
is not importable.
"""
if IS_VIRTUALENV_INST... | python | {
"resource": ""
} |
q241851 | _generate_metadata_file | train | def _generate_metadata_file(workdir,
archive_name,
platform,
python_versions,
package_name,
package_version,
build_tag,
pack... | python | {
"resource": ""
} |
q241852 | _set_archive_name | train | def _set_archive_name(package_name,
package_version,
python_versions,
platform,
build_tag=''):
"""Set the format of the output archive file.
We should aspire for the name of the archive to be
as compatible as possible w... | python | {
"resource": ""
} |
q241853 | get_source_name_and_version | train | def get_source_name_and_version(source):
"""Retrieve the source package's name and version.
If the source is a path, the name and version will be retrieved
by querying the setup.py file in the path.
If the source is PACKAGE_NAME==PACKAGE_VERSION, they will be used as
the name and version.
If ... | python | {
"resource": ""
} |
q241854 | get_source | train | def get_source(source):
"""Return a pip-installable source
If the source is a url to a package's tar file,
this will download the source and extract it to a temporary directory.
If the source is neither a url nor a local path, and is not provided
as PACKAGE_NAME==PACKAGE_VERSION, the provided sour... | python | {
"resource": ""
} |
q241855 | create | train | def create(source,
requirement_files=None,
force=False,
keep_wheels=False,
archive_destination_dir='.',
python_versions=None,
validate_archive=False,
wheel_args='',
archive_format='zip',
build_tag=''):
"""Create a Wag... | python | {
"resource": ""
} |
q241856 | install | train | def install(source,
venv=None,
requirement_files=None,
upgrade=False,
ignore_platform=False,
install_args=''):
"""Install a Wagon archive.
This can install in a provided `venv` or in the current
virtualenv in case one is currently active.
`up... | python | {
"resource": ""
} |
q241857 | validate | train | def validate(source):
"""Validate a Wagon archive. Return True if succeeds, False otherwise.
It also prints a list of all validation errors.
This will test that some of the metadata is solid, that
the required wheels are present within the archives and that
the package is installable.
Note tha... | python | {
"resource": ""
} |
q241858 | show | train | def show(source):
"""Merely returns the metadata for the provided archive.
"""
if is_verbose():
logger.info('Retrieving Metadata for: %s', source)
processed_source = get_source(source)
metadata = _get_metadata(processed_source)
shutil.rmtree(processed_source)
return metadata | python | {
"resource": ""
} |
q241859 | Client._convert_to_floats | train | def _convert_to_floats(self, data):
"""
Convert all values in a dict to floats
"""
for key, value in data.items():
data[key] = float(value)
return data | python | {
"resource": ""
} |
q241860 | PortfolioFactory.update | train | def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | python | {
"resource": ""
} |
q241861 | PortfolioFactory.trade_signals_handler | train | def trade_signals_handler(self, signals):
'''
Process buy and sell signals from the simulation
'''
alloc = {}
if signals['buy'] or signals['sell']:
# Compute the optimal portfolio allocation,
# Using user defined function
try:
... | python | {
"resource": ""
} |
q241862 | historical_pandas_yahoo | train | def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None):
'''
Fetch from yahoo! finance historical quotes
'''
#NOTE Panel for multiple symbols ?
#NOTE Adj Close column name not cool (a space)
return DataReader(symbol, source, start=start, end=end) | python | {
"resource": ""
} |
q241863 | average_returns | train | def average_returns(ts, **kwargs):
''' Compute geometric average returns from a returns time serie'''
average_type = kwargs.get('type', 'net')
if average_type == 'net':
relative = 0
else:
relative = -1 # gross
#start = kwargs.get('start', ts.index[0])
#end = kwargs.get('end', ts... | python | {
"resource": ""
} |
q241864 | returns | train | def returns(ts, **kwargs):
'''
Compute returns on the given period
@param ts : time serie to process
@param kwargs.type: gross or simple returns
@param delta : period betweend two computed returns
@param start : with end, will return the return betweend this elapsed time
@param period : del... | python | {
"resource": ""
} |
q241865 | daily_returns | train | def daily_returns(ts, **kwargs):
''' re-compute ts on a daily basis '''
relative = kwargs.get('relative', 0)
return returns(ts, delta=BDay(), relative=relative) | python | {
"resource": ""
} |
q241866 | list_files | train | def list_files(path, extension=".cpp", exclude="S.cpp"):
"""List paths to all files that ends with a given extension"""
return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))] | python | {
"resource": ""
} |
q241867 | intuition | train | def intuition(args):
'''
Main simulation wrapper
Load the configuration, run the engine and return the analyze.
'''
# Use the provided context builder to fill:
# - config: General behavior
# - strategy: Modules properties
# - market: The universe we will trade on
with setup.Co... | python | {
"resource": ""
} |
q241868 | TradingFactory._is_interactive | train | def _is_interactive(self):
''' Prevent middlewares and orders to work outside live mode '''
return not (
self.realworld and (dt.date.today() > self.datetime.date())) | python | {
"resource": ""
} |
q241869 | TradingFactory.use | train | def use(self, func, when='whenever'):
''' Append a middleware to the algorithm '''
#NOTE A middleware Object ?
# self.use() is usually called from initialize(), so no logger yet
print('registering middleware {}'.format(func.__name__))
self.middlewares.append({
'call':... | python | {
"resource": ""
} |
q241870 | TradingFactory.process_orders | train | def process_orders(self, orderbook):
''' Default and costant orders processor. Overwrite it for more
sophisticated strategies '''
for stock, alloc in orderbook.iteritems():
self.logger.info('{}: Ordered {} {} stocks'.format(
self.datetime, stock, alloc))
i... | python | {
"resource": ""
} |
q241871 | TradingFactory._call_one_middleware | train | def _call_one_middleware(self, middleware):
''' Evaluate arguments and execute the middleware function '''
args = {}
for arg in middleware['args']:
if hasattr(self, arg):
# same as eval() but safer for arbitrary code execution
args[arg] = reduce(getatt... | python | {
"resource": ""
} |
q241872 | TradingFactory._call_middlewares | train | def _call_middlewares(self):
''' Execute the middleware stack '''
for middleware in self.middlewares:
if self._check_condition(middleware['when']):
self._call_one_middleware(middleware) | python | {
"resource": ""
} |
q241873 | LiveBenchmark.normalize_date | train | def normalize_date(self, test_date):
''' Same function as zipline.finance.trading.py'''
test_date = pd.Timestamp(test_date, tz='UTC')
return pd.tseries.tools.normalize_date(test_date) | python | {
"resource": ""
} |
q241874 | Market._load_market_scheme | train | def _load_market_scheme(self):
''' Load market yaml description '''
try:
self.scheme = yaml.load(open(self.scheme_path, 'r'))
except Exception, error:
raise LoadMarketSchemeFailed(reason=error) | python | {
"resource": ""
} |
q241875 | DataQuandl.fetch | train | def fetch(self, code, **kwargs):
'''
Quandl entry point in datafeed object
'''
log.debug('fetching QuanDL data (%s)' % code)
# This way you can use your credentials even if
# you didn't provide them to the constructor
if 'authtoken' in kwargs:
self.qua... | python | {
"resource": ""
} |
q241876 | Analyze.rolling_performances | train | def rolling_performances(self, timestamp='one_month'):
''' Filters self.perfs '''
# TODO Study the impact of month choice
# TODO Check timestamp in an enumeration
# TODO Implement other benchmarks for perf computation
# (zipline issue, maybe expected)
if self.metrics:
... | python | {
"resource": ""
} |
q241877 | Analyze.overall_metrics | train | def overall_metrics(self, timestamp='one_month', metrics=None):
'''
Use zipline results to compute some performance indicators
'''
perfs = dict()
# If no rolling perfs provided, computes it
if metrics is None:
metrics = self.rolling_performances(timestamp=tim... | python | {
"resource": ""
} |
q241878 | ContextFactory._normalize_data_types | train | def _normalize_data_types(self, strategy):
''' some contexts only retrieves strings, giving back right type '''
for k, v in strategy.iteritems():
if not isinstance(v, str):
# There is probably nothing to do
continue
if v == 'true':
... | python | {
"resource": ""
} |
q241879 | Simulation._get_benchmark_handler | train | def _get_benchmark_handler(self, last_trade, freq='minutely'):
'''
Setup a custom benchmark handler or let zipline manage it
'''
return LiveBenchmark(
last_trade, frequency=freq).surcharge_market_data \
if utils.is_live(last_trade) else None | python | {
"resource": ""
} |
q241880 | Simulation.configure_environment | train | def configure_environment(self, last_trade, benchmark, timezone):
''' Prepare benchmark loader and trading context '''
if last_trade.tzinfo is None:
last_trade = pytz.utc.localize(last_trade)
# Setup the trading calendar from market informations
self.benchmark = benchmark
... | python | {
"resource": ""
} |
q241881 | apply_mapping | train | def apply_mapping(raw_row, mapping):
'''
Override this to hand craft conversion of row.
'''
row = {target: mapping_func(raw_row[source_key])
for target, (mapping_func, source_key)
in mapping.fget().items()}
return row | python | {
"resource": ""
} |
q241882 | invert_dataframe_axis | train | def invert_dataframe_axis(fct):
'''
Make dataframe index column names,
and vice et versa
'''
def inner(*args, **kwargs):
df_to_invert = fct(*args, **kwargs)
return pd.DataFrame(df_to_invert.to_dict().values(),
index=df_to_invert.to_dict().keys())
retur... | python | {
"resource": ""
} |
q241883 | use_google_symbol | train | def use_google_symbol(fct):
'''
Removes ".PA" or other market indicator from yahoo symbol
convention to suit google convention
'''
def decorator(symbols):
google_symbols = []
# If one symbol string
if isinstance(symbols, str):
symbols = [symbols]
symbols... | python | {
"resource": ""
} |
q241884 | get_sector | train | def get_sector(symbol):
'''
Uses BeautifulSoup to scrape stock sector from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
try:
sector = soup.find('td', text='Sector:').\
find_next_sibling().stri... | python | {
"resource": ""
} |
q241885 | get_industry | train | def get_industry(symbol):
'''
Uses BeautifulSoup to scrape stock industry from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
try:
industry = soup.find('td', text='Industry:').\
find_next_siblin... | python | {
"resource": ""
} |
q241886 | get_type | train | def get_type(symbol):
'''
Uses BeautifulSoup to scrape symbol category from Yahoo! Finance website
'''
url = 'http://finance.yahoo.com/q/pr?s=%s+Profile' % symbol
soup = BeautifulSoup(urlopen(url).read())
if soup.find('span', text='Business Summary'):
return 'Stock'
elif soup.find('s... | python | {
"resource": ""
} |
q241887 | get_historical_prices | train | def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested dictionary (dict of dicts).
outer dict keys are dates ('YYYY-MM-DD')
"""
params = urlencode({
's': symbol,
'a': int(st... | python | {
"resource": ""
} |
q241888 | _fx_mapping | train | def _fx_mapping(raw_rates):
''' Map raw output to clearer labels '''
return {pair[0].lower(): {
'timeStamp': pair[1],
'bid': float(pair[2] + pair[3]),
'ask': float(pair[4] + pair[5]),
'high': float(pair[6]),
'low': float(pair[7])
} for pair in map(lambda x: x.split(',... | python | {
"resource": ""
} |
q241889 | TrueFX.query_rates | train | def query_rates(self, pairs=[]):
''' Perform a request against truefx data '''
# If no pairs, TrueFx will use the ones given the last time
payload = {'id': self._session}
if pairs:
payload['c'] = _clean_pairs(pairs)
response = requests.get(self._api_url, params=payloa... | python | {
"resource": ""
} |
q241890 | next_tick | train | def next_tick(date, interval=15):
'''
Only return when we reach given datetime
'''
# Intuition works with utc dates, conversion are made for I/O
now = dt.datetime.now(pytz.utc)
live = False
# Sleep until we reach the given date
while now < date:
time.sleep(interval)
# Upd... | python | {
"resource": ""
} |
q241891 | intuition_module | train | def intuition_module(location):
''' Build the module path and import it '''
path = location.split('.')
# Get the last field, i.e. the object name in the file
obj = path.pop(-1)
return dna.utils.dynamic_import('.'.join(path), obj) | python | {
"resource": ""
} |
q241892 | build_trading_timeline | train | def build_trading_timeline(start, end):
''' Build the daily-based index we will trade on '''
EMPTY_DATES = pd.date_range('2000/01/01', periods=0, tz=pytz.utc)
now = dt.datetime.now(tz=pytz.utc)
if not start:
if not end:
# Live trading until the end of the day
bt_dates = ... | python | {
"resource": ""
} |
q241893 | is_leap | train | def is_leap(year):
"""Leap year or not in the Gregorian calendar."""
x = math.fmod(year, 4)
y = math.fmod(year, 100)
z = math.fmod(year, 400)
# Divisible by 4 and,
# either not divisible by 100 or divisible by 400.
return not x and (y or not z) | python | {
"resource": ""
} |
q241894 | gcal2jd | train | def gcal2jd(year, month, day):
"""Gregorian calendar date to Julian date.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
... | python | {
"resource": ""
} |
q241895 | jd2gcal | train | def jd2gcal(jd1, jd2):
"""Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
jd1, jd2: int
Sum of the two numbers is taken a... | python | {
"resource": ""
} |
q241896 | jcal2jd | train | def jcal2jd(year, month, day):
"""Julian calendar date to Julian date.
The input and output are for the proleptic Julian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
Month ... | python | {
"resource": ""
} |
q241897 | add_args_kwargs | train | def add_args_kwargs(func):
"""Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
"""
@wraps(func)
def w... | python | {
"resource": ""
} |
q241898 | set_up_log | train | def set_up_log(filename, verbose=True):
"""Set up log
This method sets up a basic log.
Parameters
----------
filename : str
Log file name
Returns
-------
logging.Logger instance
"""
# Add file extension.
filename += '.log'
if verbose:
print('Preparin... | python | {
"resource": ""
} |
q241899 | Observable.add_observer | train | def add_observer(self, signal, observer):
"""Add an observer to the object.
Raise an exception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
a function that will be called when the signal is emi... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.