repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
OpenCageData/python-opencage-geocoder
opencage/geocoder.py
OpenCageGeocode.geocode
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...
python
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...
[ "def", "geocode", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY2", ":", "# py3 doesn't have unicode() function, and instead we check the text_type later", "try", ":", "query", "=", "unicode", "(", "query", ")", "except", "Un...
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 ...
[ "Given", "a", "string", "to", "search", "for", "return", "the", "results", "from", "OpenCage", "s", "Geocoder", "." ]
train
https://github.com/OpenCageData/python-opencage-geocoder/blob/21f102a33a036ed29e08e8375eceaa1bb4ec5009/opencage/geocoder.py#L90-L139
OpenCageData/python-opencage-geocoder
opencage/geocoder.py
OpenCageGeocode.reverse_geocode
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: ...
python
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: ...
[ "def", "reverse_geocode", "(", "self", ",", "lat", ",", "lng", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "geocode", "(", "_query_for_reverse_geocoding", "(", "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: if you have exceeded the number of queries you can make. Exception ...
[ "Given", "a", "latitude", "&", "longitude", "return", "an", "address", "for", "that", "point", "from", "OpenCage", "s", "Geocoder", "." ]
train
https://github.com/OpenCageData/python-opencage-geocoder/blob/21f102a33a036ed29e08e8375eceaa1bb4ec5009/opencage/geocoder.py#L141-L152
zillow/ctds
src/ctds/pool/__init__.py
ConnectionPool.acquire
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...
python
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...
[ "def", "acquire", "(", "self", ")", ":", "self", ".", "_condition", ".", "acquire", "(", ")", "try", ":", "# Wait for a connection if there is an upper bound to the pool.", "if", "self", ".", "_maxsize", "is", "not", "None", "and", "self", ".", "_block", ":", ...
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.
[ "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", "." ]
train
https://github.com/zillow/ctds/blob/03c9d182f63900fe6c792dda2d320392d6e3e759/src/ctds/pool/__init__.py#L118-L149
zillow/ctds
src/ctds/pool/__init__.py
ConnectionPool.release
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()`. ...
python
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()`. ...
[ "def", "release", "(", "self", ",", "connection", ")", ":", "try", ":", "# Rollback the existing connection, closing on failure.", "connection", ".", "rollback", "(", ")", "except", "self", ".", "_dbapi2", ".", "Error", ":", "self", ".", "_close", "(", "connecti...
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...
[ "Return", "a", "connection", "back", "to", "the", "pool", "." ]
train
https://github.com/zillow/ctds/blob/03c9d182f63900fe6c792dda2d320392d6e3e759/src/ctds/pool/__init__.py#L151-L179
zillow/ctds
src/ctds/pool/__init__.py
ConnectionPool.finalize
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): ...
python
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): ...
[ "def", "finalize", "(", "self", ")", ":", "self", ".", "_condition", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "_nconnections", "!=", "len", "(", "self", ".", "_pool", ")", ":", "warnings", ".", "warn", "(", "'finalize() called with unrele...
Release all connections contained in the pool. .. note:: This should be called to cleanly shutdown the pool, i.e. on process exit.
[ "Release", "all", "connections", "contained", "in", "the", "pool", "." ]
train
https://github.com/zillow/ctds/blob/03c9d182f63900fe6c792dda2d320392d6e3e759/src/ctds/pool/__init__.py#L181-L197
sphinx-contrib/openapi
sphinxcontrib/openapi/openapi30.py
_dict_merge
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...
python
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...
[ "def", "_dict_merge", "(", "dct", ",", "merge_dct", ")", ":", "for", "k", ",", "v", "in", "merge_dct", ".", "items", "(", ")", ":", "if", "(", "k", "in", "dct", "and", "isinstance", "(", "dct", "[", "k", "]", ",", "dict", ")", "and", "isinstance"...
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: ...
[ "Recursive", "dict", "merge", "." ]
train
https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/openapi30.py#L58-L76
sphinx-contrib/openapi
sphinxcontrib/openapi/openapi30.py
_parse_schema
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 ...
python
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 ...
[ "def", "_parse_schema", "(", "schema", ",", "method", ")", ":", "if", "method", "and", "schema", ".", "get", "(", "'readOnly'", ",", "False", ")", ":", "return", "_READONLY_PROPERTY", "# allOf: Must be valid against all of the subschemas", "if", "'allOf'", "in", "...
Convert a Schema Object to a Python object. Args: schema: An ``OrderedDict`` representing the schema object.
[ "Convert", "a", "Schema", "Object", "to", "a", "Python", "object", "." ]
train
https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/openapi30.py#L79-L136
sphinx-contrib/openapi
sphinxcontrib/openapi/openapi30.py
_example
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...
python
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...
[ "def", "_example", "(", "media_type_objects", ",", "method", "=", "None", ",", "endpoint", "=", "None", ",", "status", "=", "None", ",", "nb_indent", "=", "0", ")", ":", "indent", "=", "' '", "extra_indent", "=", "indent", "*", "nb_indent", "if", "meth...
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 ...
[ "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", "...
train
https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/openapi30.py#L139-L225
sphinx-contrib/openapi
sphinxcontrib/openapi/utils.py
_resolve_refs
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...
python
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...
[ "def", "_resolve_refs", "(", "uri", ",", "spec", ")", ":", "resolver", "=", "jsonschema", ".", "RefResolver", "(", "uri", ",", "spec", ")", "def", "_do_resolve", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "collections", ".", "Mapping", ...
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...
[ "Resolve", "JSON", "references", "in", "a", "given", "dictionary", "." ]
train
https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/utils.py#L18-L45
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
convert_double_to_two_registers
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...
python
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...
[ "def", "convert_double_to_two_registers", "(", "doubleValue", ")", ":", "myList", "=", "list", "(", ")", "myList", ".", "append", "(", "int", "(", "doubleValue", "&", "0x0000FFFF", ")", ")", "#Append Least Significant Word ", "myList", ".", "append", "(", "...
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[]
[ "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", "[]" ]
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L951-L960
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
convert_float_to_two_registers
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...
python
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...
[ "def", "convert_float_to_two_registers", "(", "floatValue", ")", ":", "myList", "=", "list", "(", ")", "s", "=", "bytearray", "(", "struct", ".", "pack", "(", "'<f'", ",", "floatValue", ")", ")", "#little endian", "myList", ".", "append", "(", "s", "[", ...
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[]
[ "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", "[]" ]
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L963-L974
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
convert_registers_to_float
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] = ...
python
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] = ...
[ "def", "convert_registers_to_float", "(", "registers", ")", ":", "b", "=", "bytearray", "(", "4", ")", "b", "[", "0", "]", "=", "registers", "[", "0", "]", "&", "0xff", "b", "[", "1", "]", "=", "(", "registers", "[", "0", "]", "&", "0xff00", ")",...
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
[ "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", "r...
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L987-L999
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
ModbusClient.connect
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...
python
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...
[ "def", "connect", "(", "self", ")", ":", "if", "(", "self", ".", "__ser", "is", "not", "None", ")", ":", "serial", "=", "importlib", ".", "import_module", "(", "\"serial\"", ")", "if", "self", ".", "__stopbits", "==", "0", ":", "self", ".", "__ser", ...
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
[ "Connects", "to", "a", "Modbus", "-", "TCP", "Server", "or", "a", "Modbus", "-", "RTU", "Slave", "with", "the", "given", "Parameters" ]
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L52-L80
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
ModbusClient.close
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) ...
python
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) ...
[ "def", "close", "(", "self", ")", ":", "if", "(", "self", ".", "__ser", "is", "not", "None", ")", ":", "self", ".", "__ser", ".", "close", "(", ")", "if", "(", "self", ".", "__tcpClientSocket", "is", "not", "None", ")", ":", "self", ".", "__stopl...
Closes Serial port, or TCP-Socket connection
[ "Closes", "Serial", "port", "or", "TCP", "-", "Socket", "connection" ]
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L97-L107
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
ModbusClient.read_discreteinputs
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...
python
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...
[ "def", "read_discreteinputs", "(", "self", ",", "starting_address", ",", "quantity", ")", ":", "self", ".", "__transactionIdentifier", "+=", "1", "if", "(", "self", ".", "__ser", "is", "not", "None", ")", ":", "if", "(", "self", ".", "__ser", ".", "close...
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
[ "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", ":", ...
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L110-L198
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
ModbusClient.write_single_coil
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...
python
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...
[ "def", "write_single_coil", "(", "self", ",", "starting_address", ",", "value", ")", ":", "self", ".", "__transactionIdentifier", "+=", "1", "if", "(", "self", ".", "__ser", "is", "not", "None", ")", ":", "if", "(", "self", ".", "__ser", ".", "closed", ...
Write single Coil to Master device (Function code 5) starting_address: Coil to be written value: Coil Value to be written
[ "Write", "single", "Coil", "to", "Master", "device", "(", "Function", "code", "5", ")", "starting_address", ":", "Coil", "to", "be", "written", "value", ":", "Coil", "Value", "to", "be", "written" ]
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L468-L547
rossmann-engineering/EasyModbusTCP.PY
easymodbus/modbusClient.py
ModbusClient.write_multiple_coils
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...
python
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...
[ "def", "write_multiple_coils", "(", "self", ",", "starting_address", ",", "values", ")", ":", "self", ".", "__transactionIdentifier", "+=", "1", "if", "(", "self", ".", "__ser", "is", "not", "None", ")", ":", "if", "(", "self", ".", "__ser", ".", "closed...
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
[ "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"...
train
https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L630-L727
crunchyroll/ef-open
efopen/ef_service_registry.py
EFServiceRegistry.services
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...
python
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...
[ "def", "services", "(", "self", ",", "service_group", "=", "None", ")", ":", "# Specific service group requested", "if", "service_group", "is", "not", "None", ":", "if", "service_group", "not", "in", "EFConfig", ".", "SERVICE_GROUPS", ":", "raise", "RuntimeError",...
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
[ "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_gr...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_service_registry.py#L78-L98
crunchyroll/ef-open
efopen/ef_service_registry.py
EFServiceRegistry.iter_services
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...
python
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...
[ "def", "iter_services", "(", "self", ",", "service_group", "=", "None", ")", ":", "if", "service_group", "is", "not", "None", ":", "if", "service_group", "not", "in", "EFConfig", ".", "SERVICE_GROUPS", ":", "raise", "RuntimeError", "(", "\"service registry: {} d...
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
[ "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",...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_service_registry.py#L100-L114
crunchyroll/ef-open
efopen/ef_service_registry.py
EFServiceRegistry.valid_envs
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...
python
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...
[ "def", "valid_envs", "(", "self", ",", "service_name", ")", ":", "service_record", "=", "self", ".", "service_record", "(", "service_name", ")", "if", "service_record", "is", "None", ":", "raise", "RuntimeError", "(", "\"service registry doesn't have service: {}\"", ...
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
[ "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", "t...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_service_registry.py#L116-L140
crunchyroll/ef-open
efopen/ef_service_registry.py
EFServiceRegistry.service_record
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 ...
python
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 ...
[ "def", "service_record", "(", "self", ",", "service_name", ")", ":", "if", "not", "self", ".", "services", "(", ")", ".", "has_key", "(", "service_name", ")", ":", "return", "None", "return", "self", ".", "services", "(", ")", "[", "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
[ "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", "fou...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_service_registry.py#L142-L151
crunchyroll/ef-open
efopen/ef_service_registry.py
EFServiceRegistry.service_group
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...
python
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...
[ "def", "service_group", "(", "self", ",", "service_name", ")", ":", "for", "group", "in", "EFConfig", ".", "SERVICE_GROUPS", ":", "if", "self", ".", "services", "(", "group", ")", ".", "has_key", "(", "service_name", ")", ":", "return", "group", "return", ...
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
[ "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" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_service_registry.py#L153-L163
crunchyroll/ef-open
efopen/ef_service_registry.py
EFServiceRegistry.service_region
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....
python
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....
[ "def", "service_region", "(", "self", ",", "service_name", ")", ":", "if", "not", "self", ".", "services", "(", ")", "[", "service_name", "]", ".", "has_key", "(", "\"region\"", ")", ":", "return", "EFConfig", ".", "DEFAULT_REGION", "else", ":", "return", ...
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
[ "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...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_service_registry.py#L165-L175
penguinmenac3/starttf
starttf/estimators/tf_estimator.py
easy_train_and_evaluate
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...
python
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...
[ "def", "easy_train_and_evaluate", "(", "hyper_params", ",", "Model", "=", "None", ",", "create_loss", "=", "None", ",", "training_data", "=", "None", ",", "validation_data", "=", "None", ",", "inline_plotting", "=", "False", ",", "session_config", "=", "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...
[ "Train", "and", "evaluate", "your", "model", "without", "any", "boilerplate", "code", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/estimators/tf_estimator.py#L78-L201
penguinmenac3/starttf
starttf/estimators/tf_estimator.py
create_prediction_estimator
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: """ ...
python
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: """ ...
[ "def", "create_prediction_estimator", "(", "hyper_params", ",", "model", ",", "checkpoint_path", "=", "None", ")", ":", "if", "checkpoint_path", "is", "None", ":", "chkpts", "=", "sorted", "(", "[", "name", "for", "name", "in", "os", ".", "listdir", "(", "...
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", ":", "(", "Option...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/estimators/tf_estimator.py#L204-L224
crunchyroll/ef-open
efopen/ef_plugin.py
ef_plugin
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...
python
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...
[ "def", "ef_plugin", "(", "service_name", ")", ":", "def", "class_rebuilder", "(", "cls", ")", ":", "class", "EFPlugin", "(", "cls", ")", ":", "\"\"\"\n Base class of ef-plugins. Defines which service is extended and provides access to the current instance of\n EFContext...
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()
[ "Decorator", "for", "ef", "plugin", "classes", ".", "Any", "wrapped", "classes", "should", "contain", "a", "run", "()", "method", "which", "executes", "the", "plugin", "code", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_plugin.py#L10-L58
crunchyroll/ef-open
efopen/ef_plugin.py
run_plugins
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() """ ...
python
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() """ ...
[ "def", "run_plugins", "(", "context_obj", ",", "boto3_clients", ")", ":", "def", "print_if_verbose", "(", "message", ")", ":", "if", "context_obj", ".", "verbose", ":", "print", "(", "message", ")", "service_name", "=", "os", ".", "path", ".", "basename", ...
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", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_plugin.py#L61-L98
penguinmenac3/starttf
starttf/estimators/keras_trainer.py
easy_train_and_evaluate
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): """ ...
python
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): """ ...
[ "def", "easy_train_and_evaluate", "(", "hyper_params", ",", "Model", "=", "None", ",", "define_loss_fn", "=", "None", ",", "training_data", "=", "None", ",", "validation_data", "=", "None", ",", "continue_training", "=", "False", ",", "session_config", "=", "Non...
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...
[ "Train", "and", "evaluate", "your", "model", "without", "any", "boilerplate", "code", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/estimators/keras_trainer.py#L50-L172
penguinmenac3/starttf
starttf/utils/image_manipulation.py
crop
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. """ ...
python
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. """ ...
[ "def", "crop", "(", "img", ",", "start_y", ",", "start_x", ",", "h", ",", "w", ")", ":", "return", "img", "[", "start_y", ":", "start_y", "+", "h", ",", "start_x", ":", "start_x", "+", "w", ",", ":", "]", ".", "copy", "(", ")" ]
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", "...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/image_manipulation.py#L28-L38
penguinmenac3/starttf
starttf/utils/image_manipulation.py
resize_image_with_crop_or_pad
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...
python
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...
[ "def", "resize_image_with_crop_or_pad", "(", "img", ",", "target_height", ",", "target_width", ")", ":", "h", ",", "w", "=", "target_height", ",", "target_width", "max_h", ",", "max_w", ",", "c", "=", "img", ".", "shape", "# crop", "img", "=", "crop_center",...
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...
[ "Crops", "and", "/", "or", "pads", "an", "image", "to", "a", "target", "width", "and", "height", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/image_manipulation.py#L48-L71
penguinmenac3/starttf
starttf/utils/image_manipulation.py
_rotatedRectWithMaxArea
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...
python
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...
[ "def", "_rotatedRectWithMaxArea", "(", "w", ",", "h", ",", "angle", ")", ":", "if", "w", "<=", "0", "or", "h", "<=", "0", ":", "return", "0", ",", "0", "width_is_longer", "=", "w", ">=", "h", "side_long", ",", "side_short", "=", "(", "w", ",", "h...
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
[ "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"...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/image_manipulation.py#L74-L101
penguinmenac3/starttf
starttf/utils/image_manipulation.py
rotate_img_and_crop
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...
python
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...
[ "def", "rotate_img_and_crop", "(", "img", ",", "angle", ")", ":", "h", ",", "w", ",", "_", "=", "img", ".", "shape", "img", "=", "scipy", ".", "ndimage", ".", "interpolation", ".", "rotate", "(", "img", ",", "angle", ")", "w", ",", "h", "=", "_ro...
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.
[ "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", "."...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/image_manipulation.py#L104-L114
crunchyroll/ef-open
efopen/ef_cf_diff.py
diff_string_templates
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...
python
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...
[ "def", "diff_string_templates", "(", "string_a", ",", "string_b", ")", ":", "s1", "=", "string_a", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "s2", "=", "string_b", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "diffs", "=", "unified_d...
Determine the diff of two strings. Return an empty string if the strings are identical, and the diff output string if they are not.
[ "Determine", "the", "diff", "of", "two", "strings", ".", "Return", "an", "empty", "string", "if", "the", "strings", "are", "identical", "and", "the", "diff", "output", "string", "if", "they", "are", "not", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L50-L58
crunchyroll/ef-open
efopen/ef_cf_diff.py
render_local_template
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...
python
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...
[ "def", "render_local_template", "(", "service_name", ",", "environment", ",", "repo_root", ",", "template_file", ")", ":", "cmd", "=", "'cd {} && ef-cf {} {} --devel --verbose'", ".", "format", "(", "repo_root", ",", "template_file", ",", "environment", ")", "p", "=...
Render a given service's template for a given environment and return it
[ "Render", "a", "given", "service", "s", "template", "for", "a", "given", "environment", "and", "return", "it" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L61-L78
crunchyroll/ef-open
efopen/ef_cf_diff.py
fetch_current_cloudformation_template
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...
python
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...
[ "def", "fetch_current_cloudformation_template", "(", "service_name", ",", "environment", ",", "cf_client", ")", ":", "stack_name", "=", "get_stack_name", "(", "environment", ",", "service_name", ")", "logger", ".", "debug", "(", "'Fetching template for `%s`'", ",", "s...
Fetch the currently-deployed template for the given service in the given environment and return it.
[ "Fetch", "the", "currently", "-", "deployed", "template", "for", "the", "given", "service", "in", "the", "given", "environment", "and", "return", "it", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L81-L89
crunchyroll/ef-open
efopen/ef_cf_diff.py
diff_sevice_by_text
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`', ...
python
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`', ...
[ "def", "diff_sevice_by_text", "(", "service_name", ",", "service", ",", "environment", ",", "cf_client", ",", "repo_root", ")", ":", "global", "ret_code", "logger", ".", "info", "(", "'Investigating textual diff for `%s`:`%s` in environment `%s`'", ",", "service", "[", ...
Render the local template and compare it to the template that was last applied in the target environment.
[ "Render", "the", "local", "template", "and", "compare", "it", "to", "the", "template", "that", "was", "last", "applied", "in", "the", "target", "environment", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L92-L123
crunchyroll/ef-open
efopen/ef_cf_diff.py
diff_sevice_by_changeset
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...
python
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...
[ "def", "diff_sevice_by_changeset", "(", "service_name", ",", "service", ",", "environment", ",", "cf_client", ",", "repo_root", ")", ":", "global", "ret_code", "logger", ".", "info", "(", "'Investigating changeset for `%s`:`%s` in environment `%s`'", ",", "service", "["...
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.
[ "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",...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L198-L238
crunchyroll/ef-open
efopen/ef_cf_diff.py
get_cloudformation_client
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_...
python
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_...
[ "def", "get_cloudformation_client", "(", "service_name", ",", "environment_name", ")", ":", "region", "=", "service_registry", ".", "service_region", "(", "service_name", ")", "if", "whereami", "(", ")", "==", "'ec2'", ":", "profile", "=", "None", "else", ":", ...
Given a service name and an environment name, return a boto CloudFormation client object.
[ "Given", "a", "service", "name", "and", "an", "environment", "name", "return", "a", "boto", "CloudFormation", "client", "object", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L241-L254
crunchyroll/ef-open
efopen/ef_cf_diff.py
evaluate_service_changes
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...
python
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...
[ "def", "evaluate_service_changes", "(", "services", ",", "envs", ",", "repo_root", ",", "func", ")", ":", "for", "service_name", ",", "service", "in", "services", ".", "iteritems", "(", ")", ":", "for", "env_category", "in", "service", "[", "'environments'", ...
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.
[ "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", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L277-L297
crunchyroll/ef-open
efopen/ef_cf_diff.py
get_matching_service_template_file
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...
python
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...
[ "def", "get_matching_service_template_file", "(", "service_name", ",", "template_files", ")", ":", "# If this is a subservice, use the parent service's template", "service_name", "=", "service_name", ".", "split", "(", "'.'", ")", "[", "0", "]", "if", "service_name", "in"...
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.
[ "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", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L316-L325
crunchyroll/ef-open
efopen/ef_cf_diff.py
get_dict_registry_services
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 ...
python
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 ...
[ "def", "get_dict_registry_services", "(", "registry", ",", "template_files", ",", "warn_missing_files", "=", "True", ")", ":", "with", "open", "(", "registry", ")", "as", "fr", ":", "parsed_registry", "=", "json", ".", "load", "(", "fr", ")", "services", "="...
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...
[ "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", ...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L328-L363
crunchyroll/ef-open
efopen/ef_cf_diff.py
scan_dir_for_template_files
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): ...
python
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): ...
[ "def", "scan_dir_for_template_files", "(", "search_dir", ")", ":", "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.
[ "Return", "a", "map", "of", "likely", "service", "/", "template", "name", "to", "template", "file", ".", "This", "includes", "all", "the", "template", "files", "in", "fixtures", "and", "in", "services", "." ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L366-L378
crunchyroll/ef-open
efopen/ef_password.py
generate_secret
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....
python
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....
[ "def", "generate_secret", "(", "length", "=", "32", ")", ":", "alphabet", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "random_bytes", "=", "os", ".", "urandom", "(", "length", ")", "indices", "=", "[", "int", "(", "len", "(", "al...
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
[ "Generate", "a", "random", "secret", "consisting", "of", "mixed", "-", "case", "letters", "and", "numbers", "Args", ":", "length", "(", "int", ")", ":", "Length", "of", "the", "generated", "password", "Returns", ":", "a", "randomly", "generated", "secret", ...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_password.py#L97-L110
crunchyroll/ef-open
efopen/ef_password.py
generate_secret_file
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...
python
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...
[ "def", "generate_secret_file", "(", "file_path", ",", "pattern", ",", "service", ",", "environment", ",", "clients", ")", ":", "changed", "=", "False", "with", "open", "(", "file_path", ")", "as", "json_file", ":", "data", "=", "json", ".", "load", "(", ...
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 ...
[ "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", ")", ":", "Patt...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_password.py#L112-L146
crunchyroll/ef-open
efopen/ef_password.py
handle_args_and_set_context
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...
python
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...
[ "def", "handle_args_and_set_context", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"service\"", ",", "help", "=", "\"name of service password is being generated for\"", ")", "parser", ".", "...
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
[ "Args", ":", "args", ":", "the", "command", "line", "args", "probably", "passed", "from", "main", "()", "as", "sys", ".", "argv", "[", "1", ":", "]", "Returns", ":", "a", "populated", "EFPWContext", "object", "Raises", ":", "RuntimeError", ":", "if", "...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_password.py#L148-L183
penguinmenac3/starttf
starttf/layers/tile_2d.py
tile_2d
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 ...
python
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 ...
[ "def", "tile_2d", "(", "input", ",", "k_x", ",", "k_y", ",", "name", ",", "reorder_required", "=", "True", ")", ":", "size", "=", "input", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "c", ",", "h", ",", "w", "=", "size", "[", "3", "]"...
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...
[ "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", "...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L26-L66
penguinmenac3/starttf
starttf/layers/tile_2d.py
inverse_tile_2d
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...
python
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...
[ "def", "inverse_tile_2d", "(", "input", ",", "k_x", ",", "k_y", ",", "name", ")", ":", "batch_size", ",", "h", ",", "w", ",", "c", "=", "input", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "batch_size", "is", "None", ":", "batch_siz...
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...
[ "An", "inverse", "tiling", "layer", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L69-L99
penguinmenac3/starttf
starttf/layers/tile_2d.py
feature_passthrough
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...
python
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...
[ "def", "feature_passthrough", "(", "early_feat", ",", "late_feat", ",", "filters", ",", "name", ",", "kernel_size", "=", "(", "1", ",", "1", ")", ")", ":", "_", ",", "h_early", ",", "w_early", ",", "c_early", "=", "early_feat", ".", "get_shape", "(", "...
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, _]....
[ "A", "feature", "passthrough", "layer", "inspired", "by", "yolo9000", "and", "the", "inverse", "tiling", "layer", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L102-L128
penguinmenac3/starttf
starttf/layers/tile_2d.py
upsampling_feature_passthrough
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...
python
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...
[ "def", "upsampling_feature_passthrough", "(", "early_feat", ",", "late_feat", ",", "filters", ",", "name", ",", "kernel_size", "=", "(", "1", ",", "1", ")", ")", ":", "_", ",", "h_early", ",", "w_early", ",", "c_early", "=", "early_feat", ".", "get_shape",...
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, _]. ...
[ "An", "upsampling", "feature", "passthrough", "layer", "inspired", "by", "yolo9000", "and", "the", "tiling", "layer", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L131-L157
crunchyroll/ef-open
efopen/ef_site_config.py
EFSiteConfig.load
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)
python
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)
[ "def", "load", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "_ef_site_config", ",", "'r'", ")", "as", "yml_file", ":", "return", "yaml", ".", "safe_load", "(", "yml_file", ")", "except", "(", "IOError", ",", "yaml", ".", "pars...
Loads the config
[ "Loads", "the", "config" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_site_config.py#L32-L39
penguinmenac3/starttf
starttf/losses/loss_processors.py
interpolate_loss
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...
python
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...
[ "def", "interpolate_loss", "(", "labels", ",", "loss1", ",", "loss2", ",", "interpolation_values", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"interpolate_focus_loss\"", ")", ":", "# Select the probs or weights with the labels.", "t", "=", "tf", ".", "red...
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...
[ "Interpolate", "two", "losses", "linearly", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L27-L40
penguinmenac3/starttf
starttf/losses/loss_processors.py
alpha_balance_loss
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...
python
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...
[ "def", "alpha_balance_loss", "(", "labels", ",", "loss", ",", "alpha_weights", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"alpha_balance\"", ")", ":", "# Broadcast multiply labels with alpha weights to select weights and then reduce them along last axis.", "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 class probabilities. :param loss: A float tensor of shape [bat...
[ "Calculate", "the", "alpha", "balanced", "cross_entropy", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L43-L58
penguinmenac3/starttf
starttf/losses/loss_processors.py
batch_alpha_balance_loss
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, ....
python
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, ....
[ "def", "batch_alpha_balance_loss", "(", "labels", ",", "loss", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"batch_alpha_balance\"", ")", ":", "# Compute the occurrence probability for each class", "mu", ",", "_", "=", "tf", ".", "nn", ".", "moments", "("...
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...
[ "Calculate", "the", "alpha", "balanced", "cross_entropy", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L61-L82
penguinmenac3/starttf
starttf/losses/loss_processors.py
mask_loss
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...
python
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...
[ "def", "mask_loss", "(", "input_tensor", ",", "binary_tensor", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"mask_loss\"", ")", ":", "mask", "=", "tf", ".", "cast", "(", "tf", ".", "cast", "(", "binary_tensor", ",", "tf", ".", "bool", ")", ","...
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...
[ "Mask", "a", "loss", "by", "using", "a", "tensor", "filled", "with", "0", "or", "1", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L85-L96
penguinmenac3/starttf
starttf/losses/loss_processors.py
mean_on_masked
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...
python
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...
[ "def", "mean_on_masked", "(", "loss", ",", "mask", ",", "epsilon", "=", "1e-8", ",", "axis", "=", "None", ")", ":", "mask", "=", "tf", ".", "cast", "(", "tf", ".", "cast", "(", "mask", ",", "tf", ".", "bool", ")", ",", "tf", ".", "float32", ")"...
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...
[ "Average", "a", "loss", "correctly", "when", "it", "was", "masked", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L99-L112
penguinmenac3/starttf
starttf/losses/loss_processors.py
mask_and_mean_loss
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, ...] ...
python
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, ...] ...
[ "def", "mask_and_mean_loss", "(", "input_tensor", ",", "binary_tensor", ",", "axis", "=", "None", ")", ":", "return", "mean_on_masked", "(", "mask_loss", "(", "input_tensor", ",", "binary_tensor", ")", ",", "binary_tensor", ",", "axis", "=", "axis", ")" ]
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, ......
[ "Mask", "a", "loss", "by", "using", "a", "tensor", "filled", "with", "0", "or", "1", "and", "average", "correctly", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L115-L125
penguinmenac3/starttf
starttf/losses/loss_processors.py
variance_corrected_loss
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...
python
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...
[ "def", "variance_corrected_loss", "(", "loss", ",", "sigma_2", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"variance_corrected_loss\"", ")", ":", "sigma_cost", "=", "0", "if", "sigma_2", "is", "None", ":", "# FIXME the paper has been updated...
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...
[ "Create", "a", "variance", "corrected", "loss", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L128-L148
penguinmenac3/starttf
starttf/losses/loss_processors.py
multiloss
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...
python
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...
[ "def", "multiloss", "(", "losses", ",", "logging_namespace", "=", "\"multiloss\"", ",", "exclude_from_weighting", "=", "[", "]", ")", ":", "with", "tf", ".", "variable_scope", "(", "logging_namespace", ")", ":", "sum_loss", "=", "0", "for", "loss_name", ",", ...
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...
[ "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...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L151-L169
penguinmenac3/starttf
starttf/losses/loss_processors.py
focus_loss
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...
python
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...
[ "def", "focus_loss", "(", "labels", ",", "probs", ",", "loss", ",", "gamma", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"focus_loss\"", ")", ":", "# Compute p_t that is used in paper.", "# FIXME is it possible that the 1-p term does not make any sense?", "p_t",...
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...
[ "Calculate", "the", "alpha", "balanced", "focal", "loss", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L172-L190
penguinmenac3/starttf
starttf/layers/caffe_tensorflow.py
layer
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: ...
python
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: ...
[ "def", "layer", "(", "op", ")", ":", "def", "layer_decorated", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Automatically set a name if not provided.", "name", "=", "kwargs", ".", "setdefault", "(", "'name'", ",", "self", ".", "get_...
Decorator for composable network layers.
[ "Decorator", "for", "composable", "network", "layers", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L14-L36
penguinmenac3/starttf
starttf/layers/caffe_tensorflow.py
multi_output_layer
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...
python
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...
[ "def", "multi_output_layer", "(", "op", ")", ":", "def", "layer_decorated", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Automatically set a name if not provided.", "name", "=", "kwargs", ".", "setdefault", "(", "'name'", ",", "self", ...
Decorator for composable network layers.
[ "Decorator", "for", "composable", "network", "layers", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L39-L63
penguinmenac3/starttf
starttf/layers/caffe_tensorflow.py
Network._load
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...
python
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...
[ "def", "_load", "(", "self", ",", "data_path", ",", "ignore_missing", "=", "False", ")", ":", "if", "data_path", ".", "endswith", "(", "\".npz\"", ")", ":", "data_dict", "=", "np", ".", "load", "(", "data_path", ")", "keys", "=", "sorted", "(", "data_d...
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.
[ "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", "...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L92-L121
penguinmenac3/starttf
starttf/layers/caffe_tensorflow.py
Network.feed
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):...
python
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):...
[ "def", "feed", "(", "self", ",", "*", "args", ")", ":", "assert", "len", "(", "args", ")", "!=", "0", "self", ".", "terminals", "=", "[", "]", "for", "fed_layer", "in", "args", ":", "if", "isinstance", "(", "fed_layer", ",", "str", ")", ":", "try...
Set the input(s) for the next operation by replacing the terminal nodes. The arguments can be either layer names or the actual layers.
[ "Set", "the", "input", "(", "s", ")", "for", "the", "next", "operation", "by", "replacing", "the", "terminal", "nodes", ".", "The", "arguments", "can", "be", "either", "layer", "names", "or", "the", "actual", "layers", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L123-L136
penguinmenac3/starttf
starttf/layers/caffe_tensorflow.py
Network.get_unique_name
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)
python
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)
[ "def", "get_unique_name", "(", "self", ",", "prefix", ")", ":", "ident", "=", "sum", "(", "t", ".", "startswith", "(", "prefix", ")", "for", "t", ",", "_", "in", "self", ".", "layers", ".", "items", "(", ")", ")", "+", "1", "return", "'%s_%d'", "...
Returns an index-suffixed unique name for the given prefix. This is used for auto-generating layer names based on the type-prefix.
[ "Returns", "an", "index", "-", "suffixed", "unique", "name", "for", "the", "given", "prefix", ".", "This", "is", "used", "for", "auto", "-", "generating", "layer", "names", "based", "on", "the", "type", "-", "prefix", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L142-L147
penguinmenac3/starttf
starttf/layers/caffe_tensorflow.py
Network.make_var
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...
python
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...
[ "def", "make_var", "(", "self", ",", "op_name", ",", "name", ",", "shape", ")", ":", "if", "op_name", "in", "self", ".", "weights", "and", "name", "in", "self", ".", "weights", "[", "op_name", "]", ":", "if", "self", ".", "verbose", ":", "print", "...
Creates a new TensorFlow variable.
[ "Creates", "a", "new", "TensorFlow", "variable", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L149-L156
penguinmenac3/starttf
starttf/utils/misc.py
mode_to_str
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....
python
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....
[ "def", "mode_to_str", "(", "mode", ")", ":", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ":", "return", "\"train\"", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ":", "return", "\"eval\"", "if...
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.
[ "Converts", "a", "tf", ".", "estimator", ".", "ModeKeys", "in", "a", "nice", "readable", "string", ".", ":", "param", "mode", ":", "The", "mdoe", "as", "a", "tf", ".", "estimator", ".", "ModeKeys", ":", "return", ":", "A", "human", "readable", "string"...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/misc.py#L32-L44
penguinmenac3/starttf
starttf/utils/misc.py
tf_if
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 - ...
python
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 - ...
[ "def", "tf_if", "(", "condition", ",", "a", ",", "b", ")", ":", "int_condition", "=", "tf", ".", "to_float", "(", "tf", ".", "to_int64", "(", "condition", ")", ")", "return", "a", "*", "int_condition", "+", "(", "1", "-", "int_condition", ")", "*", ...
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.
[ "Implements", "an", "if", "condition", "in", "tensorflow", ".", ":", "param", "condition", ":", "A", "boolean", "condition", ".", ":", "param", "a", ":", "Case", "a", ".", ":", "param", "b", ":", "Case", "b", ".", ":", "return", ":", "A", "if", "co...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/misc.py#L63-L72
penguinmenac3/starttf
starttf/data/autorecords.py
_read_data_legacy
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...
python
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...
[ "def", "_read_data_legacy", "(", "prefix", ",", "batch_size", ")", ":", "prefix", "=", "prefix", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "folder", "=", "\"/\"", ".", "join", "(", "prefix", ".", "split", "(", "\"/\"", ")", "[", ":", "-", "...
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.
[ "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",...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/data/autorecords.py#L170-L208
penguinmenac3/starttf
starttf/data/autorecords.py
_read_data
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. ...
python
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. ...
[ "def", "_read_data", "(", "prefix", ",", "batch_size", ",", "augmentation", "=", "None", ")", ":", "prefix", "=", "prefix", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", "folder", "=", "\"/\"", ".", "join", "(", "prefix", ".", "split", "(", "\"/\...
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", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/data/autorecords.py#L211-L237
penguinmenac3/starttf
starttf/data/autorecords.py
create_input_fn
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...
python
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...
[ "def", "create_input_fn", "(", "prefix", ",", "batch_size", ",", "augmentation", "=", "None", ")", ":", "# Check if the version is too old for dataset api to work better than manually loading data.", "if", "tf", ".", "__version__", ".", "startswith", "(", "\"1.6\"", ")", ...
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.
[ "Loads", "a", "dataset", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/data/autorecords.py#L240-L261
penguinmenac3/starttf
starttf/data/autorecords.py
write_data
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...
python
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...
[ "def", "write_data", "(", "hyper_params", ",", "mode", ",", "sequence", ",", "num_threads", ")", ":", "if", "not", "isinstance", "(", "sequence", ",", "Sequence", ")", "and", "not", "(", "callable", "(", "getattr", "(", "sequence", ",", "\"__getitem__\"", ...
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...
[ "Write", "a", "tf", "record", "containing", "a", "feature", "dict", "and", "a", "label", "dict", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/data/autorecords.py#L264-L300
crunchyroll/ef-open
efopen/ef_context.py
EFContext.env
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...
python
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...
[ "def", "env", "(", "self", ",", "value", ")", ":", "env_valid", "(", "value", ")", "self", ".", "_env_full", "=", "value", "if", "value", ".", "find", "(", "\".\"", ")", "==", "-", "1", ":", "# plain environment, e.g. prod, staging, proto<n>", "self", ".",...
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 ...
[ "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", "c...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_context.py#L57-L79
crunchyroll/ef-open
efopen/ef_context.py
EFContext.service_registry
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
python
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
[ "def", "service_registry", "(", "self", ",", "sr", ")", ":", "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
[ "Sets", "service", "registry", "object", "in", "context", "doesn", "t", "check", "it", "Args", ":", "sr", ":", "EFServiceRegistry", "object" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_context.py#L106-L114
crunchyroll/ef-open
efopen/ef_context.py
EFContext.account_id
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
python
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
[ "def", "account_id", "(", "self", ",", "value", ")", ":", "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
[ "Sets", "the", "current", "account", "id" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_context.py#L127-L139
crunchyroll/ef-open
efopen/ef_context.py
EFContext.aws_client
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: ...
python
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: ...
[ "def", "aws_client", "(", "self", ",", "client_id", "=", "None", ")", ":", "if", "client_id", "is", "None", ":", "return", "self", ".", "_aws_clients", "elif", "self", ".", "_aws_clients", "is", "not", "None", "and", "self", ".", "_aws_clients", ".", "ha...
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
[ "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", ":"...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_context.py#L141-L155
crunchyroll/ef-open
efopen/ef_context.py
EFContext.set_aws_clients
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
python
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
[ "def", "set_aws_clients", "(", "self", ",", "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
[ "Stash", "a", "dictionary", "of", "AWS", "clients", "in", "the", "context", "object", "Args", ":", "clients", ":", "dictionary", "of", "clients" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_context.py#L157-L165
crunchyroll/ef-open
efopen/ef_version.py
handle_args_and_set_context
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...
python
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...
[ "def", "handle_args_and_set_context", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"service_name\"", ",", "help", "=", "\"name of the service\"", ")", "parser", ".", "add_argument", "(", ...
Args: args: the command line args, probably passed from main() as sys.argv[1:] Returns: a populated EFVersionContext object
[ "Args", ":", "args", ":", "the", "command", "line", "args", "probably", "passed", "from", "main", "()", "as", "sys", ".", "argv", "[", "1", ":", "]", "Returns", ":", "a", "populated", "EFVersionContext", "object" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L268-L346
crunchyroll/ef-open
efopen/ef_version.py
validate_context
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...
python
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...
[ "def", "validate_context", "(", "context", ")", ":", "# Service must exist in service registry", "if", "not", "context", ".", "service_registry", ".", "service_record", "(", "context", ".", "service_name", ")", ":", "fail", "(", "\"service: {} not found in service registr...
Set the key for the current context. Args: context: a populated EFVersionContext object
[ "Set", "the", "key", "for", "the", "current", "context", ".", "Args", ":", "context", ":", "a", "populated", "EFVersionContext", "object" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L354-L376
crunchyroll/ef-open
efopen/ef_version.py
precheck_ami_id
def precheck_ami_id(context): """ Is the AMI in service the same as the AMI marked current in the version records? This tool won't update records unless the world state is coherent. Args: context: a populated EFVersionContext object Returns: True if ok to proceed Raises: RuntimeError if not ok t...
python
def precheck_ami_id(context): """ Is the AMI in service the same as the AMI marked current in the version records? This tool won't update records unless the world state is coherent. Args: context: a populated EFVersionContext object Returns: True if ok to proceed Raises: RuntimeError if not ok t...
[ "def", "precheck_ami_id", "(", "context", ")", ":", "# get the current AMI", "key", "=", "\"{}/{}\"", ".", "format", "(", "context", ".", "env", ",", "context", ".", "service_name", ")", "print_if_verbose", "(", "\"precheck_ami_id with key: {}\"", ".", "format", "...
Is the AMI in service the same as the AMI marked current in the version records? This tool won't update records unless the world state is coherent. Args: context: a populated EFVersionContext object Returns: True if ok to proceed Raises: RuntimeError if not ok to proceed
[ "Is", "the", "AMI", "in", "service", "the", "same", "as", "the", "AMI", "marked", "current", "in", "the", "version", "records?", "This", "tool", "won", "t", "update", "records", "unless", "the", "world", "state", "is", "coherent", ".", "Args", ":", "cont...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L379-L434
crunchyroll/ef-open
efopen/ef_version.py
precheck_dist_hash
def precheck_dist_hash(context): """ Is the dist in service the same as the dist marked current in the version records? This tool won't update records unless the world state is coherent. Args: context: a populated EFVersionContext object Returns: True if ok to proceed Raises: RuntimeError if not...
python
def precheck_dist_hash(context): """ Is the dist in service the same as the dist marked current in the version records? This tool won't update records unless the world state is coherent. Args: context: a populated EFVersionContext object Returns: True if ok to proceed Raises: RuntimeError if not...
[ "def", "precheck_dist_hash", "(", "context", ")", ":", "# get the current dist-hash", "key", "=", "\"{}/{}/dist-hash\"", ".", "format", "(", "context", ".", "service_name", ",", "context", ".", "env", ")", "print_if_verbose", "(", "\"precheck_dist_hash with key: {}\"", ...
Is the dist in service the same as the dist marked current in the version records? This tool won't update records unless the world state is coherent. Args: context: a populated EFVersionContext object Returns: True if ok to proceed Raises: RuntimeError if not ok to proceed
[ "Is", "the", "dist", "in", "service", "the", "same", "as", "the", "dist", "marked", "current", "in", "the", "version", "records?", "This", "tool", "won", "t", "update", "records", "unless", "the", "world", "state", "is", "coherent", ".", "Args", ":", "co...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L437-L482
crunchyroll/ef-open
efopen/ef_version.py
precheck
def precheck(context): """ calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the p...
python
def precheck(context): """ calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the p...
[ "def", "precheck", "(", "context", ")", ":", "if", "context", ".", "noprecheck", ":", "return", "True", "func_name", "=", "\"precheck_\"", "+", "context", ".", "key", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "if", "func_name", "in", "globals", "(...
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the precheck passed, or if there was...
[ "calls", "a", "function", "named", "precheck_<key", ">", "where", "<key", ">", "is", "context_key", "with", "-", "changed", "to", "_", "(", "e", ".", "g", ".", "precheck_ami_id", ")", "Checking", "function", "should", "return", "True", "if", "OK", "or", ...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L485-L503
crunchyroll/ef-open
efopen/ef_version.py
get_versions
def get_versions(context, return_stable=False): """ Get all versions of a key Args: context: a populated EFVersionContext object return_stable: (default:False) If True, stop fetching if 'stable' version is found; return only that version Returns: json list of object data sorted in reverse by last_mo...
python
def get_versions(context, return_stable=False): """ Get all versions of a key Args: context: a populated EFVersionContext object return_stable: (default:False) If True, stop fetching if 'stable' version is found; return only that version Returns: json list of object data sorted in reverse by last_mo...
[ "def", "get_versions", "(", "context", ",", "return_stable", "=", "False", ")", ":", "s3_key", "=", "\"{}/{}/{}\"", ".", "format", "(", "context", ".", "service_name", ",", "context", ".", "env", ",", "context", ".", "key", ")", "object_version_list", "=", ...
Get all versions of a key Args: context: a populated EFVersionContext object return_stable: (default:False) If True, stop fetching if 'stable' version is found; return only that version Returns: json list of object data sorted in reverse by last_modified (newest version is first). Each item is a dict: ...
[ "Get", "all", "versions", "of", "a", "key", "Args", ":", "context", ":", "a", "populated", "EFVersionContext", "object", "return_stable", ":", "(", "default", ":", "False", ")", "If", "True", "stop", "fetching", "if", "stable", "version", "is", "found", ";...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L506-L547
crunchyroll/ef-open
efopen/ef_version.py
get_version_by_value
def get_version_by_value(context, value): """ Get the latest version that matches the provided ami-id Args: context: a populated EFVersionContext object value: the value of the version to look for """ versions = get_versions(context) for version in versions: if version.value == value: retu...
python
def get_version_by_value(context, value): """ Get the latest version that matches the provided ami-id Args: context: a populated EFVersionContext object value: the value of the version to look for """ versions = get_versions(context) for version in versions: if version.value == value: retu...
[ "def", "get_version_by_value", "(", "context", ",", "value", ")", ":", "versions", "=", "get_versions", "(", "context", ")", "for", "version", "in", "versions", ":", "if", "version", ".", "value", "==", "value", ":", "return", "version", "fail", "(", "\"Di...
Get the latest version that matches the provided ami-id Args: context: a populated EFVersionContext object value: the value of the version to look for
[ "Get", "the", "latest", "version", "that", "matches", "the", "provided", "ami", "-", "id", "Args", ":", "context", ":", "a", "populated", "EFVersionContext", "object", "value", ":", "the", "value", "of", "the", "version", "to", "look", "for" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L565-L579
crunchyroll/ef-open
efopen/ef_version.py
cmd_rollback
def cmd_rollback(context): """ Roll back by finding the most recent "stable" tagged version, and putting it again, so that it's the new "current" version. Args: context: a populated EFVersionContext object """ last_stable = get_versions(context, return_stable=True) if len(last_stable) != 1: fail("...
python
def cmd_rollback(context): """ Roll back by finding the most recent "stable" tagged version, and putting it again, so that it's the new "current" version. Args: context: a populated EFVersionContext object """ last_stable = get_versions(context, return_stable=True) if len(last_stable) != 1: fail("...
[ "def", "cmd_rollback", "(", "context", ")", ":", "last_stable", "=", "get_versions", "(", "context", ",", "return_stable", "=", "True", ")", "if", "len", "(", "last_stable", ")", "!=", "1", ":", "fail", "(", "\"Didn't find a version marked stable for key: {} in en...
Roll back by finding the most recent "stable" tagged version, and putting it again, so that it's the new "current" version. Args: context: a populated EFVersionContext object
[ "Roll", "back", "by", "finding", "the", "most", "recent", "stable", "tagged", "version", "and", "putting", "it", "again", "so", "that", "it", "s", "the", "new", "current", "version", ".", "Args", ":", "context", ":", "a", "populated", "EFVersionContext", "...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L582-L598
crunchyroll/ef-open
efopen/ef_version.py
cmd_rollback_to
def cmd_rollback_to(context): """ Roll back by finding a specific version in the history of the service and putting it as the new current version. Args: context: a populated EFVersionContext object """ version = get_version_by_value(context, context.rollback_to) context.value = version.value context...
python
def cmd_rollback_to(context): """ Roll back by finding a specific version in the history of the service and putting it as the new current version. Args: context: a populated EFVersionContext object """ version = get_version_by_value(context, context.rollback_to) context.value = version.value context...
[ "def", "cmd_rollback_to", "(", "context", ")", ":", "version", "=", "get_version_by_value", "(", "context", ",", "context", ".", "rollback_to", ")", "context", ".", "value", "=", "version", ".", "value", "context", ".", "commit_hash", "=", "version", ".", "c...
Roll back by finding a specific version in the history of the service and putting it as the new current version. Args: context: a populated EFVersionContext object
[ "Roll", "back", "by", "finding", "a", "specific", "version", "in", "the", "history", "of", "the", "service", "and", "putting", "it", "as", "the", "new", "current", "version", ".", "Args", ":", "context", ":", "a", "populated", "EFVersionContext", "object" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L601-L614
crunchyroll/ef-open
efopen/ef_version.py
cmd_set
def cmd_set(context): """ Set the new "current" value for a key. If the existing current version and the new version have identical /value/ and /status, then nothing is written, to avoid stacking up redundant entreis in the version table. Args: context: a populated EFVersionContext object """ # If ke...
python
def cmd_set(context): """ Set the new "current" value for a key. If the existing current version and the new version have identical /value/ and /status, then nothing is written, to avoid stacking up redundant entreis in the version table. Args: context: a populated EFVersionContext object """ # If ke...
[ "def", "cmd_set", "(", "context", ")", ":", "# If key value is a special symbol, see if this env allows it", "if", "context", ".", "value", "in", "EFConfig", ".", "SPECIAL_VERSIONS", "and", "context", ".", "env_short", "not", "in", "EFConfig", ".", "SPECIAL_VERSION_ENVS...
Set the new "current" value for a key. If the existing current version and the new version have identical /value/ and /status, then nothing is written, to avoid stacking up redundant entreis in the version table. Args: context: a populated EFVersionContext object
[ "Set", "the", "new", "current", "value", "for", "a", "key", ".", "If", "the", "existing", "current", "version", "and", "the", "new", "version", "have", "identical", "/", "value", "/", "and", "/", "status", "then", "nothing", "is", "written", "to", "avoid...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L639-L709
crunchyroll/ef-open
efopen/ef_version.py
Version.to_json
def to_json(self): """ called by VersionEncoder.default() when doing json.dumps() on the object the json materializes in reverse order from the order used here """ return { "build_number": self._build_number, "commit_hash": self._commit_hash, "last_modified": self._last_modif...
python
def to_json(self): """ called by VersionEncoder.default() when doing json.dumps() on the object the json materializes in reverse order from the order used here """ return { "build_number": self._build_number, "commit_hash": self._commit_hash, "last_modified": self._last_modif...
[ "def", "to_json", "(", "self", ")", ":", "return", "{", "\"build_number\"", ":", "self", ".", "_build_number", ",", "\"commit_hash\"", ":", "self", ".", "_commit_hash", ",", "\"last_modified\"", ":", "self", ".", "_last_modified", ",", "\"location\"", ":", "se...
called by VersionEncoder.default() when doing json.dumps() on the object the json materializes in reverse order from the order used here
[ "called", "by", "VersionEncoder", ".", "default", "()", "when", "doing", "json", ".", "dumps", "()", "on", "the", "object", "the", "json", "materializes", "in", "reverse", "order", "from", "the", "order", "used", "here" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L211-L225
penguinmenac3/starttf
starttf/rl/agents/agent.py
Agent.learn
def learn(self, steps=1, **kwargs): """ Train the model using the environment and the agent. Note that the model might be shared between multiple agents (which most probably are of the same type) at the same time. :param steps: The number of steps to train for. """ ...
python
def learn(self, steps=1, **kwargs): """ Train the model using the environment and the agent. Note that the model might be shared between multiple agents (which most probably are of the same type) at the same time. :param steps: The number of steps to train for. """ ...
[ "def", "learn", "(", "self", ",", "steps", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# TODO add some housekeeping", "for", "i", "in", "range", "(", "steps", ")", ":", "self", ".", "step", "(", "*", "*", "kwargs", ")" ]
Train the model using the environment and the agent. Note that the model might be shared between multiple agents (which most probably are of the same type) at the same time. :param steps: The number of steps to train for.
[ "Train", "the", "model", "using", "the", "environment", "and", "the", "agent", "." ]
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/rl/agents/agent.py#L63-L73
crunchyroll/ef-open
efopen/ef_app_config_reader.py
EFAppConfigReader.get_value
def get_value(self, symbol): """ Hierarchically searches for 'symbol' in the parameters blob if there is one (would have been retrieved by 'load()'). Order is: default, <env_short>, <env> Args: symbol: the key to resolve Returns: Hierarchically resolved value for 'symbol' in the environm...
python
def get_value(self, symbol): """ Hierarchically searches for 'symbol' in the parameters blob if there is one (would have been retrieved by 'load()'). Order is: default, <env_short>, <env> Args: symbol: the key to resolve Returns: Hierarchically resolved value for 'symbol' in the environm...
[ "def", "get_value", "(", "self", ",", "symbol", ")", ":", "default", "=", "\"default\"", "if", "not", "self", ".", "parameters", ":", "return", "None", "# Hierarchically lookup the value", "result", "=", "None", "if", "default", "in", "self", ".", "parameters"...
Hierarchically searches for 'symbol' in the parameters blob if there is one (would have been retrieved by 'load()'). Order is: default, <env_short>, <env> Args: symbol: the key to resolve Returns: Hierarchically resolved value for 'symbol' in the environment set by the constructor, or None...
[ "Hierarchically", "searches", "for", "symbol", "in", "the", "parameters", "blob", "if", "there", "is", "one", "(", "would", "have", "been", "retrieved", "by", "load", "()", ")", ".", "Order", "is", ":", "default", "<env_short", ">", "<env", ">", "Args", ...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_app_config_reader.py#L68-L94
penguinmenac3/starttf
starttf/losses/utils.py
overlay_classification_on_image
def overlay_classification_on_image(classification, rgb_image, scale=1): """ Overlay a classification either 1 channel or 3 channels on an input image. :param classification: The classification tensor of shape [bach_size, v, u, 1] or [batch_size, v, u, 3]. The value range of the c...
python
def overlay_classification_on_image(classification, rgb_image, scale=1): """ Overlay a classification either 1 channel or 3 channels on an input image. :param classification: The classification tensor of shape [bach_size, v, u, 1] or [batch_size, v, u, 3]. The value range of the c...
[ "def", "overlay_classification_on_image", "(", "classification", ",", "rgb_image", ",", "scale", "=", "1", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"debug_overlay\"", ")", ":", "if", "not", "classification", ".", "get_shape", "(", ")", "[", "3", ...
Overlay a classification either 1 channel or 3 channels on an input image. :param classification: The classification tensor of shape [bach_size, v, u, 1] or [batch_size, v, u, 3]. The value range of the classification tensor is supposed to be 0 to 1. :param rgb_image: The input image ...
[ "Overlay", "a", "classification", "either", "1", "channel", "or", "3", "channels", "on", "an", "input", "image", ".", ":", "param", "classification", ":", "The", "classification", "tensor", "of", "shape", "[", "bach_size", "v", "u", "1", "]", "or", "[", ...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/utils.py#L26-L50
penguinmenac3/starttf
starttf/losses/utils.py
inflate_to_one_hot
def inflate_to_one_hot(tensor, classes): """ Converts a tensor with index form to a one hot tensor. :param tensor: A tensor of shape [batch, h, w, 1] :param classes: The number of classes that exist. (length of one hot encoding) :return: A tensor of shape [batch, h, w, classes]. """ one_hot ...
python
def inflate_to_one_hot(tensor, classes): """ Converts a tensor with index form to a one hot tensor. :param tensor: A tensor of shape [batch, h, w, 1] :param classes: The number of classes that exist. (length of one hot encoding) :return: A tensor of shape [batch, h, w, classes]. """ one_hot ...
[ "def", "inflate_to_one_hot", "(", "tensor", ",", "classes", ")", ":", "one_hot", "=", "tf", ".", "one_hot", "(", "tensor", ",", "classes", ")", "shape", "=", "one_hot", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "return", "tf", ".", "reshape...
Converts a tensor with index form to a one hot tensor. :param tensor: A tensor of shape [batch, h, w, 1] :param classes: The number of classes that exist. (length of one hot encoding) :return: A tensor of shape [batch, h, w, classes].
[ "Converts", "a", "tensor", "with", "index", "form", "to", "a", "one", "hot", "tensor", ".", ":", "param", "tensor", ":", "A", "tensor", "of", "shape", "[", "batch", "h", "w", "1", "]", ":", "param", "classes", ":", "The", "number", "of", "classes", ...
train
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/utils.py#L53-L62
crunchyroll/ef-open
efopen/ef_config_resolver.py
EFConfigResolver.accountaliasofenv
def accountaliasofenv(self, lookup, default=None): """ Args: lookup: ENV_SHORT name of an env, such as: 'prod' or 'proto' default: the optional value to return if lookup failed; returns None if not set Returns: The account alias of the account that hosts the env named in lookupor default/N...
python
def accountaliasofenv(self, lookup, default=None): """ Args: lookup: ENV_SHORT name of an env, such as: 'prod' or 'proto' default: the optional value to return if lookup failed; returns None if not set Returns: The account alias of the account that hosts the env named in lookupor default/N...
[ "def", "accountaliasofenv", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "if", "lookup", "in", "EFConfig", ".", "ENV_ACCOUNT_MAP", ":", "return", "EFConfig", ".", "ENV_ACCOUNT_MAP", "[", "lookup", "]", "else", ":", "return", "None" ]
Args: lookup: ENV_SHORT name of an env, such as: 'prod' or 'proto' default: the optional value to return if lookup failed; returns None if not set Returns: The account alias of the account that hosts the env named in lookupor default/None if no match found
[ "Args", ":", "lookup", ":", "ENV_SHORT", "name", "of", "an", "env", "such", "as", ":", "prod", "or", "proto", "default", ":", "the", "optional", "value", "to", "return", "if", "lookup", "failed", ";", "returns", "None", "if", "not", "set", "Returns", "...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_config_resolver.py#L31-L42
crunchyroll/ef-open
efopen/ef_config_resolver.py
EFConfigResolver.customdata
def customdata(self, lookup, default=None): """ Args: lookup: the custom data file default: the optional value to return if lookup failed; returns None if not set Returns: The custom data returned from the file 'lookup' or default/None if no match found """ try: if lookup in ...
python
def customdata(self, lookup, default=None): """ Args: lookup: the custom data file default: the optional value to return if lookup failed; returns None if not set Returns: The custom data returned from the file 'lookup' or default/None if no match found """ try: if lookup in ...
[ "def", "customdata", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "try", ":", "if", "lookup", "in", "EFConfig", ".", "CUSTOM_DATA", ":", "return", "EFConfig", ".", "CUSTOM_DATA", "[", "lookup", "]", "else", ":", "return", "default",...
Args: lookup: the custom data file default: the optional value to return if lookup failed; returns None if not set Returns: The custom data returned from the file 'lookup' or default/None if no match found
[ "Args", ":", "lookup", ":", "the", "custom", "data", "file", "default", ":", "the", "optional", "value", "to", "return", "if", "lookup", "failed", ";", "returns", "None", "if", "not", "set", "Returns", ":", "The", "custom", "data", "returned", "from", "t...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_config_resolver.py#L44-L58
crunchyroll/ef-open
efopen/ef_utils.py
fail
def fail(message, exception_data=None): """ Print a failure message and exit nonzero """ print(message, file=sys.stderr) if exception_data: print(repr(exception_data)) sys.exit(1)
python
def fail(message, exception_data=None): """ Print a failure message and exit nonzero """ print(message, file=sys.stderr) if exception_data: print(repr(exception_data)) sys.exit(1)
[ "def", "fail", "(", "message", ",", "exception_data", "=", "None", ")", ":", "print", "(", "message", ",", "file", "=", "sys", ".", "stderr", ")", "if", "exception_data", ":", "print", "(", "repr", "(", "exception_data", ")", ")", "sys", ".", "exit", ...
Print a failure message and exit nonzero
[ "Print", "a", "failure", "message", "and", "exit", "nonzero" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L47-L54
crunchyroll/ef-open
efopen/ef_utils.py
http_get_metadata
def http_get_metadata(metadata_path, timeout=__HTTP_DEFAULT_TIMEOUT_SEC): """ Fetch AWS metadata from http://169.254.169.254/latest/meta-data/<metadata_path> ARGS: metadata_path - the optional path and required key to the EC2 metadata (e.g. "instance-id") RETURN: response content on success RAISE: ...
python
def http_get_metadata(metadata_path, timeout=__HTTP_DEFAULT_TIMEOUT_SEC): """ Fetch AWS metadata from http://169.254.169.254/latest/meta-data/<metadata_path> ARGS: metadata_path - the optional path and required key to the EC2 metadata (e.g. "instance-id") RETURN: response content on success RAISE: ...
[ "def", "http_get_metadata", "(", "metadata_path", ",", "timeout", "=", "__HTTP_DEFAULT_TIMEOUT_SEC", ")", ":", "metadata_path", "=", "__METADATA_PREFIX", "+", "metadata_path", "try", ":", "response", "=", "urllib2", ".", "urlopen", "(", "metadata_path", ",", "None",...
Fetch AWS metadata from http://169.254.169.254/latest/meta-data/<metadata_path> ARGS: metadata_path - the optional path and required key to the EC2 metadata (e.g. "instance-id") RETURN: response content on success RAISE: URLError if there was a problem reading metadata
[ "Fetch", "AWS", "metadata", "from", "http", ":", "//", "169", ".", "254", ".", "169", ".", "254", "/", "latest", "/", "meta", "-", "data", "/", "<metadata_path", ">", "ARGS", ":", "metadata_path", "-", "the", "optional", "path", "and", "required", "key...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L56-L73
crunchyroll/ef-open
efopen/ef_utils.py
is_in_virtualbox
def is_in_virtualbox(): """ Is the current environment a virtualbox instance? Returns a boolean Raises IOError if the necessary tooling isn't available """ if not isfile(__VIRT_WHAT) or not access(__VIRT_WHAT, X_OK): raise IOError("virt-what not available") try: return subprocess.check_output(["su...
python
def is_in_virtualbox(): """ Is the current environment a virtualbox instance? Returns a boolean Raises IOError if the necessary tooling isn't available """ if not isfile(__VIRT_WHAT) or not access(__VIRT_WHAT, X_OK): raise IOError("virt-what not available") try: return subprocess.check_output(["su...
[ "def", "is_in_virtualbox", "(", ")", ":", "if", "not", "isfile", "(", "__VIRT_WHAT", ")", "or", "not", "access", "(", "__VIRT_WHAT", ",", "X_OK", ")", ":", "raise", "IOError", "(", "\"virt-what not available\"", ")", "try", ":", "return", "subprocess", ".", ...
Is the current environment a virtualbox instance? Returns a boolean Raises IOError if the necessary tooling isn't available
[ "Is", "the", "current", "environment", "a", "virtualbox", "instance?", "Returns", "a", "boolean", "Raises", "IOError", "if", "the", "necessary", "tooling", "isn", "t", "available" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L75-L86
crunchyroll/ef-open
efopen/ef_utils.py
whereami
def whereami(): """ Determine if this is an ec2 instance or "running locally" Returns: "ec2" - this is an ec2 instance "virtualbox-kvm" - kernel VM (virtualbox with vagrant) "local" - running locally and not in a known VM "unknown" - I have no idea where I am """ # If the metadata endpoint res...
python
def whereami(): """ Determine if this is an ec2 instance or "running locally" Returns: "ec2" - this is an ec2 instance "virtualbox-kvm" - kernel VM (virtualbox with vagrant) "local" - running locally and not in a known VM "unknown" - I have no idea where I am """ # If the metadata endpoint res...
[ "def", "whereami", "(", ")", ":", "# If the metadata endpoint responds, this is an EC2 instance", "# If it doesn't, we can safely say this isn't EC2 and try the other options", "try", ":", "response", "=", "http_get_metadata", "(", "\"instance-id\"", ",", "1", ")", "if", "respons...
Determine if this is an ec2 instance or "running locally" Returns: "ec2" - this is an ec2 instance "virtualbox-kvm" - kernel VM (virtualbox with vagrant) "local" - running locally and not in a known VM "unknown" - I have no idea where I am
[ "Determine", "if", "this", "is", "an", "ec2", "instance", "or", "running", "locally", "Returns", ":", "ec2", "-", "this", "is", "an", "ec2", "instance", "virtualbox", "-", "kvm", "-", "kernel", "VM", "(", "virtualbox", "with", "vagrant", ")", "local", "-...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L88-L119
crunchyroll/ef-open
efopen/ef_utils.py
http_get_instance_env
def http_get_instance_env(): """ Returns: just the env this ec2 instance is in. Doesn't require API access like get_instance_aws_context does Example return value: "staging" """ try: info = json.loads(http_get_metadata('iam/info')) except Exception as error: raise IOError("Error looking up metadata:...
python
def http_get_instance_env(): """ Returns: just the env this ec2 instance is in. Doesn't require API access like get_instance_aws_context does Example return value: "staging" """ try: info = json.loads(http_get_metadata('iam/info')) except Exception as error: raise IOError("Error looking up metadata:...
[ "def", "http_get_instance_env", "(", ")", ":", "try", ":", "info", "=", "json", ".", "loads", "(", "http_get_metadata", "(", "'iam/info'", ")", ")", "except", "Exception", "as", "error", ":", "raise", "IOError", "(", "\"Error looking up metadata:iam/info: \"", "...
Returns: just the env this ec2 instance is in. Doesn't require API access like get_instance_aws_context does Example return value: "staging"
[ "Returns", ":", "just", "the", "env", "this", "ec2", "instance", "is", "in", ".", "Doesn", "t", "require", "API", "access", "like", "get_instance_aws_context", "does", "Example", "return", "value", ":", "staging" ]
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L121-L130
crunchyroll/ef-open
efopen/ef_utils.py
get_instance_aws_context
def get_instance_aws_context(ec2_client): """ Returns: a dictionary of aws context dictionary will contain these entries: region, instance_id, account, role, env, env_short, service Raises: IOError if couldn't read metadata or lookup attempt failed """ result = {} try: result["region"] = http_ge...
python
def get_instance_aws_context(ec2_client): """ Returns: a dictionary of aws context dictionary will contain these entries: region, instance_id, account, role, env, env_short, service Raises: IOError if couldn't read metadata or lookup attempt failed """ result = {} try: result["region"] = http_ge...
[ "def", "get_instance_aws_context", "(", "ec2_client", ")", ":", "result", "=", "{", "}", "try", ":", "result", "[", "\"region\"", "]", "=", "http_get_metadata", "(", "\"placement/availability-zone/\"", ")", "result", "[", "\"region\"", "]", "=", "result", "[", ...
Returns: a dictionary of aws context dictionary will contain these entries: region, instance_id, account, role, env, env_short, service Raises: IOError if couldn't read metadata or lookup attempt failed
[ "Returns", ":", "a", "dictionary", "of", "aws", "context", "dictionary", "will", "contain", "these", "entries", ":", "region", "instance_id", "account", "role", "env", "env_short", "service", "Raises", ":", "IOError", "if", "couldn", "t", "read", "metadata", "...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L143-L170
crunchyroll/ef-open
efopen/ef_utils.py
pull_repo
def pull_repo(): """ Pulls latest version of EF_REPO_BRANCH from EF_REPO (as set in ef_config.py) if client is in EF_REPO and on the branch EF_REPO_BRANCH Raises: RuntimeError with message if not in the correct repo on the correct branch """ try: current_repo = subprocess.check_output(["git", "remot...
python
def pull_repo(): """ Pulls latest version of EF_REPO_BRANCH from EF_REPO (as set in ef_config.py) if client is in EF_REPO and on the branch EF_REPO_BRANCH Raises: RuntimeError with message if not in the correct repo on the correct branch """ try: current_repo = subprocess.check_output(["git", "remot...
[ "def", "pull_repo", "(", ")", ":", "try", ":", "current_repo", "=", "subprocess", ".", "check_output", "(", "[", "\"git\"", ",", "\"remote\"", ",", "\"-v\"", ",", "\"show\"", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "error", ":", ...
Pulls latest version of EF_REPO_BRANCH from EF_REPO (as set in ef_config.py) if client is in EF_REPO and on the branch EF_REPO_BRANCH Raises: RuntimeError with message if not in the correct repo on the correct branch
[ "Pulls", "latest", "version", "of", "EF_REPO_BRANCH", "from", "EF_REPO", "(", "as", "set", "in", "ef_config", ".", "py", ")", "if", "client", "is", "in", "EF_REPO", "and", "on", "the", "branch", "EF_REPO_BRANCH", "Raises", ":", "RuntimeError", "with", "messa...
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L172-L195