positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def list_packets(self, name=None, start=None, stop=None, page_size=500, descending=False): """ Reads packet information between the specified start and stop time. Packets are sorted by generation time and sequence number. :param ~datetime.datetime start: Minimum generation time...
Reads packet information between the specified start and stop time. Packets are sorted by generation time and sequence number. :param ~datetime.datetime start: Minimum generation time of the returned packets (inclusive) :param ~datetime.datetime...
def delete(self, ids): """ Method to delete equipments by their id's :param ids: Identifiers of equipments :return: None """ url = build_uri_with_ids('api/v4/equipment/%s/', ids) return super(ApiV4Equipment, self).delete(url)
Method to delete equipments by their id's :param ids: Identifiers of equipments :return: None
def logical_chassis_fwdl_status_output_overall_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status") config = logical_chassis_fwdl_status output = ET.SubElement(logical_chas...
Auto Generated Code
def generate_pdf(self): """Generate a PDF from the displayed content.""" printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setPageSize(QtGui.QPrinter.A4) printer.setColorMode(QtGui.QPrinter.Color) printer.setOutputFormat(QtGui.QPrinter.PdfFormat) report_path...
Generate a PDF from the displayed content.
def update(self): """Update |KB| based on |EQB| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb(10.0) >>> tind.value = 10.0 >>> derived.kb.update() >>> derived.kb kb(100.0) """ con = self.subpars.pars.contr...
Update |KB| based on |EQB| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb(10.0) >>> tind.value = 10.0 >>> derived.kb.update() >>> derived.kb kb(100.0)
def list(self, path=None, with_metadata=False, include_partitions=False): '''Get a list of all of bundle files in the cache. Does not return partition files''' import json sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix l = {} for e in self.bucket.list(...
Get a list of all of bundle files in the cache. Does not return partition files
def try_get_dn_string(subject, shorten=False): """ Returns DN as a string :param subject: :param shorten: :return: """ try: from cryptography.x509.oid import NameOID from cryptography.x509 import ObjectIdentifier oid_names = { getattr(NameOID, 'COMMON_NAME...
Returns DN as a string :param subject: :param shorten: :return:
def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' parser = StringParser(self.langu...
Find the end of the region started with start and end markers
def ignore_rules_for_url(spider, url): """ Returns a list of ignore rules from the given spider, that are relevant to the given URL. """ ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {} return itertools.chain.from_iterable( rule_list for url_glob, rule_list ...
Returns a list of ignore rules from the given spider, that are relevant to the given URL.
def started_tasks(self, task_registry_id=None, task_cls=None): """ Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will...
Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will be consists of this subclass only :return: None or WTask or tuple...
def sanitize_text(text): """Make a safe representation of a string. Note: the `\s` special character matches any whitespace character. This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace).""" # First replace characters that have specific effects with their repr # text = re.sub("(\s...
Make a safe representation of a string. Note: the `\s` special character matches any whitespace character. This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace).
def normaliseWV(wV, normFac=1.0): """ make char probs divisible by one """ f = sum(wV) / normFac return [ i/f for i in wV ]
make char probs divisible by one
def DeviceFactory(id, lib=None): """Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ lib = lib or Library() if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP: return DeviceGroup(id, lib=lib) re...
Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance.
def start(self, positionals=None): '''start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user. '''...
start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user.
def dsort(fname, order, has_header=True, frow=0, ofname=None): r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the com...
r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the comma-separated values file to sort has column ...
def _mib_register(ident, value, the_mib, unresolved): """Internal function used to register an OID and its name in a MIBDict""" if ident in the_mib or ident in unresolved: return ident in the_mib resval = [] not_resolved = 0 for v in value: if _mib_re_integer.match(v): re...
Internal function used to register an OID and its name in a MIBDict
def find_donor_catchments(self, include_subject_catchment='auto'): """ Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` ...
Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` is set manually. The results are stored in :attr:`.donor_catchments`. The (lis...
def sample(self, multiplicity): r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """ if self._n is None: return self._uniform_phi(multiplicity) # Since the flow PDF does not...
r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles.
def init_db(drop_all=False, bind=engine): """Initialize the database, optionally dropping existing tables.""" try: if drop_all: Base.metadata.drop_all(bind=bind) Base.metadata.create_all(bind=bind) except OperationalError as err: msg = 'password authentication failed for ...
Initialize the database, optionally dropping existing tables.
def _populate_stub(self, name, stub, table): """ Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype:...
Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype: str
def connect_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0): """Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix w...
Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__...
def validate_bucket(self): """ Do a quick check to see if the s3 bucket is valid :return: """ s3_check_cmd = "aws s3 ls s3://{} --profile '{}' --region '{}'".format(self.bucket_name, self.aws_project, ...
Do a quick check to see if the s3 bucket is valid :return:
def get_available_symbols(**kwargs): """ MOVED to iexfinance.refdata.get_symbols """ import warnings warnings.warn(WNG_MSG % ("get_available_symbols", "refdata.get_symbols")) _ALL_SYMBOLS_URL = "https://api.iextrading.com/1.0/ref-data/symbols" handler = _IEXBase(**kwargs) respons...
MOVED to iexfinance.refdata.get_symbols
def flush_and_refresh(self, index): """Flush and refresh one or more indices. .. warning:: Do not call this method unless you know what you are doing. This method is only intended to be called during tests. """ self.client.indices.flush(wait_if_ongoing=True, index...
Flush and refresh one or more indices. .. warning:: Do not call this method unless you know what you are doing. This method is only intended to be called during tests.
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element...
Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element
def destroyCommit(self, varBind, **context): """Destroy Managed Object Instance. Implements the second of the multi-step workflow similar to the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the second phase is to actually remove requested Managed Object ...
Destroy Managed Object Instance. Implements the second of the multi-step workflow similar to the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the second phase is to actually remove requested Managed Object Instance from the MIB tree. When multiple Managed Object...
async def serialize(self, native=False): ''' Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False`` ...
Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False``
def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None): ''' Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. p...
Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. password The password used to login to the host. protocol Optionally set to alter...
def isinstance(self, class_or_string): """ Check whether the node is a instance of `class_or_string`. Unlinke the standard isinstance builtin, the method accepts either a class or a string. In the later case, the string is compared with self.__class__.__name__ (case insensitive). ...
Check whether the node is a instance of `class_or_string`. Unlinke the standard isinstance builtin, the method accepts either a class or a string. In the later case, the string is compared with self.__class__.__name__ (case insensitive).
def launch_process(self, command): # type: (Union[bytes,text_type])->None """* What you can do - It starts process and keep it. """ if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self....
* What you can do - It starts process and keep it.
def read(self, size = None): """Reads a given number of characters from the response. :param size: The number of characters to read, or "None" to read the entire response. :type size: ``integer`` or "None" """ r = self._buffer self._buffer = b'' if s...
Reads a given number of characters from the response. :param size: The number of characters to read, or "None" to read the entire response. :type size: ``integer`` or "None"
def valid_backbone_bond_lengths(self, atol=0.1): """True if all backbone bonds are within atol Angstroms of the expected distance. Notes ----- Ideal bond lengths taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of ...
True if all backbone bonds are within atol Angstroms of the expected distance. Notes ----- Ideal bond lengths taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of Protein Structure. New York: Springer-Verlag, 1979. ...
def run_job(self, name): ''' Run a schedule job now ''' data = self._get_schedule().get(name, {}) if 'function' in data: func = data['function'] elif 'func' in data: func = data['func'] elif 'fun' in data: func = data['fun'] ...
Run a schedule job now
def runBasic(noiseLevel=None, profile=False): """ Runs a basic experiment on continuous locations, learning a few locations on four basic objects, and inferring one of them. This experiment is mostly used for testing the pipeline, as the learned locations are too random and sparse to actually perform inferen...
Runs a basic experiment on continuous locations, learning a few locations on four basic objects, and inferring one of them. This experiment is mostly used for testing the pipeline, as the learned locations are too random and sparse to actually perform inference. Parameters: ---------------------------- @p...
def _insert_data(self, name, value, timestamp, interval, config, **kwargs): '''Helper to insert data into sql.''' conn = self._client.connect() if not self._update_data(name, value, timestamp, interval, config, conn): try: kwargs = { 'name' : name, 'interval' : in...
Helper to insert data into sql.
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, m...
Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, max, or result fields are blank, the row value is ignored here.
def touch(fpath, times=None, verbose=True): r""" Creates file if it doesnt exist Args: fpath (str): file path times (None): verbose (bool): Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> fpath = '?' >>> times = None ...
r""" Creates file if it doesnt exist Args: fpath (str): file path times (None): verbose (bool): Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> fpath = '?' >>> times = None >>> verbose = True >>> result = ...
def get_channel_names(self): """Get list of channel names. Raises a warning if the names are not unique.""" names_s, names_n = self.channel_names_s, self.channel_names_n # Figure out which channel names to use if self._channel_naming == '$PnS': channel_names, channel_names_a...
Get list of channel names. Raises a warning if the names are not unique.
def max(self): """ Compute the max across records. """ return self._constructor(self.values.max(axis=self.baseaxes, keepdims=True))
Compute the max across records.
def run(self): # Thread for receiving data from pilight """Receiver thread function called on Client.start().""" logging.debug('Pilight receiver thread started') if not self.callback: raise RuntimeError('No callback function set, cancel readout thread') def handle_messages(...
Receiver thread function called on Client.start().
def load_config(cls): """ Load global and local configuration files and update if needed.""" config_file = os.path.expanduser(cls.home_config) global_conf = cls.load(config_file, 'global') cls.load(cls.local_config, 'local') # update global configuration if needed cls.upd...
Load global and local configuration files and update if needed.
def get_packages(): """ Returns the packages used for HaTeMiLe for Python. :return: The packages used for HaTeMiLe for Python. :rtype: list(str) """ packages = find_packages(exclude=['tests']) packages.append('') packages.append('js') packages.append(LOCALES_DIRECTORY) for dir...
Returns the packages used for HaTeMiLe for Python. :return: The packages used for HaTeMiLe for Python. :rtype: list(str)
def get_symbol(x): """Retrieve recorded computation history as `Symbol`. Parameters ---------- x : NDArray Array representing the head of computation graph. Returns ------- Symbol The retrieved Symbol. """ hdl = SymbolHandle() check_call(_LIB.MXAutogradGetSymbol...
Retrieve recorded computation history as `Symbol`. Parameters ---------- x : NDArray Array representing the head of computation graph. Returns ------- Symbol The retrieved Symbol.
def verification_start( self, client, mode=None, verification_speed=None, row_doubling="off", phone_number=None, ): """ Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name ...
Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name * *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass" * *verification_speed*: (int) Allowed values: 0, 25, 50, 75, 100 * *row_doubling*: (str...
def openfile(filename, mode="rt", *args, expanduser=False, expandvars=False, makedirs=False, **kwargs): """Open filename and return a corresponding file object.""" if filename in ("-", None): return sys.stdin if "r" in mode else sys.stdout if expanduser: filename = os.path.expan...
Open filename and return a corresponding file object.
def plot(self, color='default', ret=False, ax=None): """ Generates a basic 3D visualization. :param color: Polygons color. :type color: matplotlib color, 'default' or 't' (transparent) :param ret: If True, returns the figure. It can be used to add more elem...
Generates a basic 3D visualization. :param color: Polygons color. :type color: matplotlib color, 'default' or 't' (transparent) :param ret: If True, returns the figure. It can be used to add more elements to the plot or to modify it. :type ret: bool :param ...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_retrieval_strategy' ) and self.document_retrieval_strategy is not None: _dict[ 'document_retrieval_strategy'] = self.document_retrieval_...
Return a json dictionary representing this model.
def _changeSubNos(self, path, subNos, count, action, reverse=False): """Implementation of subs add/removal handling. Args: path: file path associated with model on which work is done subNos: list of added/removed subtitle numbers count: function which accepts current...
Implementation of subs add/removal handling. Args: path: file path associated with model on which work is done subNos: list of added/removed subtitle numbers count: function which accepts current sync point's subtitle number and subNos and returns anything...
async def _readline(self, reader): """ Readline helper """ ret = await reader.readline() if len(ret) == 0 and reader.at_eof(): raise EOFError() return ret
Readline helper
def status(self): """Check power status""" vm = self.get_vm_failfast(self.config['name']) extra = self.config['extra'] parserFriendly = self.config['parserFriendly'] status_to_print = [] if extra: status_to_print = \ [["vmname", "powerstate", ...
Check power status
def encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: """ Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. ...
Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. :param data_length: Vector with sequence lengths. :param seq_len: Maximum sequence length. :return: Encoded versions of input data (data, data_length, seq_len).
def add_key_filter(self, *args): """ Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce` """ if self._input_mode == 'query': raise ValueError('Key filters are not supported in a query.') ...
Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce`
def calcTransferResistance(self, gid, seg_coords): """Precompute mapping from segment to electrode locations""" sigma = 0.3 # mS/mm # Value used in NEURON extracellular recording example ("extracellular_stim_and_rec") # rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.0...
Precompute mapping from segment to electrode locations
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters """ # VMware VMs are limited to 10 adapters if adapters > 10: raise VMwareError("Number of adapters above the maximum supp...
Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters
def do_work(self): """ Do work """ self._starttime = time.time() if not os.path.isdir(self._dir2): if self._maketarget: if self._verbose: self.log('Creating directory %s' % self._dir2) try: os.makedirs(self._di...
Do work
def managed(name, data, **kwargs): ''' Manage the device configuration given the input data structured according to the YANG models. data YANG structured data. models A list of models to be used when generating the config. profiles: ``None`` Us...
Manage the device configuration given the input data structured according to the YANG models. data YANG structured data. models A list of models to be used when generating the config. profiles: ``None`` Use certain profiles to generate the config. If not specified, wi...
async def mailed_confirm(self, **params): """Sends mail to user after offer receiveing Accepts: - cid - buyer address - price - offer_type - point - coinid """ if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists cid = params.get("cid...
Sends mail to user after offer receiveing Accepts: - cid - buyer address - price - offer_type - point - coinid
def stack(datasets): """First dataset at the bottom.""" base = datasets[0].copy() for dataset in datasets[1:]: base = base.where(dataset.isnull(), dataset) return base
First dataset at the bottom.
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This is the function called after expressions created and adde...
def split_s3_path(url: str) -> Tuple[str, str]: """Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at begin...
Split a full s3 path into the bucket name and path.
def merge(args): """ %prog merge output/*.csv > ahrd.csv Merge AHRD results, remove redundant headers, empty lines, etc. If there are multiple lines containing the same ID (first column). Then whatever comes the first will get retained. """ p = OptionParser(merge.__doc__) opts, args = p...
%prog merge output/*.csv > ahrd.csv Merge AHRD results, remove redundant headers, empty lines, etc. If there are multiple lines containing the same ID (first column). Then whatever comes the first will get retained.
def get_config_status(): ''' Get the status of the current DSC Configuration Returns: dict: A dictionary representing the status of the current DSC Configuration on the machine CLI Example: .. code-block:: bash salt '*' dsc.get_config_status ''' cmd = 'Get-Dsc...
Get the status of the current DSC Configuration Returns: dict: A dictionary representing the status of the current DSC Configuration on the machine CLI Example: .. code-block:: bash salt '*' dsc.get_config_status
def update_warning_box(self): """ updates the warning box with whatever the warning_text variable contains for this specimen """ self.warning_box.Clear() if self.warning_text == "": self.warning_box.AppendText("No Problems") else: self.warn...
updates the warning box with whatever the warning_text variable contains for this specimen
def set_preshared_key(self, new_key): """ Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None """ if self.data.get('preshared_key'): self.updat...
Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None
def _get_side2KerningGroups(self): """ Subclasses may override this method. """ found = {} for name, contents in self.items(): if name.startswith("public.kern2."): found[name] = contents return found
Subclasses may override this method.
def _make_env(resultdir=None): """Loads the env from `resultdir` if not `None` or makes a new one. An Enos environment handles all specific variables of an experiment. This function either generates a new environment or loads a previous one. If the value of `resultdir` is `None`, then this function...
Loads the env from `resultdir` if not `None` or makes a new one. An Enos environment handles all specific variables of an experiment. This function either generates a new environment or loads a previous one. If the value of `resultdir` is `None`, then this function makes a new environment and return it...
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The co...
def switch_to_plugin(self): """Switch to plugin.""" # Unmaxizime currently maximized plugin if (self.main.last_plugin is not None and self.main.last_plugin.ismaximized and self.main.last_plugin is not self): self.main.maximize_dockwidget() ...
Switch to plugin.
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking i...
def _print_image(self, line, size): """ Print formatted image """ i = 0 cont = 0 buffer = "" self._raw(S_RASTER_N) buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0) self._raw(buffer.decode('hex')) buffer = "" while i < ...
Print formatted image
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port, **kwargs): """Deletes resources for a hosting device in a plugin specific way.""" if mgmt_port is not None: try: self._cleanup_hosting_port(context, mgmt_port['id...
Deletes resources for a hosting device in a plugin specific way.
def overlay_gateway_site_extend_vlan_add(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") na...
Auto Generated Code
def process(self): """Checks whether the paths exists and updates the state accordingly.""" for path in self._paths: if os.path.exists(path): self.state.output.append((os.path.basename(path), path)) else: self.state.add_error( 'Path {0:s} does not exist'.format(str(path))...
Checks whether the paths exists and updates the state accordingly.
def exists(cls, excludes_, **filters): """ Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. ...
Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. :param excludes_: entities without this combination...
def write_configuration_file(filepath=_give_default_file_path(), overwrite=False): """Create a configuration file. Writes the current state of settings into a configuration file. .. note:: Since a file is permamently written, this function is strictly speaking not side...
Create a configuration file. Writes the current state of settings into a configuration file. .. note:: Since a file is permamently written, this function is strictly speaking not sideeffect free. Args: filepath (str): Where to write the file. The default is under both UNIX and...
def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: ...
Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7
def __get_event(self, block=True, timeout=1): """ Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and th...
Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and the next event in the event buffer is returned
def retry_on_ec2_error(self, func, *args, **kwargs): """ Call the given method with the given arguments, retrying if the call failed due to an EC2ResponseError. This method will wait at most 30 seconds and perform up to 6 retries. If the method still fails, it will propagate the ...
Call the given method with the given arguments, retrying if the call failed due to an EC2ResponseError. This method will wait at most 30 seconds and perform up to 6 retries. If the method still fails, it will propagate the error. :param func: Function to call :type func: functio...
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new results.
def get_color_mode(mode): """Convert PIL mode to ColorMode.""" name = mode.upper() name = name.rstrip('A') # Trim alpha. name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name) return getattr(ColorMode, name)
Convert PIL mode to ColorMode.
def _sanitizeFilename(filename): """Sanitizes filename for use on Windows and other brain-dead systems, by replacing a number of illegal characters with underscores.""" global _sanitize_trans out = filename.translate(_sanitize_trans) # leading dot becomes "_" if out and out[0] == '.': ou...
Sanitizes filename for use on Windows and other brain-dead systems, by replacing a number of illegal characters with underscores.
def get_state(self, force_update=False): """ Returns 0 if off and 1 if on. """ if force_update or self._state is None: return int(self.basicevent.GetBinaryState()['BinaryState']) return self._state
Returns 0 if off and 1 if on.
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" ...
Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaF...
def _ycbcr2l(self, mode): """Convert from YCbCr to L. """ self._check_modes(("YCbCr", "YCbCrA")) self.channels = [self.channels[0]] + self.channels[3:] if self.fill_value is not None: self.fill_value = [self.fill_value[0]] + self.fill_value[3:] self.mode = mo...
Convert from YCbCr to L.
def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None): """Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the location...
Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the locations in x, y, z. std : float distance in mm of the Gaussian kernel ...
def update_package(self, package_version_details, feed_id, package_name, package_version): """UpdatePackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str feed_id: :param str package_...
UpdatePackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str feed_id: :param str package_name: :param str package_version: :rtype: :class:`<Package> <azure.devops.v5_0.npm.mod...
def get_namespaces_from_names(name, all_names): """Return a generator which yields namespace objects.""" names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
Return a generator which yields namespace objects.
def get_brokendate_fx_forward_rate(self, asset_manager_id, asset_id, price_date, value_date): """ This method takes calculates broken date forward FX rate based on the passed in parameters """ self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s ...
This method takes calculates broken date forward FX rate based on the passed in parameters
def add_sideplot( ax, along, pad=0., *, grid=True, zero_line=True, arrs_to_bin=None, normalize_bin=True, ymin=0, ymax=1.1, height=0.75, c="C0" ): """Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib...
Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib AxesSubplot object The axis to add a sideplot along. along : {'x', 'y'} The dimension to add a sideplot along. pad : number (optional) Distance between axis and sideplo...
def rate_timestamp(self, rate_timestamp): """ Force the rate_timestamp to be a datetime :param rate_timestamp: :return: """ if rate_timestamp is not None: if isinstance(rate_timestamp, (str, type_check)): rate_timestamp = parse(rate_timestamp)....
Force the rate_timestamp to be a datetime :param rate_timestamp: :return:
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
Serializes mac_type and resource into a HAWK string.
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(resul...
Preserve dummy channel dim.
def reqToTxn(req): """ Transform a client request such that it can be stored in the ledger. Also this is what will be returned to the client in the reply :param req: :return: """ if isinstance(req, str): req = json.loads(req) if isinstance(req, dict): kwargs = dict( ...
Transform a client request such that it can be stored in the ledger. Also this is what will be returned to the client in the reply :param req: :return:
def load_plugins(config, plugin_kwargs): """ Discover and instantiate plugins. Args: config (dict): loaded configuration for the Gordon service. plugin_kwargs (dict): keyword arguments to give to plugins during instantiation. Returns: Tuple of 3 lists: list of names ...
Discover and instantiate plugins. Args: config (dict): loaded configuration for the Gordon service. plugin_kwargs (dict): keyword arguments to give to plugins during instantiation. Returns: Tuple of 3 lists: list of names of plugins, list of instantiated plugin objec...
def find_filepath( filename, basepaths=(os.path.curdir, DATA_PATH, BIGDATA_PATH, BASE_DIR, '~', '~/Downloads', os.path.join('/', 'tmp'), '..')): """ Given a filename or path see if it exists in any of the common places datafiles might be >>> p = find_filepath('iq_test.csv') >>> p == expand_...
Given a filename or path see if it exists in any of the common places datafiles might be >>> p = find_filepath('iq_test.csv') >>> p == expand_filepath(os.path.join(DATA_PATH, 'iq_test.csv')) True >>> p[-len('iq_test.csv'):] 'iq_test.csv' >>> find_filepath('exponentially-crazy-filename-2.7182818...
def create_comment(self, access_token, video_id, content, reply_id=None, captcha_key=None, captcha_text=None): """doc: http://open.youku.com/docs/doc?id=41 """ url = 'https://openapi.youku.com/v2/comments/create.json' data = { 'client_id': self.client_i...
doc: http://open.youku.com/docs/doc?id=41
def evpn_instance_mac_timer_max_count(self, **kwargs): """ Add "Duplicate MAC max count" under evpn instance. Args: evpn_instance_name: Instance name for evpn max_count: Duplicate MAC max count. enable (bool): If target community needs to be enabled ...
Add "Duplicate MAC max count" under evpn instance. Args: evpn_instance_name: Instance name for evpn max_count: Duplicate MAC max count. enable (bool): If target community needs to be enabled or disabled.Default:``True``. get (bool) : Get config in...
def extractArgumentsFromCallStr(callStr): """ Parse the argument string via an AST instead of the overly simple callStr.split(','). The latter incorrectly splits any string parameters that contain commas therein, like ic(1, 'a,b', 2). """ def isTuple(ele): return classname(ele) == 'Tuple...
Parse the argument string via an AST instead of the overly simple callStr.split(','). The latter incorrectly splits any string parameters that contain commas therein, like ic(1, 'a,b', 2).
def fget_object(self, bucket_name, object_name, file_path, request_headers=None, sse=None): """ Retrieves an object from a bucket and writes at file_path. Examples: minio.fget_object('foo', 'bar', 'localfile') :param bucket_name: Bucket to read object from. :param o...
Retrieves an object from a bucket and writes at file_path. Examples: minio.fget_object('foo', 'bar', 'localfile') :param bucket_name: Bucket to read object from. :param object_name: Name of the object to read. :param file_path: Local file path to save the object. :p...
def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse...
Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb