sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def create(self, name, plugin_name, hadoop_version, description=None,
cluster_configs=None, node_groups=None, anti_affinity=None,
net_id=None, default_image_id=None, use_autoconfig=None,
shares=None, is_public=None, is_protected=None,
domain_name=None):
... | Create a Cluster Template. | entailment |
def update(self, cluster_template_id, name=NotUpdated,
plugin_name=NotUpdated, plugin_version=NotUpdated,
description=NotUpdated, cluster_configs=NotUpdated,
node_groups=NotUpdated, anti_affinity=NotUpdated,
net_id=NotUpdated, default_image_id=NotUpdated,
... | Update a Cluster Template. | entailment |
def get(self, cluster_id, show_progress=False):
"""Get information about a Cluster."""
url = ('/clusters/%(cluster_id)s?%(params)s' %
{"cluster_id": cluster_id,
"params": parse.urlencode({"show_progress": show_progress})})
return self._get(url, 'cluster') | Get information about a Cluster. | entailment |
def update(self, cluster_id, name=NotUpdated, description=NotUpdated,
is_public=NotUpdated, is_protected=NotUpdated,
shares=NotUpdated):
"""Update a Cluster."""
data = {}
self._copy_if_updated(data, name=name, description=description,
... | Update a Cluster. | entailment |
def verification_update(self, cluster_id, status):
"""Start a verification for a Cluster."""
data = {'verification': {'status': status}}
return self._patch("/clusters/%s" % cluster_id, data) | Start a verification for a Cluster. | entailment |
def create(self, name, plugin_name, plugin_version,
cluster_template_id=None, default_image_id=None,
is_transient=None, description=None, cluster_configs=None,
node_groups=None, user_keypair_id=None,
anti_affinity=None, net_id=None, count=None,
... | Launch a Cluster. | entailment |
def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
... | Associates each command class with command depending on setup.cfg | entailment |
def get_json(response):
"""Provide backward compatibility with old versions of requests library."""
json_field_or_function = getattr(response, 'json', None)
if callable(json_field_or_function):
return response.json()
else:
return jsonutils.loads(response.content) | Provide backward compatibility with old versions of requests library. | entailment |
def create(self, name, data):
"""Create a Job Binary Internal.
:param str data: raw data of script text
"""
return self._update('/job-binary-internals/%s' %
urlparse.quote(name.encode('utf-8')), data,
'job_binary_internal', dump_js... | Create a Job Binary Internal.
:param str data: raw data of script text | entailment |
def update(self, job_binary_id, name=NotUpdated, is_public=NotUpdated,
is_protected=NotUpdated):
"""Update a Job Binary Internal."""
data = {}
self._copy_if_updated(data, name=name, is_public=is_public,
is_protected=is_protected)
return self... | Update a Job Binary Internal. | entailment |
def autoconvert(string):
"""Try to convert variables into datatypes."""
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string | Try to convert variables into datatypes. | entailment |
def call_plugin(plugin, f, *args, **kwargs):
"""Calls function f from plugin, returns None if plugin does not implement f."""
try:
getattr(plugin, f)
except AttributeError:
return None
if kwargs:
getattr(plugin, f)(
*args,
**kwargs
)
else:
... | Calls function f from plugin, returns None if plugin does not implement f. | entailment |
def create(self, job_id, cluster_id, input_id=None,
output_id=None, configs=None, interface=None, is_public=None,
is_protected=None):
"""Launch a Job."""
url = "/jobs/%s/execute" % job_id
data = {
"cluster_id": cluster_id,
}
self._copy_... | Launch a Job. | entailment |
def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job Execution."""
data = {}
self._copy_if_updated(data, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-executions/%s' % obj_id, data) | Update a Job Execution. | entailment |
def visitTerminal(self, ctx):
"""Converts case insensitive keywords and identifiers to lowercase
Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers,
to prevent lowercasing quoted values.
"""
text = str(super().visitTerm... | Converts case insensitive keywords and identifiers to lowercase
Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers,
to prevent lowercasing quoted values. | entailment |
def list(self, search_opts=None):
"""Get a list of Plugins."""
query = base.get_query_string(search_opts)
return self._list('/plugins%s' % query, 'plugins') | Get a list of Plugins. | entailment |
def convert_to_cluster_template(self, plugin_name, hadoop_version,
template_name, filecontent):
"""Convert to cluster template
Create Cluster Template directly, avoiding Cluster Template
mechanism.
"""
resp = self.api.post('/plugins/%s/%s/conv... | Convert to cluster template
Create Cluster Template directly, avoiding Cluster Template
mechanism. | entailment |
def create(self, name, type, mains=None, libs=None, description=None,
interface=None, is_public=None, is_protected=None):
"""Create a Job."""
data = {
'name': name,
'type': type
}
self._copy_if_defined(data, description=description, mains=mains,
... | Create a Job. | entailment |
def list(self, search_opts=None, limit=None,
marker=None, sort_by=None, reverse=None):
"""Get a list of Jobs."""
query = base.get_query_string(search_opts, limit=limit, marker=marker,
sort_by=sort_by, reverse=reverse)
url = "/jobs%s" % query
... | Get a list of Jobs. | entailment |
def update(self, job_id, name=NotUpdated, description=NotUpdated,
is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job."""
data = {}
self._copy_if_updated(data, name=name, description=description,
is_public=is_public, is_protected=is_prote... | Update a Job. | entailment |
def _query_for_reverse_geocoding(lat, lng):
"""
Given a lat & lng, what's the string search query.
If the API changes, change this function. Only for internal use.
"""
# have to do some stupid f/Decimal/str stuff to (a) ensure we get as much
# decimal places as the user already specified and (b... | Given a lat & lng, what's the string search query.
If the API changes, change this function. Only for internal use. | entailment |
def floatify_latlng(input_value):
"""
Work around a JSON dict with string, not float, lat/lngs.
Given anything (list/dict/etc) it will return that thing again, *but* any
dict (at any level) that has only 2 elements lat & lng, will be replaced
with the lat & lng turned into floats.
If the API r... | Work around a JSON dict with string, not float, lat/lngs.
Given anything (list/dict/etc) it will return that thing again, *but* any
dict (at any level) that has only 2 elements lat & lng, will be replaced
with the lat & lng turned into floats.
If the API returns the lat/lng as strings, and not numbers... | entailment |
def geocode(self, query, **kwargs):
"""
Given a string to search for, return the results from OpenCage's Geocoder.
:param string query: String to search for
:returns: Dict results
:raises InvalidInputError: if the query string is not a unicode string
:raises RateLimitEx... | Given a string to search for, return the results from OpenCage's Geocoder.
:param string query: String to search for
:returns: Dict results
:raises InvalidInputError: if the query string is not a unicode string
:raises RateLimitExceededError: if you have exceeded the number of queries ... | entailment |
def reverse_geocode(self, lat, lng, **kwargs):
"""
Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: ... | Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception ... | entailment |
def acquire(self):
'''
Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and `block=True`,
this method may block until a connec... | Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and `block=True`,
this method may block until a connection is available in the pool. | entailment |
def release(self, connection):
'''
Return a connection back to the pool.
Prior to release, :py:meth:`ctds.Connection.rollback()` is called to
rollback any pending transaction.
.. note:: This must be called once for every successful call to
:py:meth:`.acquire()`.
... | Return a connection back to the pool.
Prior to release, :py:meth:`ctds.Connection.rollback()` is called to
rollback any pending transaction.
.. note:: This must be called once for every successful call to
:py:meth:`.acquire()`.
:param connection: The connection object retu... | entailment |
def finalize(self):
'''
Release all connections contained in the pool.
.. note:: This should be called to cleanly shutdown the pool, i.e.
on process exit.
'''
self._condition.acquire()
try:
if self._nconnections != len(self._pool):
... | Release all connections contained in the pool.
.. note:: This should be called to cleanly shutdown the pool, i.e.
on process exit. | entailment |
def _dict_merge(dct, merge_dct):
"""Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/b... | Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
Arguments:
... | entailment |
def _parse_schema(schema, method):
"""
Convert a Schema Object to a Python object.
Args:
schema: An ``OrderedDict`` representing the schema object.
"""
if method and schema.get('readOnly', False):
return _READONLY_PROPERTY
# allOf: Must be valid against all of the subschemas
... | Convert a Schema Object to a Python object.
Args:
schema: An ``OrderedDict`` representing the schema object. | entailment |
def _example(media_type_objects, method=None, endpoint=None, status=None,
nb_indent=0):
"""
Format examples in `Media Type Object` openapi v3 to HTTP request or
HTTP response example.
If method and endpoint is provided, this fonction prints a request example
else status should be provid... | Format examples in `Media Type Object` openapi v3 to HTTP request or
HTTP response example.
If method and endpoint is provided, this fonction prints a request example
else status should be provided to print a response example.
Arguments:
media_type_objects (Dict[str, Dict]): Dict containing
... | entailment |
def _resolve_refs(uri, spec):
"""Resolve JSON references in a given dictionary.
OpenAPI spec may contain JSON references to its nodes or external
sources, so any attempt to rely that there's some expected attribute
in the spec may fail. So we need to resolve JSON references before
we use it (i.e. r... | Resolve JSON references in a given dictionary.
OpenAPI spec may contain JSON references to its nodes or external
sources, so any attempt to rely that there's some expected attribute
in the spec may fail. So we need to resolve JSON references before
we use it (i.e. replace with referenced object). For d... | entailment |
def convert_double_to_two_registers(doubleValue):
"""
Convert 32 Bit Value to two 16 Bit Value to send as Modbus Registers
doubleValue: Value to be converted
return: 16 Bit Register values int[]
"""
myList = list()
myList.append(int(doubleValue & 0x0000FFFF)) #Append Least Signific... | Convert 32 Bit Value to two 16 Bit Value to send as Modbus Registers
doubleValue: Value to be converted
return: 16 Bit Register values int[] | entailment |
def convert_float_to_two_registers(floatValue):
"""
Convert 32 Bit real Value to two 16 Bit Value to send as Modbus Registers
floatValue: Value to be converted
return: 16 Bit Register values int[]
"""
myList = list()
s = bytearray(struct.pack('<f', floatValue) ) #little endian
myL... | Convert 32 Bit real Value to two 16 Bit Value to send as Modbus Registers
floatValue: Value to be converted
return: 16 Bit Register values int[] | entailment |
def convert_registers_to_float(registers):
"""
Convert two 16 Bit Registers to 32 Bit real value - Used to receive float values from Modbus (Modbus Registers are 16 Bit long)
registers: 16 Bit Registers
return: 32 bit value real
"""
b = bytearray(4)
b [0] = registers[0] & 0xff
b [1] = ... | Convert two 16 Bit Registers to 32 Bit real value - Used to receive float values from Modbus (Modbus Registers are 16 Bit long)
registers: 16 Bit Registers
return: 32 bit value real | entailment |
def connect(self):
"""
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
"""
if (self.__ser is not None):
serial = importlib.import_module("serial")
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ON... | Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters | entailment |
def close(self):
"""
Closes Serial port, or TCP-Socket connection
"""
if (self.__ser is not None):
self.__ser.close()
if (self.__tcpClientSocket is not None):
self.__stoplistening = True
self.__tcpClientSocket.shutdown(socket.SHUT_RDWR)
... | Closes Serial port, or TCP-Socket connection | entailment |
def read_discreteinputs(self, starting_address, quantity):
"""
Read Discrete Inputs from Master device (Function code 2)
starting_address: First discrete input to be read
quantity: Numer of discrete Inputs to be read
returns: Boolean Array [0..quantity-1] which contains the discr... | Read Discrete Inputs from Master device (Function code 2)
starting_address: First discrete input to be read
quantity: Numer of discrete Inputs to be read
returns: Boolean Array [0..quantity-1] which contains the discrete Inputs | entailment |
def write_single_coil(self, starting_address, value):
"""
Write single Coil to Master device (Function code 5)
starting_address: Coil to be written
value: Coil Value to be written
"""
self.__transactionIdentifier+=1
if (self.__ser is not None):
if (se... | Write single Coil to Master device (Function code 5)
starting_address: Coil to be written
value: Coil Value to be written | entailment |
def write_multiple_coils(self, starting_address, values):
"""
Write multiple coils to Master device (Function code 15)
starting_address : First coil to be written
values: Coil Values [0..quantity-1] to be written
"""
self.__transactionIdentifier+=1
if (self.__se... | Write multiple coils to Master device (Function code 15)
starting_address : First coil to be written
values: Coil Values [0..quantity-1] to be written | entailment |
def services(self, service_group=None):
"""
Args:
service_group: optional name of service group
Returns:
if service_group is omitted or None, flattened dict of all service records in the service registry
if service_group is present, dict of service records in that group
"""
# Speci... | Args:
service_group: optional name of service group
Returns:
if service_group is omitted or None, flattened dict of all service records in the service registry
if service_group is present, dict of service records in that group | entailment |
def iter_services(self, service_group=None):
"""
Args:
service_group: optional name of service group
Returns:
if service_group is omitted or None, an Iterator over all flattened service records in the service registry
if service_group is present, an Iterator over all service records in tha... | Args:
service_group: optional name of service group
Returns:
if service_group is omitted or None, an Iterator over all flattened service records in the service registry
if service_group is present, an Iterator over all service records in that group | entailment |
def valid_envs(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
a list of strings - all the valid environments for 'service'
Raises:
RuntimeError if the service wasn't found
"""
service_record = self.service_record(service_na... | Args:
service_name: the name of the service in the service registry
Returns:
a list of strings - all the valid environments for 'service'
Raises:
RuntimeError if the service wasn't found | entailment |
def service_record(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
the entire service record from the service registry or None if the record was not found
"""
if not self.services().has_key(service_name):
return None
return ... | Args:
service_name: the name of the service in the service registry
Returns:
the entire service record from the service registry or None if the record was not found | entailment |
def service_group(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
the name of the group the service is in, or None of the service was not found
"""
for group in EFConfig.SERVICE_GROUPS:
if self.services(group).has_key(service_na... | Args:
service_name: the name of the service in the service registry
Returns:
the name of the group the service is in, or None of the service was not found | entailment |
def service_region(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
the region the service is in, or EFConfig.DEFAULT_REGION if the region was not found
"""
if not self.services()[service_name].has_key("region"):
return EFConfig.... | Args:
service_name: the name of the service in the service registry
Returns:
the region the service is in, or EFConfig.DEFAULT_REGION if the region was not found | entailment |
def easy_train_and_evaluate(hyper_params, Model=None, create_loss=None,
training_data=None, validation_data=None,
inline_plotting=False, session_config=None, log_suffix=None,
continue_training=False, continue_with_specific_checkpointpa... | Train and evaluate your model without any boilerplate code.
1) Write your data using the starttf.tfrecords.autorecords.write_data method.
2) Create your hyper parameter file containing all required fields and then load it using
starttf.utils.hyper_params.load_params method.
Minimal Sample Hyper... | entailment |
def create_prediction_estimator(hyper_params, model, checkpoint_path=None):
"""
Create an estimator for prediction purpose only.
:param hyper_params: The hyper params file.
:param model: The keras model.
:param checkpoint_path: (Optional) Path to the specific checkpoint to use.
:return:
"""
... | Create an estimator for prediction purpose only.
:param hyper_params: The hyper params file.
:param model: The keras model.
:param checkpoint_path: (Optional) Path to the specific checkpoint to use.
:return: | entailment |
def ef_plugin(service_name):
"""
Decorator for ef plugin classes. Any wrapped classes should contain a run() method which executes the plugin code.
Args:
service_name (str): The name of the service being extended.
Example:
@ef_plugin('ef-generate')
class NewRelicPlugin(object):
def run(self... | Decorator for ef plugin classes. Any wrapped classes should contain a run() method which executes the plugin code.
Args:
service_name (str): The name of the service being extended.
Example:
@ef_plugin('ef-generate')
class NewRelicPlugin(object):
def run(self):
exec_code() | entailment |
def run_plugins(context_obj, boto3_clients):
"""
Executes all loaded plugins designated for the service calling the function.
Args:
context_obj (obj:EFContext): The EFContext object created by the service.
boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients()
"""
... | Executes all loaded plugins designated for the service calling the function.
Args:
context_obj (obj:EFContext): The EFContext object created by the service.
boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients() | entailment |
def easy_train_and_evaluate(hyper_params, Model=None, define_loss_fn=None,
training_data=None, validation_data=None,
continue_training=False,
session_config=None, log_suffix=None, continue_with_specific_checkpointpath=None):
"""
... | Train and evaluate your model without any boilerplate code.
1) Write your data using the starttf.tfrecords.autorecords.write_data method.
2) Create your hyper parameter file containing all required fields and then load it using
starttf.utils.hyper_params.load_params method.
Minimal Sample Hyper... | entailment |
def crop(img, start_y, start_x, h, w):
"""
Crop an image given the top left corner.
:param img: The image
:param start_y: The top left corner y coord
:param start_x: The top left corner x coord
:param h: The result height
:param w: The result width
:return: The cropped image.
"""
... | Crop an image given the top left corner.
:param img: The image
:param start_y: The top left corner y coord
:param start_x: The top left corner x coord
:param h: The result height
:param w: The result width
:return: The cropped image. | entailment |
def resize_image_with_crop_or_pad(img, target_height, target_width):
"""
Crops and/or pads an image to a target width and height.
Resizes an image to a target width and height by either cropping the image or padding it with zeros.
NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom r... | Crops and/or pads an image to a target width and height.
Resizes an image to a target width and height by either cropping the image or padding it with zeros.
NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right)
:param img: Numpy array representing the image.
:param target_heig... | entailment |
def _rotatedRectWithMaxArea(w, h, angle):
"""
Given a rectangle of size wxh that has been rotated by 'angle' (in
radians), computes the width and height of the largest possible
axis-aligned rectangle (maximal area) within the rotated rectangle.
Answer from: https://stackoverflow.com/questions/16702966/rotate... | Given a rectangle of size wxh that has been rotated by 'angle' (in
radians), computes the width and height of the largest possible
axis-aligned rectangle (maximal area) within the rotated rectangle.
Answer from: https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders | entailment |
def rotate_img_and_crop(img, angle):
"""
Rotate an image and then crop it so that there is no black area.
:param img: The image to rotate.
:param angle: The rotation angle in degrees.
:return: The rotated and cropped image.
"""
h, w, _ = img.shape
img = scipy.ndimage.interpolation.rotate... | Rotate an image and then crop it so that there is no black area.
:param img: The image to rotate.
:param angle: The rotation angle in degrees.
:return: The rotated and cropped image. | entailment |
def diff_string_templates(string_a, string_b):
"""
Determine the diff of two strings. Return an empty string if the strings
are identical, and the diff output string if they are not.
"""
s1 = string_a.strip().splitlines()
s2 = string_b.strip().splitlines()
diffs = unified_diff(s2, s1, fromf... | Determine the diff of two strings. Return an empty string if the strings
are identical, and the diff output string if they are not. | entailment |
def render_local_template(service_name, environment, repo_root, template_file):
"""
Render a given service's template for a given environment and return it
"""
cmd = 'cd {} && ef-cf {} {} --devel --verbose'.format(repo_root, template_file, environment)
p = subprocess.Popen(cmd, shell=True, stdout=su... | Render a given service's template for a given environment and return it | entailment |
def fetch_current_cloudformation_template(service_name, environment, cf_client):
"""
Fetch the currently-deployed template for the given service in the given
environment and return it.
"""
stack_name = get_stack_name(environment, service_name)
logger.debug('Fetching template for `%s`', stack_nam... | Fetch the currently-deployed template for the given service in the given
environment and return it. | entailment |
def diff_sevice_by_text(service_name, service, environment, cf_client, repo_root):
"""
Render the local template and compare it to the template that was last
applied in the target environment.
"""
global ret_code
logger.info('Investigating textual diff for `%s`:`%s` in environment `%s`',
... | Render the local template and compare it to the template that was last
applied in the target environment. | entailment |
def diff_sevice_by_changeset(service_name, service, environment, cf_client, repo_root):
"""
If an ef-cf call fails, the error will be logged, the retcode set to 2, but
the function will run to completion and return the list of non-error
results.
"""
global ret_code
logger.info('Investigatin... | If an ef-cf call fails, the error will be logged, the retcode set to 2, but
the function will run to completion and return the list of non-error
results. | entailment |
def get_cloudformation_client(service_name, environment_name):
"""
Given a service name and an environment name, return a boto CloudFormation
client object.
"""
region = service_registry.service_region(service_name)
if whereami() == 'ec2':
profile = None
else:
profile = get_... | Given a service name and an environment name, return a boto CloudFormation
client object. | entailment |
def evaluate_service_changes(services, envs, repo_root, func):
"""
Given a dict of services, and a list of environments, apply the diff
function to evaluate the differences between the target environments
and the rendered templates.
Sub-services (names with '.' in them) are skipped.
"""
for... | Given a dict of services, and a list of environments, apply the diff
function to evaluate the differences between the target environments
and the rendered templates.
Sub-services (names with '.' in them) are skipped. | entailment |
def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_na... | Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file. | entailment |
def get_dict_registry_services(registry, template_files, warn_missing_files=True):
"""
Return a dict mapping service name to a dict containing the service's
type ('fixtures', 'platform_services', 'application_services', 'internal_services'),
the template file's absolute path, and a list of environments ... | Return a dict mapping service name to a dict containing the service's
type ('fixtures', 'platform_services', 'application_services', 'internal_services'),
the template file's absolute path, and a list of environments to which the
service is intended to deploy.
Service names that appear twice in the out... | entailment |
def scan_dir_for_template_files(search_dir):
"""
Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services.
"""
template_files = {}
cf_dir = os.path.join(search_dir, 'cloudformation')
for type in os.listdir(cf_dir):
... | Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services. | entailment |
def generate_secret(length=32):
"""
Generate a random secret consisting of mixed-case letters and numbers
Args:
length (int): Length of the generated password
Returns:
a randomly generated secret string
Raises:
None
"""
alphabet = string.ascii_letters + string.digits
random_bytes = os.... | Generate a random secret consisting of mixed-case letters and numbers
Args:
length (int): Length of the generated password
Returns:
a randomly generated secret string
Raises:
None | entailment |
def generate_secret_file(file_path, pattern, service, environment, clients):
"""
Generate a parameter files with it's secrets encrypted in KMS
Args:
file_path (string): Path to the parameter file to be encrypted
pattern (string): Pattern to do fuzzy string matching
service (string): Service to u... | Generate a parameter files with it's secrets encrypted in KMS
Args:
file_path (string): Path to the parameter file to be encrypted
pattern (string): Pattern to do fuzzy string matching
service (string): Service to use KMS key to encrypt file
environment (string): Environment to encrypt values
... | entailment |
def handle_args_and_set_context(args):
"""
Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFPWContext object
Raises:
RuntimeError: if repo or branch isn't as spec'd in ef_config.EF_REPO and ef_config.EF_REPO_BRANCH
ValueError: if a par... | Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFPWContext object
Raises:
RuntimeError: if repo or branch isn't as spec'd in ef_config.EF_REPO and ef_config.EF_REPO_BRANCH
ValueError: if a parameter is invalid | entailment |
def tile_2d(input, k_x, k_y, name, reorder_required=True):
"""
A tiling layer like introduced in overfeat and huval papers.
:param input: Your input tensor.
:param k_x: The tiling factor in x direction.
:param k_y: The tiling factor in y direction.
:param name: The name of the layer.
:param ... | A tiling layer like introduced in overfeat and huval papers.
:param input: Your input tensor.
:param k_x: The tiling factor in x direction.
:param k_y: The tiling factor in y direction.
:param name: The name of the layer.
:param reorder_required: To implement an exact huval tiling you need reorderin... | entailment |
def inverse_tile_2d(input, k_x, k_y, name):
"""
An inverse tiling layer.
An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,
but harness the benefits of the resolution of a higher level feature layer.
If you insist on a source yo... | An inverse tiling layer.
An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,
but harness the benefits of the resolution of a higher level feature layer.
If you insist on a source you can call it very lightly inspired by yolo9000 "passthrough... | entailment |
def feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
A feature passthrough layer inspired by yolo9000 and the inverse tiling layer.
It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)).
This layer has no activation functi... | A feature passthrough layer inspired by yolo9000 and the inverse tiling layer.
It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].... | entailment |
def upsampling_feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activat... | An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
... | entailment |
def load(self):
"""Loads the config"""
try:
with open(self._ef_site_config, 'r') as yml_file:
return yaml.safe_load(yml_file)
except (IOError, yaml.parser.ParserError) as error:
print("Error: {}".format(error), file=sys.stderr)
sys.exit(1) | Loads the config | entailment |
def interpolate_loss(labels, loss1, loss2, interpolation_values):
"""
Interpolate two losses linearly.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param loss1: A float tensor of shape [batch_size, ...] representing the loss1 for int... | Interpolate two losses linearly.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param loss1: A float tensor of shape [batch_size, ...] representing the loss1 for interpolation.
:param loss2: A float tensor of shape [batch_size, ...] repres... | entailment |
def alpha_balance_loss(labels, loss, alpha_weights):
"""
Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label c... | Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param loss: A float tensor of shape [bat... | entailment |
def batch_alpha_balance_loss(labels, loss):
"""
Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
There is yet no paper for this type of loss.
:param labels: A float tensor of shape [batch_size, .... | Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
There is yet no paper for this type of loss.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilit... | entailment |
def mask_loss(input_tensor, binary_tensor):
"""
Mask a loss by using a tensor filled with 0 or 1.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A floa... | Mask a loss by using a tensor filled with 0 or 1.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the mas... | entailment |
def mean_on_masked(loss, mask, epsilon=1e-8, axis=None):
"""
Average a loss correctly when it was masked.
:param loss: A float tensor of shape [batch_size, ...] representing the (already masked) loss to be averaged.
:param mask: A float tensor of shape [batch_size, ...] representing the mask.
:para... | Average a loss correctly when it was masked.
:param loss: A float tensor of shape [batch_size, ...] representing the (already masked) loss to be averaged.
:param mask: A float tensor of shape [batch_size, ...] representing the mask.
:param epsilon: Offset of log for numerical stability.
:param axis: Th... | entailment |
def mask_and_mean_loss(input_tensor, binary_tensor, axis=None):
"""
Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] ... | Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...... | entailment |
def variance_corrected_loss(loss, sigma_2=None):
"""
Create a variance corrected loss.
When summing variance corrected losses you get the same as multiloss.
This is especially usefull for keras where when having multiple losses they are summed by keras.
This multi-loss implementation is inspired by... | Create a variance corrected loss.
When summing variance corrected losses you get the same as multiloss.
This is especially usefull for keras where when having multiple losses they are summed by keras.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight L... | entailment |
def multiloss(losses, logging_namespace="multiloss", exclude_from_weighting=[]):
"""
Create a loss from multiple losses my mixing them.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Ci... | Create a loss from multiple losses my mixing them.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Cipolla.
:param losses: A dict containing all losses that should be merged.
:param logg... | entailment |
def focus_loss(labels, probs, loss, gamma):
"""
Calculate the alpha balanced focal loss.
See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research]
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:pa... | Calculate the alpha balanced focal loss.
See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research]
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param probs: A float tensor of shape [batch_size, ..., num... | entailment |
def layer(op):
'''Decorator for composable network layers.'''
def layer_decorated(self, *args, **kwargs):
# Automatically set a name if not provided.
name = kwargs.setdefault('name', self.get_unique_name(op.__name__))
# Figure out the layer inputs.
if len(self.terminals) == 0:
... | Decorator for composable network layers. | entailment |
def multi_output_layer(op):
'''Decorator for composable network layers.'''
def layer_decorated(self, *args, **kwargs):
# Automatically set a name if not provided.
name = kwargs.setdefault('name', self.get_unique_name(op.__name__))
output_names = kwargs.setdefault('output_names', self.ge... | Decorator for composable network layers. | entailment |
def _load(self, data_path, ignore_missing=False):
'''Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
'''
if data_path.ends... | Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored. | entailment |
def feed(self, *args):
'''Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
'''
assert len(args) != 0
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, str):... | Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers. | entailment |
def get_unique_name(self, prefix):
'''Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
'''
ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1
return '%s_%d' % (prefix, ident) | Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix. | entailment |
def make_var(self, op_name, name, shape):
'''Creates a new TensorFlow variable.'''
if op_name in self.weights and name in self.weights[op_name]:
if self.verbose:
print("Using: {} {}".format(op_name, name))
initializer = tf.constant(self.weights[op_name][name], sha... | Creates a new TensorFlow variable. | entailment |
def mode_to_str(mode):
"""
Converts a tf.estimator.ModeKeys in a nice readable string.
:param mode: The mdoe as a tf.estimator.ModeKeys
:return: A human readable string representing the mode.
"""
if mode == tf.estimator.ModeKeys.TRAIN:
return "train"
if mode == tf.estimator.ModeKeys.... | Converts a tf.estimator.ModeKeys in a nice readable string.
:param mode: The mdoe as a tf.estimator.ModeKeys
:return: A human readable string representing the mode. | entailment |
def tf_if(condition, a, b):
"""
Implements an if condition in tensorflow.
:param condition: A boolean condition.
:param a: Case a.
:param b: Case b.
:return: A if condition was true, b otherwise.
"""
int_condition = tf.to_float(tf.to_int64(condition))
return a * int_condition + (1 - ... | Implements an if condition in tensorflow.
:param condition: A boolean condition.
:param a: Case a.
:param b: Case b.
:return: A if condition was true, b otherwise. | entailment |
def _read_data_legacy(prefix, batch_size):
"""
Loads a tf record as tensors you can use.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:return: A feature tensor dict and a label tensor dict.
"""
prefix = prefix... | Loads a tf record as tensors you can use.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:return: A feature tensor dict and a label tensor dict. | entailment |
def _read_data(prefix, batch_size, augmentation=None):
"""
Loads a dataset.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:param augmentation: An augmentation function.
:return: A tensorflow.data.dataset object.
... | Loads a dataset.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:param augmentation: An augmentation function.
:return: A tensorflow.data.dataset object. | entailment |
def create_input_fn(prefix, batch_size, augmentation=None):
"""
Loads a dataset.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:param augmentation: An augmentation function.
:return: An input function for a tf est... | Loads a dataset.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:param augmentation: An augmentation function.
:return: An input function for a tf estimator. | entailment |
def write_data(hyper_params,
mode,
sequence,
num_threads):
"""
Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}}
:param mode: The mode sp... | Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}}
:param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation".
:param sequence: A tf.keras.uti... | entailment |
def env(self, value):
"""
Sets context.env, context.env_short, and context.account_alias if env is valid
For envs of the form "global.<account>" and "mgmt.<account_alias>",
env is captured as "global" or "mgmt" and account_alias is parsed
out of the full env rather than looked up
Args:
val... | Sets context.env, context.env_short, and context.account_alias if env is valid
For envs of the form "global.<account>" and "mgmt.<account_alias>",
env is captured as "global" or "mgmt" and account_alias is parsed
out of the full env rather than looked up
Args:
value: the fully-qualified env value
... | entailment |
def service_registry(self, sr):
"""
Sets service registry object in context, doesn't check it
Args:
sr: EFServiceRegistry object
"""
if type(sr) is not EFServiceRegistry:
raise TypeError("sr value must be type 'EFServiceRegistry'")
self._service_registry = sr | Sets service registry object in context, doesn't check it
Args:
sr: EFServiceRegistry object | entailment |
def account_id(self, value):
"""
Sets the current account id
Args:
value: current account id (string)
Returns:
None
"""
if type(value) is not str:
raise TypeError("commit value must be string")
self._account_id = value | Sets the current account id
Args:
value: current account id (string)
Returns:
None | entailment |
def aws_client(self, client_id=None):
"""
Get AWS client if it exists (must have been formerly stored with set_aws_clients)
If client_id is not provided, returns the dictionary of all clients
Args:
client_id: label for the client, e.g. 'ec2'; omit to get a dictionary of all clients
Returns:
... | Get AWS client if it exists (must have been formerly stored with set_aws_clients)
If client_id is not provided, returns the dictionary of all clients
Args:
client_id: label for the client, e.g. 'ec2'; omit to get a dictionary of all clients
Returns:
aws client if found, or None if not | entailment |
def set_aws_clients(self, clients):
"""
Stash a dictionary of AWS clients in the context object
Args:
clients: dictionary of clients
"""
if type(clients) is not dict:
raise TypeError("clients must be a dict")
self._aws_clients = clients | Stash a dictionary of AWS clients in the context object
Args:
clients: dictionary of clients | entailment |
def handle_args_and_set_context(args):
"""
Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFVersionContext object
"""
parser = argparse.ArgumentParser()
parser.add_argument("service_name", help="name of the service")
parser.add_argument("key", h... | Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFVersionContext object | entailment |
def validate_context(context):
"""
Set the key for the current context.
Args:
context: a populated EFVersionContext object
"""
# Service must exist in service registry
if not context.service_registry.service_record(context.service_name):
fail("service: {} not found in service registry: {}".for... | Set the key for the current context.
Args:
context: a populated EFVersionContext object | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.