Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
3,000
def list_taxa(pdb_list, sleep_time=.1): crisprThermus thermophilusSulfolobus solfataricus P2Hyperthermus butylicus DSM 5456unidentified phageSulfolobus solfataricus P2Pseudomonas aeruginosa UCBPP-PA14Pseudomonas aeruginosa UCBPP-PA14Pseudomonas aeruginosa UCBPP-PA14Sulfolobus solfataricusThermus thermophilus HB8 ...
Given a list of PDB IDs, look up their associated species This function digs through the search results returned by the get_all_info() function and returns any information on taxonomy included within the description. The PDB website description of each entry includes the name of the species (and s...
3,001
def _get_tmp_gcs_bucket(cls, writer_spec): if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec[cls.TMP_BUCKET_NAME_PARAM] return cls._get_gcs_bucket(writer_spec)
Returns bucket used for writing tmp files.
3,002
def pow(base, exp): if isinstance(base, Symbol) and isinstance(exp, Symbol): return _internal._Power(base, exp) if isinstance(base, Symbol) and isinstance(exp, Number): return _internal._PowerScalar(base, scalar=exp) if isinstance(base, Number) and isinstance(exp, Symbol): retur...
Returns element-wise result of base element raised to powers from exp element. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Use `broadcast_pow` instead. `sym.pow` is being deprecated, please use `sym.power` instead. Parameters --------- base : Symbol or scalar ...
3,003
def dropEvent(self, event): data = event.mimeData() if data.hasFormat() and \ data.hasFormat(): tableName = self.tableTypeName() if nstr(data.data()) == tableName: data = nstr(data.data()) query = Q.fromXmlStrin...
Listens for query's being dragged and dropped onto this tree. :param event | <QDropEvent>
3,004
def describe_numeric_1d(series, **kwargs): _percentile_format = "{:.0%}" stats = dict() stats[] = base.TYPE_NUM stats[] = series.mean() stats[] = series.std() stats[] = series.var() stats[] = series.min() stats[] = series.max() stats[] = stats[] - stats[] _series_n...
Compute summary statistics of a numerical (`TYPE_NUM`) variable (a Series). Also create histograms (mini an full) of its distribution. Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with in...
3,005
def to_dict(self): list_data = [] for key, value in list(self.data.items()): row = list(key) row.append(value) list_data.append(row) return { : self.groups, : list_data }
Return common list python object. :returns: Dictionary of groups and data :rtype: dict
3,006
def mptt_before_update(mapper, connection, instance): node_id = getattr(instance, instance.get_pk_name()) table = _get_tree_table(mapper) db_pk = instance.get_pk_column() default_level = instance.get_default_level() table_pk = getattr(table.c, db_pk.name) mptt_move_inside = None left_si...
Based on this example: http://stackoverflow.com/questions/889527/move-node-in-nested-set
3,007
def pad_sequence_to_length(sequence: List, desired_length: int, default_value: Callable[[], Any] = lambda: 0, padding_on_right: bool = True) -> List: if padding_on_right: padded_sequence = sequence[:desired_length] ...
Take a list of objects and pads it to the desired length, returning the padded list. The original list is not modified. Parameters ---------- sequence : List A list of objects to be padded. desired_length : int Maximum length of each sequence. Longer sequences are truncated to thi...
3,008
def _add_devices_from_config(args): config = _parse_config(args.config) for device in config[]: if args.default: if device == "default": raise ValueError() if config[][device][] == args.default: raise ValueError() add(device, config[][...
Add devices from config.
3,009
def get_time(self): if isinstance(self.path, pathlib.Path): thetime = self.path.stat().st_mtime else: thetime = np.nan return thetime
Time of the TIFF file Currently, only the file modification time is supported. Note that the modification time of the TIFF file is dependent on the file system and may have temporal resolution as low as 3 seconds.
3,010
def where(self, where: str) -> : sd = SASdata(self.sas, self.libref, self.table, dsopts=dict(self.dsopts)) sd.HTML = self.HTML sd.dsopts[] = where return sd
This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object
3,011
def reassign(self, user_ids, requester): path = .format(self.collection.name) assignments = [] if not user_ids: raise Error() for user_id in user_ids: ref = { "assignee": { "id": user_id, "type": "us...
Reassign this incident to a user or list of users :param user_ids: A non-empty list of user ids :param requester: The email address of individual requesting reassign
3,012
def Ctrl_c(self, dl = 0): self.Delay(dl) self.keyboard.press_key(self.keyboard.control_key) self.keyboard.tap_key("c") self.keyboard.release_key(self.keyboard.control_key)
Ctrl + c 复制
3,013
def API_GET(self, courseid=None): output = [] if courseid is None: courses = self.course_factory.get_all_courses() else: try: courses = {courseid: self.course_factory.get_course(courseid)} except: raise APINotFound("...
List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if t...
3,014
def get_path(self, temp_ver): if temp_ver not in self: raise RuntimeError( .format(temp_ver.name) ) return self._prefixed(temp_ver.name)
Get the path of the given version in this store Args: temp_ver TemplateVersion: version to look for Returns: str: The path to the template version inside the store Raises: RuntimeError: if the template is not in the store
3,015
def get_current_qualification_score(self, name, worker_id): qtype = self.get_qualification_type_by_name(name) if qtype is None: raise QualificationNotFoundException( .format(name) ) try: score = self.get_qualification_score(qtype["id"]...
Return the current score for a worker, on a qualification with the provided name.
3,016
def _is_prime(bit_size, n): r = 0 s = n - 1 while s % 2 == 0: r += 1 s //= 2 if bit_size >= 1300: k = 2 elif bit_size >= 850: k = 3 elif bit_size >= 650: k = 4 elif bit_size >= 550: k = 5 elif bit_size >= 450: k = 6 for ...
An implementation of Miller–Rabin for checking if a number is prime. :param bit_size: An integer of the number of bits in the prime number :param n: An integer, the prime number :return: A boolean
3,017
def remove_gaps(A, B): a_seq, b_seq = [], [] for a, b in zip(list(A), list(B)): if a == or a == or b == or b == : continue a_seq.append(a) b_seq.append(b) return .join(a_seq), .join(b_seq)
skip column if either is a gap
3,018
def get_table_cache_key(db_alias, table): cache_key = % (db_alias, table) return sha1(cache_key.encode()).hexdigest()
Generates a cache key from a SQL table. :arg db_alias: Alias of the used database :type db_alias: str or unicode :arg table: Name of the SQL table :type table: str or unicode :return: A cache key :rtype: int
3,019
def domain_search(auth=None, **kwargs): ** cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.search_domains(**kwargs)
Search domains CLI Example: .. code-block:: bash salt '*' keystoneng.domain_search salt '*' keystoneng.domain_search name=domain1
3,020
def add_update_user(self, user, capacity=None): if isinstance(user, str): user = hdx.data.user.User.read_from_hdx(user, configuration=self.configuration) elif isinstance(user, dict): user = hdx.data.user.User(user, configuration=self.configuration) if is...
Add new or update existing user in organization with new metadata. Capacity eg. member, admin must be supplied either within the User object or dictionary or using the capacity argument (which takes precedence). Args: user (Union[User,Dict,str]): Either a user id or user metadata ei...
3,021
def scale_vmss(access_token, subscription_id, resource_group, vmss_name, capacity): endpoint = .join([get_rm_endpoint(), , subscription_id, , resource_group, , vmss_name, , COMP_API]) body = + str(capacity) + ...
Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. capacit...
3,022
def parse_env(envlist): if not isinstance(envlist, list): envlist = [envlist] exports = [] for env in envlist: pieces = re.split("( |\\\".*?\\\"|)", env) pieces = [p for p in pieces if p.strip()] while len(pieces) > 0: current = pieces.pop(0) ...
parse_env will parse a single line (with prefix like ENV removed) to a list of commands in the format KEY=VALUE For example: ENV PYTHONBUFFER 1 --> [PYTHONBUFFER=1] ::Notes Docker: https://docs.docker.com/engine/reference/builder/#env
3,023
def ready(self): models_config.auto_load_configs() self.auto_load_app_modules([, ]) app_menu.auto_load_model_menu() auto_register_search_models() tabs.auto_generate_missing_tabs()
Auto load Trionyx
3,024
def check_key(self, key, raise_error=True, *args, **kwargs): return check_key( key, possible_keys=list(self), raise_error=raise_error, name=, *args, **kwargs)
Checks whether the key is a valid formatoption Parameters ---------- %(check_key.parameters.no_possible_keys|name)s Returns ------- %(check_key.returns)s Raises ------ %(check_key.raises)s
3,025
def relpath_to_modname(relpath):
Convert relative path to module name Within a project, a path to the source file is uniquely identified with a module name. Relative paths of the form 'foo/bar' are *not* converted to module names 'foo.bar', because (1) they identify directories, not regular files, and (2) already 'foo/bar/__init__.py'...
3,026
def cosine_similarity(sent1: str, sent2: str) -> float: WORD = re.compile(r) def get_cosine(vec1, vec2): intersection = set(vec1.keys()) & set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in intersection]) sum1 = sum([vec1[x]**2 for x in vec1.keys()]) sum2 = sum([...
Calculates cosine similarity between 2 sentences/documents. Thanks to @vpekar, see http://goo.gl/ykibJY
3,027
def _create_tag_lowlevel(self, tag_name, message=None, force=True, patch=False): tags = self.get_tags(patch=patch) old_commit = tags.get(ta...
Create a tag on the toplevel or patch repo If the tag exists, and force is False, no tag is made. If force is True, and a tag exists, but it is a direct ancestor of the current commit, and there is no difference in filestate between the current commit and the tagged commit, no tag is ma...
3,028
def save_series(self) -> None: hydpy.pub.sequencemanager.open_netcdf_writer( flatten=hydpy.pub.options.flattennetcdf, isolate=hydpy.pub.options.isolatenetcdf) self.prepare_sequencemanager() for sequence in self._iterate_sequences(): sequence.save_ext(...
Save time series data as defined by the actual XML `writer` element. >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> from hydpy import HydPy, TestIO, XMLInterface >>> hp = HydPy('LahnH') >>> with TestIO(): ... hp.p...
3,029
def endpoint_delete(auth=None, **kwargs): * cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.delete_endpoint(**kwargs)
Delete an endpoint CLI Example: .. code-block:: bash salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9
3,030
def plot_options(cls, obj, percent_size): from .plot import MPLPlot factor = percent_size / 100.0 obj = obj.last if isinstance(obj, HoloMap) else obj options = Store.lookup_options(cls.backend, obj, ).options fig_size = options.get(, MPLPlot.fig_size)*factor ret...
Given a holoviews object and a percentage size, apply heuristics to compute a suitable figure size. For instance, scaling layouts and grids linearly can result in unwieldy figure sizes when there are a large number of elements. As ad hoc heuristics are used, this functionality is kept se...
3,031
def handle_signature(self, sig, signode): if self._is_attr_like(): sig_match = chpl_attr_sig_pattern.match(sig) if sig_match is None: raise ValueError(.format(sig)) func_prefix, name_prefix, name, retann = sig_match.groups() arglist = None...
Parse the signature *sig* into individual nodes and append them to the *signode*. If ValueError is raises, parsing is aborted and the whole *sig* string is put into a single desc_name node. The return value is the value that identifies the object. IOW, it is the identifier that will be ...
3,032
def reindex_like(self, other, method=None, copy=True, limit=None, tolerance=None): d = other._construct_axes_dict(axes=self._AXIS_ORDERS, method=method, copy=copy, limit=limit, tolerance=tolerance) ...
Return an object with matching indices as other object. Conform the object to the same index on all axes. Optional filling logic, placing NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False...
3,033
def find_ent_space_price(package, category, size, tier_level): if category == : category_code = elif category == : category_code = else: category_code = level = ENDURANCE_TIERS.get(tier_level) for item in package[]: if int(item[]) != size: cont...
Find the space price for the given category, size, and tier :param package: The Enterprise (Endurance) product package :param category: The category of space (endurance, replication, snapshot) :param size: The size for which a price is desired :param tier_level: The endurance tier for which a price is ...
3,034
def fromXml(cls, elem): if elem is None: return None addon = cls.byName(elem.tag) if not addon: raise RuntimeError(.format(elem.tag)) return addon.load(elem)
Converts the inputted element to a Python object by looking through the IO addons for the element's tag. :param elem | <xml.etree.ElementTree.Element> :return <variant>
3,035
def mtr_tr_dense(sz): n = 2 ** sz hparams = mtf_bitransformer_base() hparams.d_model = 1024 hparams.max_length = 256 hparams.batch_size = 128 hparams.d_ff = int(4096 * n) hparams.d_kv = 128 hparams.encoder_num_heads = int(8 * n) hparams.decoder_num_heads = int(8 * n) hparams.learning_rate_deca...
Series of machine translation models. All models are trained on sequences of 256 tokens. You can use the dataset translate_enfr_wmt32k_packed. 154000 steps = 3 epochs. Args: sz: an integer Returns: a hparams
3,036
def distance_to_closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union[int, float]: assert ps closest_distance_squared = math.inf for p2 in ps: if not isinstance(p2, Point2): p2 = p2.position distance = (self[0] - p2[0]) ** 2 + ...
This function assumes the 2d distance is meant
3,037
def metrics(self): masterThrp, backupThrp = self.getThroughputs(self.instances.masterId) r = self.instance_throughput_ratio(self.instances.masterId) m = [ ("{} Monitor metrics:".format(self), None), ("Delta", self.Delta), ("Lambda", self.Lambda), ...
Calculate and return the metrics.
3,038
def set_dash(self, dashes, offset=0): cairo.cairo_set_dash( self._pointer, ffi.new(, dashes), len(dashes), offset) self._check_status()
Sets the dash pattern to be used by :meth:`stroke`. A dash pattern is specified by dashes, a list of positive values. Each value provides the length of alternate "on" and "off" portions of the stroke. :obj:`offset` specifies an offset into the pattern at which the stroke begins. ...
3,039
def search_cloud_integration_deleted_for_facet(self, facet, **kwargs): kwargs[] = True if kwargs.get(): return self.search_cloud_integration_deleted_for_facet_with_http_info(facet, **kwargs) else: (data) = self.search_cloud_integration_deleted_for_facet_with_...
Lists the values of a specific facet over the customer's deleted cloud integrations # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_cloud_integration_deleted_fo...
3,040
def add_permission(self, name): perm = self.find_permission(name) if perm is None: try: perm = self.permission_model(name=name) perm.save() return perm except Exception as e: log.error(c.LOGMSG_ERR_SEC_ADD_P...
Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
3,041
def zeros_coefs(nmax, mmax, coef_type=scalar): if(mmax > nmax): raise ValueError(err_msg[]) if(coef_type == scalar): L = (nmax + 1) + mmax * (2 * nmax - mmax + 1) vec = np.zeros(L, dtype=np.complex128) return ScalarCoefs(vec, nmax, mmax) elif(coef_type == ve...
Returns a ScalarCoefs object or a VectorCoeffs object where each of the coefficients is set to 0. The structure is such that *nmax* is th largest *n* can be in c[n, m], and *mmax* is the largest *m* can be for any *n*. (See *ScalarCoefs* and *VectorCoefs* for details.) Examples:: ...
3,042
def xmoe_2d(): hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, 4] return hparams
Two-dimensional hierarchical mixture of 16 experts.
3,043
def constraint_present(name, constraint_id, constraint_type, constraint_options=None, cibname=None): addvip_galerawithhaproxy-clone return _item_present(name=name, item=, item_id=constraint_id, item_type=constraint_type, ...
Ensure that a constraint is created Should be run on one cluster node only (there may be races) Can only be run on a node with a functional pacemaker/corosync name Irrelevant, not used (recommended: {{formulaname}}__constraint_present_{{constraint_id}}) constraint_id name for the c...
3,044
def bezier(self, points): coordinates = pgmagick.CoordinateList() for point in points: x, y = float(point[0]), float(point[1]) coordinates.append(pgmagick.Coordinate(x, y)) self.drawer.append(pgmagick.DrawableBezier(coordinates))
Draw a Bezier-curve. :param points: ex.) ((5, 5), (6, 6), (7, 7)) :type points: list
3,045
def delete(self, refobj): refobjinter = self.get_refobjinter() reference = refobjinter.get_reference(refobj) if reference: fullns = cmds.referenceQuery(reference, namespace=True) cmds.file(removeReference=True, referenceNode=reference) else: p...
Delete the content of the given refobj :param refobj: the refobj that represents the content that should be deleted :type refobj: refobj :returns: None :rtype: None :raises: None
3,046
def ebrisk(rupgetter, srcfilter, param, monitor): riskmodel = param[] E = rupgetter.num_events L = len(riskmodel.lti) N = len(srcfilter.sitecol.complete) e1 = rupgetter.first_event with monitor(, measuremem=False): with datastore.read(srcfilter.filename) as dstore: asset...
:param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: an ArrayWrapper with shape (E, L, T, ...)
3,047
def _get_seal_key_ntlm2(negotiate_flags, exported_session_key, magic_constant): if negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_128: seal_key = exported_session_key elif negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_56: seal_key = exported_session_key[:7] else: seal_k...
3.4.5.3 SEALKEY Calculates the seal_key used to seal (encrypt) messages. This for authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_128 is not negotiated, will try NEGOTIATE_56 and then will default to the 40-bit key @para...
3,048
def _stop_trial(self, trial, error=False, error_msg=None, stop_logger=True): if stop_logger: trial.close_logger() if error: self.set_status(trial, Trial.ERROR) else: self.set_status(trial, Trial.TERMINATED) try: ...
Stops this trial. Stops this trial, releasing all allocating resources. If stopping the trial fails, the run will be marked as terminated in error, but no exception will be thrown. Args: error (bool): Whether to mark this trial as terminated in error. error_msg ...
3,049
def p_factor_unary_operators(self, p): p[0] = p[2] if p[1] == : p[0] = Instruction(, context={: p[0]})
term : SUB factor | ADD factor
3,050
def prep_cwl(samples, workflow_fn, out_dir, out_file, integrations=None, add_container_tag=None): if add_container_tag is None: container_tags = None elif add_container_tag.lower() == "quay_lookup": container_tags = {} else: container_tags = collections.defaultdict(...
Output a CWL description with sub-workflows and steps.
3,051
def charge_parent(self, mol, skip_standardize=False): if not skip_standardize: mol = self.standardize(mol) fragment = self.fragment_parent(mol, skip_standardize=True) if fragment: uncharged = self.uncharge(fragment) uncharged = s...
Return the charge parent of a given molecule. The charge parent is the uncharged version of the fragment parent. :param mol: The input molecule. :type mol: rdkit.Chem.rdchem.Mol :param bool skip_standardize: Set to True if mol has already been standardized. :returns: The charge...
3,052
def check_expected_infos(self, test_method): f = lambda key, default=[]: getattr(test_method, key, default) expected_info_messages = f(EXPECTED_INFO_MESSAGES) allowed_info_messages = f(ALLOWED_INFO_MESSAGES) self.check_infos(expected_info_messages, allowed_info_messages)
This method is called after each test. It will read decorated informations and check if there are expected infos. You can set expected infos by decorators :py:func:`.expected_info_messages` and :py:func:`.allowed_info_messages`.
3,053
def server_add(s_name, s_ip, s_state=None, **connection_args): *serverNameserverIpAddress*serverNameserverIpAddressserverState ret = True if server_exists(s_name, **connection_args): return False nitro = _connect(**connection_args) if nitro is None: return False server = NSServer...
Add a server Note: The default server state is ENABLED CLI Example: .. code-block:: bash salt '*' netscaler.server_add 'serverName' 'serverIpAddress' salt '*' netscaler.server_add 'serverName' 'serverIpAddress' 'serverState'
3,054
def _set_tcp_keepalive(sock, opts): if hasattr(socket, ): if opts.get(, False): sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if hasattr(socket, ): if hasattr(socket, ): tcp_keepalive_idle = opts.get(, -1) if t...
Ensure that TCP keepalives are set for the socket.
3,055
def validation_step(self, Xi, yi, **fit_params): self.module_.eval() with torch.no_grad(): y_pred = self.infer(Xi, **fit_params) loss = self.get_loss(y_pred, yi, X=Xi, training=False) return { : loss, : y_pred, }
Perform a forward step using batched data and return the resulting loss. The module is set to be in evaluation mode (e.g. dropout is not applied). Parameters ---------- Xi : input data A batch of the input data. yi : target data A batch of t...
3,056
def combine_dictionaries(a, b): c = {} for key in list(b.keys()): c[key]=b[key] for key in list(a.keys()): c[key]=a[key] return c
returns the combined dictionary. a's values preferentially chosen
3,057
def request_generic(self, act, coro, perform, complete): overlapped = OVERLAPPED() overlapped.object = act self.add_token(act, coro, (overlapped, perform, complete)) rc, nbytes = perform(act, overlapped) completion_key = c_long(0) if rc == 0: ...
Performs an overlapped request (via `perform` callable) and saves the token and the (`overlapped`, `perform`, `complete`) trio.
3,058
def compute_absolute_error(self, predicted_data, record, dataframe_record): absolute_error = abs(record[] - predicted_data[self.ddg_analysis_type]) dataframe_record[] = absolute_error
Calculate the absolute error for this case.
3,059
def teleport(self, agent_name, location=None, rotation=None): self.agents[agent_name].teleport(location * 100, rotation) self.tick()
Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't t...
3,060
def close(self): project_nodes_id = set([n.id for n in self.nodes]) for module in self.compute(): module_nodes_id = set([n.id for n in module.instance().nodes]) if len(module_nodes_id & project_nodes_id): yield from module.instance().projec...
Closes the project, but keep information on disk
3,061
def __clear_buffer_watch(self, bw): pid = bw.pid start = bw.start end = bw.end base = MemoryAddresses.align_address_to_page_start(start) limit = MemoryAddresses.align_address_to_page_end(end) pages = MemoryAddresses.get_buffer_size_in_pag...
Used by L{dont_watch_buffer} and L{dont_stalk_buffer}. @type bw: L{BufferWatch} @param bw: Buffer watch identifier.
3,062
def get_roles(self): if self.role.exist: return [self.role] else: roles = [] if self.role_query_code: roles = RoleModel.objects.filter(**self.role_query_code) elif self.unit.exist: ...
Returns: Role instances according to task definition.
3,063
def list_pr_comments(repo: GithubRepository, pull_id: int ) -> List[Dict[str, Any]]: url = ("https://api.github.com/repos/{}/{}/issues/{}/comments" "?access_token={}".format(repo.organization, repo.name, p...
References: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
3,064
def get_http_method_arg_name(self): if self.method == : arg_name = else: arg_name = return getattr(requests, self.method), arg_name
Return the HTTP function to call and the params/data argument name
3,065
def dateadd(value: fields.DateTime(), addend: fields.Int(validate=Range(min=1)), unit: fields.Str(validate=OneOf([, ]))=): value = value or dt.datetime.utcnow() if unit == : delta = dt.timedelta(minutes=addend) else: delta = dt.timedelta(days=addend) result =...
Add a value to a date.
3,066
def _profile_module(self): with open(self._run_object, ) as srcfile, _StatProfiler() as prof: code = compile(srcfile.read(), self._run_object, ) prof.base_frame = inspect.currentframe() try: exec(code, self._globs, None) except SystemExit:...
Runs statistical profiler on a module.
3,067
def diff(new, old): if old is not None: is_update = True removed = set(new.removed(old)) updated = set(new.updated(old)) else: is_update = False updated = new removed = set() return updated, removed, is_update
Compute the difference in items of two revisioned collections. If only `new' is specified, it is assumed it is not an update. If both are set, the removed items are returned first. Otherwise, the updated and edited ones are returned. :param set new: Set of new objects :param set old: Set of old obj...
3,068
def get_translation_lookup(identifier, field, value): parts = field.split("__") transformers = parts[1:] if len(parts) > 1 else None field_name = parts[0] language = get_fallback_language() name_parts = parts[0].split("_") if len(name_parts) > 1: supported_language...
Mapper that takes a language field, its value and returns the related lookup for Translation model.
3,069
def _augment_url_with_version(auth_url): if has_in_url_path(auth_url, ["/v2.0", "/v3"]): return auth_url if get_keystone_version() >= 3: return url_path_append(auth_url, "/v3") else: return url_path_append(auth_url, "/v2.0")
Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) could be there. Keystone version needs to be a...
3,070
def django(line): [23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }dataloglevelINFOlogname[app.middleware_log_req:50]messageView func call...
>>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1 = django(input_line1) >>>...
3,071
def ekopw(fname): fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.ekopw_c(fname, ctypes.byref(handle)) return handle.value
Open an existing E-kernel file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopw_c.html :param fname: Name of EK file. :type fname: str :return: Handle attached to EK file. :rtype: int
3,072
def check_read_inputs(self, sampfrom, sampto, channels, physical, smooth_frames, return_res): if not hasattr(sampfrom, ): raise TypeError() if not hasattr(sampto, ): raise TypeError() if not isinstance(channels, list): ...
Ensure that input read parameters (from rdsamp) are valid for the record
3,073
def switch_window(self, window_id: int): if window_id not in self.tmux_available_window_ids: for i in range(max(self.tmux_available_window_ids)+1, window_id+1): self._run_raw(f) tmux_window = self.tmux_session + + str(i) cmd = shlex.quote(f) tmux_cmd = f ...
Switches currently active tmux window for given task. 0 is the default window Args: window_id: integer id of tmux window to use
3,074
def transfer_config_dict(soap_object, data_dict): for key, val in data_dict.items(): setattr(soap_object, key, val)
This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script.
3,075
def version_range(guid, version, before=None, app_versions=None): if app_versions is None: app_versions = validator.constants.APPROVED_APPLICATIONS app_key = None for app_guid, app_name in APPLICATIONS.items(): if app_name == guid: guid = app_guid break ...
Returns all values after (and including) `version` for the app `guid`
3,076
def pip_install(self, reqs): if not reqs: return log.info(, reqs) check_call([ sys.executable, , , , , , self.path] + list(reqs))
Install dependencies into this env by calling pip in a subprocess
3,077
def slugable(self): if self.page: if self.is_leaf_node(): return True if not self.is_leaf_node() and not self.page.regex: return True if not self.is_leaf_node() and self.page.regex and not self.page.show_regex: return T...
A node is slugable in following cases: 1 - Node doesn't have children. 2 - Node has children but its page doesn't have a regex. 3 - Node has children, its page has regex but it doesn't show it. 4 - Node has children, its page shows his regex and node has a default value for regex. ...
3,078
def setup_plugins(extra_plugin_dir=None): if os.path.isdir(PLUGINS_DIR): load_plugins([PLUGINS_DIR]) if extra_plugin_dir: load_plugins(extra_plugin_dir)
Loads any additional plugins.
3,079
def authenticate_user(username, password): user_model = Query() user = db.get(user_model.username == username) if not user: logger.warning("User %s not found", username) return False if user[] == hash_password(password, user.get()): return user[] return False
Authenticate a username and password against our database :param username: :param password: :return: authenticated username
3,080
def mft_mirror_offset(self): return self.bpb.bytes_per_sector * \ self.bpb.sectors_per_cluster * self.extended_bpb.mft_mirror_cluster
Returns: int: Mirror MFT Table offset from the beginning of the partition \ in bytes
3,081
def __process_by_ccore(self): ccore_metric = metric_wrapper.create_instance(self.__metric) self.__score = wrapper.silhoeutte(self.__data, self.__clusters, ccore_metric.get_pointer())
! @brief Performs processing using CCORE (C/C++ part of pyclustering library).
3,082
def _get_boolean(data, position, dummy0, dummy1): end = position + 1 return data[position:end] == b"\x01", end
Decode a BSON true/false to python True/False.
3,083
def _CollapseStrings(elided): if _RE_PATTERN_INCLUDE.match(elided): return elided collapsed = while True: match = Match(r"]*)([\, elided) if not match: collapsed += elided break head, quote, tail = match.groups() if quote == : ...
Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings.
3,084
def get_variables(self) -> Set[str]: variables = set() for cmd in self._cmd: for var in self.__formatter.parse(cmd): logger.debug("Checking variable: %s", var) if var[1] is not None and var[1] not in ["creates", "requires"]: ...
Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces.
3,085
def can_user_access_build(param_name): build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) if not build_id: logging.debug(, param_name) abort(400) ops = operations.UserOps(current_user.get_id...
Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to.
3,086
def to_python(self, value): value = super(LinkedTZDateTimeField, self).to_python(value) if not value: return value return value.astimezone(self.timezone)
Convert the value to the appropriate timezone.
3,087
def _get_metricsmgr_cmd(self, metricsManagerId, sink_config_file, port): metricsmgr_main_class = metricsmgr_cmd = [os.path.join(self.heron_java_home, ), , , , , ...
get the command to start the metrics manager processes
3,088
def generate_ast(path): if os.path.isfile(path): with open(path, ) as f: try: tree = ast.parse(f.read()) return PytTransformer().visit(tree) except SyntaxError: global recursive if not recursive: ...
Generate an Abstract Syntax Tree using the ast module. Args: path(str): The path to the file e.g. example/foo/bar.py
3,089
def set_params(w, src): params = extract_source_params(src) params.update(extract_geometry_params(src)) mfd_pars, rate_pars = extract_mfd_params(src) params.update(mfd_pars) params.update(rate_pars) strikes, dips, rakes, np_weights = extract_source_nodal_planes(src) params.u...
Set source parameters.
3,090
def make_cashed(self): self._descendance_cash = [dict() for _ in self.graph] self.descend = self._descend_cashed
Включает кэширование запросов к descend
3,091
def verify_file_exists(file_name, file_location): return __os.path.isfile(__os.path.join(file_location, file_name))
Function to verify if a file exists Args: file_name: The name of file to check file_location: The location of the file, derive from the os module Returns: returns boolean True or False
3,092
def deactivate_lvm_volume_group(block_device): vg = list_lvm_volume_group(block_device) if vg: cmd = [, , vg] check_call(cmd)
Deactivate any volume gruop associated with an LVM physical volume. :param block_device: str: Full path to LVM physical volume
3,093
def list_vdirs(site, app=_DEFAULT_APP): * ret = dict() ps_cmd = [, , r"".format(site), , r"".format(app), , "Select-Object PhysicalPath, @{ Name = ;", r"Expression = { $_.path.Split()[-1] } }"] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) ...
Get all configured IIS virtual directories for the specified site, or for the combination of site and application. Args: site (str): The IIS site name. app (str): The IIS application. Returns: dict: A dictionary of the virtual directory names and properties. CLI Example: ...
3,094
def generate_property_names(self): property_names_definition = self._definition.get(, {}) if property_names_definition is True: pass elif property_names_definition is False: self.create_variable_keys() with self.l(): self.l() e...
Means that keys of object must to follow this definition. .. code-block:: python { 'propertyNames': { 'maxLength': 3, }, } Valid keys of object for this definition are foo, bar, ... but not foobar for example.
3,095
def encode(self, sequence): polymorphisms = [] defaultSequence = binSequence = array.array(self.forma.typecode) b = 0 i = 0 trueI = 0 poly = set() while i < len(sequence)-1: b = b | self.forma[self.charToBin[sequence[i]]] if sequence[i+1] == : poly.add(sequence[i]) i += 2 else...
Returns a tuple (binary reprensentation, default sequence, polymorphisms list)
3,096
def from_dict(cls, pref, prefix = None): if prefix is None: prefix = Prefix() prefix.id = pref[] if pref[] is not None: prefix.vrf = VRF.get(pref[]) prefix.family = pref[] prefix.prefix = pref[] prefix.display_prefix = pref[] pr...
Create a Prefix object from a dict. Suitable for creating Prefix objects from XML-RPC input.
3,097
def validate(retval, func, args): if retval != 0 and not ERROR.details: return args err = "{}() failed".format(func.__name__) details = {"retval": retval, "args": args} raise ScreenShotError(err, details=details)
Validate the returned value of a Xlib or XRANDR function.
3,098
def raw(self, module, method=, data=None): request = self.session url = % (self.host, self.port, module) if self.verbose: print data if method==: response = request.get(url) elif method==: response = request.post(url,data) eli...
Submits or requsts raw input
3,099
def update_subscription(self, update_parameters, subscription_id): route_values = {} if subscription_id is not None: route_values[] = self._serialize.url(, subscription_id, ) content = self._serialize.body(update_parameters, ) response = self._send(http_method=, ...
UpdateSubscription. [Preview API] Update an existing subscription. Depending on the type of subscription and permissions, the caller can update the description, filter settings, channel (delivery) settings and more. :param :class:`<NotificationSubscriptionUpdateParameters> <azure.devops.v5_0.notificatio...