partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
HTTPRouter.add_response_headers
Adds the specified response headers while keeping existing ones in-tact
hug/routing.py
def add_response_headers(self, headers, **overrides): """Adds the specified response headers while keeping existing ones in-tact""" response_headers = self.route.get('response_headers', {}).copy() response_headers.update(headers) return self.where(response_headers=response_headers, **ove...
def add_response_headers(self, headers, **overrides): """Adds the specified response headers while keeping existing ones in-tact""" response_headers = self.route.get('response_headers', {}).copy() response_headers.update(headers) return self.where(response_headers=response_headers, **ove...
[ "Adds", "the", "specified", "response", "headers", "while", "keeping", "existing", "ones", "in", "-", "tact" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L242-L246
[ "def", "add_response_headers", "(", "self", ",", "headers", ",", "*", "*", "overrides", ")", ":", "response_headers", "=", "self", ".", "route", ".", "get", "(", "'response_headers'", ",", "{", "}", ")", ".", "copy", "(", ")", "response_headers", ".", "u...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPRouter.cache
Convenience method for quickly adding cache header to route
hug/routing.py
def cache(self, private=False, max_age=31536000, s_maxage=None, no_cache=False, no_store=False, must_revalidate=False, **overrides): """Convenience method for quickly adding cache header to route""" parts = ('private' if private else 'public', 'max-age={0}'.format(max_age), ...
def cache(self, private=False, max_age=31536000, s_maxage=None, no_cache=False, no_store=False, must_revalidate=False, **overrides): """Convenience method for quickly adding cache header to route""" parts = ('private' if private else 'public', 'max-age={0}'.format(max_age), ...
[ "Convenience", "method", "for", "quickly", "adding", "cache", "header", "to", "route" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L248-L254
[ "def", "cache", "(", "self", ",", "private", "=", "False", ",", "max_age", "=", "31536000", ",", "s_maxage", "=", "None", ",", "no_cache", "=", "False", ",", "no_store", "=", "False", ",", "must_revalidate", "=", "False", ",", "*", "*", "overrides", ")...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPRouter.allow_origins
Convenience method for quickly allowing other resources to access this one
hug/routing.py
def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides): """Convenience method for quickly allowing other resources to access this one""" response_headers = {} if origins: @hug.response_middleware() def process_data(reque...
def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides): """Convenience method for quickly allowing other resources to access this one""" response_headers = {} if origins: @hug.response_middleware() def process_data(reque...
[ "Convenience", "method", "for", "quickly", "allowing", "other", "resources", "to", "access", "this", "one" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L256-L277
[ "def", "allow_origins", "(", "self", ",", "*", "origins", ",", "methods", "=", "None", ",", "max_age", "=", "None", ",", "credentials", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "overrides", ")", ":", "response_headers", "=", "{", "}", ...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.get
Sets the acceptable HTTP method to a GET
hug/routing.py
def get(self, urls=None, **overrides): """Sets the acceptable HTTP method to a GET""" if urls is not None: overrides['urls'] = urls return self.where(accept='GET', **overrides)
def get(self, urls=None, **overrides): """Sets the acceptable HTTP method to a GET""" if urls is not None: overrides['urls'] = urls return self.where(accept='GET', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "a", "GET" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L431-L435
[ "def", "get", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'GET'", ",", "*"...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.delete
Sets the acceptable HTTP method to DELETE
hug/routing.py
def delete(self, urls=None, **overrides): """Sets the acceptable HTTP method to DELETE""" if urls is not None: overrides['urls'] = urls return self.where(accept='DELETE', **overrides)
def delete(self, urls=None, **overrides): """Sets the acceptable HTTP method to DELETE""" if urls is not None: overrides['urls'] = urls return self.where(accept='DELETE', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "DELETE" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L437-L441
[ "def", "delete", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'DELETE'", ",",...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.post
Sets the acceptable HTTP method to POST
hug/routing.py
def post(self, urls=None, **overrides): """Sets the acceptable HTTP method to POST""" if urls is not None: overrides['urls'] = urls return self.where(accept='POST', **overrides)
def post(self, urls=None, **overrides): """Sets the acceptable HTTP method to POST""" if urls is not None: overrides['urls'] = urls return self.where(accept='POST', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "POST" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L443-L447
[ "def", "post", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'POST'", ",", "...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.put
Sets the acceptable HTTP method to PUT
hug/routing.py
def put(self, urls=None, **overrides): """Sets the acceptable HTTP method to PUT""" if urls is not None: overrides['urls'] = urls return self.where(accept='PUT', **overrides)
def put(self, urls=None, **overrides): """Sets the acceptable HTTP method to PUT""" if urls is not None: overrides['urls'] = urls return self.where(accept='PUT', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "PUT" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L449-L453
[ "def", "put", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'PUT'", ",", "*"...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.trace
Sets the acceptable HTTP method to TRACE
hug/routing.py
def trace(self, urls=None, **overrides): """Sets the acceptable HTTP method to TRACE""" if urls is not None: overrides['urls'] = urls return self.where(accept='TRACE', **overrides)
def trace(self, urls=None, **overrides): """Sets the acceptable HTTP method to TRACE""" if urls is not None: overrides['urls'] = urls return self.where(accept='TRACE', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "TRACE" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L455-L459
[ "def", "trace", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'TRACE'", ",", ...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.patch
Sets the acceptable HTTP method to PATCH
hug/routing.py
def patch(self, urls=None, **overrides): """Sets the acceptable HTTP method to PATCH""" if urls is not None: overrides['urls'] = urls return self.where(accept='PATCH', **overrides)
def patch(self, urls=None, **overrides): """Sets the acceptable HTTP method to PATCH""" if urls is not None: overrides['urls'] = urls return self.where(accept='PATCH', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "PATCH" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L461-L465
[ "def", "patch", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'PATCH'", ",", ...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.options
Sets the acceptable HTTP method to OPTIONS
hug/routing.py
def options(self, urls=None, **overrides): """Sets the acceptable HTTP method to OPTIONS""" if urls is not None: overrides['urls'] = urls return self.where(accept='OPTIONS', **overrides)
def options(self, urls=None, **overrides): """Sets the acceptable HTTP method to OPTIONS""" if urls is not None: overrides['urls'] = urls return self.where(accept='OPTIONS', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "OPTIONS" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L467-L471
[ "def", "options", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'OPTIONS'", ",...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.head
Sets the acceptable HTTP method to HEAD
hug/routing.py
def head(self, urls=None, **overrides): """Sets the acceptable HTTP method to HEAD""" if urls is not None: overrides['urls'] = urls return self.where(accept='HEAD', **overrides)
def head(self, urls=None, **overrides): """Sets the acceptable HTTP method to HEAD""" if urls is not None: overrides['urls'] = urls return self.where(accept='HEAD', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "HEAD" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L473-L477
[ "def", "head", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'HEAD'", ",", "...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
URLRouter.connect
Sets the acceptable HTTP method to CONNECT
hug/routing.py
def connect(self, urls=None, **overrides): """Sets the acceptable HTTP method to CONNECT""" if urls is not None: overrides['urls'] = urls return self.where(accept='CONNECT', **overrides)
def connect(self, urls=None, **overrides): """Sets the acceptable HTTP method to CONNECT""" if urls is not None: overrides['urls'] = urls return self.where(accept='CONNECT', **overrides)
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "CONNECT" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L479-L483
[ "def", "connect", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'CONNECT'", ",...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
Object.http_methods
Creates routes from a class, where the class method names should line up to HTTP METHOD types
hug/route.py
def http_methods(self, urls=None, **route_data): """Creates routes from a class, where the class method names should line up to HTTP METHOD types""" def decorator(class_definition): instance = class_definition if isinstance(class_definition, type): instance = clas...
def http_methods(self, urls=None, **route_data): """Creates routes from a class, where the class method names should line up to HTTP METHOD types""" def decorator(class_definition): instance = class_definition if isinstance(class_definition, type): instance = clas...
[ "Creates", "routes", "from", "a", "class", "where", "the", "class", "method", "names", "should", "line", "up", "to", "HTTP", "METHOD", "types" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L72-L95
[ "def", "http_methods", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "route_data", ")", ":", "def", "decorator", "(", "class_definition", ")", ":", "instance", "=", "class_definition", "if", "isinstance", "(", "class_definition", ",", "type", ")", ...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
Object.cli
Registers a method on an Object as a CLI route
hug/route.py
def cli(self, method): """Registers a method on an Object as a CLI route""" routes = getattr(method, '_hug_cli_routes', []) routes.append(self.route) method._hug_cli_routes = routes return method
def cli(self, method): """Registers a method on an Object as a CLI route""" routes = getattr(method, '_hug_cli_routes', []) routes.append(self.route) method._hug_cli_routes = routes return method
[ "Registers", "a", "method", "on", "an", "Object", "as", "a", "CLI", "route" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L97-L102
[ "def", "cli", "(", "self", ",", "method", ")", ":", "routes", "=", "getattr", "(", "method", ",", "'_hug_cli_routes'", ",", "[", "]", ")", "routes", ".", "append", "(", "self", ".", "route", ")", "method", ".", "_hug_cli_routes", "=", "routes", "return...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.http
Starts the process of building a new HTTP route linked to this API instance
hug/route.py
def http(self, *args, **kwargs): """Starts the process of building a new HTTP route linked to this API instance""" kwargs['api'] = self.api return http(*args, **kwargs)
def http(self, *args, **kwargs): """Starts the process of building a new HTTP route linked to this API instance""" kwargs['api'] = self.api return http(*args, **kwargs)
[ "Starts", "the", "process", "of", "building", "a", "new", "HTTP", "route", "linked", "to", "this", "API", "instance" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L114-L117
[ "def", "http", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "http", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.not_found
Defines the handler that should handle not found requests against this API
hug/route.py
def not_found(self, *args, **kwargs): """Defines the handler that should handle not found requests against this API""" kwargs['api'] = self.api return not_found(*args, **kwargs)
def not_found(self, *args, **kwargs): """Defines the handler that should handle not found requests against this API""" kwargs['api'] = self.api return not_found(*args, **kwargs)
[ "Defines", "the", "handler", "that", "should", "handle", "not", "found", "requests", "against", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L126-L129
[ "def", "not_found", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "not_found", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.static
Define the routes to static files the API should expose
hug/route.py
def static(self, *args, **kwargs): """Define the routes to static files the API should expose""" kwargs['api'] = self.api return static(*args, **kwargs)
def static(self, *args, **kwargs): """Define the routes to static files the API should expose""" kwargs['api'] = self.api return static(*args, **kwargs)
[ "Define", "the", "routes", "to", "static", "files", "the", "API", "should", "expose" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L131-L134
[ "def", "static", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "static", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.sink
Define URL prefixes/handler matches where everything under the URL prefix should be handled
hug/route.py
def sink(self, *args, **kwargs): """Define URL prefixes/handler matches where everything under the URL prefix should be handled""" kwargs['api'] = self.api return sink(*args, **kwargs)
def sink(self, *args, **kwargs): """Define URL prefixes/handler matches where everything under the URL prefix should be handled""" kwargs['api'] = self.api return sink(*args, **kwargs)
[ "Define", "URL", "prefixes", "/", "handler", "matches", "where", "everything", "under", "the", "URL", "prefix", "should", "be", "handled" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L136-L139
[ "def", "sink", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "sink", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.exception
Defines how this API should handle the provided exceptions
hug/route.py
def exception(self, *args, **kwargs): """Defines how this API should handle the provided exceptions""" kwargs['api'] = self.api return exception(*args, **kwargs)
def exception(self, *args, **kwargs): """Defines how this API should handle the provided exceptions""" kwargs['api'] = self.api return exception(*args, **kwargs)
[ "Defines", "how", "this", "API", "should", "handle", "the", "provided", "exceptions" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L141-L144
[ "def", "exception", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "exception", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.cli
Defines a CLI function that should be routed by this API
hug/route.py
def cli(self, *args, **kwargs): """Defines a CLI function that should be routed by this API""" kwargs['api'] = self.api return cli(*args, **kwargs)
def cli(self, *args, **kwargs): """Defines a CLI function that should be routed by this API""" kwargs['api'] = self.api return cli(*args, **kwargs)
[ "Defines", "a", "CLI", "function", "that", "should", "be", "routed", "by", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L146-L149
[ "def", "cli", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "cli", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.object
Registers a class based router to this API
hug/route.py
def object(self, *args, **kwargs): """Registers a class based router to this API""" kwargs['api'] = self.api return Object(*args, **kwargs)
def object(self, *args, **kwargs): """Registers a class based router to this API""" kwargs['api'] = self.api return Object(*args, **kwargs)
[ "Registers", "a", "class", "based", "router", "to", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/route.py#L151-L154
[ "def", "object", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "Object", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.urls
Returns a generator of all URLs attached to this API
hug/api.py
def urls(self): """Returns a generator of all URLs attached to this API""" for base_url, mapping in self.routes.items(): for url, _ in mapping.items(): yield base_url + url
def urls(self): """Returns a generator of all URLs attached to this API""" for base_url, mapping in self.routes.items(): for url, _ in mapping.items(): yield base_url + url
[ "Returns", "a", "generator", "of", "all", "URLs", "attached", "to", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L102-L106
[ "def", "urls", "(", "self", ")", ":", "for", "base_url", ",", "mapping", "in", "self", ".", "routes", ".", "items", "(", ")", ":", "for", "url", ",", "_", "in", "mapping", ".", "items", "(", ")", ":", "yield", "base_url", "+", "url" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.handlers
Returns all registered handlers attached to this API
hug/api.py
def handlers(self): """Returns all registered handlers attached to this API""" used = [] for base_url, mapping in self.routes.items(): for url, methods in mapping.items(): for method, versions in methods.items(): for version, handler in versions.it...
def handlers(self): """Returns all registered handlers attached to this API""" used = [] for base_url, mapping in self.routes.items(): for url, methods in mapping.items(): for method, versions in methods.items(): for version, handler in versions.it...
[ "Returns", "all", "registered", "handlers", "attached", "to", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L108-L117
[ "def", "handlers", "(", "self", ")", ":", "used", "=", "[", "]", "for", "base_url", ",", "mapping", "in", "self", ".", "routes", ".", "items", "(", ")", ":", "for", "url", ",", "methods", "in", "mapping", ".", "items", "(", ")", ":", "for", "meth...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.input_format
Returns the set input_format handler for the given content_type
hug/api.py
def input_format(self, content_type): """Returns the set input_format handler for the given content_type""" return getattr(self, '_input_format', {}).get(content_type, hug.defaults.input_format.get(content_type, None))
def input_format(self, content_type): """Returns the set input_format handler for the given content_type""" return getattr(self, '_input_format', {}).get(content_type, hug.defaults.input_format.get(content_type, None))
[ "Returns", "the", "set", "input_format", "handler", "for", "the", "given", "content_type" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L119-L121
[ "def", "input_format", "(", "self", ",", "content_type", ")", ":", "return", "getattr", "(", "self", ",", "'_input_format'", ",", "{", "}", ")", ".", "get", "(", "content_type", ",", "hug", ".", "defaults", ".", "input_format", ".", "get", "(", "content_...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.set_input_format
Sets an input format handler for this Hug API, given the specified content_type
hug/api.py
def set_input_format(self, content_type, handler): """Sets an input format handler for this Hug API, given the specified content_type""" if getattr(self, '_input_format', None) is None: self._input_format = {} self._input_format[content_type] = handler
def set_input_format(self, content_type, handler): """Sets an input format handler for this Hug API, given the specified content_type""" if getattr(self, '_input_format', None) is None: self._input_format = {} self._input_format[content_type] = handler
[ "Sets", "an", "input", "format", "handler", "for", "this", "Hug", "API", "given", "the", "specified", "content_type" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L123-L127
[ "def", "set_input_format", "(", "self", ",", "content_type", ",", "handler", ")", ":", "if", "getattr", "(", "self", ",", "'_input_format'", ",", "None", ")", "is", "None", ":", "self", ".", "_input_format", "=", "{", "}", "self", ".", "_input_format", "...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.add_middleware
Adds a middleware object used to process all incoming requests against the API
hug/api.py
def add_middleware(self, middleware): """Adds a middleware object used to process all incoming requests against the API""" if self.middleware is None: self._middleware = [] self.middleware.append(middleware)
def add_middleware(self, middleware): """Adds a middleware object used to process all incoming requests against the API""" if self.middleware is None: self._middleware = [] self.middleware.append(middleware)
[ "Adds", "a", "middleware", "object", "used", "to", "process", "all", "incoming", "requests", "against", "the", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L133-L137
[ "def", "add_middleware", "(", "self", ",", "middleware", ")", ":", "if", "self", ".", "middleware", "is", "None", ":", "self", ".", "_middleware", "=", "[", "]", "self", ".", "middleware", ".", "append", "(", "middleware", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.add_exception_handler
Adds a error handler to the hug api
hug/api.py
def add_exception_handler(self, exception_type, error_handler, versions=(None, )): """Adds a error handler to the hug api""" versions = (versions, ) if not isinstance(versions, (tuple, list)) else versions if not hasattr(self, '_exception_handlers'): self._exception_handlers = {} ...
def add_exception_handler(self, exception_type, error_handler, versions=(None, )): """Adds a error handler to the hug api""" versions = (versions, ) if not isinstance(versions, (tuple, list)) else versions if not hasattr(self, '_exception_handlers'): self._exception_handlers = {} ...
[ "Adds", "a", "error", "handler", "to", "the", "hug", "api" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L150-L158
[ "def", "add_exception_handler", "(", "self", ",", "exception_type", ",", "error_handler", ",", "versions", "=", "(", "None", ",", ")", ")", ":", "versions", "=", "(", "versions", ",", ")", "if", "not", "isinstance", "(", "versions", ",", "(", "tuple", ",...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.extend
Adds handlers from a different Hug API to this one - to create a single API
hug/api.py
def extend(self, http_api, route="", base_url="", **kwargs): """Adds handlers from a different Hug API to this one - to create a single API""" self.versions.update(http_api.versions) base_url = base_url or self.base_url for router_base_url, routes in http_api.routes.items(): ...
def extend(self, http_api, route="", base_url="", **kwargs): """Adds handlers from a different Hug API to this one - to create a single API""" self.versions.update(http_api.versions) base_url = base_url or self.base_url for router_base_url, routes in http_api.routes.items(): ...
[ "Adds", "handlers", "from", "a", "different", "Hug", "API", "to", "this", "one", "-", "to", "create", "a", "single", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L160-L193
[ "def", "extend", "(", "self", ",", "http_api", ",", "route", "=", "\"\"", ",", "base_url", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "self", ".", "versions", ".", "update", "(", "http_api", ".", "versions", ")", "base_url", "=", "base_url", "or...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.set_not_found_handler
Sets the not_found handler for the specified version of the api
hug/api.py
def set_not_found_handler(self, handler, version=None): """Sets the not_found handler for the specified version of the api""" if not self.not_found_handlers: self._not_found_handlers = {} self.not_found_handlers[version] = handler
def set_not_found_handler(self, handler, version=None): """Sets the not_found handler for the specified version of the api""" if not self.not_found_handlers: self._not_found_handlers = {} self.not_found_handlers[version] = handler
[ "Sets", "the", "not_found", "handler", "for", "the", "specified", "version", "of", "the", "api" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L199-L204
[ "def", "set_not_found_handler", "(", "self", ",", "handler", ",", "version", "=", "None", ")", ":", "if", "not", "self", ".", "not_found_handlers", ":", "self", ".", "_not_found_handlers", "=", "{", "}", "self", ".", "not_found_handlers", "[", "version", "]"...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.documentation
Generates and returns documentation for this API endpoint
hug/api.py
def documentation(self, base_url=None, api_version=None, prefix=""): """Generates and returns documentation for this API endpoint""" documentation = OrderedDict() base_url = self.base_url if base_url is None else base_url overview = self.api.doc if overview: documenta...
def documentation(self, base_url=None, api_version=None, prefix=""): """Generates and returns documentation for this API endpoint""" documentation = OrderedDict() base_url = self.base_url if base_url is None else base_url overview = self.api.doc if overview: documenta...
[ "Generates", "and", "returns", "documentation", "for", "this", "API", "endpoint" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L206-L247
[ "def", "documentation", "(", "self", ",", "base_url", "=", "None", ",", "api_version", "=", "None", ",", "prefix", "=", "\"\"", ")", ":", "documentation", "=", "OrderedDict", "(", ")", "base_url", "=", "self", ".", "base_url", "if", "base_url", "is", "No...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.serve
Runs the basic hug development server against this API
hug/api.py
def serve(self, host='', port=8000, no_documentation=False, display_intro=True): """Runs the basic hug development server against this API""" if no_documentation: api = self.server(None) else: api = self.server() if display_intro: print(INTRO) ...
def serve(self, host='', port=8000, no_documentation=False, display_intro=True): """Runs the basic hug development server against this API""" if no_documentation: api = self.server(None) else: api = self.server() if display_intro: print(INTRO) ...
[ "Runs", "the", "basic", "hug", "development", "server", "against", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L249-L261
[ "def", "serve", "(", "self", ",", "host", "=", "''", ",", "port", "=", "8000", ",", "no_documentation", "=", "False", ",", "display_intro", "=", "True", ")", ":", "if", "no_documentation", ":", "api", "=", "self", ".", "server", "(", "None", ")", "el...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.determine_version
Determines the appropriate version given the set api_version, the request header, and URL query params
hug/api.py
def determine_version(self, request, api_version=None): """Determines the appropriate version given the set api_version, the request header, and URL query params""" if api_version is False: api_version = None for version in self.versions: if version and "v{0}".for...
def determine_version(self, request, api_version=None): """Determines the appropriate version given the set api_version, the request header, and URL query params""" if api_version is False: api_version = None for version in self.versions: if version and "v{0}".for...
[ "Determines", "the", "appropriate", "version", "given", "the", "set", "api_version", "the", "request", "header", "and", "URL", "query", "params" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L268-L292
[ "def", "determine_version", "(", "self", ",", "request", ",", "api_version", "=", "None", ")", ":", "if", "api_version", "is", "False", ":", "api_version", "=", "None", "for", "version", "in", "self", ".", "versions", ":", "if", "version", "and", "\"v{0}\"...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.documentation_404
Returns a smart 404 page that contains documentation for the written API
hug/api.py
def documentation_404(self, base_url=None): """Returns a smart 404 page that contains documentation for the written API""" base_url = self.base_url if base_url is None else base_url def handle_404(request, response, *args, **kwargs): url_prefix = request.forwarded_uri[:-1] ...
def documentation_404(self, base_url=None): """Returns a smart 404 page that contains documentation for the written API""" base_url = self.base_url if base_url is None else base_url def handle_404(request, response, *args, **kwargs): url_prefix = request.forwarded_uri[:-1] ...
[ "Returns", "a", "smart", "404", "page", "that", "contains", "documentation", "for", "the", "written", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L294-L319
[ "def", "documentation_404", "(", "self", ",", "base_url", "=", "None", ")", ":", "base_url", "=", "self", ".", "base_url", "if", "base_url", "is", "None", "else", "base_url", "def", "handle_404", "(", "request", ",", "response", ",", "*", "args", ",", "*...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.version_router
Intelligently routes a request to the correct handler based on the version being requested
hug/api.py
def version_router(self, request, response, api_version=None, versions={}, not_found=None, **kwargs): """Intelligently routes a request to the correct handler based on the version being requested""" request_version = self.determine_version(request, api_version) if request_version: re...
def version_router(self, request, response, api_version=None, versions={}, not_found=None, **kwargs): """Intelligently routes a request to the correct handler based on the version being requested""" request_version = self.determine_version(request, api_version) if request_version: re...
[ "Intelligently", "routes", "a", "request", "to", "the", "correct", "handler", "based", "on", "the", "version", "being", "requested" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L321-L328
[ "def", "version_router", "(", "self", ",", "request", ",", "response", ",", "api_version", "=", "None", ",", "versions", "=", "{", "}", ",", "not_found", "=", "None", ",", "*", "*", "kwargs", ")", ":", "request_version", "=", "self", ".", "determine_vers...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
HTTPInterfaceAPI.server
Returns a WSGI compatible API server for the given Hug API module
hug/api.py
def server(self, default_not_found=True, base_url=None): """Returns a WSGI compatible API server for the given Hug API module""" falcon_api = falcon.API(middleware=self.middleware) default_not_found = self.documentation_404() if default_not_found is True else None base_url = self.base_ur...
def server(self, default_not_found=True, base_url=None): """Returns a WSGI compatible API server for the given Hug API module""" falcon_api = falcon.API(middleware=self.middleware) default_not_found = self.documentation_404() if default_not_found is True else None base_url = self.base_ur...
[ "Returns", "a", "WSGI", "compatible", "API", "server", "for", "the", "given", "Hug", "API", "module" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L330-L376
[ "def", "server", "(", "self", ",", "default_not_found", "=", "True", ",", "base_url", "=", "None", ")", ":", "falcon_api", "=", "falcon", ".", "API", "(", "middleware", "=", "self", ".", "middleware", ")", "default_not_found", "=", "self", ".", "documentat...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
CLIInterfaceAPI.extend
Extends this CLI api with the commands present in the provided cli_api object
hug/api.py
def extend(self, cli_api, command_prefix="", sub_command="", **kwargs): """Extends this CLI api with the commands present in the provided cli_api object""" if sub_command and command_prefix: raise ValueError('It is not currently supported to provide both a command_prefix and sub_command') ...
def extend(self, cli_api, command_prefix="", sub_command="", **kwargs): """Extends this CLI api with the commands present in the provided cli_api object""" if sub_command and command_prefix: raise ValueError('It is not currently supported to provide both a command_prefix and sub_command') ...
[ "Extends", "this", "CLI", "api", "with", "the", "commands", "present", "in", "the", "provided", "cli_api", "object" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L408-L417
[ "def", "extend", "(", "self", ",", "cli_api", ",", "command_prefix", "=", "\"\"", ",", "sub_command", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "if", "sub_command", "and", "command_prefix", ":", "raise", "ValueError", "(", "'It is not currently supported...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.directives
Returns all directives applicable to this Hug API
hug/api.py
def directives(self): """Returns all directives applicable to this Hug API""" directive_sources = chain(hug.defaults.directives.items(), getattr(self, '_directives', {}).items()) return {'hug_' + directive_name: directive for directive_name, directive in directive_sources}
def directives(self): """Returns all directives applicable to this Hug API""" directive_sources = chain(hug.defaults.directives.items(), getattr(self, '_directives', {}).items()) return {'hug_' + directive_name: directive for directive_name, directive in directive_sources}
[ "Returns", "all", "directives", "applicable", "to", "this", "Hug", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L474-L477
[ "def", "directives", "(", "self", ")", ":", "directive_sources", "=", "chain", "(", "hug", ".", "defaults", ".", "directives", ".", "items", "(", ")", ",", "getattr", "(", "self", ",", "'_directives'", ",", "{", "}", ")", ".", "items", "(", ")", ")",...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.directive
Returns the loaded directive with the specified name, or default if passed name is not present
hug/api.py
def directive(self, name, default=None): """Returns the loaded directive with the specified name, or default if passed name is not present""" return getattr(self, '_directives', {}).get(name, hug.defaults.directives.get(name, default))
def directive(self, name, default=None): """Returns the loaded directive with the specified name, or default if passed name is not present""" return getattr(self, '_directives', {}).get(name, hug.defaults.directives.get(name, default))
[ "Returns", "the", "loaded", "directive", "with", "the", "specified", "name", "or", "default", "if", "passed", "name", "is", "not", "present" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L479-L481
[ "def", "directive", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "return", "getattr", "(", "self", ",", "'_directives'", ",", "{", "}", ")", ".", "get", "(", "name", ",", "hug", ".", "defaults", ".", "directives", ".", "get", "(...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.handlers
Returns all registered handlers attached to this API
hug/api.py
def handlers(self): """Returns all registered handlers attached to this API""" if getattr(self, '_http'): yield from self.http.handlers() if getattr(self, '_cli'): yield from self.cli.handlers()
def handlers(self): """Returns all registered handlers attached to this API""" if getattr(self, '_http'): yield from self.http.handlers() if getattr(self, '_cli'): yield from self.cli.handlers()
[ "Returns", "all", "registered", "handlers", "attached", "to", "this", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L487-L492
[ "def", "handlers", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_http'", ")", ":", "yield", "from", "self", ".", "http", ".", "handlers", "(", ")", "if", "getattr", "(", "self", ",", "'_cli'", ")", ":", "yield", "from", "self", ".", ...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.extend
Adds handlers from a different Hug API to this one - to create a single API
hug/api.py
def extend(self, api, route="", base_url="", http=True, cli=True, **kwargs): """Adds handlers from a different Hug API to this one - to create a single API""" api = API(api) if http and hasattr(api, '_http'): self.http.extend(api.http, route, base_url, **kwargs) if cli and ...
def extend(self, api, route="", base_url="", http=True, cli=True, **kwargs): """Adds handlers from a different Hug API to this one - to create a single API""" api = API(api) if http and hasattr(api, '_http'): self.http.extend(api.http, route, base_url, **kwargs) if cli and ...
[ "Adds", "handlers", "from", "a", "different", "Hug", "API", "to", "this", "one", "-", "to", "create", "a", "single", "API" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L528-L542
[ "def", "extend", "(", "self", ",", "api", ",", "route", "=", "\"\"", ",", "base_url", "=", "\"\"", ",", "http", "=", "True", ",", "cli", "=", "True", ",", "*", "*", "kwargs", ")", ":", "api", "=", "API", "(", "api", ")", "if", "http", "and", ...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API.add_startup_handler
Adds a startup handler to the hug api
hug/api.py
def add_startup_handler(self, handler): """Adds a startup handler to the hug api""" if not self.startup_handlers: self._startup_handlers = [] self.startup_handlers.append(handler)
def add_startup_handler(self, handler): """Adds a startup handler to the hug api""" if not self.startup_handlers: self._startup_handlers = [] self.startup_handlers.append(handler)
[ "Adds", "a", "startup", "handler", "to", "the", "hug", "api" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L544-L549
[ "def", "add_startup_handler", "(", "self", ",", "handler", ")", ":", "if", "not", "self", ".", "startup_handlers", ":", "self", ".", "_startup_handlers", "=", "[", "]", "self", ".", "startup_handlers", ".", "append", "(", "handler", ")" ]
080901c81576657f82e2432fd4a82f1d0d2f370c
train
API._ensure_started
Marks the API as started and runs all startup handlers
hug/api.py
def _ensure_started(self): """Marks the API as started and runs all startup handlers""" if not self.started: async_handlers = [startup_handler for startup_handler in self.startup_handlers if introspect.is_coroutine(startup_handler)] if async_handlers...
def _ensure_started(self): """Marks the API as started and runs all startup handlers""" if not self.started: async_handlers = [startup_handler for startup_handler in self.startup_handlers if introspect.is_coroutine(startup_handler)] if async_handlers...
[ "Marks", "the", "API", "as", "started", "and", "runs", "all", "startup", "handlers" ]
hugapi/hug
python
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/api.py#L551-L561
[ "def", "_ensure_started", "(", "self", ")", ":", "if", "not", "self", ".", "started", ":", "async_handlers", "=", "[", "startup_handler", "for", "startup_handler", "in", "self", ".", "startup_handlers", "if", "introspect", ".", "is_coroutine", "(", "startup_hand...
080901c81576657f82e2432fd4a82f1d0d2f370c
train
_weight_drop
Helper for `WeightDrop`.
torchnlp/nn/weight_drop.py
def _weight_drop(module, weights, dropout): """ Helper for `WeightDrop`. """ for name_w in weights: w = getattr(module, name_w) del module._parameters[name_w] module.register_parameter(name_w + '_raw', Parameter(w)) original_module_forward = module.forward def forward(...
def _weight_drop(module, weights, dropout): """ Helper for `WeightDrop`. """ for name_w in weights: w = getattr(module, name_w) del module._parameters[name_w] module.register_parameter(name_w + '_raw', Parameter(w)) original_module_forward = module.forward def forward(...
[ "Helper", "for", "WeightDrop", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/nn/weight_drop.py#L6-L26
[ "def", "_weight_drop", "(", "module", ",", "weights", ",", "dropout", ")", ":", "for", "name_w", "in", "weights", ":", "w", "=", "getattr", "(", "module", ",", "name_w", ")", "del", "module", ".", "_parameters", "[", "name_w", "]", "module", ".", "regi...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
imdb_dataset
Load the IMDB dataset (Large Movie Review Dataset v1.0). This is a dataset for binary sentiment classification containing substantially more data than previous benchmark datasets. Provided a set of 25,000 highly polar movie reviews for training, and 25,000 for testing. There is additional unlabeled data fo...
torchnlp/datasets/imdb.py
def imdb_dataset(directory='data/', train=False, test=False, train_directory='train', test_directory='test', extracted_name='aclImdb', check_files=['aclImdb/README'], url='http://ai.stanford.edu/~amaas...
def imdb_dataset(directory='data/', train=False, test=False, train_directory='train', test_directory='test', extracted_name='aclImdb', check_files=['aclImdb/README'], url='http://ai.stanford.edu/~amaas...
[ "Load", "the", "IMDB", "dataset", "(", "Large", "Movie", "Review", "Dataset", "v1", ".", "0", ")", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/imdb.py#L8-L81
[ "def", "imdb_dataset", "(", "directory", "=", "'data/'", ",", "train", "=", "False", ",", "test", "=", "False", ",", "train_directory", "=", "'train'", ",", "test_directory", "=", "'test'", ",", "extracted_name", "=", "'aclImdb'", ",", "check_files", "=", "[...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
trec_dataset
Load the Text REtrieval Conference (TREC) Question Classification dataset. TREC dataset contains 5500 labeled questions in training set and another 500 for test set. The dataset has 6 labels, 50 level-2 labels. Average length of each sentence is 10, vocabulary size of 8700. References: * https...
torchnlp/datasets/trec.py
def trec_dataset(directory='data/trec/', train=False, test=False, train_filename='train_5500.label', test_filename='TREC_10.label', check_files=['train_5500.label'], urls=[ 'http://cogcomp.org/Data...
def trec_dataset(directory='data/trec/', train=False, test=False, train_filename='train_5500.label', test_filename='TREC_10.label', check_files=['train_5500.label'], urls=[ 'http://cogcomp.org/Data...
[ "Load", "the", "Text", "REtrieval", "Conference", "(", "TREC", ")", "Question", "Classification", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/trec.py#L7-L80
[ "def", "trec_dataset", "(", "directory", "=", "'data/trec/'", ",", "train", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'train_5500.label'", ",", "test_filename", "=", "'TREC_10.label'", ",", "check_files", "=", "[", "'train_5500.label'",...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
snli_dataset
Load the Stanford Natural Language Inference (SNLI) dataset. The SNLI corpus (version 1.0) is a collection of 570k human-written English sentence pairs manually labeled for balanced classification with the labels entailment, contradiction, and neutral, supporting the task of natural language inference (NLI...
torchnlp/datasets/snli.py
def snli_dataset(directory='data/', train=False, dev=False, test=False, train_filename='snli_1.0_train.jsonl', dev_filename='snli_1.0_dev.jsonl', test_filename='snli_1.0_test.jsonl', extracted_name='sn...
def snli_dataset(directory='data/', train=False, dev=False, test=False, train_filename='snli_1.0_train.jsonl', dev_filename='snli_1.0_dev.jsonl', test_filename='snli_1.0_test.jsonl', extracted_name='sn...
[ "Load", "the", "Stanford", "Natural", "Language", "Inference", "(", "SNLI", ")", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/snli.py#L10-L91
[ "def", "snli_dataset", "(", "directory", "=", "'data/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'snli_1.0_train.jsonl'", ",", "dev_filename", "=", "'snli_1.0_dev.jsonl'", ",", "test_filename"...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
Attention.forward
Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data overwhich to apply the attention mechanism. Retur...
torchnlp/nn/attention.py
def forward(self, query, context): """ Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data ove...
def forward(self, query, context): """ Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data ove...
[ "Args", ":", "query", "(", ":", "class", ":", "torch", ".", "FloatTensor", "[", "batch", "size", "output", "length", "dimensions", "]", ")", ":", "Sequence", "of", "queries", "to", "query", "the", "context", ".", "context", "(", ":", "class", ":", "tor...
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/nn/attention.py#L45-L92
[ "def", "forward", "(", "self", ",", "query", ",", "context", ")", ":", "batch_size", ",", "output_len", ",", "dimensions", "=", "query", ".", "size", "(", ")", "query_len", "=", "context", ".", "size", "(", "1", ")", "if", "self", ".", "attention_type"...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
iwslt_dataset
Load the International Workshop on Spoken Language Translation (IWSLT) 2017 translation dataset. In-domain training, development and evaluation sets were supplied through the website of the WIT3 project, while out-of-domain training data were linked in the workshop’s website. With respect to edition 2016 o...
torchnlp/datasets/iwslt.py
def iwslt_dataset( directory='data/iwslt/', train=False, dev=False, test=False, language_extensions=['en', 'de'], train_filename='{source}-{target}/train.{source}-{target}.{lang}', dev_filename='{source}-{target}/IWSLT16.TED.tst2013.{source}-{target}.{lang}', ...
def iwslt_dataset( directory='data/iwslt/', train=False, dev=False, test=False, language_extensions=['en', 'de'], train_filename='{source}-{target}/train.{source}-{target}.{lang}', dev_filename='{source}-{target}/IWSLT16.TED.tst2013.{source}-{target}.{lang}', ...
[ "Load", "the", "International", "Workshop", "on", "Spoken", "Language", "Translation", "(", "IWSLT", ")", "2017", "translation", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/iwslt.py#L10-L111
[ "def", "iwslt_dataset", "(", "directory", "=", "'data/iwslt/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "language_extensions", "=", "[", "'en'", ",", "'de'", "]", ",", "train_filename", "=", "'{source}-{target}/t...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
Encoder.encode
Encodes an object. Args: object_ (object): Object to encode. Returns: object: Encoding of the object.
torchnlp/encoders/encoder.py
def encode(self, object_): """ Encodes an object. Args: object_ (object): Object to encode. Returns: object: Encoding of the object. """ if self.enforce_reversible: self.enforce_reversible = False if self.decode(self.encode(object...
def encode(self, object_): """ Encodes an object. Args: object_ (object): Object to encode. Returns: object: Encoding of the object. """ if self.enforce_reversible: self.enforce_reversible = False if self.decode(self.encode(object...
[ "Encodes", "an", "object", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/encoder.py#L14-L29
[ "def", "encode", "(", "self", ",", "object_", ")", ":", "if", "self", ".", "enforce_reversible", ":", "self", ".", "enforce_reversible", "=", "False", "if", "self", ".", "decode", "(", "self", ".", "encode", "(", "object_", ")", ")", "!=", "object_", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
Encoder.batch_encode
Args: batch (list): Batch of objects to encode. *args: Arguments passed to ``encode``. **kwargs: Keyword arguments passed to ``encode``. Returns: list: Batch of encoded objects.
torchnlp/encoders/encoder.py
def batch_encode(self, iterator, *args, **kwargs): """ Args: batch (list): Batch of objects to encode. *args: Arguments passed to ``encode``. **kwargs: Keyword arguments passed to ``encode``. Returns: list: Batch of encoded objects. """ ...
def batch_encode(self, iterator, *args, **kwargs): """ Args: batch (list): Batch of objects to encode. *args: Arguments passed to ``encode``. **kwargs: Keyword arguments passed to ``encode``. Returns: list: Batch of encoded objects. """ ...
[ "Args", ":", "batch", "(", "list", ")", ":", "Batch", "of", "objects", "to", "encode", ".", "*", "args", ":", "Arguments", "passed", "to", "encode", ".", "**", "kwargs", ":", "Keyword", "arguments", "passed", "to", "encode", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/encoder.py#L31-L41
[ "def", "batch_encode", "(", "self", ",", "iterator", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "self", ".", "encode", "(", "object_", ",", "*", "args", ",", "*", "*", "kwargs", ")", "for", "object_", "in", "iterator", "]" ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
Encoder.decode
Decodes an object. Args: object_ (object): Encoded object. Returns: object: Object decoded.
torchnlp/encoders/encoder.py
def decode(self, encoded): """ Decodes an object. Args: object_ (object): Encoded object. Returns: object: Object decoded. """ if self.enforce_reversible: self.enforce_reversible = False if self.encode(self.decode(encoded)) != enc...
def decode(self, encoded): """ Decodes an object. Args: object_ (object): Encoded object. Returns: object: Object decoded. """ if self.enforce_reversible: self.enforce_reversible = False if self.encode(self.decode(encoded)) != enc...
[ "Decodes", "an", "object", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/encoder.py#L43-L58
[ "def", "decode", "(", "self", ",", "encoded", ")", ":", "if", "self", ".", "enforce_reversible", ":", "self", ".", "enforce_reversible", "=", "False", "if", "self", ".", "encode", "(", "self", ".", "decode", "(", "encoded", ")", ")", "!=", "encoded", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
Encoder.batch_decode
Args: iterator (list): Batch of encoded objects. *args: Arguments passed to ``decode``. **kwargs: Keyword arguments passed to ``decode``. Returns: list: Batch of decoded objects.
torchnlp/encoders/encoder.py
def batch_decode(self, iterator, *args, **kwargs): """ Args: iterator (list): Batch of encoded objects. *args: Arguments passed to ``decode``. **kwargs: Keyword arguments passed to ``decode``. Returns: list: Batch of decoded objects. """ ...
def batch_decode(self, iterator, *args, **kwargs): """ Args: iterator (list): Batch of encoded objects. *args: Arguments passed to ``decode``. **kwargs: Keyword arguments passed to ``decode``. Returns: list: Batch of decoded objects. """ ...
[ "Args", ":", "iterator", "(", "list", ")", ":", "Batch", "of", "encoded", "objects", ".", "*", "args", ":", "Arguments", "passed", "to", "decode", ".", "**", "kwargs", ":", "Keyword", "arguments", "passed", "to", "decode", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/encoder.py#L60-L70
[ "def", "batch_decode", "(", "self", ",", "iterator", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "self", ".", "decode", "(", "encoded", ",", "*", "args", ",", "*", "*", "kwargs", ")", "for", "encoded", "in", "iterator", "]" ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
CNNEncoder.forward
Args: tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence matrix to encode. mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask. Returns: (:class:`torch.FloatTensor` [batch_size, output_dim]): Encodi...
torchnlp/nn/cnn_encoder.py
def forward(self, tokens, mask=None): """ Args: tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence matrix to encode. mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask. Returns: (:c...
def forward(self, tokens, mask=None): """ Args: tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence matrix to encode. mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask. Returns: (:c...
[ "Args", ":", "tokens", "(", ":", "class", ":", "torch", ".", "FloatTensor", "[", "batch_size", "num_tokens", "input_dim", "]", ")", ":", "Sequence", "matrix", "to", "encode", ".", "mask", "(", ":", "class", ":", "torch", ".", "FloatTensor", ")", ":", "...
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/nn/cnn_encoder.py#L82-L121
[ "def", "forward", "(", "self", ",", "tokens", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "not", "None", ":", "tokens", "=", "tokens", "*", "mask", ".", "unsqueeze", "(", "-", "1", ")", ".", "float", "(", ")", "# Our input is expected to ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
_unescape_token
Inverse of _escape_token(). Args: escaped_token: a unicode string Returns: token: a unicode string
torchnlp/encoders/text/subword_text_tokenizer.py
def _unescape_token(escaped_token): """ Inverse of _escape_token(). Args: escaped_token: a unicode string Returns: token: a unicode string """ def match(m): if m.group(1) is None: return u"_" if m.group(0) == u"\\u" else u"\\" try: return six...
def _unescape_token(escaped_token): """ Inverse of _escape_token(). Args: escaped_token: a unicode string Returns: token: a unicode string """ def match(m): if m.group(1) is None: return u"_" if m.group(0) == u"\\u" else u"\\" try: return six...
[ "Inverse", "of", "_escape_token", "()", ".", "Args", ":", "escaped_token", ":", "a", "unicode", "string", "Returns", ":", "token", ":", "a", "unicode", "string" ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L123-L142
[ "def", "_unescape_token", "(", "escaped_token", ")", ":", "def", "match", "(", "m", ")", ":", "if", "m", ".", "group", "(", "1", ")", "is", "None", ":", "return", "u\"_\"", "if", "m", ".", "group", "(", "0", ")", "==", "u\"\\\\u\"", "else", "u\"\\\...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer._tokens_to_subtoken
Converts a list of tokens to a list of subtoken. Args: tokens: a list of strings. Returns: a list of integers in the range [0, vocab_size)
torchnlp/encoders/text/subword_text_tokenizer.py
def _tokens_to_subtoken(self, tokens): """ Converts a list of tokens to a list of subtoken. Args: tokens: a list of strings. Returns: a list of integers in the range [0, vocab_size) """ ret = [] for token in tokens: ret.extend( ...
def _tokens_to_subtoken(self, tokens): """ Converts a list of tokens to a list of subtoken. Args: tokens: a list of strings. Returns: a list of integers in the range [0, vocab_size) """ ret = [] for token in tokens: ret.extend( ...
[ "Converts", "a", "list", "of", "tokens", "to", "a", "list", "of", "subtoken", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L204-L216
[ "def", "_tokens_to_subtoken", "(", "self", ",", "tokens", ")", ":", "ret", "=", "[", "]", "for", "token", "in", "tokens", ":", "ret", ".", "extend", "(", "self", ".", "_escaped_token_to_subtoken_strings", "(", "_escape_token", "(", "token", ",", "self", "....
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer._subtoken_to_tokens
Converts a list of subtoken to a list of tokens. Args: subtokens: a list of integers in the range [0, vocab_size) Returns: a list of strings.
torchnlp/encoders/text/subword_text_tokenizer.py
def _subtoken_to_tokens(self, subtokens): """ Converts a list of subtoken to a list of tokens. Args: subtokens: a list of integers in the range [0, vocab_size) Returns: a list of strings. """ concatenated = "".join(subtokens) split = concatenated.spl...
def _subtoken_to_tokens(self, subtokens): """ Converts a list of subtoken to a list of tokens. Args: subtokens: a list of integers in the range [0, vocab_size) Returns: a list of strings. """ concatenated = "".join(subtokens) split = concatenated.spl...
[ "Converts", "a", "list", "of", "subtoken", "to", "a", "list", "of", "tokens", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L218-L229
[ "def", "_subtoken_to_tokens", "(", "self", ",", "subtokens", ")", ":", "concatenated", "=", "\"\"", ".", "join", "(", "subtokens", ")", "split", "=", "concatenated", ".", "split", "(", "\"_\"", ")", "return", "[", "_unescape_token", "(", "t", "+", "\"_\"",...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer._escaped_token_to_subtoken_strings
Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings.
torchnlp/encoders/text/subword_text_tokenizer.py
def _escaped_token_to_subtoken_strings(self, escaped_token): """ Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings. """ # NOTE: This algor...
def _escaped_token_to_subtoken_strings(self, escaped_token): """ Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings. """ # NOTE: This algor...
[ "Converts", "an", "escaped", "token", "string", "to", "a", "list", "of", "subtoken", "strings", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L231-L258
[ "def", "_escaped_token_to_subtoken_strings", "(", "self", ",", "escaped_token", ")", ":", "# NOTE: This algorithm is greedy; it won't necessarily produce the \"best\"", "# list of subtokens.", "ret", "=", "[", "]", "start", "=", "0", "token_len", "=", "len", "(", "escaped_t...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer.build_to_target_size_from_token_counts
Builds a SubwordTextTokenizer that has `vocab_size` near `target_size`. Uses simple recursive binary search to find a minimum token count that most closely matches the `target_size`. Args: target_size: Desired vocab_size to approximate. token_counts: A dictionary of token c...
torchnlp/encoders/text/subword_text_tokenizer.py
def build_to_target_size_from_token_counts(cls, target_size, token_counts, min_val, max_val, ...
def build_to_target_size_from_token_counts(cls, target_size, token_counts, min_val, max_val, ...
[ "Builds", "a", "SubwordTextTokenizer", "that", "has", "vocab_size", "near", "target_size", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L280-L334
[ "def", "build_to_target_size_from_token_counts", "(", "cls", ",", "target_size", ",", "token_counts", ",", "min_val", ",", "max_val", ",", "num_iterations", "=", "4", ")", ":", "if", "min_val", ">", "max_val", ":", "raise", "ValueError", "(", "\"Lower bound for th...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer.build_from_token_counts
Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_iterations: an integer; how many iterations of refinement.
torchnlp/encoders/text/subword_text_tokenizer.py
def build_from_token_counts(self, token_counts, min_count, num_iterations=4): """Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_...
def build_from_token_counts(self, token_counts, min_count, num_iterations=4): """Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_...
[ "Train", "a", "SubwordTextTokenizer", "based", "on", "a", "dictionary", "of", "word", "counts", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L340-L405
[ "def", "build_from_token_counts", "(", "self", ",", "token_counts", ",", "min_count", ",", "num_iterations", "=", "4", ")", ":", "self", ".", "_init_alphabet_from_tokens", "(", "six", ".", "iterkeys", "(", "token_counts", ")", ")", "# Bootstrap the initial list of s...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer._init_subtokens_from_list
Initialize token information from a list of subtoken strings.
torchnlp/encoders/text/subword_text_tokenizer.py
def _init_subtokens_from_list(self, subtoken_strings): """Initialize token information from a list of subtoken strings.""" # we remember the maximum length of any subtoken to avoid having to # check arbitrarily long strings. self._all_subtoken_strings = set([s for s in subtoken_strings i...
def _init_subtokens_from_list(self, subtoken_strings): """Initialize token information from a list of subtoken strings.""" # we remember the maximum length of any subtoken to avoid having to # check arbitrarily long strings. self._all_subtoken_strings = set([s for s in subtoken_strings i...
[ "Initialize", "token", "information", "from", "a", "list", "of", "subtoken", "strings", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L407-L412
[ "def", "_init_subtokens_from_list", "(", "self", ",", "subtoken_strings", ")", ":", "# we remember the maximum length of any subtoken to avoid having to", "# check arbitrarily long strings.", "self", ".", "_all_subtoken_strings", "=", "set", "(", "[", "s", "for", "s", "in", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordTextTokenizer._init_alphabet_from_tokens
Initialize alphabet from an iterable of token or subtoken strings.
torchnlp/encoders/text/subword_text_tokenizer.py
def _init_alphabet_from_tokens(self, tokens): """Initialize alphabet from an iterable of token or subtoken strings.""" # Include all characters from all tokens in the alphabet to guarantee that # any token can be encoded. Additionally, include all escaping # characters. self._alp...
def _init_alphabet_from_tokens(self, tokens): """Initialize alphabet from an iterable of token or subtoken strings.""" # Include all characters from all tokens in the alphabet to guarantee that # any token can be encoded. Additionally, include all escaping # characters. self._alp...
[ "Initialize", "alphabet", "from", "an", "iterable", "of", "token", "or", "subtoken", "strings", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_text_tokenizer.py#L414-L420
[ "def", "_init_alphabet_from_tokens", "(", "self", ",", "tokens", ")", ":", "# Include all characters from all tokens in the alphabet to guarantee that", "# any token can be encoded. Additionally, include all escaping", "# characters.", "self", ".", "_alphabet", "=", "{", "c", "for"...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
get_moses_multi_bleu
Get the BLEU score using the moses `multi-bleu.perl` script. **Script:** https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl Args: hypotheses (list of str): List of predicted values references (list of str): List of target values lowercase (boo...
torchnlp/metrics/bleu.py
def get_moses_multi_bleu(hypotheses, references, lowercase=False): """Get the BLEU score using the moses `multi-bleu.perl` script. **Script:** https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl Args: hypotheses (list of str): List of predicted values ...
def get_moses_multi_bleu(hypotheses, references, lowercase=False): """Get the BLEU score using the moses `multi-bleu.perl` script. **Script:** https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl Args: hypotheses (list of str): List of predicted values ...
[ "Get", "the", "BLEU", "score", "using", "the", "moses", "multi", "-", "bleu", ".", "perl", "script", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/metrics/bleu.py#L30-L107
[ "def", "get_moses_multi_bleu", "(", "hypotheses", ",", "references", ",", "lowercase", "=", "False", ")", ":", "if", "isinstance", "(", "hypotheses", ",", "list", ")", ":", "hypotheses", "=", "np", ".", "array", "(", "hypotheses", ")", "if", "isinstance", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
ud_pos_dataset
Load the Universal Dependencies - English Dependency Treebank dataset. Corpus of sentences annotated using Universal Dependencies annotation. The corpus comprises 254,830 words and 16,622 sentences, taken from various web media including weblogs, newsgroups, emails, reviews, and Yahoo! answers. Refere...
torchnlp/datasets/ud_pos.py
def ud_pos_dataset(directory='data/', train=False, dev=False, test=False, train_filename='en-ud-tag.v2.train.txt', dev_filename='en-ud-tag.v2.dev.txt', test_filename='en-ud-tag.v2.test.txt', ...
def ud_pos_dataset(directory='data/', train=False, dev=False, test=False, train_filename='en-ud-tag.v2.train.txt', dev_filename='en-ud-tag.v2.dev.txt', test_filename='en-ud-tag.v2.test.txt', ...
[ "Load", "the", "Universal", "Dependencies", "-", "English", "Dependency", "Treebank", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/ud_pos.py#L8-L88
[ "def", "ud_pos_dataset", "(", "directory", "=", "'data/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'en-ud-tag.v2.train.txt'", ",", "dev_filename", "=", "'en-ud-tag.v2.dev.txt'", ",", "test_fil...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
makedirs
helper function for python 2 and 3 to call os.makedirs() avoiding an error if the directory to be created already exists
examples/snli/util.py
def makedirs(name): """helper function for python 2 and 3 to call os.makedirs() avoiding an error if the directory to be created already exists""" import os, errno try: os.makedirs(name) except OSError as ex: if ex.errno == errno.EEXIST and os.path.isdir(name): # ign...
def makedirs(name): """helper function for python 2 and 3 to call os.makedirs() avoiding an error if the directory to be created already exists""" import os, errno try: os.makedirs(name) except OSError as ex: if ex.errno == errno.EEXIST and os.path.isdir(name): # ign...
[ "helper", "function", "for", "python", "2", "and", "3", "to", "call", "os", ".", "makedirs", "()", "avoiding", "an", "error", "if", "the", "directory", "to", "be", "created", "already", "exists" ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/examples/snli/util.py#L10-L24
[ "def", "makedirs", "(", "name", ")", ":", "import", "os", ",", "errno", "try", ":", "os", ".", "makedirs", "(", "name", ")", "except", "OSError", "as", "ex", ":", "if", "ex", ".", "errno", "==", "errno", ".", "EEXIST", "and", "os", ".", "path", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
collate_fn
list of tensors to a batch tensors
examples/snli/util.py
def collate_fn(batch, train=True): """ list of tensors to a batch tensors """ premise_batch, _ = pad_batch([row['premise'] for row in batch]) hypothesis_batch, _ = pad_batch([row['hypothesis'] for row in batch]) label_batch = torch.stack([row['label'] for row in batch]) # PyTorch RNN requires batch...
def collate_fn(batch, train=True): """ list of tensors to a batch tensors """ premise_batch, _ = pad_batch([row['premise'] for row in batch]) hypothesis_batch, _ = pad_batch([row['hypothesis'] for row in batch]) label_batch = torch.stack([row['label'] for row in batch]) # PyTorch RNN requires batch...
[ "list", "of", "tensors", "to", "a", "batch", "tensors" ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/examples/snli/util.py#L56-L65
[ "def", "collate_fn", "(", "batch", ",", "train", "=", "True", ")", ":", "premise_batch", ",", "_", "=", "pad_batch", "(", "[", "row", "[", "'premise'", "]", "for", "row", "in", "batch", "]", ")", "hypothesis_batch", ",", "_", "=", "pad_batch", "(", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
smt_dataset
Load the Stanford Sentiment Treebank dataset. Semantic word spaces have been very useful but cannot express the meaning of longer phrases in a principled way. Further progress towards understanding compositionality in tasks such as sentiment detection requires richer supervised training and evaluation reso...
torchnlp/datasets/smt.py
def smt_dataset(directory='data/', train=False, dev=False, test=False, train_filename='train.txt', dev_filename='dev.txt', test_filename='test.txt', extracted_name='trees', check_files=['trees...
def smt_dataset(directory='data/', train=False, dev=False, test=False, train_filename='train.txt', dev_filename='dev.txt', test_filename='test.txt', extracted_name='trees', check_files=['trees...
[ "Load", "the", "Stanford", "Sentiment", "Treebank", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/smt.py#L41-L119
[ "def", "smt_dataset", "(", "directory", "=", "'data/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'train.txt'", ",", "dev_filename", "=", "'dev.txt'", ",", "test_filename", "=", "'test.txt'"...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
simple_qa_dataset
Load the SimpleQuestions dataset. Single-relation factoid questions (simple questions) are common in many settings (e.g. Microsoft’s search query logs and WikiAnswers questions). The SimpleQuestions dataset is one of the most commonly used benchmarks for studying single-relation factoid questions. **R...
torchnlp/datasets/simple_qa.py
def simple_qa_dataset( directory='data/', train=False, dev=False, test=False, extracted_name='SimpleQuestions_v2', train_filename='annotated_fb_data_train.txt', dev_filename='annotated_fb_data_valid.txt', test_filename='annotated_fb_data_test.txt', ...
def simple_qa_dataset( directory='data/', train=False, dev=False, test=False, extracted_name='SimpleQuestions_v2', train_filename='annotated_fb_data_train.txt', dev_filename='annotated_fb_data_valid.txt', test_filename='annotated_fb_data_test.txt', ...
[ "Load", "the", "SimpleQuestions", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/simple_qa.py#L9-L85
[ "def", "simple_qa_dataset", "(", "directory", "=", "'data/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "extracted_name", "=", "'SimpleQuestions_v2'", ",", "train_filename", "=", "'annotated_fb_data_train.txt'", ",", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
LockedDropout.forward
Args: x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to apply dropout too.
torchnlp/nn/lock_dropout.py
def forward(self, x): """ Args: x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to apply dropout too. """ if not self.training or not self.p: return x x = x.clone() mask = x.new_empty(1, x.size(1...
def forward(self, x): """ Args: x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to apply dropout too. """ if not self.training or not self.p: return x x = x.clone() mask = x.new_empty(1, x.size(1...
[ "Args", ":", "x", "(", ":", "class", ":", "torch", ".", "FloatTensor", "[", "batch", "size", "sequence", "length", "rnn", "hidden", "size", "]", ")", ":", "Input", "to", "apply", "dropout", "too", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/nn/lock_dropout.py#L52-L64
[ "def", "forward", "(", "self", ",", "x", ")", ":", "if", "not", "self", ".", "training", "or", "not", "self", ".", "p", ":", "return", "x", "x", "=", "x", ".", "clone", "(", ")", "mask", "=", "x", ".", "new_empty", "(", "1", ",", "x", ".", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
pad_tensor
Pad a ``tensor`` to ``length`` with ``padding_index``. Args: tensor (torch.Tensor [n, ...]): Tensor to pad. length (int): Pad the ``tensor`` up to ``length``. padding_index (int, optional): Index to pad tensor with. Returns (torch.Tensor [length, ...]) Padded Tensor.
torchnlp/encoders/text/text_encoder.py
def pad_tensor(tensor, length, padding_index=DEFAULT_PADDING_INDEX): """ Pad a ``tensor`` to ``length`` with ``padding_index``. Args: tensor (torch.Tensor [n, ...]): Tensor to pad. length (int): Pad the ``tensor`` up to ``length``. padding_index (int, optional): Index to pad tensor with...
def pad_tensor(tensor, length, padding_index=DEFAULT_PADDING_INDEX): """ Pad a ``tensor`` to ``length`` with ``padding_index``. Args: tensor (torch.Tensor [n, ...]): Tensor to pad. length (int): Pad the ``tensor`` up to ``length``. padding_index (int, optional): Index to pad tensor with...
[ "Pad", "a", "tensor", "to", "length", "with", "padding_index", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/text_encoder.py#L7-L23
[ "def", "pad_tensor", "(", "tensor", ",", "length", ",", "padding_index", "=", "DEFAULT_PADDING_INDEX", ")", ":", "n_padding", "=", "length", "-", "tensor", ".", "shape", "[", "0", "]", "assert", "n_padding", ">=", "0", "if", "n_padding", "==", "0", ":", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
stack_and_pad_tensors
Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``. Args: batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad. padding_index (int, optional): Index to pad tensors with. dim (int, optional): Dimension on to which to concatenate the batch of tensors. ...
torchnlp/encoders/text/text_encoder.py
def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0): """ Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``. Args: batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad. padding_index (int, optional): Index to pad tensors with. ...
def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0): """ Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``. Args: batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad. padding_index (int, optional): Index to pad tensors with. ...
[ "Pad", "a", ":", "class", ":", "list", "of", "tensors", "(", "batch", ")", "with", "padding_index", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/text_encoder.py#L26-L44
[ "def", "stack_and_pad_tensors", "(", "batch", ",", "padding_index", "=", "DEFAULT_PADDING_INDEX", ",", "dim", "=", "0", ")", ":", "lengths", "=", "[", "tensor", ".", "shape", "[", "0", "]", "for", "tensor", "in", "batch", "]", "max_len", "=", "max", "(",...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
TextEncoder.batch_encode
Args: iterator (iterator): Batch of text to encode. *args: Arguments passed onto ``Encoder.__init__``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword arguments passed onto ``Encoder.__init__``. Returns torch.Tenso...
torchnlp/encoders/text/text_encoder.py
def batch_encode(self, iterator, *args, dim=0, **kwargs): """ Args: iterator (iterator): Batch of text to encode. *args: Arguments passed onto ``Encoder.__init__``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword argume...
def batch_encode(self, iterator, *args, dim=0, **kwargs): """ Args: iterator (iterator): Batch of text to encode. *args: Arguments passed onto ``Encoder.__init__``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword argume...
[ "Args", ":", "iterator", "(", "iterator", ")", ":", "Batch", "of", "text", "to", "encode", ".", "*", "args", ":", "Arguments", "passed", "onto", "Encoder", ".", "__init__", ".", "dim", "(", "int", "optional", ")", ":", "Dimension", "along", "which", "t...
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/text_encoder.py#L49-L62
[ "def", "batch_encode", "(", "self", ",", "iterator", ",", "*", "args", ",", "dim", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "stack_and_pad_tensors", "(", "super", "(", ")", ".", "batch_encode", "(", "iterator", ")", ",", "padding_index", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
TextEncoder.batch_decode
Args: batch (list of :class:`torch.Tensor`): Batch of encoded sequences. lengths (list of int): Original lengths of sequences. dim (int, optional): Dimension along which to split tensors. *args: Arguments passed to ``decode``. **kwargs: Key word arguments pass...
torchnlp/encoders/text/text_encoder.py
def batch_decode(self, tensor, lengths, dim=0, *args, **kwargs): """ Args: batch (list of :class:`torch.Tensor`): Batch of encoded sequences. lengths (list of int): Original lengths of sequences. dim (int, optional): Dimension along which to split tensors. ...
def batch_decode(self, tensor, lengths, dim=0, *args, **kwargs): """ Args: batch (list of :class:`torch.Tensor`): Batch of encoded sequences. lengths (list of int): Original lengths of sequences. dim (int, optional): Dimension along which to split tensors. ...
[ "Args", ":", "batch", "(", "list", "of", ":", "class", ":", "torch", ".", "Tensor", ")", ":", "Batch", "of", "encoded", "sequences", ".", "lengths", "(", "list", "of", "int", ")", ":", "Original", "lengths", "of", "sequences", ".", "dim", "(", "int",...
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/text_encoder.py#L64-L77
[ "def", "batch_decode", "(", "self", ",", "tensor", ",", "lengths", ",", "dim", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", ")", ".", "batch_decode", "(", "[", "t", ".", "squeeze", "(", "0", ")", "[", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
StaticTokenizerEncoder.encode
Encodes a ``sequence``. Args: sequence (str): String ``sequence`` to encode. Returns: torch.Tensor: Encoding of the ``sequence``.
torchnlp/encoders/text/static_tokenizer_encoder.py
def encode(self, sequence): """ Encodes a ``sequence``. Args: sequence (str): String ``sequence`` to encode. Returns: torch.Tensor: Encoding of the ``sequence``. """ sequence = super().encode(sequence) sequence = self.tokenize(sequence) v...
def encode(self, sequence): """ Encodes a ``sequence``. Args: sequence (str): String ``sequence`` to encode. Returns: torch.Tensor: Encoding of the ``sequence``. """ sequence = super().encode(sequence) sequence = self.tokenize(sequence) v...
[ "Encodes", "a", "sequence", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/static_tokenizer_encoder.py#L105-L119
[ "def", "encode", "(", "self", ",", "sequence", ")", ":", "sequence", "=", "super", "(", ")", ".", "encode", "(", "sequence", ")", "sequence", "=", "self", ".", "tokenize", "(", "sequence", ")", "vector", "=", "[", "self", ".", "stoi", ".", "get", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
StaticTokenizerEncoder.decode
Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``.
torchnlp/encoders/text/static_tokenizer_encoder.py
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) tokens = [self.itos[index] for index in encode...
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) tokens = [self.itos[index] for index in encode...
[ "Decodes", "a", "tensor", "into", "a", "sequence", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/static_tokenizer_encoder.py#L121-L132
[ "def", "decode", "(", "self", ",", "encoded", ")", ":", "encoded", "=", "super", "(", ")", ".", "decode", "(", "encoded", ")", "tokens", "=", "[", "self", ".", "itos", "[", "index", "]", "for", "index", "in", "encoded", "]", "return", "self", ".", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
_reporthook
``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm Args: t (tqdm.tqdm) Progress bar. Example: >>> with tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t: ...
torchnlp/download.py
def _reporthook(t): """ ``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm Args: t (tqdm.tqdm) Progress bar. Example: >>> with tqdm(unit='B', unit_scale=True, minit...
def _reporthook(t): """ ``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm Args: t (tqdm.tqdm) Progress bar. Example: >>> with tqdm(unit='B', unit_scale=True, minit...
[ "reporthook", "to", "use", "with", "urllib", ".", "request", "that", "prints", "the", "process", "of", "the", "download", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/download.py#L15-L44
[ "def", "_reporthook", "(", "t", ")", ":", "last_b", "=", "[", "0", "]", "def", "inner", "(", "b", "=", "1", ",", "bsize", "=", "1", ",", "tsize", "=", "None", ")", ":", "\"\"\"\n Args:\n b (int, optional): Number of blocks just transferred [def...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
_download_file_from_drive
Download filename from google drive unless it's already in directory. Args: filename (str): Name of the file to download to (do nothing if it already exists). url (str): URL to download from.
torchnlp/download.py
def _download_file_from_drive(filename, url): # pragma: no cover """ Download filename from google drive unless it's already in directory. Args: filename (str): Name of the file to download to (do nothing if it already exists). url (str): URL to download from. """ confirm_token = None ...
def _download_file_from_drive(filename, url): # pragma: no cover """ Download filename from google drive unless it's already in directory. Args: filename (str): Name of the file to download to (do nothing if it already exists). url (str): URL to download from. """ confirm_token = None ...
[ "Download", "filename", "from", "google", "drive", "unless", "it", "s", "already", "in", "directory", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/download.py#L47-L81
[ "def", "_download_file_from_drive", "(", "filename", ",", "url", ")", ":", "# pragma: no cover", "confirm_token", "=", "None", "# Since the file is big, drive will scan it for virus and take it to a", "# warning page. We find the confirm token on this page and append it to the", "# URL t...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
_maybe_extract
Extract a compressed file to ``directory``. Args: compressed_filename (str): Compressed file. directory (str): Extract to directory. extension (str, optional): Extension of the file; Otherwise, attempts to extract extension from the filename.
torchnlp/download.py
def _maybe_extract(compressed_filename, directory, extension=None): """ Extract a compressed file to ``directory``. Args: compressed_filename (str): Compressed file. directory (str): Extract to directory. extension (str, optional): Extension of the file; Otherwise, attempts to extract e...
def _maybe_extract(compressed_filename, directory, extension=None): """ Extract a compressed file to ``directory``. Args: compressed_filename (str): Compressed file. directory (str): Extract to directory. extension (str, optional): Extension of the file; Otherwise, attempts to extract e...
[ "Extract", "a", "compressed", "file", "to", "directory", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/download.py#L84-L106
[ "def", "_maybe_extract", "(", "compressed_filename", ",", "directory", ",", "extension", "=", "None", ")", ":", "logger", ".", "info", "(", "'Extracting {}'", ".", "format", "(", "compressed_filename", ")", ")", "if", "extension", "is", "None", ":", "basename"...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
_get_filename_from_url
Return a filename from a URL Args: url (str): URL to extract filename from Returns: (str): Filename in URL
torchnlp/download.py
def _get_filename_from_url(url): """ Return a filename from a URL Args: url (str): URL to extract filename from Returns: (str): Filename in URL """ parse = urlparse(url) return os.path.basename(parse.path)
def _get_filename_from_url(url): """ Return a filename from a URL Args: url (str): URL to extract filename from Returns: (str): Filename in URL """ parse = urlparse(url) return os.path.basename(parse.path)
[ "Return", "a", "filename", "from", "a", "URL" ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/download.py#L109-L119
[ "def", "_get_filename_from_url", "(", "url", ")", ":", "parse", "=", "urlparse", "(", "url", ")", "return", "os", ".", "path", ".", "basename", "(", "parse", ".", "path", ")" ]
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
download_file_maybe_extract
Download the file at ``url`` to ``directory``. Extract to ``directory`` if tar or zip. Args: url (str): Url of file. directory (str): Directory to download to. filename (str, optional): Name of the file to download; Otherwise, a filename is extracted from the url. extens...
torchnlp/download.py
def download_file_maybe_extract(url, directory, filename=None, extension=None, check_files=[]): """ Download the file at ``url`` to ``directory``. Extract to ``directory`` if tar or zip. Args: url (str): Url of file. directory (str): Directory to download to. filename (str, optional): N...
def download_file_maybe_extract(url, directory, filename=None, extension=None, check_files=[]): """ Download the file at ``url`` to ``directory``. Extract to ``directory`` if tar or zip. Args: url (str): Url of file. directory (str): Directory to download to. filename (str, optional): N...
[ "Download", "the", "file", "at", "url", "to", "directory", ".", "Extract", "to", "directory", "if", "tar", "or", "zip", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/download.py#L122-L167
[ "def", "download_file_maybe_extract", "(", "url", ",", "directory", ",", "filename", "=", "None", ",", "extension", "=", "None", ",", "check_files", "=", "[", "]", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "_get_filename_from_url", "(",...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
download_files_maybe_extract
Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip. Args: urls (str): Url of files. directory (str): Directory to download to. check_files (list of str): Check if these files exist, ensuring the download succeeded. If these files exist before...
torchnlp/download.py
def download_files_maybe_extract(urls, directory, check_files=[]): """ Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip. Args: urls (str): Url of files. directory (str): Directory to download to. check_files (list of str): Check if these files exis...
def download_files_maybe_extract(urls, directory, check_files=[]): """ Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip. Args: urls (str): Url of files. directory (str): Directory to download to. check_files (list of str): Check if these files exis...
[ "Download", "the", "files", "at", "urls", "to", "directory", ".", "Extract", "to", "directory", "if", "tar", "or", "zip", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/download.py#L182-L202
[ "def", "download_files_maybe_extract", "(", "urls", ",", "directory", ",", "check_files", "=", "[", "]", ")", ":", "check_files", "=", "[", "os", ".", "path", ".", "join", "(", "directory", ",", "f", ")", "for", "f", "in", "check_files", "]", "if", "_c...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
get_accuracy
Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ignore_index (int, optional): Specifies a target index that is ...
torchnlp/metrics/accuracy.py
def get_accuracy(targets, outputs, k=1, ignore_index=None): """ Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
def get_accuracy(targets, outputs, k=1, ignore_index=None): """ Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
[ "Get", "the", "accuracy", "top", "-", "k", "accuracy", "between", "two", "tensors", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/metrics/accuracy.py#L8-L50
[ "def", "get_accuracy", "(", "targets", ",", "outputs", ",", "k", "=", "1", ",", "ignore_index", "=", "None", ")", ":", "n_correct", "=", "0.0", "for", "target", ",", "output", "in", "zip", "(", "targets", ",", "outputs", ")", ":", "if", "not", "torch...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
get_token_accuracy
Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ignore_index (int, optional): Specifies a target index that is ...
torchnlp/metrics/accuracy.py
def get_token_accuracy(targets, outputs, ignore_index=None): """ Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
def get_token_accuracy(targets, outputs, ignore_index=None): """ Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
[ "Get", "the", "accuracy", "token", "accuracy", "between", "two", "tensors", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/metrics/accuracy.py#L53-L102
[ "def", "get_token_accuracy", "(", "targets", ",", "outputs", ",", "ignore_index", "=", "None", ")", ":", "n_correct", "=", "0.0", "n_total", "=", "0.0", "for", "target", ",", "output", "in", "zip", "(", "targets", ",", "outputs", ")", ":", "if", "not", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
get_tensors
Get all tensors associated with ``object_`` Args: object_ (any): Any object to look for tensors. Returns: (list of torch.tensor): List of tensors that are associated with ``object_``.
torchnlp/utils.py
def get_tensors(object_): """ Get all tensors associated with ``object_`` Args: object_ (any): Any object to look for tensors. Returns: (list of torch.tensor): List of tensors that are associated with ``object_``. """ if torch.is_tensor(object_): return [object_] elif i...
def get_tensors(object_): """ Get all tensors associated with ``object_`` Args: object_ (any): Any object to look for tensors. Returns: (list of torch.tensor): List of tensors that are associated with ``object_``. """ if torch.is_tensor(object_): return [object_] elif i...
[ "Get", "all", "tensors", "associated", "with", "object_" ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L11-L40
[ "def", "get_tensors", "(", "object_", ")", ":", "if", "torch", ".", "is_tensor", "(", "object_", ")", ":", "return", "[", "object_", "]", "elif", "isinstance", "(", "object_", ",", "(", "str", ",", "float", ",", "int", ")", ")", ":", "return", "[", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
sampler_to_iterator
Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over dataset examples
torchnlp/utils.py
def sampler_to_iterator(dataset, sampler): """ Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over datase...
def sampler_to_iterator(dataset, sampler): """ Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over datase...
[ "Given", "a", "batch", "sampler", "or", "sampler", "returns", "examples", "instead", "of", "indices" ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L43-L59
[ "def", "sampler_to_iterator", "(", "dataset", ",", "sampler", ")", ":", "for", "sample", "in", "sampler", ":", "if", "isinstance", "(", "sample", ",", "(", "list", ",", "tuple", ")", ")", ":", "# yield a batch", "yield", "[", "dataset", "[", "i", "]", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
resplit_datasets
Deterministic shuffle and split algorithm. Given the same two datasets and the same ``random_seed``, the split happens the same exact way every call. Args: dataset (lib.datasets.Dataset): First dataset. other_dataset (lib.datasets.Dataset): Another dataset. random_seed (int, option...
torchnlp/utils.py
def resplit_datasets(dataset, other_dataset, random_seed=None, split=None): """Deterministic shuffle and split algorithm. Given the same two datasets and the same ``random_seed``, the split happens the same exact way every call. Args: dataset (lib.datasets.Dataset): First dataset. othe...
def resplit_datasets(dataset, other_dataset, random_seed=None, split=None): """Deterministic shuffle and split algorithm. Given the same two datasets and the same ``random_seed``, the split happens the same exact way every call. Args: dataset (lib.datasets.Dataset): First dataset. othe...
[ "Deterministic", "shuffle", "and", "split", "algorithm", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L105-L130
[ "def", "resplit_datasets", "(", "dataset", ",", "other_dataset", ",", "random_seed", "=", "None", ",", "split", "=", "None", ")", ":", "# Prevent circular dependency", "from", "torchnlp", ".", "datasets", "import", "Dataset", "concat", "=", "dataset", ".", "rows...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
torch_equals_ignore_index
Compute ``torch.equal`` with the optional mask parameter. Args: ignore_index (int, optional): Specifies a ``tensor`` index that is ignored. Returns: (bool) Returns ``True`` if target and prediction are equal.
torchnlp/utils.py
def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None): """ Compute ``torch.equal`` with the optional mask parameter. Args: ignore_index (int, optional): Specifies a ``tensor`` index that is ignored. Returns: (bool) Returns ``True`` if target and prediction are equal. ...
def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None): """ Compute ``torch.equal`` with the optional mask parameter. Args: ignore_index (int, optional): Specifies a ``tensor`` index that is ignored. Returns: (bool) Returns ``True`` if target and prediction are equal. ...
[ "Compute", "torch", ".", "equal", "with", "the", "optional", "mask", "parameter", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L133-L149
[ "def", "torch_equals_ignore_index", "(", "tensor", ",", "tensor_other", ",", "ignore_index", "=", "None", ")", ":", "if", "ignore_index", "is", "not", "None", ":", "assert", "tensor", ".", "size", "(", ")", "==", "tensor_other", ".", "size", "(", ")", "mas...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
lengths_to_mask
Given a list of lengths, create a batch mask. Example: >>> lengths_to_mask([1, 2, 3]) tensor([[1, 0, 0], [1, 1, 0], [1, 1, 1]], dtype=torch.uint8) >>> lengths_to_mask([1, 2, 2], [1, 2, 2]) tensor([[[1, 0], [0, 0]], <BLANKLINE>...
torchnlp/utils.py
def lengths_to_mask(*lengths, **kwargs): """ Given a list of lengths, create a batch mask. Example: >>> lengths_to_mask([1, 2, 3]) tensor([[1, 0, 0], [1, 1, 0], [1, 1, 1]], dtype=torch.uint8) >>> lengths_to_mask([1, 2, 2], [1, 2, 2]) tensor([[[1, ...
def lengths_to_mask(*lengths, **kwargs): """ Given a list of lengths, create a batch mask. Example: >>> lengths_to_mask([1, 2, 3]) tensor([[1, 0, 0], [1, 1, 0], [1, 1, 1]], dtype=torch.uint8) >>> lengths_to_mask([1, 2, 2], [1, 2, 2]) tensor([[[1, ...
[ "Given", "a", "list", "of", "lengths", "create", "a", "batch", "mask", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L156-L193
[ "def", "lengths_to_mask", "(", "*", "lengths", ",", "*", "*", "kwargs", ")", ":", "# Squeeze to deal with random additional dimensions", "lengths", "=", "[", "l", ".", "squeeze", "(", ")", ".", "tolist", "(", ")", "if", "torch", ".", "is_tensor", "(", "l", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
collate_tensors
Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. stack_tensors (callable): Function to stack tensors into a batch...
torchnlp/utils.py
def collate_tensors(batch, stack_tensors=torch.stack): """ Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. s...
def collate_tensors(batch, stack_tensors=torch.stack): """ Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. s...
[ "Collate", "a", "list", "of", "type", "k", "(", "dict", "namedtuple", "list", "etc", ".", ")", "with", "tensors", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L196-L238
[ "def", "collate_tensors", "(", "batch", ",", "stack_tensors", "=", "torch", ".", "stack", ")", ":", "if", "all", "(", "[", "torch", ".", "is_tensor", "(", "b", ")", "for", "b", "in", "batch", "]", ")", ":", "return", "stack_tensors", "(", "batch", ")...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
tensors_to
Apply ``torch.Tensor.to`` to tensors in a generic data structure. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor values to move. *args: Argume...
torchnlp/utils.py
def tensors_to(tensors, *args, **kwargs): """ Apply ``torch.Tensor.to`` to tensors in a generic data structure. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor...
def tensors_to(tensors, *args, **kwargs): """ Apply ``torch.Tensor.to`` to tensors in a generic data structure. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor...
[ "Apply", "torch", ".", "Tensor", ".", "to", "to", "tensors", "in", "a", "generic", "data", "structure", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L241-L281
[ "def", "tensors_to", "(", "tensors", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "torch", ".", "is_tensor", "(", "tensors", ")", ":", "return", "tensors", ".", "to", "(", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "isinstance...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
zero_dataset
Load the Zero dataset. The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for integration testing. The extreme simplicity of the dataset allows for models to learn the task quickly allowing for quick end-to-end testing. Args: train (bool, optional): If to lo...
torchnlp/datasets/zero.py
def zero_dataset(train=False, dev=False, test=False, train_rows=256, dev_rows=64, test_rows=64): """ Load the Zero dataset. The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for integration testing. The extreme simplicity of the dataset allows for models to learn th...
def zero_dataset(train=False, dev=False, test=False, train_rows=256, dev_rows=64, test_rows=64): """ Load the Zero dataset. The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for integration testing. The extreme simplicity of the dataset allows for models to learn th...
[ "Load", "the", "Zero", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/zero.py#L4-L41
[ "def", "zero_dataset", "(", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_rows", "=", "256", ",", "dev_rows", "=", "64", ",", "test_rows", "=", "64", ")", ":", "ret", "=", "[", "]", "for", "is_requested", "...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
SubwordEncoder.decode
Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``.
torchnlp/encoders/text/subword_encoder.py
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) return self.tokenizer.decode([self.itos[index]...
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) return self.tokenizer.decode([self.itos[index]...
[ "Decodes", "a", "tensor", "into", "a", "sequence", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/subword_encoder.py#L111-L121
[ "def", "decode", "(", "self", ",", "encoded", ")", ":", "encoded", "=", "super", "(", ")", ".", "decode", "(", "encoded", ")", "return", "self", ".", "tokenizer", ".", "decode", "(", "[", "self", ".", "itos", "[", "index", "]", "for", "index", "in"...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
LabelEncoder.encode
Encodes a ``label``. Args: label (object): Label to encode. Returns: torch.Tensor: Encoding of the label.
torchnlp/encoders/label_encoder.py
def encode(self, label): """ Encodes a ``label``. Args: label (object): Label to encode. Returns: torch.Tensor: Encoding of the label. """ label = super().encode(label) return torch.tensor(self.stoi.get(label, self.unknown_index))
def encode(self, label): """ Encodes a ``label``. Args: label (object): Label to encode. Returns: torch.Tensor: Encoding of the label. """ label = super().encode(label) return torch.tensor(self.stoi.get(label, self.unknown_index))
[ "Encodes", "a", "label", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/label_encoder.py#L76-L87
[ "def", "encode", "(", "self", ",", "label", ")", ":", "label", "=", "super", "(", ")", ".", "encode", "(", "label", ")", "return", "torch", ".", "tensor", "(", "self", ".", "stoi", ".", "get", "(", "label", ",", "self", ".", "unknown_index", ")", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
LabelEncoder.batch_encode
Args: iterator (iterator): Batch of labels to encode. *args: Arguments passed to ``Encoder.batch_encode``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword arguments passed to ``Encoder.batch_encode``. Returns: torc...
torchnlp/encoders/label_encoder.py
def batch_encode(self, iterator, *args, dim=0, **kwargs): """ Args: iterator (iterator): Batch of labels to encode. *args: Arguments passed to ``Encoder.batch_encode``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword ar...
def batch_encode(self, iterator, *args, dim=0, **kwargs): """ Args: iterator (iterator): Batch of labels to encode. *args: Arguments passed to ``Encoder.batch_encode``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword ar...
[ "Args", ":", "iterator", "(", "iterator", ")", ":", "Batch", "of", "labels", "to", "encode", ".", "*", "args", ":", "Arguments", "passed", "to", "Encoder", ".", "batch_encode", ".", "dim", "(", "int", "optional", ")", ":", "Dimension", "along", "which", ...
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/label_encoder.py#L89-L100
[ "def", "batch_encode", "(", "self", ",", "iterator", ",", "*", "args", ",", "dim", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "torch", ".", "stack", "(", "super", "(", ")", ".", "batch_encode", "(", "iterator", ",", "*", "args", ",", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
LabelEncoder.decode
Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``.
torchnlp/encoders/label_encoder.py
def decode(self, encoded): """ Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``. """ encoded = super().decode(encoded) if encoded.numel() > 1: raise ValueError( ...
def decode(self, encoded): """ Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``. """ encoded = super().decode(encoded) if encoded.numel() > 1: raise ValueError( ...
[ "Decodes", "encoded", "label", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/label_encoder.py#L102-L117
[ "def", "decode", "(", "self", ",", "encoded", ")", ":", "encoded", "=", "super", "(", ")", ".", "decode", "(", "encoded", ")", "if", "encoded", ".", "numel", "(", ")", ">", "1", ":", "raise", "ValueError", "(", "'``decode`` decodes one label at a time, use...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
LabelEncoder.batch_decode
Args: tensor (torch.Tensor): Batch of tensors. *args: Arguments passed to ``Encoder.batch_decode``. dim (int, optional): Dimension along which to split tensors. **kwargs: Keyword arguments passed to ``Encoder.batch_decode``. Returns: list: Batch of de...
torchnlp/encoders/label_encoder.py
def batch_decode(self, tensor, *args, dim=0, **kwargs): """ Args: tensor (torch.Tensor): Batch of tensors. *args: Arguments passed to ``Encoder.batch_decode``. dim (int, optional): Dimension along which to split tensors. **kwargs: Keyword arguments passed ...
def batch_decode(self, tensor, *args, dim=0, **kwargs): """ Args: tensor (torch.Tensor): Batch of tensors. *args: Arguments passed to ``Encoder.batch_decode``. dim (int, optional): Dimension along which to split tensors. **kwargs: Keyword arguments passed ...
[ "Args", ":", "tensor", "(", "torch", ".", "Tensor", ")", ":", "Batch", "of", "tensors", ".", "*", "args", ":", "Arguments", "passed", "to", "Encoder", ".", "batch_decode", ".", "dim", "(", "int", "optional", ")", ":", "Dimension", "along", "which", "to...
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/label_encoder.py#L119-L130
[ "def", "batch_decode", "(", "self", ",", "tensor", ",", "*", "args", ",", "dim", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", ")", ".", "batch_decode", "(", "[", "t", ".", "squeeze", "(", "0", ")", "for", "t", "in", "ten...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
count_dataset
Load the Count dataset. The Count dataset is a simple task of counting the number of integers in a sequence. This dataset is useful for testing implementations of sequence to label models. Args: train (bool, optional): If to load the training split of the dataset. dev (bool, optional): If ...
torchnlp/datasets/count.py
def count_dataset(train=False, dev=False, test=False, train_rows=10000, dev_rows=1000, test_rows=1000, seq_max_length=10): """ Load the Count dataset. The Count dataset is a simple task of counting t...
def count_dataset(train=False, dev=False, test=False, train_rows=10000, dev_rows=1000, test_rows=1000, seq_max_length=10): """ Load the Count dataset. The Count dataset is a simple task of counting t...
[ "Load", "the", "Count", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/count.py#L6-L64
[ "def", "count_dataset", "(", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_rows", "=", "10000", ",", "dev_rows", "=", "1000", ",", "test_rows", "=", "1000", ",", "seq_max_length", "=", "10", ")", ":", "ret", ...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
multi30k_dataset
Load the WMT 2016 machine translation dataset. As a translation task, this task consists in translating English sentences that describe an image into German, given the English sentence itself. As training and development data, we provide 29,000 and 1,014 triples respectively, each containing an English sou...
torchnlp/datasets/multi30k.py
def multi30k_dataset(directory='data/multi30k/', train=False, dev=False, test=False, train_filename='train', dev_filename='val', test_filename='test', check_files=['train.de...
def multi30k_dataset(directory='data/multi30k/', train=False, dev=False, test=False, train_filename='train', dev_filename='val', test_filename='test', check_files=['train.de...
[ "Load", "the", "WMT", "2016", "machine", "translation", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/multi30k.py#L7-L100
[ "def", "multi30k_dataset", "(", "directory", "=", "'data/multi30k/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'train'", ",", "dev_filename", "=", "'val'", ",", "test_filename", "=", "'test...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
penn_treebank_dataset
Load the Penn Treebank dataset. This is the Penn Treebank Project: Release 2 CDROM, featuring a million words of 1989 Wall Street Journal material. **Reference:** https://catalog.ldc.upenn.edu/ldc99t42 **Citation:** Marcus, Mitchell P., Marcinkiewicz, Mary Ann & Santorini, Beatrice (1993). Bu...
torchnlp/datasets/penn_treebank.py
def penn_treebank_dataset( directory='data/penn-treebank', train=False, dev=False, test=False, train_filename='ptb.train.txt', dev_filename='ptb.valid.txt', test_filename='ptb.test.txt', check_files=['ptb.train.txt'], urls=[ 'https://ra...
def penn_treebank_dataset( directory='data/penn-treebank', train=False, dev=False, test=False, train_filename='ptb.train.txt', dev_filename='ptb.valid.txt', test_filename='ptb.test.txt', check_files=['ptb.train.txt'], urls=[ 'https://ra...
[ "Load", "the", "Penn", "Treebank", "dataset", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/penn_treebank.py#L9-L80
[ "def", "penn_treebank_dataset", "(", "directory", "=", "'data/penn-treebank'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'ptb.train.txt'", ",", "dev_filename", "=", "'ptb.valid.txt'", ",", "test...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
repackage_hidden
Wraps hidden states in new Tensors, to detach them from their history.
examples/awd-lstm-lm/utils.py
def repackage_hidden(h): """Wraps hidden states in new Tensors, to detach them from their history.""" if isinstance(h, torch.Tensor): return h.detach() else: return tuple(repackage_hidden(v) for v in h)
def repackage_hidden(h): """Wraps hidden states in new Tensors, to detach them from their history.""" if isinstance(h, torch.Tensor): return h.detach() else: return tuple(repackage_hidden(v) for v in h)
[ "Wraps", "hidden", "states", "in", "new", "Tensors", "to", "detach", "them", "from", "their", "history", "." ]
PetrochukM/PyTorch-NLP
python
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/examples/awd-lstm-lm/utils.py#L4-L9
[ "def", "repackage_hidden", "(", "h", ")", ":", "if", "isinstance", "(", "h", ",", "torch", ".", "Tensor", ")", ":", "return", "h", ".", "detach", "(", ")", "else", ":", "return", "tuple", "(", "repackage_hidden", "(", "v", ")", "for", "v", "in", "h...
5f7320da5c8d781df072fab3f7e421c6347e5bfa
train
parse_to_ast
Parses the given vyper source code and returns a list of python AST objects for all statements in the source. Performs pre-processing of source code before parsing as well as post-processing of the resulting AST. :param source_code: The vyper source code to be parsed. :return: The post-processed list ...
vyper/parser/parser.py
def parse_to_ast(source_code: str) -> List[ast.stmt]: """ Parses the given vyper source code and returns a list of python AST objects for all statements in the source. Performs pre-processing of source code before parsing as well as post-processing of the resulting AST. :param source_code: The vyp...
def parse_to_ast(source_code: str) -> List[ast.stmt]: """ Parses the given vyper source code and returns a list of python AST objects for all statements in the source. Performs pre-processing of source code before parsing as well as post-processing of the resulting AST. :param source_code: The vyp...
[ "Parses", "the", "given", "vyper", "source", "code", "and", "returns", "a", "list", "of", "python", "AST", "objects", "for", "all", "statements", "in", "the", "source", ".", "Performs", "pre", "-", "processing", "of", "source", "code", "before", "parsing", ...
ethereum/vyper
python
https://github.com/ethereum/vyper/blob/c21a40a4f651ebd8426b29b8e2bb7d8b72b57cdd/vyper/parser/parser.py#L79-L97
[ "def", "parse_to_ast", "(", "source_code", ":", "str", ")", "->", "List", "[", "ast", ".", "stmt", "]", ":", "class_types", ",", "reformatted_code", "=", "pre_parse", "(", "source_code", ")", "if", "'\\x00'", "in", "reformatted_code", ":", "raise", "ParserEx...
c21a40a4f651ebd8426b29b8e2bb7d8b72b57cdd