code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _calc_new_threshold(self, score): """Determine threshold based on score.""" if self.threshold_mode == 'rel': abs_threshold_change = self.threshold * score else: abs_threshold_change = self.threshold if self.lower_is_better: new_threshold = score -...
Determine threshold based on score.
def shift(self, timezone): """ Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object, modifying the Delorean object and returning the modified object. .. testsetup:: from datetime import datetime from delorea...
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object, modifying the Delorean object and returning the modified object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: ...
def __get_path_parameters(self, path): """Parses path paremeters from a URI path and organizes them by parameter. Some of the parameters may correspond to message fields, and so will be represented as segments corresponding to each subfield; e.g. first.second if the field "second" in the message field ...
Parses path paremeters from a URI path and organizes them by parameter. Some of the parameters may correspond to message fields, and so will be represented as segments corresponding to each subfield; e.g. first.second if the field "second" in the message field "first" is pulled from the path. The resu...
def add(self, dist): """ Add a distribution to the cache. :param dist: The distribution to add. """ if dist.path not in self.path: self.path[dist.path] = dist self.name.setdefault(dist.key, []).append(dist)
Add a distribution to the cache. :param dist: The distribution to add.
def do_some_work( self, work_dict): """do_some_work :param work_dict: dictionary for key/values """ label = "do_some_work" log.info(("task - {} - start " "work_dict={}") .format(label, work_dict)) ret_data = { "job_resul...
do_some_work :param work_dict: dictionary for key/values
def build_anchor_link(header_text_trimmed: str, header_duplicate_counter: str, parser: str = 'github') -> str: r"""Apply the specified slug rule to build the anchor link. :parameter header_text_trimmed: the text that needs to be transformed in a link. :p...
r"""Apply the specified slug rule to build the anchor link. :parameter header_text_trimmed: the text that needs to be transformed in a link. :parameter header_duplicate_counter: a data structure that keeps track of possible duplicate header links in order to avoid them. This is meani...
def get_object_id(obj): """Get object identifier""" try: idx = objIds.index(obj) return idx + 1 except ValueError: objIds.append(obj) return len(objIds)
Get object identifier
def EU28as(self, to='name_short'): """ Return EU28 countries in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns -------...
Return EU28 countries in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns ------- Pandas DataFrame
def compile(self, *mibnames, **options): """Transform requested and possibly referred MIBs. The *compile* method should be invoked when *MibCompiler* object is operational meaning at least *sources* are specified. Once called with a MIB module name, *compile* will: * fetch ASN...
Transform requested and possibly referred MIBs. The *compile* method should be invoked when *MibCompiler* object is operational meaning at least *sources* are specified. Once called with a MIB module name, *compile* will: * fetch ASN.1 MIB module with given name by calling *sources* ...
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.v...
Receives a value for the object and some context on its source.
def p_param_substitution(self, p): 'param_substitution : ID EQUALS rvalue' p[0] = (p[1], p[3]) p.set_lineno(0, p.lineno(1))
param_substitution : ID EQUALS rvalue
def btc_make_p2wpkh_address( pubkey_hex ): """ Make a p2wpkh address from a hex pubkey """ pubkey_hex = keylib.key_formatting.compress(pubkey_hex) hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex')) return segwit_addr_encode(hash160_bin)
Make a p2wpkh address from a hex pubkey
def main(): """ Function for PDA to CNF Operation :type argv: list :param argv: Parameters """ if len(argv) < 3: print 'Usage for getting CFG: %s CFG_fileA CFG ' % argv[0] print 'Usage for getting STR: %s CFG_fileA STR ' \ 'Optimize[0 or 1] splitstring[0 or 1] ' % a...
Function for PDA to CNF Operation :type argv: list :param argv: Parameters
def get_netapp_elem(self, netapp_api=None, sub_element=None): """ Retrieve netapp elem """ netapp_data = self.server.invoke_elem(netapp_api) if netapp_data.results_status() == 'failed': self.log.error( 'While using netapp API failed to retrieve ' ...
Retrieve netapp elem
def parse_tables(self): """ Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables. """ tables = self._parse_tables(self._build_doc(), self.match, self.attrs) return (self._parse_thead_tbody_tfoo...
Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables.
def add_ipv6addr(self, ipv6addr): """Add an IPv6 address to the host. :param str ipv6addr: The IP address to add. :raises: ValueError """ for addr in self.ipv6addrs: if ((isinstance(addr, dict) and addr['ipv6addr'] == ipv6addr) or (isinstance(addr, H...
Add an IPv6 address to the host. :param str ipv6addr: The IP address to add. :raises: ValueError
def version_gt(version, gt): """ Code for parsing simple, numeric versions. Letters will be stripped prior to comparison. Simple appendages such as 1-rc1 are supported. Test cases for function are present on dscan/tests/fingerprint_tests.py """ version_split = strip_letters(version).split('.') ...
Code for parsing simple, numeric versions. Letters will be stripped prior to comparison. Simple appendages such as 1-rc1 are supported. Test cases for function are present on dscan/tests/fingerprint_tests.py
def get_price(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `price` record is not found. Returns: str: Price of the book (with currency) or `undefined` if `price` \ is not found. ...
Args: undefined (optional): Argument, which will be returned if the `price` record is not found. Returns: str: Price of the book (with currency) or `undefined` if `price` \ is not found.
def int2mjd(d, loc): """ Function to convert segment+integration into mjd seconds. """ # needs to take merge pkl dict if len(loc): intcol = d['featureind'].index('int') segmentcol = d['featureind'].index('segment') if d.has_key('segmenttimesdict'): # using merged pkl ...
Function to convert segment+integration into mjd seconds.
def create_bundle(self, name=None, media_url=None, audio_channel=None, metadata=None, notify_url=None, external_id=None): """Create a new bundle. 'metadata' may be None, or an object that can be converted to a JSON string. See API documentation for r...
Create a new bundle. 'metadata' may be None, or an object that can be converted to a JSON string. See API documentation for restrictions. The conversion will take place before the API call. All other parameters are also optional. For information about these see https://api.cl...
def list_permissions(self, group_name=None, resource=None): """ List permission sets associated filtering by group and/or resource. Args: group_name (string): Name of group. resource (intern.resource.boss.Resource): Identifies which data model object to o...
List permission sets associated filtering by group and/or resource. Args: group_name (string): Name of group. resource (intern.resource.boss.Resource): Identifies which data model object to operate on. Returns: (list): List of permissions. R...
def get_template_files(self, location, class_name): """ Multilanguage support means that for each template we can have multiple templtate files, this methods returns all the template (html and txt) files that match the (class) template name """ template_name = uti...
Multilanguage support means that for each template we can have multiple templtate files, this methods returns all the template (html and txt) files that match the (class) template name
def decode_coords(ds, gridfile=None): """ Reimplemented to set the mesh variables as coordinates Parameters ---------- %(CFDecoder.decode_coords.parameters)s Returns ------- %(CFDecoder.decode_coords.returns)s""" extra_coords = set(ds.coords) ...
Reimplemented to set the mesh variables as coordinates Parameters ---------- %(CFDecoder.decode_coords.parameters)s Returns ------- %(CFDecoder.decode_coords.returns)s
def ucnstring_to_unicode(ucn_string): """Return ucnstring as Unicode.""" ucn_string = ucnstring_to_python(ucn_string).decode('utf-8') assert isinstance(ucn_string, text_type) return ucn_string
Return ucnstring as Unicode.
def print_pos(self, coordinates=None, pos=None): '''Print the chessboard''' if not pos: pos = self.pos self.graph = [list(map(self._transform, pos[i])) for i in self.pos_range] xaxis = ' '.join([chr(ASC_ONE + _) for _ in range(min(self.board_size, MAX_NUM))]) if (self...
Print the chessboard
def needs_remesh(self): """ whether the star needs to be re-meshed (for any reason) """ # TODO: may be able to get away with removing the features check and just doing for pulsations, etc? # TODO: what about dpdt, deccdt, dincldt, etc? return len(self.features) > 0 or sel...
whether the star needs to be re-meshed (for any reason)
def community_post_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/posts#create-post" api_path = "/api/v2/community/posts.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/posts#create-post
def proxy_property_directly(bind_attr, attrs): """ 为类添加代理属性 """ def cls_builder(cls): """ 添加到类 """ for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(bind_attr, attr_name)) return cls return cls_builder
为类添加代理属性
def as_command(self, sock_info): """Return a find command document for this query.""" # We use the command twice: on the wire and for command monitoring. # Generate it once, for speed and to avoid repeating side-effects. if self._as_command is not None: return self._as_comman...
Return a find command document for this query.
def datagramReceived(self, data): """ Decode the JSON-encoded datagram and call the callback. """ try: obj = json.loads(data) except ValueError, e: log.err(e, 'Invalid JSON in stream: %r' % data) return if u'text' in obj: o...
Decode the JSON-encoded datagram and call the callback.
def to_grid(self, mapping): """Convert a mapping from (x, y) to v into a [[..., v, ...]] grid.""" return list(reversed([[mapping.get((x,y), None) for x in range(self.cols)] for y in range(self.rows)]))
Convert a mapping from (x, y) to v into a [[..., v, ...]] grid.
def get_column_definition_all(self, table): """Retrieve the column definition statement for all columns in a table.""" # Get complete table definition col_defs = self.get_table_definition(table).split('\n') # Return only column definitions return [i[0:-1].strip().replace(',', ',...
Retrieve the column definition statement for all columns in a table.
def plot_multiple_regions_coverage(samples, out_file, data, region_bed=None, stem_bed=None): """ given a list of bcbio samples and a bed file or BedTool of regions, makes a plot of the coverage in the regions for the set of samples if given a bed file or BedTool of locations in stem_bed with a label, ...
given a list of bcbio samples and a bed file or BedTool of regions, makes a plot of the coverage in the regions for the set of samples if given a bed file or BedTool of locations in stem_bed with a label, plots lollipops at those locations
def value(self): """returns object as a dictionary""" val = {} if self.sourcelocale is not None: val['sourcelocale'] = self.sourcelocale if self.geocodeServiceUrl is not None: val['geocodeServiceUrl'] = self.geocodeServiceUrl if self.sourcecountry is not N...
returns object as a dictionary
def generate_PVdelV_nt_pos_vecs(self, generative_model, genomic_data): """Process P(delV|V) into Pi arrays. Set the attributes PVdelV_nt_pos_vec and PVdelV_2nd_nt_pos_per_aa_vec. Parameters ---------- generative_model : GenerativeModelVJ VJ generative mo...
Process P(delV|V) into Pi arrays. Set the attributes PVdelV_nt_pos_vec and PVdelV_2nd_nt_pos_per_aa_vec. Parameters ---------- generative_model : GenerativeModelVJ VJ generative model class containing the model parameters. genomic_data : Geno...
def assert_finite(x, data=None, summarize=None, message=None, name=None): """Assert all elements of `x` are finite. Args: x: Numeric `Tensor`. data: The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`. summarize: Print this many entries of...
Assert all elements of `x` are finite. Args: x: Numeric `Tensor`. data: The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`. summarize: Print this many entries of each tensor. message: A string to prefix to the default message. name:...
def get_token_identifiers( chain_state: ChainState, payment_network_id: PaymentNetworkID, ) -> List[TokenAddress]: """ Return the list of tokens registered with the given payment network. """ payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id) if payment_net...
Return the list of tokens registered with the given payment network.
def _massage_data(self): """ Processes the data and stores it. """ self._xdata_massaged, self._ydata_massaged, self._eydata_massaged = self.get_processed_data() # # Create the odr data. # self._odr_datas = [] # for n in range(len(self._xdata_massaged)): # ...
Processes the data and stores it.
def make_admin_on_demand_service(injector_gear): """ create an admin service to stop or start the linked gear :param injector_gear: the gear to be linked to this admin service :return: the service created """ LOGGER.debug("InjectorCachedGearService.make_admin_on_demand_se...
create an admin service to stop or start the linked gear :param injector_gear: the gear to be linked to this admin service :return: the service created
def download_tile(map_layer, zoom, x, y): """ Download a given tile from the tile server. Args: map_layer (MapLayer): MapLayer object which provides the tile-url. zoom (int): zoom level x (int): Tile-x-coordinate y (int): Tile-y-coordinate Returns: file: tempora...
Download a given tile from the tile server. Args: map_layer (MapLayer): MapLayer object which provides the tile-url. zoom (int): zoom level x (int): Tile-x-coordinate y (int): Tile-y-coordinate Returns: file: temporary file containing the downloaded image.
def clear(self, keep_input=True): """ Clear the console. Parameters: ----------- keep_input : bool, optional (default True) If set, restores the old input buffer if a new prompt is written. """ if self._executing: self._control.clear() els...
Clear the console. Parameters: ----------- keep_input : bool, optional (default True) If set, restores the old input buffer if a new prompt is written.
def list_categories(self): """List the command categories and a short description of each.""" self.section("Classes of commands:") cats = list(categories.keys()) cats.sort() for cat in cats: # Foo! iteritems() doesn't do sorting self.msg(" %-13s -- %s" % (cat, categ...
List the command categories and a short description of each.
def registerInternalRouters(app): """ These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return: """ urlPat...
These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return:
def get_client_str(username: str, ip_address: str, user_agent: str, path_info: str) -> str: """ Get a readable string that can be used in e.g. logging to distinguish client requests. Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}`` """ client_d...
Get a readable string that can be used in e.g. logging to distinguish client requests. Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}``
def ccall(self, ret_type, func_obj, args): """ Creates a CCall operation. A CCall is a procedure that calculates a value at *runtime*, not at lift-time. You can use these for flags, unresolvable jump targets, etc. We caution you to avoid using them when at all possible though. ...
Creates a CCall operation. A CCall is a procedure that calculates a value at *runtime*, not at lift-time. You can use these for flags, unresolvable jump targets, etc. We caution you to avoid using them when at all possible though. For an example of how to write and use a CCall, see gymr...
def wait_for_bump(self, buttons, timeout_ms=None): """ Wait for the button to be pressed down and then released. Both actions must happen within timeout_ms. """ start_time = time.time() if self.wait_for_pressed(buttons, timeout_ms): if timeout_ms is not None:...
Wait for the button to be pressed down and then released. Both actions must happen within timeout_ms.
def set_dn(self,dn): """ Use the domain column in the process table to store the DN dn = dn to be added """ try: domain_col = self.table['process']['orderedcol'].index('domain') for row_idx in range(len(self.table['process']['stream'])): row_list = list(self.table['process']['st...
Use the domain column in the process table to store the DN dn = dn to be added
def create_volume(self, project_id, plan, size, facility, label=""): """Creates a new volume. """ try: return self.manager.create_volume(project_id, label, plan, size, facility) except packet.baseapi.Error as msg: raise PacketManagerException(msg)
Creates a new volume.
def warn_deprecated(msg, stacklevel=2): """Generate a non-silent deprecation warning with stacktrace. The used warning is ``imgaug.imgaug.DeprecationWarning``. Parameters ---------- msg : str The message of the warning. stacklevel : int, optional How many steps above this func...
Generate a non-silent deprecation warning with stacktrace. The used warning is ``imgaug.imgaug.DeprecationWarning``. Parameters ---------- msg : str The message of the warning. stacklevel : int, optional How many steps above this function to "jump" in the stacktrace for th...
def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover import mockredis return mockredis.mock_strict_redis_client() # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = cach...
Get the redis connection if not using mock
def hasannotation(self,Class,set=None): """Returns an integer indicating whether such as annotation exists, and if so, how many. See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters.""" return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations))
Returns an integer indicating whether such as annotation exists, and if so, how many. See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters.
def add_host(self, endpoint, datacenter=None, rack=None, signal=True, refresh_nodes=True): """ Called when adding initial contact points and when the control connection subsequently discovers a new node. Returns a Host instance, and a flag indicating whether it was new in the met...
Called when adding initial contact points and when the control connection subsequently discovers a new node. Returns a Host instance, and a flag indicating whether it was new in the metadata. Intended for internal use only.
def show_plane(orig, n, scale=1.0, **kwargs): """ Show the plane with the given origin and normal. scale give its size """ b1 = orthogonal_vector(n) b1 /= la.norm(b1) b2 = np.cross(b1, n) b2 /= la.norm(b2) verts = [orig + scale*(-b1 - b2), orig + scale*(b1 - b2), ...
Show the plane with the given origin and normal. scale give its size
def activities(self): """ An iterator of reverse-chronological :class:`stravalib.model.Activity` activities for this club. """ if self._activities is None: self.assert_bind_client() self._activities = self.bind_client.get_club_activities(self.id) return self._activities
An iterator of reverse-chronological :class:`stravalib.model.Activity` activities for this club.
def verify(self, store, flags, data=None, certs=None): """ Verifies signature under CMS message using trusted cert store @param store - X509Store object with trusted certs @param flags - OR-ed combination of flag consants @param data - message data, if messge has detached signa...
Verifies signature under CMS message using trusted cert store @param store - X509Store object with trusted certs @param flags - OR-ed combination of flag consants @param data - message data, if messge has detached signature param certs - list of certificates to use during verification ...
def render(self, name, value, attrs=None, renderer=None): """ Render the default widget and initialize select2. """ output = [super(TagAutoComplete, self).render(name, value, attrs)] output.append('<script type="text/javascript">') output.append('(function($) {') ...
Render the default widget and initialize select2.
def restore(self): """ Restore a soft-deleted model instance. """ if self._fire_model_event("restoring") is False: return False setattr(self, self.get_deleted_at_column(), None) self.set_exists(True) result = self.save() self._fire_model_ev...
Restore a soft-deleted model instance.
def get_room_id(self, room_alias): """Get room id from its alias. Args: room_alias (str): The room alias name. Returns: Wanted room's id. """ content = self._send("GET", "/directory/room/{}".format(quote(room_alias))) return content.get("room_id"...
Get room id from its alias. Args: room_alias (str): The room alias name. Returns: Wanted room's id.
def from_df(cls, data, entities=None, source='contrast'): ''' Create a Collection from a pandas DataFrame. Args: df (DataFrame): The DataFrame to convert to a Collection. Each column will be converted to a SimpleVariable. entities (DataFrame): An optional second ...
Create a Collection from a pandas DataFrame. Args: df (DataFrame): The DataFrame to convert to a Collection. Each column will be converted to a SimpleVariable. entities (DataFrame): An optional second DataFrame containing entity information. s...
def _dist(self, x, y, A): "(x - y)^T A (x - y)" return scipy.spatial.distance.mahalanobis(x, y, A) ** 2
(x - y)^T A (x - y)
def _expand_overlap(dna, oligo_indices, index, oligos, length_max): '''Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of...
Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of the oligo :type index: int :param left_len: length of left oligo ...
def fuzzy_match_tipnames(ttree, names, wildcard, regex, mrca=True, mono=True): """ Used in multiple internal functions (e.g., .root()) and .drop_tips()) to select an internal mrca node, or multiple tipnames, using fuzzy matching so that every name does not need to be written out by hand. name: verb...
Used in multiple internal functions (e.g., .root()) and .drop_tips()) to select an internal mrca node, or multiple tipnames, using fuzzy matching so that every name does not need to be written out by hand. name: verbose list wildcard: matching unique string regex: regex expression mrca: return ...
async def create_lease_store_if_not_exists_async(self): """ Create the lease store if it does not exist, do nothing if it does exist. :return: `True` if the lease store already exists or was created successfully, `False` if not. :rtype: bool """ try: await se...
Create the lease store if it does not exist, do nothing if it does exist. :return: `True` if the lease store already exists or was created successfully, `False` if not. :rtype: bool
def blank(self, channel): """This is called when image is cleared.""" self._image = None info = channel.extdata._header_info info.table.clear()
This is called when image is cleared.
def _convert_eta_to_c(eta, ref_position): """ Parameters ---------- eta : 1D or 2D ndarray. The elements of the array should be this model's 'transformed' shape parameters, i.e. the natural log of (the corresponding shape parameter divided by the reference shape parameter). This ...
Parameters ---------- eta : 1D or 2D ndarray. The elements of the array should be this model's 'transformed' shape parameters, i.e. the natural log of (the corresponding shape parameter divided by the reference shape parameter). This array's elements will be real valued. If `eta`...
def get_release_task_attachment_content(self, project, release_id, environment_id, attempt_id, plan_id, timeline_id, record_id, type, name, **kwargs): """GetReleaseTaskAttachmentContent. [Preview API] :param str project: Project ID or project name :param int release_id: :param in...
GetReleaseTaskAttachmentContent. [Preview API] :param str project: Project ID or project name :param int release_id: :param int environment_id: :param int attempt_id: :param str plan_id: :param str timeline_id: :param str record_id: :param str type...
def configure_cmake(self): """Create CMake instance and execute configure step """ cmake = CMake(self) cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"...
Create CMake instance and execute configure step
def set(self, key: bytes, value: bytes) -> Tuple[Hash32]: """ Returns all updated hashes in root->leaf order """ validate_is_bytes(key) validate_length(key, self._key_size) validate_is_bytes(value) path = to_int(key) node = value _, branch = self....
Returns all updated hashes in root->leaf order
def set_runtime_value_int(self, resourceid: int, intvalue: int): """Set a integer runtime value""" payload = """ <setResourceValue1 xmlns=\"utcs\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> <value i:type=\"a:WSIntegerValue\" xmlns:a=\"utcs.values\"> ...
Set a integer runtime value
def crypto_config_from_kwargs(fallback, **kwargs): """Pull all encryption-specific parameters from the request and use them to build a crypto config. :returns: crypto config and updated kwargs :rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict """ try: crypto_config = kwargs.po...
Pull all encryption-specific parameters from the request and use them to build a crypto config. :returns: crypto config and updated kwargs :rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict
def _apply(self, force=False): """ Call xrandr and apply the selected (displayed) combination mode. """ if self.displayed == self.active_layout and not force: # no change, do nothing return combination, mode = self.combinations_map.get(self.displayed, (No...
Call xrandr and apply the selected (displayed) combination mode.
def list_installed(): ''' List installed features. Supported on Windows Server 2008 and Windows 8 and newer. Returns: dict: A dictionary of installed features CLI Example: .. code-block:: bash salt '*' win_servermanager.list_installed ''' cmd = 'Get-WindowsFeature ' \...
List installed features. Supported on Windows Server 2008 and Windows 8 and newer. Returns: dict: A dictionary of installed features CLI Example: .. code-block:: bash salt '*' win_servermanager.list_installed
def get_starred(self): """ :calls: `GET /user/starred <http://developer.github.com/v3/activity/starring>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` """ return github.PaginatedList.PaginatedList( github.Repository.Rep...
:calls: `GET /user/starred <http://developer.github.com/v3/activity/starring>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
def define_from_fits(cls, fitsobj, extnum=0): """Define class object from header information in FITS file. Parameters ---------- fitsobj: file object FITS file whose header contains the DTU information needed to initialise the members of this class. extnu...
Define class object from header information in FITS file. Parameters ---------- fitsobj: file object FITS file whose header contains the DTU information needed to initialise the members of this class. extnum : int Extension number (first extension is ...
def schema_val(self, messages=None): "Perform validation with processed YAML and Schema" self._ymlproc = YAMLProcessor(self._ymlfile) self._schemaproc = SchemaProcessor(self._schemafile) valid = True log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self...
Perform validation with processed YAML and Schema
def singular_noun(self, text, count=None, gender=None): """ Return the singular of text, where text is a plural noun. If count supplied, then return the singular if count is one of: 1, a, an, one, each, every, this, that or if count is None otherwise return text unchanged. ...
Return the singular of text, where text is a plural noun. If count supplied, then return the singular if count is one of: 1, a, an, one, each, every, this, that or if count is None otherwise return text unchanged. Whitespace at the start and end is preserved.
def _token_auth(self): """Add ThreatConnect Token Auth to Session.""" return TcExTokenAuth( self, self.args.tc_token, self.args.tc_token_expires, self.args.tc_api_path, self.tcex.log, )
Add ThreatConnect Token Auth to Session.
def read(path): """Read a secret from Vault REST endpoint""" url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'), settings.VAULT_BASE_SECRET_PATH.strip('/'), path.lstrip('/')) headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN} resp =...
Read a secret from Vault REST endpoint
def edit(self, resource): """Edit a tag. :param resource: :class:`tags.Tag <tags.Tag>` object :return: :class:`tags.Tag <tags.Tag>` object :rtype: tags.Tag """ schema = TagSchema(only=('name', 'configs', 'devices', 'packages', 'results')) json = self.service.enco...
Edit a tag. :param resource: :class:`tags.Tag <tags.Tag>` object :return: :class:`tags.Tag <tags.Tag>` object :rtype: tags.Tag
def bind(self, devices_to_bind): """ This function allows an entity to list the devices to subscribe for data. This function must be called at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here. Args: devices_to_bind (list): an array...
This function allows an entity to list the devices to subscribe for data. This function must be called at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here. Args: devices_to_bind (list): an array of devices to listen to. ...
def mkpath(self, url, path, filename=None, gzip=False): """ Assembles various components to form a complete resource URL. args: url: (str) A base media URL. path: (str) The path on the host (specified in 'url') leading up to the file. ...
Assembles various components to form a complete resource URL. args: url: (str) A base media URL. path: (str) The path on the host (specified in 'url') leading up to the file. filename: (str) The file name to serve. gzip: (bool) True if clien...
def get_color_theme(theme): ''' Return the color theme to use ''' # Keep the heavy lifting out of the module space import salt.utils.data import salt.utils.files import salt.utils.yaml if not os.path.isfile(theme): log.warning('The named theme %s if not available', theme) tr...
Return the color theme to use
def _determine_doubled_obj(self): """Return the target object. Returns the object that should be treated as the target object. For partial doubles, this will be the same as ``self.obj``, but for pure doubles, it's pulled from the special ``_doubles_target`` attribute. :return: ...
Return the target object. Returns the object that should be treated as the target object. For partial doubles, this will be the same as ``self.obj``, but for pure doubles, it's pulled from the special ``_doubles_target`` attribute. :return: The object to be doubled. :rtype: obj...
def visitCodeDecl(self, ctx: ShExDocParser.CodeDeclContext): """ codeDecl: '%' iri (CODE | '%') CODE: : '{' (~[%\\] | '\\' [%\\] | UCHAR)* '%' '}' """ semact = SemAct() semact.name = self.context.iri_to_iriref(ctx.iri()) if ctx.CODE(): semact.code = ctx.CODE().ge...
codeDecl: '%' iri (CODE | '%') CODE: : '{' (~[%\\] | '\\' [%\\] | UCHAR)* '%' '}'
def set_completed(self, *, completition_date=None): """ Sets this message flag as completed :param completition_date: the datetime this followUp was completed """ self.__status = Flag.Complete completition_date = completition_date or dt.datetime.now() if completition_date...
Sets this message flag as completed :param completition_date: the datetime this followUp was completed
def _main(instaloader: Instaloader, targetlist: List[str], username: Optional[str] = None, password: Optional[str] = None, sessionfile: Optional[str] = None, download_profile_pic: bool = True, download_posts=True, download_stories: bool = False, download_highlights: bool = False,...
Download set of profiles, hashtags etc. and handle logging in and session files if desired.
def register_hook(self, hook, event_type=None): """ If ``event_type`` is provided, then ``hook`` will be called whenever that event is fired. If no ``event_type`` is specifid, but ``hook`` implements any methods with names matching an event hook, then those will be registered wi...
If ``event_type`` is provided, then ``hook`` will be called whenever that event is fired. If no ``event_type`` is specifid, but ``hook`` implements any methods with names matching an event hook, then those will be registered with their corresponding events. This allows for more stateful...
def memory_read(self, start_position: int, size: int) -> memoryview: """ Read and return a view of ``size`` bytes from memory starting at ``start_position``. """ return self._memory.read(start_position, size)
Read and return a view of ``size`` bytes from memory starting at ``start_position``.
def consistency(self, consistency): """ Sets the consistency level for the operation. See :class:`.ConsistencyLevel`. .. code-block:: python for user in User.objects(id=3).consistency(CL.ONE): print(user) """ clone = copy.deepcopy(self) clone...
Sets the consistency level for the operation. See :class:`.ConsistencyLevel`. .. code-block:: python for user in User.objects(id=3).consistency(CL.ONE): print(user)
def initGroupStyle(self, useIcons=True, columnCount=None): """ Initialzes this item with a grouping style option. """ flags = self.flags() if flags & QtCore.Qt.ItemIsSelectable: flags ^= QtCore.Qt.ItemIsSelectable self.setFlags(flags) ...
Initialzes this item with a grouping style option.
def patch_validating_webhook_configuration(self, name, body, **kwargs): """ partially update the specified ValidatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.pat...
partially update the specified ValidatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_validating_webhook_configuration(name, body, async_req=True) >>> result = thread....
def get_help_datapacks(filepath, prefix="!"): """ Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file """ help_cont...
Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file
def update(self, data): """Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on the object. Args: ...
Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on the object. Args: data (:obj:): AWS API Resource ...
def main( gpu:Param("GPU to run on", str)=None, lr: Param("Learning rate", float)=1e-3, size: Param("Size (px: 128,192,224)", int)=128, debias_mom: Param("Debias statistics", bool)=False, debias_sqr: Param("Debias statistics", bool)=False, opt: Param("Optimizer: 'adam','g...
Distributed training of Imagenette. Fastest multi-gpu speed is if you run with: python -m fastai.launch
def __find_and_modify(self, filter, projection, sort, upsert=None, return_document=ReturnDocument.BEFORE, array_filters=None, session=None, **kwargs): """Internal findAndModify helper.""" common.validate_is_mapping("filter", filter) if not isi...
Internal findAndModify helper.
def load_from_json(db_file, language=DEFAULT_LANG): """ Parses the JSON data and returns it :param db_file: File and path pointing to the JSON file to parse :param language: The user's language (en, es, etc.) :raises: All kind of exceptions if the file doesn't exist or JSON is ...
Parses the JSON data and returns it :param db_file: File and path pointing to the JSON file to parse :param language: The user's language (en, es, etc.) :raises: All kind of exceptions if the file doesn't exist or JSON is invalid. :return: None
def _analyze_function_features(self, all_funcs_completed=False): """ For each function in the function_manager, try to determine if it returns or not. A function does not return if it calls another function that is known to be not returning, and this function does not have other exits. ...
For each function in the function_manager, try to determine if it returns or not. A function does not return if it calls another function that is known to be not returning, and this function does not have other exits. We might as well analyze other features of functions in the future. :param b...
def create(self): """ Creates the object :return: the created object :rtype: object """ # In the header.location there is the newly created object so get the id out of the url created_id = self._post_request( data=self.element_to_string(self.encode()...
Creates the object :return: the created object :rtype: object
def ensure_dir(path): """Ensure that a needed directory exists, creating it if it doesn't""" try: log.info('Ensuring directory exists: %s' % path) os.makedirs(path) except OSError: if not os.path.isdir(path): raise
Ensure that a needed directory exists, creating it if it doesn't
def Li_Wu(m, x, D, rhol, rhog, mul, kl, Hvap, sigma, q=None, Te=None): r'''Calculates heat transfer coefficient for film boiling of saturated fluid in any orientation of flow. Correlation is as shown in [1]_, and also reviewed in [2]_ and [3]_. Either the heat flux or excess temperature is required...
r'''Calculates heat transfer coefficient for film boiling of saturated fluid in any orientation of flow. Correlation is as shown in [1]_, and also reviewed in [2]_ and [3]_. Either the heat flux or excess temperature is required for the calculation of heat transfer coefficient. Uses liquid Reynolds...