Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
383,000
def forward(self, inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: if self._word_embedding is not None and word_inputs is not None: try: mask_without_bos_eos = (word_inputs > 0).l...
Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch. word_inputs : ``torch.Tensor``, required. If you passed a cached vocab, you can in addition pass a tensor of shape ``(batch_siz...
383,001
def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_...
Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole
383,002
def on_builder_inited(app): app.cache_db_path = ":memory:" if app.config["uqbar_book_use_cache"]: logger.info(bold("[uqbar-book]"), nonl=True) logger.info(" initializing cache db") app.connection = uqbar.book.sphinx.create_cache_db(app.cache_db_path)
Hooks into Sphinx's ``builder-inited`` event.
383,003
def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"): if base_elements is None: base_elements = ["base_link"] links = URDF_utils.get_urdf_parameters(urdf_file, base_elements=base_elements, last...
Creates a chain from an URDF file Parameters ---------- urdf_file: str The path of the URDF file base_elements: list of strings List of the links beginning the chain last_link_vector: numpy.array Optional : The translation vector of the tip. ...
383,004
def start_server(socket, projectname, xmlfilename: str) -> None: state.initialise(projectname, xmlfilename) server = http.server.HTTPServer((, int(socket)), HydPyServer) server.serve_forever()
Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` is an absolute file path. The XML configuration file must be valid c...
383,005
def phistogram(view, a, bins=10, rng=None, normed=False): nengines = len(view.targets) with view.sync_imports(): import numpy rets = view.apply_sync(lambda a, b, rng: numpy.histogram(a,b,rng), Reference(a), bins, rng) hists = [ r[0] for r in rets ] lower_edges = [ r[1] for r i...
Compute the histogram of a remote array a. Parameters ---------- view IPython DirectView instance a : str String name of the remote array bins : int Number of histogram bins rng : (float, float) Tuple of min, max of the range t...
383,006
def remove_unicode_dict(input_dict): if isinstance(input_dict, collections.Mapping): return dict(map(remove_unicode_dict, input_dict.iteritems())) elif isinstance(input_dict, collections.Iterable): return type(input_dict)(map(remove_unicode_dict, input_dict)) else: return input_...
remove unicode keys and values from dict, encoding in utf8
383,007
def parse_encoding(fp): pos = fp.tell() fp.seek(0) try: line1 = fp.readline() has_bom = line1.startswith(codecs.BOM_UTF8) if has_bom: line1 = line1[len(codecs.BOM_UTF8):] m = _PYTHON_MAGIC_COMMENT_re.match(line1.decode(, )) if not m: try:...
Deduce the encoding of a Python source file (binary mode) from magic comment. It does this in the same way as the `Python interpreter`__ .. __: http://docs.python.org/ref/encodings.html The ``fp`` argument should be a seekable file object in binary mode.
383,008
def max_entropy_distribution(node_indices, number_of_nodes): distribution = np.ones(repertoire_shape(node_indices, number_of_nodes)) return distribution / distribution.size
Return the maximum entropy distribution over a set of nodes. This is different from the network's uniform distribution because nodes outside ``node_indices`` are fixed and treated as if they have only 1 state. Args: node_indices (tuple[int]): The set of node indices over which to take ...
383,009
def partial_dependence(self, term, X=None, width=None, quantiles=None, meshgrid=False): if not self._is_fitted: raise AttributeError() if not isinstance(term, int): raise ValueError(.format(term)) if (term >= len(self.terms))...
Computes the term functions for the GAM and possibly their confidence intervals. if both width=None and quantiles=None, then no confidence intervals are computed Parameters ---------- term : int, optional Term for which to compute the partial dependence func...
383,010
def match_comment(self): match = self.match(r"<%doc>(.*?)</%doc>", re.S) if match: self.append_node(parsetree.Comment, match.group(1)) return True else: return False
matches the multiline version of a comment
383,011
def _find_symbol(self, module, name, fallback=None): if not hasattr(module, name) and fallback: return self._find_symbol(module, fallback, None) return getattr(module, name)
Find the symbol of the specified name inside the module or raise an exception.
383,012
def __parse_dois(self, x): if isinstance(x, str): m = clean_doi(x) if m: self.doi = m elif isinstance(x, list): for entry in x: m = clean_doi(entry)...
Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs :param any x: Str or List of DOI ids :return none: list is set to self
383,013
def create_request(query): yarr_url = app.config.get(, False) if not yarr_url: raise() api_token = app.config.get(, False) headers = {: api_token} if api_token else {} payload = {: query} url = % yarr_url return requests.get(url, params=payload, headers=headers)
Creates a GET request to Yarr! server :param query: Free-text search query :returns: Requests object
383,014
def insert_lemmatisation_data(germanet_db): germanet_db.lemmatiser.drop() num_lemmas = 0 input_file = gzip.open(os.path.join(os.path.dirname(__file__), LEMMATISATION_FILE)) for line in input_file: line = line.decode().strip().split() asse...
Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object
383,015
def vtas2cas(tas, h): p, rho, T = vatmos(h) qdyn = p*((1.+rho*tas*tas/(7.*p))**3.5-1.) cas = np.sqrt(7.*p0/rho0*((qdyn/p0+1.)**(2./7.)-1.)) cas = np.where(tas<0, -1*cas, cas) return cas
tas2cas conversion both m/s
383,016
def paginate(self, url, key, params=None): if params is None: params = {} if self.per_page is not None and "per_page" not in params: params = dict(params, per_page=self.per_page) page = self.request(url, params=params) while True: try: ...
Fetch a sequence of paginated resources from the API endpoint. The initial request to ``url`` and all subsequent requests must respond with a JSON object; the field specified by ``key`` must be a list, whose elements will be yielded, and the next request will be made to the URL in the `...
383,017
def get_ip(data): try: ip = data.public_ips[0] except Exception: ip = data.private_ips[0] return ip
Return the IP address of the VM If the VM has public IP as defined by libcloud module then use it Otherwise try to extract the private IP and use that one.
383,018
def rescan_file(self, resource, date=, period=, repeat=, notify_url=, notify_changes_only=, timeout=None): params = {: self.api_key, : resource} try: response = requests.post(self.base + , params=params, proxies=self.proxies, timeout=timeout) except requests.RequestExceptio...
Rescan a previously submitted filed or schedule an scan to be performed in the future. This API allows you to rescan files present in VirusTotal's file store without having to resubmit them, thus saving bandwidth. You only need to know one of the hashes of the file to rescan. :param re...
383,019
def _mouseMoveDrag(moveOrDrag, x, y, xOffset, yOffset, duration, tween=linear, button=None): assert moveOrDrag in (, ), "moveOrDrag must be in (, ), not %s" % (moveOrDrag) if sys.platform != : moveOrDrag = xOffset = int(xOffset) if xOffset is not None else 0 yOffset = int(yOf...
Handles the actual move or drag event, since different platforms implement them differently. On Windows & Linux, a drag is a normal mouse move while a mouse button is held down. On OS X, a distinct "drag" event must be used instead. The code for moving and dragging the mouse is similar, so this functi...
383,020
def configfile_from_path(path, strict=True): extension = path.split()[-1] conf_type = FILE_TYPES.get(extension) if not conf_type: raise exc.UnrecognizedFileExtension( "Cannot parse file of type {0}. Choices are {1}.".format( extension, FILE_TYPES.key...
Get a ConfigFile object based on a file path. This method will inspect the file extension and return the appropriate ConfigFile subclass initialized with the given path. Args: path (str): The file path which represents the configuration file. strict (bool): Whether or not to parse the file...
383,021
def set_option(self, option, value): CONF.set(self.CONF_SECTION, str(option), value)
Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin.
383,022
def setColumnMapper(self, columnName, callable): columnName = nativestring(columnName) if ( callable is None and columnName in self._columnMappers ): self._columnMappers.pop(columnName) return self._columnMappers[nativestring(columnName)] = callab...
Sets the mapper for the given column name to the callable. The inputed callable should accept a single argument for a record from the tree and return the text that should be displayed in the column. :param columnName | <str> callable | <function> || <met...
383,023
async def play_tone(self, pin, tone_command, frequency, duration): if tone_command == Constants.TONE_TONE: if duration: data = [tone_command, pin, frequency & 0x7f, (frequency >> 7) & 0x7f, duration & 0x7f, (duration >> 7) & 0x7f...
This method will call the Tone library for the selected pin. It requires FirmataPlus to be loaded onto the arduino If the tone command is set to TONE_TONE, then the specified tone will be played. Else, if the tone command is TONE_NO_TONE, then any currently playing tone will be...
383,024
def starts(self, layer): starts = [] for data in self[layer]: starts.append(data[START]) return starts
Retrieve start positions of elements if given layer.
383,025
def crypto_core_ed25519_is_valid_point(p): ensure(isinstance(p, bytes) and len(p) == crypto_core_ed25519_BYTES, , raising=exc.TypeError) rc = lib.crypto_core_ed25519_is_valid_point(p) return rc == 1
Check if ``p`` represents a point on the edwards25519 curve, in canonical form, on the main subgroup, and that the point doesn't have a small order. :param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence representing a point on the edwards25519 curve :type p: bytes :return:...
383,026
def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False): if stanford: port_shift = 1 else: port_shift = 0 command1 = .format(port-1-port_shift, server2, user1, server1) command2 = .format(port-port_shift, port-port_shift-1, user2) command3 = .format...
Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*. If *verbose* is true, prints various ssh commands. If *stanford* is true, shifts ports up by 1. Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line.
383,027
def perimeter(self): return sum([a.distance(b) for a, b in self.pairs()])
Sum of the length of all sides, float.
383,028
def transfer(self, name, local, remote, **kwargs): try: remote.save(name, local.open(name)) return True except Exception as e: logger.error("Unable to save to remote storage. " "About to retry." % name) logger.exception(e...
Transfers the file with the given name from the local to the remote storage backend. :param name: The name of the file to transfer :param local: The local storage backend instance :param remote: The remote storage backend instance :returns: `True` when the transfer succeeded, `F...
383,029
def resize_max(img, max_side): h, w = img.shape[:2] if h > w: nh = max_side nw = w * (nh / h) else: nw = max_side nh = h * (nw / w) return cv.resize(img, (nw, nh))
Resize the image to threshold the maximum dimension within max_side :param img: :param max_side: Length of the maximum height or width :return:
383,030
def filter(self, s, method=, order=30): r s = self.G._check_signal(s) if s.ndim == 1 or s.shape[-1] not in [1, self.Nf]: if s.ndim == 3: raise ValueError( .format(self.Nf, s.shape)) ...
r"""Filter signals (analysis or synthesis). A signal is defined as a rank-3 tensor of shape ``(N_NODES, N_SIGNALS, N_FEATURES)``, where ``N_NODES`` is the number of nodes in the graph, ``N_SIGNALS`` is the number of independent signals, and ``N_FEATURES`` is the number of features which...
383,031
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30): from scipy import integrate from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import cnames def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0): x, y, z = coords return [sigma...
Plot a 3D visualization of the dynamics of the Lorenz system
383,032
def analyze_internal_angles(self, return_plot=False): angles = self.get_internal_angles().flatten() print(.format(np.min(angles))) print(.format(np.max(angles))) for i in range(10, 100, 10): print(.format( i, np.percentile(an...
Analyze the internal angles of the grid. Angles shouldn't be too small because this can cause problems/uncertainties in the Finite-Element solution of the forward problem. This function prints the min/max values, as well as quantiles, to the command line, and can also produce a histogram...
383,033
def write(self, data): if self.closed: raise ConnectionResetError( % self ) else: t = self.transport if self._paused or self._buffer: self._buffer.appendleft(data) self._buffer_size += len(data) ...
Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing.
383,034
def authenticate(session, username, password): if not username or not password: raise AuthenticationError() user = session.query(PasswordUser).filter( PasswordUser.username == username).first() if not user: raise AuthenticationError() if not user.authenticate(password): ...
Authenticate a PasswordUser with the specified username/password. :param session: An active SQLAlchemy session :param username: The username :param password: The password :raise AuthenticationError: if an error occurred :return: a PasswordUser
383,035
def handle_request(self): try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): self.workerpool.run(self.process_request_thread, **{: request, ...
simply collect requests and put them on the queue for the workers.
383,036
def removeAssociation(self, server_url, handle): assoc = self.getAssociation(server_url, handle) if assoc is None: return 0 else: filename = self.getAssociationFilename(server_url, handle) return _removeIfPresent(filename)
Remove an association if it exists. Do nothing if it does not. (str, str) -> bool
383,037
def get(self, model_class, strict=True, returnDict=False, fetchOne=False, **where): self.typeassert(model_class, strict, returnDict, where) table = model_class.__name__.lower() with Session(self.settings) as conn: if not where: query = f else: ...
params: model_class: The queried model class strict: bool -> If True, queries are run with EQUAL(=) operator. If False: Queries are run with RLIKE keyword returnDict: bool -> Return a list if dictionaries(field_names: values) fetchOne: bool -> cursor.fetchone() else: cursor.fetch...
383,038
def add_text(self, tag, text, global_step=None): self._file_writer.add_summary(text_summary(tag, text), global_step) if tag not in self._text_tags: self._text_tags.append(tag) extension_dir = self.get_logdir() + if not os.path.exists(extension_dir): ...
Add text data to the event file. Parameters ---------- tag : str Name for the `text`. text : str Text to be saved to the event file. global_step : int Global step value to record.
383,039
def extract_secs(self, tx, tx_in_idx): sc = tx.SolutionChecker(tx) tx_context = sc.tx_context_for_idx(tx_in_idx) solution_stack = [] for puzzle_script, solution_stack, flags, sighash_f in sc.puzzle_and_solution_iterator(tx_context): for opcode, data, pc, new...
For a given script solution, iterate yield its sec blobs
383,040
def find_config_section(self, object_type, name=None): possible = [] for name_options in object_type.config_prefixes: for name_prefix in name_options: found = self._find_sections( self.parser.sections(), name_prefix, name) if found...
Return the section name with the given name prefix (following the same pattern as ``protocol_desc`` in ``config``. It must have the given name, or for ``'main'`` an empty name is allowed. The prefix must be followed by a ``:``. Case is *not* ignored.
383,041
def flow_meter_discharge(D, Do, P1, P2, rho, C, expansibility=1.0): r beta = Do/D beta2 = beta*beta return (0.25*pi*Do*Do)*C*expansibility*( (2.0*rho*(P1 - P2))/(1.0 - beta2*beta2))**0.5
r'''Calculates the flow rate of an orifice plate based on the geometry of the plate, measured pressures of the orifice, and the density of the fluid. .. math:: m = \left(\frac{\pi D_o^2}{4}\right) C \frac{\sqrt{2\Delta P \rho_1}} {\sqrt{1 - \beta^4}}\cdot \epsilon Parameter...
383,042
def temporal_from_resource(resource): if isinstance(resource.identifier, URIRef): g = Graph().parse(str(resource.identifier)) resource = g.resource(resource.identifier) if resource.value(SCHEMA.startDate): return db.DateRange( start=resource.value(SCHEMA.startDa...
Parse a temporal coverage from a RDF class/resource ie. either: - a `dct:PeriodOfTime` with schema.org `startDate` and `endDate` properties - an inline gov.uk Time Interval value - an URI reference to a gov.uk Time Interval ontology http://reference.data.gov.uk/
383,043
def get_parent_vault_ids(self, vault_id): if self._catalog_session is not None: return self._catalog_session.get_parent_catalog_ids(catalog_id=vault_id) return self._hierarchy_session.get_parents(id_=vault_id)
Gets the parent ``Ids`` of the given vault. arg: vault_id (osid.id.Id): a vault ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the vault raise: NotFound - ``vault_id`` is not found raise: NullArgument - ``vault_id`` is ``null`` raise: OperationFailed - unable to c...
383,044
def forward(self, input_ids, target=None, mems=None): bsz = input_ids.size(0) tgt_len = input_ids.size(1) last_hidden, new_mems = self.transformer(input_ids, mems) pred_hid = last_hidden[:, -tgt_len:] if self.sample_softmax > 0 and self.training: assert sel...
Params: input_ids :: [bsz, len] target :: [bsz, len] Returns: tuple(softmax_output, new_mems) where: new_mems: list (num layers) of hidden states at the entry of each layer shape :: [mem_len, bsz, self.config.d_model...
383,045
def sh_report(self, full=True, latest=False): def pathvar_repr(var): _var = var.replace(, ) return % _var output = [] if not self.remote_url: output.append() output = output + ( [self.label] + self.clone_cmd ...
Show shell command necessary to clone this repository If there is no primary remote url, prefix-comment the command Keyword Arguments: full (bool): also include commands to recreate branches and remotes latest (bool): checkout repo.branch instead of repo.current_id Yie...
383,046
def AddXrefTo(self, ref_kind, classobj, methodobj, offset): self.xrefto[classobj].add((ref_kind, methodobj, offset))
Creates a crossreference to another class. XrefTo means, that the current class calls another class. The current class should also be contained in the another class' XrefFrom list. :param REF_TYPE ref_kind: type of call :param classobj: :class:`ClassAnalysis` object to link :par...
383,047
def clean_linebreaks(self, tag): stripped = tag.decode(formatter=None) stripped = re.sub(, , stripped) stripped = re.sub(, , stripped) return stripped
get unicode string without any other content transformation. and clean extra spaces
383,048
def columns_used(self): return list(tz.unique(tz.concatv( self.choosers_columns_used(), self.alts_columns_used(), self.interaction_columns_used())))
Columns from any table used in the model. May come from either the choosers or alternatives tables.
383,049
def iterbyscore(self, min=, max=, start=None, num=None, withscores=False, reverse=None): reverse = reverse if reverse is not None else self.reversed zfunc = self._client.zrangebyscore if not reverse \ else self._client.zrevrangebyscore _loads = self._load...
Return a range of values from the sorted set name with scores between @min and @max. If @start and @num are specified, then return a slice of the range. @min: #int minimum score, or #str '-inf' @max: #int minimum score, or #str '+inf' @start: #in...
383,050
def lookup_by_partial_name(self, partial_name): for k, v in self._name_database.items(): if _uax44lm2transform(partial_name) in k: yield v
Similar to lookup_by_name(name), this method uses loose matching rule UAX44-LM2 to attempt to find the UnicodeCharacter associated with a name. However, it attempts to permit even looser matching by doing a substring search instead of a simple match. This method will return a generator that yields ins...
383,051
def national_significant_number(numobj): national_number = U_EMPTY_STRING if numobj.italian_leading_zero: num_zeros = numobj.number_of_leading_zeros if num_zeros is None: num_zeros = 1 if num_zeros > 0: national_number = U_ZERO * num_zeros natio...
Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant number is needed. Returns the national significant numb...
383,052
def translate_js_with_compilation_plan(js, HEADER=DEFAULT_HEADER): match_increaser_str, match_increaser_num, compilation_plan = get_compilation_plan( js) cp_hash = hashlib.md5(compilation_plan.encode()).digest() try: python_code = cache[cp_hash][] except: parser = pyjspars...
js has to be a javascript source code. returns equivalent python code. compile plans only work with the following restrictions: - only enabled for oneliner expressions - when there are comments in the js code string substitution is disabled - when there nested escaped quotes string s...
383,053
def from_las3(cls, string, lexicon=None, source="LAS", dlm=, abbreviations=False): f = re.DOTALL | re.IGNORECASE regex = r pattern = re.compile(regex, flags=f) text = pattern.search(string).group(1) s = re.search(r, ...
Turn LAS3 'lithology' section into a Striplog. Args: string (str): A section from an LAS3 file. lexicon (Lexicon): The language for conversion to components. source (str): A source for the data. dlm (str): The delimiter. abbreviations (bool): Whether ...
383,054
def _insert_stack(stack, sample_count, call_tree): curr_level = call_tree for func in stack: next_level_index = { node[]: node for node in curr_level[]} if func not in next_level_index: new_node = {: func, : [], : 0} curr_l...
Inserts stack into the call tree. Args: stack: Call stack. sample_count: Sample count of call stack. call_tree: Call tree.
383,055
def cache_page(**kwargs): cache_timeout = kwargs.pop(, None) key_prefix = kwargs.pop(, None) cache_min_age = kwargs.pop(, None) decorator = decorators.decorator_from_middleware_with_args(CacheMiddleware)( cache_timeout=cache_timeout, key_prefix=key_prefix, cache_min_age=cach...
This decorator is similar to `django.views.decorators.cache.cache_page`
383,056
def on_exception(func): class OnExceptionDecorator(LambdaDecorator): def on_exception(self, exception): return func(exception) return OnExceptionDecorator
Run a function when a handler thows an exception. It's return value is returned to AWS. Usage:: >>> # to create a reusable decorator >>> @on_exception ... def handle_errors(exception): ... print(exception) ... return {'statusCode': 500, 'body': 'uh oh'} ...
383,057
def switch_focus(self, layout, column, widget): for i, l in enumerate(self._layouts): if l is layout: break else: return self._layouts[self._focus].blur() self._focus = i self._layouts[self._focus].focus(forc...
Switch focus to the specified widget. :param layout: The layout that owns the widget. :param column: The column the widget is in. :param widget: The index of the widget to take the focus.
383,058
def fetch_github_activity(gen, metadata): if in gen.settings.keys(): gen.context[] = gen.plugin_instance.fetch()
registered handler for the github activity plugin it puts in generator.context the html needed to be displayed on a template
383,059
def load_all_distributions(self): distributions = [] for this in dir(scipy.stats): if "fit" in eval("dir(scipy.stats." + this +")"): distributions.append(this) self.distributions = distributions[:]
Replace the :attr:`distributions` attribute with all scipy distributions
383,060
def format_text_as_docstr(text): r import utool as ut import re min_indent = ut.get_minimum_indentation(text) indent_ = * min_indent formated_text = re.sub( + indent_, + indent_ + , text, flags=re.MULTILINE) formated_text = re.sub(, + indent_ + , formated_text,...
r""" CommandLine: python ~/local/vim/rc/pyvim_funcs.py --test-format_text_as_docstr Example: >>> # DISABLE_DOCTEST >>> from pyvim_funcs import * # NOQA >>> text = testdata_text() >>> formated_text = format_text_as_docstr(text) >>> result = ('formated_text = \...
383,061
def _get_serialization_name(element_name): known = _KNOWN_SERIALIZATION_XFORMS.get(element_name) if known is not None: return known if element_name.startswith(): return element_name.replace(, ) if element_name.endswith(): element_name = element_name.replace(, ) for name...
converts a Python name into a serializable name
383,062
def parser(self): if self._parser is None: apkw = { : self.description, : self.epilog, } self._parser = argparse.ArgumentParser(**apkw) if self.version: self._parser.add_argument( ...
Instantiates the argparse parser
383,063
def matches(self, filter_props): if filter_props is None: return False found_one = False for key, value in filter_props.items(): if key in self.properties and value != self.properties[key]: return False elif key in self.properties and...
Check if the filter matches the supplied properties.
383,064
def parse(template, delimiters=None): if type(template) is not unicode: raise Exception("Template is not unicode: %s" % type(template)) parser = _Parser(delimiters) return parser.parse(template)
Parse a unicode template string and return a ParsedTemplate instance. Arguments: template: a unicode template string. delimiters: a 2-tuple of delimiters. Defaults to the package default. Examples: >>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}") >>> print str(parsed).replace('u', ...
383,065
def get_template_loader(app, subdir=): dmp = apps.get_app_config() return dmp.engine.get_template_loader(app, subdir, create=True)
Convenience method that calls get_template_loader() on the DMP template engine instance.
383,066
def _make_actor_method_executor(self, method_name, method, actor_imported): def actor_method_executor(dummy_return_id, actor, *args): self._worker.actor_task_counter += 1 try: if is_class_method(method): ...
Make an executor that wraps a user-defined actor method. The wrapped method updates the worker's internal state and performs any necessary checkpointing operations. Args: method_name (str): The name of the actor method. method (instancemethod): The actor method to wrap....
383,067
def spacing(text): if len(text) <= 1 or not ANY_CJK.search(text): return text new_text = text matched = CONVERT_TO_FULLWIDTH_CJK_SYMBOLS_CJK.search(new_text) while matched: start, end = matched.span() new_text = .join((new_text[:start + 1], convert_to_fullwidth(new_te...
Perform paranoid text spacing on text.
383,068
def save_new_channel(self): form_info = self.input[] channel = Channel(typ=15, name=form_info[], description=form_info[], owner_id=form_info[]) channel.blocking_save() self.current.task_data[] = channel.key
It saves new channel according to specified channel features.
383,069
def eof_received(self) -> bool: logger.debug("%s - event = eof_received()", self.side) super().eof_received() return False
Close the transport after receiving EOF. Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns ``True`` on non-TLS connections. See http://bugs.python.org/issue24539 for more information. This is inappropriate for websockets for at least three reasons: 1. The u...
383,070
def saltbridge(poscenter, negcenter, protispos): data = namedtuple( , ) pairings = [] for pc, nc in itertools.product(poscenter, negcenter): if not config.MIN_DIST < euclidean3d(pc.center, nc.center) < config.SALTBRIDGE_DIST_MAX: continue resnr = pc.resnr if protispo...
Detect all salt bridges (pliprofiler between centers of positive and negative charge)
383,071
def setup_button_connectors(self): self.help_button.clicked.connect(self.show_help) self.run_button.clicked.connect(self.accept) self.about_button.clicked.connect(self.about) self.print_button.clicked.connect(self.show_print_dialog) self.hazard_layer_combo.currentIndexCh...
Setup signal/slot mechanisms for dock buttons.
383,072
def photo_url(self): if self.url is not None: if self.soup is not None: img = self.soup.find(, class_=)[] return img.replace(, ) else: assert (self.card is not None) return PROTOCOL + self.card.img[].replace(, ) ...
获取用户头像图片地址. :return: 用户头像url :rtype: str
383,073
def Popen(self, cmd, **kwargs): prefixed_cmd = self._prepare_cmd(cmd) return subprocess.Popen(prefixed_cmd, **kwargs)
Remote Popen.
383,074
def build_matlab(static=False): cfg = get_config() if in cfg and cfg[] != : matlab_bin = cfg[].strip() else: matlab_bin = which_matlab() if matlab_bin is None: raise ValueError("specify in cfg file") extcmd = esc(os.path.join(matlab_bin, "mexex...
build the messenger mex for MATLAB static : bool Determines if the zmq library has been statically linked. If so, it will append the command line option -DZMQ_STATIC when compiling the mex so it matches libzmq.
383,075
def load(self, path=None): section1option1valueoption2value2 paths = self._paths.copy() if path: if path.is_dir(): path /= .format(self._configuration_name) paths.append(path) paths = [(path_._root / str(x)[1:] if x.is_absolute()...
Load configuration (from configuration files). Parameters ---------- path : ~pathlib.Path or None Path to configuration file, which must exist; or path to directory containing a configuration file; or None. Returns ------- ~typing.Dict[str, ~typi...
383,076
def from_pb(cls, operation_pb, client, **caller_metadata): result = cls(operation_pb.name, client, **caller_metadata) result._update_state(operation_pb) result._from_grpc = True return result
Factory: construct an instance from a protobuf. :type operation_pb: :class:`~google.longrunning.operations_pb2.Operation` :param operation_pb: Protobuf to be parsed. :type client: object: must provide ``_operations_stub`` accessor. :param client: The client used to poll fo...
383,077
def get(self): custom_arg = {} if self.key is not None and self.value is not None: custom_arg[self.key] = self.value return custom_arg
Get a JSON-ready representation of this CustomArg. :returns: This CustomArg, ready for use in a request body. :rtype: dict
383,078
def infer_child_relations(graph, node: BaseEntity) -> List[str]: return list(_infer_child_relations_iter(graph, node))
Propagate causal relations to children.
383,079
def get_meta_attributes(self, **kwargs): superuser = kwargs.get(, False) if (self.untl_object.qualifier == or self.untl_object.qualifier == ): if superuser: self.editable = True self.repeatable = True else: ...
Determine the form attributes for the meta field.
383,080
def parseSOAPMessage(data, ipAddr): "parse raw XML data string, return a (minidom) xml document" try: dom = minidom.parseString(data) except Exception: return None if dom.getElementsByTagNameNS(NS_S, "Fault"): return None soapAction = dom.getElementsByTag...
parse raw XML data string, return a (minidom) xml document
383,081
def get_acf(x, axis=0, fast=False): x = np.atleast_1d(x) m = [slice(None), ] * len(x.shape) if fast: n = int(2 ** np.floor(np.log2(x.shape[axis]))) m[axis] = slice(0, n) x = x else: n = x.shape[axis] f = np.fft.fft(x - np.mean(x, axis=axis), n=2 ...
Estimate the autocorrelation function of a time series using the FFT. :param x: The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. :param axis: (optional) The time axis of ``x``. As...
383,082
def load_credential_file(self, path): c_data = StringIO.StringIO() c_data.write("[Credentials]\n") for line in open(path, "r").readlines(): c_data.write(line.replace("AWSAccessKeyId", "aws_access_key_id").replace("AWSSecretKey", "aws_secret_access_key")) c_data.seek(...
Load a credential file as is setup like the Java utilities
383,083
def _get_clause_words( sentence_text, clause_id ): clause = [] isEmbedded = False indices = sentence_text.clause_indices clause_anno = sentence_text.clause_annotations for wid, token in enumerate(sentence_text[WORDS]): if indices[wid] == clause_id: if not clause and clause_a...
Collects clause with index *clause_id* from given *sentence_text*. Returns a pair (clause, isEmbedded), where: *clause* is a list of word tokens in the clause; *isEmbedded* is a bool indicating whether the clause is embedded;
383,084
def make_heading_authors(self, authors): author_element = etree.Element(, {: }) first = True for author in authors: if first: first = False else: append_new_text(author_element, , join_str=) collab = author.fin...
Constructs the Authors content for the Heading. This should display directly after the Article Title. Metadata element, content derived from FrontMatter
383,085
def add_aacgm_coordinates(inst, glat_label=, glong_label=, alt_label=): import aacgmv2 aalat = []; aalon = []; mlt = [] for lat, lon, alt, time in zip(inst[glat_label], inst[glong_label], inst[alt_label], inst.data.in...
Uses AACGMV2 package to add AACGM coordinates to instrument object. The Altitude Adjusted Corrected Geomagnetic Coordinates library is used to calculate the latitude, longitude, and local time of the spacecraft with respect to the geomagnetic field. Example ------- # function added...
383,086
def target_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/targets api_path = "/api/v2/targets/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/targets#show-target
383,087
def avail_locations(call=None): if call == : raise SaltCloudSystemExit( ) ret = {} conn = get_conn() for item in conn.list_locations()[]: reg, loc = item[].split() location = {: item[]} if reg not in ret: ret[reg] = {}...
Return a dict of all available VM locations on the cloud provider with relevant data
383,088
def _select_position(self, w, h): fitn = ((m.y+h, m.x, w, h, m) for m in self._max_rects if self._rect_fitness(m, w, h) is not None) fitr = ((m.y+w, m.x, h, w, m) for m in self._max_rects if self._rect_fitness(m, h, w) is not None) if not self.rot: ...
Select the position where the y coordinate of the top of the rectangle is lower, if there are severtal pick the one with the smallest x coordinate
383,089
def run(self, lines): if (not self.adjust_path) and (not self.image_ext): return lines ret = [] for line in lines: processed = {} while True: alt = img_name = match = re.search(r, line) ...
Filter method
383,090
def asFloat(self, maxval=1.0): x,y,pixels,info = self.asDirect() sourcemaxval = 2**info[]-1 del info[] info[] = float(maxval) factor = float(maxval)/float(sourcemaxval) def iterfloat(): for row in pixels: yield map(factor.__mul__, row...
Return image pixels as per :meth:`asDirect` method, but scale all pixel values to be floating point values between 0.0 and *maxval*.
383,091
def list_attributes(self): return [attribute for attribute, value in self.iteritems() if issubclass(value.__class__, Attribute)]
Returns the Node attributes names. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.list_attributes() ['attributeB', 'attributeA'] :return: Attributes names. :rtype: list
383,092
def _construct_from_permutation(self, significant_pathways): for side, pathway_feature_tuples in significant_pathways.items(): feature_pathway_dict = self._collect_pathways_by_feature( pathway_feature_tuples) self._edges_from_permutation(feature_pathway_dict)
Build the network from a dictionary of (side -> tuple lists), where the side is specified as "pos" and/or "neg" (from the feature gene signature(s)) and mapped to a tuple list of [(pathway, feature)]. Used during the PathCORE-T permutation test by applying the method `permute_pathways_ac...
383,093
def __alterDocstring(self, tail=, writer=None): assert isinstance(tail, str) and isinstance(writer, GeneratorType) lines = [] timeToSend = False inCodeBlock = False inCodeBlockObj = [False] inSection = False prefix = firstLineNum = -1 se...
Runs eternally, processing docstring lines. Parses docstring lines as they get fed in via send, applies appropriate Doxygen tags, and passes them along in batches for writing.
383,094
def update_long(self, **kwargs): for key, val in six.iteritems(kwargs): self.update_arg(key, long=val)
Update the long optional arguments (those with two leading '-') This method updates the short argument name for the specified function arguments as stored in :attr:`unfinished_arguments` Parameters ---------- ``**kwargs`` Keywords must be keys in the :attr:`unfinish...
383,095
def e(message, exit_code=None): print_log(message, YELLOW, BOLD) if exit_code is not None: sys.exit(exit_code)
Print an error log message.
383,096
def AAAA(host, nameserver=None): dig = [, , six.text_type(host), ] if nameserver is not None: dig.append(.format(nameserver)) cmd = __salt__[](dig, python_shell=False) if cmd[] != 0: log.warning( %s\, cmd[] ) return [] return ...
Return the AAAA record for ``host``. Always returns a list. CLI Example: .. code-block:: bash salt ns1 dig.AAAA www.google.com
383,097
def disconnect(receiver, signal=Any, sender=Any, weak=True): if signal is None: raise errors.DispatcherTypeError( %( receiver,sender) ) if weak: receiver = saferef.safeRef(receiver) senderkey = id(sender) try: signals = connections[senderkey] receivers = ...
Disconnect receiver from sender for signal receiver -- the registered receiver to disconnect signal -- the registered signal to disconnect sender -- the registered sender to disconnect weak -- the weakref state to disconnect disconnect reverses the process of connect, the semantics for the ind...
383,098
def filter(self, **kwargs): self._filters.append(ReadsAlignmentsFilter(**kwargs).filter) return self
Add a filter to this C{readsAlignments}. @param kwargs: Keyword arguments, as accepted by C{ReadsAlignmentsFilter}. @return: C{self}
383,099
def sendReset(self, sequenceId=0): for col in xrange(self.numColumns): self.sensorInputs[col].addResetToQueue(sequenceId) self.network.run(1)
Sends a reset signal to the network.