code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None): """Given a ndarray dict, find the optimal threshold for quantizing each value of the key.""" if stats is None: raise ImportError('scipy.stats is required for running entropy mode of calculating' ...
Given a ndarray dict, find the optimal threshold for quantizing each value of the key.
def _parse_prior(self): """Read csv paths to list of dataframes.""" paths = self.prior_ if isinstance(paths, str): paths = [paths] chain_data = [] for path in paths: parsed_output = _read_output(path) for sample, sample_stats, config, adaptatio...
Read csv paths to list of dataframes.
def url_with_auth(regex, view, kwargs=None, name=None, prefix=''): """ if view is string based, must be a full path """ from djapiauth.auth import api_auth if isinstance(view, six.string_types): # view is a string, must be full path return url(regex, api_auth(import_by_path(prefix + "." + v...
if view is string based, must be a full path
def prepare(self, start=-1): """Setup the parser for parsing. Takes the starting symbol as an argument. """ if start == -1: start = self.grammar.start self.root = None current_node = Node(start, None, [], 0, 0) self.stack = [] self.stack.appen...
Setup the parser for parsing. Takes the starting symbol as an argument.
def GET(self, *args, **kwargs): """ GET request """ return self._handle_api(self.API_GET, args, kwargs)
GET request
def _chip_erase_program_double_buffer(self, progress_cb=_stub_progress): """! @brief Double-buffered program by first performing an erase all.""" LOG.debug("%i of %i pages have erased data", len(self.page_list) - self.chip_erase_count, len(self.page_list)) progress_cb(0.0) progress = 0 ...
! @brief Double-buffered program by first performing an erase all.
def inc(self): """Corrected inclination, taking into account backsight and clino corrections.""" inc1 = self.get('INC', None) inc2 = self.get('INC2', None) if inc1 is None and inc2 is None: return None if inc2 is None: return inc1 if inc1 is None: ...
Corrected inclination, taking into account backsight and clino corrections.
def list_storage_accounts(call=None): ''' List storage accounts within the subscription. ''' if call == 'action': raise SaltCloudSystemExit( 'The list_storage_accounts function must be called with ' '-f or --function' ) storconn = get_conn(client_type='storag...
List storage accounts within the subscription.
def update_module_state(cursor, module_ident, state_name, recipe): # pragma: no cover """This updates the module's state in the database.""" cursor.execute("""\ UPDATE modules SET stateid = ( SELECT stateid FROM modulestates WHERE statename = %s ), recipe = %s, baked = now() WHERE m...
This updates the module's state in the database.
def move(x, y, absolute=True, duration=0): """ Moves the mouse. If `absolute`, to position (x, y), otherwise move relative to the current position. If `duration` is non-zero, animates the movement. """ x = int(x) y = int(y) # Requires an extra system call on Linux, but `move_relative` is me...
Moves the mouse. If `absolute`, to position (x, y), otherwise move relative to the current position. If `duration` is non-zero, animates the movement.
def check_no_element_by_selector(self, selector): """Assert an element does not exist matching the given selector.""" elems = find_elements_by_jquery(world.browser, selector) if elems: raise AssertionError("Expected no matching elements, found {}.".format( len(elems)))
Assert an element does not exist matching the given selector.
def isodate(datestamp=None, microseconds=False): """Return current or given time formatted according to ISO-8601.""" datestamp = datestamp or datetime.datetime.now() if not microseconds: usecs = datetime.timedelta(microseconds=datestamp.microsecond) datestamp = datestamp - usecs return d...
Return current or given time formatted according to ISO-8601.
def add_lb_nodes(self, lb_id, nodes): """ Adds nodes to an existing LBaaS instance :param string lb_id: Balancer id :param list nodes: Nodes to add. {address, port, [condition]} :rtype :class:`list` """ log.info("Adding load balancer nodes %s" % nodes) ...
Adds nodes to an existing LBaaS instance :param string lb_id: Balancer id :param list nodes: Nodes to add. {address, port, [condition]} :rtype :class:`list`
def attributes(self, params=None): """ Gets the attributes from a Group/Indicator or Victim Yields: attribute json """ if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) for a in self.tc_re...
Gets the attributes from a Group/Indicator or Victim Yields: attribute json
def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): """Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion ...
Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion this may cause, if `is_training=False` and `keep_prob` would cause dropout to be applied, an error ...
def btc_bitcoind_tx_serialize( tx ): """ Convert a *Bitcoind*-given transaction into its hex string. tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...}, with the same formatting rules as getrawtransaction. (in particular, each value in vout is a Decimal, in BTC) ...
Convert a *Bitcoind*-given transaction into its hex string. tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...}, with the same formatting rules as getrawtransaction. (in particular, each value in vout is a Decimal, in BTC)
def setStr(self, name, n, value): """ setStr(CHeaderMap self, std::string name, limix::muint_t n, std::string value) Parameters ---------- name: std::string n: limix::muint_t value: std::string """ return _core.CHeaderMap_setStr(self, name, n, va...
setStr(CHeaderMap self, std::string name, limix::muint_t n, std::string value) Parameters ---------- name: std::string n: limix::muint_t value: std::string
def createmeta(self, projectKeys=None, projectIds=[], issuetypeIds=None, issuetypeNames=None, expand=None, ): """Get the metadata required to create issues, optionally filtered by projects and issue...
Get the metadata required to create issues, optionally filtered by projects and issue types. :param projectKeys: keys of the projects to filter the results with. Can be a single value or a comma-delimited string. May be combined with projectIds. :type projectKeys: Union[None, Tu...
def on(self, event, handler=None): """Register an event handler. :param event: The event name. Can be ``'connect'``, ``'message'`` or ``'disconnect'``. :param handler: The function that should be invoked to handle the event. When this parameter is n...
Register an event handler. :param event: The event name. Can be ``'connect'``, ``'message'`` or ``'disconnect'``. :param handler: The function that should be invoked to handle the event. When this parameter is not given, the method a...
def confindr_targets(self, database_name='ConFindr'): """ Download OLC-specific ConFindr targets :param database_name: name of current database """ logging.info('Downloading ConFindr databases.') # NOTE: Need ConFindr >= 0.5.0 for this to work. secret_file = os.pa...
Download OLC-specific ConFindr targets :param database_name: name of current database
def set_idlesleep(self, idlesleep): """ Sets CPU idle sleep time value. :param idlesleep: idle sleep value (integer) """ is_running = yield from self.is_running() if is_running: # router is running yield from self._hypervisor.send('vm set_idle_sleep_time "{...
Sets CPU idle sleep time value. :param idlesleep: idle sleep value (integer)
def reverse_tree(tree): """Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reverse...
Reverse the dependency tree. ie. the keys of the resulting dict are objects of type ReqPackage and the values are lists of DistPackage objects. :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :returns: reversed tree :rtype: dict
def nifti2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False): """Extract some meta-data from NIFTI files (actually mostly from their paths) and stores it in a DB. Arguments: :param file_path: File path. :param file_type: File type. :param is_copy: Indicate i...
Extract some meta-data from NIFTI files (actually mostly from their paths) and stores it in a DB. Arguments: :param file_path: File path. :param file_type: File type. :param is_copy: Indicate if this file is a copy. :param step_id: Step ID. :param db_conn: Database connection. :param sid_by...
def inject_python_code2(fpath, patch_code, tag): """ Does autogeneration stuff """ import utool as ut text = ut.readfrom(fpath) start_tag = '# <%s>' % tag end_tag = '# </%s>' % tag new_text = ut.replace_between_tags(text, patch_code, start_tag, end_tag) ut.writeto(fpath, new_text)
Does autogeneration stuff
def load_class_by_name(name: str): """Given a dotted path, returns the class""" mod_path, _, cls_name = name.rpartition('.') mod = importlib.import_module(mod_path) cls = getattr(mod, cls_name) return cls
Given a dotted path, returns the class
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1, database_filter=None): """Returns a BiopaxProcessor for a PathwayCommons paths-from-to query. The paths-from-to query finds the paths from a set of source genes to a set of target genes. http://www.path...
Returns a BiopaxProcessor for a PathwayCommons paths-from-to query. The paths-from-to query finds the paths from a set of source genes to a set of target genes. http://www.pathwaycommons.org/pc2/#graph http://www.pathwaycommons.org/pc2/#graph_kind Parameters ---------- source_genes : lis...
def _merge_expressions(self, other): """ Merge the inputs of two NumericalExpressions into a single input tuple, rewriting their respective string expressions to make input names resolve correctly. Returns a tuple of (new_self_expr, new_other_expr, new_inputs) """ ...
Merge the inputs of two NumericalExpressions into a single input tuple, rewriting their respective string expressions to make input names resolve correctly. Returns a tuple of (new_self_expr, new_other_expr, new_inputs)
def prepare(self): """ Prepare the Directory for use in an Environment. This will create the directory if the create flag is set. """ if self._create: self.create() for k in self._children: self._children[k]._env = self._env self._chil...
Prepare the Directory for use in an Environment. This will create the directory if the create flag is set.
def load_package(package_dir, package=None, exclude=None, default_section=_DEFAULT_SECTION): """ 从目录中载入配置文件 :param package_dir: :param package: :param exclude: :param default_section: :return: """ init_py = '__init__.py' py_ext = '.py' files = os.listdir(package_dir) if i...
从目录中载入配置文件 :param package_dir: :param package: :param exclude: :param default_section: :return:
def prettify_metrics(metrics: List[Tuple[str, float]], precision: int = 4) -> OrderedDict: """Prettifies the dictionary of metrics.""" prettified_metrics = OrderedDict() for key, value in metrics: value = round(value, precision) prettified_metrics[key] = value return prettified_metrics
Prettifies the dictionary of metrics.
def fit_ahrs(A, H, Aoff, Arot, Hoff, Hrot): """Calculate yaw, pitch and roll for given A/H and calibration set. Author: Vladimir Kulikovsky Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot:...
Calculate yaw, pitch and roll for given A/H and calibration set. Author: Vladimir Kulikovsky Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot: numpy.array of shape(3, 3) Hoff: numpy.array o...
def constant_jump_targets_and_jumpkinds(self): """ A dict of the static jump targets of the basic block to their jumpkind. """ exits = dict() if self.exit_statements: for _, _, stmt_ in self.exit_statements: exits[stmt_.dst.value] = stmt_.jumpkind ...
A dict of the static jump targets of the basic block to their jumpkind.
def active_element(self): """ Returns the element with focus, or BODY if nothing has focus. :Usage: :: element = driver.switch_to.active_element """ if self._driver.w3c: return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)['value']...
Returns the element with focus, or BODY if nothing has focus. :Usage: :: element = driver.switch_to.active_element
def find_file_ident_desc_by_name(self, currpath): # type: (bytes) -> UDFFileIdentifierDescriptor ''' A method to find a UDF File Identifier descriptor by its name. Parameters: currpath - The UTF-8 encoded name to look up. Returns: The UDF File Identifier descri...
A method to find a UDF File Identifier descriptor by its name. Parameters: currpath - The UTF-8 encoded name to look up. Returns: The UDF File Identifier descriptor corresponding to the passed in name.
def split_prefix(self, ctx, item): """See if ``item`` has blueprint prefix, return (directory, rel_path). """ app = ctx._app try: if hasattr(app, 'blueprints'): blueprint, name = item.split('/', 1) directory = get_static_folder(app.blueprints[b...
See if ``item`` has blueprint prefix, return (directory, rel_path).
def _lib(self, name, only_if_have=False): """Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`. """ ...
Specify a linker library. Example: LDFLAGS={{ lib("rt") }} {{ lib("pthread", True) }} Will unconditionally add `-lrt` and check the environment if the key `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`.
def ini_load_hook(cfg, **kwargs): """ This handles automatically opening/creating the INI configuration files. >>> import configmaster.INIConfigFile >>> cfg = configmaster.INIConfigFile.INIConfigFile("tesr.ini") # Accepts a string for input >>> fd = open("test.ini") # Accepts a file descriptor too...
This handles automatically opening/creating the INI configuration files. >>> import configmaster.INIConfigFile >>> cfg = configmaster.INIConfigFile.INIConfigFile("tesr.ini") # Accepts a string for input >>> fd = open("test.ini") # Accepts a file descriptor too >>> cfg2 = configmaster.INIConfigFile.INI...
def check_precondition(self, key, value): ''' Override to check for timeout ''' timeout = float(value) curr_time = self.get_current_time() if curr_time > timeout: return True return False
Override to check for timeout
def execute(self, operation, *args, **kwargs): '''execute High-level api: Supported operations are get, get_config, get_schema, dispatch, edit_config, copy_config, validate, commit, discard_changes, delete_config, lock, unlock, close_session, kill_session, poweroff_machine and r...
execute High-level api: Supported operations are get, get_config, get_schema, dispatch, edit_config, copy_config, validate, commit, discard_changes, delete_config, lock, unlock, close_session, kill_session, poweroff_machine and reboot_machine. Since ModelDevice is a subclass of ...
def _get_indexes_in_altered_table(self, diff): """ :param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict """ indexes = diff.from_table.get_indexes() column_names = self._get_column_names_in_altered_table(diff) for key, ind...
:param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict
def changes_found(self): """ Returns True if the target folder is older than the source folder. """ if self.dest is None: warnings.warn("dest directory not found!") if self.src is None: warnings.warn("src directory not found!") if self.src is None ...
Returns True if the target folder is older than the source folder.
def main(): ''' Set up "optparse" and pass the options to a new instance of L{LatexMaker}. ''' prog = 'latexmk.py' version = __version__ usage = '%prog [options] [filename]' # Read description from doc doc_text = '' for line in __doc__.splitlines(): if line.find('#') == ...
Set up "optparse" and pass the options to a new instance of L{LatexMaker}.
def account_id(self, value): """The account_id property. Args: value (string). the property value. """ if value == self._defaults['ai.user.accountId'] and 'ai.user.accountId' in self._values: del self._values['ai.user.accountId'] else: ...
The account_id property. Args: value (string). the property value.
def _bfs(node, visited): """Iterate through nodes in BFS order.""" queue = collections.deque() queue.appendleft(node) while queue: node = queue.pop() if node not in visited: if node.lo is not None: queue.appendleft(node.lo) if node.hi is not None: ...
Iterate through nodes in BFS order.
def get(self): """Get the contents of a GValue. The contents of the GValue are read out as a Python type. """ # logger.debug('GValue.get: self = %s', self) gtype = self.gvalue.g_type fundamental = gobject_lib.g_type_fundamental(gtype) result = None if...
Get the contents of a GValue. The contents of the GValue are read out as a Python type.
def decode(cls, string, errors='strict'): """Return the decoded version of a string. :param string: The input string to decode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: ...
Return the decoded version of a string. :param string: The input string to decode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: `basestring` :return: T...
def _get_base_defaultLayer(self): """ This is the environment implementation of :attr:`BaseFont.defaultLayer`. Return the default layer as a :class:`BaseLayer` object. The layer will be normalized with :func:`normalizers.normalizeLayer`. Subclasses must override ...
This is the environment implementation of :attr:`BaseFont.defaultLayer`. Return the default layer as a :class:`BaseLayer` object. The layer will be normalized with :func:`normalizers.normalizeLayer`. Subclasses must override this method.
def tag_dssp_solvent_accessibility(self, force=False): """Tags each `Residues` Polymer with its solvent accessibility. Notes ----- For more about DSSP's solvent accessibilty metric, see: http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC References ------...
Tags each `Residues` Polymer with its solvent accessibility. Notes ----- For more about DSSP's solvent accessibilty metric, see: http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC References ---------- .. [1] Kabsch W, Sander C (1983) "Dictionary of prote...
def received_response(self, value): """The received_response property. Args: value (string). the property value. """ if value == self._defaults['receivedResponse'] and 'receivedResponse' in self._values: del self._values['receivedResponse'] else: ...
The received_response property. Args: value (string). the property value.
def _init_sqlite_functions(self): """additional SQL functions to the database""" self.connection.create_function("sqrt", 1,sqlfunctions._sqrt) self.connection.create_function("sqr", 1,sqlfunctions._sqr) self.connection.create_function("periodic", 1,sqlfunctions._periodic) self.c...
additional SQL functions to the database
def on_start(self): """ start the service """ LOGGER.debug("natsd.Service.on_start") self.service = threading.Thread(target=self.run_event_loop, name=self.serviceQ + " service thread") self.service.start() while not self.is_started: time.sleep(0.01)
start the service
def create_handler(Model, name=None, **kwds): """ This factory returns an action handler that creates a new instance of the specified model when a create action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to c...
This factory returns an action handler that creates a new instance of the specified model when a create action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to create when the action received. Retur...
def delete_detector(self, detector_id, **kwargs): """Remove a detector. Args: detector_id (string): the ID of the detector. """ resp = self._delete(self._u(self._DETECTOR_ENDPOINT_SUFFIX, detector_id), **kwargs)...
Remove a detector. Args: detector_id (string): the ID of the detector.
def is_enable_action_dependent(self, hosts, services): """ Check if dependencies states match dependencies statuses This basically means that a dependency is in a bad state and it can explain this object state. :param hosts: hosts objects, used to get object in act_depend_of ...
Check if dependencies states match dependencies statuses This basically means that a dependency is in a bad state and it can explain this object state. :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: servi...
def dameraulevenshtein(seq1, seq2): """Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of ...
Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of comparable objects will work. Transpos...
def get(*args, **kwargs): """Get UserEXT objects.""" try: from invenio.modules.accounts.models import UserEXT except ImportError: from invenio_accounts.models import UserEXT q = UserEXT.query return q.count(), q.all()
Get UserEXT objects.
def search(self): """Search srt in project for cells matching list of terms.""" matches = [] for pattern in Config.patterns: matches += self.termfinder(pattern) return sorted(set(matches), key=int)
Search srt in project for cells matching list of terms.
def set_wx_window_layout(wx_window, layout): '''set a WinLayout for a wx window''' try: wx_window.SetSize(layout.size) wx_window.SetPosition(layout.pos) except Exception as ex: print(ex)
set a WinLayout for a wx window
def find_by_example(self, crash, offset = None, limit = None): """ Find all crash dumps that have common properties with the crash dump provided. Results can be paged to avoid consuming too much memory if the database is large. @see: L{find} @type crash: L{Cra...
Find all crash dumps that have common properties with the crash dump provided. Results can be paged to avoid consuming too much memory if the database is large. @see: L{find} @type crash: L{Crash} @param crash: Crash object to compare with. Fields set to C{None} are ...
def json_to_string(value, null_string_repr='[]', trimable=False): """ Return a string representation of the specified JSON object. @param value: a JSON object. @param null_string_rep: the string representation of the null object. @return: a string representation of the specified JSON obje...
Return a string representation of the specified JSON object. @param value: a JSON object. @param null_string_rep: the string representation of the null object. @return: a string representation of the specified JSON object.
def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ...
Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string ...
def build(self, docs=None, filename=None): """Build FM-index Params: <iterator> | <generator> docs <str> filename """ if docs: if hasattr(docs, 'items'): for (idx, doc) in sorted(getattr(docs, 'items')(), ...
Build FM-index Params: <iterator> | <generator> docs <str> filename
def first_interesting_frame(self): """ Traverse down the frame hierarchy until a frame is found with more than one child """ root_frame = self.root_frame() frame = root_frame while len(frame.children) <= 1: if frame.children: frame = frame.chi...
Traverse down the frame hierarchy until a frame is found with more than one child
def has_credentials(self): """Returns True if there are valid credentials for the current user and required scopes.""" credentials = _credentials_from_request(self.request) return (credentials and not credentials.invalid and credentials.has_scopes(self._get_scopes()))
Returns True if there are valid credentials for the current user and required scopes.
def stylize(obj, style='plastique', theme='projexui'): """ Styles the inputed object with the given options. :param obj | <QtGui.QWidget> || <QtGui.QApplication> style | <str> base | <str> """ obj.setStyle(style) if theme: shee...
Styles the inputed object with the given options. :param obj | <QtGui.QWidget> || <QtGui.QApplication> style | <str> base | <str>
def delete_property(self, key): """Remove a property from the document. Calling code should use this method to remove properties on the document instead of modifying ``properties`` directly. If there is a property with the name in ``key``, it will be removed. Otherwise, a ``Key...
Remove a property from the document. Calling code should use this method to remove properties on the document instead of modifying ``properties`` directly. If there is a property with the name in ``key``, it will be removed. Otherwise, a ``KeyError`` will be thrown.
def create_vmfs_datastore(host_ref, datastore_name, disk_ref, vmfs_major_version, storage_system=None): ''' Creates a VMFS datastore from a disk_id host_ref vim.HostSystem object referencing a host to create the datastore on datastore_name Name of the datastor...
Creates a VMFS datastore from a disk_id host_ref vim.HostSystem object referencing a host to create the datastore on datastore_name Name of the datastore disk_ref vim.HostScsiDislk on which the datastore is created vmfs_major_version VMFS major version to use
def delete_bams(job, bams, patient_id): """ Delete the bams from the job Store once their purpose has been achieved (i.e. after all mutation calling steps). Will also delete the chimeric junction file from Star. :param dict bams: Dict of bam and bai files :param str patient_id: The ID of the patien...
Delete the bams from the job Store once their purpose has been achieved (i.e. after all mutation calling steps). Will also delete the chimeric junction file from Star. :param dict bams: Dict of bam and bai files :param str patient_id: The ID of the patient for logging purposes.
def _add_loss_summaries(total_loss): """Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages ...
Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages of losses.
def recurrent_transformer_decoder( decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder", nonpadding=None, save_weights_to=None, make_image_summary=True): """Recurrent decoder function.""" x = decoder_input attention...
Recurrent decoder function.
async def addMachines(self, params=None): """ :param params dict: Dictionary specifying the machine to add. All keys are optional. Keys include: series: string specifying the machine OS series. constraints: string holding machine constraints, if any. We'...
:param params dict: Dictionary specifying the machine to add. All keys are optional. Keys include: series: string specifying the machine OS series. constraints: string holding machine constraints, if any. We'll parse this into the json friendly dict that...
def timedelta_seconds(td): ''' Return the offset stored by a :class:`datetime.timedelta` object as an integer number of seconds. Microseconds, if present, are rounded to the nearest second. Delegates to :meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>` if available. ...
Return the offset stored by a :class:`datetime.timedelta` object as an integer number of seconds. Microseconds, if present, are rounded to the nearest second. Delegates to :meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>` if available. >>> timedelta_seconds(timedelta(hour...
def is_path_python_module(thepath): """ Given a path, find out of the path is a python module or is inside a python module. """ thepath = path.normpath(thepath) if path.isfile(thepath): base, ext = path.splitext(thepath) if ext in _py_suffixes: return True ...
Given a path, find out of the path is a python module or is inside a python module.
def target_for_product(self, product): """Looks up the target key for a product. :API: public :param product: The product to search for :return: None if there is no target for the product """ for target, products in self._products_by_target.items(): if product in products: return...
Looks up the target key for a product. :API: public :param product: The product to search for :return: None if there is no target for the product
def users(self): """ List of users of this slack team """ if not self._users: self._users = self._call_api('users.list')['members'] return self._users
List of users of this slack team
def kinesia_scores(self, data_frame): """ This method calculates the number of key taps :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ks: key taps :rtype ks: float :return duration: test duration (seconds) ...
This method calculates the number of key taps :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ks: key taps :rtype ks: float :return duration: test duration (seconds) :rtype duration: float
def reverse_index_mapping(self): """Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array """ if self._reverse_index_mapp...
Get mapping from this segment's indexes to the indexes of the base array. If the index is < 0, the index is out of range, meaning that it doesn't exist in this segment and is not mapped to the base array
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects',...
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
def validate(self, arg=None): """Check that inputted path is valid - set validator accordingly""" if os.path.isdir(self.path): self.validator.object = None else: self.validator.object = ICONS['error']
Check that inputted path is valid - set validator accordingly
def set_child_value( self, sensor_id, child_id, value_type, value, **kwargs): """Add a command to set a sensor value, to the queue. A queued command will be sent to the sensor when the gateway thread has sent all previously queued commands. If the sensor attribute new_state...
Add a command to set a sensor value, to the queue. A queued command will be sent to the sensor when the gateway thread has sent all previously queued commands. If the sensor attribute new_state returns True, the command will be buffered in a queue on the sensor, and only the internal s...
def remove_root_family(self, family_id): """Removes a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: NotFound - ``family_id`` not a root raise: NullArgument - ``family_id`` is ``null`` raise: OperationFailed - unable to complete request rai...
Removes a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: NotFound - ``family_id`` not a root raise: NullArgument - ``family_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure ...
def CLJP(S, color=False): """Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP coloring approach Returns ------...
Compute a C/F splitting using the parallel CLJP algorithm. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) color : bool use the CLJP coloring approach Returns ------- splitting : array A...
def set_up(self): """ This class overrides this method """ self.menu.pause() curses.def_prog_mode() self.menu.clear_screen()
This class overrides this method
def Kn2Der(nu, y, n=0): r"""Find the derivatives of :math:`K_\nu(y^{1/2})`. Parameters ---------- nu : float The order of the modified Bessel function of the second kind. y : array of float The values to evaluate at. n : nonnegative int, optional The order of derivat...
r"""Find the derivatives of :math:`K_\nu(y^{1/2})`. Parameters ---------- nu : float The order of the modified Bessel function of the second kind. y : array of float The values to evaluate at. n : nonnegative int, optional The order of derivative to take.
def send_all(): """ Send all eligible messages in the queue. """ # The actual backend to use for sending, defaulting to the Django default. # To make testing easier this is not stored at module level. EMAIL_BACKEND = getattr( settings, "MAILER_EMAIL_BACKEND", "django.core...
Send all eligible messages in the queue.
def select(self): """Select Slackware command """ print("\nDetected Slackware binary package for installation:\n") for pkg in self.packages: print(" " + pkg.split("/")[-1]) print("") self.msg.template(78) print("| Choose a Slackware command:") ...
Select Slackware command
def dict_to_path(as_dict): """ Turn a pure dict into a dict containing entity objects that can be sent directly to a Path constructor. Parameters ----------- as_dict : dict Has keys: 'vertices', 'entities' Returns ------------ kwargs : dict Has keys: 'vertices', 'entiti...
Turn a pure dict into a dict containing entity objects that can be sent directly to a Path constructor. Parameters ----------- as_dict : dict Has keys: 'vertices', 'entities' Returns ------------ kwargs : dict Has keys: 'vertices', 'entities'
def subselect(self, obj): """ Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults . """ return dict( (key, value) for (key, value) in obj.items() if key in self.defaults)
Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults .
def p_statements(self, p): """statements : statements statement | statement """ n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = ['statements', p[1]]
statements : statements statement | statement
def _build_cache(): """Build sets cache.""" sets = current_oaiserver.sets if sets is None: # build sets cache sets = current_oaiserver.sets = [ oaiset.spec for oaiset in OAISet.query.filter( OAISet.search_pattern.is_(None)).all()] return sets
Build sets cache.
def resolve(self, var, context): """Resolves a variable out of context if it's not in quotes""" if var is None: return var if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context)
Resolves a variable out of context if it's not in quotes
def record_get(self, creative_ids, nick=None): '''xxxxx.xxxxx.creatives.record.get =================================== 根据一个创意Id列表取得创意对应的修改记录''' request = TOPRequest('xxxxx.xxxxx.creatives.record.get') request['creative_ids'] = creative_ids if nick!=None: request['nick'] =...
xxxxx.xxxxx.creatives.record.get =================================== 根据一个创意Id列表取得创意对应的修改记录
def Then(self, f, *args, **kwargs): """ `Then(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ return self.ThenAt(1, f, *args, **kwargs)
`Then(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def unit_client(self): # type: () -> TCPClient """Return a TCPClient with same settings of the batch TCP client""" client = TCPClient(self.host, self.port, self.prefix) self._configure_client(client) return client
Return a TCPClient with same settings of the batch TCP client
def main(argv=None, directory=None): """ Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run """ logging.basicConfig(format='%(message)s') argv = argv or sys.argv arg_dict = pa...
Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run
def get_file_systems(filesystemid=None, keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): ''' Get all EFS properties or a specific instance property if...
Get all EFS properties or a specific instance property if filesystemid is specified filesystemid (string) - ID of the file system to retrieve properties creation_token (string) - A unique token that identifies an EFS. If fileysystem created via create_file_system this would ...
def list(self): """Lists all sessions in the store. .. versionadded:: 0.6 """ before, after = self.filename_template.split('%s', 1) filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before), re.escape(after))) resul...
Lists all sessions in the store. .. versionadded:: 0.6
def single_val(self): """return relative error of worst point that might make the data none symmetric. """ sv_t = self._sv(self._tdsphere) sv_p = self._sv(self._tdsphere) return (sv_t, sv_p)
return relative error of worst point that might make the data none symmetric.
def output(self, output, status=None): """Output text to stdout or a pager command. The status text is not outputted to pager or files. The message will be logged in the audit log, if enabled. The message will be written to the tee file, if enabled. The message will be written to...
Output text to stdout or a pager command. The status text is not outputted to pager or files. The message will be logged in the audit log, if enabled. The message will be written to the tee file, if enabled. The message will be written to the output file, if enabled.
def _set_automatic_tag(self, v, load=False): """ Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method...
Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should d...