sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def filter_files(self, path): """ Exclude files based on blueprint and project configuration as well as hidden files. """ excludes = r'|'.join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r'$.' for root, dirs, files in os.walk(path, topdown=True): dirs[:]...
Exclude files based on blueprint and project configuration as well as hidden files.
entailment
def find_files(self): """ Find all file paths for publishing, yield (urlname, kwargs) """ # yield blueprint paths first if getattr(self, 'blueprint_name', None): for path in walk_directory(os.path.join(self.path, self.blueprint_name), ignore=self.project.EXCLUDES): ...
Find all file paths for publishing, yield (urlname, kwargs)
entailment
def deploy_to_s3(self): """ Deploy a directory to an s3 bucket. """ self.tempdir = tempfile.mkdtemp('s3deploy') for keyname, absolute_path in self.find_file_paths(): self.s3_upload(keyname, absolute_path) shutil.rmtree(self.tempdir, True) return True
Deploy a directory to an s3 bucket.
entailment
def s3_upload(self, keyname, absolute_path): """ Upload a file to s3 """ mimetype = mimetypes.guess_type(absolute_path) options = {'Content-Type': mimetype[0]} if mimetype[0] is not None and mimetype[0].startswith('text/'): upload = open(absolute_path, 'rb') ...
Upload a file to s3
entailment
def find_file_paths(self): """ A generator function that recursively finds all files in the upload directory. """ paths = [] for root, dirs, files in os.walk(self.directory, topdown=True): rel_path = os.path.relpath(root, self.directory) for f in files: ...
A generator function that recursively finds all files in the upload directory.
entailment
def get_drive_api(): """ Get drive API client based on settings. """ settings = Settings() if settings.credentials: return get_drive_api_from_file(settings.credentials_path) if settings.client_secrets: return get_drive_api_from_client_secrets(settings.client_secrets_path)
Get drive API client based on settings.
entailment
def get_drive_api_from_client_secrets(path, reset_creds=False): """ Reads the local client secrets file if available (otherwise, opens a browser tab to walk through the OAuth 2.0 process, and stores the client secrets for future use) and then authorizes those credentials. Returns a Google Drive API ...
Reads the local client secrets file if available (otherwise, opens a browser tab to walk through the OAuth 2.0 process, and stores the client secrets for future use) and then authorizes those credentials. Returns a Google Drive API service object.
entailment
def get_drive_api_from_file(path): """ Open file with OAuth tokens. """ f = open(path) credentials = client.OAuth2Credentials.from_json(f.read()) return _get_drive_api(credentials)
Open file with OAuth tokens.
entailment
def _get_drive_api(credentials): """ For a given set of credentials, return a drive API object. """ http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('drive', 'v2', http=http) service.credentials = credentials # duck punch service obj. with credentials ...
For a given set of credentials, return a drive API object.
entailment
def main(): """ Primary Tarbell command dispatch. """ command = Command.lookup(args.get(0)) if len(args) == 0 or args.contains(('-h', '--help', 'help')): display_info(args) sys.exit(1) elif args.contains(('-v', '--version')): display_version() sys.exit(1) e...
Primary Tarbell command dispatch.
entailment
def display_info(args): """ Displays Tarbell info. """ puts('\nTarbell: Simple web publishing\n') puts('Usage: {0}\n'.format(colored.cyan('tarbell <command>'))) puts('Commands:\n') for command in Command.all_commands(): usage = command.usage or command.name help = command.he...
Displays Tarbell info.
entailment
def tarbell_generate(command, args, skip_args=False, extra_context=None, quiet=False): """ Generate static files. """ output_root = None with ensure_settings(command, args) as settings, ensure_project(command, args) as site: if not skip_args: output_root = list_get(args, 0, Fal...
Generate static files.
entailment
def tarbell_install(command, args): """ Install a project. """ with ensure_settings(command, args) as settings: project_url = args.get(0) puts("\n- Getting project information for {0}".format(project_url)) project_name = project_url.split("/").pop() error = None ...
Install a project.
entailment
def tarbell_install_blueprint(command, args): """ Install a project template. """ with ensure_settings(command, args) as settings: name = None error = None template_url = args.get(0) matches = [template for template in settings.config["project_templates"] if template.get(...
Install a project template.
entailment
def tarbell_list(command, args): """ List tarbell projects. """ with ensure_settings(command, args) as settings: projects_path = settings.config.get("projects_path") if not projects_path: show_error("{0} does not exist".format(projects_path)) sys.exit() p...
List tarbell projects.
entailment
def tarbell_list_templates(command, args): """ List available Tarbell blueprints. """ with ensure_settings(command, args) as settings: puts("\nAvailable project templates\n") _list_templates(settings) puts("")
List available Tarbell blueprints.
entailment
def tarbell_publish(command, args): """ Publish to s3. """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: bucket_name = list_get(args, 0, "staging") try: bucket_url = S3Url(site.project.S3_BUCKETS[bucket_name]) except KeyError...
Publish to s3.
entailment
def tarbell_newproject(command, args): """ Create new Tarbell project. """ with ensure_settings(command, args) as settings: # Set it up and make the directory name = _get_project_name(args) puts("Creating {0}".format(colored.cyan(name))) path = _get_path(name, settings) ...
Create new Tarbell project.
entailment
def tarbell_serve(command, args): """ Serve the current Tarbell project. """ with ensure_project(command, args) as site: with ensure_settings(command, args) as settings: address = list_get(args, 0, "").split(":") ip = list_get(address, 0, settings.config['default_server_i...
Serve the current Tarbell project.
entailment
def tarbell_switch(command, args): """ Switch to a project. """ with ensure_settings(command, args) as settings: projects_path = settings.config.get("projects_path") if not projects_path: show_error("{0} does not exist".format(projects_path)) sys.exit() pr...
Switch to a project.
entailment
def tarbell_update(command, args): """ Update the current tarbell project. """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: puts("Updating to latest blueprint\n") git = sh.git.bake(_cwd=site.base.base_dir) # stash then pull put...
Update the current tarbell project.
entailment
def tarbell_unpublish(command, args): """ Delete a project. """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: show_error("Not implemented!")
Delete a project.
entailment
def tarbell_spreadsheet(command, args): """ Open context spreadsheet """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: try: # First, try to get the Google Spreadsheet URL spreadsheet_url = _google_spreadsheet_url(site.project.SPRE...
Open context spreadsheet
entailment
def _context_source_file_url(path_or_url): """ Returns a URL for a remote or local context CSV file """ if path_or_url.startswith('http'): # Remote CSV. Just return the URL return path_or_url if path_or_url.startswith('/'): # Absolute path return "file://" + path_or_...
Returns a URL for a remote or local context CSV file
entailment
def _newproject(command, path, name, settings): """ Helper to create new project. """ key = None title = _get_project_title() template = _get_template(settings) # Init repo git = sh.git.bake(_cwd=path) puts(git.init()) if template.get("url"): # Create submodule ...
Helper to create new project.
entailment
def _install_requirements(path): """ Install a blueprint's requirements.txt """ locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path] success = True for location in locations: try: with open(os.path.join(location, "requirements.txt")): ...
Install a blueprint's requirements.txt
entailment
def _get_project_name(args): """ Get project name. """ name = args.get(0) puts("") while not name: name = raw_input("What is the project's short directory name? (e.g. my_project) ") return name
Get project name.
entailment
def _clean_suffix(string, suffix): """ If string endswith the suffix, remove it. Else leave it alone. """ suffix_len = len(suffix) if len(string) < suffix_len: # the string param was shorter than the suffix raise ValueError("A suffix can not be bigger than string argument.") if ...
If string endswith the suffix, remove it. Else leave it alone.
entailment
def _get_path(name, settings, mkdir=True): """ Generate a project path. """ default_projects_path = settings.config.get("projects_path") path = None if default_projects_path: path = raw_input("\nWhere would you like to create this project? [{0}/{1}] ".format(default_projects_path, name)...
Generate a project path.
entailment
def _mkdir(path): """ Make a directory or bail. """ try: os.mkdir(path) except OSError as e: if e.errno == 17: show_error("ABORTING: Directory {0} already exists.".format(path)) else: show_error("ABORTING: OSError {0}".format(e)) sys.exit()
Make a directory or bail.
entailment
def _get_template(settings): """ Prompt user to pick template from a list. """ puts("\nPick a template\n") template = None while not template: _list_templates(settings) index = raw_input("\nWhich template would you like to use? [1] ") if not index: index = "1"...
Prompt user to pick template from a list.
entailment
def _list_templates(settings): """ List templates from settings. """ for idx, option in enumerate(settings.config.get("project_templates"), start=1): puts(" {0!s:5} {1!s:36}".format( colored.yellow("[{0}]".format(idx)), colored.cyan(option.get("name")) )) ...
List templates from settings.
entailment
def _create_spreadsheet(name, title, path, settings): """ Create Google spreadsheet. """ if not settings.client_secrets: return None create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ") if create and not create.lower() == "y": return puts("Not creating sp...
Create Google spreadsheet.
entailment
def _add_user_to_file(file_id, service, user_email, perm_type='user', role='writer'): """ Grants the given set of permissions for a given file_id. service is an already-credentialed Google Drive service instance. """ new_permission = { 'value': user_email, 'type...
Grants the given set of permissions for a given file_id. service is an already-credentialed Google Drive service instance.
entailment
def _copy_config_template(name, title, template, path, key, settings): """ Get and render tarbell_config.py.template from Tarbell default. """ puts("\nCopying configuration file") context = settings.config context.update({ "default_context": { ...
Get and render tarbell_config.py.template from Tarbell default.
entailment
def _delete_dir(dir): """ Delete a directory. """ try: shutil.rmtree(dir) # delete directory except OSError as exc: if exc.errno != 2: # code 2 - no such file or directory raise # re-raise exception except UnboundLocalError: pass
Delete a directory.
entailment
def def_cmd(name=None, short=None, fn=None, usage=None, help=None): """ Define a command. """ command = Command(name=name, short=short, fn=fn, usage=usage, help=help) Command.register(command)
Define a command.
entailment
def save(self): """ Save settings. """ with open(self.path, "w") as f: self.config["project_templates"] = list(filter(lambda template: template.get("url"), self.config["project_templates"])) yaml.dump(self.config, f, default_flow_style=False)
Save settings.
entailment
def read_file(path, absolute=False, encoding='utf-8'): """ Read the file at `path`. If `absolute` is True, use absolute path, otherwise path is assumed to be relative to Tarbell template root dir. For example: .. code-block:: html+jinja <div class="chapter"> {{ read_fi...
Read the file at `path`. If `absolute` is True, use absolute path, otherwise path is assumed to be relative to Tarbell template root dir. For example: .. code-block:: html+jinja <div class="chapter"> {{ read_file('_chapters/one.txt')|linebreaks }} </div>
entailment
def render_file(context, path, absolute=False): """ Like :py:func:`read_file`, except that the file is rendered as a Jinja template using the current context. If `absolute` is True, use absolute path, otherwise path is assumed to be relative to Tarbell template root dir. For example: ...
Like :py:func:`read_file`, except that the file is rendered as a Jinja template using the current context. If `absolute` is True, use absolute path, otherwise path is assumed to be relative to Tarbell template root dir. For example: .. code-block:: html+jinja <div class="chapter...
entailment
def format_date(value, format='%b %d, %Y', convert_tz=None): """ Format an Excel date or date string, returning a formatted date. To return a Python :py:class:`datetime.datetime` object, pass ``None`` as a ``format`` argument. >>> format_date(42419.82163) 'Feb. 19, 2016' .. code-block:: ht...
Format an Excel date or date string, returning a formatted date. To return a Python :py:class:`datetime.datetime` object, pass ``None`` as a ``format`` argument. >>> format_date(42419.82163) 'Feb. 19, 2016' .. code-block:: html+jinja {{ row.date|format_date('%Y-%m-%d') }}
entailment
def pprint_lines(value): """ Pretty print lines """ pformatted = pformat(value, width=1, indent=4) formatted = "{0}\n {1}\n{2}".format( pformatted[0], pformatted[1:-1], pformatted[-1] ) return Markup(formatted)
Pretty print lines
entailment
def plot_composition(df, intervals, axes=None): """ Plot time series of generics and label underlying instruments which these series are composed of. Parameters: ----------- df: pd.DataFrame DataFrame of time series to be plotted. Each column is a generic time series. interv...
Plot time series of generics and label underlying instruments which these series are composed of. Parameters: ----------- df: pd.DataFrame DataFrame of time series to be plotted. Each column is a generic time series. intervals: pd.DataFrame A DataFrame including information ...
entailment
def intervals(weights): """ Extract intervals where generics are composed of different tradeable instruments. Parameters ---------- weights: DataFrame or dict A DataFrame or dictionary of DataFrames with columns representing generics and a MultiIndex of date and contract. Values...
Extract intervals where generics are composed of different tradeable instruments. Parameters ---------- weights: DataFrame or dict A DataFrame or dictionary of DataFrames with columns representing generics and a MultiIndex of date and contract. Values represent weights on tradea...
entailment
def synchronize(self): """Synchronizes Router DB from Neturon DB with EOS. Walks through the Neturon Db and ensures that all the routers created in Netuton DB match with EOS. After creating appropriate routers, it ensures to add interfaces as well. Uses idempotent properties of ...
Synchronizes Router DB from Neturon DB with EOS. Walks through the Neturon Db and ensures that all the routers created in Netuton DB match with EOS. After creating appropriate routers, it ensures to add interfaces as well. Uses idempotent properties of EOS configuration, which means ...
entailment
def create_router(self, context, router): """Create a new router entry in DB, and create it Arista HW.""" # Add router to the DB new_router = super(AristaL3ServicePlugin, self).create_router( context, router) # create router on the Arista Hw try: ...
Create a new router entry in DB, and create it Arista HW.
entailment
def update_router(self, context, router_id, router): """Update an existing router in DB, and update it in Arista HW.""" # Read existing router record from DB original_router = self.get_router(context, router_id) # Update router DB new_router = super(AristaL3ServicePlugin, self)....
Update an existing router in DB, and update it in Arista HW.
entailment
def delete_router(self, context, router_id): """Delete an existing router from Arista HW as well as from the DB.""" router = self.get_router(context, router_id) # Delete router on the Arista Hw try: self.driver.delete_router(context, router_id, router) except Except...
Delete an existing router from Arista HW as well as from the DB.
entailment
def add_router_interface(self, context, router_id, interface_info): """Add a subnet of a network to an existing router.""" new_router = super(AristaL3ServicePlugin, self).add_router_interface( context, router_id, interface_info) core = directory.get_plugin() # Get network ...
Add a subnet of a network to an existing router.
entailment
def remove_router_interface(self, context, router_id, interface_info): """Remove a subnet of a network from an existing router.""" router_to_del = ( super(AristaL3ServicePlugin, self).remove_router_interface( context, router_id, interface_info...
Remove a subnet of a network from an existing router.
entailment
def initialize_switch_endpoints(self): """Initialize endpoints for switch communication""" self._switches = {} self._port_group_info = {} self._validate_config() for s in cfg.CONF.ml2_arista.switch_info: switch_ip, switch_user, switch_pass = s.split(":") i...
Initialize endpoints for switch communication
entailment
def _check_dynamic_acl_support(self): """Log an error if any switches don't support dynamic ACLs""" cmds = ['ip access-list openstack-test dynamic', 'no ip access-list openstack-test'] for switch_ip, switch_client in self._switches.items(): try: self.r...
Log an error if any switches don't support dynamic ACLs
entailment
def _validate_config(self): """Ensure at least one switch is configured""" if len(cfg.CONF.ml2_arista.get('switch_info')) < 1: msg = _('Required option - when "sec_group_support" is enabled, ' 'at least one switch must be specified ') LOG.exception(msg) ...
Ensure at least one switch is configured
entailment
def run_openstack_sg_cmds(self, commands, switch): """Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :pa...
Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param switch: Endpoint on the Arista switch to be configured
entailment
def _run_eos_cmds(self, commands, switch): """Execute/sends a CAPI (Command API) command to EOS. This method is useful for running show commands that require no prefix or postfix commands. :param commands : List of commands to be executed on EOS. :param switch: Endpoint on the ...
Execute/sends a CAPI (Command API) command to EOS. This method is useful for running show commands that require no prefix or postfix commands. :param commands : List of commands to be executed on EOS. :param switch: Endpoint on the Arista switch to be configured
entailment
def _get_switchports(profile): """Return list of (switch_ip, interface) tuples from local_link_info""" switchports = [] if profile.get('local_link_information'): for link in profile['local_link_information']: if 'switch_info' in link and 'port_id' in link: ...
Return list of (switch_ip, interface) tuples from local_link_info
entailment
def _update_port_group_info(self, switches=None): """Refresh data on switch interfaces' port group membership""" if switches is None: switches = self._switches.keys() for switch_ip in switches: client = self._switches.get(switch_ip) ret = self._run_eos_cmds(['...
Refresh data on switch interfaces' port group membership
entailment
def _get_port_for_acl(self, port_id, switch): """Gets interface name for ACLs Finds the Port-Channel name if port_id is in a Port-Channel, otherwise ACLs are applied to Ethernet interface. :param port_id: Name of port from ironic db :param server: Server endpoint on the Arista ...
Gets interface name for ACLs Finds the Port-Channel name if port_id is in a Port-Channel, otherwise ACLs are applied to Ethernet interface. :param port_id: Name of port from ironic db :param server: Server endpoint on the Arista switch to be configured
entailment
def _supported_rule(protocol, ethertype): """Checks that the rule is an IPv4 rule of a supported protocol""" if not protocol or protocol not in utils.SUPPORTED_SG_PROTOCOLS: return False if ethertype != n_const.IPv4: return False return True
Checks that the rule is an IPv4 rule of a supported protocol
entailment
def _format_rule(self, protocol, cidr, min_port, max_port, direction): """Get EOS formatted rule""" if cidr is None: cidr = 'any' if direction == n_const.INGRESS_DIRECTION: dst_ip = 'any' src_ip = cidr elif direction == n_const.EGRESS_DIRECTION: ...
Get EOS formatted rule
entailment
def _format_rules_for_eos(self, rules): """Format list of rules for EOS and sort into ingress/egress rules""" in_rules = [] eg_rules = [] for rule in rules: protocol = rule.get('protocol') cidr = rule.get('remote_ip_prefix', 'any') min_port = rule.get(...
Format list of rules for EOS and sort into ingress/egress rules
entailment
def run_cmds_on_all_switches(self, cmds): """Runs all cmds on all configured switches This helper is used for ACL and rule creation/deletion as ACLs and rules must exist on all switches. """ for switch in self._switches.values(): self.run_openstack_sg_cmds(cmds, swit...
Runs all cmds on all configured switches This helper is used for ACL and rule creation/deletion as ACLs and rules must exist on all switches.
entailment
def run_per_switch_cmds(self, switch_cmds): """Applies cmds to appropriate switches This takes in a switch->cmds mapping and runs only the set of cmds specified for a switch on that switch. This helper is used for applying/removing ACLs to/from interfaces as this config will vary ...
Applies cmds to appropriate switches This takes in a switch->cmds mapping and runs only the set of cmds specified for a switch on that switch. This helper is used for applying/removing ACLs to/from interfaces as this config will vary from switch to switch.
entailment
def _get_switches(self, profile): """Get set of switches referenced in a port binding profile""" switchports = self._get_switchports(profile) switches = set([switchport[0] for switchport in switchports]) return switches
Get set of switches referenced in a port binding profile
entailment
def get_create_security_group_commands(self, sg_id, sg_rules): """Commands for creating ACL""" cmds = [] in_rules, eg_rules = self._format_rules_for_eos(sg_rules) cmds.append("ip access-list %s dynamic" % self._acl_name(sg_id, n_const.INGRESS_DIRECTION)) for i...
Commands for creating ACL
entailment
def get_delete_security_group_commands(self, sg_id): """Commands for deleting ACL""" cmds = [] cmds.append("no ip access-list %s" % self._acl_name(sg_id, n_const.INGRESS_DIRECTION)) cmds.append("no ip access-list %s" % self._acl_name(sg_id, n_const...
Commands for deleting ACL
entailment
def _get_rule_cmds(self, sg_id, sg_rule, delete=False): """Helper for getting add/delete ACL rule commands""" rule_prefix = "" if delete: rule_prefix = "no " in_rules, eg_rules = self._format_rules_for_eos([sg_rule]) cmds = [] if in_rules: cmds.app...
Helper for getting add/delete ACL rule commands
entailment
def get_delete_security_group_rule_commands(self, sg_id, sg_rule): """Commands for removing rule from ACLS""" return self._get_rule_cmds(sg_id, sg_rule, delete=True)
Commands for removing rule from ACLS
entailment
def _get_interface_commands(self, sg_id, profile, delete=False): """Helper for getting interface ACL apply/remove commands""" rule_prefix = "" if delete: rule_prefix = "no " switch_cmds = {} switchports = self._get_switchports(profile) for switch_ip, intf in s...
Helper for getting interface ACL apply/remove commands
entailment
def get_remove_security_group_commands(self, sg_id, profile): """Commands for removing ACL from interface""" return self._get_interface_commands(sg_id, profile, delete=True)
Commands for removing ACL from interface
entailment
def _parse_acl_config(self, acl_config): """Parse configured ACLs and rules ACLs are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., } """ parsed_acls = dict() for acl in...
Parse configured ACLs and rules ACLs are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., }
entailment
def _parse_binding_config(self, binding_config): """Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ]) """ parsed_...
Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ])
entailment
def _get_dynamic_acl_info(self, switch_ip): """Retrieve ACLs, ACLs rules and interface bindings from switch""" cmds = ["enable", "show ip access-lists dynamic", "show ip access-lists summary dynamic"] switch = self._switches.get(switch_ip) _, acls, bindin...
Retrieve ACLs, ACLs rules and interface bindings from switch
entailment
def get_expected_acls(self): """Query the neutron DB for Security Groups and Rules Groups and rules are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., } """ security_groups = db...
Query the neutron DB for Security Groups and Rules Groups and rules are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., }
entailment
def get_expected_bindings(self): """Query the neutron DB for SG->switch interface bindings Bindings are returned as a dict of bindings for each switch: {<switch1>: set([(intf1, acl_name, direction), (intf2, acl_name, direction)]), <switch2>: set([(intf1, acl_na...
Query the neutron DB for SG->switch interface bindings Bindings are returned as a dict of bindings for each switch: {<switch1>: set([(intf1, acl_name, direction), (intf2, acl_name, direction)]), <switch2>: set([(intf1, acl_name, direction)]), ..., }
entailment
def adjust_bindings_for_lag(self, switch_ip, bindings): """Adjusting interface names for expected bindings where LAGs exist""" # Get latest LAG info for switch self._update_port_group_info([switch_ip]) # Update bindings to account for LAG info adjusted_bindings = set() ...
Adjusting interface names for expected bindings where LAGs exist
entailment
def get_sync_acl_cmds(self, switch_acls, expected_acls): """Returns the list of commands required synchronize switch ACLs 1. Identify unexpected ACLs and delete them 2. Iterate over expected ACLs a. Add missing ACLs + all rules b. Delete unexpected rules c. Add ...
Returns the list of commands required synchronize switch ACLs 1. Identify unexpected ACLs and delete them 2. Iterate over expected ACLs a. Add missing ACLs + all rules b. Delete unexpected rules c. Add missing rules
entailment
def get_sync_binding_cmds(self, switch_bindings, expected_bindings): """Returns the list of commands required to synchronize ACL bindings 1. Delete any unexpected bindings 2. Add any missing bindings """ switch_cmds = list() # Update any necessary switch interface ACLs ...
Returns the list of commands required to synchronize ACL bindings 1. Delete any unexpected bindings 2. Add any missing bindings
entailment
def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dates name_func: func A function to apply ...
Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dates name_func: func A function to apply to the file strings to infer the instrument name, ...
entailment
def flatten(weights): """ Flatten weights into a long DataFrame. Parameters ---------- weights: pandas.DataFrame or dict A DataFrame of instrument weights with a MultiIndex where the top level contains pandas. Timestamps and the second level is instrument names. The columns ...
Flatten weights into a long DataFrame. Parameters ---------- weights: pandas.DataFrame or dict A DataFrame of instrument weights with a MultiIndex where the top level contains pandas. Timestamps and the second level is instrument names. The columns consist of generic names. If dict ...
entailment
def unflatten(flat_weights): """ Pivot weights from long DataFrame into weighting matrix. Parameters ---------- flat_weights: pandas.DataFrame A long DataFrame of weights, where columns are "date", "contract", "generic", "weight" and optionally "key". If "key" column is pres...
Pivot weights from long DataFrame into weighting matrix. Parameters ---------- flat_weights: pandas.DataFrame A long DataFrame of weights, where columns are "date", "contract", "generic", "weight" and optionally "key". If "key" column is present a dictionary of unflattened DataFrame...
entailment
def calc_rets(returns, weights): """ Calculate continuous return series for futures instruments. These consist of weighted underlying instrument returns, who's weights can vary over time. Parameters ---------- returns: pandas.Series or dict A Series of instrument returns with a Mult...
Calculate continuous return series for futures instruments. These consist of weighted underlying instrument returns, who's weights can vary over time. Parameters ---------- returns: pandas.Series or dict A Series of instrument returns with a MultiIndex where the top level is pandas....
entailment
def reindex(prices, index, limit): """ Reindex a pd.Series of prices such that when instrument level returns are calculated they are compatible with a pd.MultiIndex of instrument weights in calc_rets(). This amount to reindexing the series by an augmented version of index which includes the precedin...
Reindex a pd.Series of prices such that when instrument level returns are calculated they are compatible with a pd.MultiIndex of instrument weights in calc_rets(). This amount to reindexing the series by an augmented version of index which includes the preceding date for the first appearance of each ins...
entailment
def calc_trades(current_contracts, desired_holdings, trade_weights, prices, multipliers, **kwargs): """ Calculate the number of tradeable contracts for rebalancing from a set of current contract holdings to a set of desired generic notional holdings based on prevailing prices and mapping...
Calculate the number of tradeable contracts for rebalancing from a set of current contract holdings to a set of desired generic notional holdings based on prevailing prices and mapping from generics to tradeable instruments. Differences between current holdings and desired holdings are treated as 0. Zer...
entailment
def to_notional(instruments, prices, multipliers, desired_ccy=None, instr_fx=None, fx_rates=None): """ Convert number of contracts of tradeable instruments to notional value of tradeable instruments in a desired currency. Parameters ---------- instruments: pandas.Series ...
Convert number of contracts of tradeable instruments to notional value of tradeable instruments in a desired currency. Parameters ---------- instruments: pandas.Series Series of instrument holdings. Index is instrument name and values are number of contracts. prices: pandas.Series ...
entailment
def to_contracts(instruments, prices, multipliers, desired_ccy=None, instr_fx=None, fx_rates=None, rounder=None): """ Convert notional amount of tradeable instruments to number of instrument contracts, rounding to nearest integer number of contracts. Parameters ---------- instr...
Convert notional amount of tradeable instruments to number of instrument contracts, rounding to nearest integer number of contracts. Parameters ---------- instruments: pandas.Series Series of instrument holdings. Index is instrument name and values are notional amount on instrument. ...
entailment
def get_multiplier(weights, root_generic_multiplier): """ Determine tradeable instrument multiplier based on generic asset multipliers and weights mapping from generics to tradeables. Parameters ---------- weights: pandas.DataFrame or dict A pandas.DataFrame of loadings of generic contr...
Determine tradeable instrument multiplier based on generic asset multipliers and weights mapping from generics to tradeables. Parameters ---------- weights: pandas.DataFrame or dict A pandas.DataFrame of loadings of generic contracts on tradeable instruments **for a given date**. The co...
entailment
def weighted_expiration(weights, contract_dates): """ Calculate the days to expiration for generic futures, weighted by the composition of the underlying tradeable instruments. Parameters: ----------- weights: pandas.DataFrame A DataFrame of instrument weights with a MultiIndex where th...
Calculate the days to expiration for generic futures, weighted by the composition of the underlying tradeable instruments. Parameters: ----------- weights: pandas.DataFrame A DataFrame of instrument weights with a MultiIndex where the top level contains pandas.Timestamps and the second ...
entailment
def _valid_baremetal_port(port): """Check if port is a baremetal port with exactly one security group""" if port.get(portbindings.VNIC_TYPE) != portbindings.VNIC_BAREMETAL: return False sgs = port.get('security_groups', []) if len(sgs) == 0: # Nothing to do ...
Check if port is a baremetal port with exactly one security group
entailment
def synchronize_resources(self): """Synchronize worker with CVX All database queries must occur while the sync lock is held. This tightly couples reads with writes and ensures that an older read does not result in the last write. Eg: Worker 1 reads (P1 created) Worder 2...
Synchronize worker with CVX All database queries must occur while the sync lock is held. This tightly couples reads with writes and ensures that an older read does not result in the last write. Eg: Worker 1 reads (P1 created) Worder 2 reads (P1 deleted) Worker 2 writes ...
entailment
def register(self, resource, event, trigger, **kwargs): """Called in trunk plugin's AFTER_INIT""" super(AristaTrunkDriver, self).register(resource, event, trigger, kwargs) registry.subscribe(self.subport_create, resources...
Called in trunk plugin's AFTER_INIT
entailment
def create_router_on_eos(self, router_name, rdm, server): """Creates a router on Arista HW Device. :param router_name: globally unique identifier for router/VRF :param rdm: A value generated by hashing router name :param server: Server endpoint on the Arista switch to be configured ...
Creates a router on Arista HW Device. :param router_name: globally unique identifier for router/VRF :param rdm: A value generated by hashing router name :param server: Server endpoint on the Arista switch to be configured
entailment
def delete_router_from_eos(self, router_name, server): """Deletes a router from Arista HW Device. :param router_name: globally unique identifier for router/VRF :param server: Server endpoint on the Arista switch to be configured """ cmds = [] for c in self.routerDict['de...
Deletes a router from Arista HW Device. :param router_name: globally unique identifier for router/VRF :param server: Server endpoint on the Arista switch to be configured
entailment
def add_interface_to_router(self, segment_id, router_name, gip, router_ip, mask, server): """Adds an interface to existing HW router on Arista HW device. :param segment_id: VLAN Id associated with interface that is added :param router_name: globally unique identi...
Adds an interface to existing HW router on Arista HW device. :param segment_id: VLAN Id associated with interface that is added :param router_name: globally unique identifier for router/VRF :param gip: Gateway IP associated with the subnet :param router_ip: IP address of the router ...
entailment
def delete_interface_from_router(self, segment_id, router_name, server): """Deletes an interface from existing HW router on Arista HW device. :param segment_id: VLAN Id associated with interface that is added :param router_name: globally unique identifier for router/VRF :param server: S...
Deletes an interface from existing HW router on Arista HW device. :param segment_id: VLAN Id associated with interface that is added :param router_name: globally unique identifier for router/VRF :param server: Server endpoint on the Arista switch to be configured
entailment
def create_router(self, context, router): """Creates a router on Arista Switch. Deals with multiple configurations - such as Router per VRF, a router in default VRF, Virtual Router in MLAG configurations """ if router: router_name = self._arista_router_name(router['i...
Creates a router on Arista Switch. Deals with multiple configurations - such as Router per VRF, a router in default VRF, Virtual Router in MLAG configurations
entailment
def delete_router(self, context, router_id, router): """Deletes a router from Arista Switch.""" if router: router_name = self._arista_router_name(router_id, router['name']) mlag_peer_failed = False for s in self._servers: try: self...
Deletes a router from Arista Switch.
entailment
def add_router_interface(self, context, router_info): """Adds an interface to a router created on Arista HW router. This deals with both IPv6 and IPv4 configurations. """ if router_info: self._select_dicts(router_info['ip_version']) cidr = router_info['cidr'] ...
Adds an interface to a router created on Arista HW router. This deals with both IPv6 and IPv4 configurations.
entailment
def remove_router_interface(self, context, router_info): """Removes previously configured interface from router on Arista HW. This deals with both IPv6 and IPv4 configurations. """ if router_info: router_name = self._arista_router_name(router_info['id'], ...
Removes previously configured interface from router on Arista HW. This deals with both IPv6 and IPv4 configurations.
entailment
def _run_config_cmds(self, commands, server): """Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param s...
Execute/sends a CAPI (Command API) command to EOS. In this method, list of commands is appended with prefix and postfix commands - to make is understandble by EOS. :param commands : List of command to be executed on EOS. :param server: Server endpoint on the Arista switch to be configu...
entailment