code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def which_users_can(self, name): """Which role can SendMail? """ _roles = self.which_roles_can(name) result = [self.get_role_members(i.get('role')) for i in _roles] return result
Which role can SendMail?
def __verify_minion_publish(self, clear_load): ''' Verify that the passed information authorized a minion to execute :param dict clear_load: A publication load from a minion :rtype: bool :return: A boolean indicating if the minion is allowed to publish the command in the load ...
Verify that the passed information authorized a minion to execute :param dict clear_load: A publication load from a minion :rtype: bool :return: A boolean indicating if the minion is allowed to publish the command in the load
def boolify(value, nullable=False, return_string=False): """Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ...
Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for...
def _ReadStringDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a string data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, o...
Reads a string data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type...
def generate(self, chars): """Generate audio CAPTCHA data. The return data is a bytearray. :param chars: text to be generated. """ if not self._cache: self.load() body = self.create_wave_body(chars) return patch_wave_header(body)
Generate audio CAPTCHA data. The return data is a bytearray. :param chars: text to be generated.
def snake_to_pascal(name, singularize=False): """Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing each part of the resulting name. """ parts = name.split("_") if singularize: return "".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts...
Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing each part of the resulting name.
def app_state(self, app): """Informs if application is running.""" if not self.available or not self.screen_on: return STATE_OFF if self.current_app["package"] == app: return STATE_ON return STATE_OFF
Informs if application is running.
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-08-01: :mod:`v2015_08_01.models<azure.mgmt.eventhub.v2015_08_01.models>` * 2017-04-01: :mod:`v2017_04_01.models<azure.mgmt.eventhub.v2017_04_01.models>` * 2018-01-01-preview: :mod:`v2...
Module depends on the API version: * 2015-08-01: :mod:`v2015_08_01.models<azure.mgmt.eventhub.v2015_08_01.models>` * 2017-04-01: :mod:`v2017_04_01.models<azure.mgmt.eventhub.v2017_04_01.models>` * 2018-01-01-preview: :mod:`v2018_01_01_preview.models<azure.mgmt.eventhub.v2018_01_01_prev...
def OnCellText(self, event): """Text entry event handler""" row, col, _ = self.grid.actions.cursor self.grid.GetTable().SetValue(row, col, event.code) event.Skip()
Text entry event handler
def loads(content): """Loads variable definitions from a string.""" lines = _group_lines(line for line in content.split('\n')) lines = [ (i, _parse_envfile_line(line)) for i, line in lines if line.strip() ] errors = [] # Reject files with duplicate variables (no sane default). ...
Loads variable definitions from a string.
def create(self, _attributes=None, _joining=None, _touch=True, **attributes): """ Create a new instance of the related model. :param attributes: The attributes :type attributes: dict :rtype: orator.orm.Model """ if _attributes is not None: attributes...
Create a new instance of the related model. :param attributes: The attributes :type attributes: dict :rtype: orator.orm.Model
def _apply_dvs_infrastructure_traffic_resources(infra_traffic_resources, resource_dicts): ''' Applies the values of the resource dictionaries to infra traffic resources, creating the infra traffic resource if required (vim.DistributedVirtualSwitchProductSp...
Applies the values of the resource dictionaries to infra traffic resources, creating the infra traffic resource if required (vim.DistributedVirtualSwitchProductSpec)
def pacific_atlantic(matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ n = len(matrix) if not n: return [] m = len(matrix[0]) if not m: return [] res = [] atlantic = [[False for _ in range (n)] for _ in range(m)] pacific = [[False for _ in range (n)] for...
:type matrix: List[List[int]] :rtype: List[List[int]]
async def dump_message(obj, msg, field_archiver=None): """ Dumps message to the object. Returns message popo representation. :param obj: :param msg: :param field_archiver: :return: """ mtype = msg.__class__ fields = mtype.f_specs() obj = collections.OrderedDict() if obj is ...
Dumps message to the object. Returns message popo representation. :param obj: :param msg: :param field_archiver: :return:
def create_record(awsclient, name_prefix, instance_reference, type="A", host_zone_name=None): """ Builds route53 record entries enabling DNS names for services Note: gcdt.route53 create_record(awsclient, ...) is used in dataplatform cloudformation.py templates! :param name_prefix: The sub domain pr...
Builds route53 record entries enabling DNS names for services Note: gcdt.route53 create_record(awsclient, ...) is used in dataplatform cloudformation.py templates! :param name_prefix: The sub domain prefix to use :param instance_reference: The EC2 troposphere reference which's private IP should be link...
def use_comparative_grade_system_view(self): """Pass through to provider GradeSystemLookupSession.use_comparative_grade_system_view""" self._object_views['grade_system'] = COMPARATIVE # self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked for se...
Pass through to provider GradeSystemLookupSession.use_comparative_grade_system_view
def _translate_div(self, oprnd1, oprnd2, oprnd3): """Return a formula representation of an DIV instruction. """ assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src_...
Return a formula representation of an DIV instruction.
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name): ''' Returns the AC/DC values in an dict for a guid and subguid for a the given scheme ''' if scheme is None: scheme = _get_current_scheme() if __grains__['osrelease'] == '7': cmd = 'powercfg /q {0} {1}'.format(sc...
Returns the AC/DC values in an dict for a guid and subguid for a the given scheme
def synthesize_property(property_name, default = None, contract = None, read_only = False, private_member_name = None): """ When applied to a class, this decorator adds a property to it and overrides the constructor ...
When applied to a class, this decorator adds a property to it and overrides the constructor in order to set\ the default value of the property. :IMPORTANT: In order for this to work on python 2, you must use new objects that is to say that the class must inherit from object. By default, the private at...
def get_auth(self): ''' Returns username from the configfile. ''' return (self._cfgparse.get(self._section, 'username'), self._cfgparse.get(self._section, 'password'))
Returns username from the configfile.
def get_call_signature(fn: FunctionType, args: ArgsType, kwargs: KwargsType, debug_cache: bool = False) -> str: """ Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable ...
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use indirectly as a cache key. The string is a JSON representation. See ``make_cache_key`` for a more suitable actual cache key.
def gumbel_softmax(x, z_size, mode, softmax_k=0, temperature_warmup_steps=150000, summary=True, name=None): """Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottlen...
Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottleneck. z_size: Number of bits, where discrete codes range from 1 to 2**z_size. mode: tf.estimator.ModeKeys. softmax_k: If > 0 then do top-k softmax. temperature_warmup_steps: Number of steps it takes to decay temp...
def _health_check_thread(self): """ Health checker thread that pings the service every 30 seconds :return: None """ while self._run_health_checker: response = self._health_check(Health_pb2.HealthCheckRequest(service='predix-event-hub.grpc.health')) logging...
Health checker thread that pings the service every 30 seconds :return: None
def request(self, apdu): """This function is called by transaction functions to send to the application.""" if _debug: ServerSSM._debug("request %r", apdu) # make sure it has a good source and destination apdu.pduSource = self.pdu_address apdu.pduDestination = None ...
This function is called by transaction functions to send to the application.
def _is_inventory_group(key, value): ''' Verify that a module-level variable (key = value) is a valid inventory group. ''' if ( key.startswith('_') or not isinstance(value, (list, tuple, GeneratorType)) ): return False # If the group is a tuple of (hosts, data), check t...
Verify that a module-level variable (key = value) is a valid inventory group.
def is_canonical_address(address: Any) -> bool: """ Returns `True` if the `value` is an address in its canonical form. """ if not is_bytes(address) or len(address) != 20: return False return address == to_canonical_address(address)
Returns `True` if the `value` is an address in its canonical form.
def squash_layouts(self, layouts): ''' Returns a squashed layout The first element takes precedence (i.e. left to right). Dictionaries are recursively merged, overwrites only occur on non-dictionary entries. [0,1] 0: test: 'my data' 1: test: 's...
Returns a squashed layout The first element takes precedence (i.e. left to right). Dictionaries are recursively merged, overwrites only occur on non-dictionary entries. [0,1] 0: test: 'my data' 1: test: 'stuff' Result: test: 'my data' ...
def add_template_events_to_ifo(self, ifo, columns, vectors): """ Add a vector indexed """ # Just call through to the standard function self.template_events = self.template_event_dict[ifo] self.add_template_events(columns, vectors) self.template_event_dict[ifo] = self.template_eve...
Add a vector indexed
def add_component_type(self, component_type): """ Adds a component type to the model. @param component_type: Component type to be added. @type component_type: lems.model.fundamental.ComponentType """ name = component_type.name # To handle colons in names...
Adds a component type to the model. @param component_type: Component type to be added. @type component_type: lems.model.fundamental.ComponentType
def _FlushInput(self): """ Flush all read data until no more available. """ self.ser.flush() flushed = 0 while True: ready_r, ready_w, ready_x = select.select([self.ser], [], [self.ser], 0) if len(ready_x) > 0:...
Flush all read data until no more available.
def calc_J(self): """Updates self.J, returns nothing""" del self.J self.J = np.zeros([self.param_vals.size, self.data.size]) dp = np.zeros_like(self.param_vals) f0 = self.model.copy() for a in range(self.param_vals.size): dp *= 0 dp[a] = self.dl[a]...
Updates self.J, returns nothing
def parse(self): """Parse our string and return a Survey object, None, or raise :exc:`ParseException`""" if not self.survey_str: return None lines = self.survey_str.splitlines() if len(lines) < 10: raise ParseException("Expected at least 10 lines in a Compass Surv...
Parse our string and return a Survey object, None, or raise :exc:`ParseException`
def formula(self, atom_sequence): ''' Constructs standardized chemical formula NB: this is the PUBLIC method @returns formula_str ''' labels = {} types = [] y = 0 for k, atomi in enumerate(atom_sequence): lbl = re.sub("[0-9]+", "", atom...
Constructs standardized chemical formula NB: this is the PUBLIC method @returns formula_str
def list_reshape(list_, new_shape, trail=False): r""" reshapes leaving trailing dimnsions in front if prod(new_shape) != len(list_) Args: list_ (list): new_shape (tuple): Returns: list: list_ CommandLine: python -m utool.util_list --exec-list_reshape --show Ex...
r""" reshapes leaving trailing dimnsions in front if prod(new_shape) != len(list_) Args: list_ (list): new_shape (tuple): Returns: list: list_ CommandLine: python -m utool.util_list --exec-list_reshape --show Example: >>> # ENABLE_DOCTEST >>> from ...
def get_grid(grid_id): """ Return the specified grid. :param grid_id: The grid identification in h2o :returns: an :class:`H2OGridSearch` instance. """ assert_is_type(grid_id, str) grid_json = api("GET /99/Grids/%s" % grid_id) models = [get_model(key["name"]) for key in grid_json["model...
Return the specified grid. :param grid_id: The grid identification in h2o :returns: an :class:`H2OGridSearch` instance.
def split_heads(self, x): """Split x into different heads, and transpose the resulting value. The tensor is transposed to insure the inner dimensions hold the correct values during the matrix multiplication. Args: x: A tensor with shape [batch_size, length, hidden_size] Returns: A ten...
Split x into different heads, and transpose the resulting value. The tensor is transposed to insure the inner dimensions hold the correct values during the matrix multiplication. Args: x: A tensor with shape [batch_size, length, hidden_size] Returns: A tensor with shape [batch_size, num_h...
def _R2deriv(self,R,z,phi=0.,t=0.): """ NAME: _Rderiv PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT...
NAME: _Rderiv PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the second radial derivative HISTOR...
def _reset(self, framer): """ Reset the state for the framer. It is safe to call this method multiple times with the same framer; the ID of the framer object will be saved and the state only reset if the IDs are different. After resetting the state, the framer's ``init_...
Reset the state for the framer. It is safe to call this method multiple times with the same framer; the ID of the framer object will be saved and the state only reset if the IDs are different. After resetting the state, the framer's ``init_state()`` method will be called.
def remove_service(service, zone=None, permanent=True): ''' Remove a service from zone. This option can be specified multiple times. If zone is omitted, default zone will be used. CLI Example: .. code-block:: bash salt '*' firewalld.remove_service ssh To remove a service from a speci...
Remove a service from zone. This option can be specified multiple times. If zone is omitted, default zone will be used. CLI Example: .. code-block:: bash salt '*' firewalld.remove_service ssh To remove a service from a specific zone .. code-block:: bash salt '*' firewalld.remov...
def put_task_info(self, task_name, key, value): """ Put information into a task. :param task_name: name of the task :param key: key of the information item :param value: value of the information item """ params = OrderedDict([('info', ''), ('taskname', task_name)...
Put information into a task. :param task_name: name of the task :param key: key of the information item :param value: value of the information item
def set_random_seed(): """Set the random seed from flag everywhere.""" tf.set_random_seed(FLAGS.random_seed) random.seed(FLAGS.random_seed) np.random.seed(FLAGS.random_seed)
Set the random seed from flag everywhere.
def plot(self, key=None, invert=None, plotmethod='imshow', cmap=plt.cm.gray, ms=4, Max=None, fs=None, dmargin=None, wintit=None, draw=True, connect=True): """ Plot the data content in a predefined figure """ dax, KH = _plot.Data_plot(self, key=key, invert=invert, ...
Plot the data content in a predefined figure
def execute(self, program: Program): """ Execute a program on the QVM. Note that the QAM is stateful. Subsequent calls to :py:func:`execute` will not automatically reset the wavefunction or the classical RAM. If this is desired, consider starting your program with ``RESET``. ...
Execute a program on the QVM. Note that the QAM is stateful. Subsequent calls to :py:func:`execute` will not automatically reset the wavefunction or the classical RAM. If this is desired, consider starting your program with ``RESET``. :return: ``self`` to support method chaining.
def crypto_box_keypair(): """ Returns a randomly generated public and secret key. :rtype: (bytes(public_key), bytes(secret_key)) """ pk = ffi.new("unsigned char[]", crypto_box_PUBLICKEYBYTES) sk = ffi.new("unsigned char[]", crypto_box_SECRETKEYBYTES) rc = lib.crypto_box_keypair(pk, sk) ...
Returns a randomly generated public and secret key. :rtype: (bytes(public_key), bytes(secret_key))
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs): "Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`." title = 'Input / Prediction / Target' axs = subplots(len(xs), 3, imgsize=imgsize, figsize=figsize, title=title, w...
Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`.
def user_picklist(i_info, command): """Display list of instances matching args and ask user to select target. Instance list displayed and user asked to enter the number corresponding to the desired target instance, or '0' to abort. Args: i_info (dict): information on instances and details. ...
Display list of instances matching args and ask user to select target. Instance list displayed and user asked to enter the number corresponding to the desired target instance, or '0' to abort. Args: i_info (dict): information on instances and details. command (str): command specified on th...
def do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0, decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs): """ Levenberg-Marquardt optimization for every particle in the state. Convenience wrapper for LMParticleGroupCollection. Same keyword args, but ...
Levenberg-Marquardt optimization for every particle in the state. Convenience wrapper for LMParticleGroupCollection. Same keyword args, but I've set the defaults to what I've found to be useful values for optimizing particles. See LMParticleGroupCollection for documentation. See Also -------- ...
def plot_mixing_lines(self, p=None, rv=None, **kwargs): r'''Plot lines of constant mixing ratio. Adds lines of constant mixing ratio (isohumes) to the plot. The default style of these lines is dashed green lines with an alpha value of 0.8. These can be overridden using keyword arguments...
r'''Plot lines of constant mixing ratio. Adds lines of constant mixing ratio (isohumes) to the plot. The default style of these lines is dashed green lines with an alpha value of 0.8. These can be overridden using keyword arguments. Parameters ---------- rv : array_like...
def join_channel(self, channel): """ Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #) """ self.s.send(('JOIN #%s\r\n' % channel).encode('utf-8')) ...
Join a different chat channel on Twitch. Note, this function returns immediately, but the switch might take a moment :param channel: name of the channel (without #)
def form_node(cls): """A class decorator to finalize fully derived FormNode subclasses.""" assert issubclass(cls, FormNode) res = attrs(init=False, slots=True)(cls) res._args = [] res._required_args = 0 res._rest_arg = None state = _FormArgMode.REQUIRED for field in fields(res): ...
A class decorator to finalize fully derived FormNode subclasses.
def index(ubifs, lnum, offset, inodes={}, bad_blocks=[]): """Walk the index gathering Inode, Dir Entry, and File nodes. Arguments: Obj:ubifs -- UBIFS object. Int:lnum -- Logical erase block number. Int:offset -- Offset in logical erase block. Dict:inodes -- Dict of ino/dent/file nodes...
Walk the index gathering Inode, Dir Entry, and File nodes. Arguments: Obj:ubifs -- UBIFS object. Int:lnum -- Logical erase block number. Int:offset -- Offset in logical erase block. Dict:inodes -- Dict of ino/dent/file nodes keyed to inode number. Returns: Dict:inodes -- Dict of...
def added(self): ''' Returns all keys that have been added. If the keys are in child dictionaries they will be represented with . notation ''' def _added(diffs, prefix): keys = [] for key in diffs.keys(): if isinstance(diffs[key], ...
Returns all keys that have been added. If the keys are in child dictionaries they will be represented with . notation
def cursor_up(self, count=None): """Move cursor up the indicated # of lines in same column. Cursor stops at top margin. :param int count: number of lines to skip. """ top, _bottom = self.margins or Margins(0, self.lines - 1) self.cursor.y = max(self.cursor.y - (count or ...
Move cursor up the indicated # of lines in same column. Cursor stops at top margin. :param int count: number of lines to skip.
def printstartfinish(verb, inp=None, kcount=None): r"""Print start and finish with time measure and kernel count.""" if inp: if verb > 1: ttxt = str(timedelta(seconds=default_timer() - inp)) ktxt = ' ' if kcount: ktxt += str(kcount) + ' kernel call(s)'...
r"""Print start and finish with time measure and kernel count.
def _init_img_params(param): """ Initialize 2D image-type parameters that can accept either a single or two values. """ if param is not None: param = np.atleast_1d(param) if len(param) == 1: param = np.repeat(param, 2) return para...
Initialize 2D image-type parameters that can accept either a single or two values.
def free_memory(self): """Free memory signal.""" self.main.free_memory() QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory()) QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER, lambda: ...
Free memory signal.
def full_keywords(soup): "author keywords list including inline tags, such as italic" if not raw_parser.author_keywords(soup): return [] return list(map(node_contents_str, raw_parser.author_keywords(soup)))
author keywords list including inline tags, such as italic
def _connect(): ''' Return server object used to interact with Jenkins. :return: server object used to interact with Jenkins ''' jenkins_url = __salt__['config.get']('jenkins.url') or \ __salt__['config.get']('jenkins:url') or \ __salt__['pillar.get']('jenkins.url') jenkins_use...
Return server object used to interact with Jenkins. :return: server object used to interact with Jenkins
def iter_filths(): """Iterate over all instances of filth""" for filth_cls in iter_filth_clss(): if issubclass(filth_cls, RegexFilth): m = next(re.finditer(r"\s+", "fake pattern string")) yield filth_cls(m) else: yield filth_cls()
Iterate over all instances of filth
def classes(self): """return all class nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)]
return all class nodes in the diagram
def retrieve_file_handles_of_same_dataset(self, **args): ''' :return: List of handles, or empty list. Should never return None. :raise: SolrSwitchedOff :raise SolrError: If both strategies to find file handles failed. ''' mandatory_args = ['drs_id', 'version_number', 'da...
:return: List of handles, or empty list. Should never return None. :raise: SolrSwitchedOff :raise SolrError: If both strategies to find file handles failed.
def attach_zone(geoid, organization_id_or_slug): '''Attach a zone <geoid> restricted to level for a given <organization>.''' organization = Organization.objects.get_by_id_or_slug( organization_id_or_slug) if not organization: log.error('No organization found for %s', organization_id_or_slug)...
Attach a zone <geoid> restricted to level for a given <organization>.
def get_group(self, group_id): """ Return specified group. Returns a Command. """ def process_result(result): return Group(self, result) return Command('get', [ROOT_GROUPS, group_id], process_result=process_result)
Return specified group. Returns a Command.
def open(cls, pkg_file): """ Return an |OpcPackage| instance loaded with the contents of *pkg_file*. """ pkg_reader = PackageReader.from_file(pkg_file) package = cls() Unmarshaller.unmarshal(pkg_reader, package, PartFactory) return package
Return an |OpcPackage| instance loaded with the contents of *pkg_file*.
def status(self, remote=False): """ Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actio...
Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actions sent to the server. * the count of action...
def _default(cls, opts): """Setup default logger""" level = getattr(logging, opts.log_level, logging.DEBUG) logger = logging.getLogger('luigi-interface') logger.setLevel(level) stream_handler = logging.StreamHandler() stream_handler.setLevel(level) formatter = ...
Setup default logger
def GetHostMemPhysFreeMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysFreeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
def Type_string(self, text, interval = 0, dl = 0): """键盘输入字符串,interval是字符间输入时间间隔,单位"秒" """ self.Delay(dl) self.keyboard.type_string(text, interval)
键盘输入字符串,interval是字符间输入时间间隔,单位"秒"
def footprint(self,nside): """ Download the survey footprint for HEALpix pixels. """ import healpy import ugali.utils.projector if nside > 2**9: raise Exception("Overflow error: nside must be <=2**9") pix = np.arange(healpy.nside2npix(nside),dtype='int') f...
Download the survey footprint for HEALpix pixels.
def mod_watch(name, **kwargs): ''' Execute a cmd function based on a watch call .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being tr...
Execute a cmd function based on a watch call .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered.
def get_id(self, request_data, parameter_name='id'): """Extract an integer from request data.""" if parameter_name not in request_data: raise ParseError("`{}` parameter is required".format(parameter_name)) id_parameter = request_data.get(parameter_name, None) if not isinstan...
Extract an integer from request data.
def __add_bgedge(self, bgedge, merge=True): """ Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Checks that vertices in supplied :class:`bg.edge.BGEdge` instance actually are present in current :class:`BreakpointGraph` if **merge** option of provided. Other...
Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Checks that vertices in supplied :class:`bg.edge.BGEdge` instance actually are present in current :class:`BreakpointGraph` if **merge** option of provided. Otherwise a new edge is added to the current :class:`Breakpoi...
def is_source_code_missing_open_brackets(source_code): """ :param str source_code: :return: whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets :rtype: bool """ open_brackets = "[{(" close_brackets = "]})" last_close_bracket = [-1] # stack ...
:param str source_code: :return: whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets :rtype: bool
def build_all(self, verbose=False, hide_base_schemas=True, hide_implicit_types=True, hide_implicit_preds=True): """ Extract all ontology entities from an RDF graph and construct Python representations of them. """ if...
Extract all ontology entities from an RDF graph and construct Python representations of them.
def parse_line(self, line): """Parse a single line of JSON and write modified JSON back.""" prefix = "" # ignore comma at start of lines if line.startswith(","): line, prefix = line[1:], "," j = json.loads(line) yield j self.io.write_line(prefix + js...
Parse a single line of JSON and write modified JSON back.
def svd_solve(U, s, V, b, s_tol=1e-15): """ Solve the system :math:`A X = b` for :math:`X`. Here :math:`A` is a positive semi-definite matrix using the singular value decomposition. This truncates the SVD so only dimensions corresponding to non-negative and sufficiently large singular values are us...
Solve the system :math:`A X = b` for :math:`X`. Here :math:`A` is a positive semi-definite matrix using the singular value decomposition. This truncates the SVD so only dimensions corresponding to non-negative and sufficiently large singular values are used. Parameters ---------- U: ndarray ...
def G(self, y, t): """Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space ...
Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the complete network system...
def predict(self, text:str, n_words:int=1, no_unk:bool=True, temperature:float=1., min_p:float=None, sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text`." ds = self.data.single_dl.dataset self.model.reset() xb,yb = self.data.one_item(tex...
Return the `n_words` that come after `text`.
def get_bromo_fnames_da(d_em_kHz, d_bg_kHz, a_em_kHz, a_bg_kHz, ID='1+2+3+4+5+6', t_tot='480', num_p='30', pM='64', t_step=0.5e-6, D=1.2e-11, dir_=''): """Get filenames for donor and acceptor timestamps for the given parameters """ clk_p = t_step/32. # with t_step=0.5us -> 156.25 ns E_s...
Get filenames for donor and acceptor timestamps for the given parameters
def is_active(self, timperiods): """ Know if this result modulation is active now :return: True is we are in the period, otherwise False :rtype: bool """ now = int(time.time()) timperiod = timperiods[self.modulation_period] if not timperiod or timperiod.i...
Know if this result modulation is active now :return: True is we are in the period, otherwise False :rtype: bool
def mtf_resnet_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 32 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0.0 # 8-way model-parallelism hpa...
Set of hyperparameters.
def analyte_2_massname(s): """ Converts analytes in format 'Al27' to '27Al'. Parameters ---------- s : str of format [0-9]{1,3}[A-z]{1,3} Returns ------- str Name in format [A-z]{1,3}[0-9]{1,3} """ el = re.match('.*?([A-z]{1,3}).*?', s).groups()[0] m = re.ma...
Converts analytes in format 'Al27' to '27Al'. Parameters ---------- s : str of format [0-9]{1,3}[A-z]{1,3} Returns ------- str Name in format [A-z]{1,3}[0-9]{1,3}
def coordination_geometry_symmetry_measures(self, coordination_geometry, tested_permutations=False, points_perfect=None, optimization=None): """ Returns the sym...
Returns the symmetry measures of a given coordination_geometry for a set of permutations depending on the permutation setup. Depending on the parameters of the LocalGeometryFinder and on the coordination geometry, different methods are called. :param coordination_geometry: Coordination geometry...
def alignment_display(self): """Fills screen with uppercase E's for screen focus and alignment.""" self.dirty.update(range(self.lines)) for y in range(self.lines): for x in range(self.columns): self.buffer[y][x] = self.buffer[y][x]._replace(data="E")
Fills screen with uppercase E's for screen focus and alignment.
def _check_retcode(cmd): ''' Simple internal wrapper for cmdmod.retcode ''' return salt.modules.cmdmod.retcode(cmd, output_loglevel='quiet', ignore_retcode=True) == 0
Simple internal wrapper for cmdmod.retcode
def pkg_desc(self): """Print slack-desc by repository """ options = [ "-p", "--desc" ] flag = ["--color="] colors = [ "red", "green", "yellow", "cyan", "grey" ] tag = "" ...
Print slack-desc by repository
def remove_qc_reports(portal): """Removes the action Quality Control from Reports """ logger.info("Removing Reports > Quality Control ...") ti = portal.reports.getTypeInfo() actions = map(lambda action: action.id, ti._actions) for index, action in enumerate(actions, start=0): if action =...
Removes the action Quality Control from Reports
def remove_isoforms(ids): """ This is more or less a hack to remove the GMAP multiple mappings. Multiple GMAP mappings can be seen given the names .mrna1, .mrna2, etc. """ key = lambda x: x.rsplit(".", 1)[0] iso_number = lambda x: get_number(x.split(".")[-1]) ids = sorted(ids, key=key) n...
This is more or less a hack to remove the GMAP multiple mappings. Multiple GMAP mappings can be seen given the names .mrna1, .mrna2, etc.
def read_reg(self, addr): """ Read memory address in target """ # we don't call check_command here because read_reg() function is called # when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different # for different chip types (!) val, data = self...
Read memory address in target
def _cnvkit_metrics(cnns, target_bed, antitarget_bed, cov_interval, items): """Estimate noise of a sample using a flat background. Only used for panel/targeted data due to memory issues with whole genome samples. """ if cov_interval == "genome": return cnns target_cnn = [x["file"] for ...
Estimate noise of a sample using a flat background. Only used for panel/targeted data due to memory issues with whole genome samples.
def _QueryHashes(self, digests): """Queries VirusTotal for a specfic hashes. Args: digests (list[str]): hashes to look up. Returns: dict[str, object]: JSON response or None on error. """ url_parameters = {'apikey': self._api_key, 'resource': ', '.join(digests)} try: json_res...
Queries VirusTotal for a specfic hashes. Args: digests (list[str]): hashes to look up. Returns: dict[str, object]: JSON response or None on error.
def add_flow_exception(exc): """Add an exception that should not be logged. The argument must be a subclass of Exception. """ global _flow_exceptions if not isinstance(exc, type) or not issubclass(exc, Exception): raise TypeError('Expected an Exception subclass, got %r' % (exc,)) as_set = set(_flow_exc...
Add an exception that should not be logged. The argument must be a subclass of Exception.
def _nfw_func(self, x): """ Classic NFW function in terms of arctanh and arctan :param x: r/Rs :return: """ c = 0.000001 if isinstance(x, np.ndarray): x[np.where(x<c)] = c nfwvals = np.ones_like(x) inds1 = np.where(x < 1) ...
Classic NFW function in terms of arctanh and arctan :param x: r/Rs :return:
def is_dir(path): """Determine if a Path or string is a directory on the file system.""" try: return path.expanduser().absolute().is_dir() except AttributeError: return os.path.isdir(os.path.abspath(os.path.expanduser(str(path))))
Determine if a Path or string is a directory on the file system.
def minify_print( ast, obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfusca...
Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to Fa...
def dropEvent(self, event): """ Listens for query's being dragged and dropped onto this tree. :param event | <QDropEvent> """ # overload the current filtering options data = event.mimeData() if data.hasFormat('application/x-orb-table') and \ ...
Listens for query's being dragged and dropped onto this tree. :param event | <QDropEvent>
def _prompt(letters='yn', default=None): """ Wait for the user to type a character (and hit Enter). If the user enters one of the characters in `letters`, return that character. If the user hits Enter without entering a character, and `default` is specified, returns `default`. Otherwise, asks the...
Wait for the user to type a character (and hit Enter). If the user enters one of the characters in `letters`, return that character. If the user hits Enter without entering a character, and `default` is specified, returns `default`. Otherwise, asks the user to enter a character again.
def from_config(cls, cp, section, variable_args): """Returns a distribution based on a configuration file. The parameters for the distribution are retrieved from the section titled "[`section`-`variable_args`]" in the config file. The file to construct the distribution from mus...
Returns a distribution based on a configuration file. The parameters for the distribution are retrieved from the section titled "[`section`-`variable_args`]" in the config file. The file to construct the distribution from must be provided by setting `filename`. Boundary argumen...
def goodnode(self, nodelist): ''' Goes through the provided list and returns the first server node that does not return an error. ''' l = len(nodelist) for n in range(self.current_node(l), l): self.msg.message("Trying node " + str(n) + ": " + nodelist[n]) ...
Goes through the provided list and returns the first server node that does not return an error.
def remnant_mass(eta, ns_g_mass, ns_sequence, chi, incl, shift): """ Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart PRD 86, 124007 (2012). Parameters ----------- eta: float the symmetric mass ratio...
Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart PRD 86, 124007 (2012). Parameters ----------- eta: float the symmetric mass ratio of the binary ns_g_mass: float NS gravitational mass (in solar m...