code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def create_symlink(self, file_path, link_target, create_missing_dirs=True): if (not self._is_link_supported()): raise OSError('Symbolic links are not supported on Windows before Python 3.2') file_path = self.make_string_path(file_path) link_target = self.make_string_path(link_target) file_path =...
Create the specified symlink, pointed at the specified link target. Args: file_path: path to the symlink to create link_target: the target of the symlink create_missing_dirs: If `True`, any missing parent directories of file_path will be created Returns: The newly created FakeFile object. Raises: OSError: if the s...
codesearchnet
def _parse_resource(self, uri: str, json_obj: Dict[str, Any]) -> Optional[_T]: json_parser = _json_parser.JsonParser(self.handler, self.resource_time_zone) resource_type = json_obj.get('resourceType') if resource_type is None: raise ValueError(f'JSON for URI {uri} does not have a resource type.') ...
Parses a protocol buffer for the given JSON object. Args: uri: The URI of the resource to parse. json_obj: The JSON object to parse into a proto. Returns: The protocol buffer for the resource or `None` if it can not be found.
github-repos
def get_subdomain(url): if url not in URLHelper.__cache: URLHelper.__cache[url] = urlparse(url) return ".".join(URLHelper.__cache[url].netloc.split(".")[:-2])
Get the subdomain of the given URL. Args: url (str): The URL to get the subdomain from. Returns: str: The subdomain(s)
juraj-google-style
def macro_tpm_sbs(self, state_by_state_micro_tpm): validate.tpm(state_by_state_micro_tpm, check_independence=False) mapping = self.make_mapping() num_macro_states = 2 ** len(self.macro_indices) macro_tpm = np.zeros((num_macro_states, num_macro_states)) micro_states = ...
Create a state-by-state coarse-grained macro TPM. Args: micro_tpm (nd.array): The state-by-state TPM of the micro-system. Returns: np.ndarray: The state-by-state TPM of the macro-system.
juraj-google-style
def get_dataset(self, name): url = (self.url() + '/resource/dataset/{}'.format(name)) req = self.remote_utils.get_url(url) if (req.status_code is not 200): raise RemoteDataNotFoundError('Could not find {}'.format(req.text)) else: return req.json()
Returns info regarding a particular dataset. Arugments: name (str): Dataset name Returns: dict: Dataset information
codesearchnet
def _process_tensorlike(inputs): def _convert_numpy_and_scipy(x): if isinstance(x, np.ndarray): dtype = None if issubclass(x.dtype.type, np.floating): dtype = backend.floatx() return tensor_conversion.convert_to_tensor_v2_with_dispatch(x, dtype=dtype) ...
Process tensor-like inputs. This function: (1) Converts `Numpy` arrays to `Tensor`s. (2) Converts `Scipy` sparse matrices to `SparseTensor`s. (2) Converts `list`s to `tuple`s (for `tf.data` support). Args: inputs: Structure of `Tensor`s, `NumPy` arrays, or tensor-like. Returns: Structure of `Tensor`s or tensor-like...
github-repos
def convert_gather(params, w_name, scope_name, inputs, layers, weights, names): print('Converting embedding ...') if names == 'short': tf_name = 'EMBD' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) weights_name ...
Convert gather (embedding) layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
juraj-google-style
def aggregate_field(self, field, combine_fn, dest): return _GroupAndAggregate(self, ()).aggregate_field(field, combine_fn, dest)
Returns a grouping operation that also aggregates grouped values. Args: field: indicates the field to be aggregated combine_fn: indicates the aggregation function to be used dest: indicates the name that will be used for the aggregate in the output May be called repeatedly to aggregate multiple fields, e.g. GroupBy(...
github-repos
def uniform_full_int(self, shape, dtype=dtypes.uint64, name=None): dtype = dtypes.as_dtype(dtype) with ops.name_scope(name, 'stateful_uniform_full_int', [shape]) as name: shape = _shape_tensor(shape) return self._uniform_full_int(shape=shape, dtype=dtype, name=name)
Uniform distribution on an integer type's entire range. This method is the same as setting `minval` and `maxval` to `None` in the `uniform` method. Args: shape: the shape of the output. dtype: (optional) the integer type, default to uint64. name: (optional) the name of the node. Returns: A tensor of random numbers o...
github-repos
def connection_made(self, transport): self.transport = transport self.transport.sendto(self.message) self.transport.close()
Create connection, use to send message and close. Args: transport (asyncio.DatagramTransport): Transport used for sending.
juraj-google-style
def _get_bradcrack_data(bravais): r json_file = pkg_resources.resource_filename(__name__, 'bradcrack.json') with open(json_file, 'r') as f: bradcrack_data = load_json(f) return bradcrack_data[bravais]
r"""Read Bradley--Cracknell k-points path from data file Args: bravais (str): Lattice code including orientation e.g. 'trig_p_c' Returns: dict: kpoint path and special point locations, formatted as e.g.:: {'kpoints': {'\Gamma': [0., 0., 0.], 'X': [0., 0.5, 0.], ...}, 'path': [['\Gamma', 'X', ..., 'P'], ['H', 'N', .....
juraj-google-style
def replace_tensors_by_numpy_ndarrays(repr_ds: RepresentativeDataset, sess: session.Session) -> RepresentativeDataset: new_repr_ds = [] for sample in repr_ds: new_sample = {} for input_key, input_data in sample.items(): if isinstance(input_data, core.Tensor): input_da...
Replaces tf.Tensors in samples by their evaluated numpy arrays. Note: This should be run in graph mode (default in TF1) only. Args: repr_ds: Representative dataset to replace the tf.Tensors with their evaluated values. `repr_ds` is iterated through, so it may not be reusable (e.g. if it is a generator object). sess: ...
github-repos
def _BuildScanTreeNode(self, path_filter_table, ignore_list): paths_list = list(path_filter_table.paths) ignore_list = list(ignore_list) similarity_weights = _PathSegmentWeights() occurrence_weights = _PathSegmentWeights() value_weights = _PathSegmentWeights() for path_segment_index in path_filt...
Builds a scan tree node. Args: path_filter_table: a path filter table object (instance of _PathFilterTable). ignore_list: a list of path segment indexes to ignore, where 0 is the index of the first path segment relative from the root. Returns: A scan tree node (instance of PathFilterScanTreeNode). Raises: ValueError...
codesearchnet
def closest_distance(item_a, time_a, item_b, time_b, max_value): return (np.minimum(item_a.closest_distance(time_a, item_b, time_b), max_value) / float(max_value))
Euclidean distance between the pixels in item_a and item_b closest to each other. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distance value used as scaling ...
codesearchnet
def predict_next_action(self, state_key, next_action_list): if self.q_df is not None: next_action_q_df = self.q_df[self.q_df.state_key == state_key] next_action_q_df = next_action_q_df[next_action_q_df.action_key.isin(next_action_list)] if next_action_q_df.shape[0] =...
Predict next action by Q-Learning. Args: state_key: The key of state in `self.t+1`. next_action_list: The possible action in `self.t+1`. Returns: The key of action.
juraj-google-style
def member_of(self, group): if isinstance(group, Group): group = group.name return self.groups.filter(name=group).exists()
Returns whether a user is a member of a certain group. Args: group The name of a group (string) or a group object Returns: Boolean
juraj-google-style
def maybe_copy_file_to_directory(source_filepath, target_directory): if not tf.gfile.Exists(target_directory): tf.logging.info("Creating directory %s" % target_directory) os.mkdir(target_directory) target_filepath = os.path.join(target_directory, os.path.basename(source_f...
Copy a file to a directory if it is not already there. Returns the target filepath. Args: source_filepath: a string target_directory: a string Returns: a string
juraj-google-style
def from_path(cls, path, suffix=''): def _get_filepath(filename): name_pattern = (((filename + suffix) + '*') if (filename != 'POTCAR') else (filename + '*')) paths = glob.glob(os.path.join(path, name_pattern)) fpath = None if (len(paths) >= 1): paths.sort(reverse=True) ...
Convenient constructor that takes in the path name of VASP run to perform Bader analysis. Args: path (str): Name of directory where VASP output files are stored. suffix (str): specific suffix to look for (e.g. '.relax1' for 'CHGCAR.relax1.gz').
codesearchnet
def _get_file_names(file_pattern, shuffle): if isinstance(file_pattern, list): if not file_pattern: raise ValueError('Argument `file_pattern` should not be empty.') file_names = [] for entry in file_pattern: file_names.extend(gfile.Glob(entry)) else: file_...
Parse list of file names from pattern, optionally shuffled. Args: file_pattern: File glob pattern, or list of glob patterns. shuffle: Whether to shuffle the order of file names. Returns: List of file names matching `file_pattern`. Raises: ValueError: If `file_pattern` is empty, or pattern matches no files.
github-repos
def normalize(inputs, epsilon=1e-08, scope='ln'): with tf.variable_scope(scope): inputs_shape = inputs.get_shape() params_shape = inputs_shape[(- 1):] (mean, variance) = tf.nn.moments(inputs, [(- 1)], keep_dims=True) beta = tf.Variable(tf.zeros(params_shape)) gamma = tf.Varia...
Applies layer normalization. Args: inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. epsilon: A floating number. A very small number for preventing ZeroDivision Error. scope: Optional scope for `variable_scope`. reuse: Boolean, whether to reuse the weights of a previous layer by t...
codesearchnet
def version(self, api_version=True): url = self._url('/version', versioned_api=api_version) return self._result(self._get(url), json=True)
Returns version information from the server. Similar to the ``docker version`` command. Returns: (dict): The server version information Raises: :py:class:`docker.errors.APIError` If the server returns an error.
codesearchnet
def latlong_to_locator(latitude, longitude): if ((longitude >= 180) or (longitude <= (- 180))): raise ValueError if ((latitude >= 90) or (latitude <= (- 90))): raise ValueError longitude += 180 latitude += 90 locator = chr((ord('A') + int((longitude / 20)))) locator += chr((ord('...
converts WGS84 coordinates into the corresponding Maidenhead Locator Args: latitude (float): Latitude longitude (float): Longitude Returns: string: Maidenhead locator Raises: ValueError: When called with wrong or invalid input args TypeError: When args are non float values Example: The following example converts la...
codesearchnet
def set_status(self, status: Status, increment_try_count: bool=True, filename: str=None): url = self.url_record.url assert (not self._try_count_incremented), (url, status) if increment_try_count: self._try_count_incremented = True _logger.debug(__('Marking URL {0} status {1}.', url, status)) ...
Mark the item with the given status. Args: status: a value from :class:`Status`. increment_try_count: if True, increment the ``try_count`` value
codesearchnet
def Environ(variable, default): precondition.AssertType(variable, Text) value = os.environ.get(variable, default) if (value is None): return default if PY2: value = value.decode('utf-8') return value
A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given variable.
codesearchnet
def template_instance(self): ofs = self.offset() if ((self.unpack_byte(0) & 15) == 15): ofs += 4 return TemplateInstanceNode(self._buf, ofs, self._chunk, self)
parse the template instance node. this is used to compute the location of the template definition structure. Returns: TemplateInstanceNode: the template instance.
codesearchnet
def next(self): if (self._mode != 'r'): raise UnsupportedOperation("not available in 'w' mode") self._n += 1 if (self._n > self._nb_markers): raise StopIteration() return (self._bim.index[(self._n - 1)], self._read_current_marker())
Returns the next marker. Returns: tuple: The marker name as a string and its genotypes as a :py:class:`numpy.ndarray`.
codesearchnet
def cdnode(self, astr_path): l_absPath = [] (b_valid, l_absPath) = self.b_pathInTree(astr_path) if b_valid: self.l_cwd = l_absPath[:] self.snode_current = self.snode_root self.sbranch_current = self.sbranch_root for node in l_absPath[1:]: self.snode_current = self...
Change working node to astr_path. The path is converted to a list, split on '/'. By performing a 'cd' all parent and derived nodes need to be updated relative to new location. Args: astr_path (string): The path to cd to. Returns: {"status" : True/False , "path": l_cwd -- the path as list}
codesearchnet
def delete_vnet(access_token, subscription_id, resource_group, name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
Delete a virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. name (str): Name of the VNet. Returns: HTTP response. VNet JSON body.
codesearchnet
def next_moments_operating_on(self, qubits: Iterable[ops.Qid], start_moment_index: int=0) -> Dict[(ops.Qid, int)]: next_moments = {} for q in qubits: next_moment = self.next_moment_operating_on([q], start_moment_index) next_moments[q] = (len(self._moments) if (next_moment is None) else next_mome...
Finds the index of the next moment that touches each qubit. Args: qubits: The qubits to find the next moments acting on. start_moment_index: The starting point of the search. Returns: The index of the next moment that touches each qubit. If there is no such moment, the next moment is specified as the number of moment...
codesearchnet
def rename(self, container, name): url = self._url('/containers/{0}/rename', container) params = {'name': name} res = self._post(url, params=params) self._raise_for_status(res)
Rename a container. Similar to the ``docker rename`` command. Args: container (str): ID of the container to rename name (str): New name for the container Raises: :py:class:`docker.errors.APIError` If the server returns an error.
codesearchnet
def find_faces(self, image, draw_box=False): frame_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) faces = self.cascade.detectMultiScale(frame_gray, scaleFactor=1.3, minNeighbors=5, minSize=(50, 50), flags=0) if draw_box: for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), ((x + w), (...
Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale method for cascades.
codesearchnet
def plot_thermodynamic_properties(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) mol = ('' if self.structure else '-c') fig = self._plot_thermo(self.dos.cv, temperatures, ylabel='Thermodynamic properties', ylim=ylim, label='$C_v$ (J/K/mol{})'.format(mol), **kwar...
Plots all the thermodynamic properties in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. Returns: matplotlib figure
codesearchnet
def get_item(self, name, bootstrap=False): for item in self._get_items(bootstrap): if (item.name == name): return item return None
Get a particular item in the specification. Args: name (str): The name of the item to retrieve. bootstrap (bool): Only search bootstrap items Returns (YapconfItem): A YapconfItem if it is found, None otherwise.
codesearchnet
def gradient_summaries(grad_vars, groups=None, scope='gradients'): groups = (groups or {'all': '.*'}) grouped = collections.defaultdict(list) for (grad, var) in grad_vars: if (grad is None): continue for (name, pattern) in groups.items(): if re.match(pattern, var.name...
Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor.
codesearchnet
def process_messages(self, max_messages=10000): subscribe_clients = [self.primary_subscribe_client] for subscribe_client in subscribe_clients: for _ in range(max_messages): message = subscribe_client.get_message() if message is None: ...
Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning.
juraj-google-style
def signHostCsr(self, xcsr, signas, outp=None, sans=None): pkey = xcsr.get_pubkey() name = xcsr.get_subject().CN return self.genHostCert(name, csr=pkey, signas=signas, outp=outp, sans=sans)
Signs a host CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. sans (list): List of subject alternative names. Examples: Sign a host key with the CA "myca": cdir.sig...
codesearchnet
def cctop_check_status(jobid): status = 'http: status_text = requests.post(status) return status_text.text
Check the status of a CCTOP job ID. Args: jobid (str): Job ID obtained when job was submitted Returns: str: 'Finished' if the job is finished and results ready to be downloaded, 'Running' if still in progress, 'Invalid' for any errors.
codesearchnet
def _add_task(cls, worker_task, mapreduce_spec, queue_name): if not _run_task_hook(mapreduce_spec.get_hooks(), "enqueue_worker_task", worker_task, queue_name): try: ...
Schedule slice scanning by adding it to the task queue. Args: worker_task: a model.HugeTask task for slice. This is NOT a taskqueue task. mapreduce_spec: an instance of model.MapreduceSpec. queue_name: Optional queue to run on; uses the current queue of execution or the default queue if unspecified.
juraj-google-style
def write_files(dos, pdos, prefix=None, directory=None, zero_to_efermi=True): if (len(dos.densities) == 1): sdata = [[Spin.up, 1, '']] else: sdata = [[Spin.up, 1, '(up)'], [Spin.down, (- 1), '(down)']] header = ['energy'] eners = ((dos.energies - dos.efermi) if zero_to_efermi else dos.en...
Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. pdos (dict): The projected density of states. Formatted as a :obj:`dict` of :obj:`dict` mapping the elements and their orbitals to...
codesearchnet
def has_apical_dendrite(neuron, min_number=1, treefun=_read_neurite_type): types = [treefun(n) for n in neuron.neurites] return CheckResult(types.count(NeuriteType.apical_dendrite) >= min_number)
Check if a neuron has apical dendrites Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of apical dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result
juraj-google-style
def cursor_event(self, x, y, dx, dy): self.sys_camera.rot_state(x, y)
The standard mouse movement event method. Can be overriden to add new functionality. By default this feeds the system camera with new values. Args: x: The current mouse x position y: The current mouse y position dx: Delta x postion (x position difference from the previous event) dy: Delta y postion (y position differe...
codesearchnet
def _get_default_retry_params(): default = getattr(_thread_local_settings, 'default_retry_params', None) if ((default is None) or (not default.belong_to_current_request())): return RetryParams() else: return copy.copy(default)
Get default RetryParams for current request and current thread. Returns: A new instance of the default RetryParams.
codesearchnet
def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True): if (parallelism.n == 1): return x if maybe_reduce: original_parallelism = parallelism (parallelism, x) = reduce_by_device(parallelism, x, tf.add_n) if (parallelism.n == 1): y = x else: x_fl...
Compute the sum of all Tensors and put the result everywhere. Assumes that the devices are connected in a ring. Args: x: a list of Tensors with length parallelism.n parallelism: a expert_utils.Parallelism object. maybe_reduce: a boolean - first reduce per device. use_bfloat16: a boolean - saves bandwidth but loses pr...
codesearchnet
def run(self, env: env_tools.PreparedEnv, verbose: bool, previous_failures: Set['Check']) -> CheckResult: if previous_failures.intersection(self.dependencies): print(shell_tools.highlight(('Skipped ' + self.command_line_switch()), shell_tools.YELLOW)) return CheckResult(self, False, 'Skipped due to ...
Evaluates this check. Args: env: The prepared python environment to run the check in. verbose: When set, more progress output is produced. previous_failures: Checks that have already run and failed. Returns: A CheckResult instance.
codesearchnet
def tag(self, name, action='ADD', params=None): if not name: self._tcex.handle_error(925, ['name', 'tag', 'name', 'name', name]) if not self.can_update(): self._tcex.handle_error(910, [self.type]) if action in ['GET', 'ADD', 'DELETE']: return self.t...
Adds a tag to a Indicator/Group/Victim/Security Label Args: params: action: name: The name of the tag
juraj-google-style
def connect_with(self, wire_char): if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1: return for label, affected_bits in self.connections: if not affected_bits: continue affected_bits[0].connect(wire_char, [...
Connects the elements in the layer using wire_char. Args: wire_char (char): For example '║' or '│'.
juraj-google-style
def step(self, action, blocking=True): promise = self.call('step', action) if blocking: return promise() else: return promise
Step the environment. Args: action: The action to apply to the environment. blocking: Whether to wait for the result. Returns: Transition tuple when blocking, otherwise callable that returns the transition tuple.
juraj-google-style
def random_string(): numpy_state = np.random.get_state() np.random.seed(None) random_id = np.random.bytes(ray_constants.ID_SIZE) np.random.set_state(numpy_state) return random_id
Generate a random string to use as an ID. Note that users may seed numpy, which could cause this function to generate duplicate IDs. Therefore, we need to seed numpy ourselves, but we can't interfere with the state of the user's random number generator, so we extract the state of the random number generator and reset ...
codesearchnet
def verify_task_in_task_graph(task_link, graph_defn, level=logging.CRITICAL): ignore_keys = ('created', 'deadline', 'expires', 'dependencies', 'schedulerId') errors = [] runtime_defn = deepcopy(task_link.task) bad_deps = (set(runtime_defn['dependencies']) - set(graph_defn['task']['dependencies'])) b...
Verify a given task_link's task against a given graph task definition. This is a helper function for ``verify_link_in_task_graph``; this is split out so we can call it multiple times when we fuzzy match. Args: task_link (LinkOfTrust): the link to try to match graph_defn (dict): the task definition from the task-graph...
codesearchnet
def _validate_state_root(self, state_root): if (self._state_root_regex.fullmatch(state_root) is None): LOGGER.debug('Invalid state root: %s', state_root) raise _ResponseFailed(self._status.INVALID_ROOT)
Validates a state root, raising a ResponseFailed error if invalid. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be sent with the response.
codesearchnet
def _get_node_dependencies(self, proto): dependencies = {ref.local_name: ref.node_id for ref in proto.dependencies} kind = proto.WhichOneof('kind') if kind == 'function': concrete_functions = proto.function.concrete_functions for fn_name in concrete_functions: for bound_input in ...
Returns a dictionary of all dependencies of an object. Args: proto: A SavedObject proto. Returns: Dict mapping string dependency name *or* int node id to the node id. The int node id key is used for mapping function captures.
github-repos
def mnist_generator(tmp_dir, training, how_many, start_from=0): _get_mnist(tmp_dir) d = _MNIST_TRAIN_DATA_FILENAME if training else _MNIST_TEST_DATA_FILENAME l = _MNIST_TRAIN_LABELS_FILENAME if training else _MNIST_TEST_LABELS_FILENAME return mnist_common_generator(tmp_dir, training, how_many, d, l, start_fr...
Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which image to start. Returns: An instance of image_generator that produces MNIST images.
juraj-google-style
def _get_function_inputs(f, src_kwargs): if hasattr(f, '_func'): f = f._func try: argspec = inspect.getfullargspec(f) except AttributeError: argspec = inspect.getargspec(f) fkwargs = {k: v for (k, v) in six.iteritems(src_kwargs) if (k in argspec.args)} return fkwargs
Filters inputs to be compatible with function `f`'s signature. Args: f: Function according to whose input signature we filter arguments. src_kwargs: Keyword arguments to filter according to `f`. Returns: kwargs: Dict of key-value pairs in `src_kwargs` which exist in `f`'s signature.
codesearchnet
def to_pil_image(self, image, rescale=None): self._ensure_format_supported(image) if is_torch_tensor(image): image = image.numpy() if isinstance(image, np.ndarray): if rescale is None: rescale = isinstance(image.flat[0], np.floating) if image.ndim == 3 and image.shape[0] ...
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if needed. Args: image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`): The image to convert to the PIL Image format. rescale (`bool`, *optional*): Whether or not to apply the scaling factor (to make p...
github-repos
def index_filename_rel_other_index(self, other: str) -> str: return relpath(self.index_filename, start=dirname(other))
Returns the filename of this index, relative to the director of another index. (For inserting a reference to this index into ``other``.) Args: other: the other index Returns: relative filename of our index
juraj-google-style
def delete_device(self, auth_body, device_id): content = { "auth": auth_body } return self._send("DELETE", "/devices/%s" % device_id, content=content)
Deletes the given device, and invalidates any access token associated with it. NOTE: This endpoint uses the User-Interactive Authentication API. Args: auth_body (dict): Authentication params. device_id (str): The device ID of the device to delete.
juraj-google-style
def __init__(self, columns: list[str], hub_url: str, **kwargs): super().__init__(columns=columns, **kwargs) self.model_uri = hub_url
Embedding config for tensorflow hub models. This config can be used with MLTransform to embed image data. Models are loaded using the RunInference PTransform with the help of a ModelHandler. Args: columns: The columns containing the images to be embedded. hub_url: The url of the tensorflow hub model. min_batch_size: T...
github-repos
def set_default_backend(self, backend_name): if (backend_name not in BACKENDS): raise ValueError(f"Unknown backend '{backend_name}'.") self._default_backend = backend_name
Set the default backend of this circuit. This setting is only applied for this circuit. If you want to change the default backend of all gates, use `BlueqatGlobalSetting.set_default_backend()`. After set the default backend by this method, global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()`...
codesearchnet
def _accept(random_sample: float, cost_diff: float, temp: float) -> Tuple[(bool, float)]: exponent = ((- cost_diff) / temp) if (exponent >= 0.0): return (True, 1.0) else: probability = math.exp(exponent) return ((probability > random_sample), probability)
Calculates probability and draws if solution should be accepted. Based on exp(-Delta*E/T) formula. Args: random_sample: Uniformly distributed random number in the range [0, 1). cost_diff: Cost difference between new and previous solutions. temp: Current temperature. Returns: Tuple of boolean and float, with boolean ...
codesearchnet
def locked_get(self): credential = self._backend.locked_get(self._key) if (credential is not None): credential.set_store(self) return credential
Retrieves the current credentials from the store. Returns: An instance of :class:`oauth2client.client.Credentials` or `None`.
codesearchnet
def target_encode_plus(self, answer: str, add_special_tokens: bool=True, padding: Union[bool, str, PaddingStrategy]=False, truncation: Optional[Union[bool, str]]=None, max_length: Optional[int]=None, pad_to_multiple_of: Optional[int]=None, return_tensors: Optional[Union[str, TensorType]]=None, return_token_type_ids: Op...
Prepare a answer string for the model. Args: answer `str`: Corresponding answer supervision to the queries for training the model.
github-repos
def software_breakpoint(self): software_types = [enums.JLinkBreakpoint.SW_RAM, enums.JLinkBreakpoint.SW_FLASH, enums.JLinkBreakpoint.SW] return any(((self.Type & stype) for stype in software_types))
Returns whether this is a software breakpoint. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance Returns: ``True`` if the breakpoint is a software breakpoint, otherwise ``False``.
codesearchnet
def get_program_by_title(self, program_title): all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[]) matching_programs = [program for program in all_programs if (program.get('title') == program_title)] if (len(matching_programs) > 1): raise MultipleProgramMatchError(len(matching_program...
Return single program by name, or None if not found. Arguments: program_title(string): Program title as seen by students and in Course Catalog Admin Returns: dict: Program data provided by Course Catalog API
codesearchnet
def to_element(self): if (not self.protocol_info): raise DIDLMetadataError('Could not create Element for thisresource:protocolInfo not set (required).') root = XML.Element('res') root.attrib['protocolInfo'] = self.protocol_info if (self.import_uri is not None): root.attrib['importUri'] =...
Return an ElementTree Element based on this resource. Returns: ~xml.etree.ElementTree.Element: an Element.
codesearchnet
def _findSourceLine(self, annotated_source, line_number): index = None for i, line in enumerate(annotated_source.lines): if line.startswith('L%d ' % line_number): index = i break return index
Find line of given line number in annotated source. Args: annotated_source: (debugger_cli_common.RichTextLines) the annotated source line_number: (int) 1-based line number Returns: (int) If line_number is found, 0-based line index in annotated_source.lines. Otherwise, None.
github-repos
def loadfn(fname): if ((fnmatch(fname, '*POSCAR*') or fnmatch(fname, '*CONTCAR*') or ('.cif' in fname.lower())) or fnmatch(fname, '*.vasp')): return Structure.from_file(fname) elif fnmatch(fname, '*vasprun*'): from pymatgen.io.vasp import Vasprun return Vasprun(fname) elif fnmatch(fn...
Convenience method to perform quick loading of data from a filename. The type of object returned depends the file type. Args: fname (string): A filename. Returns: Note that fname is matched using unix-style, i.e., fnmatch. (Structure) if *POSCAR*/*CONTCAR*/*.cif (Vasprun) *vasprun* (obj) if *json* (passthrough to mon...
codesearchnet
def create_extended_model(model, db_penalty=None, ex_penalty=None, tp_penalty=None, penalties=None): model_extended = model.create_metabolic_model() extra_compartment = model.extracellular_compartment compartment_ids = set((c.id for c in model.compartments)) if (len(compartment_ids) > 0): logger...
Create an extended model for gap-filling. Create a :class:`psamm.metabolicmodel.MetabolicModel` with all reactions added (the reaction database in the model is taken to be the universal database) and also with artificial exchange and transport reactions added. Return the extended :class:`psamm.metabolicmodel.Metabolic...
codesearchnet
def query(self, coords): gal = coords l = gal.l.deg b = gal.b.deg scalar_input = not hasattr(l, '__len__') if scalar_input: l = np.array([l]) b = np.array([b]) ebv = np.empty(l.shape, dtype='f8') ebv[:]...
Returns E(B-V) at the specified location(s) on the sky. Args: coords (`astropy.coordinates.SkyCoord`): The coordinates to query. Returns: A float array of reddening, in units of E(B-V), at the given coordinates. The shape of the output is the same as the shape of the coordinates stored by `coords`.
juraj-google-style
def tabulate_filetypes_rest(attrnames=None, header=None, flag_wrap_description=True, description_width=40, flag_leaf=True): infos = get_filetypes_info(editor_quote='``', flag_leaf=flag_leaf) (rows, header) = filetypes_info_to_rows_header(infos, attrnames, header, flag_wrap_description, description_width) re...
Generates a reST multirow table Args: attrnames: list of attribute names (keys of FILE_TYPE_INFO_ATTRS). Defaults to all attributes header: list of strings containing headers. If not passed, uses default names flag_wrap_description: whether to wrap the description text description_width: width to wrap the description ...
codesearchnet
def swo_set_host_buffer_size(self, buf_size): buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST, ctypes.byref(buf)) if (res < 0): raise errors.JLinkException(res) return None
Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error
codesearchnet
def peek(init, exposes, debug=False): def _peek(store, container, _stack=None): args = [store.peek(objname, container, _stack=_stack) for objname in exposes] if debug: print(args) return init(*args) return _peek
Default deserializer factory. Arguments: init (callable): type constructor. exposes (iterable): attributes to be peeked and passed to `init`. Returns: callable: deserializer (`peek` routine).
codesearchnet
def authenticate(self, email=None, password=None, source=None): from gdata.service import BadAuthentication Api.yt_service.email = (email if email else settings.YOUTUBE_AUTH_EMAIL) Api.yt_service.password = (password if password else settings.YOUTUBE_AUTH_PASSWORD) Api.yt_service.source = (source if sou...
Authenticates the user and sets the GData Auth token. All params are optional, if not set, we will use the ones on the settings, if no settings found, raises AttributeError params are email, password and source. Source is the app id Raises: gdata.service.exceptions.BadAuthentication
codesearchnet
def export_mt_variants(variants, sample_id): document_lines = [] for variant in variants: line = [] position = variant.get('position') change = '>'.join([variant.get('reference'),variant.get('alternative')]) line.append(position) line.append(change) line.appe...
Export mitochondrial variants for a case to create a MT excel report Args: variants(list): all MT variants for a case, sorted by position sample_id(str) : the id of a sample within the case Returns: document_lines(list): list of lines to include in the document
juraj-google-style
def step(self, actions): observations, raw_rewards, dones, infos = self._step(actions) raw_rewards = raw_rewards.astype(np.float32) processed_rewards = self.process_rewards(raw_rewards) processed_observations = self.process_observations(observations) self.trajectories.step(pr...
Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observations, processed_rewards, dones, infos).
juraj-google-style
def set_local_interface(self, value=None, default=False, disable=False): return self._configure_mlag('local-interface', value, default, disable)
Configures the mlag local-interface value Args: value (str): The value to configure the local-interface default (bool): Configures the local-interface using the default keyword disable (bool): Negates the local-interface using the no keyword Returns: bool: Returns True if the commands complete successfully
codesearchnet
def getSlicesForText(self, body, getFingerprint=None, startIndex=0, maxResults=10): return self._text.getSlicesForText(self._retina, body, getFingerprint, startIndex, maxResults)
Get a list of slices of the text Args: body, str: The text to be evaluated (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per page (optional) Returns: list of Text ...
juraj-google-style
def __call__(self, parser, namespace, value, option_string=None, **kwargs): handle = copen(value, mode=self.mode, **self.kwargs) setattr(namespace, self.dest, handle)
Detects and opens compressed files Args: parser (ArgumentParser): parser used to generate values namespace (Namespace): namespace to set values for value (str): actual value specified by user option_string (str): argument flag used to call this function **kwargs (various): optional arguments later passed to the co...
juraj-google-style
def send(self, message): body = {'notificationType': self._notification_type, 'priority': self._priority, 'isOrganization': self._is_organization, 'message': message} if self._recipients: body['recipients'] = self._recipients self._tcex.log.debug('notification body: {}'.format(json.dumps(body))) ...
Send our message Args: message (str): The message to be sent. Returns: requests.models.Response: The response from the request.
codesearchnet
def from_filename(filename, require=None): with io.open(filename, 'r', encoding='utf-8') as json_file: data = json.load(json_file) return data, from_dict(data, require=require)
Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance.
juraj-google-style
def add_showcases(self, showcases, showcases_to_check=None): if (showcases_to_check is None): showcases_to_check = self.get_showcases() allshowcasesadded = True for showcase in showcases: if (not self.add_showcase(showcase, showcases_to_check=showcases_to_check)): allshowcasesadd...
Add dataset to multiple showcases Args: showcases (List[Union[Showcase,Dict,str]]): A list of either showcase ids or showcase metadata from Showcase objects or dictionaries showcases_to_check (List[Showcase]): list of showcases against which to check existence of showcase. Defaults to showcases containing dataset. Re...
codesearchnet
def _any(objs, query): for obj in objs: if isinstance(obj, Document): if _any(obj.roots, query): return True elif any((query(ref) for ref in obj.references())): return True else: return False
Whether any of a collection of objects satisfies a given query predicate Args: objs (seq[Model or Document]) : query (callable) Returns: True, if ``query(obj)`` is True for some object in ``objs``, else False
codesearchnet
def get_first_model_with_rest_name(cls, rest_name): models = cls.get_models_with_rest_name(rest_name) if (len(models) > 0): return models[0] return None
Get the first model corresponding to a rest_name Args: rest_name: the rest name
codesearchnet
def nuc_v(msg): tc = typecode(msg) if tc != 19: raise RuntimeError("%s: Not an airborne velocity message, expecting TC = 19" % msg) msgbin = common.hex2bin(msg) NUCv = common.bin2int(msgbin[42:45]) try: HVE = uncertainty.NUCv[NUCv]['HVE'] VVE = uncertainty.NUCv[NUCv]...
Calculate NUCv, Navigation Uncertainty Category - Velocity (ADS-B version 1) Args: msg (string): 28 bytes hexadecimal message string, Returns: int or string: 95% Horizontal Velocity Error int or string: 95% Vertical Velocity Error
juraj-google-style
def run(self, dag): self.layout = (self.layout or self.property_set['layout']) if (self.layout is None): raise TranspilerError('EnlargeWithAncilla requires property_set["layout"] or "layout" parameter to run') layout_virtual_qubits = self.layout.get_virtual_bits().keys() new_qregs = set((virtual...
Extends dag with virtual qubits that are in layout but not in the circuit yet. Args: dag (DAGCircuit): DAG to extend. Returns: DAGCircuit: An extended DAG. Raises: TranspilerError: If there is not layout in the property set or not set at init time.
codesearchnet
def FromString(val): if isinstance(val, bytes): val = val.decode('utf-8') try: return ContractParameterType[val] except Exception as e: pass try: if isinstance(val, (bytearray, bytes)): int_val = int.from_bytes(val, 'little') else: int_val ...
Create a ContractParameterType object from a str Args: val (str): the value to be converted to a ContractParameterType. val can be hex encoded (b'07'), int (7), string int ("7"), or string literal ("String") Returns: ContractParameterType
codesearchnet
def _create_typed_object_meta(get_fset): def _get_fget(attr, private_attr, type_): 'Create a property getter method for an attribute.\n\n Args:\n attr: The name of the attribute that will be retrieved.\n private_attr: The name of the attribute that will store any data\n ...
Create a metaclass for typed objects. Args: get_fset: A function that takes three parameters: the name of an attribute, the name of the private attribute that holds the property data, and a type. This function must an object method that accepts a value. Returns: A metaclass that reads annotations from a class definit...
codesearchnet
def convert_to_tensors(self, inputs, tensor_type: Optional[Union[str, TensorType]]=None, prepend_batch_axis: bool=False): if not isinstance(tensor_type, TensorType): tensor_type = TensorType(tensor_type) if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportE...
Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If unset, no modification is done. prepend_batch_axis (`int`, *optional*, defaults to `False`): Whether or not to ad...
github-repos
def get_vocab(self, vocab_name, **kwargs): vocab_dict = self.__get_vocab_dict__(vocab_name, **kwargs) filepaths = list(set([os.path.join(self.cache_dir, vocab_dict['filename']), os.path.join(self.vocab_dir, ...
Returns data stream of an rdf vocabulary args: vocab_name: the name or uri of the vocab to return
juraj-google-style
def meta_features_path(self, path): return (os.path.join(path, app.config['XCESSIV_META_FEATURES_FOLDER'], str(self.id)) + '.npy')
Returns path for meta-features Args: path (str): Absolute/local path of xcessiv folder
codesearchnet
def normalize_genotypes(genotypes): genotypes = genotypes.genotypes return (genotypes - np.nanmean(genotypes)) / np.nanstd(genotypes)
Normalize the genotypes. Args: genotypes (Genotypes): The genotypes to normalize. Returns: numpy.array: The normalized genotypes.
juraj-google-style
def __init__(self, value, opaque_type, name='Opaque Object'): super(OpaqueObject, self).__init__() self._object_type = enums.ObjectType.OPAQUE_DATA self.value = value self.opaque_type = opaque_type self.names.append(name) self._digest = None ...
Create a OpaqueObject. Args: value(bytes): The bytes representing opaque data. opaque_type(OpaqueDataType): An enumeration defining the type of the opaque value. name(string): The string name of the opaque object.
juraj-google-style
def _RDFClass(cls, table): rdf_cls_name = 'OsqueryTable{}'.format(hash(table.query)) try: return cls._rdf_cls_cache[rdf_cls_name] except KeyError: pass rdf_cls = compatibility.MakeType(rdf_cls_name, (rdf_structs.RDFProtoStruct,), {}) rdf_cls.AddDescriptor(rdf_structs.ProtoEmbedded(na...
Creates a dynamic RDF proto struct class for given osquery table. The fields of the proto will correspond to the columns of the table. Args: table: An osquery table for which the class is about to be generated. Returns: A class object corresponding to the given table.
codesearchnet
def getbalance(self, user_id="", as_decimal=True): balance = unicode(self.rpc.call("getbalance", user_id)) self.logger.debug("\"" + user_id + "\"", self.coin, "balance:", balance) if as_decimal: return Decimal(balance) else: return balance
Calculate the total balance in all addresses belonging to this user. Args: user_id (str): this user's unique identifier as_decimal (bool): balance is returned as a Decimal if True (default) or a string if False Returns: str or Decimal: this account's total coin balance
juraj-google-style
def _inject(self, value, settings): assert isinstance(value, string_types), 'Expected str; got {0.__class__}'.format(value) begin, end = '{{', '}}' if begin not in value: return value, False new_value = value begin_pos, end_pos = 0, None len_begin,...
Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the value of the named item from ``settings``. Args: value (str): The value to inject settings into settings: An object that provides the dotted access interface Returns: (str, bool): The new value an...
juraj-google-style
def intent(self, user: str = None, token: Optional[str] = None) -> "IntentAPI": if self.is_real_user: raise ValueError("Can't get child intent of real user") if token: return IntentAPI(user, self.real_user(user, token), self.bot_intent(), self.state_store, ...
Get the intent API for a specific user. Args: user: The Matrix ID of the user whose intent API to get. Returns: The IntentAPI for the given user.
juraj-google-style
def __get_default_value_from_element(self, element): if (element.name == 'select'): options = element.find_all('option') is_multiple = element.has_attr('multiple') selected_options = [option for option in options if option.has_attr('selected')] if ((not selected_options) and options)...
Get the default value of a form element Args: elements (obj): The soup element. Returns: str: The default value
codesearchnet
class RMSprop(Optimizer): def __init__(self, lr=0.001, rho=0.9, epsilon=None, decay=0.0, **kwargs): super(RMSprop, self).__init__(**kwargs) with backend.name_scope(self.__class__.__name__): self.lr = backend.variable(lr, name='lr') self.rho = backend.variable(rho, name='rho'...
RMSProp optimizer. It is recommended to leave the parameters of this optimizer at their default values (except the learning rate, which can be freely tuned). Args: lr: float >= 0. Learning rate. rho: float >= 0. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `backend.epsilon()`. decay: float >= 0. Learning ...
github-repos
def handle_message_registered(self, msg_data, host): response = None if (msg_data['method'] == 'EVENT'): logger.debug(('<%s> <euuid:%s> Event message received' % (msg_data['cuuid'], msg_data['euuid']))) response = self.event(msg_data['cuuid'], host, msg_data['euuid'], msg_data['event_data'], msg...
Processes messages that have been delivered by a registered client. Args: msg (string): The raw packet data delivered from the listener. This data will be unserialized and then processed based on the packet's method. host (tuple): The (address, host) tuple of the source message. Returns: A response that will be sent ...
codesearchnet
def __init__(self, **kwargs): try: arguments = Adapter(Schema(ApplicationOptions.SCHEMA).validate(kwargs)) self.definition = arguments.definition self.matrix_tags = [entry for entry in arguments.matrix_tags.split(',') if len(entry) > 0] self.tags = [entry...
Initializing and validating fields. Args: kwargs (dict): application command line options.
juraj-google-style
def get(self, id=None, **kwargs): server_data = self.gitlab.http_get(self.path, **kwargs) if server_data is None: return None return self._obj_cls(self, server_data)
Retrieve a single object. Args: **kwargs: Extra options to send to the server (e.g. sudo) Returns: object: The generated RESTObject Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: If the server cannot perform the request
juraj-google-style