code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def prng(s): return tf_np.asarray(s, dtype=_RNG_KEY_DTYPE)
Creates RNG state from seed. Args: s: the seed, an integer. Returns: An RNG state, as a scalar array of dtype `np.int64`.
github-repos
def WriteStatEntries(stat_entries, client_id, mutation_pool, token=None): for stat_response in stat_entries: if stat_response.pathspec.last.stream_name: stat_response.st_mode &= ~stat_type_mask stat_response.st_mode |= stat.S_IFREG if data_store.AFF4Enabled(): for stat_entry in stat_entries: CreateAFF4Object( stat_entry, client_id_urn=rdf_client.ClientURN(client_id), mutation_pool=mutation_pool, token=token) if data_store.RelationalDBEnabled(): path_infos = [rdf_objects.PathInfo.FromStatEntry(s) for s in stat_entries] data_store.REL_DB.WritePathInfos(client_id, _FilterOutPathInfoDuplicates(path_infos))
Persists information about stat entries. Args: stat_entries: A list of `StatEntry` instances. client_id: An id of a client the stat entries come from. mutation_pool: A mutation pool used for writing into the AFF4 data store. token: A token used for writing into the AFF4 data store.
juraj-google-style
def __init__(self, filename=None): self._alphabet = set() self.filename = filename if filename is not None: self._load_from_file(filename) super(SubwordTextEncoder, self).__init__()
Initialize and read from a file, if provided. Args: filename: filename from which to read vocab. If None, do not load a vocab
juraj-google-style
def get_grappler_config(optimizers_list): config = _config_pb2.ConfigProto() rewrite_options = config.graph_options.rewrite_options for optimizer in optimizers_list: rewrite_options.optimizers.append(optimizer) return config
Creates a tf.compat.v1.ConfigProto for configuring Grappler. Args: optimizers_list: List of strings that represents the list of optimizers. Returns: tf.ConfigProto.
github-repos
def authenticate(self, username, password, service='login', encoding='utf-8', resetcreds=True): @conv_func def my_conv(n_messages, messages, p_response, app_data): 'Simple conversation function that responds to any\n prompt where the echo is off with the supplied password' addr = calloc(n_messages, sizeof(PamResponse)) response = cast(addr, POINTER(PamResponse)) p_response[0] = response for i in range(n_messages): if (messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF): dst = calloc((len(password) + 1), sizeof(c_char)) memmove(dst, cpassword, len(password)) response[i].resp = dst response[i].resp_retcode = 0 return 0 if (sys.version_info >= (3,)): if isinstance(username, str): username = username.encode(encoding) if isinstance(password, str): password = password.encode(encoding) if isinstance(service, str): service = service.encode(encoding) else: if isinstance(username, unicode): username = username.encode(encoding) if isinstance(password, unicode): password = password.encode(encoding) if isinstance(service, unicode): service = service.encode(encoding) if ((b'\x00' in username) or (b'\x00' in password) or (b'\x00' in service)): self.code = 4 self.reason = 'strings may not contain NUL' return False cpassword = c_char_p(password) handle = PamHandle() conv = PamConv(my_conv, 0) retval = pam_start(service, username, byref(conv), byref(handle)) if (retval != 0): self.code = retval self.reason = 'pam_start() failed' return False retval = pam_authenticate(handle, 0) auth_success = (retval == 0) if (auth_success and resetcreds): retval = pam_setcred(handle, PAM_REINITIALIZE_CRED) self.code = retval self.reason = pam_strerror(handle, retval) if (sys.version_info >= (3,)): self.reason = self.reason.decode(encoding) if hasattr(libpam, 'pam_end'): pam_end(handle, retval) return auth_success
username and password authentication for the given service. Returns True for success, or False for failure. self.code (integer) and self.reason (string) are always stored and may be referenced for the reason why authentication failed. 0/'Success' will be stored for success. Python3 expects bytes() for ctypes inputs. This function will make necessary conversions using the supplied encoding. Inputs: username: username to authenticate password: password in plain text service: PAM service to authenticate against, defaults to 'login' Returns: success: True failure: False
codesearchnet
def run_query(self, view: views.View, limit: Optional[int]=None) -> bigquery.QueryJob: return self._client.query(self.to_sql(view, limit=limit))
Runs query for the view and returns the corresponding BigQuery job. Args: view: the view that defines the query to run. limit: optional limit of the number of items to return. Returns: bigquery.QueryJob: the job for the running query.
github-repos
def __init__( self, file_object, member_start_offset, uncompressed_data_offset): self.comment = None self.modification_time = None self.operating_system = None self.original_filename = None self._cache_start_offset = None self._cache_end_offset = None self._cache = b'' self.uncompressed_data_size = None self.uncompressed_data_offset = uncompressed_data_offset self.member_start_offset = member_start_offset self._file_object = file_object self._file_object.seek(self.member_start_offset, os.SEEK_SET) self._ReadMemberHeader(file_object) self._compressed_data_start = file_object.get_offset() self._decompressor_state = _GzipDecompressorState( self._compressed_data_start) self._LoadDataIntoCache(file_object, 0, read_all_data=True) self._ReadMemberFooter(file_object) self.member_end_offset = file_object.get_offset()
Initializes a gzip member. Args: file_object (FileIO): file-like object, containing the gzip member. member_start_offset (int): offset to the beginning of the gzip member in the containing file. uncompressed_data_offset (int): current offset into the uncompressed data in the containing file.
juraj-google-style
def union(self, other): union = Rect() lib.SDL_UnionRect(self._ptr, other._ptr, union._ptr) return union
Calculate the union of this rectangle and another rectangle. Args: other (Rect): The other rectangle. Returns: Rect: The union of this rectangle and the given other rectangle.
juraj-google-style
def set_hyperparameters(self, hyperparameters): for (block_name, block_hyperparams) in hyperparameters.items(): self.blocks[block_name].set_hyperparameters(block_hyperparams)
Set new hyperparameter values for some blocks. Args: hyperparameters (dict): A dictionary containing the block names as keys and the new hyperparameters dictionary as values.
codesearchnet
def notify_batch_pending(self, batch): txn_ids = {t.header_signature for t in batch.transactions} with self._lock: self._pending.add(batch.header_signature) self._batch_info[batch.header_signature] = txn_ids self._update_observers(batch.header_signature, ClientBatchStatus.PENDING)
Adds a Batch id to the pending cache, with its transaction ids. Args: batch (str): The id of the pending batch
juraj-google-style
def __init__(self, min_bundle_size=0, desired_bundle_size=DEFAULT_DESIRED_BUNDLE_SIZE, use_fastavro=True, with_filename=False, label='ReadAllFiles'): source_from_file = partial(_FastAvroSource, min_bundle_size=min_bundle_size) self._read_all_files = filebasedsource.ReadAllFiles(True, CompressionTypes.AUTO, desired_bundle_size, min_bundle_size, source_from_file, with_filename) self.label = label
Initializes ``ReadAllFromAvro``. Args: min_bundle_size: the minimum size in bytes, to be considered when splitting the input into bundles. desired_bundle_size: the desired size in bytes, to be considered when splitting the input into bundles. use_fastavro (bool): This flag is left for API backwards compatibility and no longer has an effect. Do not use. with_filename: If True, returns a Key Value with the key being the file name and the value being the actual data. If False, it only returns the data.
github-repos
def _export_debug_info(exported_graph: ops.Graph, export_dir: str): debug_builder = tf_stack.GraphDebugInfoBuilder() for fn_name in exported_graph._functions: fn = exported_graph._get_function(fn_name) if not isinstance(fn, defun.AtomicFunction): continue debug_builder.AppendGraphDebugInfo(fn_name, fn.graph_debug_info) graph_debug_info = debug_builder.Build() file_io.atomic_write_string_to_file(file_io.join(path_helpers.get_or_create_debug_dir(export_dir), constants.DEBUG_INFO_FILENAME_PB), graph_debug_info.SerializeToString(deterministic=True))
Exports debug information from graph to file. Creates and writes GraphDebugInfo with traces for ops in all functions of the exported_graph. Args: exported_graph: A Graph that has been created by tracing a saveable view. export_dir: SavedModel directory in which to write the debug info.
github-repos
def parse_command(command): command = command.strip() if not command: return [] brackets_intervals = [f.span() for f in _BRACKETS_PATTERN.finditer(command)] quotes_intervals = [f.span() for f in _QUOTES_PATTERN.finditer(command)] whitespaces_intervals = [f.span() for f in _WHITESPACE_PATTERN.finditer(command)] if not whitespaces_intervals: return [command] arguments = [] idx0 = 0 for start, end in whitespaces_intervals + [(len(command), None)]: if not any((interval[0] < start < interval[1] for interval in brackets_intervals + quotes_intervals)): argument = command[idx0:start] if argument.startswith('"') and argument.endswith('"') or (argument.startswith("'") and argument.endswith("'")): argument = argument[1:-1] arguments.append(argument) idx0 = end return arguments
Parse command string into a list of arguments. - Disregards whitespace inside double quotes and brackets. - Strips paired leading and trailing double quotes in arguments. - Splits the command at whitespace. Nested double quotes and brackets are not handled. Args: command: (str) Input command. Returns: (list of str) List of arguments.
github-repos
def _extract_nn_info(self, structure, nns): if self.targets is None: targets = structure.composition.elements else: targets = self.targets siw = [] max_weight = max(nn[self.weight] for nn in nns.values()) for nstats in nns.values(): site = nstats['site'] if nstats[self.weight] > self.tol * max_weight \ and self._is_in_targets(site, targets): nn_info = {'site': site, 'image': self._get_image(structure, site), 'weight': nstats[self.weight] / max_weight, 'site_index': self._get_original_site( structure, site)} if self.extra_nn_info: poly_info = nstats del poly_info['site'] nn_info['poly_info'] = poly_info siw.append(nn_info) return siw
Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors Args: structure (Structure): Structure being evaluated nns ([dicts]): Nearest neighbor information for a structure Returns: (list of tuples (Site, array, float)): See nn_info
juraj-google-style
def __init__(self, nlp, tokenizer, extractor_name: str) -> None: Extractor.__init__(self, input_type=InputType.TEXT, category="build_in_extractor", name=extractor_name) self._nlp = copy.deepcopy(nlp) self._like_email_matcher = Matcher(self._nlp.vocab) self._tokenizer = tokenizer
Initialize the extractor, storing the rule information and construct spacy rules Args: nlp: tokenizer: Tokenizer extractor_name: str Returns:
juraj-google-style
def parse_arguments(argv): parser = argparse.ArgumentParser(description='online-clustering') parser.add_argument('-m', '--mode', help='Mode to run pipeline in.', choices=['local', 'cloud'], default='local') parser.add_argument('-p', '--project', help='GCP project to run pipeline on.', default=cfg.PROJECT_ID) args, _ = parser.parse_known_args(args=argv) return args
It parses the arguments passed to the command line and returns them as an object Args: argv: The arguments passed to the command line. Returns: The arguments that are being passed in.
github-repos
def _init_from_proto(self, context_def, import_scope=None): assert isinstance(context_def, control_flow_pb2.WhileContextDef) g = ops.get_default_graph() self._name = ops.prepend_name_scope(context_def.context_name, import_scope) if context_def.maximum_iterations_name: self._maximum_iterations = g.as_graph_element(ops.prepend_name_scope(context_def.maximum_iterations_name, import_scope)) else: self._maximum_iterations = None self._parallel_iterations = context_def.parallel_iterations self._back_prop = context_def.back_prop self._swap_memory = context_def.swap_memory self._pivot_for_pred = g.as_graph_element(ops.prepend_name_scope(context_def.pivot_for_pred_name, import_scope)) self._pivot_for_body = g.as_graph_element(ops.prepend_name_scope(context_def.pivot_for_body_name, import_scope)) self._pivot = g.as_graph_element(ops.prepend_name_scope(context_def.pivot_name, import_scope)) self._loop_exits = [g.as_graph_element(ops.prepend_name_scope(exit_name, import_scope)) for exit_name in context_def.loop_exit_names] self._loop_enters = [g.as_graph_element(ops.prepend_name_scope(enter_name, import_scope)) for enter_name in context_def.loop_enter_names] super(WhileContext, self).__init__(values_def=context_def.values_def, import_scope=import_scope) if import_scope: for tensor_name in self._values: op = g.as_graph_element(tensor_name).op if util.IsLoopEnter(op): op._set_attr('frame_name', attr_value_pb2.AttrValue(s=compat.as_bytes(self.name))) self._graph = ops.get_default_graph()
Creates a new `WhileContext` from protocol buffer. Args: context_def: `WhileContextDef` protocol buffer. import_scope: Optional `string`. Name scope to add.
github-repos
def _xys(date): (X, Y, s_xy2) = _xysxy2(date) (dX, dY) = ((date.eop.dx / 1000.0), (date.eop.dy / 1000.0)) X = np.radians(((X + dX) / 3600.0)) Y = np.radians(((Y + dY) / 3600.0)) s = (np.radians((s_xy2 / 3600.0)) - ((X * Y) / 2)) return (X, Y, s)
Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians
codesearchnet
def is_union(declaration): if not is_class(declaration): return False decl = class_traits.get_declaration(declaration) return decl.class_type == class_declaration.CLASS_TYPES.UNION
Returns True if declaration represents a C++ union Args: declaration (declaration_t): the declaration to be checked. Returns: bool: True if declaration represents a C++ union
juraj-google-style
def reduce(self, initial_state, reduce_func):
Reduces this iterable object to a single element. The transformation calls `reduce_func` successively on each element. The `initial_state` argument is used for the initial state and the final state is returned as the result. Args: initial_state: An element representing the initial state of the reduction. reduce_func: A function that maps `(old_state, input_element)` to `new_state`. The structure of `new_state` must match the structure of `old_state`. For the first element, `old_state` is `initial_state`. Returns: The final state of the transformation.
github-repos
def _key_for_namespace(namespace, app): if namespace: return db.Key.from_path(metadata.Namespace.KIND_NAME, namespace, _app=app) else: return db.Key.from_path(metadata.Namespace.KIND_NAME, metadata.Namespace.EMPTY_NAMESPACE_ID, _app=app)
Return the __namespace__ key for a namespace. Args: namespace: The namespace whose key is requested. app: The id of the application that the key belongs to. Returns: A db.Key representing the namespace.
juraj-google-style
def state_view_for_block(block_wrapper, state_view_factory): state_root_hash = (block_wrapper.state_root_hash if (block_wrapper is not None) else None) return state_view_factory.create_view(state_root_hash)
Returns the state view for an arbitrary block. Args: block_wrapper (BlockWrapper): The block for which a state view is to be returned state_view_factory (StateViewFactory): The state view factory used to create the StateView object Returns: StateView object associated with the block
codesearchnet
def delete(self, domain, type_name, search_command): return self._request(domain, type_name, search_command, 'DELETE', None)
Delete entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES.
codesearchnet
def upsert(self, insert_index, val, fn=None): fn = fn or (lambda current, passed: passed) self._magnitude = 0 position = self.position_for_index(insert_index) if position < len(self.elements) and self.elements[position] == insert_index: self.elements[position + 1] = fn(self.elements[position + 1], val) else: self.elements.insert(position, val) self.elements.insert(position, insert_index)
Inserts or updates an existing index within the vector. Args: - insert_index (int): The index at which the element should be inserted. - val (int|float): The value to be inserted into the vector. - fn (callable, optional): An optional callable taking two arguments, the current value and the passed value to generate the final inserted value at the position in case of collision.
juraj-google-style
def __init__(self, c_list): c_list = [NthOrderElasticTensor(c, check_rank=4+i*2) for i, c in enumerate(c_list)] super().__init__(c_list)
Initialization method for ElasticTensorExpansion Args: c_list (list or tuple): sequence of Tensor inputs or tensors from which the elastic tensor expansion is constructed.
juraj-google-style
def _parameter_net(self, theta, kernel_shape=9): with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, (kernel_shape ** 2), nl=tf.identity) pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name='pred_filter') logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list())) return pred_filter
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
codesearchnet
def create_subscription(self, *, customer_id, credit_card_token, plan_code, quantity=None, installments=None, trial_days=None, immediate_payment=None, extra1=None, extra2=None, delivery_address=None, notify_url=None, recurring_bill_items=None): payload = {'quantity': quantity, 'installments': installments, 'trialDays': trial_days, 'immediatePayment': immediate_payment, 'extra1': extra1, 'extra2': extra2, 'customer': {'id': customer_id, 'creditCards': [{'token': credit_card_token}]}, 'plan': {'planCode': plan_code}, 'deliveryAddress': delivery_address, 'notifyUrl': notify_url, 'recurringBillItems': recurring_bill_items} return self.client._post((self.url + 'subscriptions'), json=payload, headers=self.get_headers())
Creating a new subscription of a client to a plan. Args: customer_id: Customer that will be associated to the subscription. You can find more information in the "Customer" section of this page. credit_card_token: Customer's credit card that is selected to make the payment. You can find more information in the "Credit card" section of this page. plan_code: Plan that will be associated to the subscription. You can find more information in the "Plan" section of this page. quantity: Total amount of plans that will be acquired with the subscription. Numeric. installments: Total amount of installments to defer the payment. Numeric. trial_days: Total amount of trial days of the subscription. This variable has preference over the plan's trial days. Numeric. immediate_payment: extra1: extra2: delivery_address: notify_url: recurring_bill_items: Returns:
codesearchnet
def _send_request(self, url, method='get', data=None, extra_headers=None): headers = {'Content-type': 'application/json'} if isinstance(extra_headers, dict): headers.update(extra_headers) if ((not data) or ('password' not in data)): logger.debug('Sending {method} request to {url} with data {data}'.format(method=method.upper(), url=url, data=data)) r = self.session.request(method, url, headers=headers, data=data) r.raise_for_status() return r.json()
Performs a given request and returns a json object Args: url (str): URL of the request method (str): Any of "get", "post", "delete" data (any): Possible extra data to send with the request extra_headers (dict): Possible extra headers to send along in the request Returns: dict
codesearchnet
def activate(self, experiment_key, user_id, attributes=None): if not self.is_valid: self.logger.error(enums.Errors.INVALID_DATAFILE.format('activate')) return None if not validator.is_non_empty_string(experiment_key): self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key')) return None if not isinstance(user_id, string_types): self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id')) return None variation_key = self.get_variation(experiment_key, user_id, attributes) if not variation_key: self.logger.info('Not activating user "%s".' % user_id) return None experiment = self.config.get_experiment_from_key(experiment_key) variation = self.config.get_variation_from_key(experiment_key, variation_key) self.logger.info('Activating user "%s" in experiment "%s".' % (user_id, experiment.key)) self._send_impression_event(experiment, variation, user_id, attributes) return variation.key
Buckets visitor and sends impression event to Optimizely. Args: experiment_key: Experiment which needs to be activated. user_id: ID for user. attributes: Dict representing user attributes and values which need to be recorded. Returns: Variation key representing the variation the user will be bucketed in. None if user is not in experiment or if experiment is not Running.
juraj-google-style
def create_graph_from_data(self, data, **kwargs): self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test] self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep] self.arguments['{DIRECTED}'] = 'TRUE' self.arguments['{ALPHA}'] = str(self.alpha) self.arguments['{NJOBS}'] = str(self.nb_jobs) self.arguments['{VERBOSE}'] = str(self.verbose).upper() results = self._run_pc(data, verbose=self.verbose) return nx.relabel_nodes(nx.DiGraph(results), {idx: i for idx, i in enumerate(data.columns)})
Run the PC algorithm. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by PC on the given data.
juraj-google-style
def write_all_sequences_file(self, outname, outdir=None): if not outdir: outdir = self.sequence_dir if not outdir: raise ValueError('Output directory must be specified') outfile = op.join(outdir, outname + '.faa') SeqIO.write(self.sequences, outfile, "fasta") log.info('{}: wrote all protein sequences to file'.format(outfile)) return outfile
Write all the stored sequences as a single FASTA file. By default, sets IDs to model gene IDs. Args: outname (str): Name of the output FASTA file without the extension outdir (str): Path to output directory for the file, default is the sequences directory
juraj-google-style
def iter_packages(self, name, range_=None, paths=None): for package in iter_packages(name, range_, paths): if not self.excludes(package): yield package
Same as iter_packages in packages.py, but also applies this filter. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or str): If provided, limits the versions returned to those in `range_`. paths (list of str, optional): paths to search for packages, defaults to `config.packages_path`. Returns: `Package` iterator.
juraj-google-style
def receive(self, length): slipDriver = sliplib.Driver() ret = self._serialPort.read(length) temp = slipDriver.receive(ret) return iter(temp)
Reads in data from a serial port (length bytes), decodes SLIP packets A function which reads from the serial port and then uses the SlipLib module to decode the SLIP protocol packets. Each message received is added to a receive buffer in SlipLib which is then returned. Args: length (int): Length to receive with serialPort.read(length) Returns: bytes: An iterator of the receive buffer
juraj-google-style
def parse(ifp, pb_cls, **kwargs): mode = 'rb' if isinstance(ifp, str): istream = open(ifp, mode=mode, **kwargs) else: istream = open(fileobj=ifp, mode=mode, **kwargs) with istream: for data in istream: pb_obj = pb_cls() pb_obj.ParseFromString(data) yield pb_obj
Parse a stream. Args: ifp (string or file-like object): input stream. pb_cls (protobuf.message.Message.__class__): The class object of the protobuf message type encoded in the stream.
juraj-google-style
def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False): if isinstance(ts, ops.Graph): if allow_graph: return get_tensors(ts) else: raise TypeError('allow_graph is False: cannot convert a tf.Graph.') else: if not is_iterable(ts): ts = [ts] if not ts: return [] if check_graph: check_types = None if ignore_ops else tensor_lib.Tensor get_unique_graph(ts, check_types=check_types) return [t for t in ts if isinstance(t, tensor_lib.Tensor)]
Convert ts to a list of `tf.Tensor`. Args: ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor. check_graph: if `True` check if all the tensors belong to the same graph. allow_graph: if `False` a `tf.Graph` cannot be converted. ignore_ops: if `True`, silently ignore `tf.Operation`. Returns: A newly created list of `tf.Tensor`. Raises: TypeError: if `ts` cannot be converted to a list of `tf.Tensor` or, if `check_graph` is `True`, if all the ops do not belong to the same graph.
github-repos
def set_defaults(self, defaults): def defaults_recurse(current, defaults): "Walk the current context tree in recursive inner function.\n\n On 1st iteration, current = self (i.e root of context)\n On subsequent recursive iterations, current is wherever you're at\n in the nested context hierarchy.\n\n Args:\n current: dict. Destination of merge.\n defaults: dict. Add this to current if keys don't exist\n already.\n\n " for (k, v) in defaults.items(): k = self.get_formatted_string(k) if (k in current): if types.are_all_this_type(Mapping, current[k], v): defaults_recurse(current[k], v) else: current[k] = self.get_formatted_iterable(v) defaults_recurse(self, defaults)
Set defaults in context if keys do not exist already. Adds the input dict (defaults) into the context, only where keys in defaults do not already exist in context. Supports nested hierarchies. Example: Given a context like this: key1: value1 key2: key2.1: value2.1 key3: None And defaults input like this: key1: 'updated value here won't overwrite since it already exists' key2: key2.2: value2.2 key3: 'key 3 exists so I won't overwrite Will result in context: key1: value1 key2: key2.1: value2.1 key2.2: value2.2 key3: None Args: defaults: dict. Add this dict into context. Returns: None. All operations mutate this instance of context.
codesearchnet
def __init__(self, credential=None): self.credential = credential
Initializes FormatToQido. Args: credential: # type: Google credential object, if it is specified, the Http client will use it instead of the default one.
github-repos
def GetMessages(self, soft_size_limit=None): with self._lock: ret = rdf_flows.MessageList() ret_size = 0 for message in self._Generate(): self._total_size -= len(message) ret.job.append(rdf_flows.GrrMessage.FromSerializedString(message)) ret_size += len(message) if ((soft_size_limit is not None) and (ret_size > soft_size_limit)): break return ret
Retrieves and removes the messages from the queue. Args: soft_size_limit: int If there is more data in the queue than soft_size_limit bytes, the returned list of messages will be approximately this large. If None (default), returns all messages currently on the queue. Returns: rdf_flows.MessageList A list of messages that were .Put on the queue earlier.
codesearchnet
def softsign(x): if any_symbolic_tensors((x,)): return Softsign().symbolic_call(x) return backend.nn.softsign(x)
Softsign activation function. It is defined as `f(x) = x / (abs(x) + 1)`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor([-0.100, -10.0, 1.0, 0.0, 100.0]) >>> keras.ops.softsign(x) Array([-0.09090909, -0.90909094, 0.5, 0.0, 0.990099], dtype=float32)
github-repos
def WritePathHashHistory(self, client_path, hash_entries): client_path_history = ClientPathHistory() for (timestamp, hash_entry) in iteritems(hash_entries): client_path_history.AddHashEntry(timestamp, hash_entry) self.MultiWritePathHistory({client_path: client_path_history})
Writes a collection of `Hash` observed for particular path. Args: client_path: A `ClientPath` instance. hash_entries: A dictionary with timestamps as keys and `Hash` instances as values.
codesearchnet
def recommendations(self, **kwargs): path = self._get_id_path('recommendations') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get a list of recommended movies for a movie. Args: language: (optional) ISO 639-1 code. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict representation of the JSON returned from the API.
codesearchnet
def _ReadStructureDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False): if is_member: error_message = 'data type not supported as member' raise errors.DefinitionReaderError(definition_name, error_message) return self._ReadDataTypeDefinitionWithMembers(definitions_registry, definition_values, data_types.StructureDefinition, definition_name, supports_conditions=True)
Reads a structure data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type definition is a member data type definition. Returns: StructureDefinition: structure data type definition. Raises: DefinitionReaderError: if the definitions values are missing or if the format is incorrect.
codesearchnet
def _remove_hdxobject(self, objlist, obj, matchon='id', delete=False): if objlist is None: return False if isinstance(obj, six.string_types): obj_id = obj elif isinstance(obj, dict) or isinstance(obj, HDXObject): obj_id = obj.get(matchon) else: raise HDXError('Type of object not a string, dict or T<=HDXObject') if not obj_id: return False for i, objdata in enumerate(objlist): objid = objdata.get(matchon) if objid and objid == obj_id: if delete: objlist[i].delete_from_hdx() del objlist[i] return True return False
Remove an HDX object from a list within the parent HDX object Args: objlist (List[Union[T <= HDXObject,Dict]]): list of HDX objects obj (Union[T <= HDXObject,Dict,str]): Either an id or hdx object metadata either from an HDX object or a dictionary matchon (str): Field to match on. Defaults to id. delete (bool): Whether to delete HDX object. Defaults to False. Returns: bool: True if object removed, False if not
juraj-google-style
def print_math(math_expression_lst, name='math.html', out='html', formatter=(lambda x: x)): try: shutil.rmtree('viz') except: pass pth = (get_cur_path() + print_math_template_path) shutil.copytree(pth, 'viz') html_loc = None if (out == 'html'): html_loc = (pth + 'standalone_index.html') if (out == 'notebook'): from IPython.display import display, HTML html_loc = (pth + 'notebook_index.html') html = open(html_loc).read() html = html.replace('__MATH_LIST__', json.dumps(math_expression_lst)) if (out == 'notebook'): display(HTML(html)) elif (out == 'html'): with open(name, 'w+') as out_f: out_f.write(html)
Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. Args: math_expression_lst (list): A list of LaTeX math (string) to be rendered by KaTeX out (string): {"html"|"notebook"}: HTML by default. Specifies output medium. formatter (function): function that cleans up the string for KaTeX. Returns: A HTML file in the directory where this function is called, or displays HTML output in a notebook.
codesearchnet
def dot(matrix, vector, matrix_ty, vector_ty): weld_obj = WeldObject(encoder_, decoder_) matrix_var = weld_obj.update(matrix) if isinstance(matrix, WeldObject): matrix_var = matrix.obj_id weld_obj.dependencies[matrix_var] = matrix vector_var = weld_obj.update(vector) loopsize_annotation = '' if isinstance(vector, WeldObject): vector_var = vector.obj_id weld_obj.dependencies[vector_var] = vector if isinstance(vector, np.ndarray): loopsize_annotation = ('@(loopsize: %dL)' % len(vector)) weld_template = '\n map(\n %(matrix)s,\n |row: vec[%(matrix_ty)s]|\n result(\n %(loopsize_annotation)s\n for(\n result(\n %(loopsize_annotation)s\n for(\n zip(row, %(vector)s),\n appender,\n |b2, i2, e2: {%(matrix_ty)s, %(vector_ty)s}|\n merge(b2, f64(e2.$0 * %(matrix_ty)s(e2.$1)))\n )\n ),\n merger[f64,+],\n |b, i, e| merge(b, e)\n )\n )\n )\n ' weld_obj.weld_code = (weld_template % {'matrix': matrix_var, 'vector': vector_var, 'matrix_ty': matrix_ty, 'vector_ty': vector_ty, 'loopsize_annotation': loopsize_annotation}) return weld_obj
Computes the dot product between a matrix and a vector. Args: matrix (WeldObject / Numpy.ndarray): 2-d input matrix vector (WeldObject / Numpy.ndarray): 1-d input vector ty (WeldType): Type of each element in the input matrix and vector Returns: A WeldObject representing this computation
codesearchnet
def get_enterprise_customer_for_user(auth_user): EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser') try: return EnterpriseCustomerUser.objects.get(user_id=auth_user.id).enterprise_customer except EnterpriseCustomerUser.DoesNotExist: return None
Return enterprise customer instance for given user. Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model, 1. if given user is associated with any enterprise customer, return enterprise customer. 2. otherwise return `None`. Arguments: auth_user (contrib.auth.User): Django User Returns: (EnterpriseCustomer): enterprise customer associated with the current user.
codesearchnet
def boxify(message, border_color=None): lines = message.split('\n') max_width = max((_visual_width(line) for line in lines)) padding_horizontal = 5 padding_vertical = 1 box_size_horizontal = (max_width + (padding_horizontal * 2)) chars = {'corner': '+', 'horizontal': '-', 'vertical': '|', 'empty': ' '} margin = '{corner}{line}{corner}\n'.format(corner=chars['corner'], line=(chars['horizontal'] * box_size_horizontal)) padding_lines = [('{border}{space}{border}\n'.format(border=colorize(chars['vertical'], color=border_color), space=(chars['empty'] * box_size_horizontal)) * padding_vertical)] content_lines = ['{border}{space}{content}{space}{border}\n'.format(border=colorize(chars['vertical'], color=border_color), space=(chars['empty'] * padding_horizontal), content=_visual_center(line, max_width)) for line in lines] box_str = '{margin}{padding}{content}{padding}{margin}'.format(margin=colorize(margin, color=border_color), padding=''.join(padding_lines), content=''.join(content_lines)) return box_str
Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color to outline the box with.
codesearchnet
def get_osdp(self, id_or_uri): uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path='osdp') return self._client.get(uri)
Retrieves facts about Server Profiles and Server Profile Templates that are using Deployment Plan based on the ID or URI provided. Args: id_or_uri: ID or URI of the Deployment Plan. Returns: dict: Server Profiles and Server Profile Templates
codesearchnet
def on_predict_end(self, logs=None):
Called at the end of prediction. Subclasses should override for any actions to run. Args: logs: Dict. Currently no data is passed to this argument for this method but that may change in the future.
github-repos
def add_headers(vcf_obj, nr_cases=None, sv=False): vcf_obj.add_info_to_header({'ID': 'Obs', 'Number': '1', 'Type': 'Integer', 'Description': 'The number of observations for the variant'}) if (not sv): vcf_obj.add_info_to_header({'ID': 'Hom', 'Number': '1', 'Type': 'Integer', 'Description': 'The number of observed homozygotes'}) vcf_obj.add_info_to_header({'ID': 'Hem', 'Number': '1', 'Type': 'Integer', 'Description': 'The number of observed hemizygotes'}) if nr_cases: case_header = ' vcf_obj.add_to_header(case_header) return
Add loqus specific information to a VCF header Args: vcf_obj(cyvcf2.VCF)
codesearchnet
def _ParseCshVariables(self, lines): paths = {} for line in lines: if (len(line) < 2): continue action = line[0] if (action == 'setenv'): target = line[1] path_vals = [] if line[2:]: path_vals = line[2].split(':') self._ExpandPath(target, path_vals, paths) elif (action == 'set'): set_vals = self._CSH_SET_RE.search(' '.join(line[1:])) if set_vals: (target, vals) = set_vals.groups() if (target in ('path', 'term', 'user')): target = target.upper() path_vals = vals.split() self._ExpandPath(target, path_vals, paths) return paths
Extract env_var and path values from csh derivative shells. Path attributes can be set several ways: - setenv takes the form "setenv PATH_NAME COLON:SEPARATED:LIST" - set takes the form "set path_name=(space separated list)" and is automatically exported for several types of files. The first entry in each stanza is used to decide what context to use. Other entries are used to identify the path name and any assigned values. Args: lines: A list of lines, each of which is a list of space separated words. Returns: a dictionary of path names and values.
codesearchnet
def find_all(self, collection): obj = getattr(self.db, collection) result = obj.find() return result
Search a collection for all available items. Args: collection: The db collection. See main class documentation. Returns: List of all items in the collection.
codesearchnet
def pre(fqdn, parent, stackdepth, *argl, **argd): global _atdepth_call, _cstack_call pcres = _pre_call(_atdepth_call, parent, fqdn, (stackdepth + 1), *argl, **argd) (entry, _atdepth_call, reduced, bound, ekey) = pcres _cstack_call.append(fqdn) return (entry, bound, ekey)
Adds logging for a call to the specified function that is being handled by an external module. Args: fqdn (str): fully-qualified domain name of the function being logged. parent: *object* that the function belongs to. stackdepth (int): maximum stack depth before entries are ignored. argl (list): positional arguments passed to the function call. argd (dict): keyword arguments passed to the function call.
codesearchnet
def tail(self, n): if (n < 0): n = max(0, (len(self.index) + n)) if self._is_transposed: result = self.__constructor__(self.data.transpose().take(1, (- n)).transpose(), self.index[(- n):], self.columns, self._dtype_cache) result._is_transposed = True else: result = self.__constructor__(self.data.take(0, (- n)), self.index[(- n):], self.columns, self._dtype_cache) return result
Returns the last n rows. Args: n: Integer containing the number of rows to return. Returns: DataManager containing the last n rows of the original DataManager.
codesearchnet
def __init__(self, api_key: str, config: interfaces.Config | None=None): self._config = config or interfaces.Config() self._p_genai_model = genai_model.GenaiModel(api_key=api_key, model_name=self._config.topic_generator_model_name, generate_content_config={'response_mime_type': 'application/json', 'response_schema': list[interfaces.Topic]}) self._num_topics = self._config.num_topics preamble_content = [ProcessorPart(prompts.TOPIC_GENERATION_PREAMBLE), ProcessorPart(f)] if self._config.excluded_topics: preamble_content.append(ProcessorPart(f'Here is a list of topics that should be excluded: {self._config.excluded_topics}')) preamble_content.append(ProcessorPart('You will now be provided with the user content.')) p_preamble = preamble.Preamble(content=preamble_content) p_suffix = preamble.Suffix(content=[ProcessorPart(f'Return your response as Topics JSON in the format below.\n\nYou MUST return exactly {self._config.num_topics} topics.\n\nTopic\n topic: str\n relationship_to_user_content: list[str]\n\nTopics\n list[Topic]\n\nYour JSON:\n')]) self._pipeline = p_preamble + p_suffix + self._p_genai_model
Initializes the TopicGenerator. Args: api_key: The API key to use for the GenAI API. config: The agent configuration.
github-repos
def get_critical_compositions(self, comp1, comp2): n1 = comp1.num_atoms n2 = comp2.num_atoms pd_els = self.elements c1 = self.pd_coords(comp1) c2 = self.pd_coords(comp2) if np.all(c1 == c2): return [comp1.copy(), comp2.copy()] intersections = [c1, c2] for sc in self.simplexes: intersections.extend(sc.line_intersection(c1, c2)) intersections = np.array(intersections) l = (c2 - c1) l /= np.sum(l ** 2) ** 0.5 proj = np.dot(intersections - c1, l) proj = proj[np.logical_and(proj > -self.numerical_tol, proj < proj[1] + self.numerical_tol)] proj.sort() valid = np.ones(len(proj), dtype=np.bool) valid[1:] = proj[1:] > proj[:-1] + self.numerical_tol proj = proj[valid] ints = c1 + l * proj[:, None] cs = np.concatenate([np.array([1 - np.sum(ints, axis=-1)]).T, ints], axis=-1) x = proj / np.dot(c2 - c1, l) x_unnormalized = x * n1 / (n2 + x * (n1 - n2)) num_atoms = n1 + (n2 - n1) * x_unnormalized cs *= num_atoms[:, None] return [Composition((c, v) for c, v in zip(pd_els, m)) for m in cs]
Get the critical compositions along the tieline between two compositions. I.e. where the decomposition products change. The endpoints are also returned. Args: comp1, comp2 (Composition): compositions that define the tieline Returns: [(Composition)]: list of critical compositions. All are of the form x * comp1 + (1-x) * comp2
juraj-google-style
def __init__(self, channel: 'EFBChannel', new_chats: Iterable[str] = tuple(), removed_chats: Iterable[str] = tuple(), modified_chats: Iterable[str] = tuple()): self.channel: 'EFBChannel' = channel self.new_chats: Iterable[str] = new_chats self.removed_chats: Iterable[str] = removed_chats self.modified_chats: Iterable[str] = modified_chats self.destination_channel: 'EFBChannel' = coordinator.master
__init__(channel: EFBChannel, new_chats: Iterable[str]=tuple(), removed_chats: Iterable[str]=tuple(), modified_chats: Iterable[str]=tuple()) Args: channel (:obj:`.EFBChannel`): Slave channel that issues the update new_chats (Optional[Iterable[str]]): Unique ID of new chats removed_chats (Optional[Iterable[str]]): Unique ID of removed chats modified_chats (Optional[Iterable[str]]): Unique ID of modified chats
juraj-google-style
def GetHashData(hashable): ms = StreamManager.GetStream() writer = BinaryWriter(ms) hashable.SerializeUnsigned(writer) ms.flush() retVal = ms.ToArray() StreamManager.ReleaseStream(ms) return retVal
Get the data used for hashing. Args: hashable (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin Returns: bytes:
juraj-google-style
def __init__(self, auth_key, auth_secret): self._auth_key = auth_key self._auth_secret = auth_secret
Create an authentication handler for HouseCanary API V1 requests Args: auth_key (string) - The HouseCanary API auth key auth_secret (string) - The HouseCanary API secret
juraj-google-style
def getPaddingNum(chars): match = PRINTF_SYNTAX_PADDING_RE.match(chars) if match: return int(match.group(1)) try: return sum([PAD_MAP[char] for char in chars]) except KeyError: msg = 'Detected an unsupported padding character: "{}".' msg += ' Supported padding characters: {} or printf syntax padding' msg += ' %<int>d' raise ValueError(msg.format(char, str(PAD_MAP.keys())))
Given a supported group of padding characters, return the amount of padding. Args: chars (str): a supported group of padding characters Returns: int: Raises: ValueError: if unsupported padding character is detected
codesearchnet
def insecure_channel(target, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming)
Creates an insecure Channel to a server. Args: target: The server address options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
codesearchnet
def read_uint64(self, little_endian=True): if little_endian: endian = '<' else: endian = '>' return self.unpack(('%sQ' % endian), 8)
Read 8 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int:
codesearchnet
def add_device(self, device, container): if (self.findtext('is_smart') == 'false'): self.add_object_to_path(device, container) else: raise ValueError('Devices may not be added to smart groups.')
Add a device to a group. Wraps JSSObject.add_object_to_path. Args: device: A JSSObject to add (as list data), to this object. location: Element or a string path argument to find()
codesearchnet
def get_by_name(self, name): result = self.get_by("name", name) if result: data = result[0] new_resource = self.new(self._connection, data) else: new_resource = None return new_resource
Retrieves a resource by its name. Args: name: Resource name. Returns: Resource object or None if resource does not exist.
juraj-google-style
def drop_if_default(self, default): self._default = default self._drop_if_default = True return self
The item should be dropped if its value is equal to its default. Returns: Returns self.
github-repos
def really_unicode(in_string): if isinstance(in_string, StringType): for args in (('utf-8',), ('latin-1',), ('ascii', 'replace')): try: in_string = in_string.decode(*args) break except UnicodeDecodeError: continue if not isinstance(in_string, UnicodeType): raise ValueError('%s is not a string at all.' % in_string) return in_string
Make a string unicode. Really. Ensure ``in_string`` is returned as unicode through a series of progressively relaxed decodings. Args: in_string (str): The string to convert. Returns: str: Unicode. Raises: ValueError
juraj-google-style
def make_lines_texture(num_lines=10, resolution=50): x, y = np.meshgrid( np.hstack([np.linspace(0, 1, resolution), np.nan]), np.linspace(0, 1, num_lines), ) y[np.isnan(x)] = np.nan return x.flatten(), y.flatten()
Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int): the number of lines to draw resolution (int): the number of midpoints on each line Returns: A texture.
juraj-google-style
def is_constant_jacobian(self): return self._is_constant_jacobian
Returns true iff the Jacobian matrix is not a function of x. Note: Jacobian matrix is either constant for both forward and inverse or neither. Returns: is_constant_jacobian: Python `bool`.
github-repos
def get_local_config_filepath(config_filepath, force_local=False): local_config_name = (path.basename(config_filepath).split('.')[0] + '_local.cfg') local_config_filepath = path.join(path.split(config_filepath)[0], local_config_name) real_config_filepath = '' if (path.isfile(local_config_filepath) or force_local): real_config_filepath = local_config_filepath else: real_config_filepath = config_filepath return real_config_filepath
helper for finding local filepath for config Args: config_filepath (str): path to local config abspath > relpath force_local (bool): force return of _local.cfg version Returns: str: Path to local config, or global if path DNE
codesearchnet
def as_bool(self) -> bool: if len(self._messages) != 1: raise ValueError('FHIRPath did not evaluate to a single boolean.') return proto_utils.get_value_at_field(self._messages[0], 'value')
Returns the result as a boolean. Raises: ValueError if the `EvaluationResult` is not a single boolean.
github-repos
def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]: sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep + token_ids_1 + sep) * [0]
Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not make use of token type ids, therefore a list of zeros is returned. Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of zeros.
github-repos
def create_mutation_file(self, list_of_tuples): self.mutation_infile = op.join(self.foldx_dir, 'individual_list.txt') idx = 1 with open(self.mutation_infile, 'w') as f: for mutant_group in list_of_tuples: mutstring = ''.join(list(map(lambda x: '{}{}{}{};'.format(x[0], x[1], x[2], x[3]), mutant_group))) f.write(mutstring + '\n') self.mutation_index_to_group[idx] = mutant_group idx += 1
Create the FoldX file 'individual_list.txt' to run BuildModel upon. Args: list_of_tuples (list): A list of tuples indicating mutation groups to carry out BuildModel upon. Example:: [ (('N', 'A', 308, 'S'), ('S', 'A', 320, 'T'), ('S', 'A', 321, 'H')), # Mutation group 1 (('S', 'A', 321, 'R'), ('T', 'A', 345, 'S')) # Mutation group 2 ]
juraj-google-style
def emit(self, name, *args, **kwargs): e = self.__property_events.get(name) if e is None: e = self.__events[name] return e(*args, **kwargs)
Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :class:`Event` to dispatch *args (Optional): Positional arguments to be sent to listeners **kwargs (Optional): Keyword arguments to be sent to listeners
juraj-google-style
def items(self): all_items = [(k.decode('utf-8'), v.decode('utf-8')) for (k, v) in self.rdb.hgetall(self.session_hash).items()] return all_items
Return a list of all the key, value pair tuples in the dictionary. Returns: list of tuples: [(key1,value1),(key2,value2),...,(keyN,valueN)]
codesearchnet
def __init__(self, logger): self.logger = logger self.oslogin_installed = True self.update_time = 0
Constructor. Args: logger: logger object, used to write to SysLog and serial port.
juraj-google-style
def _parse_dtype(self, space): if isinstance(space, gym.spaces.Discrete): return tf.int32 if isinstance(space, gym.spaces.Box): return tf.float32 raise NotImplementedError()
Get a tensor dtype from a OpenAI Gym space. Args: space: Gym space. Raises: NotImplementedError: For spaces other than Box and Discrete. Returns: TensorFlow data type.
juraj-google-style
def next_power_of_2(x): power_of_2 = 1 if x == 0 else 2 ** np.ceil(np.log2(x)) return power_of_2
Finds the next power of 2 value Args: x: Input value Returns: power_of_2: Next power of 2 value
juraj-google-style
def get_developer_package(path, format=None): from rez.developer_package import DeveloperPackage return DeveloperPackage.from_path(path, format=format)
Create a developer package. Args: path (str): Path to dir containing package definition file. format (str): Package definition file format, detected if None. Returns: `DeveloperPackage`.
codesearchnet
def argmax(x, axis=None, keepdims=False): if any_symbolic_tensors((x,)): return Argmax(axis=axis, keepdims=keepdims).symbolic_call(x) return backend.numpy.argmax(x, axis=axis, keepdims=keepdims)
Returns the indices of the maximum values along an axis. Args: x: Input tensor. axis: By default, the index is into the flattened tensor, otherwise along the specified axis. keepdims: If this is set to `True`, the axes which are reduced are left in the result as dimensions with size one. Defaults to `False`. Returns: Tensor of indices. It has the same shape as `x`, with the dimension along `axis` removed. Example: >>> x = keras.ops.arange(6).reshape(2, 3) + 10 >>> x array([[10, 11, 12], [13, 14, 15]], dtype=int32) >>> keras.ops.argmax(x) array(5, dtype=int32) >>> keras.ops.argmax(x, axis=0) array([1, 1, 1], dtype=int32) >>> keras.ops.argmax(x, axis=1) array([2, 2], dtype=int32)
github-repos
def send_invitation(self, invitation, **kwargs): return self.email_message( invitation.invitee_identifier, self.invitation_subject, self.invitation_body, invitation.invited_by, **kwargs ).send()
Sends an invitation message for a specific invitation. This could be overridden to do other things, such as sending a confirmation email to the sender. Args: invitation: Returns:
juraj-google-style
def valid(self, value, level=[]): self.validation_failures = [] if value is None and self._optional: return True if not isinstance(value, dict): self.validation_failures.append(('.'.join(level), str(value))) return False bRet = True for k,v in iteritems(value): lLevel = level[:] lLevel.append(k) if not self._key.valid(k): self.validation_failures.append(('.'.join(lLevel), 'invalid key: %s' % str(k))) bRet = False continue if not self._node.valid(v, lLevel): self.validation_failures.extend(self._node.validation_failures) bRet = False continue return bRet
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
juraj-google-style
def _add_sink_state(self, states): cleared = [] for i in range(0, 128): cleared.append(-1) states.append(cleared)
This function adds a sing state in the total states Args: states (list): The current states Returns: None
juraj-google-style
class TokenSpan(NamedTuple): start: int end: int
Token span in an encoded string (list of tokens). Args: start (`int`): Index of the first token in the span. end (`int`): Index of the token following the last token in the span.
github-repos
def diffuse_horizontal_illuminance(self, value=999999.0): if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `diffuse_horizontal_illuminance`'.format(value)) if value < 0.0: raise ValueError('value need to be greater or equal 0.0 ' 'for field `diffuse_horizontal_illuminance`') self._diffuse_horizontal_illuminance = value
Corresponds to IDD Field `diffuse_horizontal_illuminance` will be missing if >= 999900 Args: value (float): value for IDD Field `diffuse_horizontal_illuminance` Unit: lux value >= 0.0 Missing value: 999999.0 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
async def count(self, text, opts=None): i = 0 async for _ in self.cell.eval(text, opts=opts, user=self.user): i += 1 return i
Count the number of nodes which result from a storm query. Args: text (str): Storm query text. opts (dict): Storm query options. Returns: (int): The number of nodes resulting from the query.
juraj-google-style
def _tag_and_add_meta_graph(self, meta_graph_def, tags, signature_def_map): for tag in tags: meta_graph_def.meta_info_def.tags.append(tag) if signature_def_map is not None: for key in signature_def_map: meta_graph_def.signature_def[key].CopyFrom(signature_def_map[key]) proto_meta_graph_def = self._saved_model.meta_graphs.add() proto_meta_graph_def.CopyFrom(meta_graph_def)
Tags the meta graph def and adds it to the SavedModel. Tags the meta graph def with the supplied tags, adds signature defs to it if provided and appends the meta graph def to the SavedModel proto. Args: meta_graph_def: The meta graph def to add to the SavedModel. tags: The set of tags to annotate the meta graph def with. signature_def_map: The map of signature defs to be added to the meta graph def.
github-repos
def fetcher_with_object(cls, parent_object, relationship="child"): fetcher = cls() fetcher.parent_object = parent_object fetcher.relationship = relationship rest_name = cls.managed_object_rest_name() parent_object.register_fetcher(fetcher, rest_name) return fetcher
Register the fetcher for a served object. This method will fill the fetcher with `managed_class` instances Args: parent_object: the instance of the parent object to serve Returns: It returns the fetcher instance.
juraj-google-style
def base_http_parser(): base_parser = ArgumentParser(add_help=False) base_parser.add_argument('--url', type=str, help="identify the URL of the validator's REST API (default: http: base_parser.add_argument('-u', '--user', type=str, metavar='USERNAME[:PASSWORD]', help='specify the user to authorize request') return base_parser
Creates a parser with arguments specific to sending an HTTP request to the REST API. Returns: {ArgumentParser}: Base parser with default HTTP args
codesearchnet
def sasl_plain(self, name, password, identity=None): if identity is None: identity = name self.sasl('plain', name, password, identity)
Authenticate to a server using SASL plain, or does so on connection. Args: name (str): Name to auth with. password (str): Password to auth with. identity (str): Identity to auth with (defaults to name).
juraj-google-style
def set_colour(self, r, g, b): if not 0 <= r <= 255: raise ValueError("The value for red needs to be between 0 and 255.") if not 0 <= g <= 255: raise ValueError("The value for green needs to be between 0 and 255.") if not 0 <= b <= 255: raise ValueError("The value for blue needs to be between 0 and 255.") hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b) payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR, self.DPS_INDEX_COLOUR: hexvalue}) data = self._send_receive(payload) return data
Set colour of an rgb bulb. Args: r(int): Value for the colour red as int from 0-255. g(int): Value for the colour green as int from 0-255. b(int): Value for the colour blue as int from 0-255.
juraj-google-style
def __sendCommand(self, cmd): logging.info('%s: sendCommand[%s]', self.port, cmd) if self.logThreadStatus == self.logStatus['running']: self.logThreadStatus = self.logStatus['pauseReq'] while self.logThreadStatus != self.logStatus['paused'] and self.logThreadStatus != self.logStatus['stop']: pass ssh_stdin = None ssh_stdout = None ssh_stderr = None try: retry_times = 3 while retry_times > 0: retry_times -= 1 try: if self._is_net: ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command(cmd) else: self._sendline(cmd) self._expect(cmd) except Exception as e: logging.exception('%s: failed to send command[%s]: %s', self.port, cmd, str(e)) if retry_times == 0: raise else: break line = None response = [] retry_times = 20 stdout_lines = [] stderr_lines = [] if self._is_net: stdout_lines = ssh_stdout.readlines() stderr_lines = ssh_stderr.readlines() if stderr_lines: for stderr_line in stderr_lines: if re.search(r'Not\s+Found|failed\s+with\s+error', stderr_line.strip(), re.M | re.I): print "Command failed:" + stderr_line return 'Fail' print "Got line: " + stderr_line logging.info('%s: the read line is[%s]', self.port, stderr_line) response.append(str(stderr_line.strip())) elif stdout_lines: for stdout_line in stdout_lines: logging.info('%s: the read line is[%s]', self.port, stdout_line) if re.search(r'Not\s+Found|failed\s+with\s+error', stdout_line.strip(), re.M | re.I): print "Command failed" return 'Fail' print "Got line: " + stdout_line logging.info('%s: send command[%s] done!', self.port, cmd) response.append(str(stdout_line.strip())) response.append(WPAN_CARRIER_PROMPT) return response else: while retry_times > 0: line = self._readline() print "read line: %s" % line logging.info('%s: the read line is[%s]', self.port, line) if line: response.append(line) if re.match(WPAN_CARRIER_PROMPT, line): break elif re.search(r'Not\s+Found|failed\s+with\s+error', line, re.M | re.I): print "Command failed" return 'Fail' retry_times -= 1 time.sleep(0.1) if retry_times == 0: raise Exception('%s: failed to find end of response' % self.port) logging.info('%s: send command[%s] done!', self.port, cmd) return response except Exception, e: ModuleHelper.WriteIntoDebugLogger('sendCommand() Error: ' + str(e)) raise
send specific command to reference unit over serial port Args: cmd: OpenThread_WpanCtl command string Returns: Fail: Failed to send the command to reference unit and parse it Value: successfully retrieve the desired value from reference unit Error: some errors occur, indicates by the followed specific error number
juraj-google-style
def date_to_integer(date): if pd and isinstance(date, pd.Timestamp): try: date = date.to_datetime64() except: date = date.to_datetime() if isinstance(date, np.datetime64): return date.astype('datetime64[ms]').astype(float) elif isinstance(date, cftime_types): return cftime_to_timestamp(date, 'ms') if hasattr(date, 'timetuple'): dt_int = calendar.timegm(date.timetuple())*1000 else: raise ValueError('Datetime type not recognized') return dt_int
Converts support date types to milliseconds since epoch Attempts highest precision conversion of different datetime formats to milliseconds since the epoch (1970-01-01 00:00:00). If datetime is a cftime with a non-standard calendar the caveats described in hv.core.util.cftime_to_timestamp apply. Args: date: Date- or datetime-like object Returns: Milliseconds since 1970-01-01 00:00:00
juraj-google-style
def index_worker_output(self, worker_name, md5, index_name, subfield): if subfield: data = self.work_request(worker_name, md5)[worker_name][subfield] else: data = self.work_request(worker_name, md5)[worker_name] self.indexer.index_data(data, index_name=index_name, doc_type='unknown')
Index worker output with the Indexer. Args: worker_name: 'strings', 'pe_features', whatever md5: the md5 of the sample index_name: the name of the index subfield: index just this subfield (None for all) Returns: Nothing
juraj-google-style
def download_from_s3(context): target_file = context.solid_config['target_file'] return context.resources.download_manager.download_file_contents(context, target_file)
Download an object from s3. Args: info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource. Returns: str: The path to the downloaded object.
codesearchnet
def __init__(self, offset, size, extent_type=EXTENT_TYPE_DATA): super(VolumeExtent, self).__init__() self.offset = offset self.size = size self.extent_type = extent_type
Initializes a volume extent. Args: offset (int): start offset of the extent, in bytes. size (int): size of the extent, in bytes. extent_type (Optional[str]): type of extent.
juraj-google-style
def sample(self, hashes): api_name = 'opendns-sample' fmt_url_path = u'sample/{0}' return self._multi_get(api_name, fmt_url_path, hashes)
Get the information about a sample based on its hash. Args: hashes: an enumerable of strings as hashes Returns: An enumerable of arrays which contains the information about the original samples
juraj-google-style
def scrape_info(self, request, response, link_type=None): info = {} for scraper in self._document_scrapers: scrape_result = scraper.scrape(request, response, link_type) info[scraper] = scrape_result return info
Iterate the scrapers and return a dict of results. Returns: dict: A dict where the keys are the scrapers instances and the values are the results. That is, a mapping from :class:`BaseDocumentScraper` to :class:`ScrapeResult`.
codesearchnet
def _Insert(cursor, table, values): precondition.AssertIterableType(values, dict) if (not values): return column_names = list(sorted(values[0])) for value_dict in values: if (set(column_names) != set(value_dict)): raise ValueError('Given value dictionaries must have identical keys. Expecting columns {!r}, but got value {!r}'.format(column_names, value_dict)) query = ('INSERT IGNORE INTO %s {cols} VALUES {vals}' % table) query = query.format(cols=mysql_utils.Columns(column_names), vals=mysql_utils.Placeholders(num=len(column_names), values=len(values))) values_list = [] for values_dict in values: values_list.extend((values_dict[column] for column in column_names)) cursor.execute(query, values_list)
Inserts one or multiple rows into the given table. Args: cursor: The MySQL cursor to perform the insertion. table: The table name, where rows should be inserted. values: A list of dicts, associating column names to values.
codesearchnet
def _zip_files(files, root): zip_data = StringIO() with ZipFile(zip_data, 'w', ZIP_DEFLATED) as zip_file: for fname in files: zip_file.write(os.path.join(root, fname), fname) for zip_entry in zip_file.filelist: perms = ((zip_entry.external_attr & ZIP_PERMS_MASK) >> 16) if ((perms & stat.S_IXUSR) != 0): new_perms = 493 else: new_perms = 420 if (new_perms != perms): logger.debug('lambda: fixing perms: %s: %o => %o', zip_entry.filename, perms, new_perms) new_attr = ((zip_entry.external_attr & (~ ZIP_PERMS_MASK)) | (new_perms << 16)) zip_entry.external_attr = new_attr contents = zip_data.getvalue() zip_data.close() content_hash = _calculate_hash(files, root) return (contents, content_hash)
Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive, relative to ``root``. root (str): base directory to retrieve files from. Returns: str: content of the ZIP file as a byte string. str: A calculated hash of all the files.
codesearchnet
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False): oslogin_configured = self._GetStatus(two_factor=False) if (oslogin_configured is None): return None two_factor_configured = self._GetStatus(two_factor=True) two_factor_desired = (two_factor_desired and oslogin_desired) if oslogin_desired: params = ['activate'] if two_factor_desired: params += ['--twofactor'] if (not oslogin_configured): self.logger.info('Activating OS Login.') return (self._RunOsLoginControl(params) or self._RunOsLoginNssCache()) if (two_factor_desired and (not two_factor_configured)): self.logger.info('Activating OS Login two factor authentication.') return (self._RunOsLoginControl(params) or self._RunOsLoginNssCache()) if (two_factor_configured and (not two_factor_desired)): self.logger.info('Reactivating OS Login with two factor disabled.') return (self._RunOsLoginControl(['deactivate']) or self._RunOsLoginControl(params)) current_time = time.time() if ((current_time - self.update_time) > NSS_CACHE_DURATION_SEC): self.update_time = current_time return self._RunOsLoginNssCache() elif oslogin_configured: self.logger.info('Deactivating OS Login.') return (self._RunOsLoginControl(['deactivate']) or self._RemoveOsLoginNssCache()) return 0
Update whether OS Login is enabled and update NSS cache if necessary. Args: oslogin_desired: bool, enable OS Login if True, disable if False. two_factor_desired: bool, enable two factor if True, disable if False. Returns: int, the return code from updating OS Login, or None if not present.
codesearchnet