Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,100
def set_coupl_old(self): if self.model == or self.model == : return self.Coupl = np.zeros((self.dim,self.dim)) for i in range(self.Adj.shape[0]): for j,a in enumerate(self.Adj[i]): if a != 0: ...
Using the adjacency matrix, sample a coupling matrix.
349,101
def fullpath(relpath): if (type(relpath) is object or type(relpath) is file): relpath = relpath.name return os.path.abspath(os.path.expanduser(relpath))
Relative path to absolute
349,102
def expand_entity(self, entity): if self.name in entity: return entity for key, value in entity.items(): if isinstance(value, dict): if self.name in value: return value raise KeyError("The field %s (%s) not found in %s" % (self...
Search and return entity or sub entity that contain value of this field. :param entity: :return: entity :raise KeyError
349,103
def _generate_custom_type(self, resource_type): if not resource_type.startswith("Custom::"): raise TypeError("Custom types must start with Custom::") custom_type = type( str(resource_type.replace("::", "")), (self.inspect_resources[],), {: resourc...
Dynamically allocates a new CustomResource class definition using the specified Custom::SomeCustomName resource type. This special resource type is equivalent to the AWS::CloudFormation::CustomResource.
349,104
def get_median_area(self, mag, rake): length = 10.0 ** (-2.57 + 0.62 * mag) seis_wid = 20.0 if length < seis_wid: return length ** 2. else: return length * seis_wid
The values are a function of magnitude.
349,105
def index_bamfile(job, bamfile, sample_type, univ_options, samtools_options, sample_info=None, export=True): work_dir = os.getcwd() in_bamfile = sample_type if sample_info is not None: assert isinstance(sample_info, str) in_bamfile = .join([in_bamfile, sample_info]) ...
Index `bamfile` using samtools :param toil.fileStore.FileID bamfile: fsID for the bam file :param str sample_type: Description of the sample to inject into the filename :param dict univ_options: Dict of universal options used by almost all tools :param dict samtools_options: Options specific to samtool...
349,106
def update_items(item_seq, batch_len=500, dry_run=True, start_batch=0, end_batch=None, ignore_errors=False, verbosity=1): stats = collections.Counter() try: try: src_qs = item_seq.objects.all() except AttributeError: src_qs = item_seq.all() N = src_qs.count(...
Given a sequence (queryset, generator, tuple, list) of dicts run the _update method on them and do bulk_update
349,107
def is_uuid4(instr): v = instr.strip().replace(,).lower() if len(v) != 32: return False if not re.match(,v): return False if v[12] != : return False if not re.match(,v[16]): return False return True
A validator to confirm a string is indeed a UUID4 :param instr: input string that may be uuid4 :type instr: String :return: true if it is in UUID4 format :rtype: bool
349,108
def _relative_position_to_absolute_position_masked(x): batch, heads, length, _ = common_layers.shape_list(x) x = tf.pad(x, [[0, 0], [0, 0], [0, 0], [1, 0]]) x = tf.reshape(x, [batch, heads, 1 + length, length]) x = tf.slice(x, [0, 0, 1, 0], [-1, -1, -1, -1]) return x
Helper to dot_product_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The dimensions of the input represent: [batch, heads, query_position, memory_position - query_position + length - 1] The dimensions of the output represent: [batch, heads, query_position, memory_position] ...
349,109
def apply_handler(self, method_data, *args, **kwargs): if isinstance(method_data, tuple): len_method = len(method_data) method = method_data[0] if 1 < len_method: args = method_data[1] if 2 < len_method: kwargs = method_dat...
Call the dispatched function, optionally with other data stored/created during .register and .prepare. Assume the arguments passed in by the dispathcer are the only ones required.
349,110
def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): try: course = course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not user_manager.course_is_open_to_user(course, lti...
Helper for the GET methods of the two following classes
349,111
def cli(ctx): ctx.obj = Wio() cur_dir = os.path.abspath(os.path.expanduser("~/.wio")) if not os.path.exists(cur_dir): text = {"email":"", "token":""} os.mkdir(cur_dir) open("%s/config.json"%cur_dir,"w").write(json.dumps(text)) db_file_path = % cur_dir config = json.load...
\b Welcome to the Wio Command line utility! https://github.com/Seeed-Studio/wio-cli For more information Run: wio <command_name> --help
349,112
def read_nanopubs(fn: str) -> Iterable[Mapping[str, Any]]: jsonl_flag, json_flag, yaml_flag = False, False, False if fn == "-" or "jsonl" in fn: jsonl_flag = True elif "json" in fn: json_flag = True elif re.search("ya?ml", fn): yaml_flag = True else: log.error("...
Read file and generate nanopubs If filename has *.gz, will read as a gzip file If filename has *.jsonl*, will parsed as a JSONLines file IF filename has *.json*, will be parsed as a JSON file If filename has *.yaml* or *.yml*, will be parsed as a YAML file Args: filename (str): filename t...
349,113
def loads(s, key=None, salt=, serializer=JSONSerializer, max_age=None): base64d = force_bytes(TimestampSigner(key, salt=salt).unsign(s, max_age=max_age)) decompress = False if base64d[:1] == b: base64d = base64d[1:] decompress = True data = b64_decode(base64d) ...
Reverse of dumps(), raise BadSignature if signature fails. The serializer is expected to accept a bytestring.
349,114
def load_symbols(self): if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_process().get_handle(dwAccess) hFile ...
Loads the debugging symbols for a module. Automatically called by L{get_symbols}.
349,115
def generate_jwt(claims, priv_key=None, algorithm=, lifetime=None, expires=None, not_before=None, jti_size=16, other_headers=None): header = { : , : algorithm if priv_key else } if other_headers is not None: redefined_keys = s...
Generate a JSON Web Token. :param claims: The claims you want included in the signature. :type claims: dict :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an empty cryptographic signature and :obj:`algorithm` will be forced to...
349,116
def commit_offsets_async(self, offsets, callback=None): self._invoke_completed_offset_commit_callbacks() if not self.coordinator_unknown(): future = self._do_commit_offsets_async(offsets, callback) else: ...
Commit specific offsets asynchronously. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit callback (callable, optional): called as callback(offsets, response) response will be either an Exception or a OffsetCommitResponse struc...
349,117
def FromImport(package_name, name_leafs): for leaf in name_leafs: leaf.remove() children = [Leaf(token.NAME, u"from"), Leaf(token.NAME, package_name, prefix=u" "), Leaf(token.NAME, u"import", prefix=u" "), Node(syms.impo...
Return an import statement in the form: from package import name_leafs
349,118
def getent(refresh=False): * if in __context__ and not refresh: return __context__[] ret = [] for user in __salt__[](): stuff = {} user_info = __salt__[](user) stuff[] = stuff[] = user_info[] stuff[] = user_info[] stuff[] = user_info[] ...
Return the list of all info for all users Args: refresh (bool, optional): Refresh the cached user information. Useful when used from within a state function. Default is False. Returns: dict: A dictionary containing information about all users on the system CLI Example: .....
349,119
def from_stream(cls, stream): stream_rdr = StreamReader(stream, LITTLE_ENDIAN) px_width = stream_rdr.read_long(0x12) px_height = stream_rdr.read_long(0x16) horz_px_per_meter = stream_rdr.read_long(0x26) vert_px_per_meter = stream_rdr.read_long(0x2A) horz_dpi =...
Return |Bmp| instance having header properties parsed from the BMP image in *stream*.
349,120
def CMOVP(cpu, dest, src): dest.write(Operators.ITEBV(dest.size, cpu.PF, src.read(), dest.read()))
Conditional move - Parity/parity even. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. ...
349,121
def populate(self, priority, address, rtr, data): assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 4) self.set_attributes(priority, address, rtr) self._day = data[0] self._mon = data[1] ...
:return: None
349,122
def cqt_frequencies(n_bins, fmin, bins_per_octave=12, tuning=0.0): correction = 2.0**(float(tuning) / bins_per_octave) frequencies = 2.0**(np.arange(0, n_bins, dtype=float) / bins_per_octave) return correction * fmin * frequencies
Compute the center frequencies of Constant-Q bins. Examples -------- >>> # Get the CQT frequencies for 24 notes, starting at C2 >>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2')) array([ 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, 92.499, 97.999, 103.826, ...
349,123
def remove_duplicates(seq): last_boundary = False for char in seq: if char == : if not last_boundary: last_boundary = True yield char else: last_boundary = False yield char
Removes duplicate boundary token characters from the given character iterable. Arguments: - `seq`:
349,124
def executescript(self, *args, **kwargs): with self: self._cursor.executescript(*args, **kwargs)
Analogous to :any:`sqlite3.Cursor.executescript` :returns: self
349,125
def load(self, optional_cfg_files=None): optional_cfg_files = optional_cfg_files or [] if self._loaded: raise RuntimeError("INTERNAL ERROR: Attempt to load configuration twice!") try: namespace = {} self._set_defaults(namespace...
Actually load the configuation from either the default location or the given directory.
349,126
def get_params(self): if hasattr(self, ): return list(self.params) try: if tf.executing_eagerly(): raise NotImplementedError("For Eager execution - get_params " "must be overridden.") except AttributeError: pass scope_vars = t...
Provides access to the model's parameters. :return: A list of all Variables defining the model parameters.
349,127
def writeArray(fp, a, delim = " ", nl = 1): for i in a: fp.write("%f%s" % (i, delim)) if nl: fp.write("\n")
Writes a sequence a of floats to file pointed to by file pointer.
349,128
def get_stream_handle(stream=sys.stdout): handle = stream if os.name == "nt": from ._winconsole import get_stream_handle as get_win_stream_handle return get_win_stream_handle(stream) return handle
Get the OS appropriate handle for the corresponding output stream. :param str stream: The the stream to get the handle for :return: A handle to the appropriate stream, either a ctypes buffer or **sys.stdout** or **sys.stderr**.
349,129
def fit(self, x, fudge=1e-18): assert x.ndim == 2 ns, nc = x.shape x_cov = np.cov(x, rowvar=0) assert x_cov.shape == (nc, nc) d, v = np.linalg.eigh(x_cov) d = np.diag(1. / np.sqrt(d + fudge)) w = np.dot(np.dot(v, d), v.T) self._m...
Compute the whitening matrix. Parameters ---------- x : array An `(n_samples, n_channels)` array.
349,130
def load_keras(json_path=None, hdf5_path=None, by_name=False): import os try: import tensorflow except ImportError: os.environ[] = "theano" try: from theano import ifelse except ImportError: ...
Load a pre-trained Keras model. :param json_path: The json path containing the keras model definition. :param hdf5_path: The HDF5 path containing the pre-trained keras model weights with or without the model architecture. :return: A bigdl model.
349,131
def metadata(self, key=None, database=None, table=None, fallback=True): assert not (database is None and table is not None), \ "Cannot call metadata() with table= specified but not database=" databases = self._metadata.get("databases") or {} search_list = [] if datab...
Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found.
349,132
def isin(self, column, compare_list): return [x in compare_list for x in self._data[self._columns.index(column)]]
Returns a boolean list where each elements is whether that element in the column is in the compare_list. :param column: single column name, does not work for multiple columns :param compare_list: list of items to compare to :return: list of booleans
349,133
def _get_configured_repos(root=None): repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS repos_cfg = configparser.ConfigParser() if os.path.exists(repos): repos_cfg.read([repos + + fname for fname in os.listdir(repos) if fname.endswith(".repo")]) else: ...
Get all the info about repositories from the configurations.
349,134
def resize_widget(self, widget, row_span, col_span): row = None col = None for (r, c, rspan, cspan, w) in self._grid_widgets.values(): if w == widget: row = r col = c break if row is None or col is None: ...
Resize a widget in the grid to new dimensions. Parameters ---------- widget : Widget The widget to resize row_span : int The number of rows to be occupied by this widget. col_span : int The number of columns to be occupied by this widget.
349,135
def setup( hosts, default_keyspace, consistency=None, lazy_connect=False, retry_connect=False, **kwargs): from cassandra.cqlengine import models models.DEFAULT_KEYSPACE = default_keyspace register_connection(, hosts=hosts, consistency=consistency, lazy_...
Setup a the driver connection used by the mapper :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`) :param str default_keyspace: The default keyspace to use :param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Ses...
349,136
def plot_vs_mass(dataset, vars, filename, bins=60): n = len(vars) fig, axes = plt.subplots(nrows=n, ncols=1, sharex=, sharey=False) plt.subplots_adjust(wspace=0, hspace=0) m = for i, y in enumerate(vars)...
Plot 2D marginalised posteriors of the 'vars' vs the dark matter mass. We plot the one sigma, and two sigma filled contours. More contours can be plotted which produces something more akin to a heatmap. If one require more complicated plotting, it is recommended to write a custom plotting function by e...
349,137
def assert_element_visible(self, selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT): if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) self.assert_element(selector, by=by, timeout=tim...
Same as self.assert_element() As above, will raise an exception if nothing can be found.
349,138
def set_target(self, setpoint): fixed_set = int(setpoint * (2 ** 16)) buf = [cast_to_byte(fixed_set >> 8 * i) for i in range(5)] self.set_register(Addr.Speed, buf)
Higher level abstraction for setting the speed register. This register is responsible for telling the grizzly at what speed or position to drive at. The different control modes and type it expects is documented in the table below: Mode Type Range ...
349,139
def do(ruby, command, runas=None, cwd=None, env=None): s home directory. CLI Example: .. code-block:: bash salt rvm.do 2.0.0 <command> ' try: command = salt.utils.args.shlex_split(command) except AttributeError: command = salt.utils.args.shlex_split(six.text...
Execute a command in an RVM controlled environment. ruby Which ruby to use command The rvm command to execute runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. cwd The directory from which to...
349,140
def summary_str(self) -> str: return .format(self) + .join( .format(label, value) for label, value in self._describe_list() )
Return a string that summarizes the graph.
349,141
def _get_rule_changes(rules, _rules): to_delete = [] to_create = [] for rule in rules: try: ip_protocol = six.text_type(rule.get()) except KeyError: raise SaltInvocationError( ...
given a list of desired rules (rules) and existing rules (_rules) return a list of rules to delete (to_delete) and to create (to_create)
349,142
def _check(self): if self._returncode: rarfile.check_returncode(self, ) if self._remain != 0: raise rarfile.BadRarFile("Failed the read enough data")
Do not check final CRC.
349,143
def get_serial_number(device): a0000 = 604661760 if device.SerialNumber >= a0000: return ics.base36enc(device.SerialNumber) return str(device.SerialNumber)
Decode (if needed) and return the ICS device serial string :param device: ics device :return: ics device serial string :rtype: str
349,144
def historical(self, date, base=): try: resp = self.client.get(self.ENDPOINT_HISTORICAL % date.strftime("%Y-%m-%d"), params={: base}) resp.raise_for_status() except requests.exceptions.RequestException...
Fetches historical exchange rate data from service :Example Data: { disclaimer: "<Disclaimer data>", license: "<License data>", timestamp: 1358150409, base: "USD", rates: { AED: 3.666311, ...
349,145
def _init_data_map(self): if self._data_map is not None: return if self._xml_tree is None: fgdc_root = FGDC_ROOT else: fgdc_root = get_element_name(self._xml_tree) if fgdc_root != FGDC_ROOT: raise InvalidContent(, ro...
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions
349,146
def get_remote_port_id_local(self, tlv_data): ret, parsed_val = self._check_common_tlv_format( tlv_data, "Local:", "Port ID TLV") if not ret: return None local = parsed_val[1].split() return local[0].strip()
Returns Remote Port ID Local from the TLV.
349,147
def show(self, annotations=True): if self.is_closed: self.plot_discrete(show=True, annotations=annotations) else: self.plot_entities(show=True, annotations=annotations)
Plot the current Path2D object using matplotlib.
349,148
def get_vpc_config(self, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT): if vpc_config_override is vpc_utils.VPC_CONFIG_DEFAULT: return vpc_utils.to_dict(self.subnets, self.security_group_ids) else: return vpc_utils.sanitize(vpc_config_override)
Returns VpcConfig dict either from this Estimator's subnets and security groups, or else validate and return an optional override value.
349,149
def nodeDumpOutput(self, buf, cur, level, format, encoding): if buf is None: buf__o = None else: buf__o = buf._o if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.xmlNodeDumpOutput(buf__o, self._o, cur__o, level, format, encoding)
Dump an XML node, recursive behaviour, children are printed too. Note that @format = 1 provide node indenting only if xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was called
349,150
def _format_phone_number(self, value, attr): strict_validation = self.get_field_value( , default=False ) strict_region = self.get_field_value( , default=strict_validation ) region = self.get_field_value(, ) phone_nu...
Format and validate a phone number.
349,151
def bed2interval(align_file, bed, out_file=None): import pysam base, ext = os.path.splitext(align_file) if out_file is None: out_file = base + ".interval" with pysam.Samfile(align_file, "r" if ext.endswith(".sam") else "rb") as in_bam: header = in_bam.text def reorder_line(lin...
Converts a bed file to an interval file for use with some of the Picard tools by grabbing the header from the alignment file, reording the bed file columns and gluing them together. align_file can be in BAM or SAM format. bed needs to be in bed12 format: http://genome.ucsc.edu/FAQ/FAQformat.html#fo...
349,152
def use_region(self, offset=0, size=0, flags=0): need_region = True man = self._manager fsize = self._rlist.file_size() size = min(size or fsize, man.window_size() or fsize) if self._region is not None: if self._region.includes_ofs(offset): ...
Assure we point to a window which allows access to the given offset into the file :param offset: absolute offset in bytes into the file :param size: amount of bytes to map. If 0, all available bytes will be mapped :param flags: additional flags to be given to os.open in case a file handle is in...
349,153
def set_public_domain(self, public_domain): if self.get_public_domain_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_boolean(public_domain): raise errors.InvalidArgument() self._my_map[] = public_domain
Sets the public domain flag. arg: public_domain (boolean): the public domain status raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
349,154
def _check_field_names(self, field_names): if field_names: for field_name in field_names: try: self.column[field_name] except KeyError: raise InvalidIndexError( % field_name)
Raises InvalidIndexError if any of a field_name in field_names is not indexed.
349,155
def transform_subject(self, X): if hasattr(self, ) is False: raise NotFittedError("The model fit has not been run yet.") if X.shape[1] != self.s_.shape[1]: raise ValueError("The number of timepoints(TRs) does not match the" ...
Transform a new subject using the existing model. The subject is assumed to have recieved equivalent stimulation Parameters ---------- X : 2D array, shape=[voxels, timepoints] The fMRI data of the new subject. Returns ------- w : 2D array, shape=[v...
349,156
def perform(self, store, count): self.count = count try: self.upgradeStore(store) print except errors.ItemUpgradeError as e: print e.originalFailure.printTraceback(file=sys.stdout) print self.errorMessageFormat % ( ...
Upgrade C{store} performing C{count} upgrades per transaction. Also, catch any exceptions and print out something useful.
349,157
def revive(self, timeout=None): if timeout is not None: self.timeout = timeout self.revive_event.set()
Revive the timeout. :param timeout: If not `None`, specifies a new timeout value to use.
349,158
def infer_parameter_objects(pyfunction): object_info = pyfunction.pycore.object_info result = object_info.get_parameter_objects(pyfunction) if result is None: result = _parameter_objects(pyfunction) _handle_first_parameter(pyfunction, result) return result
Infer the `PyObject`\s of parameters of this `PyFunction`
349,159
def parse_course_key(course_identifier): try: course_run_key = CourseKey.from_string(course_identifier) except InvalidKeyError: return course_identifier return quote_plus(.join([course_run_key.org, course_run_key.course]))
Return the serialized course key given either a course run ID or course key.
349,160
def send(self, request_body): if not request_body: self._httprequest.send() else: self._httprequest.send(request_body)
Sends request body.
349,161
def _seconds_have_elapsed(token, num_seconds): now = timeit.default_timer() then = _log_timer_per_token.get(token, None) if then is None or (now - then) >= num_seconds: _log_timer_per_token[token] = now return True else: return False
Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the first call for a given 'token'. Args: token: T...
349,162
def run_evolution(path,name,E0,laser_frequencies, N_iter,dt,N_states, spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None, rho0=None,print_steps=False, integrate=False, save_systems=False,save_eigenvalues=False,rk4=False,use_netcdf=True): def py2f_bool(bool_var): if bool_var...
This function runs the Runge-Kutta method compiled in path+name...
349,163
def post(self): self.reqparse.add_argument(, type=str, required=True) self.reqparse.add_argument(, type=str, required=True) self.reqparse.add_argument(, type=dict, required=True, action=) self.reqparse.add_argument(, type=int, required=True, choices=(0, 1)) self.reqparse...
Create a new account
349,164
def retryable_writes_supported(self): return ( self._ls_timeout_minutes is not None and self._server_type in (SERVER_TYPE.Mongos, SERVER_TYPE.RSPrimary))
Checks if this server supports retryable writes.
349,165
def main(): version = get_version() circleci_build = six.moves.input("CircleCI Build ID: ") appveyor_build = six.moves.input("AppVeyor Build ID: ") coveralls_build = six.moves.input("Coveralls Build ID: ") travis_build = six.moves.input("Travis Build ID: ") populate_readme( version,...
Populate the templates with release-specific fields. Requires user input for the CircleCI, AppVeyor, Coveralls.io and Travis build IDs.
349,166
def display_channel(soup): display_channel = [] tags = raw_parser.display_channel(soup) for tag in tags: display_channel.append(node_text(tag)) return display_channel
Find the subject areas of type display-channel
349,167
def _add_replace_pair(self, name, value, quote): key = + name + key = key.lower() class_name = value.__class__.__name__ if class_name in [, ]: value = str(value) elif class_name in []: value = if value else elif class_name in []: ...
Adds a replace part to the map of replace pairs. :param name: The name of the replace pair. :param value: The value of value of the replace pair.
349,168
def _setup_phantomjs(self, capabilities): phantomjs_driver = self.config.get(, ) self.logger.debug("Phantom driver path given in properties: %s", phantomjs_driver) return webdriver.PhantomJS(executable_path=phantomjs_driver, desired_capabilities=capabilities)
Setup phantomjs webdriver :param capabilities: capabilities object :returns: a new local phantomjs driver
349,169
def head(self): if self.type == "NP" and any(w.type.startswith("NNP") for w in self): w = find(lambda w: w.type.startswith("NNP"), reversed(self)) elif self.type == "NP": w = find(lambda w: w.type.startswith("NN"), reversed(self)) elif self.type == "VP": ...
Yields the head of the chunk (usually, the last word in the chunk).
349,170
def median_fltr(dem, fsize=7, origmask=False): print("Applying median filter with size %s" % fsize) from scipy.ndimage.filters import median_filter dem_filt_med = median_filter(dem.filled(np.nan), fsize) out = np.ma.fix_invalid(dem_filt_med, copy=False, fill_value=dem.fill_value) if origma...
Scipy.ndimage median filter Does not properly handle NaN
349,171
def _install(path, args): try: from bcbio import install as bcb except: raise ImportError("It needs bcbio to do the quick installation.") path_flavor = _get_flavor() s = {"fabricrc_overrides": {"system_install": path, "local_install": os.path.join(pat...
small helper for installation in case outside bcbio
349,172
def encode(self, text: str) -> str: def callback(match: Match) -> str: name = match.group("name").lower() if name in ["here", "everyone", "channel"]: return f"<!{name}>" else: for user in self.users.values(): if us...
Encode @username into <@id> or <!alias>.
349,173
def has_insert(self, shape): for insert in self.inserts: if insert.shape == shape: return True return False
Returns True if any of the inserts have the given shape.
349,174
def set_details(self, details, **kwargs): return self._set_details(self._dxid, details, **kwargs)
:param details: Details to set for the object :type details: dict or list :raises: :class:`~dxpy.exceptions.DXAPIError` if the object is not in the "open" state Sets the details for the remote object with the specified value. If the input contains the string ``"$dnanexus_link"`` as a ke...
349,175
def collections(self): import time gotten_feed_num = 20 offset = 0 data = { :, : self.xsrf } while gotten_feed_num >= 10: data[] = "{\"answer_url\": %d,\"offset\": %d}" % (self.id, offset) res = self._session.post(u...
获取包含该答案的收藏夹 :return: 包含该答案的收藏夹 :rtype: Collection.Iterable collect_num 未必等于 len(collections),比如: https://www.zhihu.com/question/20064699/answer/13855720 显示被收藏 38 次,但只有 30 个收藏夹
349,176
def add_char(self, char): if char == : self.flush() self._r.add_tab() elif char in : self.flush() self._r.add_br() else: self._bfr.append(char)
Process the next character of input through the translation finite state maching (FSM). There are two possible states, buffer pending and not pending, but those are hidden behind the ``.flush()`` method which must be called at the end of text to ensure any pending ``<w:t>`` element is wr...
349,177
def _swap_ending(s, ending, delim=): parts = [x for x in s.split(delim)[:-1] if x != ] parts.append(ending) return delim.join(parts)
Replace the ending of a string, delimited into an arbitrary number of chunks by `delim`, with the ending provided Parameters ---------- s : string string to replace endings ending : string string used to replace ending of `s` delim : string ...
349,178
def _prepare_connection(**kwargs): pyeapi_kwargs = __salt__[](, {}) pyeapi_kwargs.update(kwargs) init_kwargs, fun_kwargs = __utils__[](pyeapi_kwargs, PYEAPI_INIT_KWARGS) if not in init_kwargs: init_kwargs[] = conn = pyeapi.client.connect(**init_kwargs) node = pyeapi.client.Node(...
Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init.
349,179
def check_worker_status(): if not in request.args: resp = {"status": "bad request"} return jsonify(**resp) else: worker_id = request.args[] assignment_id = request.args[] allow_repeats = CONFIG.getboolean(, ) if allow_repeats: try: ...
Check worker status route
349,180
def get_nameserver_detail_output_show_nameserver_nameserver_sharearea(self, **kwargs): config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_nameserver_detail, "output") show_na...
Auto Generated Code
349,181
def send_message(self, body): token, tracker = self.send_message_tracked(body) tracker.cancel() return token
Send a message to the conversation. :param msg: The message to send. :type msg: :class:`aioxmpp.Message` :return: The stanza token obtained from sending. :rtype: :class:`~aioxmpp.stream.StanzaToken` The default implementation simply calls :meth:`send_message_tracked` an...
349,182
def match_prefix(self, string): for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]: matches = [(r, r.match(string)) for r in patterns] matches = [(r, m) for r, m in matches if m] if matches != []: return Match(st...
Do a partial match of the string with the grammar. The returned :class:`Match` instance can contain multiple representations of the match. This will never return `None`. If it doesn't match at all, the "trailing input" part will capture all of the input. :param string: The input string.
349,183
def _truncate_bitmap(what): for i in xrange(len(what) - 1, -1, -1): if what[i] != : break return .join(what[0 : i + 1])
Determine the index of greatest byte that isn't all zeros, and return the bitmap that contains all the bytes less than that index. @param what: a string of octets representing a bitmap. @type what: string @rtype: string
349,184
def on_finish(self): if self._cfg_path and os.path.isfile(self._cfg_path): if self.run_as_user: subprocess.call([, , self._cfg_path], close_fds=True) else: os.remove(self._cfg_path)
A callback that should be called when this is done running.
349,185
def PopItem(self): if not self._zmq_socket: self._CreateZMQSocket() if not self._closed_event or not self._terminate_event: raise RuntimeError() logger.debug( .format(self.name, self.port)) last_retry_timestamp = time.time() + self.timeout_seconds while not self._closed_e...
Pops an item off the queue. If no ZeroMQ socket has been created, one will be created the first time this method is called. Returns: object: item from the queue. Raises: KeyboardInterrupt: if the process is sent a KeyboardInterrupt while popping an item. QueueEmpty: if the...
349,186
def text(self,text): if text: text = utfstr(text) text = text.strip() text = re.sub(,,text) if text: self.dirty = True self.escpos.text(text)
puts text in the entity. Whitespace and newlines are stripped to single spaces.
349,187
def reuse_handle( self, name: str, rename: str, pmap: Dict[str, Set[str]], ) -> bool: if name in pmap: name_map = pmap[name] if rename not in name_map: name_map.add(rename) func = self._func_map[...
判断是否复用之前的
349,188
def list_memberships(self, subject_descriptor, direction=None, depth=None): route_values = {} if subject_descriptor is not None: route_values[] = self._serialize.url(, subject_descriptor, ) query_parameters = {} if direction is not None: query_parameters[...
ListMemberships. [Preview API] Get all the memberships where this descriptor is a member in the relationship. :param str subject_descriptor: Fetch all direct memberships of this descriptor. :param str direction: Defaults to Up. :param int depth: The maximum number of edges to traverse up...
349,189
def etm_register_write(self, register_index, value, delay=False): self._dll.JLINKARM_ETM_WriteReg(int(register_index), int(value), int(delay)) return None
Writes a value to an ETM register. Args: self (JLink): the ``JLink`` instance. register_index (int): the register to write to. value (int): the value to write to the register. delay (bool): boolean specifying if the write should be buffered. Returns: `...
349,190
def apply(self, search, field, value): return search.query( self.query_type( **{ field: { self.operator: self.get_value_query(value) } } ) )
Apply lookup expression to search query.
349,191
def move_application(self, app_id, queue): self._call(, proto.MoveRequest(id=app_id, queue=queue))
Move an application to a different queue. Parameters ---------- app_id : str The id of the application to move. queue : str The queue to move the application to.
349,192
def format_xml(self, value): def normalize_iter(value): if isinstance(value, (list, tuple)): if isinstance(value[0], str): xmlval = value else: xmlval = [] elif isinstance(value, dict): xmlva...
Render a formatted multi-line XML string from a complex Python data structure. Supports tag attributes and nested dicts/lists. :param value: Complex data structure representing XML contents :returns: Formatted XML string rendered with newlines and indentation :rtype: str
349,193
def bucket_values(distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10) -> torch.Tensor: logspace_index = (distances.float().log() / math.log(2)).floor().long() + (num_identity_buckets - 1) use_identity_mask = ...
Places the given values (designed for distances) into ``num_total_buckets``semi-logscale buckets, with ``num_identity_buckets`` of these capturing single values. The default settings will bucket values into the following buckets: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+]. Parameters ----------...
349,194
def __populate_parser_from_config(self, arg_parser, config_data, prefix=): for k,v in config_data.items(): k = prefix + + k if prefix else k if isinstance(v, dict): self.__populate_parser_from_config(arg_parser, v, prefix=k) else: sel...
Populates an ArgumentParser object with arguments where each argument is a key from the given config_data dictionary. :param str prefix: Prepends the key with this prefix delimited by a single '.' character. :param argparse.ArgumentParser arg_parser: :param dict config_data: The parsed ...
349,195
def score_xrefs_by_semsim(self, xg, ont=None): logging.info("scoring xrefs by semantic similarity for {} nodes in {}".format(len(xg.nodes()), ont)) for (i,j,d) in xg.edges(data=True): pfx1 = self._id_to_ontology(i) pfx2 = self._id_to_ontology(j) ancs1 = self....
Given an xref graph (see ref:`get_xref_graph`), this will adjust scores based on the semantic similarity of matches.
349,196
def isin(self, values): if isinstance(values, dict): from pandas.core.reshape.concat import concat values = collections.defaultdict(list, values) return concat((self.iloc[:, [i]].isin(values[col]) for i, col in enumerate(self.columns)), axi...
Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If `values` is a Series, that's the index. If `values` is a di...
349,197
def ie(self): self.cdm() if self._config.ADAPTIVE: self.queue_adaptive() self.text_rank() self.title_extractor() if self._config.ADAPTIVE: self.title_adaptive() self.time_extractor() log(, ) log(, .format(self.title)) ...
信息抽取
349,198
def addFeature(self, feature): if isinstance(feature, Feature): self.features.append(feature) else: raise TypeError( % type(feature))
Appends Feature
349,199
def le(self, event_property, value): c = self.copy() c.filters.append(filters.LE(event_property, value)) return c
A less-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.le('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).le(elapsed_ms, 500)