docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D unit8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049.
def extract_labels(self, f, one_hot=False, num_classes=10): print('Extracting', f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = self._read32(bytestream) if magic != 2049: raise ValueError('Invalid magic number %d in MNIST label file: %s' % (magic, f.name)) num_items = self._read32(bytestream) buf = bytestream.read(num_items) labels = np.frombuffer(buf, dtype=np.uint8) if one_hot: return self.dense_to_one_hot(labels, num_classes) return labels
978,187
Will try to read configuration from environment variables and ini files, if no value found in either of those ``None`` is returned. Args: prefix: The environment variable prefix. section: The ini file section this configuration is scoped to filename: The path to the ini file to use
def __init__(self, prefix, section, filename=None): options = dict(prefix=prefix, section=section, filename=filename) super(Settings, self).__init__(**options)
978,318
Expands ~/path to /home/<current_user>/path On POSIX systems does it by getting the home directory for the current effective user from the passwd database. On other systems do it by using :func:`os.path.expanduser` Args: path (str): A path to expand to a user's home folder Returns: str: expanded path
def expand_user(path): if not path.startswith('~'): return path if os.name == 'posix': user = pwd.getpwuid(os.geteuid()) return path.replace('~', user.pw_dir, 1) else: return os.path.expanduser(path)
978,549
Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Handled formats for keyword arguments are: * --argument=value * --argument value Args: *args (list): a list of arguments Returns: ([positional_args], {kwargs})
def format_arguments(*args): positional_args = [] kwargs = {} split_key = None for arg in args: if arg.startswith('--'): arg = arg[2:] if '=' in arg: key, value = arg.split('=', 1) kwargs[key.replace('-', '_')] = value else: split_key = arg.replace('-', '_') elif split_key: kwargs[split_key] = arg split_key = None else: positional_args.append(arg) return positional_args, kwargs
978,551
Returns a `gocd.Server` configured by the `settings` object. Args: settings: a `gocd_cli.settings.Settings` object. Default: if falsey calls `get_settings`. Returns: gocd.Server: a configured gocd.Server instance
def get_go_server(settings=None): if not settings: settings = get_settings() return gocd.Server( settings.get('server'), user=settings.get('user'), password=settings.get('password'), )
978,554
Extract an expression from the flow of tokens. Args: rbp (int): the "right binding power" of the previous token. This represents the (right) precedence of the previous token, and will be compared to the (left) precedence of next tokens. Returns: Whatever the led/nud functions of tokens returned.
def expression(self, rbp=0): prev_token = self.consume() # Retrieve the value from the previous token situated at the # leftmost point in the expression left = prev_token.nud(context=self) while rbp < self.current_token.lbp: # Read incoming tokens with a higher 'left binding power'. # Those are tokens that prefer binding to the left of an expression # than to the right of an expression. prev_token = self.consume() left = prev_token.led(left, context=self) return left
978,823
Register a token. Args: token (Token): the token class to register regexp (str): the regexp for that token
def register(self, token, regexp): self._tokens.append((token, re.compile(regexp)))
978,897
Retrieve all token definitions matching the beginning of a text. Args: text (str): the text to test start (int): the position where matches should be searched in the string (see re.match(rx, txt, pos)) Yields: (token_class, re.Match): all token class whose regexp matches the text, and the related re.Match object.
def matching_tokens(self, text, start=0): for token_class, regexp in self._tokens: match = regexp.match(text, pos=start) if match: yield token_class, match
978,898
Retrieve the next token from some text. Args: text (str): the text from which tokens should be extracted Returns: (token_kind, token_text): the token kind and its content.
def get_token(self, text, start=0): best_class = best_match = None for token_class, match in self.matching_tokens(text): if best_match and best_match.end() >= match.end(): continue best_match = match best_class = token_class return best_class, best_match
978,899
Register a token class. Args: token_class (tdparser.Token): the token class to register regexp (optional str): the regexp for elements of that token. Defaults to the `regexp` attribute of the token class.
def register_token(self, token_class, regexp=None): if regexp is None: regexp = token_class.regexp self.tokens.register(token_class, regexp)
978,901
Split self.text into a list of tokens. Args: text (str): text to parse Yields: Token: the tokens generated from the given text.
def lex(self, text): pos = 0 while text: token_class, match = self.tokens.get_token(text) if token_class is not None: matched_text = text[match.start():match.end()] yield token_class(matched_text) text = text[match.end():] pos += match.end() elif text[0] in self.blank_chars: text = text[1:] pos += 1 else: raise LexerError( 'Invalid character %s in %s' % (text[0], text), position=pos) yield self.end_token()
978,902
Parse self.text. Args: text (str): the text to lex Returns: object: a node representing the current rule.
def parse(self, text): tokens = self.lex(text) parser = Parser(tokens) return parser.parse()
978,903
Parse a stream. Args: ifp (string or file-like object): input stream. pb_cls (protobuf.message.Message.__class__): The class object of the protobuf message type encoded in the stream.
def parse(ifp, pb_cls, **kwargs): mode = 'rb' if isinstance(ifp, str): istream = open(ifp, mode=mode, **kwargs) else: istream = open(fileobj=ifp, mode=mode, **kwargs) with istream: for data in istream: pb_obj = pb_cls() pb_obj.ParseFromString(data) yield pb_obj
979,173
Write to a stream. Args: ofp (string or file-like object): output stream. pb_objs (*protobuf.message.Message): list of protobuf message objects to be written.
def dump(ofp, *pb_objs, **kwargs): mode = 'wb' if isinstance(ofp, str): ostream = open(ofp, mode=mode, **kwargs) else: ostream = open(fileobj=ofp, mode=mode, **kwargs) with ostream: ostream.write(*pb_objs)
979,174
Write a group of one or more protobuf objects to the file. Multiple object groups can be written by calling this method several times before closing stream or exiting the runtime context. The input protobuf objects get buffered and will be written down when the number of buffered objects exceed the `self._buffer_size`. Args: pb2_obj (*protobuf.message.Message): list of protobuf messages.
def write(self, *pb2_obj): base = len(self._write_buff) for idx, obj in enumerate(pb2_obj): if self._buffer_size > 0 and \ (idx + base) != 0 and \ (idx + base) % self._buffer_size == 0: self.flush() self._write_buff.append(obj) if self._buffer_size == 0: self.flush()
979,179
Called to store the ticket data for a request. Ticket data is stored in the aiohttp_session object Args: request: aiohttp Request object. ticket: String like object representing the ticket to be stored.
async def remember_ticket(self, request, ticket): session = await get_session(request) session[self.cookie_name] = ticket
979,457
Called to forget the ticket data a request Args: request: aiohttp Request object.
async def forget_ticket(self, request): session = await get_session(request) session.pop(self.cookie_name, '')
979,458
Called to return the ticket for a request. Args: request: aiohttp Request object. Returns: A ticket (string like) object, or None if no ticket is available for the passed request.
async def get_ticket(self, request): session = await get_session(request) return session.get(self.cookie_name)
979,459
Returns a aiohttp_auth middleware factory for use by the aiohttp application object. Args: policy: A authentication policy with a base class of AbstractAuthentication.
def auth_middleware(policy): assert isinstance(policy, AbstractAuthentication) async def _auth_middleware_factory(app, handler): async def _middleware_handler(request): # Save the policy in the request request[POLICY_KEY] = policy # Call the next handler in the chain response = await handler(request) # Give the policy a chance to handle the response await policy.process_response(request, response) return response return _middleware_handler return _auth_middleware_factory
979,471
Returns the user_id associated with a particular request. Args: request: aiohttp Request object. Returns: The user_id associated with the request, or None if no user is associated with the request. Raises: RuntimeError: Middleware is not installed
async def get_auth(request): auth_val = request.get(AUTH_KEY) if auth_val: return auth_val auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError('auth_middleware not installed') request[AUTH_KEY] = await auth_policy.get(request) return request[AUTH_KEY]
979,472
Called to store and remember the userid for a request Args: request: aiohttp Request object. user_id: String representing the user_id to remember Raises: RuntimeError: Middleware is not installed
async def remember(request, user_id): auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError('auth_middleware not installed') return await auth_policy.remember(request, user_id)
979,473
Called to forget the userid for a request Args: request: aiohttp Request object Raises: RuntimeError: Middleware is not installed
async def forget(request): auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError('auth_middleware not installed') return await auth_policy.forget(request)
979,474
Called to store the userid for a request. This function creates a ticket from the request and user_id, and calls the abstract function remember_ticket() to store the ticket. Args: request: aiohttp Request object. user_id: String representing the user_id to remember
async def remember(self, request, user_id): ticket = self._new_ticket(request, user_id) await self.remember_ticket(request, ticket)
979,522
Gets the user_id for the request. Gets the ticket for the request using the get_ticket() function, and authenticates the ticket. Args: request: aiohttp Request object. Returns: The userid for the request, or None if the ticket is not authenticated.
async def get(self, request): ticket = await self.get_ticket(request) if ticket is None: return None try: # Returns a tuple of (user_id, token, userdata, validuntil) now = time.time() fields = self._ticket.validate(ticket, self._get_ip(request), now) # Check if we need to reissue a ticket if (self._reissue_time is not None and now >= (fields.valid_until - self._reissue_time)): # Reissue our ticket, and save it in our request. request[_REISSUE_KEY] = self._new_ticket(request, fields.user_id) return fields.user_id except TicketError as e: return None
979,523
Unnest collection structure extracting all its datasets and converting \ them to Pandas Dataframes. Args: collection (OrderedDict): data in JSON-stat format, previously \ deserialized to a python object by \ json.load() or json.loads(), df_list (list): list variable which will contain the converted \ datasets. Returns: Nothing.
def unnest_collection(collection, df_list): for item in collection['link']['item']: if item['class'] == 'dataset': df_list.append(Dataset.read(item['href']).write('dataframe')) elif item['class'] == 'collection': nested_collection = request(item['href']) unnest_collection(nested_collection, df_list)
979,579
Get dimensions from input data. Args: js_dict (dict): dictionary containing dataset data and metadata. naming (string, optional): dimension naming. Possible values: 'label' \ or 'id'. Returns: dimensions (list): list of pandas data frames with dimension \ category data. dim_names (list): list of strings with dimension names.
def get_dimensions(js_dict, naming): dimensions = [] dim_names = [] if check_version_2(js_dict): dimension_dict = js_dict else: dimension_dict = js_dict['dimension'] for dim in dimension_dict['id']: dim_name = js_dict['dimension'][dim]['label'] if not dim_name: dim_name = dim if naming == 'label': dim_label = get_dim_label(js_dict, dim) dimensions.append(dim_label) dim_names.append(dim_name) else: dim_index = get_dim_index(js_dict, dim) dimensions.append(dim_index) dim_names.append(dim) return dimensions, dim_names
979,580
Get label from a given dimension. Args: js_dict (dict): dictionary containing dataset data and metadata. dim (string): dimension name obtained from JSON file. Returns: dim_label(pandas.DataFrame): DataFrame with label-based dimension data.
def get_dim_label(js_dict, dim, input="dataset"): if input == 'dataset': input = js_dict['dimension'][dim] label_col = 'label' elif input == 'dimension': label_col = js_dict['label'] input = js_dict else: raise ValueError try: dim_label = input['category']['label'] except KeyError: dim_index = get_dim_index(js_dict, dim) dim_label = pd.concat([dim_index['id'], dim_index['id']], axis=1) dim_label.columns = ['id', 'label'] else: dim_label = pd.DataFrame(list(zip(dim_label.keys(), dim_label.values())), index=dim_label.keys(), columns=['id', label_col]) # index must be added to dim label so that it can be sorted try: dim_index = input['category']['index'] except KeyError: dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])), index=[0], columns=['id', 'index']) else: if type(dim_index) is list: dim_index = pd.DataFrame(list(zip(dim_index, range(0, len(dim_index)))), index=dim_index, columns=['id', 'index']) else: dim_index = pd.DataFrame(list(zip(dim_index.keys(), dim_index.values())), index=dim_index.keys(), columns=['id', 'index']) dim_label = pd.merge(dim_label, dim_index, on='id').sort_index(by='index') return dim_label
979,581
Get index from a given dimension. Args: js_dict (dict): dictionary containing dataset data and metadata. dim (string): dimension name obtained from JSON file. Returns: dim_index (pandas.DataFrame): DataFrame with index-based dimension data.
def get_dim_index(js_dict, dim): try: dim_index = js_dict['dimension'][dim]['category']['index'] except KeyError: dim_label = get_dim_label(js_dict, dim) dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])), index=[0], columns=['id', 'index']) else: if type(dim_index) is list: dim_index = pd.DataFrame(list(zip(dim_index, range(0, len(dim_index)))), index=dim_index, columns=['id', 'index']) else: dim_index = pd.DataFrame(list(zip(dim_index.keys(), dim_index.values())), index=dim_index.keys(), columns=['id', 'index']) dim_index = dim_index.sort_index(by='index') return dim_index
979,582
Get values from input data. Args: js_dict (dict): dictionary containing dataset data and metadata. value (string, optional): name of the value column. Defaults to 'value'. Returns: values (list): list of dataset values.
def get_values(js_dict, value='value'): values = js_dict[value] if type(values) is list: if type(values[0]) is not dict or tuple: return values # being not a list of dicts or tuples leaves us with a dict... values = {int(key): value for (key, value) in values.items()} if js_dict.get('size'): max_val = np.prod(np.array((js_dict['size']))) else: max_val = np.prod(np.array((js_dict['dimension']['size']))) vals = max_val * [None] for (key, value) in values.items(): vals[key] = value values = vals return values
979,583
Return unique values in a list in the original order. See: \ http://www.peterbe.com/plog/uniqifiers-benchmark Args: seq (list): original list. Returns: list: list without duplicates preserving original order.
def uniquify(seq): seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)]
979,585
Send a request to a given URL accepting JSON format and return a \ deserialized Python object. Args: path (str): The URI to be requested. Returns: response: Deserialized JSON Python object. Raises: HTTPError: the HTTP error returned by the requested server. InvalidURL: an invalid URL has been requested. Exception: generic exception.
def request(path): headers = {'Accept': 'application/json'} try: requested_object = requests.get(path, headers=headers) requested_object.raise_for_status() except requests.exceptions.HTTPError as exception: LOGGER.error((inspect.stack()[0][3]) + ': HTTPError = ' + str(exception.response.status_code) + ' ' + str(exception.response.reason) + ' ' + str(path)) raise except requests.exceptions.InvalidURL as exception: LOGGER.error('URLError = ' + str(exception.reason) + ' ' + str(path)) raise except Exception: import traceback LOGGER.error('Generic exception: ' + traceback.format_exc()) raise else: response = requested_object.json() return response
979,589
Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON file, a JSON string, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class Dataset populated with data.
def read(cls, data): if isinstance(data, pd.DataFrame): return cls((json.loads( to_json_stat(data, output='dict', version='2.0'), object_pairs_hook=OrderedDict))) elif isinstance(data, OrderedDict): return cls(data) elif (isinstance(data, basestring) and data.startswith(("http://", "https://", "ftp://", "ftps://"))): # requests will do the rest... return cls(request(data)) elif isinstance(data, basestring): try: json_dict = json.loads(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise else: try: json_dict = json.load(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise
979,590
Converts a dimension ID string and a categody ID string into the \ numeric index of that category in that dimension Args: name(string): ID string of the dimension. value(string): ID string of the category. Returns: ndx[value](int): index of the category in the dimension.
def get_dimension_index(self, name, value): if 'index' not in self.get('dimension', {}). \ get(name, {}).get('category', {}): return 0 ndx = self['dimension'][name]['category']['index'] if isinstance(ndx, list): return ndx.index(value) else: return ndx[value]
979,591
Converts a dimension/category list of dicts into a list of \ dimensions’ indices. Args: query(list): dimension/category list of dicts. Returns: indices(list): list of dimensions' indices.
def get_dimension_indices(self, query): ids = self['id'] if self.get('id') else self['dimension']['id'] indices = [] for idx, id in enumerate(ids): indices.append(self.get_dimension_index(id, [d.get(id) for d in query if id in d][0])) return indices
979,592
Converts a list of dimensions’ indices into a numeric value index. Args: indices(list): list of dimension's indices. Returns: num(int): numeric value index.
def get_value_index(self, indices): size = self['size'] if self.get('size') else self['dimension']['size'] ndims = len(size) mult = 1 num = 0 for idx, dim in enumerate(size): mult *= size[ndims - idx] if (idx > 0) else 1 num += mult * indices[ndims - idx - 1] return num
979,593
Converts a dimension/category list of dicts into a data value \ in three steps. Args: query(list): list of dicts with the desired query. Returns: value(float): numeric data value.
def get_value(self, query): indices = self.get_dimension_indices(query) index = self.get_value_index(indices) value = self.get_value_by_index(index) return value
979,594
Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON string, a JSON file, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class Dimension populated with data.
def read(cls, data): if isinstance(data, pd.DataFrame): output = OrderedDict({}) output['version'] = '2.0' output['class'] = 'dimension' [label] = [x for x in list(data.columns.values) if x not in ['id', 'index']] output['label'] = label output['category'] = OrderedDict({}) output['category']['index'] = data.id.tolist() output['category']['label'] = OrderedDict( zip(data.id.values, data[label].values)) return cls(output) elif isinstance(data, OrderedDict): return cls(data) elif isinstance(data, basestring) and data.startswith(("http://", "https://", "ftp://", "ftps://")): return cls(request(data)) elif isinstance(data,basestring): try: json_dict = json.loads(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise else: try: json_dict = json.load(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise
979,596
Writes data from a Dataset object to JSONstat or Pandas Dataframe. Args: output(string): can accept 'jsonstat' or 'dataframe' Returns: Serialized JSONstat or a Pandas Dataframe,depending on the \ 'output' parameter.
def write(self, output='jsonstat'): if output == 'jsonstat': return json.dumps(OrderedDict(self), cls=NumpyEncoder) elif output == 'dataframe': return get_dim_label(self, self['label'], 'dimension') else: raise ValueError("Allowed arguments are 'jsonstat' or 'dataframe'")
979,597
Reads data from URL or OrderedDict. Args: data: can be a URL pointing to a JSONstat file, a JSON string or an OrderedDict. Returns: An object of class Collection populated with data.
def read(cls, data): if isinstance(data, OrderedDict): return cls(data) elif isinstance(data, basestring)\ and data.startswith(("http://", "https://", "ftp://", "ftps://")): return cls(request(data)) elif isinstance(data, basestring): try: json_dict = json.loads(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise else: try: json_dict = json.load(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise
979,599
Writes data from a Collection object to JSONstat or list of \ Pandas Dataframes. Args: output(string): can accept 'jsonstat' or 'dataframe_list' Returns: Serialized JSONstat or a list of Pandas Dataframes,depending on \ the 'output' parameter.
def write(self, output='jsonstat'): if output == 'jsonstat': return json.dumps(self) elif output == 'dataframe_list': df_list = [] unnest_collection(self, df_list) return df_list else: raise ValueError( "Allowed arguments are 'jsonstat' or 'dataframe_list'")
979,600
Gets ith element of a collection in an object of the corresponding \ class. Args: output(string): can accept 'jsonstat' or 'dataframe_list' Returns: Serialized JSONstat or a list of Pandas Dataframes,depending on \ the 'output' parameter.
def get(self, element): if self['link']['item'][element]['class'] == 'dataset': return Dataset.read(self['link']['item'][element]['href']) elif self['link']['item'][element]['class'] == 'collection': return Collection.read(self['link']['item'][element]['href']) elif self['link']['item'][element]['class'] == 'dimension': return Dimension.read(self['link']['item'][element]['href']) else: raise ValueError( "Class not allowed. Please use dataset, collection or " "dimension'")
979,601
Make a (deep) copy of self. Parameters: deep : bool Make a deep copy. name : str Name of the copy, with default self.name + '_copy'.
def copy(self, deep=False, name=None): if deep: other = deepcopy(self) else: other = copy(self) if hasattr(self, 'name'): other.name = get_default(name, self.name + '_copy') return other
981,109
Parses Crianza source code and returns a native Python function. Args: args: The resulting function's number of input parameters. Returns: A callable Python function.
def xcompile(source_code, args=0, optimize=True): code = crianza.compile(crianza.parse(source_code), optimize=optimize) return crianza.native.compile(code, args=args)
981,961
Compiles to native Python bytecode and runs program, returning the topmost value on the stack. Args: optimize: Whether to optimize the code after parsing it. Returns: None: If the stack is empty obj: If the stack contains a single value [obj, obj, ...]: If the stack contains many values
def xeval(source, optimize=True): native = xcompile(source, optimize=optimize) return native()
981,962
Constant-folds simple expressions like 2 3 + to 5. Args: code: Code in non-native types. silent: Flag that controls whether to print optimizations made. ignore_errors: Whether to raise exceptions on found errors.
def constant_fold(code, silent=True, ignore_errors=True): # Loop until we haven't done any optimizations. E.g., "2 3 + 5 *" will be # optimized to "5 5 *" and in the next iteration to 25. Yes, this is # extremely slow, big-O wise. We'll fix that some other time. (TODO) arithmetic = list(map(instructions.lookup, [ instructions.add, instructions.bitwise_and, instructions.bitwise_or, instructions.bitwise_xor, instructions.div, instructions.equal, instructions.greater, instructions.less, instructions.mod, instructions.mul, instructions.sub, ])) divzero = map(instructions.lookup, [ instructions.div, instructions.mod, ]) lookup = instructions.lookup def isfunction(op): try: instructions.lookup(op) return True except KeyError: return False def isconstant(op): return op is None or interpreter.isconstant(op, quoted=True) or not isfunction(op) keep_running = True while keep_running: keep_running = False # Find two consecutive numbes and an arithmetic operator for i, a in enumerate(code): b = code[i+1] if i+1 < len(code) else None c = code[i+2] if i+2 < len(code) else None # Constant fold arithmetic operations (TODO: Move to check-func) if interpreter.isnumber(a, b) and c in arithmetic: # Although we can detect division by zero at compile time, we # don't report it here, because the surrounding system doesn't # handle that very well. So just leave it for now. (NOTE: If # we had an "error" instruction, we could actually transform # the expression to an error, or exit instruction perhaps) if b==0 and c in divzero: if ignore_errors: continue else: raise errors.CompileError(ZeroDivisionError( "Division by zero")) # Calculate result by running on a machine (lambda vm: ... is # embedded pushes, see compiler) result = interpreter.Machine([lambda vm: vm.push(a), lambda vm: vm.push(b), instructions.lookup(c)]).run().top del code[i:i+3] code.insert(i, result) if not silent: print("Optimizer: Constant-folded %s %s %s to %s" % (a,b,c,result)) keep_running = True break # Translate <constant> dup to <constant> <constant> if isconstant(a) and b == lookup(instructions.dup): code[i+1] = a if not silent: print("Optimizer: Translated %s %s to %s %s" % (a,b,a,a)) keep_running = True break # Dead code removal: <constant> drop if isconstant(a) and b == lookup(instructions.drop): del code[i:i+2] if not silent: print("Optimizer: Removed dead code %s %s" % (a,b)) keep_running = True break if a == lookup(instructions.nop): del code[i] if not silent: print("Optimizer: Removed dead code %s" % a) keep_running = True break # Dead code removal: <integer> cast_int if isinstance(a, int) and b == lookup(instructions.cast_int): del code[i+1] if not silent: print("Optimizer: Translated %s %s to %s" % (a,b,a)) keep_running = True break # Dead code removal: <float> cast_float if isinstance(a, float) and b == lookup(instructions.cast_float): del code[i+1] if not silent: print("Optimizer: Translated %s %s to %s" % (a,b,a)) keep_running = True break # Dead code removal: <string> cast_str if isinstance(a, str) and b == lookup(instructions.cast_str): del code[i+1] if not silent: print("Optimizer: Translated %s %s to %s" % (a,b,a)) keep_running = True break # Dead code removal: <boolean> cast_bool if isinstance(a, bool) and b == lookup(instructions.cast_bool): del code[i+1] if not silent: print("Optimizer: Translated %s %s to %s" % (a,b,a)) keep_running = True break # <c1> <c2> swap -> <c2> <c1> if isconstant(a) and isconstant(b) and c == lookup(instructions.swap): del code[i:i+3] code = code[:i] + [b, a] + code[i:] if not silent: print("Optimizer: Translated %s %s %s to %s %s" % (a,b,c,b,a)) keep_running = True break # a b over -> a b a if isconstant(a) and isconstant(b) and c == lookup(instructions.over): code[i+2] = a if not silent: print("Optimizer: Translated %s %s %s to %s %s %s" % (a,b,c,a,b,a)) keep_running = True break # "123" cast_int -> 123 if interpreter.isstring(a) and b == lookup(instructions.cast_int): try: number = int(a) del code[i:i+2] code.insert(i, number) if not silent: print("Optimizer: Translated %s %s to %s" % (a, b, number)) keep_running = True break except ValueError: pass if isconstant(a) and b == lookup(instructions.cast_str): del code[i:i+2] code.insert(i, str(a)) # TODO: Try-except here if not silent: print("Optimizer: Translated %s %s to %s" % (a, b, str(a))) keep_running = True break if isconstant(a) and b == lookup(instructions.cast_bool): del code[i:i+2] code.insert(i, bool(a)) # TODO: Try-except here if not silent: print("Optimizer: Translated %s %s to %s" % (a, b, bool(a))) keep_running = True break if isconstant(a) and b == lookup(instructions.cast_float): try: v = float(a) del code[i:i+2] code.insert(i, v) if not silent: print("Optimizer: Translated %s %s to %s" % (a, b, v)) keep_running = True break except ValueError: pass return code
982,550
Parses source code returns an array of instructions suitable for optimization and execution by a Machine. Args: source: A string or stream containing source code.
def parse(source): if isinstance(source, str): return parse_stream(six.StringIO(source)) else: return parse_stream(source)
982,641
Compiles and runs program, returning the machine used to execute the code. Args: optimize: Whether to optimize the code after parsing it. output: Stream which program can write output to. input: Stream which program can read input from. steps: An optional maximum number of instructions to execute on the virtual machine. Set to -1 for no limit. Returns: A Machine instance.
def execute(source, optimize=True, output=sys.stdout, input=sys.stdin, steps=-1): from crianza import compiler code = compiler.compile(parser.parse(source), optimize=optimize) machine = Machine(code, output=output, input=input) return machine.run(steps)
982,720
Run threaded code in machine. Args: steps: If specified, run that many number of instructions before stopping.
def run(self, steps=None): try: while self.instruction_pointer < len(self.code): self.step() if steps is not None: steps -= 1 if steps == 0: break except StopIteration: pass except EOFError: pass return self
982,727
Upload a file to a server Attempts to upload a local file with path filepath, to the server, where it will be named filename. Args: :param file_name: The name that the uploaded file will be called on the server. :param file_path: The path of the local file to upload. Returns: :return: A GPFile object that wraps the URI of the uploaded file, or None if the upload fails.
def upload_file(self, file_name, file_path): request = urllib.request.Request(self.url + '/rest/v1/data/upload/job_input?name=' + file_name) if self.authorization_header() is not None: request.add_header('Authorization', self.authorization_header()) request.add_header('User-Agent', 'GenePatternRest') with open(file_path, 'rb') as f: data = f.read() try: response = urllib.request.urlopen(request, data) except IOError: print("authentication failed") return None if response.getcode() != 201: print("file upload failed, status code = %i" % response.getcode()) return None return GPFile(self, response.info().get('Location'))
982,815
Starts a simple REPL for this machine. Args: optimize: Controls whether to run inputted code through the optimizer. persist: If True, the machine is not deleted after each line.
def repl(optimize=True, persist=True): print("Extra commands for the REPL:") print(".code - print code") print(".raw - print raw code") print(".quit - exit immediately") print(".reset - reset machine (IP and stacks)") print(".restart - create a clean, new machine") print(".clear - same as .restart") print(".stack - print data stack") print("") machine = Machine([]) def match(s, *args): return any(map(lambda arg: s.strip()==arg, args)) while True: try: source = raw_input("> ").strip() if source[0] == "." and len(source) > 1: if match(source, ".quit"): return elif match(source, ".code"): print_code(machine) elif match(source, ".raw"): print(machine.code) elif match(source, ".reset"): machine.reset() elif match(source, ".restart", ".clear"): machine = Machine([]) elif match(source, ".stack"): print(machine.stack) else: raise ParseError("Unknown command: %s" % source) continue code = compile(parse(source), silent=False, optimize=optimize) if not persist: machine.reset() machine.code += code machine.run() except EOFError: return except KeyboardInterrupt: return except ParseError as e: print("Parse error: %s" % e) except MachineError as e: print("Machine error: %s" % e) except CompileError as e: print("Compile error: %s" % e)
982,860
Construct an iterator. Args: timeseries: the timeseries to iterate over loop: The asyncio loop to use for iterating
def __init__(self, timeseries, loop=None): self.timeseries = timeseries self.queue = deque() self.continuation_url = timeseries._base_url
984,405
Get a URL. Args: callback(func): The response callback function Keyword Args: params(dict): Parameters for the request json(dict): JSON body for the request headers(dict): Additional headers for the request Returns: The result of the callback handling the resopnse from the executed request
def get(self, url, callback, params=None, json=None, headers=None): return self.adapter.get(url, callback, params=params, json=json, headers=headers)
984,540
Put to a URL. Args: url(string): URL for the request callback(func): The response callback function Keyword Args: params(dict): Parameters for the request json(dict): JSON body for the request headers(dict): HTTP headers for the request Returns: The result of the callback handling the resopnse from the executed request
def put(self, url, callback, params=None, json=None, headers=None): return self.adapter.put(url, callback, params=params, json=json)
984,541
Patch a URL. Args: url(string): URL for the request callback(func): The response callback function headers(dict): HTTP headers for the request Keyword Args: params(dict): Parameters for the request json(dict): JSON body for the request Returns: The result of the callback handling the resopnse from the executed request
def patch(self, url, callback, params=None, json=None, headers=None): return self.adapter.patch(url, callback, params=params, json=json, headers=headers)
984,542
Delete a URL. Args: url(string): URL for the request callback(func): The response callback function Keyword Args: json(dict): JSON body for the request Returns: The result of the callback handling the resopnse from the executed request
def delete(self, url, callback, json=None): return self.adapter.delete(url, callback, json=json)
984,543
Build a relationship list. A relationship list is used to update relationships between two resources. Setting sensors on a label, for example, uses this function to construct the list of sensor ids to pass to the Helium API. Args: type(string): The resource type for the ids in the relationship ids([uuid] or uuid): Just one or a list of resource uuids to use in the relationship Returns: A ready to use relationship JSON object.
def build_request_relationship(type, ids): if ids is None: return { 'data': None } elif isinstance(ids, str): return { 'data': {'id': ids, 'type': type} } else: return { "data": [{"id": id, "type": type} for id in ids] }
985,203
Create a basic json based object. Arguments: json(dict): A json dictionary to base attributes on
def __init__(self, json): super(Base, self).__init__() self._json_data = json self._update_attributes(json)
985,205
Create a Resource. Args: json(dict): The json to construct the resource from. session(Session): The session use for this resource Keyword Args: include([Resource class]): Resource classes that are included included([json]): A list of all included json resources
def __init__(self, json, session, include=None, included=None): self._session = session self._include = include self._included = included super(Resource, self).__init__(json)
985,207
Retrieve a single resource. This should only be called from sub-classes. Args: session(Session): The session to find the resource in resource_id: The ``id`` for the resource to look up Keyword Args: include: Resource classes to include Returns: Resource: An instance of a resource, or throws a :class:`NotFoundError` if the resource can not be found.
def find(cls, session, resource_id, include=None): url = session._build_url(cls._resource_path(), resource_id) params = build_request_include(include, None) process = cls._mk_one(session, include=include) return session.get(url, CB.json(200, process), params=params)
985,211
Create a resource of the resource. This should only be called from sub-classes Args: session(Session): The session to create the resource in. attributes(dict): Any attributes that are valid for the given resource type. relationships(dict): Any relationships that are valid for the given resource type. Returns: Resource: An instance of a resource.
def create(cls, session, attributes=None, relationships=None): resource_type = cls._resource_type() resource_path = cls._resource_path() url = session._build_url(resource_path) json = build_request_body(resource_type, None, attributes=attributes, relationships=relationships) process = cls._mk_one(session) return session.post(url, CB.json(201, process), json=json)
985,213
VCS init method. Args: callback: Callback function that will be called for each action. Returns: VCS Object Raises: None
def __init__(self, callback): self._callback = callback self._vcs = brocade_vcs( callback=pynos.utilities.return_xml )
986,129
BGP object init. Args: callback: Callback function that will be called for each action. Returns: BGP Object Raises: None
def __init__(self, callback): self._callback = callback self._rbridge = brocade_rbridge(callback=pynos.utilities.return_xml)
986,210
Add SNMP Community to NOS device. Args: community (str): Community string to be added to device. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `community` is not defined.
def add_snmp_community(self, **kwargs): community = kwargs.pop('community') callback = kwargs.pop('callback', self._callback) config = ET.Element('config') snmp_server = ET.SubElement(config, 'snmp-server', xmlns=("urn:brocade.com:mgmt:" "brocade-snmp")) community_el = ET.SubElement(snmp_server, 'community') community_name = ET.SubElement(community_el, 'community') community_name.text = community return callback(config)
986,293
VCS init function Args: callback: Callback function that will be called for each action Returns: VCS Object Raises: None
def __init__(self, callback): self._callback = callback self._brocade_tunnels = brocade_tunnels(callback=pynos.utilities.return_xml)
986,347
Set gateway type Args: name (str): gateway-name type (str): gateway-type callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def hwvtep_set_overlaygw_type(self, **kwargs): name = kwargs.pop('name') type = kwargs.pop('type') ip_args = dict(name=name, gw_type=type) method_name = 'overlay_gateway_gw_type' method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) config = gw_attr(**ip_args) output = self._callback(config) return output
986,348
Add a range of rbridge-ids Args: name (str): gateway-name vlan (str): rbridge-ids range callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def hwvtep_add_rbridgeid(self, **kwargs): name = kwargs.pop('name') id = kwargs.pop('rb_range') ip_args = dict(name=name, rb_add=id) method_name = 'overlay_gateway_attach_rbridge_id_rb_add' method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) config = gw_attr(**ip_args) output = self._callback(config) return output
986,349
Add loopback interface to the overlay-gateway Args: name (str): gateway-name int_id (int): loopback inteface id callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def hwvtep_add_loopback_interface(self, **kwargs): name = kwargs.pop('name') id = kwargs.pop('int_id') ip_args = dict(name=name, loopback_id=id) method_name = 'overlay_gateway_ip_interface_loopback_loopback_id' method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) config = gw_attr(**ip_args) output = self._callback(config) return output
986,350
Add virtual ethernet (ve) interface to the overlay-gateway Args: name (str): gateway-name int_id (int): ve id vrrp_id (int): VRPP-E group ID callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def hwvtep_add_ve_interface(self, **kwargs): name = kwargs.pop('name') ve_id = kwargs.pop('ve_id') vrrp_id = kwargs.pop('vrrp_id') ve_args = dict(name=name, ve_id=ve_id) method_name = 'overlay_gateway_ip_interface_ve_ve_id' method_class = self._brocade_tunnels ve_attr = getattr(method_class, method_name) config = ve_attr(**ve_args) output = self._callback(config) method_name = 'overlay_gateway_ip_interface_ve_vrrp_extended_group' vrrp_attr = getattr(method_class, method_name) vrrp_args = dict(name=name, vrrp_extended_group=vrrp_id) config = vrrp_attr(**vrrp_args) output = self._callback(config) return output
986,351
Activate the hwvtep Args: name (str): overlay_gateway name callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def hwvtep_activate_hwvtep(self, **kwargs): name = kwargs.pop('name') name_args = dict(name=name) method_name = 'overlay_gateway_activate' method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) config = gw_attr(**name_args) output = self._callback(config) return output
986,352
Identifies exported VLANs in VXLAN gateway configurations. Args: name (str): overlay_gateway name vlan(str): vlan_id range callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def hwvtep_attach_vlan_vid(self, **kwargs): name = kwargs.pop('name') mac = kwargs.pop('mac') vlan = kwargs.pop('vlan') name_args = dict(name=name, vid=vlan, mac=mac) method_name = 'overlay_gateway_attach_vlan_mac' method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) config = gw_attr(**name_args) output = self._callback(config) return output
986,353
Get overlay-gateway name on the switch Args: callback (function): A function executed upon completion of the method. Returns: Dictionary containing details of VXLAN Overlay Gateway. Raises: None
def get_overlay_gateway(self): urn = "urn:brocade.com:mgmt:brocade-tunnels" config = ET.Element("config") ET.SubElement(config, "overlay-gateway", xmlns=urn) output = self._callback(config, handler='get_config') result = {} element = ET.fromstring(str(output)) for overlayGw in element.iter('{%s}overlay-gateway' % urn): result['name'] = overlayGw.find('{%s}name' % urn).text isactivate = overlayGw.find('{%s}activate' % urn) if isactivate is None: result['activate'] = False else: result['activate'] = True gwtype = overlayGw.find('{%s}gw-type' % urn) if gwtype is None: result['gwtype'] = None else: result['gwtype'] = gwtype.text attach = overlayGw.find('{%s}attach' % urn) if attach is not None: rbridgeId = attach.find('{%s}rbridge-id' % urn) if rbridgeId is None: result['attached-rbridgeId'] = None else: result['attached-rbridgeId'] = rbridgeId.find('{%s}rb-add' % urn).text result['attached-vlan'] = None vlans = [] for vlan in attach.iter('{%s}vlan'%urn): vlans.append(vlan.find('{%s}vid' % urn).text) result['attached-vlan'] = vlans return result
986,354
Return the `ip unnumbered` donor name XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True``. ip_donor_interface_name (str): The donor interface name (1, 2, etc) Returns: XML to be passed to the switch. Raises: None
def _ip_unnumbered_name(self, **kwargs): method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\ 'interface_name' % kwargs['int_type'] ip_unnumbered_name = getattr(self._interface, method_name) config = ip_unnumbered_name(**kwargs) if kwargs['delete']: tag = 'ip-donor-interface-name' config.find('.//*%s' % tag).set('operation', 'delete') return config
986,447
Return the `ip unnumbered` donor type XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True``. ip_donor_interface_type (str): The donor interface type (loopback) Returns: XML to be passed to the switch. Raises: None
def _ip_unnumbered_type(self, **kwargs): method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\ 'interface_type' % kwargs['int_type'] ip_unnumbered_type = getattr(self._interface, method_name) config = ip_unnumbered_type(**kwargs) if kwargs['delete']: tag = 'ip-donor-interface-type' config.find('.//*%s' % tag).set('operation', 'delete') return config
986,448
Get and merge the `ip unnumbered` config from an interface. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: unnumbered_type: XML document with the XML to get the donor type. unnumbered_name: XML document with the XML to get the donor name. Returns: Merged XML document. Raises: None
def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name): unnumbered_type = self._callback(unnumbered_type, handler='get_config') unnumbered_name = self._callback(unnumbered_name, handler='get_config') unnumbered_type = pynos.utilities.return_xml(str(unnumbered_type)) unnumbered_name = pynos.utilities.return_xml(str(unnumbered_name)) return pynos.utilities.merge_xml(unnumbered_type, unnumbered_name)
986,449
Return the BFD minimum transmit interval XML. You should not use this method. You probably want `BGP.bfd`. Args: min_tx (str): BFD transmit interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None
def _bfd_tx(self, **kwargs): int_type = kwargs['int_type'] method_name = 'interface_%s_bfd_interval_min_tx' % int_type bfd_tx = getattr(self._interface, method_name) config = bfd_tx(**kwargs) if kwargs['delete']: tag = 'min-tx' config.find('.//*%s' % tag).set('operation', 'delete') return config
986,452
Return the BFD minimum receive interval XML. You should not use this method. You probably want `BGP.bfd`. Args: min_rx (str): BFD receive interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None
def _bfd_rx(self, **kwargs): int_type = kwargs['int_type'] method_name = 'interface_%s_bfd_interval_min_rx' % int_type bfd_rx = getattr(self._interface, method_name) config = bfd_rx(**kwargs) if kwargs['delete']: tag = 'min-rx' config.find('.//*%s' % tag).set('operation', 'delete') pass return config
986,453
Return the BFD multiplier XML. You should not use this method. You probably want `BGP.bfd`. Args: min_tx (str): BFD transmit interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None
def _bfd_multiplier(self, **kwargs): int_type = kwargs['int_type'] method_name = 'interface_%s_bfd_interval_multiplier' % int_type bfd_multiplier = getattr(self._interface, method_name) config = bfd_multiplier(**kwargs) if kwargs['delete']: tag = 'multiplier' config.find('.//*%s' % tag).set('operation', 'delete') return config
986,454
Get/Set nsx controller name Args: name: (str) : Name of the nsx controller get (bool) : Get nsx controller config(True,False) callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def nsx_controller_name(self, **kwargs): name = kwargs.pop('name') name_args = dict(name=name) method_name = 'nsx_controller_name' method_class = self._brocade_tunnels nsxcontroller_attr = getattr(method_class, method_name) config = nsxcontroller_attr(**name_args) if kwargs.pop('get', False): output = self._callback(config, handler='get_config') else: output = self._callback(config) return output
986,606
Set nsx-controller IP Args: IP (str): IPV4 address. callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def set_nsxcontroller_ip(self, **kwargs): name = kwargs.pop('name') ip_addr = str((kwargs.pop('ip_addr', None))) nsxipaddress = ip_interface(unicode(ip_addr)) if nsxipaddress.version != 4: raise ValueError('NSX Controller ip must be IPV4') ip_args = dict(name=name, address=ip_addr) method_name = 'nsx_controller_connection_addr_address' method_class = self._brocade_tunnels nsxcontroller_attr = getattr(method_class, method_name) config = nsxcontroller_attr(**ip_args) output = self._callback(config) return output
986,607
Activate NSX Controller Args: name (str): nsxcontroller name callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def activate_nsxcontroller(self, **kwargs): name = kwargs.pop('name') name_args = dict(name=name) method_name = 'nsx_controller_activate' method_class = self._brocade_tunnels nsxcontroller_attr = getattr(method_class, method_name) config = nsxcontroller_attr(**name_args) output = self._callback(config) return output
986,608
Set Nsx Controller pot on the switch Args: port (int): 1 to 65535. callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def set_nsxcontroller_port(self, **kwargs): name = kwargs.pop('name') port = str(kwargs.pop('port')) port_args = dict(name=name, port=port) method_name = 'nsx_controller_connection_addr_port' method_class = self._brocade_tunnels nsxcontroller_attr = getattr(method_class, method_name) config = nsxcontroller_attr(**port_args) output = self._callback(config) return output
986,609
Get/Set nsx controller name Args: name: (str) : Name of the nsx-controller callback (function): A function executed upon completion of the method. Returns: Return dictionary containing nsx-controller information. Returns blank dict if no nsx-controller is configured. Raises: None
def get_nsx_controller(self): urn = "urn:brocade.com:mgmt:brocade-tunnels" config = ET.Element("config") ET.SubElement(config, "nsx-controller", xmlns=urn) output = self._callback(config, handler='get_config') result = {} element = ET.fromstring(str(output)) for controller in element.iter('{%s}nsx-controller'%urn): result['name'] = controller.find('{%s}name'%urn).text isactivate = controller.find('{%s}activate'%urn) if isactivate is None: result['activate'] = False else: result['activate'] = True connection = controller.find('{%s}connection-addr'%urn) if connection is None: result['port'] = None result['address'] = None else: result['port'] = connection.find('{%s}port'%urn).text address = connection.find('{%s}address'%urn) if address is None: result['address'] = None else: result['address'] = address.text return result
986,610
LLDP init method. Args: callback (function): Callback function that will be called for each action. Returns: LLDP Object Raises: None
def __init__(self, callback): super(LLDP, self).__init__(callback) self._lldp = brcd_lldp(callback=pynos.utilities.return_xml)
986,841
Interface init function. Args: callback: Callback function that will be called for each action. Returns: Interface Object Raises: None
def __init__(self, callback): self._callback = callback self._interface = brocade_interface( callback=pynos.utilities.return_xml ) self._rbridge = brocade_rbridge( callback=pynos.utilities.return_xml ) self._mac_address_table = brocade_mac_address_table( callback=pynos.utilities.return_xml ) self._tunnels = brocade_tunnels( callback=pynos.utilities.return_xml )
986,885
Add VLAN Interface. VLAN interfaces are required for VLANs even when not wanting to use the interface for any L3 features. Args: vlan_id: ID for the VLAN interface being created. Value of 2-4096. Returns: True if command completes successfully or False if not. Raises: None
def add_vlan_int(self, vlan_id): config = ET.Element('config') vlinterface = ET.SubElement(config, 'interface-vlan', xmlns=("urn:brocade.com:mgmt:" "brocade-interface")) interface = ET.SubElement(vlinterface, 'interface') vlan = ET.SubElement(interface, 'vlan') name = ET.SubElement(vlan, 'name') name.text = vlan_id try: self._callback(config) return True # TODO add logging and narrow exception window. except Exception as error: logging.error(error) return False
986,886
Change an interface's operation to L3. Args: inter_type: The type of interface you want to configure. Ex. tengigabitethernet, gigabitethernet, fortygigabitethernet. inter: The ID for the interface you want to configure. Ex. 1/0/1 Returns: True if command completes successfully or False if not. Raises: None
def disable_switchport(self, inter_type, inter): config = ET.Element('config') interface = ET.SubElement(config, 'interface', xmlns=("urn:brocade.com:mgmt:" "brocade-interface")) int_type = ET.SubElement(interface, inter_type) name = ET.SubElement(int_type, 'name') name.text = inter ET.SubElement(int_type, 'switchport-basic', operation='delete') try: self._callback(config) return True # TODO add logging and narrow exception window. except Exception as error: logging.error(error) return False
986,887
Add a L2 Interface to a specific VLAN. Args: inter_type: The type of interface you want to configure. Ex. tengigabitethernet, gigabitethernet, fortygigabitethernet. inter: The ID for the interface you want to configure. Ex. 1/0/1 vlan_id: ID for the VLAN interface being modified. Value of 2-4096. Returns: True if command completes successfully or False if not. Raises: None
def access_vlan(self, inter_type, inter, vlan_id): config = ET.Element('config') interface = ET.SubElement(config, 'interface', xmlns=("urn:brocade.com:mgmt:" "brocade-interface")) int_type = ET.SubElement(interface, inter_type) name = ET.SubElement(int_type, 'name') name.text = inter switchport = ET.SubElement(int_type, 'switchport') access = ET.SubElement(switchport, 'access') accessvlan = ET.SubElement(access, 'accessvlan') accessvlan.text = vlan_id try: self._callback(config) return True # TODO add logging and narrow exception window. except Exception as error: logging.error(error) return False
986,888
Set IP address of a L3 interface. Args: inter_type: The type of interface you want to configure. Ex. tengigabitethernet, gigabitethernet, fortygigabitethernet. inter: The ID for the interface you want to configure. Ex. 1/0/1 ip_addr: IP Address in <prefix>/<bits> format. Ex: 10.10.10.1/24 Returns: True if command completes successfully or False if not. Raises: None
def set_ip(self, inter_type, inter, ip_addr): config = ET.Element('config') interface = ET.SubElement(config, 'interface', xmlns=("urn:brocade.com:mgmt:" "brocade-interface")) intert = ET.SubElement(interface, inter_type) name = ET.SubElement(intert, 'name') name.text = inter ipel = ET.SubElement(intert, 'ip') ip_config = ET.SubElement( ipel, 'ip-config', xmlns="urn:brocade.com:mgmt:brocade-ip-config" ) address = ET.SubElement(ip_config, 'address') ipaddr = ET.SubElement(address, 'address') ipaddr.text = ip_addr try: self._callback(config) return True # TODO add logging and narrow exception window. except Exception as error: logging.error(error) return False
986,889
Returns firmware version. Args: None Returns: Dictionary Raises: None
def firmware_version(self): namespace = "urn:brocade.com:mgmt:brocade-firmware-ext" request_ver = ET.Element("show-firmware-version", xmlns=namespace) ver = self._callback(request_ver, handler='get') return ver.find('.//*{%s}os-version' % namespace).text
987,133
Reconnect session with device. Args: None Returns: bool: True if reconnect succeeds, False if not. Raises: None
def reconnect(self): if self._auth_method is "userpass": self._mgr = manager.connect(host=self._conn[0], port=self._conn[1], username=self._auth[0], password=self._auth[1], hostkey_verify=self._hostkey_verify) elif self._auth_method is "key": self._mgr = manager.connect(host=self._conn[0], port=self._conn[1], username=self._auth[0], key_filename=self._auth_key, hostkey_verify=self._hostkey_verify) else: raise ValueError("auth_method incorrect value.") self._mgr.timeout = 600 return True
987,135
Return the BFD minimum receive interval XML. You should not use this method. You probably want `BGP.bfd`. Args: min_rx (str): BFD receive interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None
def _bfd_rx(self, **kwargs): method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \ 'bfd_interval_min_rx' bfd_rx = getattr(self._rbridge, method_name) config = bfd_rx(**kwargs) if kwargs['delete']: tag = 'min-rx' config.find('.//*%s' % tag).set('operation', 'delete') pass return config
987,166
Return the BFD multiplier XML. You should not use this method. You probably want `BGP.bfd`. Args: min_tx (str): BFD transmit interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None
def _bfd_multiplier(self, **kwargs): method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \ 'bfd_interval_multiplier' bfd_multiplier = getattr(self._rbridge, method_name) config = bfd_multiplier(**kwargs) if kwargs['delete']: tag = 'multiplier' config.find('.//*%s' % tag).set('operation', 'delete') return config
987,167
Return the BFD minimum transmit interval XML. You should not use this method. You probably want `BGP.bfd`. Args: peer_ip (str): Peer IPv4 address for BFD setting. min_tx (str): BFD transmit interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None
def _peer_bfd_tx(self, **kwargs): method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \ 'neighbor_neighbor_ips_neighbor_addr_bfd_interval_min_tx' bfd_tx = getattr(self._rbridge, method_name) config = bfd_tx(**kwargs) if kwargs['delete']: tag = 'min-tx' config.find('.//*%s' % tag).set('operation', 'delete') return config
987,171
Get and merge the `bfd` config from global BGP. You should not use this method. You probably want `BGP.bfd`. Args: tx: XML document with the XML to get the transmit interval. rx: XML document with the XML to get the receive interval. multiplier: XML document with the XML to get the interval multiplier. Returns: Merged XML document. Raises: None
def _peer_get_bfd(self, tx, rx, multiplier): tx = self._callback(tx, handler='get_config') rx = self._callback(rx, handler='get_config') multiplier = self._callback(multiplier, handler='get_config') tx = pynos.utilities.return_xml(str(tx)) rx = pynos.utilities.return_xml(str(rx)) multiplier = pynos.utilities.return_xml(str(multiplier)) config = pynos.utilities.merge_xml(tx, rx) return pynos.utilities.merge_xml(config, multiplier)
987,172
RAS init method. Args: callback: Callback function that will be called for each action. Returns: RAS Object Raises: None
def __init__(self, callback): self._callback = callback self._ras = brocade_ras(callback=pynos.utilities.return_xml)
987,230
Interface init function. Args: callback: Callback function that will be called for each action. Returns: Interface Object Raises: None
def __init__(self, callback): super(Interface, self).__init__(callback) self._mac_address_table = brocade_mac_address_table( callback=pynos.utilities.return_xml )
987,552
Vcenter init function Args: callback: Callback function that will be called for each action Returns: Vcenter Object Raises: None
def __init__(self, callback): self._callback = callback self._brocade_vswitch = brocade_vswitch(callback=pynos.utilities.return_xml)
987,619
Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def add_vcenter(self, **kwargs): config = ET.Element("config") vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch") id = ET.SubElement(vcenter, "id") id.text = kwargs.pop('id') credentials = ET.SubElement(vcenter, "credentials") url = ET.SubElement(credentials, "url") url.text = kwargs.pop('url') username = ET.SubElement(credentials, "username") username.text = kwargs.pop('username') password = ET.SubElement(credentials, "password") password.text = kwargs.pop('password') try: self._callback(config) return True except Exception as error: logging.error(error) return False
987,620
Activate vCenter on the switch Args: name: (str) : Name of an established vCenter activate (bool) : Activates the vCenter if activate=True else deactivates it callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
def activate_vcenter(self, **kwargs): name = kwargs.pop('name') activate = kwargs.pop('activate', True) vcenter_args = dict(id=name) method_class = self._brocade_vswitch if activate: method_name = 'vcenter_activate' vcenter_attr = getattr(method_class, method_name) config = vcenter_attr(**vcenter_args) output = self._callback(config) print output return output else: pass
987,621
Get vCenter hosts on the switch Args: callback (function): A function executed upon completion of the method. Returns: Returns a list of vcenters Raises: None
def get_vcenter(self, **kwargs): config = ET.Element("config") urn = "urn:brocade.com:mgmt:brocade-vswitch" ET.SubElement(config, "vcenter", xmlns=urn) output = self._callback(config, handler='get_config') result = [] element = ET.fromstring(str(output)) for vcenter in element.iter('{%s}vcenter'%urn): vc = {} vc['name'] = vcenter.find('{%s}id' % urn).text vc['url'] = (vcenter.find('{%s}credentials' % urn)).find('{%s}url' % urn).text isactive = vcenter.find('{%s}activate' %urn) if isactive is None: vc['isactive'] = False else: vc['isactive'] = True result.append(vc) return result
987,622