Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
20,400
def del_repo(repo, **kwargs): * try: _locate_repo_files(repo, rewrite=True) except IOError: return False else: return True
Remove an XBPS repository from the system. repo url of repo to remove (persistent). CLI Examples: .. code-block:: bash salt '*' pkg.del_repo <repo url>
20,401
def isoncurve(self, p): return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b
verifies if a point is on the curve
20,402
def _addRawResult(self, resid, values={}, override=False): if in values and in values: try: dtstr = % (values.get()[], values.get()[]) from datetime import datetime dtobj = datetime.strptime(dtstr, ) dateTi...
Structure of values dict (dict entry for each analysis/field): {'ALC': {'ALC': '13.55', 'DefaultResult': 'ALC', 'Remarks': ''}, 'CO2': {'CO2': '0.66', 'DefaultResult': 'CO2', 'Remarks': ''}, 'Date'...
20,403
def delete_server(self, datacenter_id, server_id): response = self._perform_request( url= % ( datacenter_id, server_id), method=) return response
Removes the server from your data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str``
20,404
def add_to_dict_val_set(dict_obj, key, val): try: dict_obj[key].add(val) except KeyError: dict_obj[key] = set([val])
Adds the given val to the set mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': set([1, 2])} >>> add_to_dict_val_set(dict_obj, 'a', 2) >>> print(dict_obj['a']) {1, 2} >>> add_to_dict_val_set(dict_obj, 'a', 3) ...
20,405
def set_version(package_name, version_str): current_version = get_version(package_name) version_file_path = helpers.package_file_path(, package_name) version_file_content = helpers.get_file_content(version_file_path) version_file_content = version_file_content.replace(current_version, version_str) ...
Set the version in _version.py to version_str
20,406
def render_error(category, error_message, error_codes, exception=None): if isinstance(error_codes, int): error_codes = [error_codes] error_code = error_codes[0] template_list = [str(code) for code in error_codes] template_list.append(str(int(error_code / 100) * 100)) template_list.app...
Render an error page. Arguments: category -- The category of the request error_message -- The message to provide to the error template error_codes -- The applicable HTTP error code(s). Will usually be an integer or a list of integers; the HTTP error response will always be the first er...
20,407
def _get_url_datafiles(url_db_view, url_db_content, mrio_regex, access_cookie=None): returnvalue = namedtuple(, [, ]) url_text = requests.post(url_db_view, cookies=access_cookie).text data_urls = [url_db_content + ff for ff ...
Urls of mrio files by parsing url content for mrio_regex Parameters ---------- url_db_view: url str Url which shows the list of mrios in the db url_db_content: url str Url which needs to be appended before the url parsed from the url_db_view to get a valid download link m...
20,408
def get_next_types(self, n=None): import sys from ..osid.osid_errors import IllegalState, OperationFailed if n > self.available(): raise IllegalState() else: next_list = [] x = 0 while x < n: try: ...
Gets the next set of ``Types`` in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Type`` elements requested which must be less than or equal to ``available()`` return: (osid.type.Type) ...
20,409
def get_template_as_json(template_id, **kwargs): user_id = kwargs[] return json.dumps(get_template_as_dict(template_id, user_id=user_id))
Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function.
20,410
def add_cli_write_bel_namespace(main: click.Group) -> click.Group: @main.command() @click.option(, , type=click.Path(file_okay=False, dir_okay=True), default=os.getcwd(), help=) @click.pass_obj def write(manager: BELNamespaceManagerMixin, directory: str): manag...
Add a ``write_bel_namespace`` command to main :mod:`click` function.
20,411
def module(self, value): if value is not None: assert type(value) is type(sys), " attribute: type is not !".format("module", value) self.__module = value
Setter for **self.__module** attribute. :param value: Attribute value. :type value: ModuleType
20,412
def all(klass, client, **kwargs): resource = klass.RESOURCE_COLLECTION request = Request(client, , resource, params=kwargs) return Cursor(klass, request, init_with=[client])
Returns a Cursor instance for a given resource.
20,413
def get_hashed_rule_name(event, function, lambda_name): event_name = event.get(, function) name_hash = hashlib.sha1(.format(lambda_name, event_name).encode()).hexdigest() return Zappa.get_event_name(name_hash, function)
Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function. This allows support for rule names that may be longer than the 64 char limit.
20,414
def doc_open(): doc_index = os.path.join(DOCS_DIRECTORY, , , ) if sys.platform == : subprocess.check_call([, doc_index]) elif sys.platform == : subprocess.check_call([, doc_index], shell=True) elif sys.platform == : subprocess.check_call([, doc_ind...
Build the HTML docs and open them in a web browser.
20,415
def fetch(self): resp = self.r_session.get(self.document_url) resp.raise_for_status() self.clear() self.update(response_to_json_dict(resp))
Retrieves the content of the current security document from the remote database and populates the locally cached SecurityDocument object with that content. A call to fetch will overwrite any dictionary content currently in the locally cached SecurityDocument object.
20,416
def version(self): res = self.client.service.Version() return .join([ustr(x) for x in res[0]])
Return version of the TR DWE.
20,417
def sendall_stderr(self, s): while s: if self.closed: raise socket.error() sent = self.send_stderr(s) s = s[sent:] return None
Send data to the channel's "stderr" stream, without allowing partial results. Unlike L{send_stderr}, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. @param s: data to send to the client as "stderr" o...
20,418
def insert(self, dct, toa=None, comment=""): if self.schema: jsonschema.validate(dct, self.schema) bson_obj = yield self.collection.insert(dct) raise Return(bson_obj.__str__())
Create a document :param dict dct: :param toa toa: Optional time of action, triggers this to be handled as a future insert action for a new document :param str comment: A comment :rtype str: :returns string bson id:
20,419
def constraint_join(cfg_nodes): r = 0 for e in cfg_nodes: r = r | constraint_table[e] return r
Looks up all cfg_nodes and joins the bitvectors by using logical or.
20,420
def extract_async(self, destination, format=, csv_delimiter=None, csv_header=True, compress=False): format = format.upper() if format == : format = if format == and csv_delimiter is None: csv_delimiter = try: response = self._api.table_extract(self._name_par...
Starts a job to export the table to GCS. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or 'avro' (default 'csv'). csv_delimiter: for CSV exports, the field delimiter to use. Defaults to ',...
20,421
def _convert_to_side(cls, side_spec): from openpyxl.styles import Side _side_key_map = { : , } if isinstance(side_spec, str): return Side(style=side_spec) side_kwargs = {} for k, v in side_spec.items(): if k in _side_key_ma...
Convert ``side_spec`` to an openpyxl v2 Side object Parameters ---------- side_spec : str, dict A string specifying the border style, or a dict with zero or more of the following keys (or their synonyms). 'style' ('border_style') 'color' ...
20,422
def search_for(self, query, include_draft=False): query = query.lower() if not query: return [] def contains_query_keyword(post_or_page): contains = query in post_or_page.title.lower() \ or query in Markup( get_parser(post_...
Search for a query text. :param query: keyword to query :param include_draft: return draft posts/pages or not :return: an iterable object of posts and pages (if allowed).
20,423
def handle_get(self): code = 400 message, explain = \ BaseHTTPServer.BaseHTTPRequestHandler.responses[code] response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % { : code, : message, : explain } sys.stdout.wri...
Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method.
20,424
def child(self, subkey): path = self._path + + subkey handle = win32.RegOpenKey(self.handle, subkey) return RegistryKey(path, handle)
Retrieves a subkey for this Registry key, given its name. @type subkey: str @param subkey: Name of the subkey. @rtype: L{RegistryKey} @return: Subkey.
20,425
def create_domainalias(self, domainid, data): return self.api_call( ENDPOINTS[][], dict(domainid=domainid), body=data)
Create a domain alias
20,426
def deploy(cls, remote_name, branch): def get_remote_url(remote): return % (remote) remote_url = cls.exec_output(get_remote_url(remote_name)) \ .replace(, ) if not remote_url or not re.search(, remote_url): remote_name = ( % ...
Deploy a PaaS instance.
20,427
def pdf(self, d, n=None): rbasis_integral ans = self._pdf(d=d) if n is not None and n != self.order: power = n - self.order numerator = d**power*ans denominator = self._pdf_basis_integral_definite(d_min=0.0, d_max=self.d_excessive, n=power) ans = n...
r'''Computes the probability density function of a continuous particle size distribution at a specified particle diameter, an optionally in a specified basis. The evaluation function varies with the distribution chosen. The interconversion between distribution orders is performed using ...
20,428
def parse_char(self, c): self.buf.extend(c) self.total_bytes_received += len(c) if self.native: if native_testing: self.test_buf.extend(c) m = self.__parse_char_native(self.test_buf) m2 = self....
input some data bytes, possibly returning a new message
20,429
def _construct(self): self._acyclic_cfg = self._cfg.copy() self._pre_process_cfg() self._pd_construct() self._graph = networkx.DiGraph() rdf = compute_dominance_frontier(self._normalized_cfg, self._post_dom) ...
Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc.
20,430
def remove_all_servers(self): for server_id in list(self._servers.keys()): self.remove_server(server_id)
Remove all registered WBEM servers from the subscription manager. This also unregisters listeners from these servers and removes all owned indication subscriptions, owned indication filters, and owned listener destinations. Raises: Exceptions raised by :class:`~pywbem.WBEMC...
20,431
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action): def f(self, *args, **kwargs): for key, value in args[-1].items(): if type(value) == file: return self._put_or_post_multipart(, self._generate_url(regex, args[:-1])...
Returns a callable which conjures the URL for the resource and POSTs data
20,432
def _year_expand(s): regex = r"^((?:19|20)\d{2})?(\s*-\s*)?((?:19|20)\d{2})?$" try: start, dash, end = match(regex, ustr(s)).groups() start = start or 1900 end = end or 2099 except AttributeError: return 1900, 2099 return (int(star...
Parses a year or dash-delimeted year range
20,433
def array_equiv(arr1, arr2): arr1, arr2 = as_like_arrays(arr1, arr2) if arr1.shape != arr2.shape: return False with warnings.catch_warnings(): warnings.filterwarnings(, "In the future, ") flag_array = (arr1 == arr2) flag_array |= (isnull(arr1) & isnull(arr2)) ...
Like np.array_equal, but also allows values to be NaN in both arrays
20,434
def _reregister_tree_admin(): try: admin.site.unregister(MODEL_TREE_CLASS) except NotRegistered: pass admin.site.register(MODEL_TREE_CLASS, _TREE_ADMIN())
Forces unregistration of tree admin class with following re-registration.
20,435
def electric_field_amplitude_intensity(s0, Isat=16.6889462814, Omega=1e6, units="ad-hoc"): E0_sat = sqrt(2*mu0*c*Isat)/Omega if units == "ad-hoc": e0 = hbar/(e*a0) E0_sat = E0_sat/e0 return E0_sat*sqrt(s0)
Return the amplitude of the electric field for saturation parameter. This is at a given saturation parameter s0=I/Isat, where I0 is by default \ Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \ rubidium for circularly polarized light. Optionally, a frequency scale \ `Omega` can be prov...
20,436
def _attrib_to_transform(attrib): transform = np.eye(4, dtype=np.float64) if in attrib: values = np.array( attrib[].split(), dtype=np.float64).reshape((4, 3)).T transform[:3, :4] = values return transform
Extract a homogenous transform from a dictionary. Parameters ------------ attrib: dict, optionally containing 'transform' Returns ------------ transform: (4, 4) float, homogeonous transformation
20,437
def expand_template(template, value): value = wrap(value) if is_text(template): return _simple_expand(template, (value,)) return _expand(template, (value,))
:param template: A UNICODE STRING WITH VARIABLE NAMES IN MOUSTACHES `{{.}}` :param value: Data HOLDING THE PARAMTER VALUES :return: UNICODE STRING WITH VARIABLES EXPANDED
20,438
def show_doc(elt, doc_string:bool=True, full_name:str=None, arg_comments:dict=None, title_level=None, alt_doc_string:str=, ignore_warn:bool=False, markdown=True, show_tests=True): "Show documentation for element `elt`. Supported types: class, Callable, and enum." arg_comments = ifnone(arg_comments,...
Show documentation for element `elt`. Supported types: class, Callable, and enum.
20,439
def observable( _method_or_viewset=None, poll_interval=None, primary_key=None, dependencies=None ): if poll_interval and dependencies: raise ValueError() def decorator_observable(method_or_viewset): if inspect.isclass(method_or_viewset): list_method = getattr(method_or_vie...
Make ViewSet or ViewSet method observable. Decorating a ViewSet class is the same as decorating its `list` method. If decorated method returns a response containing a list of items, it must use the provided `LimitOffsetPagination` for any pagination. In case a non-list response is returned, the result...
20,440
def create_ml_configuration_from_datasets(self, dataset_ids): available_columns = self.search_template_client.get_available_columns(dataset_ids) search_template = self.search_template_client.create(dataset_ids, available_columns) return self.create_ml_configuration(search_temp...
Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status)
20,441
def logout(): from uliweb import request delete_user_session() request.session.delete() request.user = None return True
Remove the authenticated user's ID from the request.
20,442
def do_class(self, element, decl, pseudo): step = self.state[self.state[]] actions = step[] strval = self.eval_string_value(element, decl.value) actions.append((, (, strval)))
Implement class declaration - pre-match.
20,443
def _purge_expired(self): time_horizon = time.time() - self._keep_time new_cache = {} for (k, v) in self._cache.items(): if v.timestamp > time_horizon: new_cache[k] = v self._cache = new_cache
Remove all expired entries from the cache.
20,444
def repeat(self, n=2, oscillate=False, callback=None): colorlist = ColorList() colors = ColorList.copy(self) for i in _range(n): colorlist.extend(colors) if oscillate: colors = colors.reverse() if callback: colors = callback(colors) return co...
Returns a list that is a repetition of the given list. When oscillate is True, moves from the end back to the beginning, and then from the beginning to the end, and so on.
20,445
def tofile(self, f): f.write(pack(self.FILE_FMT, self.scale, self.ratio, self.initial_capacity, self.error_rate)) f.write(pack(b, len(self.filters))) if len(self.filters) > 0: headerpos = f.tell() headerfm...
Serialize this ScalableBloomFilter into the file-object `f'.
20,446
def fix_empty_methods(source): def_indentation_level = 0 output = "" just_matched = False previous_line = None method = re.compile(r) for line in source.split(): if len(line.strip()) > 0: indent = " " * (def_indentation_level + 1) output += "...
Appends 'pass' to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =). Example:: # Note: This triple-single-quote inside a triple-double-quote is also a # pyminifier self-test def myfunc(): '''This is just a placeholder function.'''...
20,447
def call(command, working_directory=config.BASE_DIR): LOG.info(command) proc = sp.Popen(command, stdout=sp.PIPE, stderr=sp.PIPE, cwd=working_directory, shell=True) out, err = proc.communicate() return (out, err)
Executes shell command in a given working_directory. Command is a list of strings to execute as a command line. Returns a tuple of two byte strings: (stdout, stderr)
20,448
def new_cast_status(self, status): self.status = status if status: self.status_event.set()
Called when a new status received from the Chromecast.
20,449
def get_all_children(self, include_self=False): ownership = Ownership.objects.filter(parent=self) subsidiaries = Company.objects.filter(child__in=ownership) for sub in subsidiaries: subsidiaries = subsidiaries | sub.get_all_children() if include_self is True: ...
Return all subsidiaries of this company.
20,450
def fetch_action_restriction(self, reftrack, action): inter = self.get_typ_interface(reftrack.get_typ()) d = {: inter.is_reference_restricted, : inter.is_load_restricted, : inter.is_unload_restricted, : inter.is_replace_restricted, : inter.is_import_ref_restricted, : i...
Return wheter the given action is restricted for the given reftrack available actions are: ``reference``, ``load``, ``unload``, ``replace``, ``import_reference``, ``import_taskfile``, ``delete`` If action is not available, True is returned. :param reftrack: the reftrack to query ...
20,451
def getSignature(self, signatureKey, serialized): try: return Curve.calculateSignature(signatureKey, serialized) except InvalidKeyException as e: raise AssertionError(e)
:type signatureKey: ECPrivateKey :type serialized: bytearray
20,452
def _constructClassificationRecord(self, inputs): allSPColumns = inputs["spBottomUpOut"] activeSPColumns = allSPColumns.nonzero()[0] score = anomaly.computeRawAnomalyScore(activeSPColumns, self._prevPredictedColumns) spSize = len(allSPColumns) ...
Construct a _HTMClassificationRecord based on the state of the model passed in through the inputs. Types for self.classificationVectorType: 1 - TM active cells in learn state 2 - SP columns concatenated with error from TM column predictions and SP
20,453
def assert_condition_md5(self): if in self.request.headers: body_md5 = hashlib.md5(self.request.body).hexdigest() if body_md5 != self.request.headers[]: raise_400(self, msg=)
If the ``Content-MD5`` request header is present in the request it's verified against the MD5 hash of the request body. If they don't match, a 400 HTTP response is returned. :raises: :class:`webob.exceptions.ResponseException` of status 400 if the MD5 hash does not match the bo...
20,454
def predict_condition_models(self, model_names, input_columns, metadata_cols, data_mode="forecast", ): groups = self.condition_models.keys() predictions = pd.DataF...
Apply condition modelsto forecast data. Args: model_names: List of names associated with each condition model used for prediction input_columns: List of columns in data used as input into the model metadata_cols: Columns from input data that should be included in the data fra...
20,455
def set_state(self, entity_id, new_state, **kwargs): "Updates or creates the current state of an entity." return remote.set_state(self.api, new_state, **kwargs)
Updates or creates the current state of an entity.
20,456
def database_remove_tags(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /database-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags
20,457
def refresh_db(**kwargs): * salt.utils.pkg.clear_rtag(__opts__) cmd = call = __salt__[](cmd, output_loglevel=) if call[] != 0: comment = if in call: comment += call[] raise CommandExecutionError(comment) return True
Update list of available packages from installed repos CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
20,458
def keygen(sk_file=None, pk_file=None, **kwargs): kwargs[] = __opts__ return salt.utils.nacl.keygen(sk_file, pk_file, **kwargs)
Use libnacl to generate a keypair. If no `sk_file` is defined return a keypair. If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`. When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated using the `sk_file`. CLI Examples...
20,459
def list_pkgs(versions_as_list=False, **kwargs): <package_name><version>* versions_as_list = salt.utils.data.is_true(versions_as_list) if any([salt.utils.data.is_true(kwargs.get(x)) for x in (, )]): return {} if in __context__: if versions_as_list: return _...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
20,460
def old_unpad(s): if not s: return s try: return Padding.removePadding(s, blocksize=OLD_BLOCK_SIZE) except AssertionError: return s
Removes padding from an input string based on a given block size. :param s: string :returns: The unpadded string.
20,461
def monitor_deletion(): monitors = {} def set_deleted(x): def _(weakref): del monitors[x] return _ def monitor(item, name): monitors[name] = ref(item, set_deleted(name)) def is_alive(name): return monitors.get(name, None) is not None return monito...
Function for checking for correct deletion of weakref-able objects. Example usage:: monitor, is_alive = monitor_deletion() obj = set() monitor(obj, "obj") assert is_alive("obj") # True because there is a ref to `obj` is_alive del obj assert not is_alive("obj") # Tru...
20,462
def remove_bad_sequence(codon_list, bad_seq, bad_seqs): gene_seq = .join(codon_list) problem = bad_seq.search(gene_seq) if not problem: return False bs_start_codon = problem.start() // 3 bs_end_codon = problem.end() // 3 for i in range(bs_start_codon, bs_end_codon): prob...
Make a silent mutation to the given codon list to remove the first instance of the given bad sequence found in the gene sequence. If the bad sequence isn't found, nothing happens and the function returns false. Otherwise the function returns true. You can use these return values to easily write a ...
20,463
def create_border(self, border_style_type): if border_style_type == MenuBorderStyleType.ASCII_BORDER: return self.create_ascii_border() elif border_style_type == MenuBorderStyleType.LIGHT_BORDER: return self.create_light_border() elif border_style_type == MenuBor...
Create a new MenuBorderStyle instance based on the given border style type. Args: border_style_type (int): an integer value from :obj:`MenuBorderStyleType`. Returns: :obj:`MenuBorderStyle`: a new MenuBorderStyle instance of the specified style.
20,464
def list_kubernetes_roles(self, mount_point=): url = .format(mount_point) return self._adapter.get(url).json()
GET /auth/<mount_point>/role?list=true :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Parsed JSON response from the list roles GET request. :rtype: dict.
20,465
def lookup( name, rdtype, method=None, servers=None, timeout=None, walk=False, walk_tld=False, secure=None ): name opts = {} method = method or opts.get(, ) secure = secure or opts.get(, None) servers = servers or opts.get(, None) timeout = timeout or opts.ge...
Lookup DNS records and return their data :param name: name to lookup :param rdtype: DNS record type :param method: gai (getaddrinfo()), dnspython, dig, drill, host, nslookup or auto (default) :param servers: (list of) server(s) to try in-order :param timeout: query timeout or a valiant approximatio...
20,466
def read_hier_references(jams_file, annotation_id=0, exclude_levels=[]): hier_bounds = [] hier_labels = [] hier_levels = [] jam = jams.load(jams_file) namespaces = ["segment_salami_upper", "segment_salami_function", "segment_open", "segment_tut", "segment_salami_lower"] ...
Reads hierarchical references from a jams file. Parameters ---------- jams_file : str Path to the jams file. annotation_id : int > 0 Identifier of the annotator to read from. exclude_levels: list List of levels to exclude. Empty list to include all levels. Returns -...
20,467
def getWidget(self): widget = QtWidgets.QLabel("NO MOVEMENT YET") widget.setStyleSheet(style.detector_test) self.signals.start_move.connect(lambda : widget.setText("MOVEMENT START")) self.signals.stop_move. connect(lambda : widget.setText("MOVEMENT STOP")) return widget
Some ideas for your widget: - Textual information (alert, license place number) - Check boxes : if checked, send e-mail to your mom when the analyzer spots something - .. or send an sms to yourself - You can include the cv2.imshow window to the widget to see how the analyzer proceeds
20,468
def get_subfields(self, datafield, subfield, i1=None, i2=None, exception=False): if len(datafield) != 3: raise ValueError( "`datafield` parameter have to be exactly 3 chars long!" ) if len(subfield) != 1: raise ValueError...
Return content of given `subfield` in `datafield`. Args: datafield (str): Section name (for example "001", "100", "700"). subfield (str): Subfield name (for example "a", "1", etc..). i1 (str, default None): Optional i1/ind1 parameter value, which will be used...
20,469
def search(self, **kwargs): return super(ApiNetworkIPv6, self).get(self.prepare_url(, kwargs))
Method to search ipv6's based on extends search. :param search: Dict containing QuerySets to find ipv6's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override d...
20,470
def receive_callback(request): logger.debug("Received callback for {0} session {1}".format(request.user, request.session.session_key[:5])) code = request.GET.get(, None) state = request.GET.get(, None) try: assert code assert state except AssertionError: logger.debu...
Parses SSO callback, validates, retrieves :model:`esi.Token`, and internally redirects to the target url.
20,471
def read_gene2acc(file_path, logger): gene2acc = {} with misc.smart_open_read(file_path, mode=, try_gzip=True) as fh: reader = csv.reader(fh, dialect=) next(reader) for i, l in enumerate(reader): id_ = int(l[1]) symbol = l[15] try: ...
Extracts Entrez ID -> gene symbol mapping from gene2accession.gz file. Parameters ---------- file_path: str The path of the gene2accession.gz file (or a filtered version thereof). The file may be gzip'ed. Returns ------- dict A mapping of Entrez IDs to gene symbols.
20,472
def merge_duplicates(self): if len(self.entries) == 0: self.log.error("WARNING: `entries` is empty, loading stubs") if self.args.update: self.log.warning( "No sources changed, entry files unchanged in update." " Skipping m...
Merge and remove duplicate entries. Compares each entry ('name') in `stubs` to all later entries to check for duplicates in name or alias. If a duplicate is found, they are merged and written to file.
20,473
def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None): s VSAN system. If host_names is not provided, VSAN-eligible disks will be added to the hosts**[esxi-1.host.com, esxi-2.host.com] service_instance = salt.utils.vmware.get_service_instance(host=host, ...
Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. password The password used to login to the host. protocol Optionally set to alter...
20,474
def transform(self, data): transformed_data = _copy(data) for name, step in self._transformers: transformed_data = step.transform(transformed_data) if type(transformed_data) != _tc.SFrame: raise TypeError("The transform function in step did not return" ...
Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame A transformed SFrame. See Also ...
20,475
def issubset(self, other): self._binary_sanity_check(other) return set.issubset(self, other)
Report whether another set contains this RangeSet.
20,476
def old_status(self, old_status): allowed_values = ["NEW", "DONE", "REJECTED"] if old_status not in allowed_values: raise ValueError( "Invalid value for `old_status` ({0}), must be one of {1}" .format(old_status, allowed_values) ) ...
Sets the old_status of this BuildSetStatusChangedEvent. :param old_status: The old_status of this BuildSetStatusChangedEvent. :type: str
20,477
def delete_service(self, name): return services.delete_service(self._get_resource_root(), name, self.name)
Delete a service by name. @param name: Service name @return: The deleted ApiService object
20,478
def dirs(self, *args, **kwargs): return [p for p in self.listdir(*args, **kwargs) if p.isdir()]
D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). Accepts parameters to :meth:`listdir`.
20,479
def _build_ip_constraints(roles, ips, constraints): local_ips = copy.deepcopy(ips) for constraint in constraints: gsrc = constraint[] gdst = constraint[] gdelay = constraint[] grate = constraint[] gloss = constraint[] for s in roles[gsrc]: ...
Generate the constraints at the ip/device level. Those constraints are those used by ansible to enforce tc/netem rules.
20,480
def _node_add_with_peer_leaflist(self, child_self, child_other): parent_self = child_self.getparent() s_node = self.device.get_schema_node(child_self) if child_other.get(operation_tag) is None or \ child_other.get(operation_tag) == or \ child_other.get(operation_...
_node_add_with_peer_leaflist Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are leaf-list nodes. Element child_self will be modified during the process. RFC6020 section 7.7.7 is a reference of this meth...
20,481
def all_tamil( word_in ): if isinstance(word_in,list): word = word_in else: word = get_letters( word_in ) return all( [(letter in tamil_letters) for letter in word] )
predicate checks if all letters of the input word are Tamil letters
20,482
def check_permissions(self, request): if not self.predicates: return True return all( predicate(request, *self.predicates_params[i]) for i, predicate in enumerate(self.predicates) )
Call the predicate(s) associated with the RPC method, to check if the current request can actually call the method. Return a boolean indicating if the method should be executed (True) or not (False)
20,483
def size(self, t=None): s = sum(self.degree(t=t).values()) / 2 return int(s)
Return the number of edges at time t. Parameters ---------- t : snapshot id (default=None) If None will be returned the size of the flattened graph. Returns ------- nedges : int The number of edges See Also -------- numb...
20,484
def SegmentCollection(mode="agg-fast", *args, **kwargs): if mode == "raw": return RawSegmentCollection(*args, **kwargs) return AggSegmentCollection(*args, **kwargs)
mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash)
20,485
def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *, init: Any = NONE): _init = init def _build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]]): @wraps(function) def _wrapper(init=NONE) -> Accumulate: init = _init if i...
Decorator to wrap a function to return an Accumulate operator. :param function: function to be wrapped :param init: optional initialization for state
20,486
def publish(self, value): if not isinstance(value, list): raise ValueError(value) slaves = [ % x for x in value] return unicode(", ".join(slaves))
Accepts: list of tuples in the format (ip, port) Returns: unicode
20,487
def nullify(function): "Decorator. If empty list, returns None, else list." def wrapper(*args, **kwargs): value = function(*args, **kwargs) if(type(value) == list and len(value) == 0): return None return value return wrapper
Decorator. If empty list, returns None, else list.
20,488
def visit_module(self, node): if not node.file_stream: return text = node.file_stream.read() self._checkCopyright(text, node) if not isTestModule(node.name) and moduleNeedsTests: self._checkTestReference(text, node)
A interface will be called when visiting a module. @param node: node of current module
20,489
def _compute_stacksize(self): s code list, compute its maximal stack usage. This is done by scanning the code, and computing for each opcode the stack state at the opcode. ' code = self.code label_pos = { op : pos for pos, (op,...
Given this object's code list, compute its maximal stack usage. This is done by scanning the code, and computing for each opcode the stack state at the opcode.
20,490
def delete_script(delete=None): if connexion.request.is_json: delete = Delete.from_dict(connexion.request.get_json()) return
Delete a script Delete a script # noqa: E501 :param delete: The data needed to delete this script :type delete: dict | bytes :rtype: Response
20,491
def transform_velocity_array(array, pos_array, vel, euler, rotation_vel=(0,0,0)): trans_matrix = euler_trans_matrix(*euler) rotation_component = np.cross(rotation_vel, pos_array, axisb=1) orbital_component = np.asarray(vel) if isinstance(array, ComputedColumn): array = array.for_com...
Transform any Nx3 velocity vector array by adding the center-of-mass 'vel', accounting for solid-body rotation, and applying an euler transformation. :parameter array array: numpy array of Nx3 velocity vectors in the original (star) coordinate frame :parameter array pos_array: positions of the elem...
20,492
def get_market_last(symbols=None, **kwargs): import warnings warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last")) return Last(symbols, **kwargs).fetch()
MOVED to iexfinance.iexdata.get_last
20,493
def index_transcriptome(gtf_file, ref_file, data): gtf_fasta = gtf.gtf_to_fasta(gtf_file, ref_file) bowtie2_index = os.path.splitext(gtf_fasta)[0] bowtie2_build = config_utils.get_program("bowtie2", data["config"]) + "-build" cmd = "{bowtie2_build} --offrate 1 {gtf_fasta} {bowtie2_index}".format(**...
use a GTF file and a reference FASTA file to index the transcriptome
20,494
def do_read(self, args): if not self.current: print() return try: print(self.current.read()) except Exception as e: print(e)
Receive from the resource in use.
20,495
def add_lambda_integration(self): lambda_uri = self.generate_uris()[] self.client.put_integration( restApiId=self.api_id, resourceId=self.resource_id, httpMethod=self.trigger_settings[], integrationHttpMethod=, uri=lambda_uri, ...
Attach lambda found to API.
20,496
def read_value(self, dtype=, count=1, advance=True): data = np.frombuffer(self._blob, dtype=dtype, count=count, offset=self.pos) if advance: self._pos += data.dtype.itemsize * data.size if count == 1: data = data[0] return data
Read one or more scalars of the indicated dtype. Count specifies the number of scalars to be read in.
20,497
def from_body(self, param_name, schema): schema = schema() if isclass(schema) else schema def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): kwargs[param_name] = self.__parse_body(schema) return func(*args, **kwarg...
A decorator that converts the request body into a function parameter based on the specified schema. :param param_name: The parameter which receives the argument. :param schema: The schema class or instance used to deserialize the request body toa Python object. :return: A function
20,498
def _NDP_Attack_DAD_DoS(reply_callback, iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): def is_request(req, mac_src_filter, tgt_filter): if not (Ether in req and IPv6 in req and ICMPv6ND_NS in req): return 0 ma...
Internal generic helper accepting a specific callback as first argument, for NS or NA reply. See the two specific functions below.
20,499
def add_filter_by_pattern(self, pattern, filter_type=DefaultFilterType): self.add_filter(FilterPattern(pattern), filter_type) return self
Add a files filter by linux-style pattern to this iterator. :param pattern: linux-style files pattern (or list of patterns)