code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def build_graph(device, input_shape, perm, datatype, num_iters): with ops.device('/%s:0' % device): total_size = np.prod(input_shape) inp = np.arange(1, total_size + 1, dtype=datatype).reshape(input_shape) t = constant_op.constant(inp, shape=input_shape) outputs = [] transpos...
builds a graph containing a sequence of conv2d operations. Args: device: String, the device to run on. input_shape: Shape of the input tensor. perm: A list of ints with the same length as input tensor's dimension. datatype: numpy data type of the input tensor. num_iters: number of iterations to run transpose. Returns...
github-repos
def _compile_ast_node_to_ir(schema, current_schema_type, ast, location, context): basic_blocks = [] local_unique_directives = get_unique_directives(ast) fields = _get_fields(ast) (vertex_fields, property_fields) = fields fragment = _get_inline_fragment(ast) filter_operations = get_local_filter_d...
Compile the given GraphQL AST node into a list of basic blocks. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: the current GraphQL AST node, obtained from the graphql library location: Location object representing th...
codesearchnet
def clean_dataset_tags(self): (tags_dict, wildcard_tags) = Tags.tagscleanupdicts() def delete_tag(tag): logger.info(('%s - Deleting tag %s!' % (self.data['name'], tag))) return (self.remove_tag(tag), False) def update_tag(tag, final_tags, wording, remove_existing=True): text = ('%s...
Clean dataset tags according to tags cleanup spreadsheet and return if any changes occurred Returns: Tuple[bool, bool]: Returns (True if tags changed or False if not, True if error or False if not)
codesearchnet
def get_videos_for_ids( edx_video_ids, sort_field=None, sort_dir=SortDirection.asc ): videos, __ = _get_videos_for_filter( {"edx_video_id__in":edx_video_ids}, sort_field, sort_dir, ) return videos
Returns an iterator of videos that match the given list of ids. Args: edx_video_ids (list) 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
juraj-google-style
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None): if (trace is None): trace = 1.0 data = tomo_data['data'] keys = data[0]['circuit'].keys() counts = [] shots = [] ops = [] for dat in data: for key in keys: counts.append(dat['counts'][key]) ...
Reconstruct a state from unconstrained least-squares fitting. Args: tomo_data (list[dict]): state or process tomography data. weights (list or array or None): weights to use for least squares fitting. The default is standard deviation from a binomial distribution. trace (float or None): trace of returned operator. The...
codesearchnet
def site_specific_coordination_numbers(self): specific_coordination_numbers = {} for site in self.sites: specific_coordination_numbers[site.label] = site.site_specific_neighbours() return specific_coordination_numbers
Returns a dictionary of coordination numbers for each site type. Args: None Returns: (Dict(Str:List(Int))) : Dictionary of coordination numbers for each site type, e.g.:: { 'A' : [ 2, 4 ], 'B' : [ 2 ] }
codesearchnet
def get_settable_properties(cls): results = [] for attr, value in vars(cls).items(): if isinstance(value, property) and value.fset is not None: results.append(attr) return results
Gets the settable properties of a class. Only returns the explicitly defined properties with setters. Args: cls: A class in Python.
github-repos
def get_job(self, job_resource_name: str) -> Dict: return self.service.projects().programs().jobs().get( name=job_resource_name).execute()
Returns metadata about a previously created job. See get_job_result if you want the results of the job and not just metadata about the job. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`. Returns: A dictionary containing the metadata.
juraj-google-style
def _get_formatted_date(dataset_date, date_format=None): if dataset_date: if date_format: return dataset_date.strftime(date_format) else: return dataset_date.date().isoformat() else: return None
Get supplied dataset date as string in specified format. If no format is supplied, an ISO 8601 string is returned. Args: dataset_date (Optional[datetime.datetime]): dataset date in datetime.datetime format date_format (Optional[str]): Date format. None is taken to be ISO 8601. Defaults to None. Returns: Optional[str]...
juraj-google-style
def _GetValueAsObject(self, property_value): if property_value.type == pyolecf.value_types.BOOLEAN: return property_value.data_as_boolean if property_value.type in self._INTEGER_TYPES: return property_value.data_as_integer if property_value.type in self._STRING_TYPES: return propert...
Retrieves the property value as a Python object. Args: property_value (pyolecf.property_value): OLECF property value. Returns: object: property value as a Python object.
juraj-google-style
def all(self, customer_id, data={}, **kwargs): url = '{}/{}/tokens'.format(self.base_url, customer_id) return self.get_url(url, data, **kwargs)
Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id
codesearchnet
def _StartProfiling(self, configuration): if not configuration: return if configuration.HaveProfileMemoryGuppy(): self._guppy_memory_profiler = profilers.GuppyMemoryProfiler( self._name, configuration) self._guppy_memory_profiler.Start() if configuration.HaveProfileMemory(...
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration.
juraj-google-style
def generate_name(self, name_format=DEFAULT_FILE_NAME_FORMAT): if len(self.segments) > 0: return self.segments[0].points[0].time.strftime(name_format) + ".gpx" else: return "EmptyTrack"
Generates a name for the track The name is generated based on the date of the first point of the track, or in case it doesn't exist, "EmptyTrack" Args: name_format (str, optional): Name formar to give to the track, based on its start time. Defaults to DEFAULT_FILE_NAME_FORMAT Returns: str
juraj-google-style
def create_walker(self, selector, skip_all=True): if selector.buffered: walker = BufferedStreamWalker(selector, self._engine, skip_all=skip_all) self._queue_walkers.append(walker) return walker if (selector.match_type == DataStream.CounterType): walker = CounterStreamWalker(selec...
Create a stream walker based on the given selector. This function returns a StreamWalker subclass that will remain up to date and allow iterating over and popping readings from the stream(s) specified by the selector. When the stream walker is done, it should be passed to destroy_walker so that it is removed from int...
codesearchnet
def span_to_answer(self, text: str, start: int, end: int) -> Dict[str, Union[str, int]]: words = [] token_idx = char_start_idx = char_end_idx = chars_idx = 0 for i, word in enumerate(text.split(' ')): token = self.tokenizer.tokenize(word) if start <= token_idx <= end: if token_id...
When decoding from token probabilities, this method maps token indexes to actual word in the initial context. Args: text (`str`): The actual context to extract the answer from. start (`int`): The answer starting token index. end (`int`): The answer end token index. Returns: Dictionary like `{'answer': str, 'start': i...
github-repos
def _ComputeUniquifier(self, debuggee): uniquifier = hashlib.sha1() if (('minorversion' not in debuggee.get('labels', [])) and ('sourceContexts' not in debuggee)): uniquifier_computer.ComputeApplicationUniquifier(uniquifier) return uniquifier.hexdigest()
Computes debuggee uniquifier. The debuggee uniquifier has to be identical on all instances. Therefore the uniquifier should not include any random numbers and should only be based on inputs that are guaranteed to be the same on all instances. Args: debuggee: complete debuggee message without the uniquifier Returns: ...
codesearchnet
def CreateDynamicDisplayAdSettings(client, opener): media_service = client.GetService('MediaService', 'v201809') logo = {'xsi_type': 'Image', 'mediaId': _CreateImage(media_service, opener, 'https: dynamic_settings = {'landscapeLogoImage': logo, 'pricePrefix': 'as low as', 'promoText': 'Free shipping!'} ...
Creates dynamic display ad settings. Args: client: an AdWordsClient instance. opener: an OpenerDirector instance. Returns: A dict containing the dynamic display ad settings.
codesearchnet
def update_config_pwd(msg, cfg): msg_type = msg.__class__.__name__.lower() key_fmt = ((msg.profile + '_') + msg_type) if isinstance(msg._auth, (MutableSequence, tuple)): cfg.pwd[key_fmt] = ' :: '.join(msg._auth) else: cfg.pwd[key_fmt] = msg._auth
Updates the profile's auth entry with values set by the user. This will overwrite existing values. Args: :msg: (Message class) an instance of a message class. :cfg: (jsonconfig.Config) config instance.
codesearchnet
def wrap_inference_results(inference_result_proto): inference_proto = inference_pb2.InferenceResult() if isinstance(inference_result_proto, classification_pb2.ClassificationResponse): inference_proto.classification_result.CopyFrom( inference_result_proto.result) elif isinstance(infe...
Returns packaged inference results from the provided proto. Args: inference_result_proto: The classification or regression response proto. Returns: An InferenceResult proto with the result from the response.
juraj-google-style
def _analemma_position(self, hour): low = self.calculate_sun(12, 21, hour).is_during_day high = self.calculate_sun(6, 21, hour).is_during_day if (low and high): return 1 elif (low or high): return 0 else: return (- 1)
Check what the analemma position is for an hour. This is useful for calculating hours of analemma curves. Returns: -1 if always night, 0 if both day and night, 1 if always day.
codesearchnet
def collect_hunt_results(self, hunt): if not os.path.isdir(self.output_path): os.makedirs(self.output_path) output_file_path = os.path.join( self.output_path, '.'.join((self.hunt_id, 'zip'))) if os.path.exists(output_file_path): print('{0:s} already exists: Skipping'.format(output...
Download current set of files in results. Args: hunt: The GRR hunt object to download files from. Returns: list: tuples containing: str: human-readable description of the source of the collection. For example, the name of the source host. str: path to the collected data. Raises: ValueError: if approval is needed and ...
juraj-google-style
def hugepage_support(user, group='hugetlb', nr_hugepages=256, max_map_count=65536, mnt_point='/run/hugepages/kvm', pagesize='2MB', mount=True, set_shmmax=False): group_info = add_group(group) gid = group_info.gr_gid add_user_to_group(user, group) if max_map...
Enable hugepages on system. Args: user (str) -- Username to allow access to hugepages to group (str) -- Group name to own hugepages nr_hugepages (int) -- Number of pages to reserve max_map_count (int) -- Number of Virtual Memory Areas a process can own mnt_point (str) -- Directory to mount hugepages on pagesize (str)...
juraj-google-style
def get_HDX_code_from_location_partial(location, locations=None, configuration=None): hdx_code = Locations.get_HDX_code_from_location(location, locations, configuration) if hdx_code is not None: return hdx_code, True if locations is None: locations = L...
Get HDX code for location Args: location (str): Location for which to get HDX code locations (Optional[List[Dict]]): Valid locations list. Defaults to list downloaded from HDX. configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: Tuple[Optional[str], bool]: HDX code a...
juraj-google-style
def validate(self, message): if hasattr(message, '__json__'): message = message.__json__() if isinstance(message['body'], six.text_type): message['body'] = json.loads(message['body']) elif isinstance(message['body'], six.binary_type): warnings.warn('Message body is no...
Validate the message before the consumer processes it. This needs to raise an exception, caught by moksha. Args: message (dict): The message as a dictionary. This must, at a minimum, contain the 'topic' key with a unicode string value and 'body' key with a dictionary value. However, the message might also be an objec...
codesearchnet
def AddWarning(self, warning): self._RaiseIfNotWritable() self._AddAttributeContainer( self._CONTAINER_TYPE_EXTRACTION_WARNING, warning)
Adds an warning. Args: warning (ExtractionWarning): warning. Raises: IOError: when the storage file is closed or read-only. OSError: when the storage file is closed or read-only.
juraj-google-style
def windows(self): from foxpuppet.windows import BrowserWindow return [BrowserWindow(self.selenium, handle) for handle in self.selenium.window_handles]
Return a list of all open windows. Returns: list: List of FoxPuppet BrowserWindow objects.
codesearchnet
def objects_delete(self, bucket, key): url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._escape_key(key))) datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation.
juraj-google-style
def notify(self, notices): tmpl_html = get_template('required_tags_notice.html') tmpl_text = get_template('required_tags_notice.txt') for recipient, data in list(notices.items()): body_html = tmpl_html.render(data=data) body_text = tmpl_text.render(data=data) ...
Send notifications to the recipients provided Args: notices (:obj:`dict` of `str`: `list`): A dictionary mapping notification messages to the recipient. Returns: `None`
juraj-google-style
def _PromptUserForEncryptedVolumeCredential(self, scan_context, locked_scan_node, output_writer): credentials = credentials_manager.CredentialsManager.GetCredentials(locked_scan_node.path_spec) if (locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER): line = 'Found an APFS encry...
Prompts the user to provide a credential for an encrypted volume. Args: scan_context (SourceScannerContext): the source scanner context. locked_scan_node (SourceScanNode): the locked scan node. output_writer (StdoutWriter): the output writer.
codesearchnet
def write_bottom_half(f, row_metadata_df, data_df, data_null, data_float_format, metadata_null): size_of_left_bottom_half_df = (row_metadata_df.shape[0], 1 + row_metadata_df.shape[1]) left_bottom_half_df = pd.DataFrame(np.full(size_of_left_bottom_half_df, metadata_null, d...
Write the bottom half of the gct file: row metadata and data. Args: f (file handle): handle for output file row_metadata_df (pandas df) data_df (pandas df) data_null (string): how to represent missing values in the data metadata_null (string): how to represent missing values in the metadata data_float_format (string):...
juraj-google-style
def read_value(self): return array_ops.identity(self._variable, name='read')
Returns the value of this variable, read in the current context. Can be different from value() if it's on another device, with control dependencies, etc. Returns: A `Tensor` containing the value of the variable.
github-repos
def getHostCaPath(self, name): cert = self.getHostCert(name) if (cert is None): return None return self._getCaPath(cert)
Gets the path to the CA certificate that issued a given host keypair. Args: name (str): The name of the host keypair. Examples: Get the path to the CA cert which issue the cert for "myhost": mypath = cdir.getHostCaPath('myhost') Returns: str: The path if exists.
codesearchnet
def decode(message, pblite, ignore_first_item=False): if (not isinstance(pblite, list)): logger.warning('Ignoring invalid message: expected list, got %r', type(pblite)) return if ignore_first_item: pblite = pblite[1:] if (pblite and isinstance(pblite[(- 1)], dict)): extra_fie...
Decode pblite to Protocol Buffer message. This method is permissive of decoding errors and will log them as warnings and continue decoding where possible. The first element of the outer pblite list must often be ignored using the ignore_first_item parameter because it contains an abbreviation of the name of the proto...
codesearchnet
def errorhandler_callback(cls, exc): if exc.flash_message: flash(exc.flash_message, exc.flash_level) if (exc.redirect is not MISSING): return redirect(url_for(exc.redirect, **exc.redirect_args)) error_result = exc.error_page() if (error_result is not None): return (error_result, ...
This function should be called in the global error handlers. This will allow for consolidating of cleanup tasks if the exception bubbles all the way to the top of the stack. For example, this method will automatically rollback the database session if the exception bubbles to the top. This is the method that :meth:`re...
codesearchnet
def format_snippet(sensor_graph): output = [] output.append("disable") output.append("clear") output.append("reset") for node in sensor_graph.dump_nodes(): output.append('add_node "{}"'.format(node)) for streamer in sensor_graph.streamers: line = "add_stre...
Format this sensor graph as iotile command snippets. This includes commands to reset and clear previously stored sensor graphs. Args: sensor_graph (SensorGraph): the sensor graph that we want to format
juraj-google-style
def run_metadata_graphs(name, data, step=None): summary_metadata = summary_pb2.SummaryMetadata() summary_metadata.plugin_data.plugin_name = 'graph_run_metadata_graph' summary_metadata.plugin_data.content = b'1' data = config_pb2.RunMetadata(function_graphs=data.function_graphs, partition_graphs=data.par...
Writes graphs from a RunMetadata summary. Args: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A RunMetadata proto to write. step: Explicit `int64`-castable monotonic step value for this summary. If omitted, this defaults to `tf.summary.e...
github-repos
def to(self, device: Optional[torch.device], dtype: Optional[torch.dtype]) -> Rotation: if self._rot_mats is not None: return Rotation(rot_mats=self._rot_mats.to(device=device, dtype=dtype), quats=None) elif self._quats is not None: return Rotation(rot_mats=None, quats=self._quats.to(device=devi...
Analogous to the to() method of torch Tensors Args: device: A torch device dtype: A torch dtype Returns: A copy of the Rotation using the new device and dtype
github-repos
def create_band_mask_from_inputs(from_blocked_mask, to_blocked_mask): exp_blocked_to_pad = torch.cat([to_blocked_mask[:, 1:-3], to_blocked_mask[:, 2:-2], to_blocked_mask[:, 3:-1]], dim=2) band_mask = torch.einsum('blq,blk->blqk', from_blocked_mask[:, 2:-2], exp_blocked_to_pad) band_mask.unsqueeze_(1) re...
Create 3D attention mask from a 2D tensor mask. Args: from_blocked_mask: 2D Tensor of shape [batch_size, from_seq_length//from_block_size, from_block_size]. to_blocked_mask: int32 Tensor of shape [batch_size, to_seq_length//to_block_size, to_block_size]. Returns: float Tensor of shape [batch_size, 1, from_seq_length/...
github-repos
def build_from_config(self, config): if config: if 'input_shape' in config: self.build(config['input_shape']) elif 'shapes_dict' in config: self.build(**config['shapes_dict'])
Builds the layer's states with the supplied config dict. By default, this method calls the `build(config["input_shape"])` method, which creates weights based on the layer's input shape in the supplied config. If your config contains other information needed to load the layer's state, you should override this method. ...
github-repos
def __init__(self, length=None, experimenter=None): super().__init__(action_type=ActionType.OFPAT_EXPERIMENTER) self.length = length self.experimenter = experimenter
Create ActionExperimenterHeader with the optional parameters below. Args: experimenter (int): The experimenter field is the Experimenter ID, which takes the same form as in struct ofp_experimenter.
juraj-google-style
def _get_new_alive_state(self, new_seq, new_log_probs, new_cache): new_finished_flags = tf.equal(new_seq[(:, :, (- 1))], self.eos_id) new_log_probs += (tf.to_float(new_finished_flags) * (- INF)) (top_alive_seq, top_alive_log_probs, top_alive_cache) = _gather_topk_beams([new_seq, new_log_probs, new_cache], n...
Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabilities of new sequences float32 tensor with shape [batch_size, beam_size] new_cache: Dict of cached...
codesearchnet
def _process_for_docstring(self, node, node_type): if (node.doc is not None): if (node_type == 'module'): if (not node.body): for key in list(self._tokenized_triple_quotes.keys()): quote_record = self._tokenized_triple_quotes.get(key) if qu...
Check for docstring quote consistency. Args: node: the AST node being visited. node_type: the type of node being operated on.
codesearchnet
def run_exit_code(self, returncode): exit_status = False self.log.info('[run] Exit Code {}'.format(returncode)) self.reports.increment_total() valid_exit_codes = self.profile.get('exit_codes', [0]) self.reports.exit_code(returncode) if returncode in valid_exi...
Handle the exit code for the current run. Args: returncode (int): The return exit code. Raises: RuntimeError: Raise on invalid exit code if halt_on_fail is True. Returns: bool: True if exit code is a valid exit code, else False.
juraj-google-style
def _add_property(self, name, default_value): name = str(name) self._properties[name] = default_value
Add a device property with a given default value. Args: name (str): The name of the property to add default_value (int, bool): The value of the property
juraj-google-style
def non_transactional(func, args, kwds, allow_existing=True): from . import tasklets ctx = tasklets.get_context() if (not ctx.in_transaction()): return func(*args, **kwds) if (not allow_existing): raise datastore_errors.BadRequestError(('%s cannot be called within a transaction.' % func....
A decorator that ensures a function is run outside a transaction. If there is an existing transaction (and allow_existing=True), the existing transaction is paused while the function is executed. Args: allow_existing: If false, throw an exception if called from within a transaction. If true, temporarily re-establish...
codesearchnet
def __chunk(segment, abbr=False): names = ('north', 'east', 'south', 'west', 'north') if (not abbr): sjoin = '-' else: names = [s[0].upper() for s in names] sjoin = '' if ((segment % 2) == 0): return (names[segment].capitalize(), sjoin.join((names[segment].capitalize(), n...
Generate a ``tuple`` of compass direction names. Args: segment (list): Compass segment to generate names for abbr (bool): Names should use single letter abbreviations Returns: bool: Direction names for compass segment
codesearchnet
def fts_intersection(self, segs): fts_vecs = [self.fts(s) for s in self.filter_segs(segs)] return reduce(lambda a, b: a & b, fts_vecs)
Return the features shared by `segs` Args: segs (list): list of Unicode IPA segments Returns: set: set of (value, feature) tuples shared by the valid segments in `segs`
juraj-google-style
def get_imported_namespaces(self, must_have_imported_data_type=False, consider_annotations=False, consider_annotation_types=False): imported_namespaces = [] for (imported_namespace, reason) in self._imported_namespaces.items(): if (must_have_imported_data_type and (not reason.data_type)): co...
Returns a list of Namespace objects. A namespace is a member of this list if it is imported by the current namespace and a data type is referenced from it. Namespaces are in ASCII order by name. Args: must_have_imported_data_type (bool): If true, result does not include namespaces that were not imported for data types...
codesearchnet
def ldr(scatterer, h_pol=True): Z = scatterer.get_Z() if h_pol: return (Z[0,0] - Z[0,1] + Z[1,0] - Z[1,1]) / \ (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1]) else: return (Z[0,0] + Z[0,1] - Z[1,0] - Z[1,1]) / \ (Z[0,0] + Z[0,1] + Z[1,0] + Z[1,1])
Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR.
juraj-google-style
def __batch_update(self, train_events, test_events, n_epoch): for epoch in range(n_epoch): if (n_epoch != 1): np.random.shuffle(train_events) for e in train_events: self.rec.update(e, batch_train=True) MPR = self.__batch_evaluate(test_events) if self.debug: ...
Batch update called by the fitting method. Args: train_events (list of Event): Positive training events. test_events (list of Event): Test events. n_epoch (int): Number of epochs for the batch training.
codesearchnet
def update_exif_for_rotated_image(exif): orientation_value = exif.get('0th', ).get( piexif.ImageIFD.Orientation, exif.get('1st', ).get( piexif.ImageIFD.Orientation, None)) if orientation_value is not None: exif['0th'][piexif.ImageIFD.Orientation] = 1 if exif.ge...
Modifies the Exif tag if rotation has been performed. 0th, 1st -------- ImageWidth = 256 ImageLength = 257 XResolution = 282 YResolution = 283 TileWidth = 322 TileLength = 323 Exif ---- PixelXDimension = 40962 PixelYDimension = 40963 Args: exif (dict): The parsed Exif tag Returns: The modified Exif dict.
juraj-google-style
class Siglip2Encoder(nn.Module): def __init__(self, config: Siglip2Config): super().__init__() self.config = config self.layers = nn.ModuleList([Siglip2EncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False @can_return_tuple def ...
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Siglip2EncoderLayer`]. Args: config: Siglip2Config
github-repos
def swd_sync(self, pad=False): if pad: self._dll.JLINK_SWD_SyncBytes() else: self._dll.JLINK_SWD_SyncBits() return None
Causes a flush to write all data remaining in output buffers to SWD device. Args: self (JLink): the ``JLink`` instance pad (bool): ``True`` if should pad the data to full byte size Returns: ``None``
juraj-google-style
def ExamineEvent(self, mediator, event): event_data_type = getattr(event, 'data_type', '') if event_data_type == 'windows:registry:service': service = WindowsService.FromEvent(event) self._service_collection.AddService(service)
Analyzes an event and creates Windows Services as required. At present, this method only handles events extracted from the Registry. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event to examine.
juraj-google-style
def execute(desktop_file, files=None, return_cmd=False, background=False): desktop_file_exec = parse(desktop_file)['Exec'] for i in desktop_file_exec.split(): if i.startswith('%'): desktop_file_exec = desktop_file_exec.replace(i, '') desktop_file_exec = desktop_file_exec.replace(r'%F', '') desktop_file...
Execute a .desktop file. Executes a given .desktop file path properly. Args: desktop_file (str) : The path to the .desktop file. files (list): Any files to be launched by the .desktop. Defaults to empty list. return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False``. background ...
juraj-google-style
def __init__(self, n_output_node, input_shape): super(MlpGenerator, self).__init__(n_output_node, input_shape) if len(self.input_shape) > 1: raise ValueError("The input dimension is too high.")
Initialize the instance. Args: n_output_node: An integer. Number of output nodes in the network. input_shape: A tuple. Input shape of the network. If it is 1D, ensure the value is appended by a comma in the tuple.
juraj-google-style
def get_error_intro(tf_error): if hasattr(tf_error, 'op') and hasattr(tf_error.op, 'name'): op_name = tf_error.op.name else: op_name = None intro_lines = ['--------------------------------------', RL('!!! An error occurred during the run !!!', 'blink'), ''] out = debugger_cli_common.rich...
Generate formatted intro for TensorFlow run-time error. Args: tf_error: (errors.OpError) TensorFlow run-time error object. Returns: (RichTextLines) Formatted intro message about the run-time OpError, with sample commands for debugging.
github-repos
def im_open(self, *, user: str, **kwargs) -> SlackResponse: kwargs.update({"user": user}) return self.api_call("im.open", json=kwargs)
Opens a direct message channel. Args: user (str): The user id to open a DM with. e.g. 'W1234567890'
juraj-google-style
def __rtruediv__(self, other): raise TypeError("unsupported operand type(s) for /: '{}' and 'Dimension', please use
Use `__floordiv__` via `x // y` instead. This function exists only to have a better error message. Instead of: `TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`, this function will explicitly call for usage of `//` instead. Args: other: Another `Dimension`. Raises: TypeError.
github-repos
def user_has_access(self, user): if ROLE_ADMIN in user.roles: return True if self.enabled: if not self.required_roles: return True for role in self.required_roles: if role in user.roles: return Tr...
Check if a user has access to view information for the account Args: user (:obj:`User`): User object to check Returns: True if user has access to the account, else false
juraj-google-style
def get_unique_tags(field_to_obs): return {field: sorted(set([x.get('tag', '') for x in observations])) for field, observations in field_to_obs.items() if field in TAG_FIELDS}
Returns a dictionary of tags that a user could query over. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict that maps keys in `TAG_FIELDS` to a list of string tags present in the event files. If the dict does not have any observations of the type, maps to an empty list so that we...
juraj-google-style
def validate_bindings(bindings): if (not isinstance(bindings, (list, tuple))): raise exceptions.ConfigurationException('bindings must be a list or tuple of dictionaries, but was a {}'.format(type(bindings))) for binding in bindings: missing_keys = [] for key in ('queue', 'exchange', 'rou...
Validate the bindings configuration. Raises: exceptions.ConfigurationException: If the configuration provided is of an invalid format.
codesearchnet
def load_data_and_labels(filename, encoding='utf-8'): (sents, labels) = ([], []) (words, tags) = ([], []) with open(filename, encoding=encoding) as f: for line in f: line = line.rstrip() if line: (word, tag) = line.split('\t') words.append(word...
Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. For example: ``` EU B-ORG rejects O German B-MISC call O to O boycott O British B-MISC lamb O . O Peter B-PER Bl...
codesearchnet
def __init__(self, encoding, buffer_size=2048): super(EncodedTextReader, self).__init__() self._buffer = '' self._buffer_size = buffer_size self._current_offset = 0 self._encoding = encoding self.lines = ''
Initializes the encoded text reader object. Args: encoding (str): encoding. buffer_size (Optional[int]): buffer size.
juraj-google-style
def beta_to_uni(text, strict=False): param_key = (strict,) try: t = _BETA_CONVERSION_TRIES[param_key] except KeyError: t = _create_conversion_trie(*param_key) _BETA_CONVERSION_TRIES[param_key] = t transform = [] idx = 0 possible_word_boundary = False w...
Converts the given text from betacode to unicode. Args: text: The beta code text to convert. All of this text must be betacode. strict: Flag to allow for flexible diacritic order on input. Returns: The converted text.
juraj-google-style
def read_user_data(self, user_data_path): raw_user_data = read_value_from_path(user_data_path) variables = self.get_variables() return parse_user_data(variables, raw_user_data, self.name)
Reads and parses a user_data file. Args: user_data_path (str): path to the userdata file Returns: str: the parsed user data file
juraj-google-style
def update_user_groups(self, user, claims): if settings.GROUPS_CLAIM is not None: django_groups = [group.name for group in user.groups.all()] if settings.GROUPS_CLAIM in claims: claim_groups = claims[settings.GROUPS_CLAIM] if not isi...
Updates user group memberships based on the GROUPS_CLAIM setting. Args: user (django.contrib.auth.models.User): User model instance claims (dict): Claims from the access token
juraj-google-style
def from_dict(cls, d): for cat in ['HEADER', 'VERS']: if (cat not in d): d[cat] = None alat = (d['ALAT'] * bohr_to_angstrom) plat = (d['PLAT'] * alat) species = [] positions = [] for site in d['SITE']: species.append(re.split('[0-9*]', site['ATOM'])[0]) positi...
Creates a CTRL file object from a dictionary. The dictionary must contain the items "ALAT", PLAT" and "SITE". Valid dictionary items are: ALAT: the a-lattice parameter PLAT: (3x3) array for the lattice vectors SITE: list of dictionaries: {'ATOM': class label, 'POS': (3x1) array of fractional coordinates} CLASS (option...
codesearchnet
def execute_before(self, sensor_graph, scope_stack): parent = scope_stack[-1] new_scope = TriggerScope(sensor_graph, scope_stack, parent.clock(self.interval, basis=self.basis)) scope_stack.append(new_scope)
Execute statement before children are executed. Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying scope_stack (list(Scope)): A stack of nested scopes that may influence how this statement allocates clocks or other stream resources.
juraj-google-style
def tagged(pode, tag): if tag.startswith(' tag = tag[1:] return (pode[1]['tags'].get(tag) is not None)
Check if a packed node has a given tag. Args: pode (tuple): A packed node. tag (str): The tag to check. Examples: Check if a node is tagged with "woot" and dostuff if it is. if s_node.tagged(node,'woot'): dostuff() Notes: If the tag starts with `#`, this is removed prior to checking. Returns: bool: True if the tag...
codesearchnet
def raise_not_enough_arguments(self, string): requested = errors.number((self.counter + 1)) number = len(self.positional) verb = ('was' if (number == 1) else 'were') what = "Requested {} formatting argument for '{}' but only {} {} supplied!" what = what.format(requested, string, number, verb) ra...
Raises an errors.ArgumentError if not enough arguments were supplied. Takes care of formatting for detailed error messages. Arguments: string (str): The string of the phrase for which there weren't enough arguments. Raises: errors.ArgumentError with a detailed error message.
codesearchnet
def determine_encoding(path, default=None): byte_order_marks = ( ('utf-8-sig', (codecs.BOM_UTF8, )), ('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)), ('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)), ) try: with open(path, 'rb') as infile: raw =...
Determines the encoding of a file based on byte order marks. Arguments: path (str): The path to the file. default (str, optional): The encoding to return if the byte-order-mark lookup does not return an answer. Returns: str: The encoding of the file.
juraj-google-style
def certificate_rabbitmq(self): if (not self.__certificate_rabbitmq): self.__certificate_rabbitmq = CertificateRabbitMQ(self.__connection) return self.__certificate_rabbitmq
Gets the Certificate RabbitMQ API client. Returns: CertificateRabbitMQ:
codesearchnet
def generate_lars_path(weighted_data, weighted_labels): x_vector = weighted_data alphas, _, coefs = lars_path(x_vector, weighted_labels, method='lasso', verbose=False) return a...
Generates the lars path for weighted data. Args: weighted_data: data that has been weighted by kernel weighted_label: labels, weighted by kernel Returns: (alphas, coefs), both are arrays corresponding to the regularization parameter and coefficients, respectively
juraj-google-style
def register_items(self, items): for item in items: item.set_parent(self) self.items.extend(items)
Bulk ``register_item``. Args: items (iterable[Tree]): Sequence of nodes to be registered as children.
juraj-google-style
def numpy(self) -> npt.ArrayLike: maybe_arr = self._numpy() return maybe_arr.copy() if isinstance(maybe_arr, np.ndarray) else maybe_arr
Copy of the contents of this Tensor into a NumPy array or scalar. Unlike NumPy arrays, Tensors are immutable, so this method has to copy the contents to ensure safety. Use `memoryview` to get a readonly view of the contents without doing a copy: >>> t = tf.constant([42]) >>> np.asarray(memoryview(t)) array([42], dtyp...
github-repos
def __init__(self, text: str, name: YangIdentifier = None, rev: str = None): super().__init__(text) self.name = name self.rev = rev
Initialize the parser instance. Args: name: Expected module name. rev: Expected revision date.
juraj-google-style
def show_events(self, status=None, nids=None): nrows, ncols = get_terminal_size() for task in self.iflat_tasks(status=status, nids=nids): report = task.get_event_report() if report: print(make_banner(str(task), width=ncols, mark="=")) pri...
Print the Abinit events (ERRORS, WARNIING, COMMENTS) to stdout Args: status: if not None, only the tasks with this status are select nids: optional list of node identifiers used to filter the tasks.
juraj-google-style
def __init__(self, channel): self.ListMonitoredResourceDescriptors = channel.unary_unary( "/google.monitoring.v3.MetricService/ListMonitoredResourceDescriptors", request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_metric__service__pb2.ListMonitoredResourceDescri...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def _request_reports(self, domains): params = [{'url': domain} for domain in domains] responses = self._requests.multi_get( self.BASE_URL, query_params=params, to_json=False) return responses
Sends multiples requests for the resources to a particular endpoint. Args: resource_param_name: a string name of the resource parameter. resources: list of of the resources. endpoint_name: AlexaRankingApi endpoint URL suffix. Returns: A list of the responses.
juraj-google-style
def traverse_nodes(self, node_set, depth=0): tab = " " result = list() for n in node_set: repr = ( n if self.nodes[n]["type"] == "variable" else f"{n}{inspect.signature(self.nodes[n]['lambda_fn'])}" ) ...
BFS traversal of nodes that returns name traversal as large string. Args: node_set: Set of input nodes to begin traversal. depth: Current traversal depth for child node viewing. Returns: type: String containing tabbed traversal view.
juraj-google-style
def _kl_pareto_pareto(a, b, name=None): with tf.name_scope(name or "kl_pareto_pareto"): final_batch_shape = distribution_util.get_broadcast_shape( a.concentration, b.concentration, a.scale, b.scale) common_type = dtype_util.common_dtype( [a.concentration, b.concentr...
Calculate the batched KL divergence KL(a || b) with a and b Pareto. Args: a: instance of a Pareto distribution object. b: instance of a Pareto distribution object. name: (optional) Name to use for created operations. default is "kl_pareto_pareto". Returns: Batchwise KL(a || b)
juraj-google-style
def get_forced_variation(self, experiment_key, user_id): if not self.is_valid: self.logger.error(enums.Errors.INVALID_DATAFILE.format('get_forced_variation')) return None if not validator.is_non_empty_string(experiment_key): self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('exp...
Gets the forced variation for a given user and experiment. Args: experiment_key: A string key identifying the experiment. user_id: The user ID. Returns: The forced variation key. None if no forced variation key.
juraj-google-style
def calculate_sun_from_date_time(self, datetime, is_solar_time=False): if datetime.year != 2016 and self.is_leap_year: datetime = DateTime(datetime.month, datetime.day, datetime.hour, datetime.minute, True) sol_dec, eq_of_time = self._calcul...
Get Sun for an hour of the year. This code is originally written by Trygve Wastvedt \ (Trygve.Wastvedt@gmail.com) based on (NOAA) and modified by Chris Mackey and Mostapha Roudsari Args: datetime: Ladybug datetime is_solar_time: A boolean to indicate if the input hour is solar time. (Default: False) Returns: A sun o...
juraj-google-style
def from_cif_string(cif_string, transformations=None, primitive=True, occupancy_tolerance=1.0): parser = CifParser.from_string(cif_string, occupancy_tolerance) raw_string = re.sub("'", '"', cif_string) cif_dict = parser.as_dict() cif_keys = list(cif_dict.keys()) s = parser.get_structures(primitive)[...
Generates TransformedStructure from a cif string. Args: cif_string (str): Input cif string. Should contain only one structure. For cifs containing multiple structures, please use CifTransmuter. transformations ([Transformations]): Sequence of transformations to be applied to the input structure. primitive (bool): Opti...
codesearchnet
def get_numeric_feature_names(example): numeric_features = ('float_list', 'int64_list') features = get_example_features(example) return sorted([feature_name for feature_name in features if (features[feature_name].WhichOneof('kind') in numeric_features)])
Returns a list of feature names for float and int64 type features. Args: example: An example. Returns: A list of strings of the names of numeric features.
codesearchnet
def init(self, force_deploy=False): machines = self.provider_conf.machines networks = self.provider_conf.networks _networks = [] for network in networks: ipnet = IPNetwork(network.cidr) _networks.append({ "netpool": list(ipnet)[10:-10], ...
Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started
juraj-google-style
def initialize_logger(): logger = logging.getLogger('steppy') logger.setLevel(logging.INFO) message_format = logging.Formatter(fmt='%(asctime)s %(name)s >>> %(message)s', datefmt='%Y-%m-%d %H:%M:%S') console_handler = logging.StreamHandler(sys.stdout) console_handler.setLevel(logging.INFO) conso...
Initialize steppy logger. This logger is used throughout the steppy library to report computation progress. Example: Simple use of steppy logger: .. code-block:: python initialize_logger() logger = get_logger() logger.info('My message inside pipeline') result looks like this: .. code:: 2018-06-02 12:33:48 stepp...
codesearchnet
def interpolate(self, x: types.RealTensor, y: types.RealTensor, name: str=None): name = name or self._name + '_interpolate' with tf.name_scope(name): x = tf.convert_to_tensor(x, dtype=self._dtype, name='x') y = tf.convert_to_tensor(y, dtype=self._dtype, name='y') y = tf.expand_dims(y, ax...
Performs 2-D interpolation on a specified set of points. Args: x: Real-valued `Tensor` of shape `batch_shape + [num_points]`. Defines the x-coordinates at which the interpolation should be performed. Note that `batch_shape` should be the same as in the underlying data. y: A `Tensor` of the same shape and `dtype` as `x...
github-repos
def delete(self, filename): if is_package(filename): self.connection["jss"].Package(filename).delete() else: self.connection["jss"].Script(filename).delete()
Delete a package or script from the distribution server. This method simply finds the Package or Script object from the database with the API GET call and then deletes it. This will remove the file from the database blob. For setups which have file share distribution points, you will need to delete the files on the s...
juraj-google-style
def read_record(cls, file_handle): buf_length_expected = 12 buf = file_handle.read(buf_length_expected) if not buf: return None if len(buf) != buf_length_expected: raise ValueError('Not a valid TFRecord. Fewer than %d bytes: %s' % (buf_length_expected, codecs.encode(buf, 'hex'))) len...
Read a record from a TFRecords file. Args: file_handle: The file to read from. Returns: None if EOF is reached; the paylod of the record otherwise. Raises: ValueError: If file appears to not be a valid TFRecords file.
github-repos
def _ParseFiletime(self, byte_stream): filetime_map = self._GetDataTypeMap('filetime') try: filetime = self._ReadStructureFromByteStream(byte_stream, 0, filetime_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseError('Unable to parse FILETIME value with error: {0!s...
Parses a FILETIME date and time value from a byte stream. Args: byte_stream (bytes): byte stream. Returns: dfdatetime.Filetime: FILETIME date and time value or None if no value is set. Raises: ParseError: if the FILETIME could not be parsed.
codesearchnet
def detect_gpt(self, filename, offset, fs_guid): self.logger.debug('Detecting GPT partition type') if (fs_guid not in self.__gpt_plugins): return None else: plugins = self.__gpt_plugins.get(fs_guid) for plugin in plugins: if plugin.detect(filename, offset): ...
Used by rawdisk.session.Session to match gpt partitions agains filesystem plugins. Args: filename: device or file that it will read in order to detect the filesystem fs_id: filesystem guid to match (ex. {EBD0A0A2-B9E5-4433-87C0-68B6B72699C7}) offset: offset for the filesystem that is being matched Returns: Volume obj...
codesearchnet
def E(poly, dist=None, **kws): if (not isinstance(poly, (distributions.Dist, polynomials.Poly))): print(type(poly)) print('Approximating expected value...') out = quadrature.quad(poly, dist, veceval=True, **kws) print('done') return out if isinstance(poly, distributions.D...
Expected value operator. 1st order statistics of a probability distribution or polynomial on a given probability space. Args: poly (Poly, Dist): Input to take expected value on. dist (Dist): Defines the space the expected value is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): The e...
codesearchnet
def parse_args(self, argv: list[str]) -> ParsedArgs: tool_args = self._parser.parse_args(argv) return self.process_parsed_args(tool_args)
Parses argv. Args: argv: sys.argv[1:] Returns: A ParsedArgs object
github-repos
def _CheckStorageFile(self, storage_file_path): if os.path.exists(storage_file_path): if not os.path.isfile(storage_file_path): raise errors.BadConfigOption( 'Storage file: {0:s} already exists and is not a file.'.format( storage_file_path)) logger.warning('App...
Checks if the storage file path is valid. Args: storage_file_path (str): path of the storage file. Raises: BadConfigOption: if the storage file path is invalid.
juraj-google-style
def json_compare(self, db_data, user_data): if isinstance(db_data, (string_types)): db_data = json.loads(db_data) if isinstance(user_data, (string_types)): user_data = json.loads(user_data) return self.deep_diff(db_data, user_data)
Validate data in user data. Args: db_data (str): The data store in Redis. user_data (str): The user provided data. Returns: bool: True if the data passed validation.
juraj-google-style
def write_supercells_with_displacements(supercell, cells_with_disps, filename='geo.gen'): write_dftbp((filename + 'S'), supercell) for ii in range(len(cells_with_disps)): write_dftbp((filename + 'S-{:03d}'.format((ii + 1))), cells_with_disps[ii])
Writes perfect supercell and supercells with displacements Args: supercell: perfect supercell cells_with_disps: supercells with displaced atoms filename: root-filename
codesearchnet
def umask(self, new_mask): if (not is_int_type(new_mask)): raise TypeError('an integer is required') old_umask = self.filesystem.umask self.filesystem.umask = new_mask return old_umask
Change the current umask. Args: new_mask: (int) The new umask value. Returns: The old umask. Raises: TypeError: if new_mask is of an invalid type.
codesearchnet
def _faster_to_representation(self, instance): ret = {} fields = self._readable_fields is_fast = isinstance(instance, prefetch.FastObject) id_fields = self._readable_id_fields for field in fields: attribute = None if (is_fast and (not isinstance(field, (DynamicGenericRelationField, D...
Modified to_representation with optimizations. 1) Returns a plain old dict as opposed to OrderedDict. (Constructing ordered dict is ~100x slower than `{}`.) 2) Ensure we use a cached list of fields (this optimization exists in DRF 3.2 but not 3.1) Arguments: instance: a model instance or data object Returns: Dict of ...
codesearchnet