INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Reads the temple YAML configuration file in the repository
def read_temple_config(): """Reads the temple YAML configuration file in the repository""" with open(temple.constants.TEMPLE_CONFIG_FILE) as temple_config_file: return yaml.load(temple_config_file, Loader=yaml.SafeLoader)
Writes the temple YAML configuration
def write_temple_config(temple_config, template, version): """Writes the temple YAML configuration""" with open(temple.constants.TEMPLE_CONFIG_FILE, 'w') as temple_config_file: versioned_config = { **temple_config, **{'_version': version, '_template': template}, } ...
Obtains the configuration used for cookiecutter templating
def get_cookiecutter_config(template, default_config=None, version=None): """Obtains the configuration used for cookiecutter templating Args: template: Path to the template default_config (dict, optional): The default configuration version (str, optional): The git SHA or branch to use w...
Decorator that sets the temple command env var to value
def set_cmd_env_var(value): """Decorator that sets the temple command env var to value""" def func_decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): previous_cmd_env_var = os.getenv(temple.constants.TEMPLE_ENV_VAR) os.environ[temple.constants.T...
Perform a github API call
def _call_api(self, verb, url, **request_kwargs): """Perform a github API call Args: verb (str): Can be "post", "put", or "get" url (str): The base URL with a leading slash for Github API (v3) auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object ...
Deploys the package and documentation.
def deploy(target): """Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to...
Decorator for method run. This method will be execute before the execution from the method with this decorator.
def report(func): """ Decorator for method run. This method will be execute before the execution from the method with this decorator. """ def execute(self, *args, **kwargs): try: print "[>] Executing {n} report. . . ".format(n=self.__class__.NAME) if hasattr(self, 'test'): if self.test(): return f...
Finds. DS_Store files into path
def run(self): """ Finds .DS_Store files into path """ filename = ".DS_Store" command = "find {path} -type f -name \"{filename}\" ".format(path = self.path, filename = filename) cmd = CommandHelper(command) cmd.execute() files = cmd.output.split("\n") for f in files: if not f.endswith(filename): ...
Method executed dynamically by framework. This method will do a http request to endpoint setted into config file with the issues and other data.
def run(self): """ Method executed dynamically by framework. This method will do a http request to endpoint setted into config file with the issues and other data. """ options = {} if bool(self.config['use_proxy']): options['proxies'] = {"http": self.config['proxy'], "https": self.config['proxy']} opt...
Setter for path property
def path(self, value): """ Setter for 'path' property Args: value (str): Absolute path to scan """ if not value.endswith('/'): self._path = '{v}/'.format(v=value) else: self._path = value
Parse the config values
def parseConfig(cls, value): """ Parse the config values Args: value (dict): Dictionary which contains the checker config Returns: dict: The checker config with parsed values """ if 'enabled' in value: value['enabled'] = bool(value['enabled']) if 'exclude_paths' in value: value['exclude_pat...
Check if a software is installed into machine.
def isInstalled(value): """ Check if a software is installed into machine. Args: value (str): Software's name Returns: bool: True if the software is installed. False else """ function = """ function is_installed { local return_=1; type $1 >/dev/null 2>&1 || { local return_=0; }; echo ...
Get the OS name. If OS is linux returns the Linux distribution name
def getOSName(self): """ Get the OS name. If OS is linux, returns the Linux distribution name Returns: str: OS name """ _system = platform.system() if _system in [self.__class__.OS_WINDOWS, self.__class__.OS_MAC, self.__class__.OS_LINUX]: if _system == self.__class__.OS_LINUX: _dist = platform.li...
Executes the command setted into class
def execute(self, shell = True): """ Executes the command setted into class Args: shell (boolean): Set True if command is a shell command. Default: True """ process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell) self.output, self.errors = process.communicate()
Print a message if the class attribute verbose is enabled
def _debug(message, color=None, attrs=None): """ Print a message if the class attribute 'verbose' is enabled Args: message (str): Message to print """ if attrs is None: attrs = [] if color is not None: print colored(message, color, attrs=attrs) else: if len(attrs) > 0: print colored(messa...
Creates required directories and copy checkers and reports.
def setup(): """ Creates required directories and copy checkers and reports. """ # # Check if dir is writable # if not os.access(AtomShieldsScanner.HOME, os.W_OK): # AtomShieldsScanner.HOME = os.path.expanduser("~/.atomshields") # AtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME...
Writes a section for a plugin.
def _addConfig(instance, config, parent_section): """ Writes a section for a plugin. Args: instance (object): Class instance for plugin config (object): Object (ConfigParser) which the current config parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports' """ try: section...
Returns a dictionary which contains the current config. If a section is setted only will returns the section config
def getConfig(self, section = None): """ Returns a dictionary which contains the current config. If a section is setted, only will returns the section config Args: section (str): (Optional) Section name. Returns: dict: Representation of current config """ data = {} if section is None: for s i...
Returns a class instance from a. py file.
def _getClassInstance(path, args=None): """ Returns a class instance from a .py file. Args: path (str): Absolute path to .py file args (dict): Arguments passed via class constructor Returns: object: Class instance or None """ if not path.endswith(".py"): return None if args is None: args...
Execute an specific method for each class instance located in path
def _executeMassiveMethod(path, method, args=None, classArgs = None): """ Execute an specific method for each class instance located in path Args: path (str): Absolute path which contains the .py files method (str): Method to execute into class instance Returns: dict: Dictionary which contains the re...
Run a scan in the path setted.
def run(self): """ Run a scan in the path setted. """ self.checkProperties() self.debug("[*] Iniciando escaneo de AtomShields con las siguientes propiedades. . . ") self.showScanProperties() self.loadConfig() # Init time counter init_ts = datetime.now() # Execute plugins cwd = os.getcwd() ...
Install all the dependences
def install(): """ Install all the dependences """ cmd = CommandHelper() cmd.install("npm") cmd = CommandHelper() cmd.install("nodejs-legacy") # Install retre with npm cmd = CommandHelper() cmd.command = "npm install -g retire" cmd.execute() if cmd.errors: from termcolor import colored ...
Setter for potential property
def potential(self, value): """ Setter for 'potential' property Args: value (bool): True if a potential is required. False else """ if value: self._potential = True else: self._potential = False
Shortcut method for getting a setting value.
def get(name, default=None, allow_default=True): """ Shortcut method for getting a setting value. :param str name: Setting key name. :param default: Default value of setting if it's not explicitly set. Defaults to `None` :param bool allow_default: If true, use the pa...
Helper to try to get a setting from the environment or pyconfig or finally use a provided default.
def env(key, default): """ Helper to try to get a setting from the environment, or pyconfig, or finally use a provided default. """ value = os.environ.get(key, None) if value is not None: log.info(' %s = %r', key.lower().replace('_', '.'), value) return value key = key.l...
Try to get key from the environment.
def env_key(key, default): """ Try to get `key` from the environment. This mutates `key` to replace dots with underscores and makes it all uppercase. my.database.host => MY_DATABASE_HOST """ env = key.upper().replace('.', '_') return os.environ.get(env, default)
Changes a setting value.
def set(self, name, value): """ Changes a setting value. This implements a locking mechanism to ensure some level of thread safety. :param str name: Setting key name. :param value: Setting value. """ if not self.settings.get('pyconfig.case_sensi...
Updates the current configuration with the values in conf_dict.
def _update(self, conf_dict, base_name=None): """ Updates the current configuration with the values in `conf_dict`. :param dict conf_dict: Dictionary of key value settings. :param str base_name: Base namespace for setting keys. """ for name in conf_dict: # S...
Loads all the config plugin modules to build a working configuration.
def load(self, clear=False): """ Loads all the config plugin modules to build a working configuration. If there is a ``localconfig`` module on the python path, it will be loaded last, overriding other settings. :param bool clear: Clear out the previous settings before loading ...
Return a setting value.
def get(self, name, default, allow_default=True): """ Return a setting value. :param str name: Setting key name. :param default: Default value of setting if it's not explicitly set. :param bool allow_default: If true, use the parameter default as ...
Handle creating the new etcd client instance and other business.
def init(self, hosts=None, cacert=None, client_cert=None, client_key=None): """ Handle creating the new etcd client instance and other business. :param hosts: Host string or list of hosts (default: `'127.0.0.1:2379'`) :param cacert: CA cert filename (optional) :param client_cert...
Return a dictionary of settings loaded from etcd.
def load(self, prefix=None, depth=None): """ Return a dictionary of settings loaded from etcd. """ prefix = prefix or self.prefix prefix = '/' + prefix.strip('/') + '/' if depth is None: depth = self.inherit_depth if not self.configured: ...
Return a etcd watching generator which yields events as they happen.
def get_watcher(self): """ Return a etcd watching generator which yields events as they happen. """ if not self.watching: raise StopIteration() return self.client.eternal_watch(self.prefix, recursive=True)
Begins watching etcd for changes.
def start_watching(self): """ Begins watching etcd for changes. """ # Don't create a new watcher thread if we already have one running if self.watcher and self.watcher.is_alive(): return # Create a new watcher thread and start it self.watcher = Watcher() self...
Return hosts parsed into a tuple of tuples.
def _parse_hosts(self, hosts): """ Return hosts parsed into a tuple of tuples. :param hosts: String or list of hosts """ # Default host if hosts is None: return # If it's a string, we allow comma separated strings if isinstance(hosts, six.st...
Undocumented cross - compatability functionality with jetconfig ( https:// github. com/ shakefu/ jetconfig ) that is very sloppy.
def _parse_jetconfig(self): """ Undocumented cross-compatability functionality with jetconfig (https://github.com/shakefu/jetconfig) that is very sloppy. """ conf = env('JETCONFIG_ETCD', None) if not conf: return import urlparse auth = None...
Main script for pyconfig command.
def main(): """ Main script for `pyconfig` command. """ parser = argparse.ArgumentParser(description="Helper for working with " "pyconfigs") target_group = parser.add_mutually_exclusive_group() target_group.add_argument('-f', '--filename', help="parse an individual file ...
Handles the - m argument.
def _handle_module(args): """ Handles the -m argument. """ module = _get_module_filename(args.module) if not module: _error("Could not load module or package: %r", args.module) elif isinstance(module, Unparseable): _error("Could not determine module source: %r", args.module) ...
Print an error message and exit.
def _error(msg, *args): """ Print an error message and exit. :param msg: A message to print :type msg: str """ print(msg % args, file=sys.stderr) sys.exit(1)
Return the filename of module if it can be imported.
def _get_module_filename(module): """ Return the filename of `module` if it can be imported. If `module` is a package, its directory will be returned. If it cannot be imported ``None`` is returned. If the ``__file__`` attribute is missing, or the module or package is a compiled egg, then an :...
Parse filename appropriately and then output calls according to the args specified.
def _parse_and_output(filename, args): """ Parse `filename` appropriately and then output calls according to the `args` specified. :param filename: A file or directory :param args: Command arguments :type filename: str """ relpath = os.path.dirname(filename) if os.path.isfile(filen...
Outputs calls.
def _output(calls, args): """ Outputs `calls`. :param calls: List of :class:`_PyconfigCall` instances :param args: :class:`~argparse.ArgumentParser` instance :type calls: list :type args: argparse.ArgumentParser """ # Sort the keys appropriately if args.natural_sort or args.source:...
Return call formatted appropriately for args.
def _format_call(call, args): """ Return `call` formatted appropriately for `args`. :param call: A pyconfig call object :param args: Arguments from the command :type call: :class:`_PyconfigCall` """ out = '' if args.source: out += call.annotation() + '\n' if args.only_keys...
Return output colorized with Pygments if available.
def _colorize(output): """ Return `output` colorized with Pygments, if available. """ if not pygments: return output # Available styles # ['monokai', 'manni', 'rrt', 'perldoc', 'borland', 'colorful', 'default', # 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs', ...
Return a list of: class: _PyconfigCall from recursively parsing directory.
def _parse_dir(directory, relpath): """ Return a list of :class:`_PyconfigCall` from recursively parsing `directory`. :param directory: Directory to walk looking for python files :param relpath: Path to make filenames relative to :type directory: str :type relpath: str """ relpath ...
Return a list of: class: _PyconfigCall from parsing filename.
def _parse_file(filename, relpath=None): """ Return a list of :class:`_PyconfigCall` from parsing `filename`. :param filename: A file to parse :param relpath: Relative directory to strip (optional) :type filename: str :type relpath: str """ with open(filename, 'r') as source: s...
Return arg appropriately parsed or mapped to a usable value.
def _map_arg(arg): """ Return `arg` appropriately parsed or mapped to a usable value. """ # Grab the easy to parse values if isinstance(arg, _ast.Str): return repr(arg.s) elif isinstance(arg, _ast.Num): return arg.n elif isinstance(arg, _ast.Name): name = arg.id ...
Return this call as if it were being assigned in a pyconfig namespace.
def as_namespace(self, namespace=None): """ Return this call as if it were being assigned in a pyconfig namespace. If `namespace` is specified and matches the top level of this call's :attr:`key`, then that section of the key will be removed. """ key = self.key ...
Return this call as if it were being assigned in a pyconfig namespace but load the actual value currently available in pyconfig.
def as_live(self): """ Return this call as if it were being assigned in a pyconfig namespace, but load the actual value currently available in pyconfig. """ key = self.get_key() default = pyconfig.get(key) if default: default = repr(default) e...
Return this call as it is called in its source.
def as_call(self): """ Return this call as it is called in its source. """ default = self._default() default = ', ' + default if default else '' return "pyconfig.%s(%r%s)" % (self.method, self.get_key(), default)
Return the call key even if it has to be parsed from the source.
def get_key(self): """ Return the call key, even if it has to be parsed from the source. """ if not isinstance(self.key, Unparseable): return self.key line = self.source[self.col_offset:] regex = re.compile('''pyconfig\.[eginst]+\(([^,]+).*?\)''') ma...
Return only the default value if there is one.
def _default_value_only(self): """ Return only the default value, if there is one. """ line = self.source[self.col_offset:] regex = re.compile('''pyconfig\.[eginst]+\(['"][^)]+?['"], ?(.*?)\)''') match = regex.match(line) if not match: return '' ...
Return the default argument formatted nicely.
def _default(self): """ Return the default argument, formatted nicely. """ try: # Check if it's iterable iter(self.default) except TypeError: return repr(self.default) # This is to look for unparsable values, and if we find one, we tr...
Get mappable parameters from YAML.
def _get_param_names(self): """ Get mappable parameters from YAML. """ template = Template(self.yaml_string) names = ['yaml_string'] # always include the template for match in re.finditer(template.pattern, template.template): name = match.group('named') or ma...
Construct a pylearn2 dataset.
def _get_dataset(self, X, y=None): """ Construct a pylearn2 dataset. Parameters ---------- X : array_like Training examples. y : array_like, optional Labels. """ from pylearn2.datasets import DenseDesignMatrix X = np.asarr...
Construct pylearn2 dataset labels.
def _get_labels(self, y): """ Construct pylearn2 dataset labels. Parameters ---------- y : array_like, optional Labels. """ y = np.asarray(y) if y.ndim == 1: return y.reshape((y.size, 1)) assert y.ndim == 2 return y
Build a trainer and run main_loop.
def fit(self, X, y=None): """ Build a trainer and run main_loop. Parameters ---------- X : array_like Training examples. y : array_like, optional Labels. """ from pylearn2.config import yaml_parse from pylearn2.train import...
Get model predictions.
def _predict(self, X, method='fprop'): """ Get model predictions. See pylearn2.scripts.mlp.predict_csv and http://fastml.com/how-to-get-predictions-from-pylearn2/. Parameters ---------- X : array_like Test dataset. method : str Mo...
Construct pylearn2 dataset labels.
def _get_labels(self, y): """ Construct pylearn2 dataset labels. Parameters ---------- y : array_like, optional Labels. """ y = np.asarray(y) assert y.ndim == 1 # convert to one-hot labels = np.unique(y).tolist() oh = n...
Load the dataset using pylearn2. config. yaml_parse.
def load(self): """ Load the dataset using pylearn2.config.yaml_parse. """ from pylearn2.config import yaml_parse from pylearn2.datasets import Dataset dataset = yaml_parse.load(self.yaml_string) assert isinstance(dataset, Dataset) data = dataset.iterator...
Fits the model with random restarts.: return:
def fit(self): """ Fits the model with random restarts. :return: """ self.model.optimize_restarts(num_restarts=self.num_restarts, verbose=False)
creates an additive kernel
def _create_kernel(self): """ creates an additive kernel """ # Check kernels kernels = self.kernel_params if not isinstance(kernels, list): raise RuntimeError('Must provide enumeration of kernels') for kernel in kernels: if sorted(list(kern...
Fit and score an estimator with cross - validation
def fit_and_score_estimator(estimator, parameters, cv, X, y=None, scoring=None, iid=True, n_jobs=1, verbose=1, pre_dispatch='2*n_jobs'): """Fit and score an estimator with cross-validation This function is basically a copy of sklearn's model_selection...
Find the subclass kls of baseclass with class attribute short_name that matches the supplied short_name and then instantiate and return that class with:
def init_subclass_by_name(baseclass, short_name, params): """ Find the subclass, `kls` of baseclass with class attribute `short_name` that matches the supplied `short_name`, and then instantiate and return that class with: return kls(**params) This function also tries its best to catch any...
Recursively merge two dictionaries with the elements from top taking precedence over elements from top.
def dict_merge(base, top): """Recursively merge two dictionaries, with the elements from `top` taking precedence over elements from `top`. Returns ------- out : dict A new dict, containing the merged records. """ out = dict(top) for key in base: if key in top: ...
Context manager ( with statement ) that changes the current directory during the context.
def in_directory(path): """Context manager (with statement) that changes the current directory during the context. """ curdir = os.path.abspath(os.curdir) os.chdir(path) yield os.chdir(curdir)
Format a timedelta object for display to users
def format_timedelta(td_object): """Format a timedelta object for display to users Returns ------- str """ def get_total_seconds(td): # timedelta.total_seconds not in py2.6 return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6 seconds = i...
Like assert_all_finite but only for ndarray.
def _assert_all_finite(X): """Like assert_all_finite, but only for ndarray.""" X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent # false positives from overflow in sum method if (X.dt...
UserWarning if array contains non - finite elements
def _warn_if_not_finite(X): """UserWarning if array contains non-finite elements""" X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent # false positives from overflow in sum method if ...
Return number of samples in array - like x.
def num_samples(x, is_nested=False): """Return number of samples in array-like x.""" if hasattr(x, 'fit'): # Don't get num_samples from an ensembles length! raise TypeError('Expected sequence or array-like, got ' 'estimator %s' % x) if is_nested: return sum(n...
Check that all arrays have consistent first dimensions.
def check_arrays(*arrays, **options): """Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. By default lists and tuples are converted to numpy arrays. It is possible to enforce certain properties, such as dtype, continguity a...
Parameters ---------- params: dict Trial param set history: list of 3 - tuples History of past function evaluations. Each element in history should be a tuple ( params score status ) where params is a dict mapping parameter names to values
def is_repeated_suggestion(params, history): """ Parameters ---------- params : dict Trial param set history : list of 3-tuples History of past function evaluations. Each element in history should be a tuple `(params, score, status)`, where `pa...
Suggest params to maximize an objective function based on the function evaluation history using a tree of Parzen estimators ( TPE ) as implemented in the hyperopt package.
def suggest(self, history, searchspace): """ Suggest params to maximize an objective function based on the function evaluation history using a tree of Parzen estimators (TPE), as implemented in the hyperopt package. Use of this function requires that hyperopt be installed. ...
The config object loads its values from two sources with the following precedence:
def _merge_defaults(self, config): """The config object loads its values from two sources, with the following precedence: 1. data/default_config.yaml 2. The config file itself, passed in to this object in the constructor as `path`. in case of conflict, th...
Create a Config object from config dict directly.
def fromdict(cls, config, check_fields=True): """Create a Config object from config dict directly.""" m = super(Config, cls).__new__(cls) m.path = '.' m.verbose = False m.config = m._merge_defaults(config) if check_fields: m._check_fields() return m
Get an entry from within a section using a/ delimiter
def get_value(self, field, default=None): """Get an entry from within a section, using a '/' delimiter""" section, key = field.split('/') return self.get_section(section).get(key, default)
Get the estimator an instance of a ( subclass of ) sklearn. base. BaseEstimator
def estimator(self): """Get the estimator, an instance of a (subclass of) sklearn.base.BaseEstimator It can be loaded either from a pickle, from a string using eval(), or from an entry point. e.g. estimator: # only one of the following can actually be activ...
SHA1 hash of the config file itself.
def sha1(self): """SHA1 hash of the config file itself.""" with open(self.path, 'rb') as f: return hashlib.sha1(f.read()).hexdigest()
Returns ---------- best_candidate: the best candidate hyper - parameters as defined by
def get_best_candidate(self): """ Returns ---------- best_candidate : the best candidate hyper-parameters as defined by """ # TODO make this best mean response self.incumbent = self.surrogate.Y.max() # Objective function def z(x): # TO...
Plot 1. All iterations ( scatter plot )
def plot_1(data, *args): """Plot 1. All iterations (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) return build_scatter_tooltip( x=df_all['id'], y=df_all['mean_test_score'], tt=df_params, title='All Iterations')
Plot 2. Running best score ( scatter plot )
def plot_2(data, *args): """Plot 2. Running best score (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) x = [df_all['id'][0]] y = [df_all['mean_test_score'][0]] params = [df_params.loc[0]] for i in range(len(df_all)): if df_all['mean_test_score']...
t - SNE embedding of the parameters colored by score
def plot_3(data, ss, *args): """t-SNE embedding of the parameters, colored by score """ if len(data) <= 1: warnings.warn("Only one datapoint. Could not compute t-SNE embedding.") return None scores = np.array([d['mean_test_score'] for d in data]) # maps each parameters to a vector ...
Scatter plot of score vs each param
def plot_4(data, *args): """Scatter plot of score vs each param """ params = nonconstant_parameters(data) scores = np.array([d['mean_test_score'] for d in data]) order = np.argsort(scores) for key in params.keys(): if params[key].dtype == np.dtype('bool'): params[key] = para...
An integer/ float - valued enumerable with num items bounded between [ min max ]. Note that the right endpoint of the interval includes max. This is a wrapper around the add_enum. jump can be a float or int.
def add_jump(self, name, min, max, num, warp=None, var_type=float): """ An integer/float-valued enumerable with `num` items, bounded between [`min`, `max`]. Note that the right endpoint of the interval includes `max`. This is a wrapper around the add_enum. `jump` can be a float or int. ...
An integer - valued dimension bounded between min < = x < = max. Note that the right endpoint of the interval includes max.
def add_int(self, name, min, max, warp=None): """An integer-valued dimension bounded between `min` <= x <= `max`. Note that the right endpoint of the interval includes `max`. When `warp` is None, the base measure associated with this dimension is a categorical distribution with each wei...
A floating point - valued dimension bounded min < = x < max
def add_float(self, name, min, max, warp=None): """A floating point-valued dimension bounded `min` <= x < `max` When `warp` is None, the base measure associated with this dimension is a uniform distribution on [min, max). With `warp == 'log'`, the base measure is a uniform distribution ...
An enumeration - valued dimension.
def add_enum(self, name, choices): """An enumeration-valued dimension. The base measure associated with this dimension is a categorical distribution with equal weight on each element in `choices`. """ if not isinstance(choices, Iterable): raise ValueError('variable %...
Yield integer coordinates on the line from ( x0 y0 ) to ( x1 y1 ).
def bresenham(x0, y0, x1, y1): """Yield integer coordinates on the line from (x0, y0) to (x1, y1). Input coordinates should be integers. The result will contain both the start and the end point. """ dx = x1 - x0 dy = y1 - y0 xsign = 1 if dx > 0 else -1 ysign = 1 if dy > 0 else -1 ...
Decorator that produces DEBUG level log messages before and after calling a parser method.
def log_callback(wrapped_function): """Decorator that produces DEBUG level log messages before and after calling a parser method. If a callback raises an IgnoredMatchException the log will show 'IGNORED' instead to indicate that the parser will not create any objects from the matched string. E...
Try to find a pattern that matches the source and calll a parser method to create Python objects.
def find_match(self): """Try to find a pattern that matches the source and calll a parser method to create Python objects. A callback that raises an IgnoredMatchException indicates that the given string data is ignored by the parser and no objects are created. If none of the pa...
If the given object is an instance of Child add it to self and register self as a parent.
def add_child(self, child): """If the given object is an instance of Child add it to self and register self as a parent. """ if not isinstance(child, ChildMixin): raise TypeError( 'Requires instance of TreeElement. ' 'Got {}'.format(type(child)...
if client_port is 0 any client_port is good
def get_ip_packet(data, client_port, server_port, is_loopback=False): """ if client_port is 0 any client_port is good """ header = _loopback if is_loopback else _ethernet try: header.unpack(data) except Exception as ex: raise ValueError('Bad header: %s' % ex) tcp_p = getattr(header...
Reads listening ports from/ proc/ net/ tcp
def listening_ports(): """ Reads listening ports from /proc/net/tcp """ ports = [] if not os.path.exists(PROC_TCP): return ports with open(PROC_TCP) as fh: for line in fh: if '00000000:0000' not in line: continue parts = line.lstrip(' ').split(' ...
get stats & show them
def report(self): """ get stats & show them """ self._output.write('\r') sort_by = 'avg' results = {} for key, latencies in self._latencies_by_method.items(): result = {} result['count'] = len(latencies) result['avg'] = sum(latencies) / len(la...
Diff two thrift structs and return the result as a ThriftDiff instance
def of_structs(cls, a, b): """ Diff two thrift structs and return the result as a ThriftDiff instance """ t_diff = ThriftDiff(a, b) t_diff._do_diff() return t_diff
Diff two thrift messages by comparing their args raises exceptions if for some reason the messages can t be diffed. Only args of type struct are compared.
def of_messages(cls, msg_a, msg_b): """ Diff two thrift messages by comparing their args, raises exceptions if for some reason the messages can't be diffed. Only args of type 'struct' are compared. Returns a list of ThriftDiff results - one for each struct arg """ ...
Check if two thrift messages are diff ready.
def can_diff(msg_a, msg_b): """ Check if two thrift messages are diff ready. Returns a tuple of (boolean, reason_string), i.e. (False, reason_string) if the messages can not be diffed along with the reason and (True, None) for the opposite case """ if msg_a.metho...
Returns true if all fields of other struct are isomorphic to this struct s fields
def is_isomorphic_to(self, other): """ Returns true if all fields of other struct are isomorphic to this struct's fields """ return (isinstance(other, self.__class__) and len(self.fields) == len(other.fields) and all...
Returns true if other field s meta data ( everything except value ) is same as this one
def is_isomorphic_to(self, other): """ Returns true if other field's meta data (everything except value) is same as this one """ return (isinstance(other, self.__class__) and self.field_type == other.field_type and self.field_id == other.field_id)
tries to deserialize a message might fail if data is missing
def read(cls, data, protocol=None, fallback_protocol=TBinaryProtocol, finagle_thrift=False, max_fields=MAX_FIELDS, max_list_size=MAX_LIST_SIZE, max_map_size=MAX_MAP_SIZE, max_set_size=MAX_SET_SIZE, read_values=False)...