code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def GetRelativePath(self, path_spec):
location = getattr(path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
if not location.... | Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
Returns:
str: corresponding relative path or None if the relative ... | juraj-google-style |
def inet_to_str(inet):
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueError:
return socket.inet_ntop(socket.AF_INET6, inet) | Convert inet object to a string
Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address | codesearchnet |
def destroy_iam(app='', env='dev', **_):
session = boto3.Session(profile_name=env)
client = session.client('iam')
generated = get_details(env=env, app=app)
generated_iam = generated.iam()
app_details = collections.namedtuple('AppDetails', generated_iam.keys())
details = app_details(**gener... | Destroy IAM Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment, i.e. dev, stage, prod.
Returns:
True upon successful completion. | juraj-google-style |
def movie_list(self, **kwargs):
path = self._get_path('movie_list')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the list of Movie genres.
Args:
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API. | juraj-google-style |
def get_mnemonic(self, mnemonic, alias=None):
alias = (alias or {})
aliases = alias.get(mnemonic, [mnemonic])
for a in aliases:
if (a in self.data):
return a
return None | Instead of picking curves by name directly from the data dict, you
can pick them up with this method, which takes account of the alias
dict you pass it. If you do not pass an alias dict, then you get the
curve you asked for, if it exists, or None. NB Wells do not have alias
dicts, but Projects do.
Args:
mnemonic (str)... | codesearchnet |
def ParseFileObject(self, parser_mediator, file_object):
file_offset = 0
file_size = file_object.get_size()
record_map = self._GetDataTypeMap('pls_recall_record')
while (file_offset < file_size):
try:
(pls_record, record_data_size) = self._ReadStructureFromFileObject(file_object, fil... | Parses a PLSRecall.dat file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed. | codesearchnet |
def loss(logits, labels, batch_size=None):
if not batch_size:
batch_size = FLAGS.batch_size
sparse_labels = tf.reshape(labels, [batch_size, 1])
indices = tf.reshape(tf.range(batch_size), [batch_size, 1])
concated = tf.concat(axis=1, values=[indices, sparse_labels])
num_classes = logits[0].get_sh... | Adds all losses for the model.
Note the final loss is not returned. Instead, the list of losses are collected
by slim.losses. The losses are accumulated in tower_loss() and summed to
calculate the total loss.
Args:
logits: List of logits from inference(). Each entry is a 2-D float Tensor.
labels: Labels from distorte... | juraj-google-style |
def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True,
shard_ctx=None, slice_ctx=None):
if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle):
return
shard_context = shard_ctx or self.shard_context
slice_context = slice_ctx or self.slice_co... | Makes sure shard life cycle interface are respected.
Args:
obj: the obj that may have implemented _ShardLifeCycle.
slice_id: current slice_id
last_slice: whether this is the last slice.
begin_slice: whether this is the beginning or the end of a slice.
shard_ctx: shard ctx for dependency injection. If None, it will be ... | juraj-google-style |
def update(self, **kwargs):
for arg in kwargs:
if hasattr(self, arg):
setattr(self, arg, kwargs[arg])
else:
raise ValueError(('Invalid RayParams parameter in update: %s' % arg))
self._check_usage() | Update the settings according to the keyword arguments.
Args:
kwargs: The keyword arguments to set corresponding fields. | codesearchnet |
def assert_like_rnncell(cell_name, cell):
conditions = [_hasattr(cell, 'output_size'), _hasattr(cell, 'state_size'), _hasattr(cell, 'get_initial_state') or _hasattr(cell, 'zero_state'), callable(cell)]
errors = ["'output_size' property is missing", "'state_size' property is missing", "either 'zero_state' or 'ge... | Raises a TypeError if cell is not like an RNNCell.
NOTE: Do not rely on the error message (in particular in tests) which can be
subject to change to increase readability. Use
ASSERT_LIKE_RNNCELL_ERROR_REGEXP.
Args:
cell_name: A string to give a meaningful error referencing to the name of
the functionargument.
cell: T... | github-repos |
def step(self, actions):
for index, (env, action) in enumerate(zip(self._envs, actions)):
if not env.action_space.contains(action):
message = 'Invalid action at index {}: {}'
raise ValueError(message.format(index, action))
if self._blocking:
transitions = [
env.step(ac... | Forward a batch of actions to the wrapped environments.
Args:
actions: Batched action to apply to the environment.
Raises:
ValueError: Invalid actions.
Returns:
Batch of observations, rewards, and done flags. | juraj-google-style |
def to_image(self, filename='palette.png', band_width=1, length=60, max_width=0, vertical=True, alpha_channel=False):
if (max_width < 1):
pass
else:
band_width = int((max_width / len(self._colours)))
image_width = (band_width * len(self._colours))
if alpha_channel:
my_image = Ima... | Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
length(Optional[int]): the length of the overall image in pixels.
This is the d... | codesearchnet |
def export_panels(adapter, panels, versions=None, build='37'):
if versions and (len(versions) != len(panels)):
raise SyntaxError("If version specify for each panel")
headers = []
build_string = ("
headers.append(build_string.format(build))
header_string = ("
contig_string = ("... | Export all genes in gene panels
Exports the union of genes in one or several gene panels to a bed like format with coordinates.
Args:
adapter(scout.adapter.MongoAdapter)
panels(iterable(str)): Iterable with panel ids
bed(bool): If lines should be bed formated | juraj-google-style |
def running(processid):
try:
os.kill(processid, 0)
except OverflowError as exc:
print('checking validity of pid ({p}) failed with: {e}'.format(p=processid, e=exc))
sys.exit(1)
except OSError:
return False
else:
return True | Check the validity of a process ID.
Arguments:
processid (int): Process ID number.
Returns:
True if process ID is found otherwise False. | codesearchnet |
def make_repr(self, attrs):
if (config.REPR_VERBOSITY in [MEDIUM, HIGH]):
return self.__str__()
elif (config.REPR_VERBOSITY is LOW):
return '{}({})'.format(self.__class__.__name__, ', '.join((((attr + '=') + repr(getattr(self, attr))) for attr in attrs)))
raise ValueError('Invalid value for ... | Construct a repr string.
If `config.REPR_VERBOSITY` is ``1`` or ``2``, this function calls the
object's __str__ method. Although this breaks the convention that __repr__
should return a string which can reconstruct the object, readable reprs are
invaluable since the Python interpreter calls `repr` to represent all
obj... | codesearchnet |
def override_default_args(**kwargs):
override_default_kwargs = kwargs
def custom_getter(getter, *args, **kwargs):
updated_kwargs = override_default_kwargs.copy()
updated_kwargs.update({kw: value for kw, value in six.iteritems(kwargs)
if value is not None})
return get... | Creates a custom getter that applies specified named arguments.
The returned custom getter treats the specified named arguments as revised
defaults, and does not override any non-`None` argument values supplied by
the original get_variable call (or by a nested scope's custom getter).
Args:
**kwargs: Overriding argume... | juraj-google-style |
def render(raw_config, environment=None):
t = Template(raw_config)
buff = StringIO()
if not environment:
environment = {}
try:
substituted = t.substitute(environment)
except KeyError as e:
raise exceptions.MissingEnvironment(e.args[0])
except ValueError:
... | Renders a config, using it as a template with the environment.
Args:
raw_config (str): the raw stacker configuration string.
environment (dict, optional): any environment values that should be
passed to the config
Returns:
str: the stacker configuration populated with any values passed from
the environment | juraj-google-style |
def update_hparams_for_universal_transformer(hparams):
hparams.daisy_chain_variables = False
hparams.add_hparam('mix_with_transformer', None)
hparams.add_hparam('num_mixedin_layers', 2)
hparams.add_hparam('num_inrecurrence_layers', 1)
hparams.add_hparam('recurrence_type', 'basic')
hparams.add_hp... | Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Universal Transformers hyper-parameters | codesearchnet |
def InitUser():
result = AppUser.query((AppUser.user == users.get_current_user())).fetch()
if result:
app_user = result[0]
else:
app_user = AppUser(user=users.get_current_user(), email=users.get_current_user().email())
app_user.put()
return app_user | Initialize application user.
Retrieve existing user credentials from datastore or add new user.
Returns:
AppUser instance of the application user. | codesearchnet |
def _get_rand_attn_plan(from_seq_length, from_block_size, num_rand_blocks):
plan_from_length = []
plan_num_rand_blocks = []
if 2 * num_rand_blocks + 5 < from_seq_length
plan_from_length.append(int((2 * num_rand_blocks + 5) * from_block_size))
plan_num_rand_blocks.append(num_rand_blocks)
... | Gives the plan of where to put random attention.
Args:
from_seq_length: int. length of from sequence.
from_block_size: int. size of block in from sequence.
num_rand_blocks: int. Number of random chunks per row.
Returns:
plan_from_length: ending location of from block plan_num_rand_blocks: number of random ending loca... | github-repos |
def json_set_description(recipe, variables):
if 'script' in recipe:
if 'description' in recipe['script']:
try:
recipe['script']['description'] = text_set_fields(recipe['script']['description'], variables)
except KeyError:
pass | Replaces all fields in description with values provided.
Checks if recipe['script']['description'] exist. The replaces all %(???)s
variables
with values provided. Note: %(???)s must match { "field":{ "name":"???" }}
in JOSN.
Args:
recipe: (dict) A dictionary representation of the JSON script.
variables: (dict) A lo... | github-repos |
def _resize_for_patching(self, image: np.array, target_resolution: tuple, resample, input_data_format: ChannelDimension) -> np.array:
new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format)
resized_image = resize(image, (new_height, new_width), resample=resample, input_data_fo... | Resizes an image to a target resolution while maintaining aspect ratio.
Args:
image (np.array):
The input image.
target_resolution (tuple):
The target resolution (height, width) of the image.
resample (`PILImageResampling`):
Resampling filter to use if resizing the image.
input_data_format (`ChannelDimension` or `str`... | github-repos |
def __init__(self, bits: List[int], order: int, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform(), name: Union[None, str]=None):
parity_layer = energy_utils.Parity(bits, order)
self._num_terms = parity_layer.num_terms
self._indices = parity_layer.indices
pre_process = ... | Initializes a KOBE.
Args:
bits: Each entry is an index on which the distribution is supported.
order: The order of the KOBE.
initializer: Specifies how to initialize the values of the parameters.
name: Optional name for the model. | github-repos |
def holiday_name(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError('value {} need to be of type str '
'for field `holiday_name`'.format(value))
if ',' ... | Corresponds to IDD Field `holiday_name`
Args:
value (str): value for IDD Field `holiday_name`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
def _minimum_one_is_missing(self, **kwargs):
rqset = self._meta_data['minimum_additional_parameters']
if rqset:
kwarg_set = set(iterkeys(kwargs))
if kwarg_set.isdisjoint(rqset):
args = sorted(rqset)
error_message = ('This resource requires at least one of the mandatory ad... | Helper function to do operation on sets
Verify if at least one of the elements
is present in **kwargs. If no items of rqset
are contained in **kwargs the function
raises exception.
This check will only trigger if rqset is not empty.
Raises:
MissingRequiredCreationParameter | codesearchnet |
def _define_loop(graph, logdir, train_steps, eval_steps):
loop = tools.Loop(logdir, graph.step, graph.should_log, graph.do_report, graph.force_reset)
loop.add_phase('train', graph.done, graph.score, graph.summary, train_steps, report_every=train_steps, log_every=(train_steps
loop.add_phase('eval', graph.do... | Create and configure a training loop with training and evaluation phases.
Args:
graph: Object providing graph elements via attributes.
logdir: Log directory for storing checkpoints and summaries.
train_steps: Number of training steps per epoch.
eval_steps: Number of evaluation steps per epoch.
Returns:
Loop object. | codesearchnet |
def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name):
self._set_grid_info('x', x_low, x_high, num_x, xscale, xval_name)
return | Set the grid values for x.
Create information for the grid of x values.
Args:
num_x (int): Number of points on axis.
x_low/x_high (float): Lowest/highest value for the axis.
xscale (str): Scale of the axis. Choices are 'log' or 'lin'.
xval_name (str): Name representing the axis. See GenerateContainer documentation
fo... | juraj-google-style |
def get_word_index(path='reuters_word_index.json'):
origin_folder = 'https:
path = get_file(path, origin=origin_folder + 'reuters_word_index.json', file_hash='4d44cc38712099c9e383dc6e5f11a921')
with open(path) as f:
return json.load(f) | Retrieves a dict mapping words to their index in the Reuters dataset.
Actual word indices starts from 3, with 3 indices reserved for:
0 (padding), 1 (start), 2 (oov).
E.g. word index of 'the' is 1, but the in the actual training data, the
index of 'the' will be 1 + 3 = 4. Vice versa, to translate word indices in
trai... | github-repos |
def _set_request_cache_if_django_cache_hit(key, django_cached_response):
if django_cached_response.is_found:
DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value) | Sets the value in the request cache if the django cached response was a hit.
Args:
key (string)
django_cached_response (CachedResponse) | codesearchnet |
def GetConsoleAttr(encoding=None, reset=False):
attr = ConsoleAttr._CONSOLE_ATTR_STATE
if not reset:
if not attr:
reset = True
elif encoding and encoding != attr.GetEncoding():
reset = True
if reset:
attr = ConsoleAttr(encoding=encoding)
ConsoleAttr._C... | Gets the console attribute state.
If this is the first call or reset is True or encoding is not None and does
not match the current encoding or out is not None and does not match the
current out then the state is (re)initialized. Otherwise the current state
is returned.
This call associates the out file stream with t... | github-repos |
class Sliceable:
def __init__(self, array):
self.array = array
def __getitem__(self, indices):
return self.array[indices]
@classmethod
def cast(cls, x, dtype):
return x.astype(dtype)
@classmethod
def convert_to_numpy(cls, x):
return ... | `Sliceable` wrapping a tensor.
A `Sliceable` implements the subscript operator to slice or index against
the first dimension of the array. It also has conversion methods for each
one of the backends.
Args:
array: the native array or tensor to wrap.
Attributes:
shape: the shape of the full dense native array. | github-repos |
def destroy_cloudwatch_event(app='', env='dev', region=''):
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
event_rules = get_cloudwatch_event_rule(app_name=app, account=env, region=region)
for rule in event_rules:
cloudwatch_cli... | Destroy Cloudwatch event subscription.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion. | juraj-google-style |
def print_tensors_in_checkpoint_file(file_name, tensor_name, all_tensors, all_tensor_names=False, count_exclude_pattern=''):
try:
reader = py_checkpoint_reader.NewCheckpointReader(file_name)
if all_tensors or all_tensor_names:
var_to_shape_map = reader.get_variable_to_shape_map()
... | Prints tensors in a checkpoint file.
If no `tensor_name` is provided, prints the tensor names and shapes
in the checkpoint file.
If `tensor_name` is provided, prints the content of the tensor.
Args:
file_name: Name of the checkpoint file.
tensor_name: Name of the tensor in the checkpoint file to print.
all_tensors: ... | github-repos |
def create_combination(list_of_sentences):
num_sentences = len(list_of_sentences) - 1
combinations = []
for i, _ in enumerate(list_of_sentences):
if i == num_sentences:
break
num_pairs = num_sentences - i
populated = num_pairs * [list_of_sentences[i]]
zipped = list(zip(populated, list_of_... | Generates all possible pair combinations for the input list of sentences.
For example:
input = ["paraphrase1", "paraphrase2", "paraphrase3"]
output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphrase3")]
Args:
list_of_sentences: the list of input sentences.
Returns:
the li... | juraj-google-style |
def reset_time_estimate(self, **kwargs):
path = ('%s/%s/reset_time_estimate' % (self.manager.path, self.get_id()))
return self.manager.gitlab.http_post(path, **kwargs) | Resets estimated time for the object to 0 seconds.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done | codesearchnet |
def get_key_by_job_id(cls, mapreduce_id):
return db.Key.from_path(cls.kind(), "%s:%s" % (mapreduce_id, cls._KEY_NAME)) | Retrieves the Key for a mapreduce ID.
Args:
mapreduce_id: The job to fetch.
Returns:
Datastore Key for the command for the given job ID. | juraj-google-style |
def get_attribute_from_config(config, section, attribute):
section = config.get(section)
if section:
option = section.get(attribute)
if option:
return option
raise ConfigurationError("Config file badly formed!\n"
"Failed to get attribute '{}' fro... | Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Returns:
str: The string corresponding to the section and attribute.
Raises:
ConfigurationError | juraj-google-style |
def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str='htk') -> Union[float, np.ndarray]:
if mel_scale not in ['slaney', 'htk', 'kaldi']:
raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".')
if mel_scale == 'htk':
return 2595.0 * np.log10(1.0 + freq / 700.0)
e... | Convert frequency from hertz to mels.
Args:
freq (`float` or `np.ndarray`):
The frequency, or multiple frequencies, in hertz (Hz).
mel_scale (`str`, *optional*, defaults to `"htk"`):
The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`.
Returns:
`float` or `np.ndarray`: The frequencies on the mel scale. | github-repos |
def union(df, other, index=False, keep='first'):
validate_set_ops(df, other)
stacked = df.append(other)
if index:
stacked_reset_indexes = stacked.reset_index()
index_cols = [col for col in stacked_reset_indexes.columns if (col not in df.columns)]
index_name = df.index.names
r... | Returns rows that appear in either DataFrame.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): Boolean indicating whether to consider the pandas index
as part of the set operation (default `False`).
k... | codesearchnet |
def calculate_query_times(**kwargs):
return {'total_time_avg': round(numpy.mean(kwargs['total_times']), 1), 'total_time_min': round(numpy.min(kwargs['total_times']), 1), 'total_time_max': round(numpy.max(kwargs['total_times']), 1), 'total_time_85': round(numpy.percentile(kwargs['total_times'], 85), 1), 'execution_t... | Calculates aggregate query times from all iteration times
Kwargs:
total_times(list): List of total time calculations
execution_times(list): List of execution_time calculations
results_iter_times(list): List of results_iter_time calculations
connect_times(list): List of connect_time calculations
Returns:
query_executi... | codesearchnet |
def send_batches(self, batch_list):
if isinstance(batch_list, BaseMessage):
batch_list = batch_list.SerializeToString()
return self._post('/batches', batch_list) | Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict | juraj-google-style |
def _get_user_id(arguments_dict):
if 'user_id' not in arguments_dict:
raise TypeError('Each invocation of a UserTaskMixin subclass must include the user_id')
user_id = arguments_dict['user_id']
try:
get_user_model().objects.get(pk=user_id)
except (ValueError, get_user_model().DoesNo... | Get and validate the `user_id` argument to a task derived from `UserTaskMixin`.
Arguments:
arguments_dict (dict): The parsed positional and keyword arguments to the task
Returns
-------
int: The primary key of a user record (may not be an int if using a custom user model) | juraj-google-style |
def import_certificate(self, certificate_data, bay_number=None):
uri = '{}/https/certificaterequest'.format(self.data['uri'])
if bay_number:
uri += ('?bayNumber=%d' % bay_number)
headers = {'Content-Type': 'application/json'}
return self._helper.do_put(uri, certificate_data, (- 1), headers) | Imports a signed server certificate into the enclosure.
Args:
certificate_data: Dictionary with Signed certificate and type.
bay_number: OA to which the signed certificate will be imported.
Returns:
Enclosure. | codesearchnet |
def add_handler(self, handler):
handler['logger'] = self._get_logger(handler)
handler['reads'] = 0
handler['data_read'] = 0
self.capture_handlers.append(handler) | Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters. | codesearchnet |
def picture_view(request, user_id, year=None):
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
raise Http404
default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")
if user is None:
raise Http404
else:
if... | Displays a view of a user's picture.
Args:
user_id
The ID of the user whose picture is being fetched.
year
The user's picture from this year is fetched. If not
specified, use the preferred picture. | juraj-google-style |
def listFormats(self, vendorSpecific=None):
response = self.listFormatsResponse(vendorSpecific)
return self._read_dataone_type_response(response, 'ObjectFormatList') | See Also: listFormatsResponse()
Args:
vendorSpecific:
Returns: | juraj-google-style |
def is_supported(cls, desc):
for l in cls:
if l.matches(desc):
return True
return False | Determines if the given label descriptor is supported.
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the label descriptor to test
Return:
`True` if desc is supported, otherwise `False` | codesearchnet |
def _get_longest_diag_index(input_matrix):
diags = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dict(input_matrix, input_matrix.nonzero())
diags_values = list(diags.values())
diags_keys = list(diags.keys())
best_diag = np.argmax(diags_values)
diag_start_index = diags_keys[best_dia... | Returns the start index and length of the longest diagonal in the given input.
Args:
input_matrix (numpy.ndarray): The input matrix.
Returns:
tuple: A tuple containing the start index and length of the longest diagonal. | github-repos |
def is_attribute_multivalued(self, attribute):
rule_set = self._attribute_rule_sets.get(attribute)
return rule_set.multiple_instances_permitted | Check if the attribute is allowed to have multiple instances.
Args:
attribute (string): The name of the attribute
(e.g., 'State'). Required. | codesearchnet |
def load_configuration(config_file, config_dir, service_file):
config_files = [config_file]
config = configparser.ConfigParser()
config.read_dict(DEFAULT_OPTIONS)
if (not os.path.isfile(config_file)):
raise ValueError("{f} configuration file either isn't readable or doesn't exist".format(f=confi... | Build configuration objects.
If all sanity checks against daemon and service check settings are passed
then it builds a ConfigParser object which holds all our configuration
and a dictionary data structure which holds Bird configuration per IP
protocol version.
Arguments:
config_file (str): The file name which holds ... | codesearchnet |
def select_by_key(self, key):
self._selected_key = None
self._selected_item = None
for item in self.children.values():
item.attributes['selected'] = False
if key in self.children:
self.children[key].attributes['selected'] = True
self._selecte... | Selects an item by its key.
Args:
key (str): The unique string identifier of the item that have to be selected. | juraj-google-style |
def _process_update(self, item, feed_item):
pass | Handles updates to the creative asset object.
Since creative assets are read only in DCM, there is nothing to do here,
this method is mandatory as it is invoked by the BaseDAO class.
Args:
item: The creative asset DCM object being updated.
feed_item: The feed item representing the creative asset from the
Bulkdozer fe... | github-repos |
def roots_in_unit_interval(coeffs):
all_roots = polynomial.polyroots(coeffs)
all_roots = all_roots[((_UNIT_INTERVAL_WIGGLE_START < all_roots.real) & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END))]
real_inds = (np.abs(all_roots.imag) < _IMAGINARY_WIGGLE)
return all_roots[real_inds].real | r"""Compute roots of a polynomial in the unit interval.
Args:
coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in
monomial / power basis.
Returns:
numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`. | codesearchnet |
def list_resource_groups(access_token, subscription_id):
endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', '?api-version=', RESOURCE_API])
return do_get(endpoint, access_token) | List the resource groups in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. | codesearchnet |
def find_gaps(self, index=False):
return self.__find_incongruities(op=operator.lt, index=index) | Finds gaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog. | codesearchnet |
def inspect_plugin(self, name):
url = self._url('/plugins/{0}/json', name)
return self._result(self._get(url), True) | Retrieve plugin metadata.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
Returns:
A dict containing plugin info | juraj-google-style |
def show(config, section, opt):
if (section not in config.keys()):
raise ConfigError("section '{}' doesn't exist".format(section))
if (opt not in config[section].keys()):
raise ConfigError("option '{}.{}' doesn't exist".format(section, opt))
logger.info(config[section][opt]) | Prints option value from the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name. | codesearchnet |
def _run(self, cmd):
if isinstance(cmd, six.string_types):
cmd = salt.utils.args.shlex_split(cmd)
try:
log.debug(cmd)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p.communicate()
except (OSError, IOError) as exc:
log.deb... | Internal function for running commands. Used by the uninstall function.
Args:
cmd (str, list): The command to run
Returns:
str: The stdout of the command | codesearchnet |
def parse_query_param(url, param):
try:
return parse.parse_qs(parse.urlparse(url).query)[param][0]
except:
return None | Parses the query string of a URL and returns the value of a parameter.
Args:
url: A URL.
param: A string representing the name of the parameter.
Returns:
The value of the parameter. | codesearchnet |
def get_lang_tags(index_page):
dom = dhtmlparser.parseString(index_page)
lang_tags = [get_html_lang_tags(dom), get_dc_lang_tags(dom), [detect_language(dom)], get_html_tag_lang_params(dom)]
return list(sorted(set((SourceString(normalize(lang), source=lang.source) for lang in sum(lang_tags, []))))) | Collect informations about language of the page from HTML and Dublin core
tags and langdetect guesses.
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceString` objects. | codesearchnet |
def resolve(self, name, version, max_id):
if (not isinstance(name, six.text_type)):
raise TypeError(('Name must be a Unicode sequence: %r' % name))
if (not isinstance(version, int)):
raise TypeError(('Version must be an int: %r' % version))
if (version <= 0):
raise ValueError(('Versi... | Resolves the table for a given name and version.
Args:
name (unicode): The name of the table to resolve.
version (int): The version of the table to resolve.
max_id (Optional[int]): The maximum ID of the table requested.
May be ``None`` in which case an exact match on ``name`` and ``version``
is required.
Returns:
Sym... | codesearchnet |
def set_rgb_dim_level_with_time(
self,
channelIndex: int,
rgb: RGBColorState,
dimLevel: float,
onTime: float,
rampTime: float,
):
data = {
"channelIndex": channelIndex,
"deviceId": self.id,
"simpleRGBColorState": rg... | sets the color and dimlevel of the lamp
Args:
channelIndex(int): the channelIndex of the lamp. Use self.topLightChannelIndex or self.bottomLightChannelIndex
rgb(RGBColorState): the color of the lamp
dimLevel(float): the dimLevel of the lamp. 0.0 = off, 1.0 = MAX
onTime(float):
rampTime(float):
Returns:
the result of t... | juraj-google-style |
def incoming(self, messages):
if self._observers:
campfire = self._room.get_campfire()
for message in messages:
for observer in self._observers:
observer(Message(campfire, message)) | Called when incoming messages arrive.
Args:
messages (tuple): Messages (each message is a dict) | juraj-google-style |
def _separable_conv_block(ip, filters, kernel_size=(3, 3), strides=(1, 1), block_id=None):
channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1
with backend.name_scope(f'separable_conv_block_{block_id}'):
x = layers.Activation('relu')(ip)
if strides == (2, 2):
x... | Adds 2 blocks of [relu-separable conv-batchnorm].
Args:
ip: Input tensor
filters: Number of output filters per layer
kernel_size: Kernel size of separable convolutions
strides: Strided convolution for downsampling
block_id: String block_id
Returns:
A Keras tensor | github-repos |
def _transform_binary_composition_to_expression(expression, node, context):
if expression.operator not in constants.SUPPORTED_OPERATORS:
raise NotImplementedError(
u'Filter operation "{}" is not supported by the SQL backend.'.format(
expression.operator))
sql_operator = ... | Transform a BinaryComposition compiler expression into a SQLAlchemy expression.
Recursively calls _expression_to_sql to convert its left and right sub-expressions.
Args:
expression: expression, BinaryComposition compiler expression.
node: SqlNode, the SqlNode the expression applies to.
context: CompilationContext, gl... | juraj-google-style |
def cast(self, value):
if self.type is None:
return value
if self.type in (str, int, float):
try:
return self.type(value)
except Exception as e:
raise errors.BisonError(
'Failed t... | Cast a value to the type required by the option, if one is set.
This is used to cast the string values gathered from environment
variable into their required type.
Args:
value: The value to cast.
Returns:
The value casted to the expected type for the option. | juraj-google-style |
def _convert_appengine_app_assertion_credentials(credentials):
return google.auth.app_engine.Credentials(
scopes=_helpers.string_to_scopes(credentials.scope),
service_account_id=credentials.service_account_id) | Converts to :class:`google.auth.app_engine.Credentials`.
Args:
credentials (oauth2client.contrib.app_engine.AppAssertionCredentials):
The credentials to convert.
Returns:
google.oauth2.service_account.Credentials: The converted credentials. | juraj-google-style |
def exp(array, ty):
weld_obj = WeldObject(encoder_, decoder_)
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
weld_template =
weld_obj.weld_code = weld_template % {"array": array_var, "ty":... | Computes the per-element exponenet of the passed-in array.
Args:
array (WeldObject / Numpy.ndarray): Input array
ty (WeldType): Type of each element in the input array
Returns:
A WeldObject representing this computation | juraj-google-style |
def update_config(self, new_config):
self._assert_not_running()
self._ad.log.info('[LogcatService] Changing config from %s to %s', self._config, new_config)
self._config = new_config | Updates the configuration for the service.
The service needs to be stopped before updating, and explicitly started
after the update.
This will reset the service. Previous output files may be orphaned if
output path is changed.
Args:
new_config: Config, the new config to use. | github-repos |
def get_language(self, text):
files = {'text': text}
res, status_code = self.post(self.language_service, files=files)
if status_code != 200:
logger.debug('Language recognition failed.')
return self.decode(res), status_code | Recognise the language of the text in input
Args:
id (str): The text whose the language needs to be recognised
Returns:
dict, int: A dict containing the recognised language and the
confidence score. | juraj-google-style |
def get_arrhenius_plot(temps, diffusivities, diffusivity_errors=None, **kwargs):
(Ea, c, _) = fit_arrhenius(temps, diffusivities)
from pymatgen.util.plotting import pretty_plot
plt = pretty_plot(12, 8)
arr = (c * np.exp(((- Ea) / ((const.k / const.e) * np.array(temps)))))
t_1 = (1000 / np.array(temp... | Returns an Arrhenius plot.
Args:
temps ([float]): A sequence of temperatures.
diffusivities ([float]): A sequence of diffusivities (e.g.,
from DiffusionAnalyzer.diffusivity).
diffusivity_errors ([float]): A sequence of errors for the
diffusivities. If None, no error bar is plotted.
\\*\\*kwargs:
Any keyword args suppo... | codesearchnet |
def build_input(data, batch_size, dataset, train):
image_size = 32
depth = 3
num_classes = (10 if (dataset == 'cifar10') else 100)
(images, labels) = data
num_samples = (images.shape[0] - (images.shape[0] % batch_size))
dataset = tf.contrib.data.Dataset.from_tensor_slices((images[:num_samples], ... | Build CIFAR image and labels.
Args:
data_path: Filename for cifar10 data.
batch_size: Input batch size.
train: True if we are training and false if we are testing.
Returns:
images: Batches of images of size
[batch_size, image_size, image_size, 3].
labels: Batches of labels of size [batch_size, num_classes].
Raises:
... | codesearchnet |
def get_reachable_ports(self, id_or_uri, start=0, count=(- 1), filter='', query='', sort='', networks=[]):
uri = (self._client.build_uri(id_or_uri) + '/reachable-ports')
if networks:
elements = "'"
for n in networks:
elements += (n + ',')
elements = (elements[:(- 1)] + "'")
... | Gets the storage ports that are connected on the specified networks
based on the storage system port's expected network connectivity.
Returns:
list: Reachable Storage Port List. | codesearchnet |
def params(self, params):
url = furl(self._request.rawurl)
url = url.add(params)
self._request.url = url.url
self.add_matcher(matcher('QueryMatcher', params)) | Defines a set of URL query params to match.
Arguments:
params (dict): set of params to match.
Returns:
self: current Mock instance. | juraj-google-style |
def save_metrics(self, split, metrics, combined=True):
if not self.is_world_process_zero():
return
path = os.path.join(self.args.output_dir, f'{split}_results.json')
with open(path, 'w') as f:
json.dump(metrics, f, indent=4, sort_keys=True)
if combined:
path = os.path.join(self.a... | Save metrics into a json file for that split, e.g. `train_results.json`.
Under distributed environment this is done only for a process with rank 0.
Args:
split (`str`):
Mode/split name: one of `train`, `eval`, `test`, `all`
metrics (`Dict[str, float]`):
The metrics returned from train/evaluate/predict
combined (`bool... | github-repos |
def __init__(self, xid=None, role=None, generation_id=None):
super().__init__(xid, role, generation_id)
self.header.message_type = Type.OFPT_ROLE_REQUEST | Create a RoleRequest with the optional parameters below.
Args:
xid (int): OpenFlow xid to the header.
role (:class:`~.controller2switch.common.ControllerRole`):
Is the new role that the controller wants to assume.
generation_id (int): Master Election Generation Id. | juraj-google-style |
def get_parent_of_type(typ, obj):
if (type(typ) is not text):
typ = typ.__name__
while hasattr(obj, 'parent'):
obj = obj.parent
if (obj.__class__.__name__ == typ):
return obj | Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object which is the start of the
search process. | codesearchnet |
def has_unchecked_field(self, locator, **kwargs):
kwargs['checked'] = False
return self.has_selector('field', locator, **kwargs) | Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
bool: Whether it exists. | codesearchnet |
def _ParseLogLine(self, parser_mediator, structure):
try:
date_time = dfdatetime_time_elements.TimeElements(time_elements_tuple=structure.date_time)
date_time.is_local_time = True
except ValueError:
parser_mediator.ProduceExtractionWarning('invalid date time value: {0!s}'.format(structur... | Parse a single log line and and produce an event object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file. | codesearchnet |
def get_max_size(pool, num_option, item_length):
max_items = POOL_SIZE / item_length
existing = POOL_OPTION_MIN_SIZE * num_option + sum([max(0, len(pool.get(i, {})) - 5) for i in xrange(num_option)])
return int(max_items - existing) | Calculate the max number of item that an option can stored in the pool at give time.
This is to limit the pool size to POOL_SIZE
Args:
option_index (int): the index of the option to calculate the size for
pool (dict): answer pool
num_option (int): total number of options available for the question
item_length (int): ... | juraj-google-style |
def pyrdf2(value, class_type=None, datatype=None, lang=None, **kwargs):
try:
if isinstance(value, dict):
if value.get('type') == "literal":
if not value.get("datatype"):
return XsdString(value['value'])
... | Coverts an input to one of the rdfdatatypes classes
Args:
value: any rdfdatatype, json dict or vlaue
class_type: "literal", "uri" or "blanknode"
datatype: "xsd:string", "xsd:int" , etc | juraj-google-style |
def configure(cls, api_token, api_url='https:
cls._auth = QuboleAuth(api_token)
cls.api_token = api_token
cls.version = version
cls.baseurl = api_url
if (poll_interval < Qubole.MIN_POLL_INTERVAL):
log.warn(('Poll interval cannot be less than %s seconds. Setting it to %s seconds.\n' % (Qubole... | Set parameters governing interaction with QDS
Args:
`api_token`: authorization token for QDS. required
`api_url`: the base URL for QDS API. configurable for testing only
`version`: QDS REST api version. Will be used throughout unless overridden in Qubole.agent(..)
`poll_interval`: interval in secs when polling QDS ... | codesearchnet |
def FindUnspentCoins(self, from_addr=None, use_standard=False, watch_only_val=0):
ret = []
for coin in self.GetCoins():
if (((coin.State & CoinState.Confirmed) > 0) and ((coin.State & CoinState.Spent) == 0) and ((coin.State & CoinState.Locked) == 0) and ((coin.State & CoinState.Frozen) == 0) and ((coin.... | Finds unspent coin objects in the wallet.
Args:
from_addr (UInt160): a bytearray (len 20) representing an address.
use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).
watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watc... | codesearchnet |
def saveAsTFRecords(df, output_dir):
tf_rdd = df.rdd.mapPartitions(toTFExample(df.dtypes))
tf_rdd.saveAsNewAPIHadoopFile(output_dir, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat",
keyClass="org.apache.hadoop.io.BytesWritable",
valueClass="org.... | Save a Spark DataFrame as TFRecords.
This will convert the DataFrame rows to TFRecords prior to saving.
Args:
:df: Spark DataFrame
:output_dir: Path to save TFRecords | juraj-google-style |
def run(self):
with util.timed_block() as t:
files = self._collect_files()
log.info('Collected <33>{} <32>files in <33>{}s'.format(len(files), t.elapsed_s))
if self.verbose:
for p in files:
log.info(' <0>{}', p)
if (not files):
return self.allow_empty
with util.t... | Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise. | codesearchnet |
def starts_with(self, prefix):
prefix = prefix.lower()
found_words = []
res = cgaddag.gdg_starts_with(self.gdg, prefix.encode(encoding="ascii"))
tmp = res
while tmp:
word = tmp.contents.str.decode("ascii")
found_words.append(word)
tm... | Find all words starting with a prefix.
Args:
prefix: A prefix to be searched for.
Returns:
A list of all words found. | juraj-google-style |
def _DeserializeAttributeContainer(self, container_type, serialized_data):
if not serialized_data:
return None
if self._serializers_profiler:
self._serializers_profiler.StartTiming(container_type)
try:
serialized_string = serialized_data.decode('utf-8')
except UnicodeDecodeError... | Deserializes an attribute container.
Args:
container_type (str): attribute container type.
serialized_data (bytes): serialized attribute container data.
Returns:
AttributeContainer: attribute container or None.
Raises:
IOError: if the serialized data cannot be decoded.
OSError: if the serialized data cannot be decod... | juraj-google-style |
def __init__(self, pqc: cirq.Circuit, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform(0, 2), name: Union[None, str]=None):
raw_symbol_names = list(sorted(tfq.util.get_circuit_symbols(pqc)))
symbol_names = tf.constant([str(x) for x in raw_symbol_names], dtype=tf.string)
val... | Initializes a DirectQuantumCircuit.
Args:
pqc: Representation of a parameterized quantum circuit.
initializer: A `tf.keras.initializers.Initializer` which specifies how to
initialize the values of the parameters in `circuit`. The default
initializer assumes parameters of gates are exponents, so that one full
period i... | github-repos |
def get_rml(self, rml_def, **kwargs):
if isinstance(rml_def, str):
rml_procs = self.es_defs.get("kds_esRmlProcessor", [])
for item in rml_procs:
if item['name'] == rml_def:
rml_def = item
break
proc_kwargs = {rml_de... | returns the rml mapping output for specified mapping
Args:
-----
rml_def: The name of the mapping or a dictionary definition | juraj-google-style |
def get_text_features(self, input_ids=None, attention_mask=None, position_ids=None, token_type_ids=None, output_attentions=None, output_hidden_states=None, return_dict=None):
text_outputs = self.text_model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, token_type_ids=token_type_ids, ... | Returns:
text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
the projection layer to the pooled output of [`TFCLIPTextModel`].
Examples:
```python
>>> from transformers import TFVisionTextDualEncoderModel, AutoTokenizer
>>> model = TFVisionTextDualEncoderModel.fro... | github-repos |
def delete(self, resource, force=False, export_only=None, suppress_device_updates=None, timeout=(- 1)):
custom_headers = {'If-Match': '*'}
if ('uri' in resource):
uri = resource['uri']
else:
uri = self._client.build_uri(resource)
if suppress_device_updates:
uri += '?suppressDevic... | Deletes a managed volume.
Args:
resource (dict):
Object to delete.
force:
If set to true, the operation completes despite any problems with
network connectivity or errors on the resource itself. The default is false.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the opera... | codesearchnet |
def _dataset_partition(self, mode, config, params):
if mode != tf.estimator.ModeKeys.TRAIN or not hasattr(config, "tpu_config"):
self._next_partition_id = 0
return 0, 1
phift = config.tpu_config.per_host_input_for_training
if (hasattr(tpu_config.InputPipelineConfig, "BROADCAST")... | Which part of the training data to read.
If there are multiple parallel calls to input_fn (multiple TPU hosts),
then we want each one to read from a separate partition of the training
data.
Args:
mode: tf.estimator.ModeKeys
config: RunConfig
params: A dict that contains parameters.
Returns:
partition_id: an integer
n... | juraj-google-style |
def __init__(self, debug=False):
facility = logging.handlers.SysLogHandler.LOG_DAEMON
self.logger = logger.Logger(
name='google-clock-skew', debug=debug, facility=facility)
self.distro_utils = distro_utils.Utils(debug=debug)
self.watcher = metadata_watcher.MetadataWatcher(logger=self.logger... | Constructor.
Args:
debug: bool, True if debug output should write to the console. | juraj-google-style |
def add_user_role(self, user, role):
self.project_service.set_auth(self._token_project)
self.project_service.add_user_role(user, role) | Add role to given user.
Args:
user (string): User name.
role (string): Role to assign.
Raises:
requests.HTTPError on failure. | juraj-google-style |
def getDelOps(self, buid):
return (
('prop:del', (buid, self.form.name, self.name, self.storinfo)),
) | Get a list of storage operations to delete this property from the buid.
Args:
buid (bytes): The node buid.
Returns:
(tuple): The storage operations | juraj-google-style |
def set_description(self, name, value=None, default=False, disable=False):
string = 'description'
commands = self.command_builder(string, value=value, default=default, disable=disable)
return self.configure_interface(name, commands) | Configures the interface description
EosVersion:
4.13.7M
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (string): The value to set the description to.
default (boolean): Specifies to default the interface description
disable (boolean): Specifies to negate ... | codesearchnet |
def GetName(self, number):
value = self._data_type_definition.values_per_number.get(number, None)
if (not value):
return None
return value.name | Retrieves the name of an enumeration value by number.
Args:
number (int): number.
Returns:
str: name of the enumeration value or None if no corresponding
enumeration value was found. | codesearchnet |
def ignore_errors(log_warning=False):
def _apply_fn(dataset):
return dataset.ignore_errors(log_warning)
return _apply_fn | Creates a `Dataset` from another `Dataset` and silently ignores any errors.
Use this transformation to produce a dataset that contains the same elements
as the input, but silently drops any elements that caused an error. For
example:
```python
dataset = tf.data.Dataset.from_tensor_slices([1., 2., 0., 4.])
# Computin... | github-repos |
def timezone(self, timezone=0):
tz_dt = timedelta(hours=timezone)
for segment in self.segments:
for point in segment.points:
point.time = point.time + tz_dt
return self | Sets the timezone of the entire track
Args:
timezone (int): Timezone hour delta | juraj-google-style |
def period_start_day(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError('value {} need to be of type str '
'for field `period_start_day`'.format(value))
... | Corresponds to IDD Field `period_start_day`
Args:
value (str): value for IDD Field `period_start_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.