Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
361,500
def get_virtual_transactions(blockchain_name, blockchain_opts, first_block_height, last_block_height, tx_filter=None, **hints): if blockchain_name == : return get_bitcoin_virtual_transactions(blockchain_opts, first_block_height, last_block_height, tx_filter=tx_filter, **hints) else: raise ...
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...
361,501
def align_bam(in_bam, ref_file, names, align_dir, data): config = data["config"] out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"])) novoalign = config_utils.get_program("novoalign", config) samtools = config_utils.get_program("samtools", config) resources = config_utils.ge...
Perform realignment of input BAM file; uses unix pipes for avoid IO.
361,502
def writeTraining(self, file_obj): json.dump(self.training_pairs, file_obj, default=serializer._to_json, tuple_as_array=False, ensure_ascii=True)
Write to a json file that contains labeled examples Keyword arguments: file_obj -- file object to write training data to
361,503
def nonull_dict(self): return {k: v for k, v in six.iteritems(self.dict) if v and k != }
Like dict, but does not hold any null values. :return:
361,504
def _connect_database(config): settings = config.registry.settings mongo_uri = "mongodb://localhost:27017" mongodb_name = "test" if settings.get("mongo_url"): mongo_uri = settings["mongo_url"] if settings.get("mongodb_name"): mongodb_name = settings["mongodb_name"] retur...
Create simple connection with Mongodb config comes with settings from .ini file.
361,505
def options(self, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params): return self.request(, url=url, headers=headers, timeout=timeout, **params)
Calls the service at the specified URL using the "OPTIONS" method
361,506
def raise_errors_on_nested_writes(method_name, serializer, validated_data): assert not any( in field.source and (key in validated_data) and isinstance(validated_data[key], (list, dict)) for key, field in serializer.fields.items() ), ( ...
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...
361,507
def matrix_chain_mult(M): 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
361,508
def _load_greedy(self, module_name, dependencies, recursive): found = module_name in self.modules allmodules = list(self._pathfiles.keys()) i = 0 while not found and i < len(allmodules): current = allmodules[i] if not current in self._modulefiles: ...
Keeps loading modules in the filepaths dictionary until all have been loaded or the module is found.
361,509
def getData(self): url = self.server + self.name data = GitHubUser.__getDataFromURL(url) web = BeautifulSoup(data, "lxml") self.__getContributions(web) self.__getLocation(web) self.__getAvatar(web) self.__getNumberOfRepositories(web) self.__getNum...
Get data of the GitHub user.
361,510
def folderitems(self): items = super(ARTemplateAnalysesView, self).folderitems() self.categories.sort() return items
TODO: Refactor to non-classic mode
361,511
def _get_bit(self, n, hash_bytes): if hash_bytes[n // 8] >> int(8 - ((n % 8) + 1)) & 1 == 1: return True return False
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 ...
361,512
def server_info_cb(self, context, server_info_p, userdata): server_info = server_info_p.contents self.request_update(context)
Retrieves the default sink and calls request_update
361,513
def sample_u(self, q): r q = scipy.atleast_1d(q) if len(q) != len(self.sigma): raise ValueError("length of q must equal the number of parameters!") if q.ndim != 1: raise ValueError("q must be one-dimensional!") if (q < 0).any() or (q > 1).any(): ...
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, ...
361,514
def qteSetKeyFilterPolicy(self, receiveBefore: bool=False, useQtmacs: bool=None, receiveAfter: bool=False): self.filterKeyEvents = useQtmacs self.receiveBeforeQtmacsParser = receiveBefore self.receiveAfterQtmacsParser ...
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...
361,515
def _wrap_callback_parse_alarm_data(subscription, on_data, message): if (message.type == message.DATA and message.data.type == yamcs_pb2.ALARM_DATA): proto = getattr(message.data, ) alarm_event = AlarmEvent(proto) subscription._process(alarm_event) if on_dat...
Wraps an (optional) user callback to parse Alarm data from a WebSocket data message
361,516
def set_raw(self,text): node_raw = self.root.find() if node_raw is None: node_raw = etree.Element() self.root.insert(0,node_raw) node_raw.text = etree.CDATA(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
361,517
def get_labs(format): techshops_soup = data_from_techshop_ws(techshop_us_url) techshops = {} data = techshops_soup.findAll(, attrs={: }) for element in data: links = element.findAll() hrefs = {} for k, a in enumerate(links): if "contact" not in a[]: ...
Gets Techshop data from techshop.ws.
361,518
def update(self, file): params = { "message": file.logs, "author": file.author.dict(), "content": file.base64, "sha": file.blob, "branch": file.branch } uri = "{api}/repos/{origin}/contents/{path}".format( api=self....
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)
361,519
def guard_cancel(analysis_request): for partition in analysis_request.getDescendants(all_descendants=False): if not isTransitionAllowed(partition, "cancel"): return False cancellable_states = ["unassigned", "registered"] for analysis in analysis_request.objectVa...
Returns whether 'cancel' transition can be performed or not. Returns True only if all analyses are in "unassigned" status
361,520
async def _execute(self, fn, *args, **kwargs): return await self._conn._execute(fn, *args, **kwargs)
Execute the given function on the shared connection's thread.
361,521
def _execute_phase_once(self, phase_desc, is_last_repeat): if phase_desc.options.run_if and not phase_desc.options.run_if(): _LOG.debug(, phase_desc.name) return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP) override_result = None with self.test_state.running_phase_...
Executes the given phase, returning a PhaseExecutionOutcome.
361,522
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.
361,523
def _f_preactivations(self, X): preactivations_list = list() net = X preactivations_list.append(X) for W, b, i in zip(self.W_list, self.b_list, np.arange(len(self.W_list))): net = np.dot(net, W) net = net + b if i < len(self.W_list) - 1: ...
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, ...]
361,524
def 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
361,525
def retrieve_all(self): with sqlite3.connect(self.dbname) as carddb: for row in carddb.execute("SELECT code FROM CARDS"): yield self.load_card(row[0])
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.
361,526
def dispatch_subcommand(self, parser): re doing this is elegant, but dangerous. It doesn args = parser.parse_args(sys.argv[1:2]) if not hasattr(self, args.subcommand): print() parser.print_help() exit(1) self.configs = Confi...
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
361,527
def find_observatories(self, match=None): url = "%s/gwf.json" % _url_prefix response = self._requestresponse("GET", url) sitelist = sorted(set(decode(response.read()))) if match: regmatch = re.compile(match) sitelist = [site for site in sitelist if regmat...
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...
361,528
def _identify_prefix(self, msg, data): prefix_id = -1 for prefix in data: msg_dict = {} prefix_id += 1 match = None if in prefix: log.debug(, prefix[]) try: match = prefix[](msg) ...
Check the message again each OS prefix and if matched return the message dict
361,529
def _validate_attrs(dataset): def check_attr(name, value): if isinstance(name, str): if not name: raise ValueError( ) else: raise TypeError("Invalid name for attr: {} must be a string for ...
`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.
361,530
def get_attribute(self, name): def get_attribute_element(): return self.element.get_attribute(name) return self.execute_and_handle_webelement_exceptions(get_attribute_element, + str(name) + )
Retrieves specified attribute from WebElement @type name: str @param name: Attribute to retrieve @rtype: str @return: String representation of the attribute
361,531
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...
361,532
def _stop_transport(self): try: self._check_is_started() except (BaseSSHTunnelForwarderError, HandlerSSHTunnelForwarderError) as e: self.logger.warning(e) for _srv in self._server_list: tunnel = _srv.local_address if self.t...
Close the underlying transport when nothing more is needed
361,533
def compare(self, word1, word2): return ( self._plequal(word1, word2, self.plural_noun) or self._plequal(word1, word2, self.plural_verb) or self._plequal(word1, word2, self.plural_adj) )
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
361,534
def click_element_at_coordinates(self, coordinate_X, coordinate_Y): self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y)) driver = self._current_application() action = TouchAction(driver) action.press(x=coordinate_X, y=coordinate_Y).release().perform()
click element at a certain coordinate
361,535
def ask(self, question, default=False): choices = % ( if default else , if default else ) while True: response = raw_input( % (question, choices)).strip() if not response: return default elif response in : return True ...
Ask a y/n question to the user.
361,536
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow): c_base = self.uPinv(EndOfPrdvP) PrefShkCount = self.PrefShkVals.size PrefShk_temp = np.tile(np.reshape(self.PrefShkVals**(1.0/self.CRRA),(PrefShkCount,1)), (1,c_base.size)) self.cNrmNow ...
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...
361,537
def populateFromRow(self, referenceSetRecord): self._dataUrl = referenceSetRecord.dataurl self._description = referenceSetRecord.description self._assemblyId = referenceSetRecord.assemblyid self._isDerived = bool(referenceSetRecord.isderived) self._md5checksum = referenc...
Populates this reference set from the values in the specified DB row.
361,538
def append_var_uint32(self, value): if not 0 <= value <= wire_format.UINT32_MAX: raise errors.EncodeError( % value) self.append_var_uint64(value)
Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint.
361,539
def require_scalar(self, *args: Type) -> None: node = Node(self.yaml_node) if len(args) == 0: if not node.is_scalar(): raise RecognitionError(().format( self.yaml_node.start_mark, os.linesep)) else: for typ in args: ...
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:...
361,540
def _format_line(self, side, flag, linenum, text): try: linenum = % linenum id = % (self._prefix[side], linenum) except TypeError: id = text = text.replace("&", "&amp;"). \ replace(">", "&gt;"). \ repla...
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
361,541
def _generateRangeDescription(self, 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" % (ranges[i][0]) if i < numRanges - 1: desc += ",...
generate description from a text description of the ranges
361,542
def camel_to_(s): s1 = re.sub(, r, s) return re.sub(, r, s1).lower()
Convert CamelCase to camel_case
361,543
def go_in(self, vertex): 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.
361,544
def delete_service_settings_on_scope_delete(sender, instance, **kwargs): for service_settings in ServiceSettings.objects.filter(scope=instance): service_settings.unlink_descendants() service_settings.delete()
If VM that contains service settings were deleted - all settings resources could be safely deleted from NC.
361,545
def py3round(number): 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.
361,546
def mse(y_true, y_pred): y_true, y_pred = _mask_nan(y_true, y_pred) return ((y_true - y_pred) ** 2).mean(axis=None)
Mean squared error
361,547
def _decrypt(message, encryption_data, key_encryption_key=None, resolver=None): _validate_not_none(, message) content_encryption_key = _validate_and_unwrap_cek(encryption_data, key_encryption_key, resolver) if not (_EncryptionAlgorithm.AES_CBC_256 == encryption_data.encryption_agent.encryption_algorit...
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: ...
361,548
def get_pay_giftcard(self, rule_id): return self._post( , data={ : rule_id, }, result_processor=lambda x: x[], )
查询支付后投放卡券的规则 详情请参见 https://mp.weixin.qq.com/wiki?id=mp1466494654_K9rNz :param rule_id: 支付即会员的规则 ID :return: 支付后投放卡券的规则 :rtype: dict
361,549
def transform_binary_dist(self, archive_path): logger.debug("Transforming binary distribution: %s.", archive_path) archive = tarfile.open(archive_path, ) for member in archive.getmembers(): member.mode = 0o...
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...
361,550
def load_fits(self): log.info("Loading FITS file for %d." % (self.ID)) with pyfits.open(self.fitsfile) as f: self.loaded = True self.is_parent = False try: self.X1N = f[2].data[] except KeyError: self...
Load the FITS file from disk and populate the class instance with its data.
361,551
def get_domain_smarthost(self, domainid, serverid): return self.api_call( ENDPOINTS[][], dict(domainid=domainid, serverid=serverid))
Get a domain smarthost
361,552
def make_force_ES(q_vars, mass): U = U_ij(q_vars, mass, 0, 1) vn_q = np.array([q.var_name for q in q_vars]) vn_fl = np.array(sorted(U.var_names)) q2fl = np.array([np.argmax((vn_q == v)) for v in vn_fl]) fl2q = np.array([np.argmax((vn_fl == v)) for v in vn_q]) force...
Fluxion with the potential energy of the earth-sun sytem
361,553
def regex_findall_variables(content): try: vars_list = [] for var_tuple in variable_regex_compile.findall(content): vars_list.append( var_tuple[0] or var_tuple[1] ) return vars_list except TypeError: return []
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...
361,554
def coordinates(self): if not getattr(self, , False): query_params = { : , : , : self.title, } request = _wiki_request(query_params) if in request: coordinates = request[][][self.pageid][] self._coordinates = (Decimal(coordinates[0][]), Decimal...
Tuple of Decimals in the form of (lat, lon) or None
361,555
def cli(ctx, verbose, config): assert isinstance(ctx, Context) 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.getLogger() ctx.log.setLevel(log_level) console_forma...
IPS Vagrant Management Utility
361,556
def read(self, len=1024): while True: try: return self._sslobj.read(len) except SSLError: ex = sys.exc_info()[1] if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: return b elif ex.arg...
Read up to LEN bytes and return them. Return zero-length string on EOF.
361,557
def FromMilliseconds(self, millis): self.seconds = millis // _MILLIS_PER_SECOND self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND
Converts milliseconds since epoch to Timestamp.
361,558
def forward(self, inputs: torch.Tensor, tags: torch.Tensor, mask: torch.ByteTensor = None) -> torch.Tensor: if mask is None: mask = torch.ones(*tags.size(), dtype=torch.long) log_denominator = self._input_likelihood(inputs, m...
Computes the log likelihood.
361,559
def max_tot_value(self, value): 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
361,560
def _generate_cache(self): 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 self._yield_distributions(): if isinstance(dist, InstalledDistribution): self...
Scan the path for distributions and populate the cache with those that are found.
361,561
def get_obj(app_label, model_name, object_id): try: model = apps.get_model("{}.{}".format(app_label, model_name)) assert is_valid_django_model(model), ("Model {}.{} do not exist.").format( app_label, model_name ) obj = get_Object_or_None(model, pk=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
361,562
def register(self, hook): assert callable(hook), \ "Hook must be a callable" assert issubclass(hook, HookBase), \ "The hook does not inherit from HookBase" self._registry.append(hook)
Register a hook. @hook: a HookBase subclass reference.
361,563
def limit_dragpos(self): 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 = self.img.GetWidth()-1 if se...
limit dragpos to sane values
361,564
def connection_service_name(service, *args): if isinstance(service, str): return service return normalize_string(type(service).__name__)
the name of a service that manages the connection between services
361,565
def download_segmentation_image(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint=0, zplane=0, align = False): response = self._download_segmentation_image( mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint, zpl...
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...
361,566
def set_all_ylims(self, ylim, dy, yscale, fontsize=None): self._set_all_lims(, ylim, dy, yscale, fontsize) return
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...
361,567
def theta_limit(theta): while theta <= -1 * np.pi / 2: theta += np.pi while theta > np.pi / 2: theta -= np.pi return 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.
361,568
def _parse_attribute_details_file(self, prop=ATTRIBUTES): self._attr_details_file_url = parse_property( self._xml_tree, None, self._data_map, ) if not self._attr_details_file_url: return None try: tree_t...
Concatenates a list of Attribute Details data structures parsed from a remote file
361,569
def sum_rightmost_ndims_preserving_shape(x, ndims): x = tf.convert_to_tensor(value=x) if x.shape.ndims is not None: axes = tf.range(x.shape.ndims - ndims, x.shape.ndims) else: axes = tf.range(tf.rank(x) - ndims, tf.rank(x)) return tf.reduce_sum(input_tensor=x, axis=axes)
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...
361,570
def _set_ve(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ve.ve, is_container=, presence=False, yang_name="ve", rest_name="Ve", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u: u, u: No...
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...
361,571
def sync(self): self.elk.send(cs_encode()) self.get_descriptions(TextDescriptions.OUTPUT.value)
Retrieve areas from ElkM1
361,572
def write_single_register(self, reg_addr, reg_value): if not (0 <= int(reg_addr) <= 65535): self.__debug_msg() return None if not (0 <= int(reg_value) <= 65535): self.__debug_msg() return None tx_buffer = self._mbus_frame...
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
361,573
def ridgeplot(self, mult, linewidth, alpha, ax): if alpha is None: alpha = 1.0 zorder = 0 for plotter in self.plotters.values(): for x, y_min, y_max, color in plotter.ridgeplot(mult): if alpha == 0: border = color ...
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 ...
361,574
def paintEvent(self, event): super(IconLineEdit, self).paintEvent(event) painter = QPainter(self) rect = self.geometry() space = int((rect.height())/6) h = rect.height() - space w = rect.width() - h if self._icon_visible: if self._status and...
Qt Override. Include a validation icon to the left of the line edit.
361,575
def run(self): if subprocess.call([, ]) != 0: raise RuntimeError() self.check_call([, ], cwd=HTML_RENDERER_DIR) self.check_call([, , ], cwd=HTML_RENDERER_DIR) self.copy_file(HTML_RENDERER_DIR+, ) setuptools.command.build_py.build_py.run(self)
compile the JS, then run superclass implementation
361,576
def write_ds9(regions, filename, coordsys=, fmt=, radunit=): output = ds9_objects_to_string(regions, coordsys, fmt, radunit) with open(filename, ) as fh: fh.write(output)
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...
361,577
def putfile(self, filepath, buildroot, metahash): def gen_obj_path(filename): filehash = util.hash_file(filepath).hexdigest() return filehash, os.path.join(self.obj_cachedir, filehash[0:2], filehash[2:4], filehash) filepath_rela...
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
361,578
def f_ratios(calON_obs,calOFF_obs,chan_per_coarse,**kwargs): L_ON,H_ON = integrate_calib(calON_obs,chan_per_coarse,**kwargs) L_OFF,H_OFF = integrate_calib(calOFF_obs,chan_per_coarse,**kwargs) f_ON = H_ON/L_ON-1 f_OFF = H_OFF/L_OFF-1 return f_ON, f_OFF
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 ...
361,579
def _shift_wavelengths(model1, model2): if isinstance(model1, _models.RedshiftScaleFactor): val = _get_sampleset(model2) if val is None: w = val else: w = model1.inverse(val) elif isinstance(model1, _models.Scale): w = _get_sampleset(model2) else:...
One of the models is either ``RedshiftScaleFactor`` or ``Scale``. Possible combos:: RedshiftScaleFactor | Model Scale | Model Model | Scale
361,580
def _maybe_launch_index_impl_thread(self): if self._index_impl_lock.acquire(False): self._index_impl_thread = threading.Thread( target=self._async_index_impl, name=) self._index_impl_thread.start()
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.
361,581
def regexer_for_targets(targets): 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
361,582
def parse_command_line(): parser = argparse.ArgumentParser( prog=, description=) parser.add_argument(, type=argparse.FileType(), help=) parser.add_argument(, , help=, action=) parser.add_argument(, , help=, acti...
Parse command line arguments.
361,583
def to_json_type(self): 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.
361,584
def retrieve(self, url, filename=None, reporthook=None, data=None): url = unwrap(to_bytes(url)) if self.tempcache and url in self.tempcache: return self.tempcache[url] type, url1 = splittype(url) if filename is None and (not type or type == ): try: ...
retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.
361,585
def set_queue_metadata(self, queue_name, metadata=None, timeout=None): _validate_not_none(, queue_name) request = HTTPRequest() request.method = request.host = self._get_host() request.path = _get_path(queue_name) request.query = [ (, ), ...
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...
361,586
def IsWindowVisible(handle: int) -> 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.
361,587
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 delay_task.append(message) ...
周期/延时 消息报告
361,588
def table_exists(self, project_id, dataset_id, table_id): service = self.get_service() try: service.tables().get( projectId=project_id, datasetId=dataset_id, tableId=table_id).execute(num_retries=self.num_retries) return True excep...
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 ...
361,589
def index_exists(index, hosts=None, profile=None): es = _get_instance(hosts, profile) try: return es.indices.exists(index=index) except elasticsearch.exceptions.NotFoundError: return False except elasticsearch.TransportError as e: raise CommandExecutionError("Cannot retriev...
Return a boolean indicating whether given index exists index Index name CLI example:: salt myminion elasticsearch.index_exists testindex
361,590
def contains(self, name: str) -> List[str]: return sorted(keyword for keyword in self if name in keyword)
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...
361,591
def filter(table, predicates): resolved_predicates = _resolve_predicates(table, predicates) return _L.apply_filter(table, resolved_predicates)
Select rows from table based on boolean expressions Parameters ---------- predicates : boolean array expressions, or list thereof Returns ------- filtered_expr : TableExpr
361,592
def fit_plots(ax,xfit,xraw,yfit,yraw): global _yfits_ _yfits_ = yfit ax.plot(xfit, yfit) ax.plot(xfit, np.sum(yfit,axis=1)) ax.scatter(xraw, yraw) ax.set_xlabel() ax.set_ylabel()
#==================================================================== plot the fitted results for data fit and refit #====================================================================
361,593
def read_profile_from_environment_variables(): role_arn = os.environ.get(, None) external_id = os.environ.get(, None) return role_arn, external_id
Read profiles from env :return:
361,594
def export_survey_participant_list(self, instrument, event=None, format=): pl = self.__basepl(content=, format=format) pl[] = instrument if event: pl[] = event return self._call_api(pl, )
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...
361,595
def clean_assembly(gtf_file, clean=None, dirty=None): base, ext = os.path.splitext(gtf_file) db = gtf.get_gtf_db(gtf_file, in_memory=True) clean = clean if clean else base + ".clean" + ext dirty = dirty if dirty else base + ".dirty" + ext if file_exists(clean): return clean, dirty l...
clean the likely garbage transcripts from the GTF file including: 1. any novel single-exon transcripts 2. any features with an unknown strand
361,596
def get_node_by_coord(self, coord, relative=False): if not isinstance(coord, (list, tuple)) or False in list(map(lambda i: type(i)==int, coord)): logger.warning("%s.get_node_by_coord: node«%s», arg «coord»=«%s», «coord» must be list or tuple of integers." % (self.__class__.__name__, self.na...
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...
361,597
def scramble_caching_sha2(password, nonce): if not password: return b p1 = hashlib.sha256(password).digest() p2 = hashlib.sha256(p1).digest() p3 = hashlib.sha256(p2 + nonce).digest() res = bytearray(p1) if PY2: p3 = bytearray(p3) for i in range(len(p3)): r...
Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce))
361,598
def transfer_bankcard(self, true_name, bank_card_no, bank_code, amount, desc=None, out_trade_no=None): if not out_trade_no: now = datetime.now() out_trade_no = .format( self.mch_id, now.strftime(), random.randint(1000, 10000) ...
企业付款到银行卡接口 :param true_name: 开户人名称 :param bank_card_no: 银行卡号 :param bank_code: 银行编号 :param amount: 付款金额,单位分 :param desc: 付款说明 :param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成 :return: 返回的结果信息
361,599
def calc_mean_time_deviation(timepoints, weights, mean_time=None): timepoints = numpy.array(timepoints) weights = numpy.array(weights) validtools.test_equal_shape(timepoints=timepoints, weights=weights) validtools.test_non_negative(weights=weights) if mean_time is None: mean_time = calc...
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...