Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
339,700
def getStrikes(self, contract_identifier, smin=None, smax=None): strikes = [] contracts = self.contractDetails(contract_identifier)["contracts"] if contracts[0].m_secType not in ("FOP", "OPT"): return [] for contract in contracts: strikes.appen...
return strikes of contract / "multi" contract's contracts
339,701
def readeach(self, stream, **kwargs): for o in self.reader.loadeach(stream): yield o
Temporary hook for API while streaming reads are in experimental phase. Read each object from stream as available with generator. JSON blocks indefinitely waiting on JSON entities to arrive. MsgPack requires unpacker property to be fed stream using unpacker.feed() method.
339,702
def get_sort_order(molecules): neg_count = 0 pos_count = 0 for index in range(len(molecules)): scoreList = molecules[index].GetProp() for element in scoreList: if float(element) > 0: pos_count += 1 elif float(element) < 0: neg_c...
Count up the total number of scores whose values are positve and negative. If a greater number are negative, then sort in ascending order (e.g. for binding energy estimates) Otherwise, sort in descending order (e.g. for similarity values)
339,703
def _handle_config(self, data): self.room.config.update(data) self.conn.enqueue_data("config", data)
Handle initial config push and config changes
339,704
def psdump(self, filename=None, **kargs): canvas = self.canvas_dump(**kargs) if filename is None: fname = get_temp_file(autoext=".eps") canvas.writeEPSfile(fname) subprocess.Popen([conf.prog.psreader, fname+".eps"]) else: canvas.writeEPSfi...
psdump(filename=None, layer_shift=0, rebuild=1) Creates an EPS file describing a packet. If filename is not provided a temporary file is created and gs is called.
339,705
def click(self, jquery=False): if jquery: e = JQuery(self) e.click() else: super(Clickable, self).click()
Click by WebElement, if not, JQuery click
339,706
def parse(cls, args): parsed = {} try: (options, args) = cls.optparser.parse_args(args) except OptionParsingError as e: raise ParseError(e.msg, cls.optparser.format_help()) except OptionParsingExit as e: return None parsed[] = option...
Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args: `args`: sequence of arguments Returns: Dictionary that can be used in create method Raises: ParseError: when the arguments are no...
339,707
def delete_token(self): if self.token_path.exists(): self.token_path.unlink() return True return False
Deletes the token file :return bool: Success / Failure
339,708
def load(self, in_fh, header=False, delimit=None, verbose=False): self.clear() if verbose: sys.stderr.write("getting input...\n") in_strm = in_fh if isinstance(in_strm, basestring): in_strm = open(in_strm) for line in in_strm: line = line.strip() if line == "": ...
Load this data_table from a stream or file. Blank lines in the file are skipped. Any existing values in this dataTable object are cleared before loading the new ones. :param in_fh: load from this stream. Can also be a string, in which case we treat it as a filename and attempt to l...
339,709
def saved_searches(self): return bind_api( api=self, path=, payload_type=, payload_list=True, require_auth=True )
:reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
339,710
def for_meters(cls, meter_x, meter_y, zoom): point = Point.from_meters(meter_x=meter_x, meter_y=meter_y) pixel_x, pixel_y = point.pixels(zoom=zoom) return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
Creates a tile from X Y meters in Spherical Mercator EPSG:900913
339,711
def version_id(self): return hashlib.sha1(.format( self.id, self.updated).encode()).hexdigest()
Return the version of the community. :returns: hash which encodes the community id and its las update. :rtype: str
339,712
def email_to(self): for field in self.form_fields: if issubclass(fields.CLASSES[field.field_type], forms.EmailField): return self.cleaned_data["field_%s" % field.id] return None
Return the value entered for the first field of type ``forms.EmailField``.
339,713
def update(self, Pi, Tij): r from msmtools import analysis as msmana self._Tij = np.array(Tij) assert msmana.is_transition_matrix(self._Tij), assert self._Tij.shape[0] == self._nstates, self._spectral_decomp_available = False assert ...
r""" Updates the transition matrix and recomputes all derived quantities
339,714
def set_settings(profile, setting, value, store=): if profile.lower() not in (, , ): raise ValueError(.format(profile)) if setting.lower() not in (, , , , ): rais...
Configure firewall settings. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules ...
339,715
def post_save(self): if self.run: self.run = False self.create_tasks() self.save()
can be removed when a proper task manager admin interface implemented
339,716
def get_form_kwargs(self): kwargs = super(FormAcceptsRequestMixin, self).get_form_kwargs() if self.form_accepts_request: kwargs.update({: self.request}) return kwargs
Returns the keyword arguments for instantiating the form.
339,717
def generate_policy_statements(self): statements = self._policy_statements statements.extend( lambda_basic_execution_statements( self.function.Ref() ) ) extended_statements = self.extended_policy_statements() if extended_statements...
Generates the policy statements for the role used by the function. To add additional statements you can either override the `extended_policy_statements` method to return a list of Statements to be added to the policy, or override this method itself if you need more control. Ret...
339,718
def get_target_list(module, action_parameter=None): * exec_output = exec_action(module, , action_parameter=action_parameter) if not exec_output: return None target_list = [] if isinstance(exec_output, list): for item in exec_output: target_list.append(item.split(None, 1)...
List available targets for the given module. module name of the module to be queried for its targets action_parameter additional params passed to the defined action .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' eselect.get_target_list kernel
339,719
def get_dfdx(self): if self._dfdx is True: if self.indep is None: zero = 0*self.be.Dummy()**0 self._dfdx = self.be.Matrix(1, self.ny, [zero]*self.ny) else: self._dfdx = self.be.Matrix(1, self.ny, [expr.diff(self.indep) for expr in ...
Calculates 2nd derivatives of ``self.exprs``
339,720
def viable_source_types (target_type): assert isinstance(target_type, basestring) if target_type not in __viable_source_types_cache: __vst_cached_types.append(target_type) __viable_source_types_cache [target_type] = __viable_source_types_real (target_type) return __viable_source_types_c...
Helper rule, caches the result of '__viable_source_types_real'.
339,721
def _check_nominal_power(self, storage_parameters, timeseries): if storage_parameters.get(, None) is None: try: storage_parameters[] = max(abs(timeseries)) except: raise ValueError("Could not assign a nominal power to the " ...
Tries to assign a nominal power to the storage. Checks if nominal power is provided through `storage_parameters`, otherwise tries to return the absolute maximum of `timeseries`. Raises an error if it cannot assign a nominal power. Parameters ---------- timeseries : :obj...
339,722
def write(file, data, samplerate, subtype=None, endian=None, format=None, closefd=True): import numpy as np data = np.asarray(data) if data.ndim == 1: channels = 1 else: channels = data.shape[1] with SoundFile(file, , samplerate, channels, subtype, e...
Write data to a sound file. .. note:: If `file` exists, it will be truncated and overwritten! Parameters ---------- file : str or int or file-like object The file to write to. See :class:`SoundFile` for details. data : array_like The data to write. Usually two-dimensional (frames...
339,723
def get_base(managed_policy, **conn): managed_policy[] = 1 arn = _get_name_from_structure(managed_policy, ) policy = get_policy(arn, **conn) document = get_managed_policy_document(arn, policy_metadata=policy, **conn) managed_policy.update(policy[]) managed_policy[] = document ma...
Fetch the base Managed Policy. This includes the base policy and the latest version document. :param managed_policy: :param conn: :return:
339,724
def external_incompatibilities(self): if isinstance(self._cause, ConflictCause): cause = self._cause for incompatibility in cause.conflict.external_incompatibilities: yield incompatibility for incompatibility in cause.other.external_incompatibili...
Returns all external incompatibilities in this incompatibility's derivation graph.
339,725
def _run_program(name, *args, **kwargs): shell = kwargs.get("shell", False) return_object = kwargs.get("ro", False) return_object = kwargs.get("return_object", return_object) no_return = kwargs.get("nr", False) no_return = kwargs.get("no_return", no_return) inp = kwargs.get("input", None...
Runs program name with the arguments of *args :param shell: if true, runs the command in the shell :type shell: bool :param return_object: if true, returns a CommandOutput object :type return_object: bool :param ro: same as return_object :type ro: bool :param no_return: doesn't return re...
339,726
def splitPolygon(self, polygon, coplanarFront, coplanarBack, front, back): COPLANAR = 0 FRONT = 1 BACK = 2 SPANNING = 3 polygonType = 0 vertexLocs = [] numVertices = len(polygon.vertices) for i in range(numVertices)...
Split `polygon` by this plane if needed, then put the polygon or polygon fragments in the appropriate lists. Coplanar polygons go into either `coplanarFront` or `coplanarBack` depending on their orientation with respect to this plane. Polygons in front or in back of this plane go into ei...
339,727
def unflatten(guide, falttened_input): return [unflatten(sub_list, falttened_input) if isinstance(sub_list, list) else next(falttened_input) for sub_list in guide]
Unflatten a falttened generator. Args: guide: A guide list to follow the structure falttened_input: A flattened iterator object Usage: guide = [["a"], ["b","c","d"], [["e"]], ["f"]] input_list = [0, 1, 2, 3, 4, 5, 6, 7] unflatten(guide, iter(input_list)) >> [[0...
339,728
def only(iterable, default=None, too_long=None): it = iter(iterable) value = next(it, default) try: next(it) except StopIteration: pass else: raise too_long or ValueError() return value
If *iterable* has only one item, return it. If it has zero items, return *default*. If it has more than one item, raise the exception given by *too_long*, which is ``ValueError`` by default. >>> only([], default='missing') 'missing' >>> only([1]) 1 >>> only([1, 2]) # doctest: +IGNORE_E...
339,729
def validate(self, val): self.validate_type_only(val) self.validate_fields_only(val) return val
For a val to pass validation, val must be of the correct type and have all required fields present.
339,730
def compute_batch_indices(batch_size, beam_size): batch_pos = tf.range(batch_size * beam_size) // beam_size batch_pos = tf.reshape(batch_pos, [batch_size, beam_size]) return batch_pos
Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which batch the beam item is in. This will create the i of the i,j coordinate needed for the gather. Args: batch_size: Batch size beam_size: Size of the beam. Returns...
339,731
def register(request): serializer_class = registration_settings.REGISTER_SERIALIZER_CLASS serializer = serializer_class(data=request.data) serializer.is_valid(raise_exception=True) kwargs = {} if registration_settings.REGISTER_VERIFICATION_ENABLED: verification_flag_field = get_user_s...
Register new user.
339,732
def disable_root(): def enter_password(): password1 = getpass.getpass(prompt=% sudo_user) password2 = getpass.getpass(prompt=) if password1 <> password2: print env.host, enter_password() return password1 (olduser,host,port) = normalize(env.host...
Disables root and creates a new sudo user as specified by HOST_USER in your settings or your host_string The normal pattern for hosting is to get a root account which is then disabled. returns True on success
339,733
def _simple_acronym_detection(s, i, words, *args): acronym = .join(words[s:i]) for _ in xrange(s, i): del words[s] words.insert(s, .join(acronym)) return s
Detect acronyms based on runs of upper-case letters.
339,734
def create_swag_from_ctx(ctx): swag_opts = {} if ctx.type == : swag_opts = { : , : ctx.data_dir, : ctx.data_file } elif ctx.type == : swag_opts = { : , : ctx.bucket_name, : ctx.data_file, : ctx.r...
Creates SWAG client from the current context.
339,735
def predict(self, *args, **kwargs): return super(PmmlModel, self).predict(*args, **kwargs)
Predict given DataFrame using the given model. Actual prediction steps will not be executed till an operational step is called. After execution, three columns will be appended to the table: +-------------------+--------+----------------------------------------------------+ | Field name...
339,736
def _finalize_ticks(self, axis, dimensions, xticks, yticks, zticks): ndims = len(dimensions) if dimensions else 0 xdim = dimensions[0] if ndims else None ydim = dimensions[1] if ndims > 1 else None if xdim: self._set_axis_formatter(axis.xaxis, xdim, self.xf...
Finalizes the ticks on the axes based on the supplied ticks and Elements. Sets the axes position as well as tick positions, labels and fontsize.
339,737
def get_dorefa(bitW, bitA, bitG): def quantize(x, k): n = float(2 ** k - 1) @tf.custom_gradient def _quantize(x): return tf.round(x * n) / n, lambda dy: dy return _quantize(x) def fw(x): if bitW == 32: return x if bitW == 1: ...
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
339,738
def compute_K_analytical(self, spacing): K = redaK.compute_K_analytical(self.data, spacing=spacing) self.data = redaK.apply_K(self.data, K) redafixK.fix_sign_with_K(self.data)
Compute geometrical factors over the homogeneous half-space with a constant electrode spacing
339,739
def add_inote(self, msg, idx, off=None): if self.code != None: self.code.add_inote(msg, idx, off)
Add a message to a specific instruction by using (default) the index of the address if specified :param msg: the message :type msg: string :param idx: index of the instruction (the position in the list of the instruction) :type idx: int :param off: address of...
339,740
def __get_jwks_key(self, jwks_uri, **kwargs): jwks_key = kwargs.pop(, None) if not jwks_key: res = self._session.get(jwks_uri) res.raise_for_status() jwks_key = res.json() self.jwks_key_set = None self.jwks_key = None if in...
Get from jwks_ui all the JWK keys required to decode JWT Token. Parameters ---------- jwks_uri : string The URL where to gather JWKS key kwargs : Dict The constructor parameters
339,741
def self_sign(self, req, receiver=, aud=None): if self.entity_id: _iss = self.entity_id else: _iss = self.iss creq = req.copy() if not in creq and not \ in creq: _copy = creq.copy() _jws = self.self_signer.sign(_...
Sign the extended request. :param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance :param receiver: The intended user of this metadata statement :param aud: The audience, a list of receivers. :return: An augmented set of request arguments
339,742
def import_name(name): if isinstance(name, str): components = name.split() mod = __import__(.join(components[0:-1]), globals(), locals(), [components[-1]] ) return getattr(mod, components[-1]) else: return name
import module given by str or pass the module if it is not str
339,743
def get_context(self, name, value, attrs): context = super(CaptchaTextInput, self).get_context(name, value, attrs) context[] = self.image_url() context[] = self.audio_url() return context
Add captcha specific variables to context.
339,744
def setup_filter(self, ): types = self.refobjinter.types.keys() for i, t in enumerate(types): cb = QtGui.QCheckBox("%s" % t) cb.setChecked(True) cb.toggled.connect(self.update_filter) self.typecbmap[t] = cb self.typefilter_grid.addWidg...
Create a checkbox for every reftrack type so one can filter them :returns: None :rtype: None :raises: None
339,745
def with_json(self, data=None, **params): if isinstance(data, (tuple, list)): data = dict(data) if params: if isinstance(data, dict): data.update(params) elif data is None: data = params else: ...
Add a json body to the request. :param data: A json string, a dict, or a list of key, value pairs :param params: A dict of key value pairs to JSON encode
339,746
def path(self, which=None): base = urljoin( self._server_config.url + , self._meta[] ) if (which == or which is None) and hasattr(self, ): return urljoin(base + , str(self.upload_id)) return super(ContentUpload, self).path(whic...
Extend ``nailgun.entity_mixins.Entity.path``.
339,747
def to_unicode(path, errors="replace"): if isinstance(path, UNICODE): return path return path.decode(sys.getfilesystemencoding(), errors)
Given a bytestring/unicode path, return it as unicode.
339,748
def loads(s, filename=None, loader=None, implicit_tuple=True, env={}, schema=None): ast = reads(s, filename=filename, loader=loader, implicit_tuple=implicit_tuple) if not isinstance(env, framework.Environment): env = framework.Environment(dict(_default_bindings, **env)) obj = framework.eval(ast, ...
Load and evaluate a GCL expression from a string.
339,749
def verify(self) -> None: if not self.anns: self._toy2ann.clear() raise RuntimeError( % (self.name, objecttools.devicename(self))) for toy, ann_ in self: ann_.verify() ...
Raise a |RuntimeError| and removes all handled neural networks, if the they are defined inconsistently. Dispite all automated safety checks explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.Season...
339,750
def set_mkl_thread_limit(cores): if "linux" in sys.platform: mkl_rt = ctypes.CDLL() else: mkl_rt = ctypes.CDLL() oldlimit = mkl_rt.mkl_get_max_threads() mkl_rt.mkl_set_num_threads(ctypes.byref(ctypes.c_int(cores))) return oldlimit
set mkl thread limit and return old value so we can reset when finished.
339,751
def load_pos_model(lang="en", version="2"): src_dir = "pos{}".format(version) p = locate_resource(src_dir, lang) fh = _open(p) return dict(np.load(fh))
Return a part of speech tagger parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used.
339,752
def from_dict(self, d): if in d: if d[]: self._uid = d[] if in d: if d[]: self._name = d[] if in d: if isinstance(d[], str) or isinstance(d[], unicode): if d[] in states._pipeline_state_values.keys...
Create a Pipeline from a dictionary. The change is in inplace. :argument: python dictionary :return: None
339,753
def from_text(self, line, line_index, column, is_escaped): begin = self._begin end = self._end single = self._single single_len = len(single) start_len = len(begin) if _token_at_col_in_line(line, column, single, single_len): return (STATE_IN_COMMENT...
Return the new state of the comment parser.
339,754
def exact_sqrt(n2): "If n2 is a perfect square, return its square root, else raise error." n = int(math.sqrt(n2)) assert n * n == n2 return n
If n2 is a perfect square, return its square root, else raise error.
339,755
def onPollVoted( self, mid=None, poll=None, added_options=None, removed_options=None, author_id=None, thread_id=None, thread_type=None, ts=None, metadata=None, msg=None, ): log.info( "{} voted in pol...
Called when the client is listening, and somebody votes in a group poll :param mid: The action ID :param poll: Poll, that user voted in :param author_id: The ID of the person who voted in the poll :param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads` ...
339,756
def dump(recid, from_date, with_json=False, latest_only=False, with_collections=False, **kwargs): if latest_only: revision_iter = [get_record_revisions(recid, from_date)[-1]] else: revision_iter = get_record_revisions(recid, from_date) ...
Dump MARCXML and JSON representation of a record. :param recid: Record identifier :param from_date: Dump only revisions from this date onwards. :param with_json: If ``True`` use old ``Record.create`` to generate the JSON representation of the record. :param latest_only: Dump only the last revis...
339,757
def write(filename, mesh, write_binary=False): assert not write_binary if mesh.points.shape[1] == 2: logging.warning( "mdpa requires 3D points, but 2D points given. " "Appending 0 third component." ) mesh.points = numpy.column_stack( [mesh.points[...
Writes mdpa files, cf. <https://github.com/KratosMultiphysics/Kratos/wiki/Input-data>.
339,758
def validate_arguments(self, view_class, kwargs): if not issubclass(view_class, View): raise PopupViewIsNotSubclassView() self.view_class_name = view_class.__name__ self.popup_dialog_title = kwargs.pop("popup_dialog_title", _("Popup Dialog: Select value")) ...
view_class : View Class used to render content popup dialog view_class must be subclass of django.views.generic.View
339,759
def _parse_signal_lines(signal_lines): n_sig = len(signal_lines) signal_fields = {} for field in SIGNAL_SPECS.index: signal_fields[field] = n_sig * [None] for ch in range(n_sig): (signal_fields[][ch], signal_fields[][ch], signal_fields[][ch], signal_fields[...
Extract fields from a list of signal line strings into a dictionary.
339,760
def kick_chat_member( self, chat_id: Union[int, str], user_id: Union[int, str], until_date: int = 0 ) -> Union["pyrogram.Message", bool]: chat_peer = self.resolve_peer(chat_id) user_peer = self.resolve_peer(user_id) if isinstance(chat_peer, types.Inp...
Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. You must be an administrator in the chat for this to work and must have ...
339,761
def changelog(ctx, check, version, old_version, initial, quiet, dry_run): if check not in get_valid_checks(): abort(.format(check)) cur_version = old_version or get_version_string(check) if parse_version_info(version) <= parse_version_info(cur_version): abort(.format(cur_version, ...
Perform the operations needed to update the changelog. This method is supposed to be used by other tasks and not directly.
339,762
def default_model(): project_root = get_project_root() models_dir = os.path.join(project_root, "models") curr_dir = os.getcwd() if os.path.commonprefix([models_dir, curr_dir]) == models_dir and \ curr_dir != models_dir: latest_model = curr_dir else: latest_model = get_lat...
Get a path for a default value for the model. Start searching in the current directory.
339,763
def hold(name=None, pkgs=None, **kwargs): **["foo", "bar"] targets = [] if pkgs: targets.extend(pkgs) else: targets.append(name) ret = {} for target in targets: if isinstance(target, dict): target = next(six.iterkeys(target)) ret[target] = {: targe...
Version-lock packages .. note:: This function is provided primarily for compatibilty with some parts of :py:mod:`states.pkg <salt.states.pkg>`. Consider using Consider using :py:func:`pkg.lock <salt.modules.pkgng.lock>` instead. instead. name The name of the package to be held....
339,764
def _process_comparison_filter_directive(filter_operation_info, location, context, parameters, operator=None): comparison_operators = {u, u, u, u, u, u} if operator not in comparison_operators: raise AssertionError(u u.format(com...
Return a Filter basic block that performs the given comparison against the property field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this fi...
339,765
def _print_lines(self, lines, start, breaks=(), frame=None): if frame: current_lineno = frame.f_lineno exc_lineno = self.tb_lineno.get(frame, -1) else: current_lineno = exc_lineno = -1 for lineno, line in enumerate(lines, start): s = str(l...
Print a range of lines.
339,766
def dfs_do_func_on_graph(node, func, *args, **kwargs): for _node in node.tree_iterator(): func(_node, *args, **kwargs)
invoke func on each node of the dr graph
339,767
def _py2java(sc, obj): if isinstance(obj, RDD): obj = _to_java_object_rdd(obj) elif isinstance(obj, DataFrame): obj = obj._jdf elif isinstance(obj, SparkContext): obj = obj._jsc elif isinstance(obj, list): obj = [_py2java(sc, x) for x in obj] elif isinstance(obj,...
Convert Python object into Java
339,768
def value(self): if not self.is_value_set: raise MeasurementNotSetError(, self.name) return [dimensions + (value,) for dimensions, value in six.iteritems(self.value_dict)]
The values stored in this record. Returns: A list of tuples; the last element of each tuple will be the measured value, the other elements will be the associated coordinates. The tuples are output in the order in which they were set.
339,769
def run(self, deployments=None, command=): if deployments is None: deployments = self.runway_config[] context = Context(env_name=get_env(self.env_root, self.runway_config.get(, False)), env_region=None, ...
Execute apps/code command.
339,770
def chk_associations(self, fout_err="gaf.err"): obj = GafData("2.1") return obj.chk(self.associations, fout_err)
Check that fields are legal in GAF
339,771
def group_plugins_into_categories(plugins): if not plugins: return {} plugins = sorted(plugins, key=lambda p: p.verbose_name) categories = {} for plugin in plugins: title = str(plugin.category or u"") if title not in categories: categories[title] = [] ...
Return all plugins, grouped by category. The structure is a {"Categorynane": [list of plugin classes]}
339,772
def get_one(self, fields=list()): response = self.session.get(self._get_table_url(), params=self._get_formatted_query(fields, limit=None, order_by=list(), offset=None)) content = self._get_content(response) l = len(content) if l > 1: ...
Convenience function for queries returning only one result. Validates response before returning. :param fields: List of fields to return in the result :raise: :MultipleResults: if more than one match is found :return: - Record content
339,773
def _parse_request(self, xml): for node in xml.xpath(".//ti:groupname", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.groupname, lang=lang, value=node.text) self.set_creator(node.text, lang) ...
Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element]
339,774
def setUncertainty(self, unc): if self.isAboveUpperDetectionLimit() or \ self.isBelowLowerDetectionLimit(): self.getField().set(self, None) else: self.getField().set(self, unc)
Sets the uncertainty for this analysis. If the result is a Detection Limit or the value is below LDL or upper UDL, sets the uncertainty value to 0
339,775
def add_route(self, router, index=None): assert isinstance(router, Router), assert router is not self, for r in self.routes: if r == router: return r elif r._route == router._route: raise ValueError( % ...
Add a new :class:`Router` to the :attr:`routes` list.
339,776
def snapshot_peek_number( fd, off ): fd.seek( off - 8, os.SEEK_SET ) value_hex = fd.read(8) if len(value_hex) != 8: return None try: value = int(value_hex, 16) except ValueError: return None return value
Read the last 8 bytes of fd and interpret it as an int.
339,777
def get_object(self, **kwargs): if hasattr(self, ) and self.object: return self.object obj = super(CommonSingleObjectViewMixin, self).get_object(**kwargs) self.object = obj return obj
Sometimes preprocessing of a view need to happen before the object attribute has been set for a view. In this case, just return the object if it has already been set when it's called down the road since there's no need to make another query.
339,778
def lookup(self, request: Request) -> List[Callable[[], Handler]]: key = request.__class__.__name__ if key not in self._registry: if request.is_command(): raise ConfigurationException("There is no handler registered for this request") elif request.is_even...
Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return:
339,779
def decode(self, tx): if not isinstance(self._service, BitcoinBlockrService): raise NotImplementedError() return self._service.decode(tx)
Decodes the given transaction. Args: tx: hex of transaction Returns: decoded transaction .. note:: Only supported for blockr.io at the moment.
339,780
def fit(self, method=, iterlim=1000, tol=.0001, verbose=0, no_callback=False, **kwargs): self.tol = tol self.method = method self.verbose = verbose p = zeros(self.len, dtype=float) for stochastic in self.stochastics: p[self._slices[stochastic]] =...
N.fit(method='fmin_powell', iterlim=1000, tol=.001): Causes the normal approximation object to fit itself. method: May be one of the following, from the scipy.optimize package: -fmin_l_bfgs_b -fmin_ncg -fmin_cg -fmin_powell -fmin no_...
339,781
def grok_vars(elements): default_vars = [] iterbody = None if hasattr(elements, ): iterbody = elements.body elif hasattr(elements, ): iterbody = elements.nodes for element in iterbody: if isinstance(element, jinja2.nodes.Output): default_vars = default_vars ...
Returns a list of vars for which the value is being appropriately set This currently includes the default filter, for-based iterators, and the explicit use of set
339,782
def send_mass_mail( datatuple, fail_silently=False, auth_user=None, auth_password=None ): connection = SMTPConnection( username=auth_user, password=auth_password, fail_silently=fail_silently ) messages = [ EmailMessage(subject, message, sender, recipient) for subjec...
Send multiple emails to multiple recipients. Given a datatuple of (subject, message, sender, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent. If auth_user and auth_password are set, they're used to log in. Note: The API for this method is frozen. ...
339,783
def done(message): def done(value, _context, **_params): return Done(value, message) return done
Create a Deleted response builder with specified message.
339,784
def expr(self, callback): nodes = [] for node in self.nodes: if callback(node): nodes.append(node) self.nodes = nodes return self
Filter by custom expression. :param callback: Callback for custom expression. :type name: ``function`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node`
339,785
def is_protected_type(obj): return isinstance(obj, ( types.NoneType, int, long, datetime.datetime, datetime.date, datetime.time, float, Decimal) )
Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_unicode(strings_only=True).
339,786
def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep...
Show Popup box and immediately return (does not block) :param args: :param button_type: :param button_color: :param background_color: :param text_color: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param font: :param...
339,787
def _is_at_qry_start(self, nucmer_hit): hit_coords = nucmer_hit.qry_coords() return hit_coords.start < self.qry_end_tolerance
Returns True iff the hit is "close enough" to the start of the query sequence
339,788
def serve_dir(dir_path): print() created_files = _create_index_files(dir_path, True) if (PIL_ENABLED): print() background_indexer = BackgroundIndexFileGenerator(dir_path) background_indexer.run() _clean_up(created_files)
Generate indexes and run server from the given directory downwards. @param {String} dir_path - The directory path (absolute, or relative to CWD) @return {None}
339,789
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: return self._get_argument(name, default, self.request.query_arguments, strip)
Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the l...
339,790
def change_status(self, status): def cb(): self.user.update(status=status) return status return signals.user_update(self, ACTIONS["STATUS"], cb, data={"status": self.status})
Change the user's status :param user: :param email: :return:
339,791
def sizes(args): p = OptionParser(sizes.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bedfile, = args assert op.exists(bedfile) sizesfile = bedfile.rsplit(".", 1)[0] + ".sizes" fw = must_open(sizesfile, "w", checkexists=True, skipch...
%prog sizes bedfile Infer the sizes for each seqid. Useful before dot plots.
339,792
def fromdict(dict): key = hb_decode(dict[]) check_fraction = dict[] return Merkle(check_fraction, key)
Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert
339,793
def set_target(self, target, ctx=None): if target is not None: if is_intercepted(target): self._interception = target self.target, self.ctx = get_intercepted(target) else: ...
Set target. :param target: new target to use. :param target ctx: target ctx if target is an class/instance attribute.
339,794
def trim_trailing_silence(self): length = self.get_active_length() self.pianoroll = self.pianoroll[:length]
Trim the trailing silence of the pianoroll.
339,795
def send(self, stack: Layers): if not isinstance(stack, Stack): stack = Stack(stack) if in self._update and stack.has_layer(Update): layer = stack.get_layer(Update) try: msg = self._update[][] except KeyError: l...
Intercept any potential "AnswerCallbackQuery" before adding the stack to the output buffer.
339,796
def build(self, builder, formname=None): params = dict(ItemGroupOID=formname if formname else self.itemgroupoid) if self.transaction_type is not None: params["TransactionType"] = self.transaction_type if self.item_group_repeat_key is not None: params["ItemGrou...
Build XML by appending to builder
339,797
def encode(self, vecs): assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert D == self.Ds * self.M, "input dimension must be Ds * M" codes = np.empty((N, self.M), dtype=self.code_dtype) for m in range(self.M): if se...
Encode input vectors into PQ-codes. Args: vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32. Returns: np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype
339,798
def update_address_scope(self, address_scope, body=None): return self.put(self.address_scope_path % (address_scope), body=body)
Updates a address scope.
339,799
def _new_session(retry_timeout_config): retry = requests.packages.urllib3.Retry( total=None, connect=retry_timeout_config.connect_retries, read=retry_timeout_config.read_retries, method_whitelist=retry_timeout_config.method_whitelist, redirect...
Return a new `requests.Session` object.