code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def _handle_produce_response(self, node_id, send_time, batches, response): log.debug('Parsing produce response: %r', response) if response: batches_by_partition = dict([(batch.topic_partition, batch) for batch in batches]) for topic, parti...
Handle a produce response.
def update(self, command=None, **kwargs): if command is None: argparser = self.argparser else: argparser = self[command] for k,v in kwargs.items(): setattr(argparser, k, v)
update data, which is usually passed in ArgumentParser initialization e.g. command.update(prog="foo")
def method_id(self, api_info): if api_info.resource_name: resource_part = '.%s' % self.__safe_name(api_info.resource_name) else: resource_part = '' return '%s%s.%s' % (self.__safe_name(api_info.name), resource_part, self.__safe_name(self.name))
Computed method name.
def get_properties(cls_def): prop_list = {prop: value for prop, value in cls_def.items() \ if 'rdf_Property' in value.get('rdf_type', "") or \ value.get('rdfs_domain')} return prop_list
cycles through the class definiton and returns all properties
def location_filter(files_with_tags, location, radius): on_location = dict() for f, tags in files_with_tags.items(): if 'GPS GPSLatitude' in tags: try: lat = convert_to_decimal(str(tags['GPS GPSLatitude'])) long = convert_to_decimal(str(tags['GPS GPSLong...
Get photos taken within the specified radius from a given point.
def _graphite_url(self, query, raw_data=False, graphite_url=None): query = escape.url_escape(query) graphite_url = graphite_url or self.reactor.options.get('public_graphite_url') url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format( base=graphite_url, query=q...
Build Graphite URL.
async def send_api(container, targetname, name, params = {}): handle = object() apiEvent = ModuleAPICall(handle, targetname, name, params = params) await container.wait_for_send(apiEvent)
Send API and discard the result
def get_by_name(self, name): rs, _ = self.list(filter=field('name').eq(name), limit=1) if len(rs) is 0: raise CDRouterError('no such device') return rs[0]
Get a device by name. :param name: Device name as string. :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device
def _handle_captcha(captcha_data, message=''): from tempfile import NamedTemporaryFile tmpf = NamedTemporaryFile(suffix='.png') tmpf.write(captcha_data) tmpf.flush() captcha_text = input('Please take a look at the captcha image "%s" and provide the code:' % tmpf.name) tmp...
Called when a captcha must be solved Writes the image to a temporary file and asks the user to enter the code. Args: captcha_data: Bytestring of the PNG captcha image. message: Optional. A message from Steam service. Returns: A string containing the solved c...
def upgrade_tools_all(call=None): if call != 'function': raise SaltCloudSystemExit( 'The upgrade_tools_all function must be called with ' '-f or --function.' ) ret = {} vm_properties = ["name"] vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.Vi...
To upgrade VMware Tools on all virtual machines present in the specified provider .. note:: If the virtual machine is running Windows OS, this function will attempt to suppress the automatic reboot caused by a VMware Tools upgrade. CLI Example: .. code-block:: bash s...
def _replace_match(m, env): s = m.group()[1:-1].strip() try: return getattr(env, s) except AttributeError: pass for r in [_replace_envvar, _replace_config, _replace_posargs]: try: return r(s, env) except ValueError: pass raise NotImplementedErr...
Given a match object, having matched something inside curly braces, replace the contents if matches one of the supported tox-substitutions.
def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None): t2t_env = rl_utils.setup_env( hparams, batch_size=hparams.real_batch_size, max_num_noops=hparams.max_num_noops ) if which_epoch_data is not None: if which_epoch_data == "last": which_epoch_data = infer_last_epoch_num(data_di...
Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env.
def customer(self): url = self._get_link('customer') if url: resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url) return Customer(resp)
Return the customer for this subscription.
def load(fp, expand_includes=True, include_position=False, include_comments=False, **kwargs): p = Parser(expand_includes=expand_includes, include_comments=include_comments, **kwargs) ast = p.load(fp) m = MapfileToDict(include_position=include_position, include_comments=i...
Load a Mapfile from an open file or file-like object. Parameters ---------- fp: file A file-like object - as with all Mapfiles this should be encoded in "utf-8" expand_includes: boolean Load any ``INCLUDE`` files in the MapFile include_comments: boolean Include or discard ...
def all_settings(self, uppercase_keys=False): d = {} for k in self.all_keys(uppercase_keys): d[k] = self.get(k) return d
Return all settings as a `dict`.
def _read_requires_python(metadata): value = metadata.dictionary.get("requires_python") if value is not None: return value if metadata._legacy: value = metadata._legacy.get("Requires-Python") if value is not None and value != "UNKNOWN": return value return ""
Read wheel metadata to know the value of Requires-Python. This is surprisingly poorly supported in Distlib. This function tries several ways to get this information: * Metadata 2.0: metadata.dictionary.get("requires_python") is not None * Metadata 2.1: metadata._legacy.get("Requires-Python") is not No...
def get_allowed(allow, disallow): if allow is None and disallow is None: return SUMO_VEHICLE_CLASSES elif disallow is None: return allow.split() else: disallow = disallow.split() return tuple([c for c in SUMO_VEHICLE_CLASSES if c not in disallow])
Normalize the given string attributes as a list of all allowed vClasses.
def _mark_quoted_email_splitlines(markers, lines): markerlist = list(markers) for i, line in enumerate(lines): if markerlist[i] != 'm': continue for pattern in SPLITTER_PATTERNS: matcher = re.search(pattern, line) if matcher: markerlist[i] = 's...
When there are headers indented with '>' characters, this method will attempt to identify if the header is a splitline header. If it is, then we mark it with 's' instead of leaving it as 'm' and return the new markers.
def method(func): attr = abc.abstractmethod(func) attr.__imethod__ = True return attr
Wrap a function as a method.
def _resolve_version(version): if version is not LATEST: return version resp = urlopen('https://pypi.python.org/pypi/setuptools/json') with contextlib.closing(resp): try: charset = resp.info().get_content_charset() except Exception: charset = 'UTF-8' r...
Resolve LATEST version
def convert_x_www_form_urlencoded_to_dict(post_data): if isinstance(post_data, str): converted_dict = {} for k_v in post_data.split("&"): try: key, value = k_v.split("=") except ValueError: raise Exception( "Invalid x_www_fo...
convert x_www_form_urlencoded data to dict Args: post_data (str): a=1&b=2 Returns: dict: {"a":1, "b":2}
def tag_reachable_scripts(cls, scratch): if getattr(scratch, 'hairball_prepared', False): return reachable = set() untriggered_events = {} for script in cls.iter_scripts(scratch): if not isinstance(script, kurt.Comment): starting_type = cls.script_...
Tag each script with attribute reachable. The reachable attribute will be set false for any script that does not begin with a hat block. Additionally, any script that begins with a 'when I receive' block whose event-name doesn't appear in a corresponding broadcast block is marked as unr...
def operate_on(self, when=None, apply=False, **kwargs): pzone = self.get(**kwargs) now = timezone.now() if when is None: when = now if when < now: histories = pzone.history.filter(date__lte=when) if histories.exists(): pzone.data = hist...
Do something with operate_on. If apply is True, all transactions will be applied and saved via celery task.
def KillOldFlows(self): if not self.IsRunning(): return False start_time = self.Get(self.Schema.LAST_RUN_TIME) lifetime = self.Get(self.Schema.CRON_ARGS).lifetime elapsed = rdfvalue.RDFDatetime.Now() - start_time if lifetime and elapsed > lifetime: self.StopCurrentRun() stats_colle...
Disable cron flow if it has exceeded CRON_ARGS.lifetime. Returns: bool: True if the flow is was killed.
def response(code, body='', etag=None, last_modified=None, expires=None, **kw): if etag is not None: if not (etag[0] == '"' and etag[-1] == '"'): etag = '"%s"' % etag kw['etag'] = etag if last_modified is not None: kw['last_modified'] = datetime_to_httpdate(last_modified) ...
Helper to build an HTTP response. Parameters: code : An integer status code. body : The response body. See `Response.__init__` for details. etag : A value for the ETag header. Double quotes will be added unless the string starts and ends with a double quote. last_modified...
def parse_footnotes(document, xmlcontent): footnotes = etree.fromstring(xmlcontent) document.footnotes = {} for footnote in footnotes.xpath('.//w:footnote', namespaces=NAMESPACES): _type = footnote.attrib.get(_name('{{{w}}}type'), None) if _type in ['separator', 'continuationSeparator', 'con...
Parse footnotes document. Footnotes are defined in file 'footnotes.xml'
def cancel(self): try: del self._protocol._consumers[self.queue] except (KeyError, AttributeError): pass try: del self._protocol.factory._consumers[self.queue] except (KeyError, AttributeError): pass self._running = False yi...
Cancel the consumer and clean up resources associated with it. Consumers that are canceled are allowed to finish processing any messages before halting. Returns: defer.Deferred: A deferred that fires when the consumer has finished processing any message it was in the mid...
def info(self, msg=None, *args, **kwargs): return self._log(logging.INFO, msg, args, kwargs)
Similar to DEBUG but at INFO level.
def gender(self): element = self._first('NN') if element: if re.search('([m|f|n)])\.', element, re.U): genus = re.findall('([m|f|n)])\.', element, re.U)[0] return genus
Tries to scrape the gender for a given noun from leo.org.
def _shutdown_cherrypy(self): if cherrypy.engine.state == cherrypy.engine.states.STARTED: threading.Timer(1, cherrypy.engine.exit).start()
Shutdown cherrypy in one second, if it's running
def class_result(classname): def wrap_errcheck(result, func, arguments): if result is None: return None return classname(result) return wrap_errcheck
Errcheck function. Returns a function that creates the specified class.
def n_sections(neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder): return sum(1 for _ in iter_sections(neurites, iterator_type=iterator_type, neurite_filter=is_type(neurite_type)))
Number of sections in a collection of neurites
def stop_change(self): self.logger.info("Dimmer %s stop_change", self.device_id) self.hub.direct_command(self.device_id, '18', '00') success = self.hub.check_success(self.device_id, '18', '00') if success: self.logger.info("Dimmer %s stop_change: Light stopped changing succes...
Stop changing light level manually
def disable_all(self, disable): commands = ['ENBH 0', 'ENBL 0', 'MODL 0' ] command_string = '\n'.join(commands) print_string = '\n\t' + command_string.replace('\n', '\n\t') logging.info(print_string) if disable: ...
Disables all modulation and outputs of the Standford MW func. generator
def tcpip(self, port: int or str = 5555) -> None: self._execute('-s', self.device_sn, 'tcpip', str(port))
Restart adb server listening on TCP on PORT.
def parent(self): try: return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True) except KeyError: raise ResourceMissing('%s has no parent resource' % self)
Return parent resource :rtype: Resource :raises ResourceNotFound: parent resource doesn't exists :raises ResourceMissing: parent resource is not defined
def from_filename(cls, filename): if not filename: logger.error('No filename specified') return None if not os.path.exists(filename): logger.error("Err: File '%s' does not exist", filename) return None if os.path.isdir(filename): logger...
Class constructor using the path to the corresponding mp3 file. The metadata will be read from this file to create the song object, so it must at least contain valid ID3 tags for artist and title.
def next_batch(self): is_success, results = AtlasRequest( url_path=self.atlas_url, user_agent=self._user_agent, server=self.server, verify=self.verify, ).get() if not is_success: raise APIResponseError(results) self.total_count ...
Querying API for the next batch of objects and store next url and batch of objects.
def iget(self, irods_path, attempts=1, pause=15): if attempts > 1: cmd = cmd = lstrip(cmd) cmd = cmd.format(attempts, irods_path, pause) self.add(cmd) else: self.add('iget -v "{}"'.format(irods_path))
Add an iget command to retrieve a file from iRODS. Parameters ---------- irods_path: str Filepath which should be fetched using iget attempts: int (default: 1) Number of retries, if iRODS access fails pause: int (default: 15) ...
def handle_bad_update(operation, ret): print("Error " + operation) sys.exit('Return code: ' + str(ret.status_code) + ' Error: ' + ret.text)
report error for bad update
def from_csv(cls, path): with open(path) as f: fields = map(float, next(f).split(',')) if len(fields) == 3: return u.Quantity([[fields[0], 0, 0], [0, fields[1], 0], [0, 0, fields[2]]], unit=u.nanometers) elif l...
Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters ---------- path : str ...
def cal(self, opttype, strike, exp1, exp2): assert pd.Timestamp(exp1) < pd.Timestamp(exp2) _row1 = _relevant_rows(self.data, (strike, exp1, opttype,), "No key for {} strike {} {}".format(exp1, strike, opttype)) _row2 = _relevant_rows(self.data, (strike, exp2, opttype,), ...
Metrics for evaluating a calendar spread. Parameters ------------ opttype : str ('call' or 'put') Type of option on which to collect data. strike : numeric Strike price. exp1 : date or date str (e.g. '2015-01-01') Earlier expiration date. ...
def get_django_settings(cls, name, default=None): if hasattr(cls, '__django_settings__'): return getattr(cls.__django_settings__, name, default) from django.conf import settings cls.__django_settings__ = settings return cls.get_django_settings(name)
Get params from Django settings. :param name: name of param :type name: str,unicode :param default: default value of param :type default: object :return: Param from Django settings or default.
def gendict(cls, *args, **kwargs): gk = cls.genkey return dict((gk(k), v) for k, v in dict(*args, **kwargs).items())
Pre-translated key dictionary constructor. See :type:`dict` for more info. :returns: dictionary with uppercase keys :rtype: dict
def get_contacts_of_client_per_page(self, client_id, per_page=1000, page=1): return self._get_resource_per_page( resource=CONTACTS, per_page=per_page, page=page, params={'client_id': client_id}, )
Get contacts of client per page :param client_id: the client id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
def get_uint32(self): token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') value = long(token.value) if ...
Read the next token and interpret it as a 32-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int
def print_typedefs(self, w=0, **print3opts): for k in _all_kinds: t = [(self._prepr(a), v) for a, v in _items(_typedefs) if v.kind == k and (v.both or self._code_)] if t: self._printf('%s%*d %s type%s: basicsize, itemsize, _len_(), _refs()', ...
Print the types and dict tables. *w=0* -- indentation for each line *print3options* -- print options, as in Python 3.0
def disable_code_breakpoint(self, dwProcessId, address): p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.disable(p, None)
Disables the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint} L{enable_one_shot_code_breakpoint}, L{erase_code_breakpoint}, @type dwP...
def is_numeric(value, minimum = None, maximum = None, **kwargs): try: value = validators.numeric(value, minimum = minimum, maximum = maximum, **kwargs) ex...
Indicate whether ``value`` is a numeric value. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to...
def _glob(filenames): if isinstance(filenames, string_types): filenames = [filenames] matches = [] for name in filenames: matched_names = glob(name) if not matched_names: matches.append(name) else: matches.extend(matched_names) return matches
Glob a filename or list of filenames but always return the original string if the glob didn't match anything so URLs for remote file access are not clobbered.
async def send_message(self, message, **kwargs): if 'end' in kwargs: warnings.warn('"end" argument is deprecated, use ' '"stream.send_trailing_metadata" explicitly', stacklevel=2) end = kwargs.pop('end', False) assert not kwargs, kw...
Coroutine to send message to the client. If server sends UNARY response, then you should call this coroutine only once. If server sends STREAM response, then you can call this coroutine as many times as you need. :param message: message object
def _QueryHash(self, digest): if not self._url: self._url = '{0:s}://{1:s}:{2:d}/file/find'.format( self._protocol, self._host, self._port) request_data = {self.lookup_hash: digest} try: json_response = self.MakeRequestAndDecodeJSON( self._url, 'POST', data=request_data) ...
Queries the Viper Server for a specfic hash. Args: digest (str): hash to look up. Returns: dict[str, object]: JSON response or None on error.
def draw(self): colors = resolve_colors(len(self.support_)) if self._mode == BALANCE: self.ax.bar( np.arange(len(self.support_)), self.support_, color=colors, align='center', width=0.5 ) else: bar_width = 0.35 labels...
Renders the class balance chart on the specified axes from support.
def similar(self, similarity): pattern = Pattern(self.path) pattern.similarity = similarity return pattern
Returns a new Pattern with the specified similarity threshold
def max_knob_end_distance(self): return max([distance(self.knob_end, h) for h in self.hole])
Maximum distance between knob_end and each of the hole side-chain centres.
def prep_hla(work_dir, sample, calls, hlas, normal_bam, tumor_bam): work_dir = utils.safe_makedir(os.path.join(work_dir, sample, "inputs")) hla_file = os.path.join(work_dir, "%s-hlas.txt" % sample) with open(calls) as in_handle: with open(hla_file, "w") as out_handle: next(in_handle) ...
Convert HLAs into ABSOLUTE format for use with LOHHLA. LOHHLA hard codes names to hla_a, hla_b, hla_c so need to move
def AuthorizeUser(self, user, subject): user_set = self.authorized_users.setdefault(subject, set()) user_set.add(user)
Allow given user access to a given subject.
def _vars(ftype, name, *dims): shape = _dims2shape(*dims) objs = list() for indices in itertools.product(*[range(i, j) for i, j in shape]): objs.append(_VAR[ftype](name, indices)) return farray(objs, shape, ftype)
Return a new farray filled with Boolean variables.
def delete(self, reason=None): response = API.delete_user(self.api_token, self.password, reason=reason, in_background=0) _fail_if_contains_errors(response)
Delete the user's account from Todoist. .. warning:: You cannot recover the user after deletion! :param reason: The reason for deletion. :type reason: str >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> user.delete() ...
def use_plenary_composition_view(self): self._object_views['composition'] = PLENARY for session in self._get_provider_sessions(): try: session.use_plenary_composition_view() except AttributeError: pass
Pass through to provider CompositionLookupSession.use_plenary_composition_view
def more_search(self, more_page): next_page = self.current_page + 1 top_page = more_page + self.current_page for page in range(next_page, (top_page + 1)): start = "start={0}".format(str((page - 1) * 10)) url = "{0}{1}&{2}".format(self.google, self.query, start) ...
Method to add more result to an already exist result. more_page determine how many result page should be added to the current result.
def cli(env, identifier): mgr = SoftLayer.ObjectStorageManager(env.client) credential_list = mgr.list_credential(identifier) table = formatting.Table(['id', 'password', 'username', 'type_name']) for credential in credential_list: table.add_row([ credential['id'], credenti...
Retrieve credentials used for generating an AWS signature. Max of 2.
def _populate_bunch_with_element(element): if 'value' in element.attrib: return element.get('value') current_bunch = Bunch() if element.get('id'): current_bunch['nextra_element_id'] = element.get('id') for subelement in element.getchildren(): current_bunch[subelement.tag] = _popu...
Helper function to recursively populates a Bunch from an XML tree. Returns leaf XML elements as a simple value, branch elements are returned as Bunches containing their subelements as value or recursively generated Bunch members.
def u(data, bits=None, endian=None, target=None): return globals()['u%d' % _get_bits(bits, target)](data, endian=endian, target=target)
Unpack a signed pointer for a given target. Args: data(bytes): The data to unpack. bits(:class:`pwnypack.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`): Ov...
def checksum(digits, scale): chk_nbr = 11 - (sum(map(operator.mul, digits, scale)) % 11) if chk_nbr == 11: return 0 return chk_nbr
Calculate checksum of Norwegian personal identity code. Checksum is calculated with "Module 11" method using a scale. The digits of the personal code are multiplied by the corresponding number in the scale and summed; if remainder of module 11 of the sum is less than 10, checksum is the remainder. ...
def pathparse(value, sep=os.pathsep, os_sep=os.sep): escapes = [] normpath = ntpath.normpath if os_sep == '\\' else posixpath.normpath if '\\' not in (os_sep, sep): escapes.extend(( ('\\\\', '<ESCAPE-ESCAPE>', '\\'), ('\\"', '<ESCAPE-DQUOTE>', '"'), ('\\\'', '<ESC...
Get enviroment PATH directories as list. This function cares about spliting, escapes and normalization of paths across OSes. :param value: path string, as given by os.environ['PATH'] :type value: str :param sep: PATH separator, defaults to os.pathsep :type sep: str :param os_sep: OS filesy...
def get(self, run_id, metric_id): run_id = self._parse_run_id(run_id) query = self._build_query(run_id, metric_id) row = self._read_metric_from_db(metric_id, run_id, query) metric = self._to_intermediary_object(row) return metric
Read a metric of the given id and run. The returned object has the following format (timestamps are datetime objects). .. code:: {"steps": [0,1,20,40,...], "timestamps": [timestamp1,timestamp2,timestamp3,...], "values": [0,1 2,3,4,5,6,...], "na...
def _print_details(extra=None): def print_node_handler(name, node, depth): line = "{0}{1} {2} ({3}:{4})".format(depth, (" " * depth), name, node.line, ...
Return a function that prints node details.
def get_server_alerts(call=None, for_output=True, **kwargs): for key, value in kwargs.items(): servername = "" if key == "servername": servername = value creds = get_creds() clc.v2.SetCredentials(creds["user"], creds["password"]) alerts = clc.v2.Server(servername).Alerts() ...
Return a list of alerts from CLC as reported by their infra
def ajax_login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponse(content='Successful login', ...
Accept a POST request to login. :param request: `django.http.HttpRequest` object, containing mandatory parameters username and password required.
def update_pipe_channel(self, uid, channel_name, label): pipe_group_name = _form_pipe_channel_name(channel_name) if self.channel_layer: current = self.channel_maps.get(uid, None) if current != pipe_group_name: if current: async_to_sync(self.cha...
Update this consumer to listen on channel_name for the js widget associated with uid
def indent(indent_str=None): def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { Indent: inst.layout_handler_indent, Dedent: inst.layout_handler_dedent, Newline: inst.layout_handler_newline, OptionalNewline: inst.layout_h...
An example indentation ruleset.
def _load_torrents_directory(self): r = self._req_lixian_get_id(torrent=True) self._downloads_directory = self._load_directory(r['cid'])
Load torrents directory If it does not exist yet, this request will cause the system to create one
def get_parent(self, log_info): if self.data.get('scope', 'log') == 'log': if log_info.scope_type != 'projects': raise ValueError("Invalid log subscriber scope") parent = "%s/%s" % (log_info.scope_type, log_info.scope_id) elif self.data['scope'] == 'project': ...
Get the parent container for the log sink
def _generate_cpu_stats(): cpu_name = urwid.Text("CPU Name N/A", align="center") try: cpu_name = urwid.Text(get_processor_name().strip(), align="center") except OSError: logging.info("CPU name not available") return [urwid.Text(('bold text', "CPU Detected"), ...
Read and display processor name
def root_manifest_id(self, root_manifest_id): if root_manifest_id is not None and len(root_manifest_id) > 32: raise ValueError("Invalid value for `root_manifest_id`, length must be less than or equal to `32`") self._root_manifest_id = root_manifest_id
Sets the root_manifest_id of this UpdateCampaignPutRequest. :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest. :type: str
def get(self, name): return self.prepare_model(self.client.api.inspect_image(name))
Gets an image. Args: name (str): The name of the image. Returns: (:py:class:`Image`): The image. Raises: :py:class:`docker.errors.ImageNotFound` If the image does not exist. :py:class:`docker.errors.APIError` If t...
def create_permission(self): return Permission( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of permission services facade.
def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''): _, ext = os.path.splitext(filename) if ext != '.png': filename += '.png' gnuplot_cmds = \ scr = _GnuplotScriptTemp(gnuplot_cmds) data = _GnuplotDataTemp(x, y) args_dict = { 'filename': filename, 'filename_d...
Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label (str): x-axis label. y_label (str): y-axis label.
def get_idle_pc_prop(self): is_running = yield from self.is_running() was_auto_started = False if not is_running: yield from self.start() was_auto_started = True yield from asyncio.sleep(20) log.info('Router "{name}" [{id}] has started calculating Idle...
Gets the idle PC proposals. Takes 1000 measurements and records up to 10 idle PC proposals. There is a 10ms wait between each measurement. :returns: list of idle PC proposal
def Dump(self): prefs_file = open(self.prefs_path, 'w') for n in range(0,len(self.prefs)): if len(list(self.prefs.items())[n]) > 1: prefs_file.write(str(list(self.prefs.items())[n][0]) + ' = ' + str(list(self.prefs.items())[n][1]) + '\n') ...
Dumps the current prefs to the preferences.txt file
def get_sum(qs, field): sum_field = '%s__sum' % field qty = qs.aggregate(Sum(field))[sum_field] return qty if qty else 0
get sum for queryset. ``qs``: queryset ``field``: The field name to sum.
def read_configs(__pkg: str, __name: str = 'config', *, local: bool = True) -> ConfigParser: configs = get_configs(__pkg, __name) if local: localrc = path.abspath('.{}rc'.format(__pkg)) if path.exists(localrc): configs.append(localrc) cfg = ConfigParser(converter...
Process configuration file stack. We export the time parsing functionality of ``jnrbase`` as custom converters for :class:`configparser.ConfigParser`: =================== =========================================== Method Function =================== ===============================...
def anonymize(self, value): assert isinstance(value, bool) if self._anonymize != value: self.dirty = True self._anonymize = value return self.recipe
Should this recipe be anonymized
def _backup_bytes(target, offset, length): click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format( l=length, offset=offset, file=target)) with open(target, 'r+b') as f: f.seek(offset) with open(target + '.bytes_backup', 'w+b') as b: for _ in ...
Read bytes from one file and write it to a backup file with the .bytes_backup suffix
def getAmbientThreshold(self): command = '$GO' threshold = self.sendCommand(command) if threshold[0] == 'NK': return 0 else: return float(threshold[1])/10
Returns the ambient temperature threshold in degrees Celcius, or 0 if no Threshold is set
def send_is_typing(self, peer_jid: str, is_typing: bool): if self.is_group_jid(peer_jid): return self._send_xmpp_element(chatting.OutgoingGroupIsTypingEvent(peer_jid, is_typing)) else: return self._send_xmpp_element(chatting.OutgoingIsTypingEvent(peer_jid, is_typing))
Updates the 'is typing' status of the bot during a conversation. :param peer_jid: The JID that the notification will be sent to :param is_typing: If true, indicates that we're currently typing, or False otherwise.
def parse_bytes(self, bytestr, isfinal=True): with self._context(): self.filename = None self.p.Parse(bytestr, isfinal) return self._root
Parse a byte string. If the string is very large, split it in chuncks and parse each chunk with isfinal=False, then parse an empty chunk with isfinal=True.
def observe(self, ob): option = Option() option.number = defines.OptionRegistry.OBSERVE.number option.value = ob self.del_option_by_number(defines.OptionRegistry.OBSERVE.number) self.add_option(option)
Add the Observe option. :param ob: observe count
def stage_import_from_filesystem(self, filepath): schema = ImportSchema() resp = self.service.post(self.base, params={'path': filepath}) return self.service.decode(schema, resp)
Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object
def get_notmuch_setting(self, section, key, fallback=None): value = None if section in self._notmuchconfig: if key in self._notmuchconfig[section]: value = self._notmuchconfig[section][key] if value is None: value = fallback return value
look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the sp...
def get_consumer_groups(self, consumer_group_id=None, names_only=False): if consumer_group_id is None: group_ids = self.get_children("/consumers") else: group_ids = [consumer_group_id] if names_only: return {g_id: None for g_id in group_ids} consumer_o...
Get information on all the available consumer-groups. If names_only is False, only list of consumer-group ids are sent. If names_only is True, Consumer group offset details are returned for all consumer-groups or given consumer-group if given in dict format as:- { '...
def backup_progress(self): epoch_time = int(time.time() * 1000) if self.deploymentType == 'Cloud': url = self._options['server'] + '/rest/obm/1.0/getprogress?_=%i' % epoch_time else: logging.warning( 'This functionality is not available in Server version')...
Return status of cloud backup as a dict. Is there a way to get progress for Server version?
def chmod_r(root: str, permission: int) -> None: os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(os.path.join(dirpath, d), permission) for f in filenames: os.chmod(os.path.join(dirpath, f), permission)
Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR``
def requirements(filename): with open(filename) as f: return [x.strip() for x in f.readlines() if x.strip()]
Reads requirements from a file.
def to_feature_reports(self, debug=False): rest = self.to_string() seq = 0 out = [] while rest: this, rest = rest[:7], rest[7:] if seq > 0 and rest: if this != b'\x00\x00\x00\x00\x00\x00\x00': this += yubico_util.chr_byte(yubike...
Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey.
def run_step(self): rewriter = StreamRewriter(self.context.iter_formatted_strings) super().run_step(rewriter)
Do the file in-out rewrite.
def publish(self, topic, data, defer=None): if defer is None: self.send(nsq.publish(topic, data)) else: self.send(nsq.deferpublish(topic, data, defer))
Publish a message to the given topic over tcp. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6)
def ip_unnumbered(self, **kwargs): kwargs['ip_donor_interface_name'] = kwargs.pop('donor_name') kwargs['ip_donor_interface_type'] = kwargs.pop('donor_type') kwargs['delete'] = kwargs.pop('delete', False) callback = kwargs.pop('callback', self._callback) valid_int_types = ['gigabi...
Configure an unnumbered interface. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). name (str): Name of interface id. (For interface: 1/0/5, 1/0/10 etc). delete (bool): True is the IP address is added and F...
def timestampFormat(self, timestampFormat): if not isinstance(timestampFormat, str): raise TypeError('not of type unicode') self._timestampFormat = timestampFormat
Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime Raises: AssertionError: if timestampFormat is not of type unicode. Args: timestampFormat (unicode): assign timestampFormat to _timestampFormat. Formatting string for c...