Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
370,300
def weighted_rand(weights, round_result=False): return random.choice(weights)[0]
Generate a non-uniform random value based on a list of weight tuples. Treats weights as coordinates for a probability distribution curve and rolls accordingly. Constructs a piece-wise linear curve according to coordinates given in ``weights`` and rolls random values in the curve's bounding box until a ...
370,301
def _put_attributes_using_post(self, domain_or_name, item_name, attributes, replace=True, expected_value=None): domain, domain_name = self.get_domain_and_name(domain_or_name) params = {: domain_name, : item_name} self._build_name_value_list(params, attribute...
Monkey-patched version of SDBConnection.put_attributes that uses POST instead of GET The GET version is subject to the URL length limit which kicks in before the 256 x 1024 limit for attribute values. Using POST prevents that. https://github.com/BD2KGenomics/toil/issues/502
370,302
def _get_roles_query(self, session, identifier): return (session.query(Role). join(role_membership_table, Role.pk_id == role_membership_table.c.role_id). join(User, role_membership_table.c.user_id == User.pk_id). filter(User.identifier == identifier))
:type identifier: string
370,303
def show(dataset_uri): try: dataset = dtoolcore.ProtoDataSet.from_uri( uri=dataset_uri, config_path=CONFIG_PATH ) except dtoolcore.DtoolCoreTypeError: dataset = dtoolcore.DataSet.from_uri( uri=dataset_uri, config_path=CONFIG_PATH ...
Show the descriptive metadata in the readme.
370,304
def Result(self, res): if isinstance(res, str): text = res elif res: text = "yes" else: text = "no" if self.did_show_result == 0: self.Display(text + "\n") self.did_show_result = 1
Inform about the result of the test. If res is not a string, displays 'yes' or 'no' depending on whether res is evaluated as true or false. The result is only displayed when self.did_show_result is not set.
370,305
def create_anonymous_client(cls): client = cls(project="<none>", credentials=AnonymousCredentials()) client.project = None return client
Factory: return client with anonymous credentials. .. note:: Such a client has only limited access to "public" buckets: listing their contents and downloading their blobs. :rtype: :class:`google.cloud.storage.client.Client` :returns: Instance w/ anonymous credentials and...
370,306
def get_all_memberships( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership" ...
Retrieve all memberships updated since "since_when" Loop over queries of size limit_to until either a non-full queryset is returned, or max_depth is reached (used in tests). Then the recursion collapses to return a single concatenated list.
370,307
def includeme(config): settings = _parse_settings(config.registry.settings) base_settings = _get_proxy_settings(settings) if not settings.get(, False): config.add_tween() root = settings.get(, ) if not os.path.exists(root): os.makedirs(root) capakey_settings = ...
Include `crabpy_pyramid` in this `Pyramid` application. :param pyramid.config.Configurator config: A Pyramid configurator.
370,308
def on_key_press(self, event): key = event.key if event.modifiers: return if self.enable_keyboard_pan and key in self._arrows: self._pan_keyboard(key) if key in self._pm: self._zoom_keyboard(key) ...
Pan and zoom with the keyboard.
370,309
def send_message(self, payload): self.l.info("Creating outbound message request") result = ms_client.create_outbound(payload) self.l.info("Created outbound message request") return result
Create a post request to the message sender
370,310
def fetch(self, category=CATEGORY_MESSAGE, offset=DEFAULT_OFFSET, chats=None): if not offset: offset = DEFAULT_OFFSET kwargs = {"offset": offset, "chats": chats} items = super().fetch(category, **kwargs) return items
Fetch the messages the bot can read from the server. The method retrieves, from the Telegram server, the messages sent with an offset equal or greater than the given. A list of chats, groups and channels identifiers can be set using the parameter `chats`. When it is set, only those ...
370,311
def url_unparse(components): scheme, netloc, path, query, fragment = \ normalize_string_tuple(components) s = make_literal_wrapper(scheme) url = s() if netloc or (scheme and path.startswith(s())): if path and path[:1] != s(): path = s() + path ...
The reverse operation to :meth:`url_parse`. This accepts arbitrary as well as :class:`URL` tuples and returns a URL as a string. :param components: the parsed URL as tuple which should be converted into a URL string.
370,312
def token_list_len(tokenlist): ZeroWidthEscape = Token.ZeroWidthEscape return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)
Return the amount of characters in this token list. :param tokenlist: List of (token, text) or (token, text, mouse_handler) tuples.
370,313
def plot_somas(somas): _, ax = common.get_figure(new_fig=True, subplot=111, params={: , : }) for s in somas: common.plot_sphere(ax, s.center, s.radius, color=random_color(), alpha=1) plt.show()
Plot set of somas on same figure as spheres, each with different color
370,314
def to_properties(cls, config, compact=False, indent=2, key_stack=[]): def escape_value(value): return value.replace(, ).replace(, ).replace(, ).replace(, ) stripped_key_stack = [key.strip() for key in key_stack] lines = [] if isinstance(config, ConfigTree): ...
Convert HOCON input into a .properties output :return: .properties string representation :type return: basestring :return:
370,315
def scan_processes_and_threads(self): our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) found_tids = set() if our_pid in dead_pids: dead_pids.remove(our_pid) dwFla...
Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. ...
370,316
def options(self, context, module_options): if not in module_options: context.log.error() exit(1) if module_options[].lower() not in [, ]: context.log.error() exit(1) self.action = module_options[].lower()
ACTION Enable/Disable RDP (choices: enable, disable)
370,317
def flair_template_sync(self, editable, limit, static, sort, use_css, use_text): if not use_text and not use_css: raise Exception() sorts = (, ) if sort not in sorts: raise Exception(.format(.join(sorts))) ...
Synchronize templates with flair that already exists on the site. :param editable: Indicates that all the options should be editable. :param limit: The minimum number of users that must share the flair before it is added as a template. :param static: A list of flair templates that w...
370,318
def set_iscsi_initiator_info(self, initiator_iqn): if(self._is_boot_mode_uefi() is True): iscsi_uri = self._check_iscsi_rest_patch_allowed() initiator_info = {: initiator_iqn} status, headers, response = self._rest_patch(iscsi_uri, ...
Set iSCSI initiator information in iLO. :param initiator_iqn: Initiator iqn for iLO. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the system is in the bios boot mode.
370,319
def dump_response_data(response_schema, response_data, status_code=200, headers=None, response_format=None): if response_schema: response_data = response_schema.dump(response_data).data return make_response...
Dumps response data as JSON using the given schema. Forces JSON encoding even if the client did not specify the `Accept` header properly. This is friendlier to client and test software, even at the cost of not distinguishing HTTP 400 and 406 errors.
370,320
def create_dir(self, directory_path, perm_bits=PERM_DEF): directory_path = self.make_string_path(directory_path) directory_path = self.absnormpath(directory_path) self._auto_mount_drive_if_needed(directory_path) if self.exists(directory_path, check_link=True): self.r...
Create `directory_path`, and all the parent directories. Helper method to set up your test faster. Args: directory_path: The full directory path to create. perm_bits: The permission bits as set by `chmod`. Returns: The newly created FakeDirectory object. ...
370,321
def retention_schedule(name, retain, strptime_format=None, timezone=None): name = os.path.expanduser(name) ret = {: name, : {: [], : [], : []}, : True, : } if not name: return _error(ret, ) if not os.path.isdir(name): return _error(ret, ) a...
Apply retention scheduling to backup storage directory. .. versionadded:: 2016.11.0 :param name: The filesystem path to the directory containing backups to be managed. :param retain: Delete the backups, except for the ones we want to keep. The N below should be an integer but may ...
370,322
def info(name, root=None): * if root is not None: getspnam = functools.partial(_getspnam, root=root) else: getspnam = functools.partial(spwd.getspnam) try: data = getspnam(name) ret = { : data.sp_namp if hasattr(data, ) else data.sp_nam, : data.sp...
Return information for the specified user name User to get the information for root Directory to chroot into CLI Example: .. code-block:: bash salt '*' shadow.info root
370,323
def rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False): if rad: anglerad = angle else: anglerad = angle / 57.29578 axis = utils.versor(axis) a = np.cos(anglerad / 2) b, c, d = -axis * np.sin(anglerad / 2) aa, bb, cc, dd =...
Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`.
370,324
def refresh(self): response = requests.get( % (API_BASE_URL, self.id)) attributes = response.json() self.category = Category(attributes[]) self.url = attributes[] self.title = attributes[] if attributes[]: self.image = Image(attributes[][]) else: ...
Refetch instance data from the API.
370,325
def write_report(self, output_file): logger.debug("Writing the assembly report into: {}".format( output_file)) with open(output_file, "w") as fh: for contig_id, vals in self.report.items(): fh.write("{}, {}\\n".format(contig_id, vals))
Writes a report with the test results for the current assembly Parameters ---------- output_file : str Name of the output assembly file.
370,326
def _append(self, menu): from wx_loader import wx menu.AppendMenu(-1, self.name, self.wx_menu())
append this menu item to a menu
370,327
def _handle_end_relation(self): self._result.append(Relation(result=self._result, **self._curr)) self._curr = {}
Handle closing relation element
370,328
def Incr(self, x, term=1): self.d[x] = self.d.get(x, 0) + term
Increments the freq/prob associated with the value x. Args: x: number value term: how much to increment by
370,329
def salsa20_8(B): x = B[:] for i in (8, 6, 4, 2): a = (x[0] + x[12]) & 0xffffffff x[4] ^= ((a << 7) | (a >> 25)) a = (x[4] + x[0]) & 0xffffffff x[8] ^= ((a << 9) | (a >> 23)) a = (...
Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20
370,330
def check_network_role(self, public_key): state_root = self._current_root_func() if state_root == INIT_ROOT_KEY: LOGGER.debug("Chain head is not set yet. Permit all.") return True self._cache.update_view(state_root) role = self._cache.get_role("network",...
Check the public key of a node on the network to see if they are permitted to participate. The roles being checked are the following, from first to last: "network" "default" The first role that is set will be the one used to enforce if the ...
370,331
def proxy_schema(self): for option in self.options: if option.number == defines.OptionRegistry.PROXY_SCHEME.number: return option.value return None
Get the Proxy-Schema option of a request. :return: the Proxy-Schema values or None if not specified by the request :rtype : String
370,332
def cfg_to_args(config): kwargs = {} opts_to_args = { : [ (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), ...
Compatibility helper to use setup.cfg in setup.py.
370,333
def select_color(cpcolor, evalcolor, idx=0): color = utilities.color_generator() if isinstance(cpcolor, str): color[0] = cpcolor if isinstance(cpcolor, (list, tuple)): color[0] = cpcolor[idx] if isinstance(evalcolor, str): color[1] = evalcolor ...
Selects item color for plotting. :param cpcolor: color for control points grid item :type cpcolor: str, list, tuple :param evalcolor: color for evaluated points grid item :type evalcolor: str, list, tuple :param idx: index of the current geometry object :type idx: int :return: a list of col...
370,334
def search_alert_entities(self, **kwargs): kwargs[] = True if kwargs.get(): return self.search_alert_entities_with_http_info(**kwargs) else: (data) = self.search_alert_entities_with_http_info(**kwargs) return data
Search over a customer's non-deleted alerts # 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_alert_entities(async_req=True) >>> result = thread.get() ...
370,335
def get_aliases(self): for index, desc in self.get_metadata().indices.items(): if not desc["aliases"]: yield wrap({"index": index}) elif desc[][0] == index: Log.error("should not happen") else: for a in desc["aliases"]:...
RETURN LIST OF {"alias":a, "index":i} PAIRS ALL INDEXES INCLUDED, EVEN IF NO ALIAS {"alias":Null}
370,336
def set(self, value): if self.validate(value): self.hasvalue = True if isinstance(value, float): self.value = round(value) else: self.value = int(value) return True else: return...
This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter
370,337
def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor: "Compute accuracy when `y_pred` and `y_true` are the same size." if sigmoid: y_pred = y_pred.sigmoid() return ((y_pred>thresh)==y_true.byte()).float().mean()
Compute accuracy when `y_pred` and `y_true` are the same size.
370,338
def aggregate_groups(self, ct_agg, nr_groups, skip_key, carray_factor, groupby_cols, agg_ops, dtype_dict, bool_arr=None): dimension for col in groupby_cols: result_array = ctable_ext.groupby_value(self[col], carray_factor, ...
Perform aggregation and place the result in the given ctable. Args: ct_agg (ctable): the table to hold the aggregation nr_groups (int): the number of groups (number of rows in output table) skip_key (int): index of the output row to remove from results (used for filtering) ...
370,339
def sys_pipes_forever(encoding=_default_encoding): global _mighty_wurlitzer if _mighty_wurlitzer is None: _mighty_wurlitzer = sys_pipes(encoding) _mighty_wurlitzer.__enter__()
Redirect all C output to sys.stdout/err This is not a context manager; it turns on C-forwarding permanently.
370,340
def consume(self): try: bytes = self.read() except IOError: bytes = self.truncate() if len(bytes) > 0: self.write(bytes) self.seek(0)
Chops the tail off the stream starting at 0 and ending at C{tell()}. The stream pointer is set to 0 at the end of this function. @since: 0.4
370,341
def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): : dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter...
Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The...
370,342
def __update_service_status(self, statuscode): if self.__service_status != statuscode: self.__service_status = statuscode self.__send_service_status_to_frontend()
Set the internal status of the service object, and notify frontend.
370,343
def copy(self: BoardT, *, stack: Union[bool, int] = True) -> BoardT: board = super().copy() board.chess960 = self.chess960 board.ep_square = self.ep_square board.castling_rights = self.castling_rights board.turn = self.turn board.fullmove_number = self.fullmove...
Creates a copy of the board. Defaults to copying the entire move stack. Alternatively, *stack* can be ``False``, or an integer to copy a limited number of moves.
370,344
def get_class(classname, all=False): try: classes = _registry[classname] except KeyError: raise RegistryError( .format(classname)) if len(classes) > 1: if all: return _registry[classname] raise RegistryError( .format(class...
Retrieve a class from the registry. :raises: marshmallow.exceptions.RegistryError if the class cannot be found or if there are multiple entries for the given class name.
370,345
def get_path(self, api_info): path = self.__path or if path and path[0] == : path = path[1:] else: if api_info.path: path = % (api_info.path, if path else , path) parts = path.split() for n, part in enumerate(parts): r = _VALID_PART_RE if n < len...
Get the path portion of the URL to the method (for RESTful methods). Request path can be specified in the method, and it could have a base path prepended to it. Args: api_info: API information for this API, possibly including a base path. This is the api_info property on the class that's bee...
370,346
def sort_by(self, sb): self._dataset = self._dataset.sort(key=lambda x: x.pubdate, reverse=True) return self
Sort results
370,347
def read(filename, loader=None, implicit_tuple=True, allow_errors=False): with open(filename, ) as f: return reads(f.read(), filename=filename, loader=loader, implicit_tuple=implicit_tuple, allow_errors=allow_errors)
Load but don't evaluate a GCL expression from a file.
370,348
async def get_auth(request): auth_val = request.get(AUTH_KEY) if auth_val: return auth_val auth_policy = request.get(POLICY_KEY) if auth_policy is None: raise RuntimeError() request[AUTH_KEY] = await auth_policy.get(request) return request[AUTH_KEY]
Returns the user_id associated with a particular request. Args: request: aiohttp Request object. Returns: The user_id associated with the request, or None if no user is associated with the request. Raises: RuntimeError: Middleware is not installed
370,349
def raw_request(self, method, resource, access_token=None, **kwargs): headers = self._pop_headers(kwargs) headers[] = self._get_authorization_header(access_token) url = self._get_resource_url(resource) return self.session.request(method, url, allow_redirects=True, headers=header...
Makes a HTTP request and returns the raw :class:`~requests.Response` object.
370,350
def groupby_task_class(self): class2tasks = OrderedDict() for task in self.iflat_tasks(): cls = task.__class__ if cls not in class2tasks: class2tasks[cls] = [] class2tasks[cls].append(task) return class2tasks
Returns a dictionary mapping the task class to the list of tasks in the flow
370,351
def get_relative_airmass(zenith, model=): kastenyoung1989kastenyoung1989simplekasten1966youngirvine1967kastenyoung1989gueymard1993young1994pickering2002 z = np.where(zenith > 90, np.nan, zenith) zenith_rad = np.radians(z) model = model.lower() if == model: am = (1.0 / (np.cos(z...
Gives the relative (not pressure-corrected) airmass. Gives the airmass at sea-level when given a sun zenith angle (in degrees). The ``model`` variable allows selection of different airmass models (described below). If ``model`` is not included or is not valid, the default model is 'kastenyoung1989'. ...
370,352
def complete_path(curr_dir, last_dir): if not last_dir or curr_dir.startswith(last_dir): return curr_dir elif last_dir == : return os.path.join(last_dir, curr_dir)
Return the path to complete that matches the last entered component. If the last entered component is ~, expanded path would not match, so return all of the available paths. :param curr_dir: str :param last_dir: str :return: str
370,353
def lock_retention_policy(self, client=None): if "metageneration" not in self._properties: raise ValueError("Bucket has no retention policy assigned: try ?") policy = self._properties.get("retentionPolicy") if policy is None: raise ValueError("Bucket has no ret...
Lock the bucket's retention policy. :raises ValueError: if the bucket has no metageneration (i.e., new or never reloaded); if the bucket has no retention policy assigned; if the bucket's retention policy is already locked.
370,354
def flush_on_close(self, stream): assert get_thread_ident() == self.ioloop_thread_id stream.KATCPServer_closing = True return stream.write()
Flush tornado iostream write buffer and prevent further writes. Returns a future that resolves when the stream is flushed.
370,355
def write_to_file(src, dst): n = 0 for block in src: dst.write(block) n += len(block) return n
Write data from `src` into `dst`. Args: src (iterable): iterable that yields blocks of data to write dst (file-like object): file-like object that must support .write(block) Returns: number of bytes written to `dst`
370,356
def _set_default_versions(self, config): out = [] for name in ["gatk", "gatk4", "picard", "mutect"]: v = tz.get_in(["resources", name, "version"], config) if not v: try: v = programs.get_version(name, config=config) exc...
Retrieve pre-computed version information for expensive to retrieve versions. Starting up GATK takes a lot of resources so we do it once at start of analysis.
370,357
def p_class_constant_declaration(p): if len(p) == 6: p[0] = p[1] + [ast.ClassConstant(p[3], p[5], lineno=p.lineno(2))] else: p[0] = [ast.ClassConstant(p[2], p[4], lineno=p.lineno(1))]
class_constant_declaration : class_constant_declaration COMMA STRING EQUALS static_scalar | CONST STRING EQUALS static_scalar
370,358
def decamel(string): regex = re.compile(r) return regex.sub(r, string)
Split CamelCased words. CamelCase -> Camel Case, dromedaryCase -> dromedary Case.
370,359
def _proxy(self): if self._context is None: self._context = SyncListPermissionContext( self._version, service_sid=self._solution[], list_sid=self._solution[], identity=self._solution[], ) return self._contex...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SyncListPermissionContext for this SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncLi...
370,360
def _post(url, headers, body, retries=3, timeout=3.0): retry = 0 out = None while out is None: try: out = requests.post(url, headers=headers, data=body, timeout=timeout) except (requests.exceptions.Timeout, ...
Try 3 times to request the content. :param headers: The HTTP headers :type headers: dict :param body: The body of the HTTP post :type body: str :param retries: The number of times to retry before giving up :type retries: int :param timeout: The time to wait for the post to complete, before ...
370,361
def download_data(url, signature, data_home=None, replace=False, extract=True): data_home = get_data_home(data_home) basename = os.path.basename(url) name, _ = os.path.splitext(basename) archive = os.path.join(data_home, basename) datadir = os.path.join(data_home, name) if...
Downloads the zipped data set specified at the given URL, saving it to the data directory specified by ``get_data_home``. This function verifies the download with the given signature and extracts the archive. Parameters ---------- url : str The URL of the dataset on the Internet to GET ...
370,362
def matches_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): matches = [] if guess: fuzzy = min(fuzzy,80) fuzzy_fragment = min(fuzzy_fragment,70) option_not_in = lambda item,match_list: all([x[0]!=item for x in match_list]) if it...
Returns the members of ``options`` that best matches ``item``. Will prioritize exact matches, then filename-style matching, then fuzzy matching. Returns a tuple of item, index, match type, and fuzziness (if applicable) :item: string to match :options: list of examples...
370,363
def dump(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2, default_name=, **kwargs): to_json(dct, jfile, overwrite=overwrite, dirlevel=dirlevel, sort_keys=sort_keys, indent=indent, default_name=default_name, **kwargs)
output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to overwrite existing files dirlevel : int if jfile is path to folder, defines how many key levels to set as sub-folders ...
370,364
def value(self, observations): input_data = self.input_block(observations) base_output = self.value_backbone(input_data) value_output = self.value_head(base_output) return value_output
Calculate only value head for given state
370,365
def modify(*units): ret = [] for unit in units: for attr, idx in [("energy", 1), ("life", 2), ("shields", 3)]: newValue = getattr(unit, attr) if not newValue: continue new = DebugCommand(unit_value=DebugSetUnitValue( value = newValue, ...
set the unit defined by in-game tag with desired properties NOTE: all units must be owned by the same player or the command fails.
370,366
def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error): logger.debug() device = device_list().get(peripheral) if device is not None: device._set_disconnected() device_list().remove(peripheral)
Called when a device is disconnected.
370,367
def update_description(self, description): desc_node = self.metadata.find() if desc_node is None: log.debug(.format(str(self.iocid))) log.debug() desc_node = ioc_et.make_description_node(description) insert_index = 0 for child in self....
Update the description) of an IOC This creates the description node if it is not present. :param description: Value to set the description too :return: True
370,368
def uncertain_conditional(Xnew_mu, Xnew_var, feat, kern, q_mu, q_sqrt, *, mean_function=None, full_output_cov=False, full_cov=False, white=False): e_mean_Kuf = tf.reshape(e_mean_Kuf, [num_data, num_func, num_ind]) e_fmean_mean = tf.einsum("nqm,mz->nqz", e_mean_Kuf, L...
Calculates the conditional for uncertain inputs Xnew, p(Xnew) = N(Xnew_mu, Xnew_var). See ``conditional`` documentation for further reference. :param Xnew_mu: mean of the inputs, size N x Din :param Xnew_var: covariance matrix of the inputs, size N x Din x Din :param feat: gpflow.InducingFeature object...
370,369
def google(rest): "Look up a phrase on google" API_URL = try: key = pmxbot.config[] except KeyError: return "Configure in config" custom_search = params = dict( key=key, cx=custom_search, q=rest.strip(), ) url = API_URL + urllib.parse.urlencode(params) resp = requests.get(url) resp.raise_for_...
Look up a phrase on google
370,370
def parse_data_to_internal(self, data=None): if data is None: data = parse.getdata(open(self.location_dat, "rb"), argnum=self.argnum, close=True) if self.filetype is "pickle": pickle.dump(data, open(self.location_internal, "wb")) ...
Parse data and save to pickle/hickle
370,371
def find_line(scihdu, refhdu): sci_bin, sci_corner = get_corner(scihdu.header) ref_bin, ref_corner = get_corner(refhdu.header) if (sci_corner[0] == ref_corner[0] and sci_corner[1] == ref_corner[1] and sci_bin[0] == ref_bin[0] and sci_bin[1] == ref_bin[1] and scihdu.da...
Obtain bin factors and corner location to extract and bin the appropriate subset of a reference image to match a science image. If the science image has zero offset and is the same size and binning as the reference image, ``same_size`` will be set to `True`. Otherwise, the values of ``rx``, ``ry``,...
370,372
def count(self, val=True): return sum((elem.count(val) for elem in self._iter_components()))
Get the number of bits in the array with the specified value. Args: val: A boolean value to check against the array's value. Returns: An integer of the number of bits in the array equal to val.
370,373
def get_min_inc_exc(self, inc_set=None, exc_set=None): if inc_set is None and exc_set is None: return {} inc = self.get_evcodes(inc_set, exc_set) exc = set(self.code2nt.keys()).difference(inc) return {:inc} if len(inc) <= len(exc) else {: exc}
Get the user-specified Evidence codes. Return smaller set: include/exclude
370,374
def percent_encode(text, encode_set=DEFAULT_ENCODE_SET, encoding=): s ``quote``, this function accepts a blacklist instead of a whitelist of safe characters. '.join([mapping(char) for char in byte_string])
Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters.
370,375
def periodic_callback(self): if self.stopped: return if not self.scanning and len(self._connections) == 0 and self.connecting_count == 0: self._logger.info("Restarting scan for devices") self.start_scan(self._active_scan) self._logger.i...
Periodic cleanup tasks to maintain this adapter, should be called every second
370,376
async def contains_albums(self, *albums: Sequence[Union[str, Album]]) -> List[bool]: _albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums] return await self.user.http.is_saved_album(_albums)
Check if one or more albums is already saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- albums : Union[Album, str] A sequence of artist objects or spotify IDs
370,377
def main(dimension, iterations): objective_function = minimize(functions.sphere) stopping_condition = max_iterations(iterations) (solution, metrics) = optimize(objective_function=objective_function, domain=Domain(-5.12, 5.12, dimension), ...
Main function to execute gbest GC PSO algorithm.
370,378
def Engauge_2d_parser(lines, flat=False): z_values = [] x_lists = [] y_lists = [] working_xs = [] working_ys = [] new_curve = True for line in lines: if line.strip() == : new_curve = True elif new_curve: z = float(line.split()[1]) ...
Not exposed function to read a 2D file generated by engauge-digitizer; for curve fitting.
370,379
def index(self, config): for subrep_cfg in config: orderings = [s for s in subrep_cfg.get(, ).strip().split() if s] queries = [] for key in orderings: values = getattr(self.layout, % (key, PLURAL_SUFFIX[key]))() ...
Traverse the reports config definition and instantiate reportlets. This method also places figures in their final location.
370,380
def dict2DingoObjDict(data): info_tuple = dict2tuple(data) info_dict = tuple2dict(info_tuple, constructor=DingoObjDict) return info_dict
Turn a dictionary of the form used by DINGO (i.e., a key is mapped to either another dictionary, a list or a value) into a DingoObjDict.
370,381
def _next_unscanned_addr(self, alignment=None): if self._next_addr is None: self._next_addr = self._get_min_addr() curr_addr = self._next_addr else: curr_addr = self._next_addr + 1 if not self._inside_regions(curr_addr): curr_ad...
Find the next address that we haven't processed :param alignment: Assures the address returns must be aligned by this number :return: An address to process next, or None if all addresses have been processed
370,382
def aes_encrypt(base64_encryption_key, data): if isinstance(data, text_type): data = data.encode("UTF-8") aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data = _pad(data) iv_bytes = os.urandom(AES_BLOCK_SIZE) cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv...
Encrypt data with AES-CBC and sign it with HMAC-SHA256 Arguments: base64_encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte string containing the data to be encrypted Retur...
370,383
def count(self, val): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, val) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], val) pos_right =...
Return the number of occurrences of *val* in the list.
370,384
def adapt_array(arr): out = io.BytesIO() np.save(out, arr) out.seek(0) return sqlite3.Binary(out.read())
http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
370,385
def serialize_number(x, fmt=SER_BINARY, outlen=None): ret = b if fmt == SER_BINARY: while x: x, r = divmod(x, 256) ret = six.int2byte(int(r)) + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, b) return ret ...
Serializes `x' to a string of length `outlen' in format `fmt'
370,386
def setupDock(self): self.dock = QtWidgets.QDockWidget("Classes", self) self.dock.setWidget(self.tree) self.dock.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)
Setup empty Dock at startup.
370,387
def get_damage(self, amount: int, target) -> int: if target.immune: self.log("%r is immune to %s for %i damage", target, self, amount) return 0 return amount
Override to modify the damage dealt to a target from the given amount.
370,388
def _check_file_syntax(filename, temp_dir, override_lang=None, enforce=True): def check_python(filename): pyc_path = os.path.join(temp_dir, os.path.basename(filename) + ".pyc") try: if USING_PYTHON2: filename = filename.encode(sys....
Checks that the code in FILENAME parses, attempting to autodetect the language if necessary. Raises IOError if the file cannot be read. Raises DXSyntaxError if there is a problem and "enforce" is True.
370,389
def quiver( x, y, z, u, v, w, size=default_size * 10, size_selected=default_size_selected * 10, color=default_color, color_selected=default_color_selected, marker="arrow", **kwargs ): fig = gcf() _grow_limits(x, y, z) if in kwargs or in kwargs or in kw...
Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w. :param x: {x} :param y: {y} :param z: {z} :param u: {u_dir} :param v: {v_dir} :param w: {w_dir} :param size: {size} :param size_selected: like size, but for selected glyphs ...
370,390
def make_list(obj, cast=True): if isinstance(obj, list): return list(obj) if isinstance(obj, types.GeneratorType): return list(obj) if isinstance(obj, (tuple, set)) and cast: return list(obj) else: return [obj]
Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list.
370,391
def interpolate_to_grid(x, y, z, interp_type=, hres=50000, minimum_neighbors=3, gamma=0.25, kappa_star=5.052, search_radius=None, rbf_func=, rbf_smooth=0, boundary_coords=None): r if boundary_coords is None: boundary_coords = g...
r"""Interpolate given (x,y), observation (z) pairs to a grid based on given parameters. Parameters ---------- x: array_like x coordinate y: array_like y coordinate z: array_like observation value interp_type: str What type of interpolation to use. Available optio...
370,392
def _print_pgfplot_libs_message(data): pgfplotslibs = ",".join(list(data["pgfplots libs"])) tikzlibs = ",".join(list(data["tikz libs"])) print(70 * "=") print("Please add the following lines to your LaTeX preamble:\n") print("\\usepackage[utf8]{inputenc}") print("\\usepackage{fontspec} % ...
Prints message to screen indicating the use of PGFPlots and its libraries.
370,393
def _get_instance_repo(self, namespace): self._validate_namespace(namespace) if namespace not in self.instances: self.instances[namespace] = [] return self.instances[namespace]
Returns the instance repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the instance repository does not cont...
370,394
def _check_init(self, node): if not self.linter.is_message_enabled( "super-init-not-called" ) and not self.linter.is_message_enabled("non-parent-init-called"): return klass_node = node.parent.frame() to_call = _ancestors_to_call(klass_node) not_ca...
check that the __init__ method call super or ancestors'__init__ method
370,395
def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None): from MAVProxy.modules.mavproxy_map import mp_slipmap if vehicle_type is None: vehicle_type = self.vehicle_type_name if name in self.have_vehicle and self.have_vehicle[name] == vehicle_type: ...
add a vehicle to the map
370,396
def clear(self): for n in self.nodes(): if self.nodes[n]["type"] == "variable": self.nodes[n]["value"] = None elif self.nodes[n]["type"] == "function": self.nodes[n]["func_visited"] = False
Clear variable nodes for next computation.
370,397
def size(self) -> Optional[int]: if not self._parts: return 0 total = 0 for part, encoding, te_encoding in self._parts: if encoding or te_encoding or part.size is None: return None total += int( 2 + len(self._boundary...
Size of the payload.
370,398
def _absf(ins): output = _float_oper(ins.quad[2]) output.append() output.extend(_fpush()) return output
Absolute value of top of the stack (48 bits)
370,399
def fit(self, scores, y_true): if self.equal_priors: counter = Counter(y_true) positive, negative = counter[True], counter[False] if positive > negative: majority, minority = True, False n_majority, n_minority = po...
Train calibration Parameters ---------- scores : (n_samples, ) array-like Uncalibrated scores. y_true : (n_samples, ) array-like True labels (dtype=bool).