code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def update_compounds(self, variants):
LOG.debug("Updating compound objects")
for var_id in variants:
variant_obj = variants[var_id]
if not variant_obj.get('compounds'):
continue
updated_compounds = self.update_variant_compounds(variant_obj, ... | Update the compounds for a set of variants.
Args:
variants(dict): A dictionary with _ids as keys and variant objs as values | juraj-google-style |
def run(self, sensor_graph, model):
for node, inputs, outputs in sensor_graph.iterate_bfs():
can_remove = False
if len(outputs) != 0:
continue
if sensor_graph.is_outpu... | Run this optimization pass on the sensor graph
If necessary, information on the device model being targeted
can be found in the associated model argument.
Args:
sensor_graph (SensorGraph): The sensor graph to optimize
model (DeviceModel): The device model we're using | juraj-google-style |
def get_current_epoch_time():
return int(round(time.time() * 1000)) | Current epoch time in milliseconds.
Returns:
An integer representing the current epoch time in milliseconds. | github-repos |
def _on_cancelok(self, cancel_frame):
_log.info('Consumer canceled; returning all unprocessed messages to the queue')
self._channel.basic_nack(delivery_tag=0, multiple=True, requeue=True) | Called when the server acknowledges a cancel request.
Args:
cancel_frame (pika.spec.Basic.CancelOk): The cancelok frame from
the server. | codesearchnet |
def _PrintAPFSVolumeIdentifiersOverview(
self, volume_system, volume_identifiers):
header = 'The following Apple File System (APFS) volumes were found:\n'
self._output_writer.Write(header)
column_names = ['Identifier', 'Name']
table_view = views.CLITabularTableView(column_names=column_names)... | Prints an overview of APFS volume identifiers.
Args:
volume_system (dfvfs.APFSVolumeSystem): volume system.
volume_identifiers (list[str]): allowed volume identifiers.
Raises:
SourceScannerError: if a volume cannot be resolved from the volume
identifier. | juraj-google-style |
def convert_slice(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting slice ...')
if (len(params['axes']) > 1):
raise AssertionError('Cannot convert slice by multiple dimensions')
if (params['axes'][0] not in [0, 1, 2, 3]):
raise AssertionError('Slice by dimension ... | Convert slice operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | codesearchnet |
def forward(self, pixel_values: torch.FloatTensor, spatial_shapes: torch.LongTensor) -> torch.Tensor:
target_dtype = self.patch_embedding.weight.dtype
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
positional_embeddings = self.position_embedding.weight.reshape(self.position_embeddi... | Args:
pixel_values (`torch.FloatTensor`):
Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
spatial_shapes (`List[Tuple[int, int]]`):
Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to | github-repos |
def real(x):
if any_symbolic_tensors((x,)):
return Real().symbolic_call(x)
return backend.numpy.real(x) | Return the real part of the complex argument.
Args:
x: Input tensor.
Returns:
The real component of the complex argument. | github-repos |
def Scripts(unicode_dir=_UNICODE_DIR):
scripts = {}
def DoLine(codes, fields):
'Process single Scripts.txt line, updating scripts.'
(_, name) = fields
scripts.setdefault(name, []).extend(codes)
ReadUnicodeTable((unicode_dir + '/Scripts.txt'), 2, DoLine)
return scripts | Returns dict mapping script names to code lists.
Args:
unicode_dir: Unicode data directory
Returns:
dict mapping script names to code lists | codesearchnet |
def with_scopes_if_required(credentials, scopes):
if (isinstance(credentials, Scoped) and credentials.requires_scopes):
return credentials.with_scopes(scopes)
else:
return credentials | Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`). This function will call
:meth:`Scoped.with_scopes` if the credentials are scoped... | codesearchnet |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
for subkey in registry_key.GetSubkeys():
drive_letter = subkey.name
if not drive_letter:
continue
values_dict = {
'DriveLetter': drive_letter,
'Type': 'Mapped Drive'}
remote_path_value... | Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | juraj-google-style |
def delay(self, secs):
secs = int(secs)
for i in reversed(range(secs)):
sys.stdout.write('\r')
sys.stdout.write("sleep %ds, left %2ds" % (secs, i+1))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\n")
return self | Delay some seconds
Args:
secs: float seconds
Returns:
self | juraj-google-style |
def __init__(self, terms: Mapping[raw_types.Gate, value.Scalar]) -> None:
super().__init__(terms, validator=self._is_compatible) | Initializes linear combination from a collection of terms.
Args:
terms: Mapping of gates to coefficients in the linear combination
being initialized. | juraj-google-style |
def set_datetime_format(self, format):
if not format in ["UNIX", "RFC3339"]:
return
self.datetime_format = format
self.set_header("Accept-Datetime-Format", self.datetime_format) | Set the Accept-Datetime-Format header to an acceptable
value
Args:
format: UNIX or RFC3339 | juraj-google-style |
def read_gbq(table, dataset=None, project_id=None, use_bqstorage_api=False, **kwargs):
if table is None:
raise ValueError('Please specify a BigQuery table to read from.')
elif len(kwargs) > 0:
raise ValueError(f'Encountered unsupported parameter(s) in read_gbq: {kwargs.keys()!r}')
return _Re... | This function reads data from a BigQuery table and produces a
:class:`~apache_beam.dataframe.frames.DeferredDataFrame.
Args:
table (str): Please specify a table. This can be done in the format
'PROJECT:dataset.table' if one would not wish to utilize
the parameters below.
dataset (str): Please specify the dataset
(can ... | github-repos |
def instantiate_references_json(references_json):
references = {}
for obj in references_json:
obj_id = obj['id']
obj_type = obj.get('subtype', obj['type'])
cls = get_class(obj_type)
instance = cls.__new__(cls, id=obj_id)
if (instance is None):
raise RuntimeErr... | Given a JSON representation of all the models in a graph, return a
dict of new model objects.
Args:
references_json (``JSON``)
JSON specifying new Bokeh models to create
Returns:
dict[str, Model] | codesearchnet |
def set_flowcontrol_receive(self, name, value=None, default=False, disable=False):
return self.set_flowcontrol(name, 'receive', value, default, disable) | Configures the interface flowcontrol receive value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (boolean): True if the interface should enable receiving
flow control packets, otherwise False
default (boolean): Specifies to default the interface flow
con... | codesearchnet |
def GetAddress(self):
script = ((b'21' + self.PublicKey.encode_point(True)) + b'ac')
script_hash = Crypto.ToScriptHash(script)
address = Crypto.ToAddress(script_hash)
return address | Returns the public NEO address for this KeyPair
Returns:
str: The private key | codesearchnet |
def adjust(self, amount, update=True, flow=True, fee=0.0):
self._capital += amount
self._last_fee += fee
if flow:
self._net_flows += amount
if update:
self.root.stale = True | Adjust capital - used to inject capital to a Strategy. This injection
of capital will have no effect on the children.
Args:
* amount (float): Amount to adjust by.
* update (bool): Force update?
* flow (bool): Is this adjustment a flow? A flow will not have an
impact on the performance (price index). Example of flows a... | codesearchnet |
def reminders_info(self, *, reminder: str, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"reminder": reminder})
return self.api_call("reminders.info", http_verb="GET", params=kwargs) | Gets information about a reminder.
Args:
reminder (str): The ID of the reminder. e.g. 'Rm12345678' | juraj-google-style |
def get_area_url(location, distance):
locations = [location.destination(i, distance) for i in range(0, 360, 90)]
latitudes = list(map(attrgetter('latitude'), locations))
longitudes = list(map(attrgetter('longitude'), locations))
bounds = (min(longitudes), min(latitudes), max(longitudes), max(latitudes))... | Generate URL for downloading OSM data within a region.
This function defines a boundary box where the edges touch a circle of
``distance`` kilometres in radius. It is important to note that the box is
neither a square, nor bounded within the circle.
The bounding box is strictly a trapezoid whose north and south edge... | codesearchnet |
def pred_to_prob(Y_h, k):
Y_h = Y_h.clone()
if (Y_h.dim() > 1):
Y_h = Y_h.squeeze()
assert (Y_h.dim() == 1)
assert (Y_h >= 1).all()
assert (Y_h <= k).all()
n = Y_h.shape[0]
Y_s = torch.zeros((n, k), dtype=Y_h.dtype, device=Y_h.device)
for (i, j) in enumerate(Y_h):
Y_s[(i,... | Converts a 1D tensor of predicted labels into a 2D tensor of probabilistic labels
Args:
Y_h: an [n], or [n,1] tensor of predicted (int) labels in {1,...,k}
k: the largest possible label in Y_h
Returns:
Y_s: a torch.FloatTensor of shape [n, k] where Y_s[i, j-1] is the probabilistic
label for item i and label j | codesearchnet |
def _infer_fused_data_format(self, input_batch):
input_shape = input_batch.get_shape().as_list()
input_shape_len = len(input_shape)
if (input_shape_len != 4):
raise NotImplementedError('fused batch norm supports only input with 4 dimensions, it received input of dimensionality {:d}'.format(input_sha... | Infers the data format for the fused batch norm.
It uses the axis option to infer this information. Specifically, the
axis value (0, 1, 2) corresponds to data format NHWC and the
axis value (0, 2, 3) to data format NCHW.
Args:
input_batch: A Tensor of arbitrary dimension.
Returns:
A string description of the data fo... | codesearchnet |
def Convert(self, input_file, output_file):
for version, schema, raw_binary, _ in self._schemas:
try:
data_candidate = self._Read(input_file, schema, raw_binary)
except RuntimeError:
continue
if 'version' not in data_candidate:
data_candidate['version'] = ... | Perform schema conversion from input_file to output_file.
Args:
input_file: Filename of TensorFlow Lite data to convert from. Must
be `.json` or `.bin` extension files for JSON or Binary forms of
the TensorFlow FlatBuffer schema.
output_file: Filename to write to. Extension also must be `.json`
or `.bin`.
Raises:
Run... | github-repos |
def generate_data(self, data_dir, tmp_dir, task_id=-1):
tf.logging.info("generate_data task_id=%s" % task_id)
encoder = self.get_or_create_vocab(data_dir, tmp_dir)
assert task_id >= 0 and task_id < self.num_generate_tasks
if task_id < self.num_train_shards:
out_file = self.training_filepaths(... | Generates training/dev data.
Args:
data_dir: a string
tmp_dir: a string
task_id: an optional integer
Returns:
shard or shards for which data was generated. | juraj-google-style |
def get_matching_text_in_strs(a, b, match_min_size=30, ignore='', end_characters=''):
compare = difflib.SequenceMatcher((lambda x: (x in ignore)))
compare.set_seqs(a=a, b=b)
matching_text = list()
for match in compare.get_matching_blocks():
start = match.a
text = a[start:(start + match.s... | Returns a list of matching blocks of text in a and b
Args:
a (str): First string to match
b (str): Second string to match
match_min_size (int): Minimum block size to match on. Defaults to 30.
ignore (str): Any characters to ignore in matching. Defaults to ''.
end_characters (str): End characters to look for. Defaults ... | codesearchnet |
def _field(self, field, value):
field = str(field)
value = str(value)
if (any([char in value for char in QUOTE_LIST]) and '"' not in value
and not any([char in value for char in UNQUOTE_LIST])):
value = '"' + value + '"'
... | Add a ``field:value`` term to the query.
Matches will have the ``value`` in the ``field``.
Note:
This method triggers advanced mode.
Arguments:
field (str): The field to check for the value, in Elasticsearch dot syntax.
value (str): The value to match.
Returns:
SearchHelper: Self | juraj-google-style |
def update(self, friendly_name=None, description=None, expiry=None, schema=None):
self._load_info()
if (friendly_name is not None):
self._info['friendlyName'] = friendly_name
if (description is not None):
self._info['description'] = description
if (expiry is not None):
if isinsta... | Selectively updates Table information.
Any parameters that are omitted or None are not updated.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
expiry: if not None, the new expiry time, either as a DateTime or milliseconds since epoch.
schema: if not None, the n... | codesearchnet |
def run(self, dag):
if self.layout is None:
if self.property_set["layout"]:
self.layout = self.property_set["layout"]
else:
self.layout = Layout.generate_trivial_layout(*dag.qregs.values())
self.property_set['is_direction_mapped'] = True
... | If `dag` is mapped and the direction is correct the property
`is_direction_mapped` is set to True (or to False otherwise).
Args:
dag (DAGCircuit): DAG to check. | juraj-google-style |
def export_to_xml(video_id, resource_fs, static_dir, course_id=None):
video_image_name = ''
video = _get_video(video_id)
try:
course_video = CourseVideo.objects.select_related('video_image').get(course_id=course_id, video=video)
video_image_name = course_video.video_image.image.name
exce... | Exports data for a video into an xml object.
NOTE: For external video ids, only transcripts information will be added into xml.
If external=False, then edx_video_id is going to be on first index of the list.
Arguments:
video_id (str): Video id of the video to export transcripts.
course_id (str): The ID of the course ... | codesearchnet |
def get_cytoband_coordinates(chrom, pos):
coordinate = ''
if (chrom in CYTOBANDS):
for interval in CYTOBANDS[chrom][pos]:
coordinate = interval.data
return coordinate | Get the cytoband coordinate for a position
Args:
chrom(str)
pos(int)
Returns:
coordinate(str) | codesearchnet |
def basis_state(str_state, num):
n = int(str_state, 2)
if num >= len(str_state):
state = np.zeros(1 << num, dtype=complex)
state[n] = 1
return state
else:
raise QiskitError('size of bitstring is greater than num.') | Return a basis state ndarray.
Args:
str_state (string): a string representing the state.
num (int): the number of qubits
Returns:
ndarray: state(2**num) a quantum state with basis basis state.
Raises:
QiskitError: if the dimensions is wrong | juraj-google-style |
def shift_relative_position_tensor(self, pos_tensor):
zero_pad = torch.zeros((*pos_tensor.size()[:3], 1), device=pos_tensor.device, dtype=pos_tensor.dtype)
pos_tensor_padded = torch.cat([zero_pad, pos_tensor], dim=-1)
pos_tensor_padded = pos_tensor_padded.view(*pos_tensor.size()[:2], pos_tensor.size(3) + 1,... | Args:
pos_tensor (torch.Tensor of shape (batch_size, head, time1, 2*time1-1)): Input tensor. | github-repos |
def _handle_response(self, response, valid_status_codes, resource):
if (response.status_code not in valid_status_codes):
raise InvalidStatusCodeError(status_code=response.status_code, expected_status_codes=valid_status_codes)
if response.content:
data = response.json()
if isinstance(data... | Handles Response objects
Args:
response: An HTTP reponse object
valid_status_codes: A tuple list of valid status codes
resource: The resource class to build from this response
returns:
resources: A list of Resource instances | codesearchnet |
def partitioned_dim_sizes(self):
return self._partitioned_dim_sizes | The partitioned dimension sizes for this shape.
Returns:
A `list` of 0-D or 1-D integer `Tensor`. | github-repos |
def date_range(start, end, boo):
earliest = datetime.strptime(start.replace('-', ' '), '%Y %m %d')
latest = datetime.strptime(end.replace('-', ' '), '%Y %m %d')
num_days = ((latest - earliest).days + 1)
all_days = [(latest - timedelta(days=x)) for x in range(num_days)]
all_days.reverse()
output ... | Return list of dates within a specified range, inclusive.
Args:
start: earliest date to include, String ("2015-11-25")
end: latest date to include, String ("2015-12-01")
boo: if true, output list contains Numbers (20151230); if false, list contains Strings ("2015-12-30")
Returns:
list of either Numbers or Strings | codesearchnet |
def _validate_min_version(min_version):
if min_version is not None:
try:
parsed_min_version = version.StrictVersion(min_version)
except ValueError:
return ExtensionVersionResult(
error_reason=ExtensionValidationError.UNPARSEABLE_REQUESTED_VERSION,
requested_extension_version... | Validates the extension version matches the requested version.
Args:
min_version: Minimum version passed as a query param when establishing the
connection.
Returns:
An ExtensionVersionResult indicating validation status. If there is a
problem, the error_reason field will be non-empty. | juraj-google-style |
def sort(self, by=None, reverse=False):
if by is None:
by = self.kdims
elif not isinstance(by, list):
by = [by]
sorted_columns = self.interface.sort(self, by, reverse)
return self.clone(sorted_columns) | Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset | juraj-google-style |
def object_key(self, root_path: KeyPath, *, value: Any, parent: Any, css_classes: Optional[Sequence[str]]=None, key_color: Union[Tuple[Optional[str], Optional[str]], Callable[[KeyPath, Any, Any], Tuple[Optional[str], Optional[str]]]]=None, enable_key_tooltip: bool=True, key_tooltip_fn: Optional[Callable[..., Html]]=Non... | Renders a label-style key for the value.
Args:
root_path: The root path of the value.
value: The value to render.
parent: The parent of the value.
css_classes: The CSS classes to add to the HTML element.
key_color: The color of the key. If None, the key will be rendered
without a color. If a tuple, the first element i... | github-repos |
def calculate_sun(self, month, day, hour, is_solar_time=False):
datetime = DateTime(month, day, *self._calculate_hour_and_minute(hour),
leap_year=self.is_leap_year)
return self.calculate_sun_from_date_time(datetime, is_solar_time) | Get Sun data for an hour of the year.
Args:
month: An integer between 1-12
day: An integer between 1-31
hour: A positive number between 0..23
is_solar_time: A boolean to indicate if the input hour is solar time.
(Default: False)
Returns:
A sun object for this particular time | juraj-google-style |
def get_all_results_for_query_batch(self, batch_id, job_id=None, chunk_size=2048):
result_ids = self.get_query_batch_result_ids(batch_id, job_id=job_id)
if not result_ids:
raise RuntimeError('Batch is not complete')
for result_id in result_ids:
yield self.get_que... | Gets result ids and generates each result set from the batch and returns it
as an generator fetching the next result set when needed
Args:
batch_id: id of batch
job_id: id of job, if not provided, it will be looked up | juraj-google-style |
def get_image_features(self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.LongTensor, qformer_attention_mask: Optional[torch.LongTensor]=None, interpolate_pos_encoding: Optional[bool]=False, return_dict: Optional[bool]=False):
pass | Encodes images into continuous embeddings that can be forwarded to the language model.
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
The tensors corresponding to the input images. | github-repos |
def _string_to_byte_list(self, data):
bytes_length = 16
m = self.digest()
m.update(str.encode(data))
hex_digest = m.hexdigest()
return list((int(hex_digest[(num * 2):((num * 2) + 2)], bytes_length) for num in range(bytes_length))) | Creates a hex digest of the input string given to create the image,
if it's not already hexadecimal
Returns:
Length 16 list of rgb value range integers
(each representing a byte of the hex digest) | codesearchnet |
def check_whitelist(host, whitelist):
if ':' not in host:
host = host + ':80'
if host in whitelist:
return True
return any(match_host(host, pattern) for pattern in whitelist) | Check a given request host against a whitelist.
Args:
host (str) :
A host string to compare against a whitelist.
If the host does not specify a port, then ``":80"`` is implicitly
assumed.
whitelist (seq[str]) :
A list of host patterns to match against
Returns:
``True``, if ``host`` matches any pattern in ``whitelis... | juraj-google-style |
def _create_c_op(graph, node_def, inputs, control_inputs, op_def=None, extract_traceback=True) -> pywrap_tf_session.TF_Operation:
if op_def is None:
op_def = graph.op_def_for_type(node_def.op)
inputs = _reconstruct_sequence_inputs(op_def, inputs, node_def.attr)
with graph._c_graph.get() as c_graph:
... | Creates a TF_Operation.
Args:
graph: a `Graph`.
node_def: `node_def_pb2.NodeDef` for the operation to create.
inputs: A flattened list of `Tensor`s. This function handles grouping
tensors into lists as per attributes in the `node_def`.
control_inputs: A list of `Operation`s to set as control dependencies.
op_def: Opti... | github-repos |
def plugin_wait_time(seconds: float, item_session: ItemSession, error: Optional[Exception]=None) -> float:
return seconds | Return the wait time between requests.
Args:
seconds: The original time in seconds.
item_session:
error:
Returns:
The time in seconds. | codesearchnet |
def to_array(tensor):
if tensor.HasField('segment'):
raise ValueError('Currently not supporting loading segments.')
if (tensor.data_type == TensorProto.UNDEFINED):
raise ValueError('The data type is not defined.')
tensor_dtype = tensor.data_type
np_dtype = mapping.TENSOR_TYPE_TO_NP_TYPE[... | Converts a tensor def object to a numpy array.
Inputs:
tensor: a TensorProto object.
Returns:
arr: the converted array. | codesearchnet |
def _inspect_history_cache(self, cache, replica_id, step_num, tensor_trace_order):
if not tensor_trace_order.traced_tensors:
logging.warn('TT history mode has no tensors in the cache to check.')
return control_flow_ops.no_op
stats = ['\n\n', 'core:', replica_id, ',', 'step:', step_num]
diffs... | Generates a conditional print operation to log differences in tensor values.
Args:
cache: Tensor storing the trace results for the step.
replica_id: Tensor storing the replica id of the running core.
step_num: Step number.
tensor_trace_order: TensorTraceOrder object holding tensorname to id map.
Returns:
The Op to fl... | github-repos |
def apply(self, func, **kwargs):
import dask
delayed_call = self.delayed_call
self.delayed_call = self.dask_obj
return self.__class__(dask.delayed(func)(delayed_call, **kwargs)) | Apply some callable function to the data in this partition.
Note: It is up to the implementation how kwargs are handled. They are
an important part of many implementations. As of right now, they
are not serialized.
Args:
func: The lambda to apply (may already be correctly formatted)
Returns:
A new `BaseFramePartitio... | juraj-google-style |
def on_epoch_end(self, epoch, logs=None): | Called at the end of an epoch.
Subclasses should override for any actions to run. This function should
only be called during TRAIN mode.
Args:
epoch: Integer, index of epoch.
logs: Dict, metric results for this training epoch, and for the
validation epoch if validation is performed. Validation result
keys are prefixe... | github-repos |
def get_cohesive_energy(self, material_id, per_atom=False):
entry = self.get_entry_by_material_id(material_id)
ebulk = entry.energy / \
entry.composition.get_integer_formula_and_factor()[1]
comp_dict = entry.composition.reduced_composition.as_dict()
isolated_ato... | Gets the cohesive for a material (eV per formula unit). Cohesive energy
is defined as the difference between the bulk energy and the sum of
total DFT energy of isolated atoms for atom elements in the bulk.
Args:
material_id (str): Materials Project material_id, e.g. 'mp-123'.
per_atom (bool): Whether or not to return c... | juraj-google-style |
def remove_roles(self, databaseName, roleNames, collectionName=None):
for roleName in roleNames:
self.remove_role(databaseName, roleName, collectionName) | Remove multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection | juraj-google-style |
def find(name, arg=None):
for p in get_processes():
if p.name.lower().find(name.lower()) != -1:
if arg is not None:
for a in p.cmdline or []:
if a.lower().find(arg.lower()) != -1:
return p
else:
return p... | Find process by name or by argument in command line.
Args:
name (str): Process name to search for.
arg (str): Command line argument for a process to search for.
Returns:
tea.process.base.IProcess: Process object if found. | juraj-google-style |
def set_weather_from_metar(metar: typing.Union[(Metar.Metar, str)], in_file: typing.Union[(str, Path)], out_file: typing.Union[(str, Path)]=None) -> typing.Tuple[(typing.Union[(str, None)], typing.Union[(str, None)])]:
(error, metar) = custom_metar.CustomMetar.get_metar(metar)
if error:
return (error, N... | Applies the weather from a METAR object to a MIZ file
Args:
metar: metar object
in_file: path to MIZ file
out_file: path to output MIZ file (will default to in_file)
Returns: tuple of error, success | codesearchnet |
def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed):
feed_item_service = client.GetService('FeedItemService', 'v201809')
now = datetime.now()
mars_date = datetime(now.year, now.month, 1, 0, 0)
venus_date = datetime(now.year, now.month, 15, 0, 0)
time_format = '%Y%m%d %H%M%S'
feed_i... | Creates FeedItems for the specified AdGroups.
These FeedItems contain values to use in ad customizations for the AdGroups.
Args:
client: an AdWordsClient instance.
adgroup_ids: a list containing two AdGroup Ids.
ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
with.
Raises:
GoogleAdsError: if... | juraj-google-style |
def _num_elements(self):
return math_ops.reduce_prod(self.inner_shape) | Number of elements in a shape.
Returns:
The number of elements in the shape. | github-repos |
def unpack_message(buffer):
hdr_size = Header().get_size()
hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:]
header = Header()
header.unpack(hdr_buff)
message = new_message_from_header(header)
message.unpack(msg_buff)
return message | Unpack the whole buffer, including header pack.
Args:
buffer (bytes): Bytes representation of a openflow message.
Returns:
object: Instance of openflow message. | juraj-google-style |
def malware(self, malware, password, file_name):
if (not self.can_update()):
self._tcex.handle_error(910, [self.type])
self._data['malware'] = malware
self._data['password'] = password
self._data['fileName'] = file_name
request = {'malware': malware, 'password': password, 'fileName': file_na... | Uploads to malware vault.
Args:
malware:
password:
file_name: | codesearchnet |
def omim_terms(case_obj):
LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get('display_name')))
disorders = []
case_disorders = case_obj.get('diagnosis_phenotypes')
if case_disorders:
for disorder in case_disorders:
disorder_obj = {
"id" : ':'.... | Extract all OMIM phenotypes available for the case
Args:
case_obj(dict): a scout case object
Returns:
disorders(list): a list of OMIM disorder objects | juraj-google-style |
def shared_s3_app_bucket(self, include_region=False):
if include_region:
shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].format(**self.data)
else:
shared_s3_app_bucket = self.format['shared_s3_app_bucket'].format(**self.data)
return shared_s3_ap... | Generate shared s3 application bucket name.
Args:
include_region (bool): Include region in the name generation. | juraj-google-style |
def add_cell_argument(self, name, help, required=False):
for action in self._actions:
if (action.dest == name):
raise ValueError(('Arg "%s" was added by add_argument already.' % name))
self._cell_args[name] = {'required': required, 'help': help} | Add a cell only argument.
Args:
name: name of the argument. No need to start with "-" or "--".
help: the help string of the argument.
required: Whether it is required in cell content. | codesearchnet |
def run(self, args):
jlink = self.create_jlink(args)
if args.product:
print(('Product: %s' % jlink.product_name))
manufacturer = ('SEGGER' if (jlink.oem is None) else jlink.oem)
print(('Manufacturer: %s' % manufacturer))
print(('Hardware Version: %s' % jlink.hardware_version))
... | Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | codesearchnet |
def get_open_clinvar_submission(self, user_id, institute_id):
LOG.info("Retrieving an open clinvar submission for user '%s' and institute %s", user_id, institute_id)
query = dict(user_id=user_id, institute_id=institute_id, status='open')
submission = self.clinvar_submission_collection.... | Retrieve the database id of an open clinvar submission for a user and institute,
if none is available then create a new submission and return it
Args:
user_id(str): a user ID
institute_id(str): an institute ID
Returns:
submission(obj) : an open clinvar submission object | juraj-google-style |
def parse_args():
parser = argparse.ArgumentParser()
parser.register('type', 'bool', lambda v: v.lower() == 'true')
parser.add_argument('--max_steps', type=int, default=10, help='Number of steps to run trainer.')
parser.add_argument('--train_batch_size', type=int, default=100, help='Batch size used duri... | Parses commandline arguments.
Returns:
A tuple (parsed, unparsed) of the parsed object and a group of unparsed
arguments that did not match the parser. | github-repos |
def save(value: Any, path: str, *args, **kwargs) -> Any:
save_handler = flags.get_save_handler() or default_save_handler
return save_handler(value, path, *args, **kwargs) | Save a symbolic value using the global save handler.
Example::
@pg.members([
('x', pg.typing.Any())
])
class A(pg.Object):
pass
a1 = A(1)
file = 'my_file.json'
a1.save(file)
a2 = pg.load(file)
assert pg.eq(a1, a2)
Args:
value: value to save.
path: A path string for saving `value`.
*args: Positional arguments that w... | github-repos |
def was_init():
mask = lib.SDL_WasInit(0)
return enumtools.get_items(InitFlags, mask, {InitFlags.everything}) | This function returns the subsystems which have previously been initialized.
Returns:
Set[InitFlag]: Flags indicating which subsystems have been initialized. | codesearchnet |
def __init__(self, saved_model_dir, saved_model_tags=None, saved_model_exported_names=None, trackable_obj=None):
super(TFLiteSavedModelConverterV2, self).__init__()
self.saved_model_dir = saved_model_dir
self._saved_model_tags = saved_model_tags
self._saved_model_exported_names = saved_model_exported_na... | Constructor for TFLiteConverter.
Args:
saved_model_dir: Directory of the SavedModel.
saved_model_tags: Set of tags identifying the MetaGraphDef within the
SavedModel to analyze. All tags in the tag set must be present. (default
{tf.saved_model.SERVING}).
saved_model_exported_names: Names to be exported when the saved ... | github-repos |
def regularizer(name, regularization_fn, name_filter='weights'):
regex = re.compile(name_filter)
def fn(var_name, variable, phase):
if ((phase is pt.Phase.train) and regex.search(var_name)):
with tf.name_scope(None, name, [variable]):
loss = regularization_fn(variable)
... | Wraps a regularizer in a parameter-function.
Args:
name: The name scope for this regularizer.
regularization_fn: A function with signature:
fn(variable) -> loss `Tensor` or `None`.
name_filter: A regex that will be used to filter variables by name.
Returns:
A parameter modification function that adds the loss to the
... | codesearchnet |
def read_tree_newick(newick):
if not isinstance(newick, str):
try:
newick = str(newick)
except:
raise TypeError("newick must be a str")
if newick.lower().endswith('.gz'):
f = gopen(expanduser(newick)); ts = f.read().decode().strip(); f.close()
elif isfil... | Read a tree from a Newick string or file
Args:
``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped)
Returns:
``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a ``list`` of ``Tree`` objects will be returned | juraj-google-style |
def _set_notification(self, conn, char, enabled, timeout=1.0):
if 'client_configuration' not in char:
return False, {'reason': 'Cannot enable notification without a client configuration attribute for characteristic'}
props = char['properties']
if not props.notify:
... | Enable/disable notifications on a GATT characteristic
Args:
conn (int): The connection handle for the device we should interact with
char (dict): The characteristic we should modify
enabled (bool): Should we enable or disable notifications
timeout (float): How long to wait before failing | juraj-google-style |
def create_sns_topic(self, region):
sns = self.session.client('sns', region_name=region)
self.log.info('Creating SNS topic for {}/{}'.format(self.account, region))
res = sns.create_topic(Name=self.topic_name)
arn = res['TopicArn']
tmpl = get_template('cloudtrail_sns_policy.json')
policy = tmpl.r... | Creates an SNS topic if needed. Returns the ARN if the created SNS topic
Args:
region (str): Region name
Returns:
`str` | codesearchnet |
def headless(self, value):
if value is True:
self._arguments.append('-headless')
elif '-headless' in self._arguments:
self._arguments.remove('-headless') | Sets the headless argument
Args:
value: boolean value indicating to set the headless option | juraj-google-style |
def indexSearch(self, indexes):
if not self._dataFrame.empty:
filter0 = self._dataFrame.index == -9999
for index in indexes:
filter1 = self._dataFrame.index == index
filter0 = np.logical_or(filter0, filter1)
return filter0
el... | Filters the data by a list of indexes.
Args:
indexes (list of int): List of index numbers to return.
Returns:
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned. | juraj-google-style |
def locked_put(self, credentials):
entity = self._model.get_or_insert(self._key_name)
setattr(entity, self._property_name, credentials)
entity.put()
if self._cache:
self._cache.set(self._key_name, credentials.to_json()) | Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store. | juraj-google-style |
def update(dst, src):
for k, v in src.items():
if isinstance(v, Mapping):
r = update(dst.get(k, {}), v)
dst[k] = r
else:
dst[k] = src[k]
return dst | Recursively update values in dst from src.
Unlike the builtin dict.update() function, this method will decend into
nested dicts, updating all nested values.
Arguments:
dst (dict): Destination dict.
src (dict): Source dict.
Returns:
dict: dst updated with entries from src. | juraj-google-style |
def __init__(self, use_memory_view_min_size=4096):
self.use_memory_view_min_size = use_memory_view_min_size
self._deque = collections.deque()
self.clear() | Constructor.
Args:
use_memory_view_min_size (int): minimum size before using
memoryview objects (advanced option, the default is probably
good for you). | juraj-google-style |
def DeserializeFromDB(buffer):
m = StreamManager.GetStream(buffer)
reader = BinaryReader(m)
uns = UnspentCoinState()
uns.Deserialize(reader)
StreamManager.ReleaseStream(m)
return uns | Deserialize full object.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
UnspentCoinState: | juraj-google-style |
def write(self, data):
start_time = time.time()
self._get_write_buffer().write(data)
ctx = context.get()
operation.counters.Increment(COUNTER_IO_WRITE_BYTES, len(data))(ctx)
operation.counters.Increment(COUNTER_IO_WRITE_MSEC, int(((time.time() - start_time) * 1000)))(ctx) | Write data to the GoogleCloudStorage file.
Args:
data: string containing the data to be written. | codesearchnet |
def create_queue(self, register=False):
queue = asyncio.Queue(loop=self._loop)
if register:
self._work_queues.add(queue)
return queue | Create a new work queue and optionally register it.
This will make sure the queue is attached to the correct event loop.
You can optionally choose to automatically register it so that
wait_idle() will block until the queue is empty.
Args:
register (bool): Whether to call register_workqueue() automatically.
Returns:
... | juraj-google-style |
def _CreateShapesFolder(self, schedule, doc):
if not schedule.GetShapeList():
return None
shapes_folder = self._CreateFolder(doc, 'Shapes')
shapes = list(schedule.GetShapeList())
shapes.sort(key=lambda x: x.shape_id)
for shape in shapes:
placemark = self._CreatePlacemark(shapes_fold... | Create a KML Folder containing all the shapes in a schedule.
The folder contains a placemark for each shape. If there are no shapes in
the schedule then the folder is not created and None is returned.
Args:
schedule: The transitfeed.Schedule instance.
doc: The KML Document ElementTree.Element instance.
Returns:
The ... | juraj-google-style |
def validate(self, config):
if not isinstance(config, dict):
raise errors.SchemeValidationError(
'Scheme can only validate a dictionary config, but was given '
'{} (type: {})'.format(config, type(config))
)
for arg in self.args:
... | Validate the given config against the `Scheme`.
Args:
config (dict): The configuration to validate.
Raises:
errors.SchemeValidationError: The configuration fails
validation against the `Schema`. | juraj-google-style |
def __init__(self, api_key=None):
try:
self.api_key = api_key or os.environ['AIRTABLE_API_KEY']
except KeyError:
raise KeyError('Api Key not found. Pass api_key as a kwarg \
or set an env var AIRTABLE_API_KEY with your key') | Authentication used by Airtable Class
Args:
api_key (``str``): Airtable API Key. Optional.
If not set, it will look for
enviroment variable ``AIRTABLE_API_KEY`` | juraj-google-style |
def stage_tc_batch(self, owner, staging_data):
batch = self.tcex.batch(owner)
for group in (staging_data.get('group') or []):
variable = group.pop('variable', None)
path = group.pop('path', None)
data = self.path_data(group, path)
if (group.get('xid') is None):
group[... | Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data. | codesearchnet |
def _close_open_file(self, file_des):
self.open_files[file_des] = None
heapq.heappush(self._free_fd_heap, file_des) | Remove file object with given descriptor from the list
of open files.
Sets the entry in open_files to None.
Args:
file_des: Descriptor of file object to be removed from
open files list. | codesearchnet |
def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors:
fn_cnt = 0
rel_cnt = 0
nested_cnt = 0
for key in parsed:
if parsed[key]["type"] == "Function":
fn_cnt += 1
if parsed[key]["type"] == "Relation":
rel_cnt += 1
if par... | Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input | juraj-google-style |
def _generate_visualization(template_file: str, loader: jinja2.BaseLoader, **kwargs) -> str:
env = jinja2.Environment(loader=loader)
template = env.get_template(template_file)
return template.render(cytoscape_url=_CYTOSCAPE_URL, dagre_url=_DAGRE_URL, cytoscape_dagre_url=_CYTOSCAPE_DAGRE_URL, **kwargs) | Generate the visualization webpage.
Args:
template_file: str. A jinja2 template filename.
loader: jinja2.BaseLoader. The loader needs to be able to load files in this
file's directory.
**kwargs: Additional args passed on to the template.
Returns:
str. The rendered visualization page. | github-repos |
def AddEventAttribute(self, attribute_name, attribute_value):
if (attribute_name in self._extra_event_attributes):
raise KeyError('Event attribute {0:s} already set'.format(attribute_name))
self._extra_event_attributes[attribute_name] = attribute_value | Adds an attribute that will be set on all events produced.
Setting attributes using this method will cause events produced via this
mediator to have an attribute with the provided name set with the
provided value.
Args:
attribute_name (str): name of the attribute to add.
attribute_value (str): value of the attribute ... | codesearchnet |
def closest_point_to(self, point, thr=20.0):
i = 0
point_arr = point.gen2arr()
def closest_in_line(pointA, pointB):
temp = closest_point(pointA.gen2arr(), pointB.gen2arr(), point_arr)
return Point(temp[1], temp[0], None)
for (p_a, p_b) in pairwise(self.points):
candidate = close... | Finds the closest point in the segment to a given point
Args:
point (:obj:`Point`)
thr (float, optional): Distance threshold, in meters, to be considered
the same point. Defaults to 20.0
Returns:
(int, Point): Index of the point. -1 if doesn't exist. A point is given if it's along the segment | codesearchnet |
def __init__(self, *args, **kwargs):
super(MemoryStream, self).__init__(*args, **kwargs) | Create an instance.
Args:
*args:
**kwargs: | juraj-google-style |
def wait_for_contract(self, contract_address_hex, timeout=None):
contract_address = decode_hex(contract_address_hex)
start_time = time.time()
result = self._raiden.chain.client.web3.eth.getCode(to_checksum_address(contract_address))
current_time = time.time()
while (not result):
if (timeout ... | Wait until a contract is mined
Args:
contract_address_hex (string): hex encoded address of the contract
timeout (int): time to wait for the contract to get mined
Returns:
True if the contract got mined, false otherwise | codesearchnet |
def build_institute(internal_id, display_name, sanger_recipients=None,
coverage_cutoff=None, frequency_cutoff=None):
LOG.info("Building institute %s with display name %s", internal_id,display_name)
institute_obj = Institute(
internal_id=internal_id,
display_name=displ... | Build a institute object
Args:
internal_id(str)
display_name(str)
sanger_recipients(list(str)): List with email addresses
Returns:
institute_obj(scout.models.Institute) | juraj-google-style |
def to_string(
self,
fmt: str = "medium",
canonicalize: bool = False,
decanonicalize: bool = False,
orthologize: str = None,
) -> str:
arg_string = ", ".join([a.to_string(fmt=fmt) for a in self.args])
if fmt in ["short", "medium"]:
funct... | Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Returns:
str: string version of BEL AST | juraj-google-style |
def stop(self, accountID, **kwargs):
return self.create(accountID, order=StopOrderRequest(**kwargs)) | Shortcut to create a Stop Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a StopOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | codesearchnet |
def _ExtractPath(response, pathspec_attribute=None):
path_specification = response
if (pathspec_attribute is not None):
if response.HasField(pathspec_attribute):
path_specification = response.Get(pathspec_attribute)
if path_specification.HasField('pathspec'):
path_specification =... | Returns the path from a client action response as a string.
Args:
response: A client action response.
pathspec_attribute: Specifies the field which stores the pathspec.
Returns:
The path as a string or None if no path is found. | codesearchnet |
def register_trainable(name, trainable):
from ray.tune.trainable import Trainable
from ray.tune.function_runner import wrap_function
if isinstance(trainable, type):
logger.debug("Detected class for trainable.")
elif isinstance(trainable, FunctionType):
logger.debug("Detected funct... | Register a trainable function or class.
Args:
name (str): Name to register.
trainable (obj): Function or tune.Trainable class. Functions must
take (config, status_reporter) as arguments and will be
automatically converted into a class during registration. | juraj-google-style |
def start(self, extra_args="", tag=""):
if self.started:
return
utils.create_dir(self.log_path)
if tag:
tag = tag + ','
out_file_name = "IPerfServer,{},{}{}.log".format(
self.port, tag, len(self.log_files))
full_out_path = os.path.join... | Starts iperf server on specified port.
Args:
extra_args: A string representing extra arguments to start iperf
server with.
tag: Appended to log file name to identify logs from different
iperf runs. | juraj-google-style |
def _super_stack(inputs,
attention_bias,
hparams,
mp,
padding="LEFT"):
layers = hparams.layers.strip(",").split(",")
moe_hidden_sizes = [int(s) for s in hparams.moe_hidden_sizes.split(",")]
if hparams.diet_experts:
hsize, = moe_hidden_size... | A stack of super_lm layers.
Args:
inputs: a list of Tensors
attention_bias: list of bias Tensor for self-attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
mp: a Parallelism object
padding: a string
Returns:
y: a list of Tensors
extra_loss: an optional scalar | juraj-google-style |
def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B):
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A))
ang_vel_B = rot_A_in_B.dot(ang_vel_A)
return... | Converts linear and angular velocity of a point in frame A to the equivalent in frame B.
Args:
vel_A: 3-dim iterable for linear velocity in A
ang_vel_A: 3-dim iterable for angular velocity in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
vel_B, ang_vel_B: two numpy array... | juraj-google-style |
def verify_gmt_integrity(gmt):
set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
assert len(set(set_ids)) == len(set_ids), (
"Set identifiers should be unique. set_ids: {}".format(set_ids)) | Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None | juraj-google-style |
def GetConfig(self, request, global_params=None):
config = self.GetMethodConfig('GetConfig')
return self._RunMethod(config, request, global_params=global_params) | Get encoded debug configuration for component. Not cacheable.
Args:
request: (DataflowProjectsJobsDebugGetConfigRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(GetDebugConfigResponse) The response message. | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.