code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def add(self, layer): if hasattr(layer, '_keras_history'): origin_layer = layer._keras_history[0] if isinstance(origin_layer, input_layer.InputLayer): layer = origin_layer logging.warning('Please add `keras.layers.InputLayer` instead of `keras.Input` to Sequential model. `ker...
Adds a layer instance on top of the layer stack. Args: layer: layer instance. Raises: TypeError: If `layer` is not a layer instance. ValueError: In case the `layer` argument does not know its input shape. ValueError: In case the `layer` argument has multiple output tensors, or is already connected somewhere else (for...
github-repos
def _InfoBackup(component): info = {} info['type_name'] = type(component).__name__ info['string_form'] = str(component) filename, lineno = GetFileAndLine(component) info['file'] = filename info['line'] = lineno info['docstring'] = inspect.getdoc(component) try: info['length'] = s...
Returns a dict with information about the given component. This function is to be called only in the case that IPython's oinspect module is not available. The info dict it produces may contain less information that contained in the info dict produced by oinspect. Args: component: The component to analyze. Returns: A ...
github-repos
def selfSignCert(self, cert, pkey): cert.set_issuer(cert.get_subject()) cert.sign(pkey, self.signing_digest)
Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given private key: cdir.selfSignCert(mycert, myotherprivatekey) Returns: None
juraj-google-style
def data(self, rows=None): rows = tf.range(self._capacity) if rows is None else rows assert rows.shape.ndims == 1 episode = tools.nested.map(lambda var: tf.gather(var, rows), self._buffers) length = tf.gather(self._length, rows) return episode, length
Access a batch of episodes from the memory. Padding elements after the length of each episode are unspecified and might contain old data. Args: rows: Episodes to select, defaults to all. Returns: Tuple containing a tuple of transition quantities with batch and time dimensions, and a batch of sequence lengths.
juraj-google-style
def bind_parameters(self, value_dict): new_circuit = self.copy() if (value_dict.keys() > self.parameters): raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format([str(p) for p in (value_dict.keys() - self.parameters)])) for (parameter, value) in value_dict.items(): ...
Assign parameters to values yielding a new circuit. Args: value_dict (dict): {parameter: value, ...} Raises: QiskitError: If value_dict contains parameters not present in the circuit Returns: QuantumCircuit: copy of self with assignment substitution.
codesearchnet
def acos(cls, x: 'TensorFluent') -> 'TensorFluent': return cls._unary_op(x, tf.acos, tf.float32)
Returns a TensorFluent for the arccos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the arccos function.
juraj-google-style
def get_array_for_fit(observables: dict, track_pt_bin: int, jet_pt_bin: int) -> histogram.Histogram1D: for (name, observable) in observables.items(): if ((observable.track_pt_bin == track_pt_bin) and (observable.jet_pt_bin == jet_pt_bin)): return histogram.Histogram1D.from_existing_hist(observab...
Get a Histogram1D associated with the selected jet and track pt bins. This is often used to retrieve data for fitting. Args: observables (dict): The observables from which the hist should be retrieved. track_pt_bin (int): Track pt bin of the desired hist. jet_ptbin (int): Jet pt bin of the desired hist. Returns: Hist...
codesearchnet
def GetNumberOfEventSources(self): number_of_event_sources = self._CountStoredAttributeContainers(self._CONTAINER_TYPE_EVENT_SOURCE) number_of_event_sources += self._GetNumberOfSerializedAttributeContainers(self._CONTAINER_TYPE_EVENT_SOURCE) return number_of_event_sources
Retrieves the number event sources. Returns: int: number of event sources.
codesearchnet
def index_buffer(self, buffer, index_element_size=4): if (not (type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes])): raise VAOError('buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance') if isinstance(buffer, numpy.ndarray): buffer = self.ctx.buffer(buffer.tobytes())...
Set the index buffer for this VAO Args: buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes`` Keyword Args: index_element_size (int): Byte size of each element. 1, 2 or 4
codesearchnet
def get_image_features(self, pixel_values: torch.FloatTensor, vision_feature_layer: Optional[Union[int, List[int]]]=None, vision_feature_select_strategy: Optional[str]=None, **kwargs): vision_feature_layer = vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer vision_fe...
Obtains image last hidden states from the vision tower and apply multimodal projection. Args: pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`): The tensors corresponding to the input images. vision_feature_layer (`Union[int, List[int]]`, *optional*): The index of the layer to select...
github-repos
def get_changeset(changeset): url = 'https: return ET.fromstring(requests.get(url).content)
Get the changeset using the OSM API and return the content as a XML ElementTree. Args: changeset: the id of the changeset.
codesearchnet
def stitch_values(values_and_indices_list): length = 0 for values_and_indices in values_and_indices_list: length += len(values_and_indices[0]) result = [None] * length for values_and_indices in values_and_indices_list: if values_and_indices and values_and_indices[0]: for v, i...
Stitch values together according to their indices. Args: values_and_indices_list: a list of tuples of values and indices indicating the values and positions in the returned list. Returns: a stitched list of values.
github-repos
def _ref(self): return self._variable
Returns a reference to this variable. You usually do not need to call this method as all ops that need a reference to the variable call it automatically. Returns is a `Tensor` which holds a reference to the variable. You can assign a new value to the variable by passing the tensor to an assign op. See `tf.Variable.v...
github-repos
def peek(self) -> str: try: return self.input[self.offset] except IndexError: raise EndOfInput(self)
Return the next character without advancing offset. Raises: EndOfInput: If past the end of `self.input`.
codesearchnet
def device_id_to_slug(did): try: device_slug = IOTileDeviceSlug(did, allow_64bits=False) except ValueError: raise ArgumentError('Unable to recognize {} as a device id'.format(did)) return str(device_slug)
Converts a device id into a correct device slug. Args: did (long) : A device id did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX Returns: str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format Raises: ArgumentError: if the ID is not in the [1, 16**12] range, or if no...
codesearchnet
def _detect(self): results = [] for c in self.contracts: for f in c.functions: if (f.contract != c): continue if (f.view or f.pure): if f.contains_assembly: attr = ('view' if f.view else 'pure') info = '{}.{}...
Detect the constant function changing the state Recursively visit the calls Returns: list: {'vuln', 'filename,'contract','func','#varsWritten'}
codesearchnet
def extract_cookies(self, response, request, referrer_host=None): new_response = HTTPResponseInfoWrapper(response) new_request = convert_http_request(request, referrer_host) self._cookie_jar.extract_cookies(new_response, new_request)
Wrapped ``extract_cookies``. Args: response: An instance of :class:`.http.request.Response`. request: An instance of :class:`.http.request.Request`. referrer_host (str): An hostname or IP address of the referrer URL.
codesearchnet
def Serialize(self, writer): writer.WriteHashes(self.HashStart) if self.HashStop is not None: writer.WriteUInt256(self.HashStop)
Serialize object. Args: writer (neo.IO.BinaryWriter):
juraj-google-style
def save_checkpoint(model, filename, optimizer=None, meta=None): if meta is None: meta = {} elif not isinstance(meta, dict): raise TypeError('meta must be a dict or None, but got {}'.format( type(meta))) meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) mm...
Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved....
juraj-google-style
def create_alias(alias_name, alias_command): (alias_name, alias_command) = (alias_name.strip(), alias_command.strip()) alias_table = get_alias_table() if (alias_name not in alias_table.sections()): alias_table.add_section(alias_name) alias_table.set(alias_name, 'command', alias_command) _com...
Create an alias. Args: alias_name: The name of the alias. alias_command: The command that the alias points to.
codesearchnet
def sg_transpose(tensor, opt): assert (opt.perm is not None), 'perm is mandatory' return tf.transpose(tensor, opt.perm, name=opt.name)
r"""Permutes the dimensions according to `opt.perm`. See `tf.transpose()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: perm: A permutation of the dimensions of `tensor`. The target shape. name: If provided, replace current tensor's name. Returns: A `Tensor`.
codesearchnet
def _get_format(format, fname, inp=None): fmt = None err = True if (format is not None): if (format in fmt_to_exts): fmt = format err = False elif fname: file_ext = os.path.splitext(fname)[1][len(os.path.extsep):] for (fmt_name, exts) in fmt_to_exts.items(...
Try to guess markup format of given input. Args: format: explicit format override to use fname: name of file, if a file was used to read `inp` inp: optional bytestring to guess format of (can be None, if markup format is to be guessed only from `format` and `fname`) Returns: guessed format (a key of fmt_to_exts dict) ...
codesearchnet
def accuracy(y_true: [list, np.ndarray], y_predicted: [list, np.ndarray]) -> float: examples_len = len(y_true) correct = sum([(y1 == y2) for (y1, y2) in zip(y_true, y_predicted)]) return ((correct / examples_len) if examples_len else 0)
Calculate accuracy in terms of absolute coincidence Args: y_true: array of true values y_predicted: array of predicted values Returns: portion of absolutely coincidental samples
codesearchnet
def AddForwardedIp(self, address, interface): address = address if IP_ALIAS_REGEX.match(address) else '%s/32' % address args = ['add', 'to', 'local', address] options = self._CreateRouteOptions(dev=interface) self._RunIpRoute(args=args, options=options)
Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use.
juraj-google-style
def convert_drive(self, shift, instruction): command_dict = {'name': instruction.command.name, 't0': (shift + instruction.start_time), 'ch': instruction.channels[0].name} return self._qobj_model(**command_dict)
Return converted `PulseInstruction`. Args: shift(int): Offset time. instruction (PulseInstruction): drive instruction. Returns: dict: Dictionary of required parameters.
codesearchnet
def __directory_list_descriptor(self, configs): descriptor = {'kind': 'discovery items = [] for config in configs: item_descriptor = self.__item_descriptor(config) if item_descriptor: items.append(item_descriptor) if items: descriptor['items'] = items return descr...
Builds a directory list for an API. Args: configs: List of dicts containing the service configurations to list. Returns: A dictionary that can be deserialized into JSON in discovery list format. Raises: ApiConfigurationError: If there's something wrong with the API configuration, such as a multiclass API decorated w...
codesearchnet
def _LastEntryTimestamp(dct, upper_bound_timestamp): if upper_bound_timestamp is None: upper_bound = lambda _: True else: upper_bound = lambda key: key <= upper_bound_timestamp try: return max(filter(upper_bound, iterkeys(dct))) except ValueError: return None
Searches for greatest timestamp lower than the specified one. Args: dct: A dictionary from timestamps to some items. upper_bound_timestamp: An upper bound for timestamp to be returned. Returns: Greatest timestamp that is lower than the specified one. If no such value exists, `None` is returned.
juraj-google-style
def AddSerializedFile(self, serialized_file_desc_proto): from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(serialized_file_desc_proto) self.Add(file_desc_proto)
Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add.
codesearchnet
def _parse_description(details): description = details.find("div", {"class": "detailPopis"}) if not description: return None ekniha = description[0].find("div", {"class": "ekniha"}) if ekniha: ekniha[0].replaceWith(dhtmlparser.HTMLElement("")) detail = descript...
Parse description of the book. Args: details (obj): HTMLElement containing slice of the page with details. Returns: str/None: Details as string with currency or None if not found.
juraj-google-style
def encode(self): blob = bytearray() for record in self.records: blob += record.encode() header = struct.pack('<LL', self.SCRIPT_MAGIC, (len(blob) + self.SCRIPT_HEADER_LENGTH)) blob = (header + blob) sha = hashlib.sha256() sha.update(blob) hash_value = sha.digest()[:16] return (b...
Encode this record into a binary blob. This binary blob could be parsed via a call to FromBinary(). Returns: bytearray: The binary encoded script.
codesearchnet
def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3): if (api_version not in [3]): raise RuntimeError(('Unsupported api version: %s, expected 3.' % api_version)) if (destination is None): destination = self.server_name cipher = self._GetServerCi...
Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload. Args: message_list: A MessageList rdfvalue containing a list of GrrMessages. result: A ClientCommunication rdfvalue which will be filled in. destination: The CN of the remote system this should go to. timestamp...
codesearchnet
def get_poi_types(self, **kwargs): params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } result = self.make_request('geo', 'get_poi_types', **params) values = result.get('types', []) return True, [emtype.PoiType(**a) ...
Obtain POI types. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[PoiType]), or message string in case of error.
juraj-google-style
def lookup_symbol(self, name, namespace_stack): symbol = Symbol(name, name.split('::'), namespace_stack) assert symbol.parts if (symbol.parts[0] == ''): symbol.parts = symbol.parts[1:] elif (namespace_stack is not None): result = self._lookup_in_all_namespaces(symbol) if result: ...
Returns AST node and module for symbol if found. Args: name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'in', 'current', 'scope'] Returns: (ast.Node, module (ie, any object stored with symbol)) if found Raises: Error if the symbol cannot be found.
codesearchnet
def get_summary(self): func_summaries = [f.get_summary() for f in self.functions] modif_summaries = [f.get_summary() for f in self.modifiers] return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries)
Return the function summary Returns: (str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)
codesearchnet
def join_dags(self, names=None): return self._client.send(Request(action='join_dags', payload={'names': names})).success
Wait for the specified dags to terminate. This function blocks until the specified dags terminate. If no dags are specified wait for all dags of the workflow, except the dag of the task calling this signal, to terminate. Args: names (list): The names of the dags that have to terminate. Returns: bool: True if all the...
codesearchnet
def ParseLines(lines, message, allow_unknown_extension=False, allow_field_number=False): parser = _Parser(allow_unknown_extension, allow_field_number) return parser.ParseLines(lines, message)
Parses an text representation of a protocol message into a message. Args: lines: An iterable of lines of a message's text representation. message: A protocol buffer message to merge into. allow_unknown_extension: if True, skip over missing extensions and keep parsing allow_field_number: if True, both field number and ...
juraj-google-style
def getUserForHost(self, user, host): for name in iterFqdnUp(host): usercert = '%s@%s' % (user, name) if self.isUserCert(usercert): return usercert
Gets the name of the first existing user cert for a given user and host. Args: user (str): The name of the user. host (str): The name of the host. Examples: Get the name for the "myuser" user cert at "cool.vertex.link": usercertname = cdir.getUserForHost('myuser', 'cool.vertex.link') Returns: str: The cert name, if...
juraj-google-style
def postprocess(self, args: argparse.Namespace): names = {k for k in self.pytype_single_args if hasattr(args, k)} opt_map = {k: self._pytype_arg_map[k].long_opt for k in names} pytype_config.Postprocessor(names, opt_map, args).process()
Postprocesses the subset of pytype_single_args that appear in args. Args: args: an argparse.Namespace.
github-repos
def get_controller(self, path): path_info = path.lstrip('/').split('/', 2) try: return self._routes.get(((path_info[0] + '/') + path_info[1])) except (IndexError, KeyError): return self._routes.get((path_info[0] or 'index'))
Return controller that handle given path. Args: - path: requested path, like: /blog/post_view/15
codesearchnet
def plot_title(ax, pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None): current_title = ax.get_title() if (not current_title): current_title = ((pretitle + title) + posttitle) title_arg = dict_if_none(title_arg) ax.set_title(current_title, fontsize=title_fontsize, **tit...
Set title options of a matplotlib plot Args: ax: matplotlib axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_ar...
codesearchnet
def get_available_palettes(chosen_palette): result = None try: result = ALL_PALETTES[:(ALL_PALETTES.index(chosen_palette) + 1)] except ValueError: pass return result
Given a chosen palette, returns tuple of those available, or None when not found. Because palette support of a particular level is almost always a superset of lower levels, this should return all available palettes. Returns: Boolean, None: is tty or None if not found.
codesearchnet
def load(cls, fh): dat = fh.read() try: ret = cls.from_json(dat) except: ret = cls.from_yaml(dat) return ret
Load json or yaml data from file handle. Args: fh (file): File handle to load from. Examlple: >>> with open('data.json', 'r') as json: >>> jsdata = composite.load(json) >>> >>> with open('data.yml', 'r') as yml: >>> ymldata = composite.load(yml)
juraj-google-style
def sample(self, num_rows=1): self.check_fit() res = {} means = np.zeros(self.covariance.shape[0]) size = (num_rows,) clean_cov = np.nan_to_num(self.covariance) samples = np.random.multivariate_normal(means, clean_cov, size=size) for i, (label, distrib...
Creates sintentic values stadistically similar to the original dataset. Args: num_rows: `int` amount of samples to generate. Returns: np.ndarray: Sampled data.
juraj-google-style
def image_summary(predictions, targets, hparams): del hparams results = tf.cast(tf.argmax(predictions, axis=-1), tf.uint8) gold = tf.cast(targets, tf.uint8) summary1 = tf.summary.image("prediction", results, max_outputs=2) summary2 = tf.summary.image("data", gold, max_outputs=2) summary = tf.summary.merg...
Reshapes predictions and passes it to tensorboard. Args: predictions : The predicted image (logits). targets : The ground truth. hparams: model hparams. Returns: summary_proto: containing the summary images. weights: A Tensor of zeros of the same shape as predictions.
juraj-google-style
def get_status(self, batch_id): with self._lock: if self._batch_committed(batch_id): return ClientBatchStatus.COMMITTED if (batch_id in self._invalid): return ClientBatchStatus.INVALID if (batch_id in self._pending): return ClientBatchStatus.PENDING ...
Returns the status enum for a batch. Args: batch_id (str): The id of the batch to get the status for Returns: int: The status enum
codesearchnet
class IntSoftmax(nn.Module): def __init__(self, output_bit, quant_mode=False, force_dequant='none'): super().__init__() self.output_bit = output_bit self.max_bit = 32 self.quant_mode = quant_mode if force_dequant in ['nonlinear', 'softmax']: logger.info('Force de...
Quantized version of `torch.nn.Softmax`. Adds quantization-specific arguments on top of `torch.nn.Softmax`. Args: output_bit (`int`): Bitwidth for the layer output activation. quant_mode (`bool`, *optional*, defaults to `False`): Whether or not the layer is quantized. force_dequant (`str`, *optional*, defaults to `"no...
github-repos
def _merge_doc(original, to_merge): if not original: return to_merge or '' if not to_merge: return original or '' sections = [] for name in ('usage', 'arguments', 'options'): sections.append(_merge_section( _get_section(name, original), _get_sect...
Merge two usage strings together. Args: original: The source of headers and initial section lines. to_merge: The source for the additional section lines to append. Returns: A new usage string that contains information from both usage strings.
juraj-google-style
def recipe_dynamic_costs(config, dcm_account, auth_read, configuration_sheet_url, auth_write, bigquery_dataset): dynamic_costs(config, {'auth': auth_read, 'account': dcm_account, 'sheet': {'template': {'url': 'https:
Calculate DV360 cost at the dynamic creative combination level. Args: dcm_account (string) - NA auth_read (authentication) - Credentials used for reading data. configuration_sheet_url (string) - NA auth_write (authentication) - Credentials used for writing data. bigquery_dataset (string) - NA
github-repos
def sample_with_temperature(logits, temperature, sampling_keep_top_k=-1): if temperature == 0.0: logits_shape = shape_list(logits) argmax = tf.argmax(tf.reshape(logits, [-1, logits_shape[-1]]), axis=1) return tf.reshape(argmax, logits_shape[:-1]) else: assert temperature > 0.0 if sampli...
Either argmax or random sampling. Args: logits: a Tensor. temperature: a float 0.0=argmax 1.0=random sampling_keep_top_k: If not -1, only sample from the top k logits. Returns: a Tensor with one fewer dimension than logits.
juraj-google-style
def unzip_file(source_file, dest_dir=None, mkdir=False): if dest_dir is None: dest_dir, fname = os.path.split(source_file) elif not os.path.isdir(dest_dir): if mkdir: preparedir(dest_dir) else: created = preparedir(dest_dir, False) if not cre...
Unzip a compressed file. Args: source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip) dest_dir: Target folder to extract to (e.g. c:/ladybug). Default is set to the same directory as the source file. mkdir: Set to True to create the directory if doesn't exist (Default: False)
juraj-google-style
def best_case(self, matrix, m_list, indices_left): m_indices = [] fraction_list = [] for m in m_list: m_indices.extend(m[2]) fraction_list.extend([m[0]] * m[1]) indices = list(indices_left.intersection(m_indices)) interaction_matrix = matrix[ind...
Computes a best case given a matrix and manipulation list. Args: matrix: the current matrix (with some permutations already performed) m_list: [(multiplication fraction, number_of_indices, indices, species)] describing the manipulation indices: Set of indices which haven't had a permutation performed on them.
juraj-google-style
def get_tag(self, main_type, sub_type, unique_id, tag, owner=None, params=None): params = params or {} return self.tag(main_type, sub_type, unique_id, tag, owner=owner, params=params)
Args: owner: main_type: sub_type: unique_id: tag: params: Return:
juraj-google-style
def get_component(self, colour, tolerance=0, default=None): if not (0 <= tolerance <= np.sqrt(195075)): raise LegendError('Tolerance must be between 0 and 441.67') for decor in self.__list: if colour.lower() == decor.colour: return decor.component ...
Get the component corresponding to a display colour. This is for generating a Striplog object from a colour image of a striplog. Args: colour (str): The hex colour string to look up. tolerance (float): The colourspace distance within which to match. default (component or None): The component to return in the event of ...
juraj-google-style
def load(hdf5_filename): hdf5_filename = os.path.expanduser(hdf5_filename) try: f = h5py.File(hdf5_filename, "r") data_layers = f.get('image').get('CUTOUT') except Exception as e: raise ValueError("Could not load file {0} for conversion. {}".format( ...
Import a HDF5 file into a numpy array. Arguments: hdf5_filename: A string filename of a HDF5 datafile Returns: A numpy array with data from the HDF5 file
juraj-google-style
def search(self, resources_request=None): name_pattern, version_range = self._parse_request(resources_request) family_names = set( x.name for x in iter_package_families(paths=self.package_paths) if fnmatch.fnmatch(x.name, name_pattern) ) famil...
Search for resources. Args: resources_request (str): Resource to search, glob-style patterns are supported. If None, returns all matching resource types. Returns: 2-tuple: - str: resource type (family, package, variant); - List of `ResourceSearchResult`: Matching resources. Will be in alphabetical order if families, ...
juraj-google-style
def not_storable(_type): return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type)))
Helper for tagging unserializable types. Arguments: _type (type): type to be ignored. Returns: Storable: storable instance that does not poke.
juraj-google-style
def read_from_file(self, filename, negative_occupancies='warn'): valid_negative_occupancies = ['warn', 'raise', 'ignore', 'zero'] if (negative_occupancies not in valid_negative_occupancies): raise ValueError('"{}" is not a valid value for the keyword `negative_occupancies`.'.format(negative_occupancies)...
Reads the projected wavefunction character of each band from a VASP PROCAR file. Args: filename (str): Filename of the PROCAR file. negative_occupancies (:obj:Str, optional): Sets the behaviour for handling negative occupancies. Default is `warn`. Returns: None Note: Valid options for `negative_occupancies` are: `wa...
codesearchnet
def regroup_if_changed(group, op_list, name=None): has_deltas = isinstance(op_list, sequence_with_deltas.SequenceWithDeltas) if (group is None or len(group.control_inputs) != len(op_list) or (has_deltas and op_list.has_changed())): if has_deltas: op_list.mark() if op_list: return tf.gro...
Creates a new group for op_list if it has changed. Args: group: The current group. It is returned if op_list is unchanged. op_list: The list of operations to check. name: The name to use if a new group is created. Returns: Either group or a new group (or if op_list is empty then no_op).
juraj-google-style
def Scalars(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Scalars(tag)
Retrieve the scalar events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available for the given run. Returns: An array of `event_accumulator...
juraj-google-style
def period_neighborhood_probability(self, radius, smoothing, threshold, stride,start_time,end_time): neighbor_x = self.x[::stride, ::stride] neighbor_y = self.y[::stride, ::stride] neighbor_kd_tree = cKDTree(np.vstack((neighbor_x.ravel(), neighbor_y.ravel())).T) neighbor_prob = ...
Calculate the neighborhood probability over the full period of the forecast Args: radius: circular radius from each point in km smoothing: width of Gaussian smoother in km threshold: intensity of exceedance stride: number of grid points to skip for reduced neighborhood grid Returns: (neighborhood probabilities)
juraj-google-style
def _convert_to_sparse_tensors(sp_inputs): if isinstance(sp_inputs, list): return [_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs] if isinstance(sp_inputs, tuple): return (_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs) raise TypeError('Inputs must be a list or ...
Convert `sp_inputs` to `SparseTensor` objects and return them. Args: sp_inputs: `list` or `tuple` of `SparseTensor` or `SparseTensorValue` objects. Returns: `sp_inputs` converted to `SparseTensor` objects. Raises: ValueError: if any item in `sp_inputs` is neither `SparseTensor` nor `SparseTensorValue`.
github-repos
def depth_june_average_ground_temperature(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `depth_june_a...
Corresponds to IDD Field `depth_june_average_ground_temperature` Args: value (float): value for IDD Field `depth_june_average_ground_temperature` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
juraj-google-style
def write(self, brightness): if not isinstance(brightness, (bool, int)): raise TypeError("Invalid brightness type, should be bool or int.") if isinstance(brightness, bool): brightness = self._max_brightness if brightness else 0 else: if not 0 <= brig...
Set the brightness of the LED to `brightness`. `brightness` can be a boolean for on/off, or integer value for a specific brightness. Args: brightness (bool, int): Brightness value to set. Raises: LEDError: if an I/O or OS error occurs. TypeError: if `brightness` type is not bool or int.
juraj-google-style
def __contains__(self, nurest_object): for obj in self: if obj.equals(nurest_object): return True return False
Verify if the fetcher contains the given NURESTObject Args: nurest_object (bambou.NURESTObject): the NURESTObject object to verify Returns: Returns True if the object has been found. False otherwise
juraj-google-style
def fuzzy_match(self, proc): return any(((proc in row[self.command_name]) for row in self.data))
Are there any commands that contain the given text? Returns: boolean: ``True`` if the word ``proc`` appears in the command column. .. note:: 'proc' can match anywhere in the command path, name or arguments.
codesearchnet
def _linear(self, inputs): first_dims = shape_list(inputs)[:-1] x = tf.reshape(inputs, [-1, self.hidden_size]) logits = tf.matmul(x, self.weight, transpose_b=True) return tf.reshape(logits, first_dims + [self.vocab_size])
Computes logits by running inputs through a linear layer. Args: inputs: A float32 tensor with shape [..., hidden_size] Returns: float32 tensor with shape [..., vocab_size].
github-repos
def write_compartments(self, stream, compartments, adjacencies, properties=None): def convert(entry): return self.convert_compartment_entry(entry, adjacencies.get(entry.id)) self._write_entries(stream, compartments, convert, properties)
Write iterable of compartments as YAML object to stream. Args: stream: File-like object. compartments: Iterable of compartment entries. adjacencies: Dictionary mapping IDs to adjacent compartment IDs. properties: Set of compartment properties to output (or None to output all).
codesearchnet
def get(): result = runCommand('facter --json', raise_error_on_fail=True) json_facts = result[1] facts = json.loads(json_facts) return facts
Get local facts about this machine. Returns: json-compatible dict with all facts of this host
codesearchnet
def take_profit_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=TakeProfitOrderRequest(**kwargs) )
Shortcut to replace a pending Take Profit Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to create a TakeProfitOrderRequest Returns: v20.response.Response containing the results from submitting the request
juraj-google-style
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): super(Credential, self).read(input_stream, kmip_version=kmip_version) local_stream = BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.CREDENTIAL_TYPE, local_stream): self._credential_type = primitive...
Read the data encoding the Credential struct and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will b...
codesearchnet
def get_graph(self, item_ids, language=None): def _related(item_ids): if item_ids is None: items = Item.objects.filter(active=True).prefetch_related('parents', 'children') else: item_ids = [ii for iis in item_ids.values() for ii in iis] ...
Get a subgraph of items reachable from the given set of items through any relation. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in the given language Returns: dict: item id -> list of items (parent items), root items...
juraj-google-style
def register_mbr_plugin(self, fs_id, plugin): self.logger.debug('MBR: {}, FS ID: {}'.format(self.__get_plugin_name(plugin), fs_id)) self.__mbr_plugins[fs_id].append(plugin)
Used in plugin's registration routine, to associate it's detection method with given filesystem id Args: fs_id: filesystem id that is read from MBR partition entry plugin: plugin that supports this filesystem
codesearchnet
def hwvtep_add_loopback_interface(self, **kwargs): name = kwargs.pop('name') id = kwargs.pop('int_id') ip_args = dict(name=name, loopback_id=id) method_name = 'overlay_gateway_ip_interface_loopback_loopback_id' method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) ...
Add loopback interface to the overlay-gateway Args: name (str): gateway-name int_id (int): loopback inteface id callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
codesearchnet
def audio(self, audio, sample_rate, name=None, subdir=''): from chainerui.report.audio_report import check_available if not check_available(): return from chainerui.report.audio_report import report as _audio col_name = self.get_col_name(name, 'audio') out_...
Summary audio to listen on web browser. Args: audio (:class:`numpy.ndarray` or :class:`cupy.ndarray` or \ :class:`chainer.Variable`): sampled wave array. sample_rate (int): sampling rate. name (str): name of image. set as column name. when not setting, assigned ``'audio'`` + sequential number. subdir (str): sub-direct...
juraj-google-style
def do_post(endpoint, body, access_token): headers = {'content-type': 'application/json', 'Authorization': ('Bearer ' + access_token)} headers['User-Agent'] = get_user_agent() return requests.post(endpoint, data=body, headers=headers)
Do an HTTP POST request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to post. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
codesearchnet
def difference(self, *other): from_frozenset = self.items.difference(*map(set, other)) return self.from_iterable(from_frozenset, sort=True)
Returns a new :class:`FrameSet` with elements in `self` but not in `other`. Args: other (:class:`FrameSet`): or objects that can cast to :class:`FrameSet` Returns: :class:`FrameSet`:
juraj-google-style
def onScreen(x, y=None): x, y = _unpackXY(x, y) x = int(x) y = int(y) width, height = platformModule._size() return 0 <= x < width and 0 <= y < height
Returns whether the given xy coordinates are on the screen or not. Args: Either the arguments are two separate values, first arg for x and second for y, or there is a single argument of a sequence with two values, the first x and the second y. Example: onScreen(x, y) or onScreen([x, y]) Returns: bool: True if the xy ...
juraj-google-style
def merge_variables(variables, **kwargs): var_dict = OrderedDict() for v in variables: if v.name not in var_dict: var_dict[v.name] = [] var_dict[v.name].append(v) return [merge_variables(vars_, **kwargs) for vars_ in list(var_dict....
Concatenates Variables along row axis. Args: variables (list): List of Variables to merge. Variables can have different names (and all Variables that share a name will be concatenated together). Returns: A list of Variables.
juraj-google-style
def _longToBytestring(value, signed=False, numberOfRegisters=2): _checkInt(value, description='inputvalue') _checkBool(signed, description='signed parameter') _checkInt(numberOfRegisters, minvalue=2, maxvalue=2, description='number of registers') formatcode = '>' if signed: formatcod...
Convert a long integer to a bytestring. Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave. Args: * value (int): The numerical value to be converted. * signed (bool): Whether large positive values should be interpreted as negative values. * numberOfRegisters (int): Should be...
juraj-google-style
def __eq__(self, other): if not isinstance(other, SemanticTime): return False return self._SORT_ORDER == other._SORT_ORDER
Determines if the date time values are equal to other. Args: other (DateTimeValues): date time values to compare against. Returns: bool: True if the date time values are equal to other.
juraj-google-style
def get_schema_descendant( self, route: SchemaRoute) -> Optional[SchemaNode]: node = self for p in route: node = node.get_child(*p) if node is None: return None return node
Return descendant schema node or ``None`` if not found. Args: route: Schema route to the descendant node (relative to the receiver).
juraj-google-style
def eval_rs(gains, losses): count = (len(gains) + len(losses)) avg_gains = (stats.avg(gains, count=count) if gains else 1) avg_losses = (stats.avg(losses, count=count) if losses else 1) if (avg_losses == 0): return avg_gains else: return (avg_gains / avg_losses)
Evaluates the RS variable in RSI algorithm Args: gains: List of price gains. losses: List of prices losses. Returns: Float of average gains over average losses.
codesearchnet
def ValidateSyntax(rdf_artifact): if (not rdf_artifact.doc): raise rdf_artifacts.ArtifactSyntaxError(rdf_artifact, 'missing doc') for supp_os in rdf_artifact.supported_os: valid_os = rdf_artifact.SUPPORTED_OS_LIST if (supp_os not in valid_os): detail = ("invalid `supported_os...
Validates artifact syntax. This method can be used to validate individual artifacts as they are loaded, without needing all artifacts to be loaded first, as for Validate(). Args: rdf_artifact: RDF object artifact. Raises: ArtifactSyntaxError: If artifact syntax is invalid.
codesearchnet
def tuplize(nested): if isinstance(nested, str): return nested try: return tuple(map(tuplize, nested)) except TypeError: return nested
Recursively converts iterables into tuples. Args: nested: A nested structure of items and iterables. Returns: A nested structure of items and tuples.
codesearchnet
def _get_ground_truth_detections(instances_file, allowlist_file=None, num_images=None): with open(instances_file, 'r') as annotation_dump: data_dict = ast.literal_eval(annotation_dump.readline()) image_data = collections.OrderedDict() if allowlist_file is not None: with open(allowlist_file, ...
Processes the annotations JSON file and returns ground truth data corresponding to allowlisted image IDs. Args: instances_file: COCO instances JSON file, usually named as instances_val20xx.json. allowlist_file: File containing COCO minival image IDs to allowlist for evaluation, one per line. num_images: Number of allo...
github-repos
def accept_confirm(self, text=None, wait=None): with self.driver.accept_modal('confirm', text=text, wait=wait): (yield)
Execute the wrapped code, accepting a confirm. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFound: If a modal dialog hasn't been found.
codesearchnet
def receive(self): pickled_request = self._connection.connection.lpop(self._request_key) return (pickle.loads(pickled_request) if (pickled_request is not None) else None)
Returns a single request. Takes the first request from the list of requests and returns it. If the list is empty, None is returned. Returns: Response: If a new request is available a Request object is returned, otherwise None is returned.
codesearchnet
def on_item_changed(self, item, new_value, row, column): return (item, new_value, row, column)
Event for the item change. Args: emitter (TableWidget): The emitter of the event. item (TableItem): The TableItem instance. new_value (str): New text content. row (int): row index. column (int): column index.
codesearchnet
def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP: return Bsp(x, y, w, h)
Create a new BSP instance with the given rectangle. Args: x (int): Rectangle left coordinate. y (int): Rectangle top coordinate. w (int): Rectangle width. h (int): Rectangle height. Returns: BSP: A new BSP instance. .. deprecated:: 2.0 Call the :any:`BSP` class instead.
juraj-google-style
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...
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...
juraj-google-style
def _build_js(inputs, outputs, name, implementation, support_code): input_fields = json.dumps([f[0] for f in inputs]) output_fields = [{'name': f[0], 'type': f[1]} for f in outputs] output_fields = json.dumps(output_fields, sort_keys=True) if support_code is None: s...
Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of the function implementation: a javascript function defining the UDF logic. support_code: additional...
juraj-google-style
def is_object_new(self, func): self.load_lazy_attribute('__new__') self.load_lazy_attribute('__new__extra_args') return [func] == self.members['__new__'].data or [func] == self.members['__new__extra_args'].data
Whether the given function is object.__new__. Args: func: A function. Returns: True if func equals either of the pytd definitions for object.__new__, False otherwise.
github-repos
def convert_wav(org_wav_fn: Path, tgt_wav_fn: Path) -> None: if (not org_wav_fn.exists()): raise FileNotFoundError args = [config.FFMPEG_PATH, '-i', str(org_wav_fn), '-ac', '1', '-ar', '16000', str(tgt_wav_fn)] subprocess.run(args)
Converts the wav into a 16bit mono 16000Hz wav. Args: org_wav_fn: A `Path` to the original wave file tgt_wav_fn: The `Path` to output the processed wave file
codesearchnet
class CustomObjectScope: def __init__(self, custom_objects): self.custom_objects = custom_objects or {} self.backup = None def __enter__(self): self.backup = global_state.get_global_attribute('custom_objects_scope_dict', {}).copy() global_state.set_global_attribute('custom_obje...
Exposes custom classes/functions to Keras deserialization internals. Under a scope `with custom_object_scope(objects_dict)`, Keras methods such as `keras.models.load_model()` or `keras.models.model_from_config()` will be able to deserialize any custom object referenced by a saved config (e.g. a custom layer or metric)...
github-repos
def _worker(self, constructor, conn): try: env = constructor() while True: try: if (not conn.poll(0.1)): continue (message, payload) = conn.recv() except (EOFError, KeyboardInterrupt): break if (m...
The process waits for actions and sends back environment results. Args: constructor: Constructor for the OpenAI Gym environment. conn: Connection for communication to the main process. Raises: KeyError: When receiving a message of unknown type.
codesearchnet
def add_ref(self, timestamp: int) -> None: self._ref_times.append(timestamp)
Adds a reference to this tensor with the specified timestamp. Args: timestamp: Timestamp of object reference as an integer.
github-repos
def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): line = clean_lines.elided[linenum] match = Match(r'^(.*[^ ({>]){', line) if match: ...
Checks for horizontal spacing near commas. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: ...
juraj-google-style
def build_graph(device, input_shape, output_sizes, axis): with ops.device('/%s:0' % device): inp = array_ops.zeros(input_shape) outputs = [] for _ in range(100): outputs.extend(array_ops.split(inp, output_sizes, axis)) return control_flow_ops.group(*outputs)
Build a graph containing a sequence of split operations. Args: device: string, the device to run on. input_shape: shape of the input tensor. output_sizes: size of each output along axis. axis: axis to be split along. Returns: An array of tensors to run()
github-repos
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]: if token_ids_1 is None: raise ValueError('With TAPAS, you must provide both question IDs and table IDs.') return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1
Build model inputs from a question and flattened table for question answering or sequence classification tasks by concatenating and adding special tokens. Args: token_ids_0 (`List[int]`): The ids of the question. token_ids_1 (`List[int]`, *optional*): The ids of the flattened table. Returns: `List[int]`: The model in...
github-repos
def shell(cmd, *args, **kwargs): if (kwargs.get('rel_path') and (not cmd.startswith('/'))): cmd = os.path.join(kwargs['rel_path'], cmd) status = 0 try: output = subprocess.check_output(((cmd,) + args), stderr=kwargs.get('stderr')) except subprocess.CalledProcessError as e: if kwa...
Execute shell command and return output Args: cmd (str): the command itself, i.e. part until the first space *args: positional arguments, i.e. other space-separated parts rel_path (bool): execute relative to the path (default: `False`) raise_on_status(bool): bool, raise exception if command exited with non-zero status...
codesearchnet