code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def load_template(path_or_buffer): from itertools import groupby from operator import itemgetter path_or_buffer = _stringify_path(path_or_buffer) if is_file_like(path_or_buffer): templates = json.load(path_or_buffer) else: with open(path_or_buffer, 'r') as f: temp...
Build tabula-py option from template file Args: file_like_obj: File like object of Tabula app template Returns: `obj`:dict: tabula-py options
juraj-google-style
def set_json(self, reason='', new_page=False): compressed_json = json.dumps(self._compress_json(self.cached_json)) if len(compressed_json) > self.max_page_size: raise OverflowError( 'Usernotes page is too large (>{0} characters)'. format(self.max_pag...
Send the JSON from the cache to the usernotes wiki page. Arguments: reason: the change reason that will be posted to the wiki changelog (str) Raises: OverflowError if the new JSON data is greater than max_page_size
juraj-google-style
def AddForwardLoopCounter(self, outer_grad_state): n = constant_op.constant(0, name='f_count') if outer_grad_state is not None: outer_add_op = outer_grad_state.forward_index.op.inputs[0].op n.op._add_control_input(outer_add_op) self.Enter() self.AddName(n.name) enter_n = _Enter(n, se...
Adds a loop that counts the number of iterations. This is added to the forward loop at the time when we start to create the loop for backprop gradient computation. Called in the outer context of this forward context. The pseudocode is: `n = 0; while (_pivot) { n++; }` Note that a control dependency is added to `n` t...
github-repos
def AddStorageMediaImageOptions(self, argument_group): argument_group.add_argument( '--partitions', '--partition', dest='partitions', action='store', type=str, default=None, help=( 'Define partitions to be processed. A range of ' 'partitions can be defined as: "3..5". Mu...
Adds the storage media image options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
juraj-google-style
def listSubjects( self, query, status=None, start=None, count=None, vendorSpecific=None ): response = self.listSubjectsResponse( query, status, start, count, vendorSpecific ) return self._read_dataone_type_response(response, 'SubjectInfo')
See Also: listSubjectsResponse() Args: query: status: start: count: vendorSpecific: Returns:
juraj-google-style
def add_keyword(self, keyword, schema=None, source=None): keyword_dict = self._sourced_dict(source, value=keyword) if schema is not None: keyword_dict['schema'] = schema self._append_to('keywords', keyword_dict)
Add a keyword. Args: keyword(str): keyword to add. schema(str): schema to which the keyword belongs. source(str): source for the keyword.
juraj-google-style
def validate(self, x: symbolic.Symbolic) -> None: if self._validator is not None: self._validator(x)
Validates an input's integrity. This method will be called in :func:`pyglove.patch` when a chain of patchers have been applied, as to validate the patched object in chain still conforms to the patcher's plan. Args: x: The input after modification.
github-repos
def __init__(self, *args, **kwargs): super(EnrollmentTransaction, self).__init__(*args, **kwargs) self.Type = TransactionType.EnrollmentTransaction
Create an instance. Args: *args: **kwargs:
juraj-google-style
def try_pick_piece_of_work(self, worker_id, submission_id=None): client = self._datastore_client unclaimed_work_ids = None if submission_id: unclaimed_work_ids = [k for (k, v) in iteritems(self.work) if (is_unclaimed(v) and (v['submission_id'] == submission_id))] if (not unclaimed_work_ids): ...
Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work for this submission Returns: ID...
codesearchnet
def GetConsensusAddress(validators): vlen = len(validators) script = Contract.CreateMultiSigRedeemScript((vlen - int(((vlen - 1) / 3))), validators) return Crypto.ToScriptHash(script)
Get the script hash of the consensus node. Args: validators (list): of Ellipticcurve.ECPoint's Returns: UInt160:
codesearchnet
def do_operation_update(self, info, an_op): self.update_op_func(self.metric_name, info, an_op)
Updates an operation using the assigned update_op_func Args: info: (:class:`endpoints_management.control.report_request.Info`): the info instance to update an_op: (:class:`endpoints_management.control.report_request.Info`): the info instance to update Return: `True` if desc is supported, otherwise `False`
codesearchnet
def goto(self, iroute: 'InstanceRoute') -> 'InstanceNode': inst = self for sel in iroute: inst = sel.goto_step(inst) return inst
Move the focus to an instance inside the receiver's value. Args: iroute: Instance route (relative to the receiver). Returns: The instance node corresponding to the target instance. Raises: InstanceValueError: If `iroute` is incompatible with the receiver's value. NonexistentInstance: If the instance node doesn't exi...
codesearchnet
def log_cert_info(logger, msg_str, cert_obj): list(map(logger, (['{}:'.format(msg_str)] + [' {}'.format(v) for v in ['Subject: {}'.format(_get_val_str(cert_obj, ['subject', 'value'], reverse=True)), 'Issuer: {}'.format(_get_val_str(cert_obj, ['issuer', 'value'], reverse=True)), 'Not Valid Before: {}'.format(cert_o...
Dump basic certificate values to the log. Args: logger: Logger Logger to which to write the certificate values. msg_str: str A message to write to the log before the certificate values. cert_obj: cryptography.Certificate Certificate containing values to log. Returns: None
codesearchnet
def reflection(n1, n2): r = abs((n1-n2) / (n1+n2))**2 return r
Calculate the power reflection at the interface of two refractive index materials. Args: n1 (float): Refractive index of material 1. n2 (float): Refractive index of material 2. Returns: float: The percentage of reflected power.
juraj-google-style
def update_mp_firware_version(self, timeout=-1): uri = "{}/mpFirmwareVersion".format(self.data["uri"]) return self._helper.do_put(uri, None, timeout, None)
Updates the iLO firmware on a physical server to a minimum ILO firmware version required by OneView to manage the server. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: Resource
juraj-google-style
def get_class(schema_name): global _registry_loaded if not _registry_loaded: load_message_classes() try: return _schema_name_to_class[schema_name] except KeyError: _log.warning( 'The schema "%s" is not in the schema registry! Either install ' "the pa...
Retrieve the message class associated with the schema name. If no match is found, the default schema is returned and a warning is logged. Args: schema_name (six.text_type): The name of the :class:`Message` sub-class; this is typically the Python path. Returns: Message: A sub-class of :class:`Message` to create the m...
juraj-google-style
def diagonalize_real_symmetric_matrix(matrix: np.ndarray, *, rtol: float=1e-05, atol: float=1e-08) -> np.ndarray: if (np.any((np.imag(matrix) != 0)) or (not predicates.is_hermitian(matrix))): raise ValueError('Input must be real and symmetric.') (_, result) = np.linalg.eigh(matrix) return result
Returns an orthogonal matrix that diagonalizes the given matrix. Args: matrix: A real symmetric matrix to diagonalize. rtol: float = 1e-5, atol: float = 1e-8 Returns: An orthogonal matrix P such that P.T @ matrix @ P is diagonal. Raises: ValueError: Matrix isn't real symmetric.
codesearchnet
def includes(self, lo_freq: float) -> bool: if self._lb <= lo_freq <= self._ub: return True return False
Whether `lo_freq` is within the `LoRange`. Args: lo_freq: LO frequency to be checked Returns: bool: True if lo_freq is included in this range, otherwise False
juraj-google-style
def split_leading_dim(tensor, inputs, n_dims=2): input_shape_static = inputs.get_shape() input_shape_list = input_shape_static.as_list() tensor_shape_static = tensor.get_shape() tensor_shape_list = tensor_shape_static.as_list() if (input_shape_static.is_fully_defined() and tensor_shape_static.is_full...
Split the first dimension of a tensor. Args: tensor: Tensor to have its first dimension split. inputs: Original reference input to look the dimensions of. n_dims: Number of dimensions to split. Returns: The input tensor, with its first dimension split.
juraj-google-style
def _get_events_list(object_key: str) -> List[str]: return DB.get_list(_keys.events_list(object_key))
Get list of event ids for the object with the specified key. Args: object_key (str): Key of an object in the database.
codesearchnet
def get_worfklow_spec(self): if (self.current.workflow_name not in self.workflow_spec_cache): try: self.current.wf_object = BPMNWorkflow.objects.get(name=self.current.workflow_name) except ObjectDoesNotExist: self.current.wf_object = BPMNWorkflow.objects.get(name='not_found')...
Generates and caches the workflow spec package from BPMN diagrams that read from disk Returns: SpiffWorkflow Spec object.
codesearchnet
def add_string_pairs_from_text_view_element(xib_file, results, text_view, special_ui_components_prefix): text_view_entry_comment = extract_element_internationalized_comment(text_view) if (text_view_entry_comment is None): return if (text_view.hasAttribute('usesAttributedText') and (text_view.attribu...
Adds string pairs from a textview element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. text_view(element): The textview element from the xib, to extract the string pairs from. special_ui_components_prefix(str): A custom prefix for internationalize component to allow (def...
codesearchnet
def create_parser(): parser = argparse_flags.ArgumentParser(description='saved_model_cli: Command-line interface for SavedModel', conflict_handler='resolve') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers(title='commands', description='valid comm...
Creates a parser that parse the command line arguments. Returns: A namespace parsed from command line arguments.
github-repos
def _HasExpired(self, key): self.logger.debug('Processing key: %s.', key) try: (schema, json_str) = key.split(None, 3)[2:] except (ValueError, AttributeError): self.logger.debug('No schema identifier. Not expiring key.') return False if (schema != 'google-ssh'): self.logg...
Check whether an SSH key has expired. Uses Google-specific semantics of the OpenSSH public key format's comment field to determine if an SSH key is past its expiration timestamp, and therefore no longer to be trusted. This format is still subject to change. Reliance on it in any way is at your own risk. Args: key: st...
codesearchnet
def _parse_networks(service_list: dict) -> list: networks = [] for n_values in service_list['networks'].values(): for n_key, n_value in n_values.items(): if 'name' in n_key: networks.append(n_value) return networks
Parse network key. Args: service_list (dict): Service configurations Returns: list, List of networks
juraj-google-style
def _get_edge_sentences( G: AnalysisGraph, source: str, target: str ) -> List[str]: return chain.from_iterable( [ [repr(e.text) for e in s.evidence] for s in G.edges[source, target]["InfluenceStatements"] ] )
Return the sentences that led to the construction of a specified edge. Args: G source: The source of the edge. target: The target of the edge.
juraj-google-style
def calc_transition_to_state(self, newstate): cached_val = JTAGStateMachine._lookup_cache.get((self.state, newstate)) if cached_val: return cached_val if (newstate not in self.states): raise ValueError(('%s is not a valid state for this state machine' % newstate)) path = self._find_short...
Given a target state, generate the sequence of transitions that would move this state machine instance to that target state. Args: newstate: A str state name to calculate the path to. Returns: A bitarray containing the bits that would transition this state machine to the target state. The bits read from right to left...
codesearchnet
def gates_to_uncompute(self): q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q, name='disentangler') remaining_param = self.params for i in range(self.num_qubits): (remaining_param, thetas, phis) = Initialize._rotations_to_disentangle(remaining_param) rz_mult = self._multi...
Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to |00..0>
codesearchnet
def setSingleStep(self, singleStep): if not isinstance(singleStep, int): raise TypeError("Argument is not of type int") self._singleStep = abs(singleStep) return self._singleStep
setter to _singleStep. converts negativ values to positiv ones. Args: singleStep (int): new _singleStep value. converts negativ values to positiv ones. Raises: TypeError: If the given argument is not an integer. Returns: int or long: the absolute value of the given argument.
juraj-google-style
def put(self, block_id, priority, pb_type='offline'): if (pb_type not in ('offline', 'realtime')): raise ValueError('Invalid PB type.') with self._mutex: added_time = datetime.datetime.utcnow().isoformat() entry = (priority, (sys.maxsize - self._index), block_id, pb_type, added_time) ...
Add a Processing Block to the queue. When a new entry it added, the queue is (re-)sorted by priority followed by insertion order (older blocks with equal priority are first). Args: block_id (str): Processing Block Identifier priority (int): Processing Block scheduling priority (higher values = higher priority) pb_typ...
codesearchnet
def rental_report(self, address, zipcode, format_type="json"): query_params = { "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/rental_report", query_params)
Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json".
juraj-google-style
def get_user_info(self, token): url = self.get_user_info_url() try: headers = {'Authorization': 'Bearer {}'.format(token)} response = requests.get(url, headers=headers) except requests.RequestException: logger.exception('Failed to retrieve user info due to a request exception.') ...
Retrieves the user info from the OAuth provider. Arguments: token (str): OAuth2 access token. Returns: dict Raises: UserInfoRetrievalFailed: Retrieval of user info from the remote server failed.
codesearchnet
def get_key_counter_alg(seed, alg): if alg is None: alg = Algorithm.AUTO_SELECT.value alg = convert_alg_to_int(alg) key, counter = _get_key_counter(seed, alg) return (key, counter, alg)
Calculates the key, counter and algorithm to pass to raw RNG ops. This function calculates the key and counter, and determines the algorithm that will be passed to the raw RNG ops like `StatelessRandomUniformV2`. Depending on the input `alg`, the key and counter may be scrambled or copied from `seed`. If `alg` is `"au...
github-repos
def console_set_char_foreground(con: tcod.console.Console, x: int, y: int, col: Tuple[(int, int, int)]) -> None: lib.TCOD_console_set_char_foreground(_console(con), x, y, col)
Change the foreground color of x,y to col. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from the top. col (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance. .. deprecated:: 8.4 Array access performs significan...
codesearchnet
def append(self, text, afterline=None): if afterline: self._vim.current.buffer.append(text, afterline) else: self._vim.current.buffer.append(text)
Append text to the current buffer. Args: text (str or Sequence[str]): One or many lines of text to append. afterline (Optional[int]): Line number to append after. If 0, text is prepended before the first line; if ``None``, at end of the buffer.
codesearchnet
def import_project(self, file, path, namespace=None, overwrite=False, override_params=None, **kwargs): files = {'file': ('file.tar.gz', file)} data = {'path': path, 'overwrite': overwrite} if override_params: for (k, v) in override_params.items(): data[('override_params[%s]' % k)] = v ...
Import a project from an archive file. Args: file: Data or file object containing the project path (str): Name and path for the new project namespace (str): The ID or path of the namespace that the project will be imported to overwrite (bool): If True overwrite an existing project with the same path override_params (d...
codesearchnet
def create_from_json(cls, json_data): prop = Property() address_info = json_data['address_info'] prop.address = address_info['address'] prop.block_id = address_info['block_id'] prop.zipcode = address_info['zipcode'] prop.zipcode_plus4 = address_info['zipcode_plus4'] prop.address_full = addre...
Deserialize property json data into a Property object Args: json_data (dict): The json data for this property Returns: Property object
codesearchnet
def object_upload(self, bucket, key, content, content_type): args = {'uploadType': 'media', 'name': key} headers = {'Content-Type': content_type} url = (Api._UPLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, ''))) return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers, crede...
Writes text content to the object. Args: bucket: the name of the bucket containing the object. key: the key of the object to be written. content: the text content to be written. content_type: the type of text content. Raises: Exception if the object could not be written to.
codesearchnet
def set_aliases_and_defaults(self, aliases_config=None, default_properties=None): if (aliases_config is None): with open(os.path.join(os.path.dirname(__file__), 'aliases.json')) as f: d = json.load(f) self.aliases = d.get('aliases', {}) self.default_criteria = d.get('defa...
Set the alias config and defaults to use. Typically used when switching to a collection with a different schema. Args: aliases_config: An alias dict to use. Defaults to None, which means the default aliases defined in "aliases.json" is used. See constructor for format. default_properties: List of property names (strin...
codesearchnet
def run(self, verbose=True): self.results.clear() for analysis_group in self.config.analysis_groups: if analysis_group.providers: for provider in analysis_group.providers: logger.info('Run provider %s', provider.identifier) pr...
Run the analysis. Generate data from each provider, then check these data with every checker, and store the analysis results. Args: verbose (bool): whether to immediately print the results or not.
juraj-google-style
def _get_transformers(self): transformer_dict = {} for table in self.metadata['tables']: table_name = table['name'] for field in table['fields']: transformer_type = field.get('type') if transformer_type: col_name = field['name'] transformer...
Load the contents of meta_file and extract information about the transformers. Returns: dict: tuple(str, str) -> Transformer.
codesearchnet
def order(self, image_catalog_ids, batch_size=100, callback=None): def _order_single_batch(url_, ids, results_list): data = (json.dumps(ids) if (callback is None) else json.dumps({'acquisitionIds': ids, 'callback': callback})) r = self.gbdx_connection.post(url_, data=data) r.raise_for_statu...
Orders images from GBDX. Args: image_catalog_ids (str or list): A single catalog id or a list of catalog ids. batch_size (int): The image_catalog_ids will be split into batches of batch_size. The ordering API max batch size is 100, if batch_size is greater than 100 it will be truncated. callback (str): A url to call w...
codesearchnet
def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): with tf.name_scope('apply_gradients'): var_update_ops = [] for (vid, (g, v)) in enumerate(ps_var_grads): apply_gradient_op = opt.apply_gradients([(g, v)]) barrier = self._add_sync_queues_and_barrier('param...
Apply averaged gradients to ps vars, and then copy the updated variables back to each tower. Args: raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers ps_var_grads: Nvar x 2 (grad, ps_var) Returns: list of copy ops
codesearchnet
def call(self, inputs, training=None, mask=None): return self._run_internal_graph(inputs, training=training, mask=mask)
Calls the model on new inputs. In this case `call` just reapplies all ops in the graph to the new inputs (e.g. build a new computational graph from the provided inputs). Args: inputs: A tensor or list of tensors. training: Boolean or boolean scalar tensor, indicating whether to run the `Network` in training mode or i...
github-repos
def checkUser(self, user): return (not self.conn('POST', '{0}/GetCredentialType.srf'.format(SkypeConnection.API_MSACC), json={'username': user}).json().get('IfExistsResult'))
Query a username or email address to see if a corresponding Microsoft account exists. Args: user (str): username or email address of an account Returns: bool: whether the account exists
codesearchnet
def get_videos_for_course(course_id, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None): return _get_videos_for_filter({'courses__course_id': six.text_type(course_id), 'courses__is_hidden': False}, sort_field, sort_dir, pagination_conf)
Returns an iterator of videos for the given course id. Args: course_id (String) sort_field (VideoSortField) sort_dir (SortDirection) Returns: A generator expression that contains the videos found, sorted by the given field and direction, with ties broken by edx_video_id to ensure a total order.
codesearchnet
def get(cls): if cls.is_twoconspect: return (cls.subconspect_el.value or None) input_value = cls.input_el.value.strip() if (not input_value): return None mdt = conspectus.mdt_by_name.get(input_value) if (not mdt): alert(('Invalid sub-conspect `%s`!' % input_value)) re...
Get code selected by user. Returns: str: Code or None in case that user didn't selected anything yet.
codesearchnet
def lookup_descriptor(self, definition_name): try: return self.__descriptors[definition_name] except KeyError: pass if self.__descriptor_loader: definition = self.__descriptor_loader(definition_name) self.__descriptors[definition_name] = ...
Lookup descriptor by name. Get descriptor from library by name. If descriptor is not found will attempt to find via descriptor loader if provided. Args: definition_name: Definition name to find. Returns: Descriptor that describes definition name. Raises: DefinitionNotFoundError if not descriptor exists for definit...
juraj-google-style
def get(account): account = Account.get(account) if not account: return None acct_type = AccountType.get(account.account_type_id).account_type account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], acct_type) return account_class(account)
Returns the class object identified by `account_id` Args: account (`int`, `str`): Unique ID of the account to load from database Returns: `Account` object if found, else None
juraj-google-style
def Sleep(self, seconds): time.sleep((seconds - int(seconds))) for _ in range(int(seconds)): time.sleep(1) if (self.GetMemoryUsage() > self.memory_quota): raise MemoryError('Exceeded memory allowance.') if (not self.running): break
Sleep a given time in 1 second intervals. When a machine is suspended during a time.sleep(n) call for more than n seconds, sometimes the sleep is interrupted and all threads wake up at the same time. This leads to race conditions between the threads issuing the heartbeat and the one checking for it. By sleeping in sma...
codesearchnet
def guess_settings(self, major, minor): version = major, minor if self.vbr_method == 2: if version in ((3, 90), (3, 91), (3, 92)) and self.encoding_flags: if self.bitrate < 255: return u"--alt-preset %d" % self.bitrate else: ...
Gives a guess about the encoder settings used. Returns an empty string if unknown. The guess is mostly correct in case the file was encoded with the default options (-V --preset --alt-preset --abr -b etc) and no other fancy options. Args: major (int) minor (int) Returns: text
juraj-google-style
def get_readrows_iterator(bq_read_client: BigQueryReadClient, table_metadata: TableMetadata, columns: Iterable[str] | None=None, data_format: DataFormat=DataFormat.AVRO) -> Iterable[Mapping]: requested_session = ReadSession(table=table_metadata.table_path, data_format=data_format.value, read_options={'selected_fiel...
Get an Iterator of row Mappings with the requested columns of the table, using an authenticated BigQuery Storage API client. Note: Does NOT support nested columns. Args: * bq_read_client: BigQuery Storage API Read client * table_metadata: TableMetadata object * columns (optional): List of columns to select * data_for...
github-repos
def complete(self, stream): assert not self.is_complete() self._marker.addInputPort(outputPort=stream.oport) self.stream.oport.schema = stream.oport.schema self._pending_schema._set(self.stream.oport.schema) ...
Complete the pending stream. Any connections made to :py:attr:`stream` are connected to `stream` once this method returns. Args: stream(Stream): Stream that completes the connection.
juraj-google-style
def add_multiple_to_queue(self, items, container=None): if (container is not None): container_uri = container.resources[0].uri container_metadata = to_didl_string(container) else: container_uri = '' container_metadata = '' chunk_size = 16 item_list = list(items) for i...
Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items.
codesearchnet
def feed(self, data_len, feed_time=None): self._bytes_transferred += data_len self._collected_bytes_transferred += data_len time_now = feed_time or time.time() time_diff = time_now - self._last_feed_time if time_diff < self._sample_min_time: return ...
Update the bandwidth meter. Args: data_len (int): The number of bytes transfered since the last call to :func:`feed`. feed_time (float): Current time.
juraj-google-style
def user_lists(self, username, member_type="USER"): return self.client.service.getUserLists(username, member_type, self.proxy_id)
Look up all the lists that the user is a member of. Args: username (str): The MIT username of the user member_type(str): The type of user, "USER" or "STRING" Returns: list of strings: names of the lists that this user is a member of
juraj-google-style
def ask_for_approval(full_changeset=None, params_diff=None, include_verbose=False): approval_options = ['y', 'n'] if include_verbose: approval_options.append('v') approve = ui.ask("Execute the above changes? [{}] ".format( '/'.join(approval_options))).lower() ...
Prompt the user for approval to execute a change set. Args: full_changeset (list, optional): A list of the full changeset that will be output if the user specifies verbose. params_diff (list, optional): A list of DictValue detailing the differences between two parameters returned by :func:`stacker.actions.diff.diff_di...
juraj-google-style
def generate_string(self, initial_logits, initial_state, sequence_length): current_logits = initial_logits current_state = initial_state generated_letters = [] for _ in range(sequence_length): char_index = tf.squeeze(tf.multinomial(current_logits, 1)) char_one_hot = tf.one_hot(...
Builds sub-graph to generate a string, sampled from the model. Args: initial_logits: Starting logits to sample from. initial_state: Starting state for the RNN core. sequence_length: Number of characters to sample. Returns: A Tensor of characters, with dimensions `[sequence_length, batch_size, output_size]`.
juraj-google-style
def testDefaultBoundaryConditionsWithInnerTerm(self, default_bc): def second_order_coeff_fn(t, coord_grid): del t x = coord_grid[0] return [[-(-x ** 3 + x)]] def first_order_coeff_fn(t, coord_grid): del t x = coord_grid[0] return [1 + x] def inner_first_ord...
Test for PDE with default boundary condition with inner term. Take equation `u_{t} - (x - x**3)[u]_{xx} + (1 + x) * [(1 - x**2) u]_{x} + (2 * x**2 - 1 + 2 *x - (1 - x**2))u = 0` with boundary conditions `u_{t} + (x - 1) u_{x} = 0` at x = 0 and `u(t, 1) = exp(t + 1)`, and an initial condition `u(0, x) = exp(x)`. Solve...
github-repos
def close_stream_transport(self, stream_transport, timeout): with self._stream_transport_map_lock: if (stream_transport.local_id in self._stream_transport_map): del self._stream_transport_map[stream_transport.local_id] if stream_transport.remote_id: self.transport.wri...
Remove the given stream transport's id from our map of id's. If the stream id is actually removed, we send a CLSE message to let the remote end know (this happens when we are ack'ing a CLSE message we received). The ADB protocol doesn't say this is a requirement, but ADB does it, so we do too. Args: stream_transport...
codesearchnet
def _check_mr_state(cls, state, mr_id): if (state is None): logging.warning('Mapreduce State for job %s is missing. Dropping Task.', mr_id) return False if (not state.active): logging.warning('Mapreduce %s is not active. Looks like spurious task execution. Dropping Task.', mr_id) ...
Check MapreduceState. Args: state: an MapreduceState instance. mr_id: mapreduce id. Returns: True if state is valid. False if not and this task should be dropped.
codesearchnet
def get_compression_type_string(cls, options): if not options: return '' elif isinstance(options, TFRecordOptions): return cls.get_compression_type_string(options.compression_type) elif isinstance(options, TFRecordCompressionType): return cls.compression_type_map[options] elif op...
Convert various option types to a unified string. Args: options: `TFRecordOption`, `TFRecordCompressionType`, or string. Returns: Compression type as string (e.g. `'ZLIB'`, `'GZIP'`, or `''`). Raises: ValueError: If compression_type is invalid.
github-repos
def _render_trajectories(self, trajectories: Tuple[NonFluents, Fluents, Fluents, Fluents, np.array]) -> None: if self._verbose: non_fluents, initial_state, states, actions, interms, rewards = trajectories shape = states[0][1].shape batch_size, horizon, = ...
Prints the first batch of simulated `trajectories`. Args: trajectories: NonFluents, states, actions, interms and rewards.
juraj-google-style
def is_supported(cls, desc): for m in cls: if m.matches(desc): return True return False
Determines if the given metric descriptor is supported. Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the metric descriptor to test Return: `True` if desc is supported, otherwise `False`
juraj-google-style
def make_group_index(self, groupby_cols, bool_arr): (factor_list, values_list) = self.factorize_groupby_cols(groupby_cols) if (len(factor_list) == 0): tmp_rootdir = self.create_tmp_rootdir() carray_factor = bcolz.zeros(len(self), dtype='int64', rootdir=tmp_rootdir, mode='w') carray_value...
Create unique groups for groupby loop Args: factor_list: values_list: groupby_cols: bool_arr: Returns: carray: (carray_factor) int: (nr_groups) the number of resulting groups int: (skip_key)
codesearchnet
def _get_environment_updates(self, display_all_distributions=False): updates = [] for distribution in self.pip.get_installed_distributions(): versions = self.get_available_versions(distribution.project_name) max_version = max(versions.keys()) if versions else UNKNOW_NUM...
Check all pacakges installed in the environment to see if there are any updates availalble. Args: display_all_distributions (bool): Return distribution even if it is up-to-date. Defaults to ``False``. Returns: list: A list of Update objects ordered based on ``instance.name``.
juraj-google-style
def timestampFormat(self, timestampFormat): if not isinstance(timestampFormat, str): raise TypeError('not of type unicode') self._timestampFormat = timestampFormat
Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime Raises: AssertionError: if timestampFormat is not of type unicode. Args: timestampFormat (unicode): assign timestampFormat to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime. Used in dat...
juraj-google-style
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20): print '%s call joinCommissioned' % self.port self.__sendCommand('ifconfig up') cmd = 'joiner start %s %s' %(strPSKd, self.provisioningUrl) print cmd if self.__sendCommand(cmd)[0] == "Done": m...
start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner
juraj-google-style
def ParseForwardedIps(self, forwarded_ips): addresses = [] forwarded_ips = forwarded_ips or [] for ip in forwarded_ips: if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)): addresses.append(ip[:-3] if ip.endswith('/32') else ip) else: self.logger.warning('Could not pa...
Parse and validate forwarded IP addresses. Args: forwarded_ips: list, the IP address strings to parse. Returns: list, the valid IP address strings.
juraj-google-style
def __init__(self, comma_compat=False): self._comma_compat = comma_compat name = 'whitespace or comma' if self._comma_compat else 'whitespace' BaseListParser.__init__(self, None, name)
Initializer. Args: comma_compat: bool - Whether to support comma as an additional separator. If false then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated.
juraj-google-style
def _print_unhashable(df, columns=None): for c in df.columns if columns is None else columns: if df.dtypes[c] == object: try: df[c].apply(hash) except TypeError: df[c] = df[c].dropna().apply(pformat).ix[df.index] return df
Replace unhashable values in a DataFrame with their string repr Args: df: DataFrame columns: columns to replace, if necessary. Default None replaces all columns.
juraj-google-style
def _ParseMRUListKey(self, parser_mediator, registry_key, codepage='cp1252'): try: mrulist = self._ParseMRUListValue(registry_key) except (ValueError, errors.ParseError) as exception: parser_mediator.ProduceExtractionWarning('unable to parse MRUList value with error: {0!s}'.format(exception)) ...
Extract event objects from a MRUList Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. codepage (Optional[str]): extended ASCII string codepage.
codesearchnet
def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=('qualitative', 'Set1_9')): ticksize = int((width * 2.5)) golden_ratio = ((math.sqrt(5) - 1) / 2) if (not height): height = int((width * golden_ratio)) if (plt is None): import matplotlib.pyplot as plt import i...
Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt (matplotlib.pyplot): If plt is supplied, changes will be made to an existing plot. Otherwise, a new ...
codesearchnet
def desc_from_uri(uri): if ":" in uri: _, uri = uri.split(":", 1) query_string = parse_qs(urlparse(uri, 'http').query) if query_string.get('sn'): account_serial_number = query_string['sn'][0] try: acco...
Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'``
juraj-google-style
def _backspaced_single_line_animation(animation_, *args, **kwargs): animation_gen = animation_(*args, **kwargs) yield next(animation_gen) yield from util.concatechain( util.BACKSPACE_GEN(kwargs['width']), animation_gen)
Turn an animation into an automatically backspaced animation. Args: animation: A function that returns a generator that yields strings for animation frames. args: Arguments for the animation function. kwargs: Keyword arguments for the animation function. Returns: the animation generator, with backspaces applied to eac...
juraj-google-style
def post_headline(self, name, level, message): self._client.post_headline(name, level, message)
Asynchronously update the sticky headline for a service. Args: name (string): The name of the service level (int): A message level in states.*_LEVEL message (string): The user facing error message that will be stored for the service and can be queried later.
juraj-google-style
def energies(self, samples_like, dtype=np.float): samples, labels = as_samples(samples_like) if labels: idx, label = zip(*enumerate(labels)) labeldict = dict(zip(label, idx)) else: labeldict = {} num_samples = samples.shape[0] energi...
The energies of the given samples. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`, optional): The data type of the returned energies. Defaults to float. Returns: :obj:`numpy.ndarray`:...
juraj-google-style
def _init_global_step(self, global_step=USE_DEFAULT): if global_step is Supervisor.USE_DEFAULT: global_step = self._get_first_op_from_collection(ops.GraphKeys.GLOBAL_STEP) if global_step is None: global_step = self._default_global_step_tensor() if global_step is not None: ...
Initializes global_step. Args: global_step: An integer Tensor of size 1 that counts steps. If set to USE_DEFAULT, creates global_step tensor.
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: return self.prefix_tokens + token_ids_0 + self.suffix_tokens return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. The special tokens depend on calling set_lang. An SeamlessM4T sequence has the following format, where `X` represents the sequence: - `input_ids` (for encoder) `[src_lang_code] X [eos...
github-repos
def __init__(self, num_labels: int, matcher: MaskFormerHungarianMatcher, weight_dict: Dict[str, float], eos_coef: float): super().__init__() requires_backends(self, ['scipy']) self.num_labels = num_labels self.matcher = matcher self.weight_dict = weight_dict self.eos_coef = eos_coef empty_we...
The MaskFormer Loss. The loss is computed very similar to DETR. The process happens in two steps: 1) we compute hungarian assignment between ground truth masks and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and mask) Args: num_labels (`int`): The number of ...
github-repos
def put(f, s3_path, multipart_chunk_size_mb=500, logger=None): if not logger: logger = log.get_logger('s3') fname = os.path.basename(f) target = os.path.join(s3_path, fname) s3cmd_cline = 's3cmd put {} {} --multipart-chunk-size-mb {}'.format(f, ...
Uploads a single file to S3, using s3cmd. Args: f (str): Path to a single file. s3_path (str): The S3 path, with the filename omitted. The S3 filename will be the basename of the ``f``. For example:: put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/') will result in an uploaded S3 path of ``s3://my_...
juraj-google-style
def anchored_pairs(self, anchor): pairs = OrderedDict() for term in self.keys: score = self.get_pair(anchor, term) if score: pairs[term] = score return utils.sort_dict(pairs)
Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The distances, in descending order.
juraj-google-style
def add_chain(self, name, order): if name not in self.chains: setattr(self.chains, name, MarkovChain(order=order)) else: raise ValueError("Chain with this name already exists")
Add chain to current shelve file Args: name: chain name order: markov chain order
juraj-google-style
def update_shared_file(self, sharekey=None, title=None, description=None): if not sharekey: raise Exception( "You must specify a sharekey for the sharedfile" "you wish to update....
Update the editable details (just the title and description) of a SharedFile. Args: sharekey (str): Sharekey of the SharedFile to update. title (Optional[str]): Title of the SharedFile. description (Optional[str]): Description of the SharedFile Returns: SharedFile on success, 404 on Sharekey not found, 403 on unautho...
juraj-google-style
def easeInBack(n, s=1.70158): _checkRange(n) return ((n * n) * (((s + 1) * n) - s))
A tween function that backs up first at the start and then goes to the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
codesearchnet
def _calculate_scores(self, query, key): q_reshaped = ops.expand_dims(query, axis=-2) k_reshaped = ops.expand_dims(key, axis=-3) scale = self.scale if self.use_scale else 1.0 return ops.sum(scale * ops.tanh(q_reshaped + k_reshaped), axis=-1)
Calculates attention scores as a nonlinear sum of query and key. Args: query: Query tensor of shape `(batch_size, Tq, dim)`. key: Key tensor of shape `(batch_size, Tv, dim)`. Returns: Tensor of shape `(batch_size, Tq, Tv)`.
github-repos
def compute_probab_ratios(p_new, p_old, actions, reward_mask): (B, T) = actions.shape assert ((B, (T + 1)) == p_old.shape[:2]) assert ((B, (T + 1)) == p_new.shape[:2]) logp_old = chosen_probabs(p_old, actions) logp_new = chosen_probabs(p_new, actions) assert ((B, T) == logp_old.shape) assert...
Computes the probability ratios for each time-step in a trajectory. Args: p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy network assigns to all the actions at each time-step in each batch using the old parameters. p_old: ndarray of shape [B, T+1, A], same as above, but using old policy ne...
codesearchnet
def _SendItem(self, zmq_socket, item, block=True): try: logger.debug('{0:s} sending item'.format(self.name)) if block: zmq_socket.send_pyobj(item) else: zmq_socket.send_pyobj(item, zmq.DONTWAIT) logger.debug('{0:s} sent item'.format(self.name)) return ...
Attempts to send an item to a ZeroMQ socket. Args: zmq_socket (zmq.Socket): used to the send the item. item (object): sent on the queue. Will be pickled prior to sending. block (Optional[bool]): whether the push should be performed in blocking or non-blocking mode. Returns: bool: whether the item was sent successfull...
codesearchnet
def restore(self, file_prefix: tensor_lib.Tensor, options: 'checkpoint_options.CheckpointOptions | None'=None) -> Mapping[str, ops.Operation]: options = options or checkpoint_options.CheckpointOptions() def restore_fn() -> Mapping[str, ops.Operation]: restore_fn_inputs = {} restore_fn_input_cou...
Restore the saveable objects from a checkpoint with `file_prefix`. Args: file_prefix: A string or scalar string Tensor containing the prefix for files to read from. options: Optional `CheckpointOptions` object. Returns: When not run eagerly or when saving on a single device, returns a dictionary mapping from Saveable...
github-repos
def _get_latest_eval_step_value(update_ops): if isinstance(update_ops, dict): update_ops = list(update_ops.values()) with ops.control_dependencies(update_ops): return array_ops.identity(_get_or_create_eval_step().read_value())
Gets the eval step `Tensor` value after running `update_ops`. Args: update_ops: A list of `Tensors` or a dictionary of names to `Tensors`, which are run before reading the eval step value. Returns: A `Tensor` representing the value for the evaluation step.
github-repos
def economic_svd(G, epsilon=sqrt(finfo(float).eps)): from scipy.linalg import svd G = asarray(G, float) (U, S, V) = svd(G, full_matrices=False, check_finite=False) ok = (S >= epsilon) S = S[ok] U = U[(:, ok)] V = V[(ok, :)] return (U, S, V)
r"""Economic Singular Value Decomposition. Args: G (array_like): Matrix to be factorized. epsilon (float): Threshold on the square root of the eigen values. Default is ``sqrt(finfo(float).eps)``. Returns: :class:`numpy.ndarray`: Unitary matrix. :class:`numpy.ndarray`: Singular values. :class:`numpy.ndarray`: Unitary ...
codesearchnet
def convert(self, vroot, entry_variables): self.graph_info = GraphInfo(vroot) self.entry_variables = entry_variables with nn.parameter_scope(self.name): for t, func in enumerate(self.graph_info.funcs): if func....
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
juraj-google-style
def is_blast_result_trunc(qstart, qend, sstart, send, qlen, slen): q_match_len = abs(qstart - qend) + 1 s_max = max(sstart, send) s_min = min(sstart, send) return (q_match_len < qlen) and (s_max >= slen or s_min <= 1)
Check if a query sequence is truncated by the end of a subject sequence Args: qstart (int): Query sequence start index qend (int): Query sequence end index sstart (int): Subject sequence start index send (int): Subject sequence end index qlen (int): Query sequence length slen (int): Subject sequence length Returns: b...
juraj-google-style
def subscribe(self, clock_name: str=None, clock_slots: Iterable[str]=None, subscriptions: Dict[str, Any]={}): for area in subscriptions: init_full(self, area, subscriptions[area]) subscriptions[area] = {'slots': subscriptions[area]} if clock_name is not None: self.clock_name = clock_name self.cloc...
Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run. Args: clock_name: The name of the Area that is used as synchronizing Clock. clock_slots: The slots of the Clock relevant to this Area. subscriptions: A dictionary containing the relevant Areas names as keys and o...
juraj-google-style
def get_list_of_concatenated_objects(obj, dot_separated_name, lst=None): from textx.scoping import Postponed if lst is None: lst = [] if not obj: return lst if obj in lst: return lst lst.append(obj) if type(obj) is Postponed: ...
get a list of the objects consisting of - obj - obj+"."+dot_separated_name - (obj+"."+dot_separated_name)+"."+dot_separated_name (called recursively) Note: lists are expanded Args: obj: the starting point dot_separated_name: "the search path" (applied recursively) lst: the initial list (e.g. []) Returns: the filled l...
juraj-google-style
def check_for_empty_defaults(status): dirs_to_check = ('./vars', './handlers', './defaults', './tasks') for (dirpath, dirname, filename) in os.walk('.'): if ((dirpath == './files') or (dirpath == './templates')): if (not any([dirname, filename])): status.append('There are no ...
Method to check for empty roles structure. When a role is created using ansible-galaxy it creates a default scaffolding structure. Best practice dictates that if any of these are not used then they should be removed. For example a bare main.yml with the following string is created for a 'defaults' for a role called 'm...
codesearchnet
def _ParseNoHeaderSingleLine(self, parser_mediator, structure): if not self._last_event_data: logger.debug('SkyDrive, found isolated line with no previous events') return event_data = SkyDriveOldLogEventData() event_data.offset = self._last_event_data.offset event_data.text = structure...
Parse an isolated header line and store appropriate attributes. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file.
juraj-google-style
def kill_log_monitor(self, check_alive=True): self._kill_process_type(ray_constants.PROCESS_TYPE_LOG_MONITOR, check_alive=check_alive)
Kill the log monitor. Args: check_alive (bool): Raise an exception if the process was already dead.
codesearchnet
def dump(graphs, file, triples=False, cls=PENMANCodec, **kwargs): text = dumps(graphs, triples=triples, cls=cls, **kwargs) if hasattr(file, 'write'): print(text, file=file) else: with open(file, 'w') as fh: print(text, file=fh)
Serialize each graph in *graphs* to PENMAN and write to *file*. Args: graphs: an iterable of Graph objects file: a filename or file-like object to write to triples: if True, write graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls*
juraj-google-style
def apply_to_miz(self, miz): report = ['Building mission with weather:'] miz.mission.weather.wind_at_ground_level_dir = self.wind_at_ground_level_dir miz.mission.weather.wind_at_ground_level_speed = self.wind_at_ground_level_speed miz.mission.weather.wind_at2000_dir = self._ra...
Applies weather to an opened Miz file (the mission will be mutated) Args: miz: source miz Returns: True
juraj-google-style