_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q260300
get
validation
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 parameter default as default if the key is not set, else raise
python
{ "resource": "" }
q260301
env
validation
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)
python
{ "resource": "" }
q260302
env_key
validation
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.
python
{ "resource": "" }
q260303
Config.set
validation
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_sensitive',
python
{ "resource": "" }
q260304
Config._update
validation
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: # Skip private names if name.startswith('_'): continue value = conf_dict[name] # Skip Namespace if it's imported if value is Namespace: continue # Use a base namespace if base_name: name = base_name + '.' + name if isinstance(value, Namespace): for name, value in value.iteritems(name):
python
{ "resource": "" }
q260305
Config.load
validation
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 """ if clear: self.settings = {} defer = [] # Load all config plugins for conf in pkg_resources.iter_entry_points('pyconfig'): if conf.attrs: raise RuntimeError("config must be a module") mod_name = conf.module_name base_name = conf.name if conf.name != 'any' else None log.info("Loading module '%s'", mod_name) mod_dict = runpy.run_module(mod_name) # If this module wants to be deferred, save it for later if mod_dict.get('deferred', None) is deferred: log.info("Deferring module '%s'", mod_name) mod_dict.pop('deferred')
python
{ "resource": "" }
q260306
Config.get
validation
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 default if the key is not set, else raise :exc:`LookupError` :raises: :exc:`LookupError` if allow_default is false and the setting is
python
{ "resource": "" }
q260307
etcd.init
validation
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: Client cert filename (optional) :param client_key: Client key filename (optional) :type ca: str :type cert: str :type key: str """ # Try to get the etcd module try: import etcd self.module = etcd except ImportError: pass if not self.module: return self._parse_jetconfig() # Check env for overriding configuration or pyconfig setting hosts = env('PYCONFIG_ETCD_HOSTS', hosts) protocol = env('PYCONFIG_ETCD_PROTOCOL', None) cacert = env('PYCONFIG_ETCD_CACERT', cacert) client_cert = env('PYCONFIG_ETCD_CERT', client_cert) client_key = env('PYCONFIG_ETCD_KEY',
python
{ "resource": "" }
q260308
etcd.load
validation
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: log.debug("etcd not available") return if self.watching: log.info("Starting watcher for %r", prefix) self.start_watching() log.info("Loading from etcd %r", prefix) try: result = self.client.get(prefix) except self.module.EtcdKeyNotFound: result = None if not result: log.info("No configuration found") return {} # Iterate over the returned keys from etcd update = {} for item in result.children: key = item.key value = item.value # Try to parse them as JSON strings, just in case it works try: value = pytool.json.from_json(value) except:
python
{ "resource": "" }
q260309
etcd.get_watcher
validation
def get_watcher(self): """ Return a etcd watching generator which yields events as they happen.
python
{ "resource": "" }
q260310
etcd.start_watching
validation
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
python
{ "resource": "" }
q260311
etcd._parse_hosts
validation
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.string_types): # Split comma-separated list hosts = [host.strip() for host in hosts.split(',')] # Split host and port hosts =
python
{ "resource": "" }
q260312
main
validation
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 or directory", metavar='F') target_group.add_argument('-m', '--module', help="parse a package or module, recursively looking inside it", metavar='M') parser.add_argument('-v', '--view-call', help="show the actual pyconfig call made (default: show namespace)", action='store_true') parser.add_argument('-l', '--load-configs', help="query the currently set value for each key found",
python
{ "resource": "" }
q260313
_handle_module
validation
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,
python
{ "resource": "" }
q260314
_error
validation
def _error(msg, *args): """ Print an error message and exit. :param msg:
python
{ "resource": "" }
q260315
_get_module_filename
validation
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 :class:`Unparseable` instance is returned, since the source can't be retrieved. :param module: A module name, such as ``'test.test_config'`` :type module: str """ # Split up the module and its containing package, if it has one module = module.split('.') package = '.'.join(module[:-1]) module = module[-1] try: if not package: # We aren't accessing a module within a package, but rather a top # level package, so it's a straight up import module = __import__(module) else: # Import the package containing our desired module package = __import__(package, fromlist=[module]) # Get the module from that package module = getattr(package, module, None) filename = getattr(module, '__file__', None) if not filename: # No filename? Nothing to do
python
{ "resource": "" }
q260316
_parse_and_output
validation
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(filename): calls = _parse_file(filename, relpath) elif os.path.isdir(filename): calls = _parse_dir(filename, relpath) else: # XXX(shakefu): This is an error of some sort, maybe symlinks? # Probably need some thorough testing _error("Could not determine file type: %r", filename) if not calls: # XXX(shakefu): Probably want to change this to not be an error and # just be a normal fail (e.g. command runs, no output).
python
{ "resource": "" }
q260317
_output
validation
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: calls = sorted(calls, key=lambda c: (c.filename, c.lineno)) else: calls = sorted(calls, key=lambda c: c.key) out = [] # Handle displaying only the list of keys if args.only_keys: keys = set() for call in calls: if call.key in keys: continue out.append(_format_call(call, args)) keys.add(call.key) out = '\n'.join(out) if args.color: out = _colorize(out) print(out, end=' ') # We're done here return
python
{ "resource": "" }
q260318
_format_call
validation
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` """
python
{ "resource": "" }
q260319
_colorize
validation
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',
python
{ "resource": "" }
q260320
_map_arg
validation
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 if name == 'True': return True elif name == 'False':
python
{ "resource": "" }
q260321
_PyconfigCall.as_namespace
validation
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. """
python
{ "resource": "" }
q260322
_PyconfigCall.as_live
validation
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)
python
{ "resource": "" }
q260323
_PyconfigCall.as_call
validation
def as_call(self): """ Return this call as it is called in its source. """ default = self._default() default = ', '
python
{ "resource": "" }
q260324
_PyconfigCall.get_key
validation
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:]
python
{ "resource": "" }
q260325
_PyconfigCall._default_value_only
validation
def _default_value_only(self): """ Return only the default value, if there is one. """ line = self.source[self.col_offset:]
python
{ "resource": "" }
q260326
_PyconfigCall._default
validation
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
python
{ "resource": "" }
q260327
Pylearn2Estimator._get_param_names
validation
def _get_param_names(self): """ Get mappable parameters from YAML. """ template = Template(self.yaml_string) names = ['yaml_string'] #
python
{ "resource": "" }
q260328
Pylearn2Estimator._get_dataset
validation
def _get_dataset(self, X, y=None): """ Construct a pylearn2 dataset. Parameters ---------- X : array_like Training examples. y : array_like, optional
python
{ "resource": "" }
q260329
Pylearn2Estimator.fit
validation
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 Train # build trainer params = self.get_params() yaml_string = Template(self.yaml_string).substitute(params) self.trainer = yaml_parse.load(yaml_string) assert isinstance(self.trainer, Train) if self.trainer.dataset is not None: raise ValueError('Train YAML database must evaluate to None.') self.trainer.dataset = self._get_dataset(X, y) # update monitoring dataset(s) if (hasattr(self.trainer.algorithm, 'monitoring_dataset') and
python
{ "resource": "" }
q260330
Pylearn2Estimator._predict
validation
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 Model method to call for prediction. """ import theano
python
{ "resource": "" }
q260331
Pylearn2DatasetLoader.load
validation
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(mode='sequential', num_batches=1, data_specs=dataset.data_specs,
python
{ "resource": "" }
q260332
GaussianProcessKernel._create_kernel
validation
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(kernel.keys())) != ['name', 'options', 'params']: raise RuntimeError( 'strategy/params/kernels must contain keys: "name", "options", "params"') # Turn into entry points. # TODO use eval to allow user to specify internal variables for kernels (e.g. V) in config file. kernels = [] for kern in self.kernel_params: params = kern['params'] options = kern['options'] name = kern['name'] kernel_ep = load_entry_point(name, 'strategy/params/kernels') if issubclass(kernel_ep, KERNEL_BASE_CLASS): if options['independent']: # TODO Catch errors here?
python
{ "resource": "" }
q260333
fit_and_score_estimator
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._BaseSearchCV._fit(), which is the core of the GridSearchCV fit() method. Unfortunately, that class does _not_ return the training set scores, which we want to save in the database, and because of the way it's written, you can't change it by subclassing or monkeypatching. This function uses some undocumented internal sklearn APIs (non-public). It was written against sklearn version 0.16.1. Prior Versions are likely to fail due to changes in the design of cross_validation module. Returns ------- out : dict, with keys 'mean_test_score' 'test_scores', 'train_scores' The scores on the training and test sets, as well as the mean test set score. """ scorer = check_scoring(estimator, scoring=scoring) n_samples = num_samples(X) X, y = check_arrays(X, y, allow_lists=True, sparse_format='csr', allow_nans=True) if y is not None: if len(y) != n_samples: raise ValueError('Target variable (y) has a different number ' 'of samples (%i) than data (X: %i samples)' % (len(y), n_samples)) cv = check_cv(cv=cv, y=y, classifier=is_classifier(estimator)) out = Parallel( n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch )( delayed(_fit_and_score)(clone(estimator), X, y, scorer, train, test, verbose, parameters, fit_params=None) for train, test in cv.split(X, y)) assert len(out) == cv.n_splits train_scores, test_scores = [], [] n_train_samples, n_test_samples = [], [] for test_score, n_test, train_score, n_train, _ in out: train_scores.append(train_score) test_scores.append(test_score) n_test_samples.append(n_test) n_train_samples.append(n_train) train_scores, test_scores = map(list, check_arrays(train_scores,
python
{ "resource": "" }
q260334
dict_merge
validation
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:
python
{ "resource": "" }
q260335
format_timedelta
validation
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 = int(get_total_seconds(td_object)) periods = [('year', 60*60*24*365),
python
{ "resource": "" }
q260336
_assert_all_finite
validation
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.dtype.char in np.typecodes['AllFloat'] and
python
{ "resource": "" }
q260337
_warn_if_not_finite
validation
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 (X.dtype.char in np.typecodes['AllFloat'] and
python
{ "resource": "" }
q260338
Config.fromdict
validation
def fromdict(cls, config, check_fields=True): """Create a Config object from config dict directly.""" m = super(Config, cls).__new__(cls)
python
{ "resource": "" }
q260339
Config.sha1
validation
def sha1(self): """SHA1 hash of the config file itself.""" with open(self.path, 'rb') as f:
python
{ "resource": "" }
q260340
plot_3
validation
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 of floats warped = np.array([ss.point_to_unit(d['parameters']) for d in data]) # Embed into 2 dimensions with t-SNE X = TSNE(n_components=2).fit_transform(warped) e_scores = np.exp(scores) mine, maxe = np.min(e_scores), np.max(e_scores) color = (e_scores - mine) / (maxe - mine) mapped_colors = list(map(rgb2hex, cm.get_cmap('RdBu_r')(color))) p = bk.figure(title='t-SNE (unsupervised)', tools=TOOLS) df_params = nonconstant_parameters(data) df_params['score'] = scores df_params['x'] = X[:, 0] df_params['y'] = X[:, 1] df_params['color'] = mapped_colors
python
{ "resource": "" }
q260341
plot_4
validation
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] = params[key].astype(np.int) p_list = [] for key in params.keys(): x = params[key][order] y = scores[order] params = params.loc[order] try: radius = (np.max(x) -
python
{ "resource": "" }
q260342
SearchSpace.add_int
validation
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 weight on each of the integers in [min, max]. With `warp == 'log'`, the base measure is a uniform distribution on the log of the variable, with bounds at `log(min)` and `log(max)`. This is appropriate for variables that are "naturally" in log-space. Other `warp` functions are not supported (yet), but may be at a later time. Please note that this functionality is not supported for `hyperopt_tpe`.
python
{ "resource": "" }
q260343
SearchSpace.add_float
validation
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 on the log of the variable, with bounds at `log(min)` and `log(max)`. This is appropriate for variables that are "naturally" in log-space. Other `warp` functions are not supported (yet), but may be at a later time. """ min, max = map(float, (min, max)) if not min < max:
python
{ "resource": "" }
q260344
SearchSpace.add_enum
validation
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):
python
{ "resource": "" }
q260345
log_callback
validation
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. Example: DEBUG:poyo.parser:parse_simple <- 123: 456.789 DEBUG:poyo.parser:parse_int <- 123 DEBUG:poyo.parser:parse_int -> 123 DEBUG:poyo.parser:parse_float <- 456.789 DEBUG:poyo.parser:parse_float -> 456.789 DEBUG:poyo.parser:parse_simple -> <Simple name: 123, value: 456.789> """ def debug_log(message): """Helper to log an escaped version of the given message to DEBUG""" logger.debug(message.encode('unicode_escape').decode()) @functools.wraps(wrapped_function) def _wrapper(parser, match, **kwargs): func_name = wrapped_function.__name__
python
{ "resource": "" }
q260346
_Parser.find_match
validation
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 pattern match a NoMatchException is raised. """ for pattern, callback in self.rules: match = pattern.match(self.source, pos=self.pos) if not match: continue
python
{ "resource": "" }
q260347
ContainerMixin.add_child
validation
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.
python
{ "resource": "" }
q260348
get_ip_packet
validation
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.data, 'data', None)
python
{ "resource": "" }
q260349
LatencyPrinter.report
validation
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(latencies) result['min'] = min(latencies) result['max'] = max(latencies) latencies = sorted(latencies) result['p90'] = percentile(latencies, 0.90) result['p95'] = percentile(latencies, 0.95) result['p99'] = percentile(latencies, 0.99) result['p999'] = percentile(latencies, 0.999) results[key] = result
python
{ "resource": "" }
q260350
ThriftDiff.of_structs
validation
def of_structs(cls, a, b): """ Diff two thrift structs and return the result as a ThriftDiff instance """
python
{ "resource": "" }
q260351
ThriftDiff.of_messages
validation
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 """ ok_to_diff, reason
python
{ "resource": "" }
q260352
ThriftDiff.can_diff
validation
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
python
{ "resource": "" }
q260353
ThriftStruct.is_isomorphic_to
validation
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__)
python
{ "resource": "" }
q260354
ThriftMessage.read
validation
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): """ tries to deserialize a message, might fail if data is missing """ # do we have enough data? if len(data) < cls.MIN_MESSAGE_SIZE: raise ValueError('not enough data') if protocol is None: protocol = cls.detect_protocol(data, fallback_protocol) trans = TTransport.TMemoryBuffer(data) proto = protocol(trans) # finagle-thrift prepends a RequestHeader # # See: http://git.io/vsziG header = None if finagle_thrift: try: header = ThriftStruct.read( proto, max_fields,
python
{ "resource": "" }
q260355
Stream.pop
validation
def pop(self, nbytes): """ pops packets with _at least_ nbytes of payload """ size = 0 popped = [] with self._lock_packets: while size < nbytes: try: packet = self._packets.pop(0) size += len(packet.data.data)
python
{ "resource": "" }
q260356
Stream.pop_data
validation
def pop_data(self, nbytes): """ similar to pop, but returns payload + last timestamp """ last_timestamp = 0
python
{ "resource": "" }
q260357
Stream.push
validation
def push(self, ip_packet): """ push the packet into the queue """ data_len = len(ip_packet.data.data) seq_id = ip_packet.data.seq if data_len == 0: self._next_seq_id = seq_id return False # have we seen this packet?
python
{ "resource": "" }
q260358
Dispatcher.run
validation
def run(self, *args, **kwargs): """ Deal with the incoming packets """ while True: try: timestamp, ip_p = self._queue.popleft() src_ip = get_ip(ip_p, ip_p.src) dst_ip = get_ip(ip_p, ip_p.dst) src = intern('%s:%s' % (src_ip, ip_p.data.sport)) dst = intern('%s:%s' % (dst_ip, ip_p.data.dport)) key = intern('%s<->%s' % (src, dst)) stream = self._streams.get(key) if stream is None: stream = Stream(src, dst) self._streams[key] = stream # HACK: save the timestamp setattr(ip_p, 'timestamp', timestamp) pushed = stream.push(ip_p)
python
{ "resource": "" }
q260359
get_disk_image_by_name
validation
def get_disk_image_by_name(pbclient, location, image_name): """ Returns all disk images within a location with a given image name. The name must match exactly. The list may be empty. """ all_images = pbclient.list_images() matching = [i for i in all_images['items'] if
python
{ "resource": "" }
q260360
ProfitBricksService._read_config
validation
def _read_config(self, filename=None): """ Read the user configuration """ if filename: self._config_filename = filename else: try: import appdirs except ImportError: raise Exception("Missing dependency for determining config path. Please install "
python
{ "resource": "" }
q260361
ProfitBricksService._save_config
validation
def _save_config(self, filename=None): """ Save the given user configuration. """ if filename is None: filename = self._config_filename parent_path = os.path.dirname(filename)
python
{ "resource": "" }
q260362
ProfitBricksService._get_username
validation
def _get_username(self, username=None, use_config=True, config_filename=None): """Determine the username If a username is given, this name is used. Otherwise the configuration file will be consulted if `use_config` is set to True. The user is asked for the username if the username is not available. Then the username is stored in the configuration file. :param username: Username (used directly if given) :type username: ``str`` :param use_config: Whether to read username from configuration file
python
{ "resource": "" }
q260363
ProfitBricksService._get_password
validation
def _get_password(self, password, use_config=True, config_filename=None, use_keyring=HAS_KEYRING): """ Determine the user password If the password is given, this password is used. Otherwise this function will try to get the password from the user's keyring if `use_keyring` is set to True. :param username: Username (used directly if given) :type username: ``str`` :param use_config: Whether to read username from configuration file :type use_config: ``bool`` :param config_filename: Path to the configuration file :type config_filename: ``str`` """ if not password and use_config: if self._config is None: self._read_config(config_filename) password = self._config.get("credentials", "password", fallback=None) if not password and use_keyring: logger = logging.getLogger(__name__) question = ("Please enter your password for {} on {}: " .format(self.username, self.host_base)) if HAS_KEYRING: password = keyring.get_password(self.keyring_identificator, self.username) if password is None: password = getpass.getpass(question) try: keyring.set_password(self.keyring_identificator, self.username, password) except keyring.errors.PasswordSetError as error: logger.warning("Storing password in keyring '%s' failed: %s", self.keyring_identificator, error) else: logger.warning("Install the 'keyring' Python module to store your password " "securely in your keyring!") password = self._config.get("credentials", "password", fallback=None)
python
{ "resource": "" }
q260364
ProfitBricksService.get_datacenter
validation
def get_datacenter(self, datacenter_id, depth=1): """ Retrieves a data center by its ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param depth: The depth of the response data.
python
{ "resource": "" }
q260365
ProfitBricksService.get_datacenter_by_name
validation
def get_datacenter_by_name(self, name, depth=1): """ Retrieves a data center by its name. Either returns the data center response or raises an Exception if no or more than one data center was found with the name. The search for the name is done in this relaxing way: - exact name match - case-insentive name match - data center starts with the name - data center starts with the name (case insensitive) - name appears in the data center name - name appears in the data center name (case insensitive)
python
{ "resource": "" }
q260366
ProfitBricksService.delete_datacenter
validation
def delete_datacenter(self, datacenter_id): """ Removes the data center and all its components such as servers, NICs, load balancers, volumes. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str``
python
{ "resource": "" }
q260367
ProfitBricksService.get_firewall_rule
validation
def get_firewall_rule(self, datacenter_id, server_id, nic_id, firewall_rule_id): """ Retrieves a single firewall rule by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` :param firewall_rule_id: The unique ID of
python
{ "resource": "" }
q260368
ProfitBricksService.delete_firewall_rule
validation
def delete_firewall_rule(self, datacenter_id, server_id, nic_id, firewall_rule_id): """ Removes a firewall rule from the NIC. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` :param firewall_rule_id: The unique ID of the firewall rule.
python
{ "resource": "" }
q260369
ProfitBricksService.create_firewall_rule
validation
def create_firewall_rule(self, datacenter_id, server_id, nic_id, firewall_rule): """ Creates a firewall rule on the specified NIC and server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` :param firewall_rule: A firewall rule dict. :type firewall_rule: ``dict`` """ properties = { "name": firewall_rule.name } if firewall_rule.protocol: properties['protocol'] = firewall_rule.protocol
python
{ "resource": "" }
q260370
ProfitBricksService.update_firewall_rule
validation
def update_firewall_rule(self, datacenter_id, server_id, nic_id, firewall_rule_id, **kwargs): """ Updates a firewall rule. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` :param firewall_rule_id: The unique ID of the firewall rule. :type firewall_rule_id: ``str`` """ data = {} for attr, value in kwargs.items(): data[self._underscore_to_camelcase(attr)] = value if attr == 'source_mac': data['sourceMac'] = value elif attr == 'source_ip': data['sourceIp'] = value elif attr == 'target_ip': data['targetIp'] = value elif attr == 'port_range_start': data['portRangeStart'] = value
python
{ "resource": "" }
q260371
ProfitBricksService.delete_image
validation
def delete_image(self, image_id): """ Removes only user created images. :param image_id: The unique ID of the image. :type image_id: ``str`` """
python
{ "resource": "" }
q260372
ProfitBricksService.update_image
validation
def update_image(self, image_id, **kwargs): """ Replace all properties of an image. """ data = {} for attr, value in kwargs.items():
python
{ "resource": "" }
q260373
ProfitBricksService.delete_ipblock
validation
def delete_ipblock(self, ipblock_id): """ Removes a single IP block from your account. :param ipblock_id: The unique ID of the IP block. :type ipblock_id: ``str`` """
python
{ "resource": "" }
q260374
ProfitBricksService.reserve_ipblock
validation
def reserve_ipblock(self, ipblock): """ Reserves an IP block within your account. """ properties = { "name": ipblock.name } if ipblock.location: properties['location'] = ipblock.location if ipblock.size: properties['size'] = str(ipblock.size)
python
{ "resource": "" }
q260375
ProfitBricksService.get_lan
validation
def get_lan(self, datacenter_id, lan_id, depth=1): """ Retrieves a single LAN by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param lan_id: The unique ID of the LAN. :type lan_id: ``str`` :param depth: The depth of the response data. :type depth: ``int`` """
python
{ "resource": "" }
q260376
ProfitBricksService.list_lans
validation
def list_lans(self, datacenter_id, depth=1): """ Retrieves a list of LANs available in the account. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param depth: The depth of the response data. :type
python
{ "resource": "" }
q260377
ProfitBricksService.delete_lan
validation
def delete_lan(self, datacenter_id, lan_id): """ Removes a LAN from the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param lan_id: The unique ID of the LAN. :type
python
{ "resource": "" }
q260378
ProfitBricksService.create_lan
validation
def create_lan(self, datacenter_id, lan): """ Creates a LAN in the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param lan: The LAN object to be created. :type lan: ``dict``
python
{ "resource": "" }
q260379
ProfitBricksService.update_lan
validation
def update_lan(self, datacenter_id, lan_id, name=None, public=None, ip_failover=None): """ Updates a LAN :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param lan_id: The unique ID of the LAN. :type lan_id: ``str`` :param name: The new name of the LAN. :type name: ``str``
python
{ "resource": "" }
q260380
ProfitBricksService.get_lan_members
validation
def get_lan_members(self, datacenter_id, lan_id, depth=1): """ Retrieves the list of NICs that are part of the LAN. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param lan_id: The unique ID of the LAN. :type
python
{ "resource": "" }
q260381
ProfitBricksService.get_loadbalancer
validation
def get_loadbalancer(self, datacenter_id, loadbalancer_id): """ Retrieves a single load balancer by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type
python
{ "resource": "" }
q260382
ProfitBricksService.list_loadbalancers
validation
def list_loadbalancers(self, datacenter_id, depth=1): """ Retrieves a list of load balancers in the data center. :param datacenter_id: The unique ID of the data center. :type
python
{ "resource": "" }
q260383
ProfitBricksService.delete_loadbalancer
validation
def delete_loadbalancer(self, datacenter_id, loadbalancer_id): """ Removes the load balancer from the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type
python
{ "resource": "" }
q260384
ProfitBricksService.create_loadbalancer
validation
def create_loadbalancer(self, datacenter_id, loadbalancer): """ Creates a load balancer within the specified data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer: The load balancer object to be created. :type loadbalancer: ``dict``
python
{ "resource": "" }
q260385
ProfitBricksService.update_loadbalancer
validation
def update_loadbalancer(self, datacenter_id, loadbalancer_id, **kwargs): """ Updates a load balancer :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type loadbalancer_id: ``str`` """ data = {} for attr, value in kwargs.items(): data[self._underscore_to_camelcase(attr)] = value
python
{ "resource": "" }
q260386
ProfitBricksService.get_loadbalancer_members
validation
def get_loadbalancer_members(self, datacenter_id, loadbalancer_id, depth=1): """ Retrieves the list of NICs that are associated with a load balancer. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type loadbalancer_id: ``str`` :param depth: The depth of the response data. :type
python
{ "resource": "" }
q260387
ProfitBricksService.add_loadbalanced_nics
validation
def add_loadbalanced_nics(self, datacenter_id, loadbalancer_id, nic_id): """ Associates a NIC with the given load balancer. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type loadbalancer_id: ``str`` :param nic_id: The ID of the NIC. :type nic_id: ``str`` """
python
{ "resource": "" }
q260388
ProfitBricksService.get_loadbalanced_nic
validation
def get_loadbalanced_nic(self, datacenter_id, loadbalancer_id, nic_id, depth=1): """ Gets the properties of a load balanced NIC. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type loadbalancer_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` :param
python
{ "resource": "" }
q260389
ProfitBricksService.remove_loadbalanced_nic
validation
def remove_loadbalanced_nic(self, datacenter_id, loadbalancer_id, nic_id): """ Removes a NIC from the load balancer. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param loadbalancer_id: The unique ID of the load balancer. :type loadbalancer_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` """
python
{ "resource": "" }
q260390
ProfitBricksService.get_location
validation
def get_location(self, location_id, depth=0): """ Retrieves a single location by ID. :param location_id: The unique ID of the location. :type location_id: ``str`` """
python
{ "resource": "" }
q260391
ProfitBricksService.get_nic
validation
def get_nic(self, datacenter_id, server_id, nic_id, depth=1): """ Retrieves a NIC by its ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` :param depth: The depth of the response data. :type
python
{ "resource": "" }
q260392
ProfitBricksService.list_nics
validation
def list_nics(self, datacenter_id, server_id, depth=1): """ Retrieves a list of all NICs bound to the specified server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param depth: The depth of the response data. :type depth: ``int``
python
{ "resource": "" }
q260393
ProfitBricksService.delete_nic
validation
def delete_nic(self, datacenter_id, server_id, nic_id): """ Removes a NIC from the server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` """
python
{ "resource": "" }
q260394
ProfitBricksService.create_nic
validation
def create_nic(self, datacenter_id, server_id, nic): """ Creates a NIC on the specified server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic: A NIC dict. :type nic: ``dict`` """ data
python
{ "resource": "" }
q260395
ProfitBricksService.update_nic
validation
def update_nic(self, datacenter_id, server_id, nic_id, **kwargs): """ Updates a NIC with the parameters provided. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_id: ``str`` """ data = {} for attr, value
python
{ "resource": "" }
q260396
ProfitBricksService.get_request
validation
def get_request(self, request_id, status=False): """ Retrieves a single request by ID. :param request_id: The unique ID of the request. :type request_id: ``str`` :param status: Retreive the full status
python
{ "resource": "" }
q260397
ProfitBricksService.get_server
validation
def get_server(self, datacenter_id, server_id, depth=1): """ Retrieves a server by its ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param depth: The depth of the response data. :type depth: ``int`` """
python
{ "resource": "" }
q260398
ProfitBricksService.list_servers
validation
def list_servers(self, datacenter_id, depth=1): """ Retrieves a list of all servers bound to the specified data center. :param datacenter_id: The unique ID of the data center.
python
{ "resource": "" }
q260399
ProfitBricksService.delete_server
validation
def delete_server(self, datacenter_id, server_id): """ Removes the server from your data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type
python
{ "resource": "" }