Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,000
def getApplicationAutoLaunch(self, pchAppKey): fn = self.function_table.getApplicationAutoLaunch result = fn(pchAppKey) return result
Gets the application auto-launch flag. This is only valid for applications which return true for VRApplicationProperty_IsDashboardOverlay_Bool.
347,001
def make_name(s, camel=None, lower=None, space=, remove_prefix=None, language=, string_type=str): if camel is None and lower is None: lower = True if not s: return None ecma_languages = [, ] unicode_languages = ecma_languages language = language or language = language.lower...
Process a string to produce a valid python variable/class/type name Arguments: space (str): string to substitute for spaces ('' to delete all whitespace) camel (bool): whether to camel-case names, Django Model Name style (first letter capitalized) lower (bool): whether to lowercase all strings ...
347,002
async def unpack_message(wallet_handle: int, jwe: bytes) -> bytes: logger = logging.getLogger(__name__) logger.debug("unpack_message: >>> wallet_handle: %r, jwe: %r", wallet_handle, jwe) def transform_cb(arr_ptr: POINTER(c_uint8), arr_len: c_...
Unpacks a JWE-like formatted message outputted by pack_message (Experimental) #Params command_handle: command handle to map callback to user context. wallet_handle: wallet handler (created by open_wallet) message: the output of a pack message #Returns -> See HIPE 0028 for details (Authcrypt mo...
347,003
def mean_oob_mae_weight(trees): weights = [] active_trees = [] for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: continue weights.append(oob_mae.mean) active_trees.append(tree) ...
Returns weights proportional to the out-of-bag mean absolute error for each tree.
347,004
def get_attributes(self, item_name, attribute_name=None, consistent_read=False, item=None): return self.connection.get_attributes(self, item_name, attribute_name, consistent_read, item)
Retrieve attributes for a given item. :type item_name: string :param item_name: The name of the item whose attributes are being retrieved. :type attribute_names: string or list of strings :param attribute_names: An attribute name or list of attribute names. This ...
347,005
def flash_block(self, addr, data, smart_flash=True, chip_erase=None, progress_cb=None, fast_verify=False): assert self.region is not None assert self.region.contains_range(start=addr, length=len(data)) fb = FlashBuilder(self) fb.add_data(addr, data) info = fb.pr...
! @brief Flash a block of data.
347,006
def removeBlock(self, block): if issubclass(block.__class__, AdvancedTag): return self.removeChild(block) else: return self.removeText(block)
removeBlock - Removes a single block (text node or AdvancedTag) which is a child of this object. @param block <str/AdvancedTag> - The block (text node or AdvancedTag) to remove. @return Returns the removed block if one was removed, or None if requested block is not a child of this ...
347,007
def num_leaves(tree): if tree.is_leaf: return 1 else: return num_leaves(tree.left_child) + num_leaves(tree.right_child)
Determine the number of leaves in a tree
347,008
def prepare_arg(value): if value is None: return value elif isinstance(value, (list, dict)) or hasattr(value, ): return json.dumps(_normalize(value)) elif isinstance(value, datetime.timedelta): now = datetime.datetime.now() return int((now + value).timestamp()) elif ...
Stringify dicts/lists and convert datetime/timedelta to unix-time :param value: :return:
347,009
def focus_next(self, count=1): " Focus the next pane. " panes = self.panes if panes: self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)] else: self.active_pane = None
Focus the next pane.
347,010
def config(commands=None, config_file=None, template_engine=, context=None, defaults=None, saltenv=, **kwargs): *spanning-tree mode mstp**servers1.2.3.4 initial_config = show(, **kwargs)[0] if config_file: file_str = __salt__[](config...
Configures the Nexus switch with the specified commands. This method is used to send configuration commands to the switch. It will take either a string or a list and prepend the necessary commands to put the session into config mode. .. warning:: All the commands will be applied directly int...
347,011
def encode_list(key, list_): if not list_: return {} return {key: " ".join(str(i) for i in list_)}
Converts a list into a space-separated string and puts it in a dictionary :param key: Dictionary key to store the list :param list_: A list of objects :return: A dictionary key->string or an empty dictionary
347,012
def _load_builtins(self): pymux = self.pymux kb = KeyBindings() has_prefix = HasPrefix(pymux) waits_for_confirmation = WaitsForConfirmation(pymux) prompt_or_command_focus = has_focus(COMMAND) | has_focus(PROMPT) display_pane_numbers = Condition(lambda: ...
Fill the Registry with the hard coded key bindings.
347,013
def url(self): scheme, auth, host, port, path, query, fragment = self url = if scheme is not None: url += scheme + if auth is not None: url += auth + if host is not None: url += host if port is not None: ...
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Examp...
347,014
def forwards(self, orm): "Write your forwards methods here." for tag in orm[].objects.all(): if tag.tagtitle_set.all().count() == 0: orm[].objects.create( trans_name=tag.name, tag=tag, language=)
Write your forwards methods here.
347,015
def merge(data, cfg=None): if type(cfg) == str: cfg = _read_yaml(cfg) if cfg == None: cfg = _read_yaml() if cfg == None: print() cfg = {} ...
WORK IN PROGRESS Concat, merge, join, drop keys in dictionary of pandas.DataFrames into one pandas.DataFrame (data) and a pandas.Series (labels). Parameters ---------- data : dict of pandas.DataFrames Result of icy.read() cfg : dict or str, optional Dictionary of action...
347,016
def dP_Zukauskas(Re, n, ST, SL, D, rho, Vmax): r a = ST/D b = SL/D if a == b: parameter = (a-1.)/(b-1.) f = float(dP_inline_f(Re, b)) x = float(dP_inline_correction(parameter, Re)) else: parameter = a/b f = float(dP_staggered_f(Re, a)) x = float(dP_sta...
r'''Calculates pressure drop for crossflow across a tube bank of tube number n at a specified Re. Method presented in [1]_. Also presented in [2]_. .. math:: \Delta P = N_L \chi \left(\frac{\rho V_{max}^2}{2}\right)f Parameters ---------- Re : float Reynolds number, [-] n :...
347,017
def _get_pika_properties(properties_in): properties = pika.BasicProperties() for key in properties_in or {}: if properties_in.get(key) is not None: setattr(properties, key, properties_in.get(key)) return properties
Return a :class:`pika.spec.BasicProperties` object for a :class:`rejected.data.Properties` object. :param dict properties_in: Properties to convert :rtype: :class:`pika.spec.BasicProperties`
347,018
def i4_bit_lo0(n): bit = 1 i = np.floor(n) while i != 2 * (i // 2): bit += 1 i //= 2 return bit
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer. Example: +------+------------+---- | N | Binary | BIT +------+------------+---- | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 10 | 1 | 3 | 11 | 3 | ...
347,019
def id(self): if self.is_logged_in_user: return self._current_user_id return int(self._id_xpb.one_(self.profile_tree))
:returns: The id that okcupid.com associates with this profile.
347,020
def update_contact_of_client(self, contact_id, contact_dict): return self._create_put_request(resource=CONTACTS, billomat_id=contact_id, send_data=contact_dict)
Updates a contact :param contact_id: the id of the contact :param contact_dict: dict :return: dict
347,021
def get_surveys(self, url=_SURVEYS_URL): res = self.client._get(url=url, expected_status_code=200) soup = BeautifulSoup(res.text, _DEFAULT_BEAUTIFULSOUP_PARSER) surveys_soup = soup.select(_SURVEYS_SELECTOR) survey_list = [] for survey_soup in surveys_soup: su...
Function to get the surveys for the account
347,022
def _add(self, *rules): for rule in rules: if rule in self: continue self._validate_rule(rule) for rule in rules: for r in self._split_rules(rule): for side in r.rule: for s in side: ...
Add rules into the set. Each rule is validated and split if needed. The method add the rules into dictionary, so the rule can be deleted with terminals or nonterminals. :param rules: Rules to insert. :return: Inserted rules. :raise NotRuleException: If the parameter doesn't inherit from ...
347,023
def itermerged(self): for key in self: val = self._container[key.lower()] yield val[0], .join(val[1:])
Iterate over all headers, merging duplicate ones together.
347,024
def get_privilege_set(self, hiveObject, user_name, group_names): self.send_get_privilege_set(hiveObject, user_name, group_names) return self.recv_get_privilege_set()
Parameters: - hiveObject - user_name - group_names
347,025
def Almedeij(Re): r phi4 = ((6E-17*Re**2.63)**-10 + 0.2**-10)**-1 phi3 = (1.57E8*Re**-1.625)**10 phi2 = ((0.148*Re**0.11)**-10 + 0.5**-10)**-1 phi1 = (24*Re**-1)**10 + (21*Re**-0.67)**10 + (4*Re**-0.33)**10 + 0.4**10 Cd = (1/((phi1 + phi2)**-1 + phi3**-1) + phi4)**0.1 return Cd
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left[\frac{1}{(\phi_1 + \phi_2)^{-1} + (\phi_3)^{-1}} + \phi_4\right]^{0.1} \phi_1 = (24Re^{-1})^{10} + (21Re^{-0.67})^{10} + (4Re^{-0.33})^{10} + 0.4^{10} \phi_2 = \left...
347,026
def from_passwd(uid_min=None, uid_max=None): import pwd users = Users(oktypes=User) passwd_list = pwd.getpwall() if not uid_min: uid_min = UID_MIN if not uid_max: uid_max = UID_MAX sudoers_entries = read_sudoers() for pwd_entry in ...
Create collection from locally discovered data, e.g. /etc/passwd.
347,027
def tableType( self ): if not self._tableType: if self._tableTypeName: self._tableType = Orb.instance().model(nstr(self._tableTypeName)) return self._tableType
Returns the table type for this instance. :return <subclass of orb.Table> || None
347,028
def print_reproduceable(self, request): command = "curl -u $SL_USER:$SL_APIKEY -X {method} -H {headers} {data} " method = REST_SPECIAL_METHODS.get(request.method) if method is None: method = if request.args: method = data = if reques...
Prints out the minimal python code to reproduce a specific request The will also automatically replace the API key so its not accidently exposed. :param request request: Request object
347,029
def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.cancel() elif event.key() == QtCore.Qt.Key_Left: self.goBack() elif event.key() == QtCore.Qt.Key_Right: self.goForward() elif event.key() == QtCore.Qt.Key_Hom...
Listens for the left/right keys and the escape key to control the slides. :param event | <QtCore.Qt.QKeyEvent>
347,030
def get(self, name, factory, *factory_args, **factory_kwargs): update_thread_local = getattr(factory, , True) if (not update_thread_local) or (name not in self.__dict__): obj = factory(*factory_args, **factory_kwargs) if update_thread_local: setattr(self,...
Get attribute, creating if required using specified factory.
347,031
def clean_link(self, url): return self._clean_re.sub(lambda match: "%%%2x" % ord(match.group(0)), url)
Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).
347,032
def update_pull_request_iteration_statuses(self, patch_document, repository_id, pull_request_id, iteration_id, project=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if repository_id is not None: route_values[] ...
UpdatePullRequestIterationStatuses. [Preview API] Update pull request iteration statuses collection. The only supported operation type is `remove`. :param :class:`<[JsonPatchOperation]> <azure.devops.v5_1.git.models.[JsonPatchOperation]>` patch_document: Operations to apply to the pull request statuses ...
347,033
def change_points_geo_ref(self, points, points_geo_ref=None): import copy is_list = isinstance(points, list) points = ensure_numeric(points, num.float) if len(points.shape) == 1: msg = assert len(points) == 2, msg ...
Change the geo reference of a list or numeric array of points to be this reference.(The reference used for this object) If the points do not have a geo ref, assume 'absolute' values
347,034
def push(self): sock = self.__sock(zmq.PUSH) return self.__send_function(sock)
Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: function
347,035
def run_job(name, force=False): ** ret = {: [], : True} if not name: ret[] = ret[] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if in data and not data[] and not force: ret[] = .forma...
Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled.
347,036
def from_dict(cls, data): auth_info = _AuthenticationInformation.from_dict(data.get("auth_info")) instance = cls(auth_info=auth_info) instance.user_id_hash_type = data.get("hash_type") instance.attributes = data.get("attributes", {}) instance.user_id = data.get("user_id"...
:type data: dict[str, dict[str, str] | str] :rtype: satosa.internal_data.InternalResponse :param data: A dict representation of an InternalResponse object :return: An InternalResponse object
347,037
def run(system, outfile=, name=, doc_string=, group=, data={}, descr={}, units={}, params=[], fnamex=[], fnamey=[], mandatory=[], zeros=[], powers=[], currents=[], voltages=[], z=[], y...
Input data consistency check
347,038
def assemble(self): sp_r = self.split_run() ar_r = self.argument_run(sp_r) de_r = self.dereference_run(ar_r) program = self.program_run(de_r) return program
.. _assembler: Chains split_run_, argument_run_, dereference_run_ and program_run_.
347,039
def _get_xdata_for_function(self, n, xdata): if self[][n] in [None, 0]: return _n.array(xdata) if self[][n] == : return _n.logspace(_n.log10(min(xdata)), _n.log10(max(xdata)), self[][n], True, 1...
Generates the x-data for plotting the function. Parameters ---------- n Which data set we're using xdata Data set upon which to base this Returns ------- float
347,040
def gain_chart(df, col_true=None, col_pred=None, col_scores=None, pos_label=1): r if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS) if not col_scores: col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE) thresh, tp, fn, tn, fp = _run_roc_node...
r""" Compute positive proportion, true positive rate (TPR) and threshold from predicted DataFrame. The trace can be plotted as a cumulative gain chart Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param pos_label: positive labe...
347,041
def dcs_modules(): dcs_dirname = os.path.dirname(__file__) module_prefix = __package__ + if getattr(sys, , False): importer = pkgutil.get_importer(dcs_dirname) return [module for module in list(importer.toc) if module.startswith(module_prefix) and module.count() == 2] else: ...
Get names of DCS modules, depending on execution environment. If being packaged with PyInstaller, modules aren't discoverable dynamically by scanning source directory because `FrozenImporter` doesn't implement `iter_modules` method. But it is still possible to find all potential DCS modules by iterating thr...
347,042
def markForRebuild( self, state = True ): self._rebuildRequired = state if ( state ): self.show() self.update()
Sets the rebuild state for this item. :param state | <bool>
347,043
def custom_template_name(self): base_path = getattr(settings, "CUSTOM_SPECIAL_COVERAGE_PATH", "special_coverage/custom") if base_path is None: base_path = "" return "{0}/{1}_custom.html".format( base_path, self.slug.replace("-", "_") ).lstrip("/")
Returns the path for the custom special coverage template we want.
347,044
def remote_route(self): proxy = self.environ.get() if proxy: return [ip.strip() for ip in proxy.split()] remote = self.environ.get() return [remote] if remote else []
A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients.
347,045
def table(big_array): number_of_columns = len(big_array) number_of_rows_in_column = [len(column) for column in big_array] max_cell_size = [len(max(column, key=len)) for column in big_array] table = [] row_array = [column[0] for column in big_array] table.append(table_row(row_array, pa...
Return a formatted table, generated from arrays representing columns. The function requires a 2-dimensional array, where each array is a column of the table. This will be used to generate a formatted table in string format. The number of items in each columns does not need to be consitent. >>> table([[...
347,046
async def sinterstore(self, dest, keys, *args): res = await self.sinter(keys, *args) await self.delete(dest) if res: await self.sadd(dest, *res) return len(res) else: return 0
Store the intersection of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. Cluster impl: Use sinter() --> Delete dest key --> store result in dest key
347,047
def add_ping(self, rule, status_code=200, app=None): app = self._get_app(app) @app.route(rule) def ping(): return , status_code
Add a ping route. :param str rule: The URL rule. This will not use the API prefix, as the ping endpoint is not really part of the API. :param int status_code: The ping response status code. The default is 200 rather than the more correct 204 because many health checks ...
347,048
def create(self, output_path, dry_run=False, output_format=None, compresslevel=None): if output_format is None: file_name, file_ext = path.splitext(output_path) output_format = file_ext[len(extsep):].lower() self.LOG.debug("Output format is not explicitly set, determ...
Create the archive at output_file_path. Type of the archive is determined either by extension of output_file_path or by output_format. Supported formats are: gz, zip, bz2, xz, tar, tgz, txz @param output_path: Output file path. @type output_path: str @param dry_run: Determines...
347,049
def what_requires(self, name): r = self.local_renderer r.env.name = name r.local()
Lists the packages that require the given package.
347,050
def get_download_urls(self): info = self.model._meta.app_label, self.model._meta.model_name return [ url(r + self.upload_to + , self.file_download_view, name= % info), ]
Use like this: def get_urls(self): return self.get_download_urls() + super().get_urls() Returns: File download URLs for this model.
347,051
def from_tms(cls, tms_x, tms_y, zoom): max_tile = (2 ** zoom) - 1 assert 0 <= tms_x <= max_tile, assert 0 <= tms_y <= max_tile, return cls(tms_x=tms_x, tms_y=tms_y, zoom=zoom)
Creates a tile from Tile Map Service (TMS) X Y and zoom
347,052
def auto_code_block(self, node): assert isinstance(node, nodes.literal_block) original_node = node if not in node: return None self.state_machine.reset(self.document, node.parent, self.current_level) ...
Try to automatically generate nodes for codeblock syntax. Parameters ---------- node : nodes.literal_block Original codeblock node Returns ------- tocnode: docutils node The converted toc tree node, None if conversion is not possible.
347,053
def getLockStatsMode(self): info_dict = {: dict(zip(self.lockModes, (0,) * len(self.lockModes))), : dict(zip(self.lockModes, (0,) * len(self.lockModes)))} cur = self._conn.cursor() cur.execute("SELECT TRIM(mode, ), granted, COUNT(*) FROM pg_locks " ...
Returns the number of active lock discriminated by lock mode. @return: : Dictionary of stats.
347,054
def _get_alphanumeric_index(query_string):
Given an input string of either int or char, returns what index in the alphabet and case it is :param query_string: str, query string :return: (int, str), list of the index and type
347,055
def parse_reqs(req_path=): install_requires = [] with io.open(os.path.join(here, ), encoding=) as handle: lines = (line.strip() for line in handle if line.strip() and not line.startswith()) for line in lines: if line.startswith(): ...
Recursively parse requirements from nested pip files.
347,056
def load_hdf(cls, filename, path=, name=None): if not os.path.exists(filename): raise IOError(.format(filename)) store = pd.HDFStore(filename) try: samples = store[path+] attrs = store.get_storer(path+).attrs except: store.close() ...
A class method to load a saved StarModel from an HDF5 file. File must have been created by a call to :func:`StarModel.save_hdf`. :param filename: H5 file to load. :param path: (optional) Path within HDF file. :return: :class:`StarModel` object.
347,057
def set_info(self, *args, **kwargs) -> None: self.root_logger.setLevel(logging.INFO) try: self.messaging.pub_handler.setLevel(logging.INFO) except Exception: pass
Sets the log level to `INFO`
347,058
def pca_calc(nc, d): ind = ~np.apply_along_axis(any, 1, np.isnan(d)) if any(~ind): pcs = np.full((d.shape[0], nc), np.nan) d = d[ind, :] pca = PCA(nc).fit(d) if any(~ind): pcs[ind, :] = pca.transform(d) else: pcs = pca.transform(d) retur...
Calculates pca of d. Parameters ---------- nc : int Number of components d : np.ndarray An NxM array, containing M observations of N variables. Data must be floats. Can contain NaN values. Returns ------- pca, dt : tuple fitted PCA object, and transf...
347,059
def deserialize(self, value, flags): FLAGS = self.FLAGS if flags & FLAGS[]: value = self.compression.decompress(value) if flags & FLAGS[]: return value if flags & FLAGS[]: return int(value) elif flags & FLAGS[]: return...
Deserialized values based on flags or just return it if it is not serialized. :param value: Serialized or not value. :type value: six.string_types, int :param flags: Value flags :type flags: int :return: Deserialized value :rtype: six.string_types|int
347,060
def get_sql_insert(table: str, fieldlist: Sequence[str], delims: Tuple[str, str] = ("", "")) -> str: return ( "INSERT INTO " + delimit(table, delims) + " (" + ",".join([delimit(x, delims) for x in fieldlist]) + ") VALUES (" + ",".joi...
Returns ?-marked SQL for an INSERT statement.
347,061
def rpcexec(self, payload): if not self.ws: self.connect() log.debug(json.dumps(payload)) self.__lock.acquire() try: self.ws.send(json.dumps(payload, ensure_ascii=False).encode("utf8")) ...
Execute a call by sending the payload :param json payload: Payload data :raises ValueError: if the server does not respond in proper JSON format
347,062
def stop(name, runas=None): * domain_target, path = _get_domain_target(name) return launchctl(, domain_target, path, runas=runas)
Stop a launchd service. Raises an error if the service fails to stop .. note:: Though ``service.stop`` will unload a service in macOS, the service will start on next boot unless it is disabled. Use ``service.disable`` to disable the service :param str name: Service label, file name, o...
347,063
def convert_machine_list_time_val(text: str) -> datetime.datetime: text = text[:14] if len(text) != 14: raise ValueError() year = int(text[0:4]) month = int(text[4:6]) day = int(text[6:8]) hour = int(text[8:10]) minute = int(text[10:12]) second = int(text[12:14]) ...
Convert RFC 3659 time-val to datetime objects.
347,064
def request(self, method, url, callback=None, retry=0, **kwargs): return self.pool.submit( self._request, method=method, url=url, retry=retry, callback=callback or self.default_callback, **kwargs )
Similar to `requests.request`, but return as NewFuture.
347,065
def _get_plotbounds_from_cf(coord, bounds): if bounds.shape[:-1] != coord.shape or bounds.shape[-1] != 2: raise ValueError( "Cannot interprete bounds with shape {0} for {1} " "coordinate with shape {2}.".format( bounds.shape, coord.name, ...
Get plot bounds from the bounds stored as defined by CFConventions Parameters ---------- coord: xarray.Coordinate The coordinate to get the bounds for bounds: xarray.DataArray The bounds as inferred from the attributes of the given `coord` Returns ...
347,066
def export_dict(mesh, encoding=None): def encode(item, dtype=None): if encoding is None: return item.tolist() else: if dtype is None: dtype = item.dtype return util.array_to_encoded(item, dtype=dtype, encoding=encoding) return...
Export a mesh to a dict Parameters ------------ mesh : Trimesh object Mesh to be exported encoding : str, or None 'base64' Returns -------------
347,067
def is_valid_image_extension(file_path): valid_extensions = [, , , ] _, extension = os.path.splitext(file_path) return extension.lower() in valid_extensions
is_valid_image_extension.
347,068
def search_repositories(self, query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None): params = {: query} headers = {} if sort in (, , ): params[] = sort if order in (, ): ...
Find repositories via various criteria. The query can contain any combination of the following supported qualifers: - ``in`` Qualifies which fields are searched. With this qualifier you can restrict the search to just the repository name, description, readme, or any combina...
347,069
def _update_response_location_header(self, resource): location = resource_to_url(resource, request=self.request) loc_hdr = (, location) hdr_names = [hdr[0].upper() for hdr in self.request.response.headerlist] try: idx = hdr_names.index() except ValueError: ...
Adds a new or replaces an existing Location header to the response headers pointing to the URL of the given resource.
347,070
def section_names(self, ordkey="wall_time"): section_names = [] for idx, timer in enumerate(self.timers()): if idx == 0: section_names = [s.name for s in timer.order_sections(ordkey)] ...
Return the names of sections ordered by ordkey. For the time being, the values are taken from the first timer.
347,071
def process_certificates(service_name, relation_id, unit, custom_hostname_link=None, user=, group=): data = relation_get(rid=relation_id, unit=unit) ssl_dir = os.path.join(, service_name) mkdir(path=ssl_dir) name = local_unit().replace(, ) certs = data.get(.format(name)...
Process the certificates supplied down the relation :param service_name: str Name of service the certifcates are for. :param relation_id: str Relation id providing the certs :param unit: str Unit providing the certs :param custom_hostname_link: str Name of custom link to create :param user: (Option...
347,072
def run(self): if self.has_rust_extensions(): log.info("running build_rust") build_rust = self.get_finalized_command("build_rust") build_rust.inplace = self.inplace build_rust.run() _build_ext.run(self)
Run build_rust sub command
347,073
def attach_usage_plan_to_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): usage plan id[{"apiId": "some id 1", "stage": "some stage 1"}] return _update_usage_plan_apis(plan_id, apis, , region=region, key=key, keyid=keyid, profile=profile)
Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: apiId a string, which is the id of the created API in AWS ApiGateway stage ...
347,074
async def _dump_message_field(self, writer, msg, field, fvalue=None): fname, ftype, params = field[0], field[1], field[2:] fvalue = getattr(msg, fname, None) if fvalue is None else fvalue await self.dump_field(writer, fvalue, ftype, params)
Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return:
347,075
def _qsub_block(self, output_dir, error_dir, tid_specs): processes = [] job_names = [] for (tid, spec) in tid_specs: job_name = "%s_%s_tid_%d" % (self.batch_name, self.job_timestamp, tid) job_names.append(job_name) cmd_args = self.command( ...
This method handles static argument specifiers and cases where the dynamic specifiers cannot be queued before the arguments are known.
347,076
def _get_package_data(root, file_patterns=None): if file_patterns is None: file_patterns = [] return _get_files(file_patterns, _glob_pjoin(HERE, root))
Expand file patterns to a list of `package_data` paths. Parameters ----------- root: str The relative path to the package root from `HERE`. file_patterns: list or str, optional A list of glob patterns for the data file locations. The globs can be recursive if they include a `**`...
347,077
def file_variations(filename, extensions): (label, ext) = splitext(filename) return [label + extention for extention in extensions]
Create a variation of file names. Generate a list of variations on a filename by replacing the extension with a the provided list. :param filename: The original file name to use as a base. :param extensions: A list of file extensions to generate new filenames.
347,078
def remove_null(obj): if isinstance(obj, set): try: obj.remove(None) except: pass elif isinstance(obj, list): for item in obj: if not is_not_null(item): obj.remove(item) return obj
reads through a list or set and strips any null values
347,079
def do_local_der(self, filename, keytype, keyusage=None, kid=): _bkey = import_private_rsa_key_from_file(filename) if keytype.lower() != : raise NotImplemented() if not keyusage: keyusage = ["enc", "sig"] else: keyusage = harmonize_usage(key...
Load a DER encoded file amd create a key from it. :param filename: :param keytype: Presently only 'rsa' supported :param keyusage: encryption ('enc') or signing ('sig') or both
347,080
async def download(self, files: Sequence[Union[str, Path]], dest: Union[str, Path] = , show_progress: bool = False): params = {} if self.owner_access_key: params[] = self.owner_access_key rqst = Request(self.session, ...
Downloads the given list of files from the compute session. :param files: The list of file paths in the compute session. If they are relative paths, the path is calculated from ``/home/work`` in the compute session container. :param dest: The destination directory in the client-...
347,081
async def work_async(self): try: raise self._error except TypeError: pass except Exception as e: _logger.warning("%r", e) raise try: await self.lock_async() if self._closing: _logger.debug("C...
Perform a single Connection iteration asynchronously.
347,082
def deauth(self): self.method = None self.key = None self.last_auth = None if self.debug: print("Changing auth key and method to None") if self.rfid.authed: self.rfid.stop_crypto() if self.debug: print("Stopping crypt...
Resets authentication info. Calls stop_crypto() if RFID is in auth state
347,083
def insertmany(self, table, columns, value, ignore=False, commit=True): if not isinstance(value, (list, tuple)): raise TypeError() _sql = .join([, if ignore else , , self._backtick(table), , self._backtick_columns(columns), , .join([] * len(columns...
Insert multiple records within one query. :type table: string :type columns: list :type value: list|tuple :param value: Doesn't support MySQL functions :param value: Example: [(value1_column1, value1_column2,), ] :type ignore: bool :type commit: bool :retu...
347,084
def get_gtf(): size, md5, url = GTF full_gtf = os.path.join(args.data_dir, os.path.basename(url)) subset_gtf = os.path.join( args.data_dir, os.path.basename(url).replace(, % CHROM)) if not _up_to_date(md5, subset_gtf): download(url, full_gtf) cmds = [ ,...
Download GTF file from Ensembl, only keeping the chr17 entries.
347,085
def density_matrix_rotation(J_values, alpha, beta, gamma): r size = sum([2*J+1 for J in J_values]) D = zeros(size, size) ind0 = 0 for J in J_values: DJ = wigner_d(J, alpha, beta, gamma) sizeJ = 2*J+1 indf = ind0 + sizeJ D[ind0: indf, ind0: indf] = DJ ind0 += s...
r"""Return a block-wise diagonal Wigner D matrix for that rotates a density matrix of an ensemble of particles in definite total angular momentum states given by J_values. >>> from sympy import Integer, pi >>> half = 1/Integer(2) >>> J_values = [2*half, 0] >>> density_matrix_rotation(J_values, ...
347,086
def show(keyword=): keyword = keyword.strip().lower() max_len = max(len(k) for k in env.iterkeys()) keyword_found = False for k in sorted(env.keys()): if keyword and keyword not in k.lower(): continue keyword_found = True print( % (k.ljust(max_len),)) ...
Displays a list of all environment key/value pairs for the current role.
347,087
def wait( self, timeout: Union[int, float] = None, safe: bool = False ) -> List[Union[Any, Exception]]: return self.process_list.wait(timeout, safe)
alias for :py:meth:`ProcessList.wait()`
347,088
def get_sizeof_descriptor_table(version="Denali"): if version == "Denali": return sizeof(DescriptorTableDenali) elif version == "Spec20": return sizeof(DescriptorTableSpec20) elif version == "Spec12": return 0 else: raise RuntimeError("Error version!")
Get sizeof DescriptorTable
347,089
def get_filename4code(module, content, ext=None): imagedir = module + "-images" fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest() try: os.mkdir(imagedir) sys.stderr.write( + imagedir + ) except OSError: pass if ext: fn += "." + ext re...
Generate filename based on content The function ensures that the (temporary) directory exists, so that the file can be written. Example: filename = get_filename4code("myfilter", code)
347,090
def copy(self): clone = self.__class__() clone.fields = self.copy_fields_dict(self.fields) clone.default_fields = self.copy_fields_dict(self.default_fields) clone.overloaded_fields = self.overloaded_fields.copy() clone.underlayer = self.underlayer clone.explicit ...
Returns a deep copy of the instance.
347,091
def parse_optimize(self): match = re.search("EQUILIBRIUM GEOMETRY LOCATED", self.text) spmatch = "SADDLE POINT LOCATED" in self.text located = True if match or spmatch else False points = grep_split(" BEGINNING GEOMETRY SEARCH POINT NSERCH=", self.te...
Parse the ouput resulted of a geometry optimization. Or a saddle point.
347,092
def _client_data(self, client): data = {} if client: data[] = client data[] = client.id data[] = client.absolute_url() data[] = to_utf8(client.getName()) return data
Returns a dict that represents the client specified Keys: obj, id, url, name
347,093
def terminate(self, uuid): request_url = self._client.base_api_url + self.terminate_url.format( id=uuid ) response = self._client.session.post(request_url) self.validate_request_success( response_text=response.text, request...
Terminate the task instance with given UUID. Args: uuid (str): The UUID of the task instance to terminate. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance that wa...
347,094
def create_similar_image(self, content, width, height): return Surface._from_pointer( cairo.cairo_surface_create_similar_image( self._pointer, content, width, height), incref=False)
Create a new image surface that is as compatible as possible for uploading to and the use in conjunction with this surface. However, this surface can still be used like any normal image surface. Initially the surface contents are all 0 (transparent if contents have transparency, black o...
347,095
def RIBNextHopLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs): config = ET.Element("config") RIBNextHopLimitExceeded = ET.SubElement(config, "RIBNextHopLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.SubElement(RIBN...
Auto Generated Code
347,096
def immutable(function): def wrapper(self, *args, **kwargs): state = freeze(self._get_state()) return function(self, state, *args, **kwargs) return wrapper
Add the instance internal state as the second parameter of the decorated function.
347,097
def perform_update(self, data, instance): for key, val in data.items(): setattr(instance, key, val)
Hook for controlling the update of an model instance. Override this if you need to do more with your data before updating the object than just mapping the deserialized data to the attribute of the instance.
347,098
def store_meta(self,meta): "Inplace method that adds meta information to the meta dictionary" if self.meta is None: self.meta = {} self.meta.update(meta) return self
Inplace method that adds meta information to the meta dictionary
347,099
def int_to_array(i, length=2): res = [] for dummy in range(0, length): res.append(i & 0xff) i = i >> 8 return reversed(res)
Convert an length byte integer to an array of bytes.