code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_virtual_transactions(blockchain_name, blockchain_opts, first_block_height, last_block_height, tx_filter=None, **hints): """ Get the sequence of virtualchain transactions from a particular blockchain over a given range of block heights. Returns a list of tuples in the format of [(block height, [txs])...
Get the sequence of virtualchain transactions from a particular blockchain over a given range of block heights. Returns a list of tuples in the format of [(block height, [txs])], where each tx in [txs] is the parsed transaction. The parsed transaction will conform to... # TODO write a spec for this Ea...
def align_bam(in_bam, ref_file, names, align_dir, data): """Perform realignment of input BAM file; uses unix pipes for avoid IO. """ config = data["config"] out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) novoalign = config_utils.get_program("novoalign", config) samtools...
Perform realignment of input BAM file; uses unix pipes for avoid IO.
def writeTraining(self, file_obj): # pragma: no cover """ Write to a json file that contains labeled examples Keyword arguments: file_obj -- file object to write training data to """ json.dump(self.training_pairs, file_obj, default=s...
Write to a json file that contains labeled examples Keyword arguments: file_obj -- file object to write training data to
def nonull_dict(self): """Like dict, but does not hold any null values. :return: """ return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}
Like dict, but does not hold any null values. :return:
def _connect_database(config): """Create simple connection with Mongodb config comes with settings from .ini file. """ settings = config.registry.settings mongo_uri = "mongodb://localhost:27017" mongodb_name = "test" if settings.get("mongo_url"): mongo_uri = settings["mongo_url"] ...
Create simple connection with Mongodb config comes with settings from .ini file.
def options(self, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params): """Calls the service at the specified URL using the "OPTIONS" method""" return self.request('OPTIONS', url=url, headers=headers, timeout=timeout, **params)
Calls the service at the specified URL using the "OPTIONS" method
def raise_errors_on_nested_writes(method_name, serializer, validated_data): """ Give explicit errors when users attempt to pass writable nested data. If we don't do this explicitly they'd get a less helpful error when calling `.save()` on the serializer. We don't *automatically* support these sort...
Give explicit errors when users attempt to pass writable nested data. If we don't do this explicitly they'd get a less helpful error when calling `.save()` on the serializer. We don't *automatically* support these sorts of nested writes because there are too many ambiguities to define a default behavi...
def matrix_chain_mult(M): """Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications """ opt, arg = matrix_mult_opt_order(M) return _apply_order(M, arg, 0, len(M)-1)
Matrix chain multiplication :param M: list of matrices :returns: M[0] * ... * M[-1], computed in time optimal order :complexity: whatever is needed by the multiplications
def _load_greedy(self, module_name, dependencies, recursive): """Keeps loading modules in the filepaths dictionary until all have been loaded or the module is found.""" found = module_name in self.modules allmodules = list(self._pathfiles.keys()) i = 0 while not found an...
Keeps loading modules in the filepaths dictionary until all have been loaded or the module is found.
def getData(self): """Get data of the GitHub user.""" url = self.server + self.name data = GitHubUser.__getDataFromURL(url) web = BeautifulSoup(data, "lxml") self.__getContributions(web) self.__getLocation(web) self.__getAvatar(web) self.__getNumberOfRepos...
Get data of the GitHub user.
def folderitems(self): """TODO: Refactor to non-classic mode """ items = super(ARTemplateAnalysesView, self).folderitems() self.categories.sort() return items
TODO: Refactor to non-classic mode
def _get_bit(self, n, hash_bytes): """ Determines if the n-th bit of passed bytes is 1 or 0. Arguments: hash_bytes - List of hash byte values for which the n-th bit value should be checked. Each element of the list should be an integer from 0 to 255. Retu...
Determines if the n-th bit of passed bytes is 1 or 0. Arguments: hash_bytes - List of hash byte values for which the n-th bit value should be checked. Each element of the list should be an integer from 0 to 255. Returns: True if the bit is 1. False if the bit ...
def server_info_cb(self, context, server_info_p, userdata): """Retrieves the default sink and calls request_update""" server_info = server_info_p.contents self.request_update(context)
Retrieves the default sink and calls request_update
def sample_u(self, q): r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Ba...
r"""Extract a sample from random variates uniform on :math:`[0, 1]`. For a univariate distribution, this is simply evaluating the inverse CDF. To facilitate efficient sampling, this function returns a *vector* of PPF values, one value for each variable. Basically, the idea is that, ...
def qteSetKeyFilterPolicy(self, receiveBefore: bool=False, useQtmacs: bool=None, receiveAfter: bool=False): """ Set the policy on how Qtmacs filters keyboard events for a particular widgets. The options can be arbitrarily combi...
Set the policy on how Qtmacs filters keyboard events for a particular widgets. The options can be arbitrarily combined, eg. :: widget.qteSetKeyFilterPolicy(True, True, False) will first pass the event to the applet's ``keyPressEvent`` method and afterwards pass the same ev...
def _wrap_callback_parse_alarm_data(subscription, on_data, message): """ Wraps an (optional) user callback to parse Alarm data from a WebSocket data message """ if (message.type == message.DATA and message.data.type == yamcs_pb2.ALARM_DATA): proto = getattr(message.data, 'alarmDa...
Wraps an (optional) user callback to parse Alarm data from a WebSocket data message
def set_raw(self,text): """ Sets the text of the raw element (or creates the layer if does not exist) @param text: text of the raw layer @type text: string """ node_raw = self.root.find('raw') if node_raw is None: node_raw = etree.Element('raw') ...
Sets the text of the raw element (or creates the layer if does not exist) @param text: text of the raw layer @type text: string
def get_labs(format): """Gets Techshop data from techshop.ws.""" techshops_soup = data_from_techshop_ws(techshop_us_url) techshops = {} # Load all the TechShops # By first parsing the html data = techshops_soup.findAll('div', attrs={'id': 'main-content'}) for element in data: link...
Gets Techshop data from techshop.ws.
def update(self, file): """ Make an update query on Github API for given file :param file: File to update, with its content :return: File with new information, including success (or Error) """ params = { "message": file.logs, "author": file.author.dict(),...
Make an update query on Github API for given file :param file: File to update, with its content :return: File with new information, including success (or Error)
def guard_cancel(analysis_request): """Returns whether 'cancel' transition can be performed or not. Returns True only if all analyses are in "unassigned" status """ # Ask to partitions for partition in analysis_request.getDescendants(all_descendants=False): if not isTransitionAllowed(partiti...
Returns whether 'cancel' transition can be performed or not. Returns True only if all analyses are in "unassigned" status
async def _execute(self, fn, *args, **kwargs): """Execute the given function on the shared connection's thread.""" return await self._conn._execute(fn, *args, **kwargs)
Execute the given function on the shared connection's thread.
def _execute_phase_once(self, phase_desc, is_last_repeat): """Executes the given phase, returning a PhaseExecutionOutcome.""" # Check this before we create a PhaseState and PhaseRecord. if phase_desc.options.run_if and not phase_desc.options.run_if(): _LOG.debug('Phase %s skipped due to run_if returni...
Executes the given phase, returning a PhaseExecutionOutcome.
def validate_utf8(alleged_utf8, error = None) : "alleged_utf8 must be null-terminated bytes." error, my_error = _get_error(error) result = dbus.dbus_validate_utf8(alleged_utf8, error._dbobj) != 0 my_error.raise_if_set() return \ result
alleged_utf8 must be null-terminated bytes.
def _f_preactivations(self, X): """Computes the network preactivations, i.e. the results of all intermediate linear layers before applying the activation function on them :param X: input data :return: list of preactivations [X, XW+b, f(XW+b)W+b, ...] """ preactivations_l...
Computes the network preactivations, i.e. the results of all intermediate linear layers before applying the activation function on them :param X: input data :return: list of preactivations [X, XW+b, f(XW+b)W+b, ...]
def get_arguments(self): """ Extracts the specific arguments of this CLI """ # ApiCli.get_arguments(self) if self.args.file_name is not None: self.file_name = self.args.file_name
Extracts the specific arguments of this CLI
def retrieve_all(self): """ A generator that iterates over each card in the library database. This is best used in for loops as it will only load a card from the library as needed rather then all at once. """ with sqlite3.connect(self.dbname) as carddb: for r...
A generator that iterates over each card in the library database. This is best used in for loops as it will only load a card from the library as needed rather then all at once.
def dispatch_subcommand(self, parser): ''' Note that the way we're doing this is elegant, but dangerous. It doesn't require, but does encourage, us to define no Application# methods beyond those corresponding to the supported subcommands ''' # read in the subcommand ...
Note that the way we're doing this is elegant, but dangerous. It doesn't require, but does encourage, us to define no Application# methods beyond those corresponding to the supported subcommands
def find_observatories(self, match=None): """Query the LDR host for observatories. Use match to restrict returned observatories to those matching the regular expression. Example: >>> connection.find_observatories() ['AGHLT', 'G', 'GHLTV', 'GHLV', 'GHT', 'H', 'HL', 'HLT'...
Query the LDR host for observatories. Use match to restrict returned observatories to those matching the regular expression. Example: >>> connection.find_observatories() ['AGHLT', 'G', 'GHLTV', 'GHLV', 'GHT', 'H', 'HL', 'HLT', 'L', 'T', 'V', 'Z'] >>> connection...
def _identify_prefix(self, msg, data): ''' Check the message again each OS prefix and if matched return the message dict ''' prefix_id = -1 for prefix in data: msg_dict = {} prefix_id += 1 match = None if '__python_fun__' in...
Check the message again each OS prefix and if matched return the message dict
def _validate_attrs(dataset): """`attrs` must have a string key and a value which is either: a number, a string, an ndarray or a list/tuple of numbers/strings. """ def check_attr(name, value): if isinstance(name, str): if not name: raise ValueError('Invalid name for a...
`attrs` must have a string key and a value which is either: a number, a string, an ndarray or a list/tuple of numbers/strings.
def get_attribute(self, name): """ Retrieves specified attribute from WebElement @type name: str @param name: Attribute to retrieve @rtype: str @return: String representation of the attribute """ def get_attribute_element(): ...
Retrieves specified attribute from WebElement @type name: str @param name: Attribute to retrieve @rtype: str @return: String representation of the attribute
def minimize_one_step(gradient_unregularized_loss, hessian_unregularized_loss_outer, hessian_unregularized_loss_middle, x_start, tolerance, l1_regularizer, l2_regularizer=None, ...
One step of (the outer loop of) the minimization algorithm. This function returns a new value of `x`, equal to `x_start + x_update`. The increment `x_update in R^n` is computed by a coordinate descent method, that is, by a loop in which each iteration updates exactly one coordinate of `x_update`. (Some updat...
def _stop_transport(self): """ Close the underlying transport when nothing more is needed """ try: self._check_is_started() except (BaseSSHTunnelForwarderError, HandlerSSHTunnelForwarderError) as e: self.logger.warning(e) for _srv in self._server_l...
Close the underlying transport when nothing more is needed
def compare(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms ...
compare word1 and word2 for equality regardless of plurality return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise
def click_element_at_coordinates(self, coordinate_X, coordinate_Y): """ click element at a certain coordinate """ self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y)) driver = self._current_application() action = TouchAction(driver) action.press(x=coordinate_X,...
click element at a certain coordinate
def ask(self, question, default=False): """ Ask a y/n question to the user. """ choices = '[%s/%s]' % ('Y' if default else 'y', 'n' if default else 'N') while True: response = raw_input('%s %s' % (question, choices)).strip() if not response: return...
Ask a y/n question to the user.
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow): ''' Find endogenous interpolation points for each asset point and each discrete preference shock. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np....
Find endogenous interpolation points for each asset point and each discrete preference shock. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array Array of end-of-period asset values that yield the margina...
def populateFromRow(self, referenceSetRecord): """ Populates this reference set from the values in the specified DB row. """ self._dataUrl = referenceSetRecord.dataurl self._description = referenceSetRecord.description self._assemblyId = referenceSetRecord.assembl...
Populates this reference set from the values in the specified DB row.
def append_var_uint32(self, value): """Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint. """ if not 0 <= value <= wire_format.UINT32_MAX: raise errors.EncodeError('Value out of range: %d' % value) self.append_var_uint64(value)
Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint.
def require_scalar(self, *args: Type) -> None: """Require the node to be a scalar. If additional arguments are passed, these are taken as a list \ of valid types; if the node matches one of these, then it is \ accepted. Example: # Match either an int or a string ...
Require the node to be a scalar. If additional arguments are passed, these are taken as a list \ of valid types; if the node matches one of these, then it is \ accepted. Example: # Match either an int or a string node.require_scalar(int, str) Arguments:...
def _format_line(self, side, flag, linenum, text): """Returns HTML markup of "from" / "to" text lines side -- 0 or 1 indicating "from" or "to" text flag -- indicates if difference on line linenum -- line number (used for line number column) text -- line text to be marked up ...
Returns HTML markup of "from" / "to" text lines side -- 0 or 1 indicating "from" or "to" text flag -- indicates if difference on line linenum -- line number (used for line number column) text -- line text to be marked up
def _generateRangeDescription(self, ranges): """generate description from a text description of the ranges""" desc = "" numRanges = len(ranges) for i in xrange(numRanges): if ranges[i][0] != ranges[i][1]: desc += "%.2f-%.2f" % (ranges[i][0], ranges[i][1]) else: desc += "%.2f"...
generate description from a text description of the ranges
def camel_to_(s): """ Convert CamelCase to camel_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Convert CamelCase to camel_case
def go_in(self, vertex): """ Tell the edge to go into this vertex. Args: vertex (Vertex): vertex to go into. """ if self.vertex_in: self.vertex_in.edges_in.remove(self) self.vertex_in = vertex vertex.edges_in.add(self)
Tell the edge to go into this vertex. Args: vertex (Vertex): vertex to go into.
def delete_service_settings_on_scope_delete(sender, instance, **kwargs): """ If VM that contains service settings were deleted - all settings resources could be safely deleted from NC. """ for service_settings in ServiceSettings.objects.filter(scope=instance): service_settings.unlink_descend...
If VM that contains service settings were deleted - all settings resources could be safely deleted from NC.
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
Unified rounding in all python versions.
def mse(y_true, y_pred): """Mean squared error """ y_true, y_pred = _mask_nan(y_true, y_pred) return ((y_true - y_pred) ** 2).mean(axis=None)
Mean squared error
def _decrypt(message, encryption_data, key_encryption_key=None, resolver=None): ''' Decrypts the given ciphertext using AES256 in CBC mode with 128 bit padding. Unwraps the content-encryption-key using the user-provided or resolved key-encryption-key (kek). Returns the original plaintex. :param str mes...
Decrypts the given ciphertext using AES256 in CBC mode with 128 bit padding. Unwraps the content-encryption-key using the user-provided or resolved key-encryption-key (kek). Returns the original plaintex. :param str message: The ciphertext to be decrypted. :param _EncryptionData encryption_data: ...
def get_pay_giftcard(self, rule_id): """ 查询支付后投放卡券的规则 详情请参见 https://mp.weixin.qq.com/wiki?id=mp1466494654_K9rNz :param rule_id: 支付即会员的规则 ID :return: 支付后投放卡券的规则 :rtype: dict """ return self._post( 'card/paygiftcard/getbyid', ...
查询支付后投放卡券的规则 详情请参见 https://mp.weixin.qq.com/wiki?id=mp1466494654_K9rNz :param rule_id: 支付即会员的规则 ID :return: 支付后投放卡券的规则 :rtype: dict
def transform_binary_dist(self, archive_path): """ Transform binary distributions into a form that can be cached for future use. :param archive_path: The pathname of the original binary distribution archive. :returns: An iterable of tuples with two values each: 1. A :...
Transform binary distributions into a form that can be cached for future use. :param archive_path: The pathname of the original binary distribution archive. :returns: An iterable of tuples with two values each: 1. A :class:`tarfile.TarInfo` object. 2. A file-like ob...
def load_fits(self): ''' Load the FITS file from disk and populate the class instance with its data. ''' log.info("Loading FITS file for %d." % (self.ID)) with pyfits.open(self.fitsfile) as f: # Params and long cadence data self.loaded = True ...
Load the FITS file from disk and populate the class instance with its data.
def get_domain_smarthost(self, domainid, serverid): """Get a domain smarthost""" return self.api_call( ENDPOINTS['domainsmarthosts']['get'], dict(domainid=domainid, serverid=serverid))
Get a domain smarthost
def make_force_ES(q_vars, mass): """Fluxion with the potential energy of the earth-sun sytem""" # Build the potential energy fluxion; just one pair of bodies U = U_ij(q_vars, mass, 0, 1) # Varname arrays for both the coordinate system and U vn_q = np.array([q.var_name for q in q_vars]) vn_fl = ...
Fluxion with the potential energy of the earth-sun sytem
def regex_findall_variables(content): """ extract all variable names from content, which is in format $variable Args: content (str): string content Returns: list: variables list extracted from string content Examples: >>> regex_findall_variables("$variable") ["variable...
extract all variable names from content, which is in format $variable Args: content (str): string content Returns: list: variables list extracted from string content Examples: >>> regex_findall_variables("$variable") ["variable"] >>> regex_findall_variables("/blog...
def coordinates(self): ''' Tuple of Decimals in the form of (lat, lon) or None ''' if not getattr(self, '_coordinates', False): query_params = { 'prop': 'coordinates', 'colimit': 'max', 'titles': self.title, } request = _wiki_request(query_params) if 'qu...
Tuple of Decimals in the form of (lat, lon) or None
def cli(ctx, verbose, config): """ IPS Vagrant Management Utility """ assert isinstance(ctx, Context) # Set up the logger verbose = verbose if (verbose <= 3) else 3 log_levels = {1: logging.WARN, 2: logging.INFO, 3: logging.DEBUG} log_level = log_levels[verbose] ctx.log = logging.ge...
IPS Vagrant Management Utility
def read(self, len=1024): """Read up to LEN bytes and return them. Return zero-length string on EOF.""" while True: try: return self._sslobj.read(len) except SSLError: ex = sys.exc_info()[1] if ex.args[0] == SSL_ERROR_EOF an...
Read up to LEN bytes and return them. Return zero-length string on EOF.
def FromMilliseconds(self, millis): """Converts milliseconds since epoch to Timestamp.""" self.seconds = millis // _MILLIS_PER_SECOND self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND
Converts milliseconds since epoch to Timestamp.
def forward(self, inputs: torch.Tensor, tags: torch.Tensor, mask: torch.ByteTensor = None) -> torch.Tensor: """ Computes the log likelihood. """ # pylint: disable=arguments-differ if mask is None: mask = torch.ones(*tags...
Computes the log likelihood.
def max_tot_value(self, value): """Set maximum ToT value that is considered to be a hit""" self._max_tot_value = value self.interpreter.set_max_tot(self._max_tot_value) self.histogram.set_max_tot(self._max_tot_value) self.clusterizer.set_max_hit_charge(self._max_tot_value)
Set maximum ToT value that is considered to be a hit
def _generate_cache(self): """ Scan the path for distributions and populate the cache with those that are found. """ gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in ...
Scan the path for distributions and populate the cache with those that are found.
def get_obj(app_label, model_name, object_id): """ Function used to get a object :param app_label: A valid Django Model or a string with format: <app_label>.<model_name> :param model_name: Key into kwargs that contains de data: new_person :param object_id: :return: instance """ try: ...
Function used to get a object :param app_label: A valid Django Model or a string with format: <app_label>.<model_name> :param model_name: Key into kwargs that contains de data: new_person :param object_id: :return: instance
def register(self, hook): """ Register a hook. @hook: a HookBase subclass reference. """ assert callable(hook), \ "Hook must be a callable" assert issubclass(hook, HookBase), \ "The hook does not inherit from HookBase" self._registry.appe...
Register a hook. @hook: a HookBase subclass reference.
def limit_dragpos(self): '''limit dragpos to sane values''' if self.dragpos.x < 0: self.dragpos.x = 0 if self.dragpos.y < 0: self.dragpos.y = 0 if self.img is None: return if self.dragpos.x >= self.img.GetWidth(): self.dragpos.x = s...
limit dragpos to sane values
def connection_service_name(service, *args): ''' the name of a service that manages the connection between services ''' # if the service is a string if isinstance(service, str): return service return normalize_string(type(service).__name__)
the name of a service that manages the connection between services
def download_segmentation_image(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint=0, zplane=0, align = False): '''Downloads a segmentation image. Parameters ---------- plate_id: int ID of the parent experiment mapobject_type...
Downloads a segmentation image. Parameters ---------- plate_id: int ID of the parent experiment mapobject_type_name: str name of the segmented objects plate_name: str name of the plate well_name: str name of the well in whi...
def set_all_ylims(self, ylim, dy, yscale, fontsize=None): """Set limits and ticks for y axis for whole figure. This will set y axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: ylim (len-2 list of floats): The limits for t...
Set limits and ticks for y axis for whole figure. This will set y axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: ylim (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by between the l...
def theta_limit(theta): """ Angle theta is periodic with period pi. Constrain theta such that -pi/2<theta<=pi/2. Parameters ---------- theta : float Input angle. Returns ------- theta : float Rotate angle. """ while theta <= -1 * np.pi / 2: theta += ...
Angle theta is periodic with period pi. Constrain theta such that -pi/2<theta<=pi/2. Parameters ---------- theta : float Input angle. Returns ------- theta : float Rotate angle.
def _parse_attribute_details_file(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ # Parse content from remote file URL, which may be stored in one of two places: # Starting at: contentInfo/MD_FeatureCatalogueDescription/featu...
Concatenates a list of Attribute Details data structures parsed from a remote file
def sum_rightmost_ndims_preserving_shape(x, ndims): """Return `Tensor` with right-most ndims summed. Args: x: the `Tensor` whose right-most `ndims` dimensions to sum ndims: number of right-most dimensions to sum. Returns: A `Tensor` resulting from calling `reduce_sum` on the `ndims` right-most d...
Return `Tensor` with right-most ndims summed. Args: x: the `Tensor` whose right-most `ndims` dimensions to sum ndims: number of right-most dimensions to sum. Returns: A `Tensor` resulting from calling `reduce_sum` on the `ndims` right-most dimensions. If the shape of `x` is statically known, the r...
def _set_ve(self, v, load=False): """ Setter method for ve, mapped from YANG variable /overlay_gateway/ip/interface/ve (container) If this variable is read-only (config: false) in the source YANG file, then _set_ve is considered as a private method. Backends looking to populate this variable should ...
Setter method for ve, mapped from YANG variable /overlay_gateway/ip/interface/ve (container) If this variable is read-only (config: false) in the source YANG file, then _set_ve is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ve() direct...
def sync(self): """Retrieve areas from ElkM1""" self.elk.send(cs_encode()) self.get_descriptions(TextDescriptions.OUTPUT.value)
Retrieve areas from ElkM1
def write_single_register(self, reg_addr, reg_value): """Modbus function WRITE_SINGLE_REGISTER (0x06) :param reg_addr: register address (0 to 65535) :type reg_addr: int :param reg_value: register value to write :type reg_value: int :returns: True if write ok or None if f...
Modbus function WRITE_SINGLE_REGISTER (0x06) :param reg_addr: register address (0 to 65535) :type reg_addr: int :param reg_value: register value to write :type reg_value: int :returns: True if write ok or None if fail :rtype: bool or None
def ridgeplot(self, mult, linewidth, alpha, ax): """Draw ridgeplot for each plotter. Parameters ---------- mult : float How much to multiply height by. Set this to greater than 1 to have some overlap. linewidth : float Width of line on border of ridges ...
Draw ridgeplot for each plotter. Parameters ---------- mult : float How much to multiply height by. Set this to greater than 1 to have some overlap. linewidth : float Width of line on border of ridges alpha : float Transparency of ridges ...
def paintEvent(self, event): """Qt Override. Include a validation icon to the left of the line edit. """ super(IconLineEdit, self).paintEvent(event) painter = QPainter(self) rect = self.geometry() space = int((rect.height())/6) h = rect.height() - space ...
Qt Override. Include a validation icon to the left of the line edit.
def run(self): '''compile the JS, then run superclass implementation''' if subprocess.call(['npm', '--version']) != 0: raise RuntimeError('npm is required to build the HTML renderer.') self.check_call(['npm', 'install'], cwd=HTML_RENDERER_DIR) self.check_call(['npm', 'run',...
compile the JS, then run superclass implementation
def write_ds9(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'): """ Converts a `list` of `~regions.Region` to DS9 string and write to file. Parameters ---------- regions : `list` List of `regions.Region` objects filename : `str` Filename in which the string is to be ...
Converts a `list` of `~regions.Region` to DS9 string and write to file. Parameters ---------- regions : `list` List of `regions.Region` objects filename : `str` Filename in which the string is to be written. coordsys : `str`, optional #TODO Coordinate system that overrides t...
def putfile(self, filepath, buildroot, metahash): """Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object """ def gen_obj_path(filename): ...
Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object
def f_ratios(calON_obs,calOFF_obs,chan_per_coarse,**kwargs): ''' Calculate f_ON, and f_OFF as defined in van Straten et al. 2012 equations 2 and 3 Parameters ---------- calON_obs : str Path to filterbank file (any format) for observation ON the calibrator source calOFF_obs : str ...
Calculate f_ON, and f_OFF as defined in van Straten et al. 2012 equations 2 and 3 Parameters ---------- calON_obs : str Path to filterbank file (any format) for observation ON the calibrator source calOFF_obs : str Path to filterbank file (any format) for observation OFF the calibrator ...
def _shift_wavelengths(model1, model2): """One of the models is either ``RedshiftScaleFactor`` or ``Scale``. Possible combos:: RedshiftScaleFactor | Model Scale | Model Model | Scale """ if isinstance(model1, _models.RedshiftScaleFactor): val = _get_sampleset(model2) ...
One of the models is either ``RedshiftScaleFactor`` or ``Scale``. Possible combos:: RedshiftScaleFactor | Model Scale | Model Model | Scale
def _maybe_launch_index_impl_thread(self): """Attempts to launch a thread to compute index_impl(). This may not launch a new thread if one is already running to compute index_impl(); in that case, this function is a no-op. """ # Try to acquire the lock for computing index_impl(), without blocking. ...
Attempts to launch a thread to compute index_impl(). This may not launch a new thread if one is already running to compute index_impl(); in that case, this function is a no-op.
def regexer_for_targets(targets): """Pairs up target files with their correct regex""" for target in targets: path, file_ext = os.path.splitext(target) regexer = config.regexers[file_ext] yield target, regexer
Pairs up target files with their correct regex
def parse_command_line(): """Parse command line arguments.""" parser = argparse.ArgumentParser( prog='csp_pulsar_sender', description='Send fake pulsar data using ftp protocol.') parser.add_argument('config_file', type=argparse.FileType('r'), help='JSON configuration ...
Parse command line arguments.
def to_json_type(self): """ Return a dictionary for the document with values converted to JSON safe types. """ document_dict = self._json_safe(self._document) self._remove_keys(document_dict, self._private_fields) return document_dict
Return a dictionary for the document with values converted to JSON safe types.
def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.""" url = unwrap(to_bytes(url)) if self.tempcache and url in self.tempcache: return self.tempcach...
retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.
def set_queue_metadata(self, queue_name, metadata=None, timeout=None): ''' Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param dict metadata: ...
Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. :param str queue_name: The name of an existing queue. :param dict metadata: A dict containing name-value pairs to associate with the queue as metadat...
def IsWindowVisible(handle: int) -> bool: """ IsWindowVisible from Win32. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsWindowVisible(ctypes.c_void_p(handle)))
IsWindowVisible from Win32. handle: int, the handle of a native window. Return bool.
def timeout_message_report(): """ 周期/延时 消息报告 """ timeout_list = glb.ioloop._timeouts delay_task = [] for timeout in timeout_list: if not timeout.callback: continue if len(timeout.callback.args) == 2: task_type, message = timeout.callback.args d...
周期/延时 消息报告
def table_exists(self, project_id, dataset_id, table_id): """ Checks for the existence of a table in Google BigQuery. :param project_id: The Google cloud project in which to look for the table. The connection supplied to the hook must provide access to the specified proj...
Checks for the existence of a table in Google BigQuery. :param project_id: The Google cloud project in which to look for the table. The connection supplied to the hook must provide access to the specified project. :type project_id: str :param dataset_id: The name of the ...
def index_exists(index, hosts=None, profile=None): ''' Return a boolean indicating whether given index exists index Index name CLI example:: salt myminion elasticsearch.index_exists testindex ''' es = _get_instance(hosts, profile) try: return es.indices.exists(ind...
Return a boolean indicating whether given index exists index Index name CLI example:: salt myminion elasticsearch.index_exists testindex
def contains(self, name: str) -> List[str]: """Return a list of all keywords containing the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... ...
Return a list of all keywords containing the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.contains('keyw...
def filter(table, predicates): """ Select rows from table based on boolean expressions Parameters ---------- predicates : boolean array expressions, or list thereof Returns ------- filtered_expr : TableExpr """ resolved_predicates = _resolve_predicates(table, predicates) re...
Select rows from table based on boolean expressions Parameters ---------- predicates : boolean array expressions, or list thereof Returns ------- filtered_expr : TableExpr
def fit_plots(ax,xfit,xraw,yfit,yraw): ''' #==================================================================== plot the fitted results for data fit and refit #==================================================================== ''' global _yfits_ _yfits_ = yfit ax.plot(xfit, yfit) ...
#==================================================================== plot the fitted results for data fit and refit #====================================================================
def read_profile_from_environment_variables(): """ Read profiles from env :return: """ role_arn = os.environ.get('AWS_ROLE_ARN', None) external_id = os.environ.get('AWS_EXTERNAL_ID', None) return role_arn, external_id
Read profiles from env :return:
def export_survey_participant_list(self, instrument, event=None, format='json'): """ Export the Survey Participant List Notes ----- The passed instrument must be set up as a survey instrument. Parameters ---------- instrument: str Name of ins...
Export the Survey Participant List Notes ----- The passed instrument must be set up as a survey instrument. Parameters ---------- instrument: str Name of instrument as seen in second column of Data Dictionary. event: str Unique event name...
def clean_assembly(gtf_file, clean=None, dirty=None): """ clean the likely garbage transcripts from the GTF file including: 1. any novel single-exon transcripts 2. any features with an unknown strand """ base, ext = os.path.splitext(gtf_file) db = gtf.get_gtf_db(gtf_file, in_memory=True) ...
clean the likely garbage transcripts from the GTF file including: 1. any novel single-exon transcripts 2. any features with an unknown strand
def get_node_by_coord(self, coord, relative=False): """Get a node from a node coord. :param coord: the coordinates of the required node. :type coord: tuple or list :param relative: `True` if coord is relative to the node instance, `False` for absolute coordinates. :...
Get a node from a node coord. :param coord: the coordinates of the required node. :type coord: tuple or list :param relative: `True` if coord is relative to the node instance, `False` for absolute coordinates. :type relative: bool :returns: the node corresponding to...
def scramble_caching_sha2(password, nonce): # (bytes, bytes) -> bytes """Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce)) """ if not password: return b'' p1 = hashlib.sha256(password).digest() p2 = hashlib.sha...
Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
def transfer_bankcard(self, true_name, bank_card_no, bank_code, amount, desc=None, out_trade_no=None): """ 企业付款到银行卡接口 :param true_name: 开户人名称 :param bank_card_no: 银行卡号 :param bank_code: 银行编号 :param amount: 付款金额,单位分 :param desc: 付款说明 :param out_trade_no: 可...
企业付款到银行卡接口 :param true_name: 开户人名称 :param bank_card_no: 银行卡号 :param bank_code: 银行编号 :param amount: 付款金额,单位分 :param desc: 付款说明 :param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成 :return: 返回的结果信息
def calc_mean_time_deviation(timepoints, weights, mean_time=None): """Return the weighted deviation of the given timepoints from their mean time. With equal given weights, the is simply the standard deviation of the given time points: >>> from hydpy import calc_mean_time_deviation >>> calc_mea...
Return the weighted deviation of the given timepoints from their mean time. With equal given weights, the is simply the standard deviation of the given time points: >>> from hydpy import calc_mean_time_deviation >>> calc_mean_time_deviation(timepoints=[3., 7.], ... wei...