code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def _construct(configdict, prefix, ua): if not ua: raise UserAgentError("User_agent parameter missing. It can be your project's name for example.") preprefix = configdict.get('preprefix') if preprefix: user_agent = '%s:' % preprefix else: ...
Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text Returns: str: Full user agent string
juraj-google-style
def load(self): if self.loaded: LOGGER.debug('Already loaded') return try: (basepath, dirs, _) = os.walk(self.path).next() except StopIteration: raise MalformedWorkdir(('Empty dir %s' % self.path)) full_path = partial(os.path.join, basepath) found_current = False ...
Loads the prefixes that are available is the workdir Returns: None Raises: MalformedWorkdir: if the wordir is malformed
codesearchnet
def init_app(self, app): app.ldap3_login_manager = self servers = list(self._server_pool) for s in servers: self._server_pool.remove(s) self.init_config(app.config) if hasattr(app, 'teardown_appcontext'): app.teardown_appcontext(self.teardown) else: app.teardown_request(s...
Configures this extension with the given app. This registers an ``teardown_appcontext`` call, and attaches this ``LDAP3LoginManager`` to it as ``app.ldap3_login_manager``. Args: app (flask.Flask): The flask app to initialise with
codesearchnet
def _get_cached_time(self): if (not self._cached_time): self._cached_time = self._meta.datetime.utcnow() return self._cached_time
Method that will allow for consistent modified and archived timestamps. Returns: self.Meta.datetime: This method will return a datetime that is compatible with the current class's datetime library.
codesearchnet
def create_datastore_for_topline(self, delete_first=0, path=None): data = load_yaml(script_dir_plus_file(join('..', 'hdx_datasource_topline.yml'), Resource)) self.create_datastore_from_dict_schema(data, delete_first, path=path)
For tabular data, create a resource in the HDX datastore which enables data preview in HDX using the built in YAML definition for a topline. If path is not supplied, the file is first downloaded from HDX. Args: delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0....
juraj-google-style
def registry_key(self, key_name, value_name, value_type, **kwargs): indicator_obj = RegistryKey(key_name, value_name, value_type, **kwargs) return self._indicator(indicator_obj)
Add Registry Key data to Batch object. Args: key_name (str): The key_name value for this Indicator. value_name (str): The value_name value for this Indicator. value_type (str): The value_type value for this Indicator. confidence (str, kwargs): The threat confidence for this Indicator. date_added (str, kwargs): The dat...
codesearchnet
def step(self, input_stream, value): reading = IOTileReading(input_stream.encode(), self.tick_count, value) self.sensor_graph.process_input(input_stream, reading, self.rpc_executor)
Step the sensor graph through one since input. The internal tick count is not advanced so this function may be called as many times as desired to input specific conditions without simulation time passing. Args: input_stream (DataStream): The input stream to push the value into value (int): The reading value to push a...
juraj-google-style
def df(self): import pandas as pd return pd.concat([w.df(uwi=True) for w in self])
Makes a pandas DataFrame containing Curve data for all the wells in the Project. The DataFrame has a dual index of well UWI and curve Depths. Requires `pandas`. Args: No arguments. Returns: `pandas.DataFrame`.
codesearchnet
def stack_colormap(lower, upper, n=256): A = get_cmap(lower) B = get_cmap(upper) name = "%s-%s" % (A.name, B.name) lin = np.linspace(0, 1, n) return array_cmap(np.vstack((A(lin), B(lin))), name, n=n)
Stacks two colormaps (``lower`` and ``upper``) such that low half -> ``lower`` colors, high half -> ``upper`` colors Args: lower (colormap): colormap for the lower half of the stacked colormap. upper (colormap): colormap for the upper half of the stacked colormap. n (int): Number of colormap steps. Default is ``256...
juraj-google-style
def get_site_orbital_dos(self, site, orbital): return Dos(self.efermi, self.energies, self.pdos[site][orbital])
Get the Dos for a particular orbital of a particular site. Args: site: Site in Structure associated with CompleteDos. orbital: Orbital in the site. Returns: Dos containing densities for orbital of site.
codesearchnet
def get_symmetric_wallace_tensor(self, tau): wallace = self.get_wallace_tensor(tau) return Tensor(0.5 * (wallace + np.transpose(wallace, [2, 3, 0, 1])))
Gets the symmetrized wallace tensor for determining yield strength criteria. Args: tau (3x3 array-like): stress at which to evaluate the wallace tensor.
juraj-google-style
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): if (end == 0): ext = filename_tmpl.split('.')[(- 1)] end = len([name for name in scandir(frame_dir, ext)]) first_file = osp.join(frame_dir, filename_tmpl.format(start))...
Read the frame images from a directory and join them as a video Args: frame_dir (str): The directory containing video frames. video_file (str): Output filename. fps (float): FPS of the output video. fourcc (str): Fourcc of the output video, this should be compatible with the output file type. filename_tmpl (str): File...
codesearchnet
def _FormatDate(self, event): date_time = dfdatetime_posix_time.PosixTimeInMicroseconds( timestamp=event.timestamp) year, month, day_of_month = date_time.GetDate() try: return '{0:04d}-{1:02d}-{2:02d}'.format(year, month, day_of_month) except (TypeError, ValueError): ...
Formats the date. Args: event (EventObject): event. Returns: str: date field.
juraj-google-style
def custom_line_color_map(self, values): if (not isinstance(values, list)): raise TypeError('custom_line_color_map must be a list') self.options['custom_line_color_map'] = values
Set the custom line color map. Args: values (list): list of colors. Raises: TypeError: Custom line color map must be a list.
codesearchnet
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id] if token_ids_1 is not None: output += token_ids_1 + [self.sep_token_id] return output
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A Lxmert sequence has the following format: - single sequence: `[CLS] X [SEP]` - pair of sequences: `[CLS] A [SEP] B [SEP]` Args: token_ids_0 (`List[int]`): List of IDs to which the s...
github-repos
def solve_sweep_wavelength(self, structure, wavelengths, filename='wavelength_n_effs.dat', plot=True): n_effs = [] for w in tqdm.tqdm(wavelengths, ncols=70): structure.change_wavelength(w) self.solve(structure) n_effs.append(np.real(self.n_effs)) if filename: self._write_n_ef...
Solve for the effective indices of a fixed structure at different wavelengths. Args: structure (Slabs): The target structure to solve for modes. wavelengths (list): A list of wavelengths to sweep over. filename (str): The nominal filename to use when saving the effective indices. Defaults to 'wavelength_n_effs.dat'. ...
codesearchnet
def index(self, value, start=0, end=None): try: index = self._dict[value] except KeyError: raise ValueError else: start = self._fix_neg_index(start) end = self._fix_end_index(end) if start <= index and index < end: return index else: raise ValueError
Return the index of value between start and end. By default, the entire setlist is searched. This runs in O(1) Args: value: The value to find the index of start (int): The index to start searching at (defaults to 0) end (int): The index to stop searching at (defaults to the end of the list) Returns: int: The index o...
juraj-google-style
def GetAdGroups(self, client_customer_id, campaign_id): self.client.SetClientCustomerId(client_customer_id) selector = {'fields': ['Id', 'Name', 'Status'], 'predicates': [{'field': 'CampaignId', 'operator': 'EQUALS', 'values': [campaign_id]}, {'field': 'Status', 'operator': 'NOT_EQUALS', 'values': ['REMOVED']}]...
Retrieves all AdGroups for the given campaign that haven't been removed. Args: client_customer_id: str Client Customer Id being used in API request. campaign_id: str id of the campaign for which to fetch ad groups. Returns: list List of AdGroup data objects.
codesearchnet
def indicator(self, indicator_type, summary, **kwargs): indicator_obj = Indicator(indicator_type, summary, **kwargs) return self._indicator(indicator_obj)
Add Indicator data to Batch object. Args: indicator_type (str): The ThreatConnect define Indicator type. summary (str): The value for this Indicator. confidence (str, kwargs): The threat confidence for this Indicator. date_added (str, kwargs): The date timestamp the Indicator was created. last_modified (str, kwargs): ...
codesearchnet
def memory_read8(self, addr, num_bytes, zone=None): return self.memory_read(addr, num_bytes, zone=zone, nbits=8)
Reads memory from the target system in units of bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_bytes (int): number of bytes to read zone (str): memory zone to read from Returns: List of bytes read from the target system. Raises: JLinkException: if memory could not be rea...
codesearchnet
def compile_dependencies(self, sourcepath, include_self=False): items = self.inspector.parents(sourcepath) if include_self: items.add(sourcepath) return filter(None, [self.compile_source(item) for item in items])
Apply compile on all dependencies Args: sourcepath (string): Sass source path to compile to its destination using project settings. Keyword Arguments: include_self (bool): If ``True`` the given sourcepath is add to items to compile, else only its dependencies are compiled.
codesearchnet
def _ParseFileEntry(self, knowledge_base, file_entry): root_key = self._GetPlistRootKey(file_entry) if not root_key: location = getattr(file_entry.path_spec, 'location', '') raise errors.PreProcessFail(( 'Unable to read: {0:s} plist: {1:s} with error: missing root ' 'key.')....
Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessing fails.
juraj-google-style
def to_api_repr(self): resource = copy.deepcopy(self._properties) query_parameters = resource['query'].get('queryParameters') if query_parameters: if (query_parameters[0].get('name') is None): resource['query']['parameterMode'] = 'POSITIONAL' else: resource['query']['...
Build an API representation of the query job config. Returns: dict: A dictionary in the format used by the BigQuery API.
codesearchnet
def imread(path, grayscale=False, size=None, interpolate='bilinear', channel_first=False, as_uint16=False, num_channels=(- 1)): _imread_before(grayscale, num_channels) r_mode = (cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_UNCHANGED) img = _imread_helper(path, r_mode) if (as_uint16 and (img.dtype !...
Read image by cv2 module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (width, height). If None, output img shape depends on the files to read. channel_first (bool): This argument specifies the shape of img is whether (height, width, channel) or (channel, heig...
codesearchnet
def _get_genes(self, variant): ensembl_ids = [] hgnc_symbols = [] for transcript in variant.transcripts: if transcript.ensembl_id: ensembl_ids.append(transcript.ensembl_id) if transcript.hgnc_symbol: hgnc_symbols.append(tr...
Add the genes for a variant Get the hgnc symbols from all transcripts and add them to the variant Args: variant (dict): A variant dictionary Returns: genes (list): A list of Genes
juraj-google-style
def start(self, request: Request) -> Response: if (self._session_state != SessionState.ready): raise RuntimeError('Session not ready') response = Response() (yield from self._prepare_fetch(request, response)) response.file_transfer_size = (yield from self._fetch_size(request)) if request.res...
Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine.
codesearchnet
def indicator(self, data): data = self.get_first_hash(data) super(File, self).indicator(data)
Update the request URI to include the Indicator for specific indicator retrieval. Args: data (string): The indicator value
juraj-google-style
def audio(self, tag, audiodata, step=None, sample_rate=44100): audiodata = onp.array(audiodata) if (step is None): step = self._step else: self._step = step audiodata = onp.clip(onp.squeeze(audiodata), (- 1), 1) if (audiodata.ndim != 1): raise ValueError('Audio data must be 1...
Saves audio. NB: single channel only right now. Args: tag: str: label for this data audiodata: ndarray [Nsamples,]: data between (-1.0,1.0) to save as wave step: int: training step sample_rate: sample rate of passed in audio buffer
codesearchnet
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): super(LocateRequestPayload, self).read(input_buffer, kmip_version=kmip_version) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.MAXIMUM_ITEMS, local_buffer): self._maximum_items...
Read the data encoding the Locate request payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults...
codesearchnet
def changes(self, **kwargs): path = '%s/%s/changes' % (self.manager.path, self.get_id()) return self.manager.gitlab.http_get(path, **kwargs)
List the merge request changes. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabListError: If the list could not be retrieved Returns: RESTObjectList: List of changes
juraj-google-style
def _default_static_lib(self, obj_files): c_compiler = self.F90_COMPILER.c_compiler static_lib_dir = os.path.join(self.build_lib, "bezier", "lib") if not os.path.exists(static_lib_dir): os.makedirs(static_lib_dir) c_compiler.create_static_lib( obj_files, ...
Create a static library (i.e. a ``.a`` / ``.lib`` file). Args: obj_files (List[str]): List of paths of compiled object files.
juraj-google-style
def _get_accumulator(tensor): assert isinstance(tensor.graph, func_graph_module.FuncGraph) def get_func_graph_output(t): for output in tensor.graph.outputs: if output is t: return t identity_op = t.consumers()[0] if identity_op.type == 'Identity' and...
Returns TensorList if any containing accumulated values of tensor. We try to find a pattern of the form: input_tl tensor \ / (TensorListPushBack) | output_tl which satisfies the following conditions: 1. input_tl must be in tensor.graph.inputs. 2. output_tl or Identity(output_tl) must be in tensor.graph.out...
github-repos
def wait_until_finished( self, refresh_period=DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD ): return self.manager.wait_until_finished( uuid=self.uuid, refresh_period=refresh_period )
Wait until a task instance with the given UUID is finished. Args: refresh_period (int, optional): How many seconds to wait before checking the task's status. Defaults to 5 seconds. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: This task instance model after it finished.
juraj-google-style
def _semicircle_integral(dist_bins, idx): r = 1 x1 = dist_bins[idx] x2 = dist_bins[idx + 1] if dist_bins[idx] == 1: area1 = 0.25 * math.pi * r ** 2 else: area1 = 0.5 * ((x1 * math.sqrt(r ** 2 - x1 ** 2)) + ( r ** 2 * math.ata...
An internal method to get an integral between two bounds of a unit semicircle. Used in algorithm to determine bond probabilities. Args: dist_bins: (float) list of all possible bond weights idx: (float) index of starting bond weight Returns: (float) integral of portion of unit semicircle
juraj-google-style
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True): add_regs = set() reg_frag_chk = {} for v in keyregs.values(): reg_frag_chk[v] = {j: False for j in range(len(v))} for k in edge_map.keys(): if (k[0].name in keyregs): reg_frag_chk[k[0]][k[1]] = True ...
Check that wiremap neither fragments nor leaves duplicate registers. 1. There are no fragmented registers. A register in keyregs is fragmented if not all of its (qu)bits are renamed by edge_map. 2. There are no duplicate registers. A register is duplicate if it appears in both self and keyregs but not in edge_map. Ar...
codesearchnet
def sin(duration: int, amp: complex, freq: float = None, phase: float = 0, name: str = None) -> SamplePulse: if freq is None: freq = 1/duration return _sampled_sin_pulse(duration, amp, freq, phase=phase, name=name)
Generates sine wave `SamplePulse`. Args: duration: Duration of pulse. Must be greater than zero. amp: Pulse amplitude. freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle. phase: Pulse phase. name: Name of pulse.
juraj-google-style
def assert_no_new_pyobjects_executing_eagerly(warmup_iters: int=2) -> Callable[[Callable[..., Any]], Callable[..., None]]: def wrap_f(f: Callable[..., Any]) -> Callable[..., None]: def decorator(self: 'TensorFlowTestCase', *args, **kwargs) -> None: with context.eager_mode(): ...
Decorator for asserting that no new Python objects persist after a test. Returns a decorator that runs the test multiple times executing eagerly, first as a warmup and then to let objects accumulate. The warmup helps ignore caches which do not grow as the test is run repeatedly. Useful for checking that there are no ...
github-repos
def _safe_initial_value_from_tensor(name, tensor, op_cache): op = tensor.op new_op = op_cache.get(op.name) if new_op is None: new_op = _safe_initial_value_from_op(name, op, op_cache) op_cache[op.name] = new_op return new_op.outputs[tensor.value_index]
Replace dependencies on variables with their initialized values. Args: name: Variable name. tensor: A `Tensor`. The tensor to replace. op_cache: A dict mapping operation names to `Operation`s. Used to memoize the results so as to avoid creating redundant operations. Returns: A `Tensor` compatible with `tensor`. Any i...
github-repos
async def get_messages(self, name): resp = await self.send_command(OPERATIONS.CMD_QUERY_MESSAGES, {'name': name}, MESSAGES.QueryMessagesResponse, timeout=5.0) return [states.ServiceMessage.FromDictionary(x) for x in resp]
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service
juraj-google-style
def get_scalar_arg_dtypes(self): dtypes = [] for (name, data) in self._kernel_data.items(): dtypes.extend(data.get_scalar_arg_dtypes()) return dtypes
Get the location and types of the input scalars. Returns: list: for every kernel input element either None if the data is a buffer or the numpy data type if if is a scalar.
codesearchnet
def get_estimator(output_dir, train_config, args): target_name = train_config['target_column'] if (is_classification_model(args.model_type) and (target_name not in train_config['categorical_columns'])): raise ValueError('When using a classification model, the target must be a categorical variable.') ...
Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean estimator Raises: Valu...
codesearchnet
def add(self, row): if not self._types: raise wandb.Error( 'TypedTable.set_columns must be called before add.') mapped_row = {} for key, val in row.items(): try: typed_val = self._types[key](val) if hasattr(typed_va...
Add a row to the table. Args: row: A dict whose keys match the keys added in set_columns, and whose values can be cast to the types added in set_columns.
juraj-google-style
def download(cls, root, check=None): path = os.path.join(root, cls.name) check = path if check is None else check if not os.path.isdir(check): for url in cls.urls: if isinstance(url, tuple): url, filename = url else: ...
Download and unzip an online archive (.zip, .gz, or .tgz). Arguments: root (str): Folder to download data to. check (str or None): Folder whose existence indicates that the dataset has already been downloaded, or None to check the existence of root/{cls.name}. Returns: str: Path to extracted dataset.
juraj-google-style
def Delete(self, request, global_params=None): config = self.GetMethodConfig('Delete') return self._RunMethod(config, request, global_params=global_params)
Deletes a snapshot. Args: request: (DataflowProjectsLocationsSnapshotsDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (DeleteSnapshotResponse) The response message.
github-repos
def _parse_networks(self, config): networks = list() regexp = r'network (.+)/(\d+) area (\d+\.\d+\.\d+\.\d+)' matches = re.findall(regexp, config) for (network, netmask, area) in matches: networks.append(dict(network=network, netmask=netmask, area=area)) ret...
Parses config file for the networks advertised by the OSPF process Args: config(str): Running configuration Returns: list: dict: keys: network (str) netmask (str) area (str)
juraj-google-style
def regularizer(name, regularization_fn, name_filter='weights'): regex = re.compile(name_filter) def fn(var_name, variable, phase): if phase is pt.Phase.train and regex.search(var_name): with tf.name_scope(None, name, [variable]): loss = regularization_fn(variable) if loss is not None: ...
Wraps a regularizer in a parameter-function. Args: name: The name scope for this regularizer. regularization_fn: A function with signature: fn(variable) -> loss `Tensor` or `None`. name_filter: A regex that will be used to filter variables by name. Returns: A parameter modification function that adds the loss to the ...
juraj-google-style
def __init__(self, comment=None): super(EventTag, self).__init__() self._event_identifier = None self.comment = comment self.event_entry_index = None self.event_row_identifier = None self.event_stream_number = None self.labels = []
Initializes an event tag attribute container. Args: comment (Optional[str]): comments.
juraj-google-style
def set_input_embeddings(self, value: nn.Module): base_model = getattr(self, self.base_model_prefix, self) if base_model is not self: base_model.set_input_embeddings(value) else: raise NotImplementedError
Set model's input embeddings. Args: value (`nn.Module`): A module mapping vocabulary to hidden states.
github-repos
def get_releasenotes(project_dir=os.curdir, bugtracker_url=''): releasenotes = '' pkg_info_file = os.path.join(project_dir, 'PKG-INFO') releasenotes_file = os.path.join(project_dir, 'RELEASE_NOTES') if os.path.exists(pkg_info_file) and os.path.exists(releasenotes_file): with open(releasenot...
Retrieves the release notes, from the RELEASE_NOTES file (if in a package) or generates it from the git history. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: str: release notes Raises: RuntimeError: If the release notes could not be...
juraj-google-style
def embeddings(idx): embed = [] embed.append((f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight', f'stage{idx}.patch_embed.proj.weight')) embed.append((f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias', f'stage{idx}.patch_embed.proj.bias')) embed.ap...
The function helps in renaming embedding layer weights. Args: idx: stage number in original model
github-repos
def apply(self, func, axis, *args, **kwargs): if callable(func): return self._callable_func(func, axis, *args, **kwargs) elif isinstance(func, dict): return self._dict_func(func, axis, *args, **kwargs) elif is_list_like(func): return self._list_like_f...
Apply func across given axis. Args: func: The function to apply. axis: Target axis to apply the function along. Returns: A new PandasQueryCompiler.
juraj-google-style
def cast_if_floating_dtype(x, dtype=None): return nest.map_structure(functools.partial(cast_single_tensor, dtype=dtype), x)
Casts the given data tensors to the default floating point type. Casts only if the input is already a floating point type. Args: x: tensor or list/tuple of tensors. dtype: The dtype to which Tensors should be cast. Returns: Converted input.
github-repos
def evaluate_model(self, accuracy, num_steps, feed_vars=(), feed_data=None, summary_tag=None, print_every=0): if (not hasattr(self, '_saver')): raise ValueError('Before evaluating, you must initialize the model with load_from_checkpoint, prepare or saver.') self._run_init_test_vars_op() if ((not isi...
Evaluates the given model. Args: accuracy: The metric that is being evaluated or a tuple of metrics. num_steps: The number of steps to run in the evaluator. feed_vars: A list or tuple of the variables that will be fed. feed_data: A generator that produces tuples of the same length as feed_vars. summary_tag: If provide...
codesearchnet
def GetStandardAddress(self): for contract in self._contracts.values(): if contract.IsStandard: return contract.ScriptHash raise Exception('Could not find a standard contract address')
Get the Wallet's default address. Raises: Exception: if no default contract address is set. Returns: UInt160: script hash.
codesearchnet
def transform(self, value): with tf.name_scope(self._name + '/transform'): no_batch_dim = value.shape.ndims == self._mean.shape.ndims if no_batch_dim: value = value[None, ...] if self._center: value -= self._mean[None, ...] if self._scale: value...
Normalize a single or batch tensor. Applies the activated transformations in the constructor using current estimates of mean and variance. Args: value: Batch or single value tensor. Returns: Normalized batch or single value tensor.
juraj-google-style
def setData(self, data, setName=None): if (not isinstance(data, DataFrame)): if ((pd is not None) and isinstance(data, pd.DataFrame)): data = DataFrame.fromPandas(data) if (setName is None): lock_and_call((lambda : self._impl.setData(data._impl)), self._lock) else: lock_a...
Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices values of the DataFrame are to be assigned. Raises: AMPLException: if the data assignment procedure w...
codesearchnet
def get_name_scope() -> str: if context.executing_eagerly(): return context.context().scope_name.rstrip('/') return get_default_graph().get_name_scope()
Returns the current name scope in the default_graph. For example: ```python with tf.name_scope('scope1'): with tf.name_scope('scope2'): print(tf.get_name_scope()) ``` would print the string `scope1/scope2`. Returns: A string representing the current name scope.
github-repos
def register_flag_by_module(self, module_name, flag): flags_by_module = self.flags_by_module_dict() flags_by_module.setdefault(module_name, []).append(flag)
Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: str, the name of a Python module. flag: Flag, the Flag instance that is key to the module.
juraj-google-style
def _is_variant(self, gemini_variant, ind_objs): indexes = (ind.ind_index for ind in ind_objs) for index in indexes: gt_call = gemini_variant['gt_types'][index] if ((gt_call == 1) or (gt_call == 3)): return True return False
Check if the variant is a variation in any of the individuals Args: gemini_variant (GeminiQueryRow): The gemini variant ind_objs (list(puzzle.models.individual)): A list of individuals to check Returns: bool : If any of the individuals has the variant
codesearchnet
def run(stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None, quiet=False, overwrite_output=False): process = run_async(stream_spec, cmd, pipe_stdin=(input is not None), pipe_stdout=capture_stdout, pipe_stderr=capture_stderr, quiet=quiet, overwrite_output=overwrite_output) (out, err...
Invoke ffmpeg for the supplied node graph. Args: capture_stdout: if True, capture stdout (to be used with ``pipe:`` ffmpeg outputs). capture_stderr: if True, capture stderr. quiet: shorthand for setting ``capture_stdout`` and ``capture_stderr``. input: text to be sent to stdin (to be used with ``pipe:`` ffmpeg inputs)...
codesearchnet
def visit_Call(self, node): if self.depth == 0: return node if self.ignore_exceptions is None: ignore_exceptions = ast.Name("None", ast.Load()) else: ignore_exceptions = ast.List(self.ignore_exceptions, ast.Load()) catch_exception_type = se...
Propagate 'debug' wrapper into inner function calls if needed. Args: node (ast.AST): node statement to surround.
juraj-google-style
def CreateRetryTask(self): retry_task = Task(session_identifier=self.session_identifier) retry_task.file_entry_type = self.file_entry_type retry_task.merge_priority = self.merge_priority retry_task.path_spec = self.path_spec retry_task.storage_file_size = self.storage_file_size self.has_retry = ...
Creates a new task to retry a previously abandoned task. The retry task will have a new identifier but most of the attributes will be a copy of the previously abandoned task. Returns: Task: a task to retry a previously abandoned task.
codesearchnet
def FromDateTimeToTimestamp(datetime_obj): dt = datetime_obj.replace(tzinfo=None) return int((dt - datetime.datetime(1970, 1, 1)).total_seconds())
Converts datetime object to internal nss_cache timestamp. Args: datetime object Returns: number of seconds since epoch
github-repos
async def get_action_context_and_template(chain, parent_link, decision_link): actions_path = decision_link.get_artifact_full_path('public/actions.json') all_actions = load_json_or_yaml(actions_path, is_path=True)['actions'] action_name = get_action_callback_name(parent_link.task) action_defn = _get_acti...
Get the appropriate json-e context and template for an action task. Args: chain (ChainOfTrust): the chain of trust. parent_link (LinkOfTrust): the parent link to test. decision_link (LinkOfTrust): the parent link's decision task link. tasks_for (str): the reason the parent link was created (cron, hg-push, action) Ret...
codesearchnet
def autocorrect(query, possibilities, delta=0.75): possibilities = [possibility.lower() for possibility in possibilities] if (query in possibilities): return query options = [word for word in possibilities if word.startswith(query)] if (len(options) > 0): possibilities = options ...
Attempts to figure out what possibility the query is This autocorrect function is rather simple right now with plans for later improvement. Right now, it just attempts to finish spelling a word as much as possible, and then determines which possibility is closest to said word. Args: query (unicode): query to attempt...
codesearchnet
def get_device_name(self, cached=True): if cached and self.name is not None: return self.name device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME) if device_name is None: logger.warn('Failed to find handle for device name') return...
Returns the SK8 device BLE name. Args: cached (bool): if True, returns the locally cached copy of the name. If this is set to False, or the name is not cached, it will read from the device instead. Returns: str. The current device name. May be `None` if an error occurs.
juraj-google-style
def union(cls, *mhs): if (len(mhs) < 2): raise ValueError('Cannot union less than 2 MinHash') num_perm = len(mhs[0]) seed = mhs[0].seed if any((((seed != m.seed) or (num_perm != len(m))) for m in mhs)): raise ValueError('The unioning MinHash must have the same seed and...
Create a MinHash which is the union of the MinHash objects passed as arguments. Args: *mhs: The MinHash objects to be united. The argument list length is variable, but must be at least 2. Returns: datasketch.MinHash: A new union MinHash.
codesearchnet
def restart(self, **kwargs): return self.client.api.restart(self.id, **kwargs)
Restart this container. Similar to the ``docker restart`` command. Args: timeout (int): Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds. Raises: :py:class:`docker.errors.APIError` If the server returns an error.
juraj-google-style
async def _auth_cram_md5(self, username, password): mechanism = 'CRAM-MD5' (code, message) = (await self.do_cmd('AUTH', mechanism, success=(334,))) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new(key=password.encode('utf-8'), msg=decoded_challenge, digestmod='md5') hex_hash =...
Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (share...
codesearchnet
def prefer_static_broadcast_shape(shape1, shape2, name='prefer_static_broadcast_shape'): with tf.name_scope(name): def make_shape_tensor(x): return tf.convert_to_tensor(value=x, name='shape', dtype=tf.int32) def get_tensor_shape(s): if isinstance(s, tf.TensorShape): ...
Convenience function which statically broadcasts shape when possible. Args: shape1: `1-D` integer `Tensor`. Already converted to tensor! shape2: `1-D` integer `Tensor`. Already converted to tensor! name: A string name to prepend to created ops. Returns: The broadcast shape, either as `TensorShape` (if broadcast ...
codesearchnet
def validate_layout_display(self, table, display_condition): display = False if (display_condition is None): display = True else: display_query = 'select count(*) from {} where {}'.format(table, display_condition) try: cur = self.db_conn.cursor() cur.execute(d...
Check to see if the display condition passes. Args: table (str): The name of the DB table which hold the App data. display_condition (str): The "where" clause of the DB SQL statement. Returns: bool: True if the row count is greater than 0.
codesearchnet
def BuildFindSpecs(self, artifact_filter_names, environment_variables=None): find_specs = [] for name in artifact_filter_names: definition = self._artifacts_registry.GetDefinitionByName(name) if (not definition): logger.debug('undefined artifact definition: {0:s}'.format(name)) ...
Builds find specifications from artifact definitions. Args: artifact_filter_names (list[str]): names of artifact definitions that are used for filtering file system and Windows Registry key paths. environment_variables (Optional[list[EnvironmentVariableArtifact]]): environment variables.
codesearchnet
def factored_joint_mvn(distributions): graph_parents = [tensor for distribution in distributions for tensor in distribution._graph_parents] with tf.compat.v1.name_scope('factored_joint_mvn', values=graph_parents): dtype = tf.debugging.assert_same_float_dtype(distributions) broadcast_ones = tf.on...
Combine MultivariateNormals into a factored joint distribution. Given a list of multivariate normal distributions `dist[i] = Normal(loc[i], scale[i])`, construct the joint distribution given by concatenating independent samples from these distributions. This is multivariate normal with mean vector given by the concate...
codesearchnet
def __frontend_limit_descriptor(self, api_info): if api_info.frontend_limits is None: return None descriptor = {} for propname, descname in (('unregistered_user_qps', 'unregisteredUserQps'), ('unregistered_qps', 'unregisteredQps'), ('...
Builds a frontend limit descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A dictionary with frontend limit information.
juraj-google-style
def _process_string_token(self, token, start_row, start_col): for (i, char) in enumerate(token): if (char in QUOTES): break norm_quote = token[i:] if ((len(norm_quote) >= 3) and (norm_quote[:3] in TRIPLE_QUOTE_OPTS.values())): self._tokenized_triple_quotes[start_row] = (token, no...
Internal method for identifying and checking string tokens from the token stream. Args: token: the token to check. start_row: the line on which the token was found. start_col: the column on which the token was found.
codesearchnet
def list_values(hive, key=None, use_32bit_registry=False, include_default=True): return __utils__['reg.list_values'](hive=hive, key=key, use_32bit_registry=use_32bit_registry, include_default=include_default)
r''' Enumerates the values in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR - HKEY_CURRENT_CONFIG or HKCC key (str): The key (looks like a path) to the value name. I...
codesearchnet
def prepare_message(self, message): message.meta.update(path=self.path) for handler in self.handlers: handler.outgoing(message, self) return message
Prepares the message before sending it out Returns: - message.Message: the message
codesearchnet
def fn(x: tuple[int, ...]): return x
Test function Args: x: The input Returns: The output
github-repos
def learn(self, grad_arr, fix_opt_flag=False): delta_arr = super().learn(grad_arr, fix_opt_flag) if self.__add_channel_flag is True: return delta_arr[:, 0] else: return delta_arr
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
juraj-google-style
def prepare_amazon_algorithm_estimator(estimator, inputs, mini_batch_size=None): if isinstance(inputs, list): for record in inputs: if (isinstance(record, amazon_estimator.RecordSet) and (record.channel == 'train')): estimator.feature_dim = record.feature_dim brea...
Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data. Args: estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase): An estimator for a built-in Amazon algorithm to get information from and update. inputs: The training data. * (sagemaker.amazon.amazo...
codesearchnet
def handle_callback(self, callback_id, ret_value, rpc_func_name):
Creates a callback handler for the asynchronous RPC. Args: callback_id: str, the callback ID for creating a callback handler object. ret_value: any, the result field of the RPC response. rpc_func_name: str, the name of the snippet function executed on the server. Returns: The callback handler object.
github-repos
def __init__(self, field, lower_bound, upper_bound): super(BetweenClause, self).__init__(field, lower_bound, upper_bound) self.field = field self.lower_bound = lower_bound self.upper_bound = upper_bound self.validate()
Construct an expression that is true when the field value is within the given bounds. Args: field: LocalField Expression, denoting the field in consideration lower_bound: lower bound constraint for given field upper_bound: upper bound constraint for given field Returns: a new BetweenClause object
juraj-google-style
def add_all_exchange_reactions(model, compartment, allow_duplicates=False): all_reactions = {} if (not allow_duplicates): for rxnid in model.database.reactions: rx = model.database.get_reaction(rxnid) all_reactions[rx] = rxnid added = set() added_compounds = set() ini...
Add all exchange reactions to database and to model. Args: model: :class:`psamm.metabolicmodel.MetabolicModel`.
codesearchnet
def list(self, **kwargs): request = Request('GET', '/v3/accounts') response = self.ctx.request(request) if (response.content_type is None): return response if (not response.content_type.startswith('application/json')): return response jbody = json.loads(response.raw_body) parsed_...
Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request
codesearchnet
def add_help_text(parent, filepath, prefix='!'): import tkinter as tk import tkinter.ttk as ttk help_contents = get_help_data(filepath) text = tk.Text(parent, wrap='word', font=('Helvetica', 10)) text.grid(row=0, column=0, sticky='W E N S') text.tag_config('heading', font=('Helvetica', 14)) ...
Load help text from a file and adds it to the parent Args: parent: A tk or ttk object filepath (str): The file to load help text from prefix (str): The prefix to use for commands
codesearchnet
def match_not_exists(self, field, new_group=False): return self.exclude_field(field, '*', new_group=new_group)
Require a field to not exist in the results. Matches will not have ``field`` present. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"mdf.source_name"`` is the ``source_name`` field of the ``mdf`` dictionary. new_group (boo...
codesearchnet
def next_event_type(self): type_ = self._libinput.libinput_next_event_type(self._li) if (type_ == 0): return None else: return EventType(type_)
Return the type of the next event in the internal queue. This method does not pop the event off the queue and the next call to :attr:`events` returns that event. Returns: ~libinput.constant.EventType: The event type of the next available event or :obj:`None` if no event is available.
codesearchnet
def chrome_tracing_object_transfer_dump(self, filename=None): client_id_to_address = {} for client_info in ray.global_state.client_table(): client_id_to_address[client_info['ClientID']] = '{}:{}'.format(client_info['NodeManagerAddress'], client_info['ObjectManagerPort']) all_events = [] for (key...
Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to enable "Flow events" in the "Vie...
codesearchnet
def to_json(self): return {'xblock_id': six.text_type(self.xblock_id), 'messages': [message.to_json() for message in self.messages], 'empty': self.empty}
Convert to a json-serializable representation. Returns: dict: A dict representation that is json-serializable.
codesearchnet
def read_dftbp(filename): infile = open(filename, 'r') lines = infile.readlines() for ss in lines: if ss.strip().startswith(' lines.remove(ss) natoms = int(lines[0].split()[0]) symbols = lines[1].split() if (lines[0].split()[1].lower() == 'f'): is_scaled = True ...
Reads DFTB+ structure files in gen format. Args: filename: name of the gen-file to be read Returns: atoms: an object of the phonopy.Atoms class, representing the structure found in filename
codesearchnet
def get_course_runs_from_program(program): course_runs = set() for course in program.get("courses", []): for run in course.get("course_runs", []): if "key" in run and run["key"]: course_runs.add(run["key"]) return course_runs
Return course runs from program data. Arguments: program(dict): Program data from Course Catalog API Returns: set: course runs in given program
juraj-google-style
def put(self, filename): from . import LocalFile target = get_target_path(filename, self.source) with self.open('rb') as infile, open(target, 'wb') as outfile: shutil.copyfileobj(infile, outfile) return LocalFile(target)
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
juraj-google-style
def headers(self, headers=None, **kw): headers = (kw if kw else headers) self._request.headers = headers self.add_matcher(matcher('HeadersMatcher', headers))
Defines a dictionary of arguments. Header keys are case insensitive. Arguments: headers (dict): headers to match. **headers (dict): headers to match as variadic keyword arguments. Returns: self: current Mock instance.
codesearchnet
def generate_visualizations(methods, data, true_labels, base_dir = 'visualizations', figsize=(18,10), **scatter_options): plt.figure(figsize=figsize) for method in methods: preproc= method[0] if isinstance(preproc, Preprocess): preprocessed, ll = preproc.run(data) ...
Generates visualization scatters for all the methods. Args: methods: follows same format as run_experiments. List of tuples. data: genes x cells true_labels: array of integers base_dir: base directory to save all the plots figsize: tuple of ints representing size of figure scatter_options: options for plt.scatter
juraj-google-style
def get(self, element): if self['link']['item'][element]['class'] == 'dataset': return Dataset.read(self['link']['item'][element]['href']) elif self['link']['item'][element]['class'] == 'collection': return Collection.read(self['link']['item'][element]['href']) ...
Gets ith element of a collection in an object of the corresponding \ class. Args: output(string): can accept 'jsonstat' or 'dataframe_list' Returns: Serialized JSONstat or a list of Pandas Dataframes,depending on \ the 'output' parameter.
juraj-google-style
def xldate_as_datetime(xldate, datemode=0, option='to_datetime'): if (option == 'to_float'): d = ((xldate - 25589) * 86400.0) else: try: d = (datetime.datetime(1899, 12, 30) + datetime.timedelta(days=(xldate + (1462 * datemode)))) if (option == 'to_string'): ...
Converts a xls date stamp to a more sensible format. Args: xldate (str): date stamp in Excel format. datemode (int): 0 for 1900-based, 1 for 1904-based. option (str): option in ("to_datetime", "to_float", "to_string"), return value Returns: datetime (datetime object, float, or string).
codesearchnet
def remove_handler(self, handler: Handler, group: int = 0): if isinstance(handler, DisconnectHandler): self.disconnect_handler = None else: self.dispatcher.remove_handler(handler, group)
Removes a previously-added update handler. Make sure to provide the right group that the handler was added in. You can use the return value of the :meth:`add_handler` method, a tuple of (handler, group), and pass it directly. Args: handler (``Handler``): The handler to be removed. group (``int``, *optional*): The gr...
juraj-google-style
def set_license(self, license, **kwargs): data = {'license': license} return self.http_post('/license', post_data=data, **kwargs)
Add a new license. Args: license (str): The license string **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabPostError: If the server cannot perform the request Returns: dict: The new license information
juraj-google-style
def ParseOptions(cls, options, config_object, category=None, names=None): for (helper_name, helper_class) in cls._helper_classes.items(): if ((category and (helper_class.CATEGORY != category)) or (names and (helper_name not in names))): continue try: helper_class.ParseOptions...
Parses and validates arguments using the appropriate helpers. Args: options (argparse.Namespace): parser options. config_object (object): object to be configured by an argument helper. category (Optional[str]): category of helpers to apply to the group, such as storage, output, where None will apply the arguments to a...
codesearchnet
def sample(self, features): (logits, losses) = self(features) if self._target_modality_is_real: return (logits, logits, losses) if (self.hparams.sampling_method == 'argmax'): samples = tf.argmax(logits, axis=(- 1)) else: assert (self.hparams.sampling_method == 'random') ...
Run the model and extract samples. Args: features: an map of string to `Tensor`. Returns: samples: an integer `Tensor`. logits: a list of `Tensor`s, one per datashard. losses: a dictionary: {loss-name (string): floating point `Scalar`}.
codesearchnet