code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def remove_showcase(self, showcase): dataset_showcase = self._get_dataset_showcase_dict(showcase) showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration) showcase._write_to_hdx('disassociate', dataset_showcase, 'package_id')
Remove dataset from showcase Args: showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary Returns: None
codesearchnet
def _initialize_global_state(self, redis_address, redis_password=None, timeout=20): self.redis_client = services.create_redis_client( redis_address, redis_password) start_time = time.t...
Initialize the GlobalState object by connecting to Redis. It's possible that certain keys in Redis may not have been fully populated yet. In this case, we will retry this method until they have been populated or we exceed a timeout. Args: redis_address: The Redis address to connect. redis_password: The password of th...
juraj-google-style
def request_token(self) -> None: response: requests.Response = requests.post(self._TOKEN_URL, auth=HTTPBasicAuth(self._client_id, self._client_key), data={'grant_type': self._GRANT_TYPE}, verify=True) response.raise_for_status() self._token = response.json() self._token_expires_at = (time.time() + self....
Requests a new Client Credentials Flow authentication token from the Spotify API and stores it in the `token` property of the object. Raises: requests.HTTPError: If an HTTP error occurred during the request.
codesearchnet
def update_course(self, course, enterprise_customer, enterprise_context): course['course_runs'] = self.update_course_runs( course_runs=course.get('course_runs') or [], enterprise_customer=enterprise_customer, enterprise_context=enterprise_context, ) ...
Update course metadata of the given course and return updated course. Arguments: course (dict): Course Metadata returned by course catalog API enterprise_customer (EnterpriseCustomer): enterprise customer instance. enterprise_context (dict): Enterprise context to be added to course runs and URLs.. Returns: (dict): Up...
juraj-google-style
def put(self, item): QueueBase.put(self, item) if self.sender: self.sender.start()
Adds the passed in item object to the queue and notifies the :func:`sender` to start an asynchronous send operation by calling :func:`start`. Args: item (:class:`contracts.Envelope`) the telemetry envelope object to send to the service.
juraj-google-style
def Decrypt(self, encrypted_data): index_split = -(len(encrypted_data) % Blowfish.block_size) if index_split: remaining_encrypted_data = encrypted_data[index_split:] encrypted_data = encrypted_data[:index_split] else: remaining_encrypted_data = b'' decrypted_data = self._blowfish...
Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes,bytes]: decrypted data and remaining encrypted data.
juraj-google-style
def size(input, name=None, out_type=None): if out_type is None: if flags.config().tf_shape_default_int64.value(): out_type = dtypes.int64 else: out_type = dtypes.int32 return size_internal(input, name, optimize=True, out_type=out_type)
Returns the size of a tensor. Returns a 0-D `Tensor` representing the number of elements in `input` of type `out_type`. Defaults to tf.int32. For example: ```python t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) tf.size(t) # 12 ``` Args: input: A `Tensor` or `SparseTensor`. name: A name for the ...
github-repos
def ngettext_lazy(singular, plural, n, domain=DEFAULT_DOMAIN): return LazyProxy(ngettext, singular, plural, n, domain=domain, enable_cache=False)
Mark a message with plural forms translateable, and delay the translation until the message is used. Works the same was a `ngettext`, with a delaying functionality similiar to `gettext_lazy`. Args: singular (unicode): The singular form of the message. plural (unicode): The plural form of the message. n (int): The num...
codesearchnet
def next(self): smallest = None for key in self.queue.keys(): if (self.queue[key]['status'] == 'queued'): if ((smallest is None) or (key < smallest)): smallest = key return smallest
Get the next processable item of the queue. A processable item is supposed to have the status `queued`. Returns: None : If no key is found. Int: If a valid entry is found.
codesearchnet
def create_update_event(self): events = [] for (fields, rules) in iteritems(self._meta.update_messages): if (not isinstance(fields, (list, tuple, set))): fields = (fields,) changed = any([(getattr(self, field) != getattr(self.get_original(), field)) for field in fields]) if c...
Parse the update messages DSL to insert the data into the Event. Returns: list[fleaker.peewee.EventStorageMixin]: All the events that were created for the update.
codesearchnet
def remove(self, x): with tf.name_scope('pad_reduce/remove'): x_shape = x.get_shape().as_list() x = tf.gather_nd(x, indices=self.nonpad_ids) if (not tf.executing_eagerly()): x.set_shape(([None] + x_shape[1:])) return x
Remove padding from the given tensor. Args: x (tf.Tensor): of shape [dim_origin,...] Returns: a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin
codesearchnet
def center_crop(self, image, size): self._ensure_format_supported(image) if not isinstance(size, tuple): size = (size, size) if is_torch_tensor(image) or isinstance(image, np.ndarray): if image.ndim == 2: image = self.expand_dims(image) image_shape = image.shape[1:] if im...
Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the size given, it will be padded (so the returned result has the size asked). Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)):...
github-repos
def tasks(self, filters=None): if (filters is None): filters = {} filters['service'] = self.id return self.client.api.tasks(filters=filters)
List the tasks in this service. Args: filters (dict): A map of filters to process on the tasks list. Valid filters: ``id``, ``name``, ``node``, ``label``, and ``desired-state``. Returns: :py:class:`list`: List of task dictionaries. Raises: :py:class:`docker.errors.APIError` If the server returns an error.
codesearchnet
def range(self, start_row=0, max_rows=None): fetcher = self._get_row_fetcher(start_row=start_row, max_rows=max_rows) return iter(datalab.utils.Iterator(fetcher))
Get an iterator to iterate through a set of table rows. Args: start_row: the row of the table at which to start the iteration (default 0) max_rows: an upper limit on the number of rows to iterate through (default None) Returns: A row iterator.
juraj-google-style
def diff_xIndex(self, diffs, loc): chars1 = 0 chars2 = 0 last_chars1 = 0 last_chars2 = 0 for x in range(len(diffs)): (op, text) = diffs[x] if op != self.DIFF_INSERT: chars1 += len(text) if op != self.DIFF_DELETE: chars2 += len(text) if chars1 > loc: ...
loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 Args: diffs: Array of diff tuples. loc: Location within text1. Returns: Location within text2.
juraj-google-style
def arccos(self: EventSetOrNode) -> EventSetOrNode: from temporian.core.operators.unary import arccos return arccos(self)
Calculates the inverse cosine of an [`EventSet`][temporian.EventSet]'s features. Can only be used on floating point features. Example: ```python >>> a = tp.event_set( ... timestamps=[1, 2, 3], ... features={"M": [1.0, 0, -1.0]}, ... ) >>> a.arccos() indexes: ... timestamps: [1. 2. 3.] 'M': [0. 1.5708 3.14...
github-repos
def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)): self.pos = pos self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2) self.branches = branches self.sigma = sigma self.comp = len(self.branches) self.age = 0 self.nodes = [ ...
The contructor. Args: pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2) branches (tupel/array): Holding array/s with scale and angle for every branch. sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2)
juraj-google-style
def __init__(self, hps, images, labels, mode): self.hps = hps self._images = images self.labels = labels self.mode = mode self._extra_train_ops = []
ResNet constructor. Args: hps: Hyperparameters. images: Batches of images of size [batch_size, image_size, image_size, 3]. labels: Batches of labels of size [batch_size, num_classes]. mode: One of 'train' and 'eval'.
juraj-google-style
def _ConvertMessage(value, message): message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): _ConvertWrapperMessage(value, message) elif (full_name in _WKTJSONMETHODS): _WKTJSONMETHODS[full_name][1](value, message) el...
Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to record the data. Raises: ParseError: In case of convert problems.
codesearchnet
def delete(self, key): with self._lmdb.begin(write=True, buffers=True) as txn: txn.delete(key.encode())
Removes a key:value from the database Args: key (str): The key to remove.
juraj-google-style
def DeregisterOutput(cls, output_class): output_class_name = output_class.NAME.lower() if output_class_name in cls._disabled_output_classes: class_dict = cls._disabled_output_classes else: class_dict = cls._output_classes if output_class_name not in class_dict: raise KeyError( ...
Deregisters an output class. The output classes are identified based on their NAME attribute. Args: output_class (type): output module class. Raises: KeyError: if output class is not set for the corresponding data type.
juraj-google-style
def _ReverseHostname(self, hostname): if (not hostname): return '' if (len(hostname) <= 1): return hostname if (hostname[(- 1)] == '.'): return hostname[::(- 1)][1:] return hostname[::(- 1)][0:]
Reverses the hostname and strips the leading dot. The hostname entry is reversed: moc.elgoog.www. Should be: www.google.com Args: hostname (str): reversed hostname. Returns: str: hostname without a leading dot.
codesearchnet
def parse(self, template): self._compile_delimiters() start_index = 0 (content_end_index, parsed_section, section_key) = (None, None, None) parsed_template = ParsedTemplate() states = [] while True: match = self._template_re.search(template, start_index) if (match is None): ...
Parse a template string starting at some index. This method uses the current tag delimiter. Arguments: template: a unicode string that is the template to parse. index: the index at which to start parsing. Returns: a ParsedTemplate instance.
codesearchnet
def date_to_delorean(year, month, day): return Delorean(datetime=dt(year, month, day), timezone='UTC')
Converts date arguments to a Delorean instance in UTC Args: year: int between 1 and 9999. month: int between 1 and 12. day: int between 1 and 31. Returns: Delorean instance in UTC of date.
juraj-google-style
def update(self, data, offset, is_last, buffer_index=0): if buffer_index >= self.num_buffers: raise ValueError('Expected buffer index < {} but got index {}.'.format(self.num_buffers, buffer_index)) if self.buffers[buffer_index] is not None and self.buffers[buffer_index].shape[0] > ...
Update the buffer at the given index. Args: data (np.ndarray): The frames. offset (int): The index of the first frame in `data` within the sequence. is_last (bool): Whether this is the last block of frames in the sequence. buffer_index (int): The index of the buffer to update (< self.num_buffers).
juraj-google-style
def determine_inst(i_info, param_str, command): qty_instances = len(i_info) if (not qty_instances): print('No instances found with parameters: {}'.format(param_str)) sys.exit(1) if (qty_instances > 1): print('{} instances match these parameters:'.format(qty_instances)) tar_id...
Determine the instance-id of the target instance. Inspect the number of instance-ids collected and take the appropriate action: exit if no ids, return if single id, and call user_picklist function if multiple ids exist. Args: i_info (dict): information and details for instances. param_str (str): the title to display ...
codesearchnet
def table_update(self, table_name, table_info): url = Api._ENDPOINT + (Api._TABLES_PATH % table_name) return datalab.utils.Http.request(url, method='PUT', data=table_info, credentials=self._credentials)
Updates the Table info. Args: table_name: the name of the table to update as a tuple of components. table_info: the Table resource with updated fields.
juraj-google-style
def _add_genotype_calls(self, variant_obj, variant_line, case_obj): variant_line = variant_line.split('\t') if len(variant_line) > 8: gt_format = variant_line[8].split(':') for individual in case_obj.individuals: sample_id = individual.ind_id ...
Add the genotype calls for the variant Args: variant_obj (puzzle.models.Variant) variant_dict (dict): A variant dictionary case_obj (puzzle.models.Case)
juraj-google-style
def extract_features(points, n_tops): max_bin = -1 for point in points: max_bin = max(max_bin, point.vel) max_bin = int(round(max_bin)) + 1 histogram = [0] * max_bin time = 0 for point in points: bin_index = int(round(point.vel)) histogram[bin_index] += p...
Feature extractor Args: points (:obj:`list` of :obj:`Point`) n_tops (int): Number of top speeds to extract Returns: :obj:`list` of float: with length (n_tops*2). Where the ith even element is the ith top speed and the i+1 element is the percentage of time spent on that speed
juraj-google-style
def do(self, resource, method, params=None, data=None, json=None, headers=None): uri = '{0}/{1}'.format(self._api_base, resource) if (not params): params = {} params.update({'token': self._token}) req = Request(method=method, url=uri, params=params, headers=headers, data=data, json=json) s =...
Does the request job Args: resource(str): resource uri(relative path) method(str): HTTP method params(dict): uri queries data(dict): HTTP body(form) json(dict): HTTP body(json) headers(dict): HTTP headers Returns: RTMResponse
codesearchnet
def __init__(self, ea=UseCurrentAddress, name=None, index=None, segment_t=None): if sum((ea not in (self.UseCurrentAddress, None), name is not None, index is not None, segment_t is not None,)) > 1: raise ValueError(( "Expected only one (ea, n...
Wrapper around IDA segments. There are 3 ways to get a segment - by name, ea or index. Only use one. Args: ea - address in the segment name - name of the segment index - index of the segment
juraj-google-style
def storage_pools(self): if (not self.__storage_pools): self.__storage_pools = StoragePools(self.__connection) return self.__storage_pools
Gets the StoragePools API client. Returns: StoragePools:
codesearchnet
def save_project_id(project_id): try: subprocess.call(['gcloud', 'config', 'set', 'project', project_id]) except: config_file = os.path.join(get_config_dir(), 'config.json') config = {} if os.path.exists(config_file): with open(config_file) as f: config = json.loads(f.read()) ...
Save project id to config file. Args: project_id: the project_id to save.
juraj-google-style
def compare_name(given_name, family_name, question_name): given_name = given_name.lower() family_name = family_name.lower() question_name = question_name.lower() if (',' in question_name): name_split = question_name.split(',') name_split.reverse() question_name = ' '.join(name_sp...
Compares a name in question to a specified name separated into given and family. The name in question ``question_name`` can be of varying format, including "Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and "K Niemeyer". Other possibilities include names with hyphens such as "Chih-Jen Sung", "C....
codesearchnet
def _process_from_queue(self, queue): now = time.time() log = self.log.bind(queue=queue) batch_size = self._get_queue_batch_size(queue) queue_lock, failed_to_acquire = self._get_queue_lock(queue, log) if failed_to_acquire: return [], -1 ...
Internal method to process a task batch from the given queue. Args: queue: Queue name to be processed Returns: Task IDs: List of tasks that were processed (even if there was an error so that client code can assume the queue is empty if nothing was returned) Count: The number of tasks that were attempted to be ...
juraj-google-style
def create_border(video, color="blue", border_percent=2): if video.shape[-1] != 3: return video color_to_axis = {"blue": 2, "red": 0, "green": 1} axis = color_to_axis[color] _, _, height, width, _ = video.shape border_height = np.ceil(border_percent * height / 100.0).astype(np.int) border_width = ...
Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array.
juraj-google-style
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None): init_params = super(Estimator, cls)._prepare_init_params_from_job_description(job_details, model_channel_name) init_params['image_name'] = init_params.pop('image') return init_params
Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_name (str): Name of the channel where pre-trained model data will be downloaded Returns: dictionary: The transformed init_params
juraj-google-style
def declarations(cls, extra_defs=None): warnings.warn('Factory.declarations is deprecated; use Factory._meta.pre_declarations instead.', DeprecationWarning, stacklevel=2) decls = cls._meta.pre_declarations.as_dict() decls.update((extra_defs or {})) return decls
Retrieve a copy of the declared attributes. Args: extra_defs (dict): additional definitions to insert into the retrieved DeclarationDict.
codesearchnet
def pbs_for_create(document_path, document_data): extractor = DocumentExtractor(document_data) if extractor.deleted_fields: raise ValueError("Cannot apply DELETE_FIELD in a create request.") write_pbs = [] if extractor.empty_document or extractor.set_fields: write_pbs.a...
Make ``Write`` protobufs for ``create()`` methods. Args: document_path (str): A fully-qualified document path. document_data (dict): Property names and values to use for creating a document. Returns: List[google.cloud.firestore_v1beta1.types.Write]: One or two ``Write`` protobuf instances for ``create()``.
juraj-google-style
def _validate_iss(claims, issuer=None): if (issuer is not None): if isinstance(issuer, string_types): issuer = (issuer,) if (claims.get('iss') not in issuer): raise JWTClaimsError('Invalid issuer')
Validates that the 'iss' claim is valid. The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL. Args: claims (dict): The claims di...
codesearchnet
def flatten_rules(self, declarations): rules = [] for protocole, paths in declarations: if protocole: continue rules.extend([self.strip_quotes(v.strip()) for v in paths.split(',')]) return list...
Flatten returned import rules from regex. Because import rules can contains multiple items in the same rule (called multiline import rule), the regex ``REGEX_IMPORT_RULE`` return a list of unquoted items for each rule. Args: declarations (list): A SCSS source. Returns: list: Given SCSS source with all comments remov...
juraj-google-style
def get_date(date, date_format = None): date_obj = datetime.datetime.now() if date: if date_format: date_obj = datetime.datetime.strptime(date, date_format) else: if match_date(date): if len(date.split('-')) == 3: date = date.split...
Return a datetime object if there is a valid date Raise exception if date is not valid Return todays date if no date where added Args: date(str) date_format(str) Returns: date_obj(datetime.datetime)
juraj-google-style
def _process_rules(self, rules): cidr = [] non_cidr = [] for rule in rules: if '.' in rule['app']: self.log.debug('Custom CIDR rule: %s', rule) self._validate_cidr(rule) cidr.append(rule) else: self...
Process rules into cidr and non-cidr lists. Args: rules (list): Allowed Security Group ports and protocols. Returns: (list, list): Security Group reference rules and custom CIDR rules.
juraj-google-style
def _ParseDLSPageHeader(self, file_object, page_offset): page_header_map = self._GetDataTypeMap('dls_page_header') try: (page_header, page_size) = self._ReadStructureFromFileObject(file_object, page_offset, page_header_map) except (ValueError, errors.ParseError) as exception: raise errors.Pa...
Parses a DLS page header from a file-like object. Args: file_object (file): file-like object to read the header from. page_offset (int): offset of the start of the page header, relative to the start of the file. Returns: tuple: containing: dls_page_header: parsed record structure. int: header size. Raises: ParseErr...
codesearchnet
def get_coder_from_spec(coder_spec): assert coder_spec is not None ignored_wrappers = 'com.google.cloud.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder' if coder_spec['@type'] in ignored_wrappers: assert len(coder_spec['component_encodings']) == 1 coder_spec = coder_spec['component_enco...
Return a coder instance from a coder spec. Args: coder_spec: A dict where the value of the '@type' key is a pickled instance of a Coder instance. Returns: A coder instance (has encode/decode methods).
github-repos
def __init__(self, length=None, vendor=None): super().__init__(action_type=ActionType.OFPAT_VENDOR, length=length) self.vendor = vendor
Create an ActionVendorHeader with the optional parameters below. Args: length (int): Length is a multiple of 8. vender (int): Vendor ID with the same form as in VendorHeader. Defaults to None.
juraj-google-style
def __init__(self, project_id=None, context=None): self._context = context or datalab.context.Context.default() self._project_id = project_id or self._context.project_id self._client = _utils.make_client(project_id, context) self._group_dict = None
Initializes the Groups for a Stackdriver project. Args: project_id: An optional project ID or number to override the one provided by the context. context: An optional Context object to use instead of the global default.
juraj-google-style
def size(self, path): try: return self._blobstorageIO().size(path) except Exception as e: raise BeamIOError('Size operation failed', {path: e})
Get size in bytes of a file on the FileSystem. Args: path: string filepath of file. Returns: int size of file according to the FileSystem. Raises: ``BeamIOError``: if path doesn't exist.
github-repos
def FromJsonString(self, value): timezone_offset = value.find('Z') if (timezone_offset == (- 1)): timezone_offset = value.find('+') if (timezone_offset == (- 1)): timezone_offset = value.rfind('-') if (timezone_offset == (- 1)): raise ParseError('Failed to parse timestamp: missin...
Parse a RFC 3339 date string format to Timestamp. Args: value: A date string. Any fractional digits (or none) and any offset are accepted as long as they fit into nano-seconds precision. Example of accepted format: '1972-01-01T10:00:20.021-05:00' Raises: ParseError: On parsing problems.
codesearchnet
def ip(ip_addr, return_tuple=True): regex_ip = __re.compile("^((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))$") if return_tuple: ...
Function to check if a address is good Args: ip_addr: IP address in the following format 192.168.1.1 return_tuple: Set to True it returns a IP, set to False returns True or False Returns: see return_tuple for return options
juraj-google-style
def _AddAttributeNodes(self, attribute_names): for attribute_name in attribute_names: self.graph[attribute_name] = self.Node(is_artifact=False)
Add the attribute nodes to the graph. For every attribute that is required for the collection of requested artifacts, add a node to the dependency graph. An attribute node will have incoming edges from the artifacts that provide this attribute and outgoing edges to the artifacts that depend on it. An attribute is rea...
codesearchnet
def get_linear_interpolation(self, percentile): with self._lock: return self._get_linear_interpolation(percentile)
Calculate percentile estimation based on linear interpolation. It first finds the bucket which includes the target percentile and projects the estimated point in the bucket by assuming all the elements in the bucket are uniformly distributed. Args: percentile: The target percentile of the value returning from this me...
github-repos
async def debug(self, client_id, conn_string, command, args): conn_id = self._client_info(client_id, 'connections')[conn_string] return (await self.adapter.debug(conn_id, command, args))
Send a debug command to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. command (str): The name of the debug command to run. args (dict): An...
codesearchnet
def _validate_field(msg: message.Message, field: descriptor.FieldDescriptor, field_name: str, primitive_handler_: primitive_handler.PrimitiveHandler) -> None: if annotation_utils.field_is_required(field) and (not proto_utils.field_is_set(msg, field)): raise fhir_errors.InvalidFhirError(f'Required field `{fi...
Validates that required fields are set, and performs basic temporal checks. Args: msg: The Message that the field belongs to. field: The FieldDescriptor of the field to examine. field_name: The name of the field. primitive_handler_: Responsible for returning PrimitiveWrappers. Raises: fhir_errors.InvalidFhirError: In...
github-repos
def __iadd__(self, other): assert isinstance(other, LocationDescriptor), "You can only add LocationDescriptor together." assert self._separation_char == other._separation_char, \ "You can only add LocationDescriptor together if they share the same separator character." ...
**Extend** an existing :class:`LocationDescriptor` object by another. Args: self: This :class:`LocationDescriptor` object. other: Another :class:`LocationDescriptor` object. Returns: The updated :class:`LocationDescriptor` object itself.
juraj-google-style
def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None): new = cls(manager=manager) new.add_becs_from_scf_task(scf_task, ddk_tolerance, ph_tolerance) return new
Build tasks for the computation of Born effective charges from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default. ph_tolerance: dict {"varname": value} with the tolerance used in the phonon run. None to use AbiPy default. manager: ...
codesearchnet
def recipe_dv360_editor(config, auth_dv, auth_sheet, auth_bigquery, recipe_name, recipe_slug, command): dataset(config, {'__comment__': 'Ensure dataset exists.', 'auth': auth_bigquery, 'dataset': recipe_slug}) drive(config, {'__comment__': 'Copy the default template to sheet with the recipe name', 'auth': auth_...
Allows bulk editing DV360 through Sheets and BigQuery. Args: auth_dv (authentication) - Credentials used for dv. auth_sheet (authentication) - Credentials used for sheet. auth_bigquery (authentication) - Credentials used for bigquery. recipe_name (string) - Name of Google Sheet to create. recipe_slug (string) - Name o...
github-repos
def _deduplicate_indexed_slices(values, indices): unique_indices, new_index_positions = array_ops.unique(indices) summed_values = math_ops.unsorted_segment_sum(values, new_index_positions, array_ops.shape(unique_indices)[0]) return (summed_values, unique_indices)
Sums `values` associated with any non-unique `indices`. Args: values: A `Tensor` with rank >= 1. indices: A one-dimensional integer `Tensor`, indexing into the first dimension of `values` (as in an IndexedSlices object). Returns: A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a de-duplicated...
github-repos
def register_keras_serializable(package='Custom', name=None): def decorator(arg): class_name = name if name is not None else arg.__name__ registered_name = package + '>' + class_name if tf_inspect.isclass(arg) and (not hasattr(arg, 'get_config')): raise ValueError('Cann...
Registers an object with the Keras serialization framework. This decorator injects the decorated class or function into the Keras custom object dictionary, so that it can be serialized and deserialized without needing an entry in the user-provided custom object dict. It also injects a function that Keras will call to ...
github-repos
def set_config_variables(repo, variables): with repo.config_writer() as writer: for (k, value) in variables.items(): (section, option) = k.split('.') writer.set_value(section, option, value) writer.release()
Set config variables Args: repo (git.Repo): repo variables (dict): entries of the form 'user.email': 'you@example.com'
codesearchnet
def unreduce_array(array, shape, axis, keepdims): if ((axis is not None) and ((not keepdims) or (keepdims is numpy._NoValue))): if isinstance(axis, int): axis = (axis,) for ax in sorted(axis): array = numpy.expand_dims(array, ax) return numpy.broadcast_to(array, shape)
Reverse summing over a dimension, NumPy implementation. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton axes. Returns: An array with axes broadcast to match the shape of the o...
codesearchnet
def parse_debug_node_name(node_name): prefix = '__dbg_' name = node_name if not name.startswith(prefix): raise ValueError("Invalid prefix in debug node name: '%s'" % node_name) name = name[len(prefix):] if name.count('_') < 2: raise ValueError("Invalid debug node name: '%s'" % node_n...
Parse the name of a debug node. Args: node_name: Name of the debug node. Returns: 1. Name of the watched node, as a str. 2. Output slot index of the watched tensor, as an int. 3. Index of the debug node, as an int. 4. Name of the debug op, as a str, e.g, "DebugIdentity". Raises: ValueError: If the input node name is...
github-repos
def _check_warnings(self, json_response): self.warnings = None if json_response: self.warnings = json_response.get('warnings') if self.debug and self.warnings: for w in self.warnings: print("WARNING: %s - %s" % (w['warning_name'], w['warning_msg...
Extract warnings from the response to make them accessible Args: json_response (dict): JSON response
juraj-google-style
def __init__(self, input_energy: energy.BitstringEnergy, num_expectation_samples: int, initial_seed: Union[None, tf.Tensor]=None, name: Union[None, str]=None): super().__init__(input_energy, initial_seed, name) self.num_expectation_samples = num_expectation_samples
Initializes an EnergyInference. Args: input_energy: The parameterized energy function which defines this distribution via the equations of an energy based model. This class assumes that all parameters of `energy` are `tf.Variable`s and that they are all returned by `energy.variables`. num_expectation_samples: Number ...
github-repos
def get_sequence_sliding_window_properties(self, scale, window, representatives_only=True): for g in tqdm(self.genes): g.protein.get_sequence_sliding_window_properties(scale=scale, window=window, representative_only=representative...
Run Biopython ProteinAnalysis and EMBOSS pepstats to summarize basic statistics of all protein sequences. Results are stored in the protein's respective SeqProp objects at ``.annotations`` Args: representative_only (bool): If analysis should only be run on the representative sequences
juraj-google-style
def _relocate_if_symbolic(self, key: Union[str, int], value: Any) -> Any: if isinstance(value, Symbolic): root_path = utils.KeyPath(key, self.sym_path) if value.sym_parent is not None and (value.sym_parent is not self or root_path != value.sym_path): value = value.clone() if isinstan...
Relocate if a symbolic value is to be inserted as member. NOTE(daiyip): when a symbolic value is inserted into the object tree, if it already has a parent, we need to make a shallow copy of this object to avoid multiple parents. Otherwise we need to set its parent and root_path according to current object. Args: key:...
github-repos
def key_for_namespace(cls, namespace): if namespace: return model.Key(cls.KIND_NAME, namespace) else: return model.Key(cls.KIND_NAME, cls.EMPTY_NAMESPACE_ID)
Return the Key for a namespace. Args: namespace: A string giving the namespace whose key is requested. Returns: The Key for the namespace.
juraj-google-style
class Speech2TextProcessor(ProcessorMixin): feature_extractor_class = 'Speech2TextFeatureExtractor' tokenizer_class = 'Speech2TextTokenizer' def __init__(self, feature_extractor, tokenizer): super().__init__(feature_extractor, tokenizer) self.current_processor = self.feature_extractor ...
Constructs a Speech2Text processor which wraps a Speech2Text feature extractor and a Speech2Text tokenizer into a single processor. [`Speech2TextProcessor`] offers all the functionalities of [`Speech2TextFeatureExtractor`] and [`Speech2TextTokenizer`]. See the [`~Speech2TextProcessor.__call__`] and [`~Speech2TextProce...
github-repos
def _ProcessDirectory(self, mediator, file_entry): self.processing_status = definitions.STATUS_INDICATOR_COLLECTING if self._processing_profiler: self._processing_profiler.StartTiming('collecting') for sub_file_entry in file_entry.sub_file_entries: if self._abort: break try...
Processes a directory file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry of the directory.
juraj-google-style
def _base_expansion_size(num, bases): return (tf.floor((tf.math.log(num) / tf.math.log(bases))) + 1)
Computes the number of terms in the place value expansion. Let num = a0 + a1 b + a2 b^2 + ... ak b^k be the place value expansion of `num` in base b (ak <> 0). This function computes and returns `k+1` for each base `b` specified in `bases`. This can be inferred from the base `b` logarithm of `num` as follows: $$k = F...
codesearchnet
def __init__(self, replacements): self.replacements = replacements self.in_replacements = False self.preserved_annos = {anno.Basic.DIRECTIVES, anno.Basic.EXTRA_LOOP_TEST, anno.Basic.ORIGIN, anno.Basic.SKIP_PROCESSING, anno.Static.ORIG_DEFINITIONS, 'function_context_name'}
Create a new ReplaceTransformer. Args: replacements: A mapping from placeholder names to (lists of) AST nodes that these placeholders will be replaced by.
github-repos
def _list_valid_filenames_in_directory(directory, white_list_formats, split, class_indices, follow_links): dirname = os.path.basename(directory) if split: all_files = list(_iter_valid_files(directory, white_list_formats, follow_links)) num_files = len(all_files) start, stop = (int(split[...
Lists paths of files in `subdir` with extensions in `white_list_formats`. Args: directory: absolute path to a directory containing the files to list. The directory name is used as class label and must be a key of `class_indices`. white_list_formats: set of strings containing allowed extensions for the files to be coun...
github-repos
def lengths(self): return np.array([math.sqrt(sum((row ** 2))) for row in self.matrix])
The cell lengths. Args: None Returns: (np.array(a,b,c)): The cell lengths.
codesearchnet
def schema(self): if (not self._schema): try: self._load_info() self._schema = _schema.Schema(self._info['schema']['fields']) except KeyError: raise Exception('Unexpected table response: missing schema') return self._schema
Retrieves the schema of the table. Returns: A Schema object containing a list of schema fields and associated metadata. Raises Exception if the request could not be executed or the response was malformed.
codesearchnet
def _generate_enqueue_op(self, flat_inputs: List[internal_types.NativeObject], flat_weights: List[Optional[internal_types.NativeObject]], flat_features: List[tpu_embedding_v2_utils.FeatureConfig], device_ordinal: int, mode_override: Text) -> ops.Operation: combiners = [table.combiner for table in self._table_config...
Outputs a the enqueue op given the inputs and weights. Args: flat_inputs: A list of input tensors. flat_weights: A list of input weights (or None) of the same length as flat_inputs. flat_features: A list of FeatureConfigs of the same length as flat_inputs. device_ordinal: The device to create the enqueue op for. mode_...
github-repos
def import_object_from_string_code(code, object): sha256 = hashlib.sha256(code.encode('UTF-8')).hexdigest() module = imp.new_module(sha256) try: exec_(code, module.__dict__) except Exception as e: raise exceptions.UserError('User code exception', exception_message=str(e)) sys.mo...
Used to import an object from arbitrary passed code. Passed in code is treated as a module and is imported and added to `sys.modules` with its SHA256 hash as key. Args: code (string): Python code to import as module object (string): Name of object to extract from imported module
juraj-google-style
def _setup_parser(self, filename=None): assert isinstance(filename, str) or filename is None if not filename: filename = MACKUP_CONFIG_FILE parser = configparser.SafeConfigParser(allow_no_value=True) parser.read(os.path.join(os.path.join(os.environ['HOME']...
Configure the ConfigParser instance the way we want it. Args: filename (str) or None Returns: SafeConfigParser
juraj-google-style
def save(self, **fields): for field in fields: if (field in self.writable_fields): setattr(self, field, fields[field]) else: self._handle_wrong_field(field, ATTR_TYPE_WRITE) if self._populated_fields: self._update(**self._modified_fields) else: self._c...
Save the instance to the remote Transifex server. If it was pre-populated, it updates the instance on the server, otherwise it creates a new object. Any values given in `fields` will be attempted to be saved on the object. The same goes for any other values already set to the object by `model_instance.attr = value`. ...
codesearchnet
def new_from_list(cls, content, fill_title=True, **kwargs): obj = cls(**kwargs) obj.append_from_list(content, fill_title) return obj
Populates the Table with a list of tuples of strings. Args: content (list): list of tuples of strings. Each tuple is a row. fill_title (bool): if true, the first tuple in the list will be set as title
juraj-google-style
def get_element_spd_dos(self, el): el = get_el_sp(el) el_dos = {} for site, atom_dos in self.pdos.items(): if site.specie == el: for orb, pdos in atom_dos.items(): orbital_type = _get_orb_type_lobster(orb) if orbital_ty...
Get element and spd projected Dos Args: el: Element in Structure.composition associated with LobsterCompleteDos Returns: dict of {Element: {"S": densities, "P": densities, "D": densities}}
juraj-google-style
def dispatch_callback(self, items): if not self._manager.is_active: return batched_commands = collections.defaultdict(list) for item in items: batched_commands[item.__class__].append(item) _LOGGER.debug("Handling %d batched requests", len(items)) ...
Map the callback request to the appropriate gRPC request. Args: action (str): The method to be invoked. kwargs (Dict[str, Any]): The keyword arguments for the method specified by ``action``. Raises: ValueError: If ``action`` isn't one of the expected actions "ack", "drop", "lease", "modify_ack_deadline" or "nack".
juraj-google-style
def _compute_nfps_uniform(cum_counts, sizes): nfps = np.zeros((len(sizes), len(sizes))) for l in range(len(sizes)): for u in range(l, len(sizes)): nfps[l, u] = _compute_nfp_uniform(l, u, cum_counts, sizes) return nfps
Computes the matrix of expected false positives for all possible sub-intervals of the complete domain of set sizes, assuming uniform distribution of set_sizes within each sub-intervals. Args: cum_counts: the complete cummulative distribution of set sizes. sizes: the complete domain of set sizes. Return (np.array): th...
juraj-google-style
def loadFunction(self, root): for element in root.iter(): if (element.tag == 'function'): self.functionList.append(element.attrib['name'])
Loads a list with all the functions in the Fortran File Args: root: The root of the XML ast tree. Returns: None Does not return anything but populates a list (self.functionList) that contains all the functions in the Fortran File.
codesearchnet
def _GetApprovals(self, approval_type, offset, count, filter_func=None, token=None): approvals_base_urn = aff4.ROOT_URN.Add('users').Add(token.username).Add('approvals').Add(approval_type) all_children = aff4.FACTORY.RecursiveMultiListChildren([approvals_base_urn]) approvals_urns = [] for (subject, chil...
Gets all approvals for a given user and approval type. Args: approval_type: The type of approvals to get. offset: The starting index within the collection. count: The number of items to return. filter_func: A predicate function, returning True if a specific approval should be included in the result and False otherwise...
codesearchnet
def create(self, name, targetUrl, resource, event, filter=None, secret=None, **request_parameters): check_type(name, basestring, may_be_none=False) check_type(targetUrl, basestring, may_be_none=False) check_type(resource, basestring, may_be_none=False) check_type(event, basestring, may_be_none=False) ...
Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. resource(basestring): The resource type for the webhook. event(basestring): The event type for the webhook. filter(basestring): The filter that defines the webhook...
codesearchnet
def _split_cell(cell, module): lines = cell.split('\n') code = None last_def = -1 name = None define_wild_re = re.compile('^DEFINE\s+.*$', re.IGNORECASE) define_re = re.compile('^DEFINE\s+QUERY\s+([A-Z]\w*)\s*?(.*)$', re.IGNORECASE) select_re = re.compile('^SELECT\s*.*$', re.IGNORECASE) standard_sql_...
Split a hybrid %%sql cell into the Python code and the queries. Populates a module with the queries. Args: cell: the contents of the %%sql cell. module: the module that the contents will populate. Returns: The default (last) query for the module.
juraj-google-style
def __init__(self, directory, container, entry_point, use_gpu): self.name = os.path.basename(directory) self.directory = directory self.container = container self.entry_point = entry_point self.use_gpu = use_gpu
Initializes instance of Submission class. Args: directory: location of the submission. container: URL of Docker container which should be used to run submission. entry_point: entry point script, which invokes submission. use_gpu: whether to use Docker with GPU or not.
juraj-google-style
def __init__(self, name, transition_min=258.15, transition_max=298.15, transition_gamma=3.0, **kwargs): self.transition_min = transition_min self.transition_max = transition_max self.transition_gamma = transition_gamma super(CloudCompositor, self).__init__(name,...
Collect custom configuration values. Args: transition_min (float): Values below or equal to this are clouds -> opaque white transition_max (float): Values above this are cloud free -> transparent transition_gamma (float): Gamma correction to apply at the end
juraj-google-style
def consolidate(self, args): result = dict(args) for opt in self: if opt.name in result: result[opt.name] = opt.convert(result[opt.name]) else: if opt.default is not None: result[opt.name] = opt.convert(opt.default) ...
Consolidate the provided arguments. If the provided arguments have matching options, this performs a type conversion. For any option that has a default value and is not present in the provided arguments, the default value is added. Args: args (dict): A dictionary of the provided arguments. Returns: dict: A dictionar...
juraj-google-style
def process_api_config_response(self, config_json): with self._config_lock: self._add_discovery_config() for config in config_json.get('items', []): lookup_key = (config.get('name', ''), config.get('version', '')) self._configs[lookup_key] = config for config in self....
Parses a JSON API config and registers methods for dispatch. Side effects: Parses method name, etc. for all methods and updates the indexing data structures with the information. Args: config_json: A dict, the JSON body of the getApiConfigs response.
codesearchnet
def create_datastore(self, schema=None, primary_key=None, delete_first=0, path=None): if (delete_first == 0): pass elif (delete_first == 1): self.delete_datastore() elif (delete_first == 2): if (primary_key is None): self.delete_datastore() else: raise HDXErro...
For tabular data, create a resource in the HDX datastore which enables data preview in HDX. If no schema is provided all fields are assumed to be text. If path is not supplied, the file is first downloaded from HDX. Args: schema (List[Dict]): List of fields and types of form {'id': 'FIELD', 'type': 'TYPE'}. Defaults t...
codesearchnet
def jump_if(state, op, ctx, *, jump_if_val, pop=PopBehavior.NONE): if pop is PopBehavior.ALWAYS: state, value = state.pop() else: value = state.top() if jump_if_val is None: normal_val = frame_state.NOT_NONE elif jump_if_val is frame_state.NOT_NONE: normal_val = None ...
Implementation of various _JUMP_IF bytecodes. Args: state: Initial FrameState. op: An opcode. ctx: The current context. jump_if_val: Indicates what value leads to a jump. The non-jump state is reached by the value's negation. Use frame_state.NOT_NONE for `not None`. pop: Whether and how the opcode pops a value off the...
github-repos
def WriteEventBody(self, event): output_string = NativePythonFormatterHelper.GetFormattedEventObject(event) self._output_writer.Write(output_string)
Writes the body of an event to the output. Args: event (EventObject): event.
juraj-google-style
def _initialize_operations(self): if isinstance(self._graph, tf.Graph): return self._graph.get_operations() elif isinstance(self._graph, mtf.Graph): return self._graph.operations else: raise TypeError('Graph is not tf.Graph or mtf.Graph: {}'.format(type(self._graph)))
Initializer for _operations. Raises: TypeError: _graph is not a tf.Graph or mtf.Graph. Returns: a list of (tf.Operation or mtf.Operation)
codesearchnet
def UpdateTaskAsProcessingByIdentifier(self, task_identifier): with self._lock: task_processing = self._tasks_processing.get(task_identifier, None) if task_processing: task_processing.UpdateProcessingTime() self._UpdateLatestProcessingTime(task_processing) return task...
Updates the task manager to reflect the task is processing. Args: task_identifier (str): unique identifier of the task. Raises: KeyError: if the task is not known to the task manager.
juraj-google-style
def get_run_key(feed_dict, fetches): return json.dumps(RunKey(get_flattened_names(feed_dict), get_flattened_names(fetches)))
Summarize the names of feeds and fetches as a RunKey JSON string. Args: feed_dict: The feed_dict given to the `Session.run()` call. fetches: The fetches from the `Session.run()` call. Returns: A JSON Array consisting of two items. They first items is a flattened Array of the names of the feeds. The second item is a f...
github-repos
def operations_happening_at_same_time_as(self, scheduled_operation: ScheduledOperation) -> List[ScheduledOperation]: overlaps = self.query(time=scheduled_operation.time, duration=scheduled_operation.duration) return [e for e in overlaps if (e != scheduled_operation)]
Finds operations happening at the same time as the given operation. Args: scheduled_operation: The operation specifying the time to query. Returns: Scheduled operations that overlap with the given operation.
codesearchnet
def has_axon(neuron, treefun=_read_neurite_type): return CheckResult(NeuriteType.axon in (treefun(n) for n in neuron.neurites))
Check if a neuron has an axon Arguments: neuron(Neuron): The neuron object to test treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result
juraj-google-style
def get_block(self, block_id): block = backend.query.get_block(self.connection, block_id) latest_block = self.get_latest_block() latest_block_height = (latest_block['height'] if latest_block else 0) if ((not block) and (block_id > latest_block_height)): return result = {'height': block_id, '...
Get the block with the specified `block_id`. Returns the block corresponding to `block_id` or None if no match is found. Args: block_id (int): block id of the block to get.
codesearchnet
def pad(self, image: np.array, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None): height, width = get_image_size(image) size = max(height, width) image = pad(image=image, padding=((0, size - height), (0, size - width)), constant_values=...
Pad an image to a square with gray pixels on the bottom and the right, as per the original OWLv2 implementation. Args: image (`np.ndarray`): Image to pad. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. input_dat...
github-repos