repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
luqasz/librouteros | librouteros/connections.py | Decoder.decodeLength | def decodeLength(length):
"""
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length.
"""
bytes_length = len(length)
if bytes_length < 2:
offset = b'\x00\x00\x00'
XOR = 0
elif bytes_leng... | python | def decodeLength(length):
"""
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length.
"""
bytes_length = len(length)
if bytes_length < 2:
offset = b'\x00\x00\x00'
XOR = 0
elif bytes_leng... | [
"def",
"decodeLength",
"(",
"length",
")",
":",
"bytes_length",
"=",
"len",
"(",
"length",
")",
"if",
"bytes_length",
"<",
"2",
":",
"offset",
"=",
"b'\\x00\\x00\\x00'",
"XOR",
"=",
"0",
"elif",
"bytes_length",
"<",
"3",
":",
"offset",
"=",
"b'\\x00\\x00'"... | Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length. | [
"Decode",
"length",
"based",
"on",
"given",
"bytes",
"."
] | 59293eb49c07a339af87b0416e4619e78ca5176d | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L88-L114 | train |
luqasz/librouteros | librouteros/connections.py | ApiProtocol.writeSentence | def writeSentence(self, cmd, *words):
"""
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
"""
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded) | python | def writeSentence(self, cmd, *words):
"""
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
"""
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded) | [
"def",
"writeSentence",
"(",
"self",
",",
"cmd",
",",
"*",
"words",
")",
":",
"encoded",
"=",
"self",
".",
"encodeSentence",
"(",
"cmd",
",",
"*",
"words",
")",
"self",
".",
"log",
"(",
"'<---'",
",",
"cmd",
",",
"*",
"words",
")",
"self",
".",
"... | Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words. | [
"Write",
"encoded",
"sentence",
"."
] | 59293eb49c07a339af87b0416e4619e78ca5176d | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L129-L138 | train |
luqasz/librouteros | librouteros/connections.py | SocketTransport.read | def read(self, length):
"""
Read as many bytes from socket as specified in length.
Loop as long as every byte is read unless exception is raised.
"""
data = bytearray()
while len(data) != length:
data += self.sock.recv((length - len(data)))
if not ... | python | def read(self, length):
"""
Read as many bytes from socket as specified in length.
Loop as long as every byte is read unless exception is raised.
"""
data = bytearray()
while len(data) != length:
data += self.sock.recv((length - len(data)))
if not ... | [
"def",
"read",
"(",
"self",
",",
"length",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"while",
"len",
"(",
"data",
")",
"!=",
"length",
":",
"data",
"+=",
"self",
".",
"sock",
".",
"recv",
"(",
"(",
"length",
"-",
"len",
"(",
"data",
")",
")... | Read as many bytes from socket as specified in length.
Loop as long as every byte is read unless exception is raised. | [
"Read",
"as",
"many",
"bytes",
"from",
"socket",
"as",
"specified",
"in",
"length",
".",
"Loop",
"as",
"long",
"as",
"every",
"byte",
"is",
"read",
"unless",
"exception",
"is",
"raised",
"."
] | 59293eb49c07a339af87b0416e4619e78ca5176d | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L178-L188 | train |
luqasz/librouteros | librouteros/protocol.py | parseWord | def parseWord(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
... | python | def parseWord(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
... | [
"def",
"parseWord",
"(",
"word",
")",
":",
"mapping",
"=",
"{",
"'yes'",
":",
"True",
",",
"'true'",
":",
"True",
",",
"'no'",
":",
"False",
",",
"'false'",
":",
"False",
"}",
"_",
",",
"key",
",",
"value",
"=",
"word",
".",
"split",
"(",
"'='",
... | Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair. | [
"Split",
"given",
"attribute",
"word",
"to",
"key",
"value",
"pair",
"."
] | 59293eb49c07a339af87b0416e4619e78ca5176d | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L1-L16 | train |
luqasz/librouteros | librouteros/protocol.py | composeWord | def composeWord(key, value):
"""
Create a attribute word from key, value pair.
Values are casted to api equivalents.
"""
mapping = {True: 'yes', False: 'no'}
# this is necesary because 1 == True, 0 == False
if type(value) == int:
value = str(value)
else:
value = mapping.g... | python | def composeWord(key, value):
"""
Create a attribute word from key, value pair.
Values are casted to api equivalents.
"""
mapping = {True: 'yes', False: 'no'}
# this is necesary because 1 == True, 0 == False
if type(value) == int:
value = str(value)
else:
value = mapping.g... | [
"def",
"composeWord",
"(",
"key",
",",
"value",
")",
":",
"mapping",
"=",
"{",
"True",
":",
"'yes'",
",",
"False",
":",
"'no'",
"}",
"# this is necesary because 1 == True, 0 == False",
"if",
"type",
"(",
"value",
")",
"==",
"int",
":",
"value",
"=",
"str",... | Create a attribute word from key, value pair.
Values are casted to api equivalents. | [
"Create",
"a",
"attribute",
"word",
"from",
"key",
"value",
"pair",
".",
"Values",
"are",
"casted",
"to",
"api",
"equivalents",
"."
] | 59293eb49c07a339af87b0416e4619e78ca5176d | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L19-L30 | train |
luqasz/librouteros | librouteros/login.py | login_token | def login_token(api, username, password):
"""Login using pre routeros 6.43 authorization method."""
sentence = api('/login')
token = tuple(sentence)[0]['ret']
encoded = encode_password(token, password)
tuple(api('/login', **{'name': username, 'response': encoded})) | python | def login_token(api, username, password):
"""Login using pre routeros 6.43 authorization method."""
sentence = api('/login')
token = tuple(sentence)[0]['ret']
encoded = encode_password(token, password)
tuple(api('/login', **{'name': username, 'response': encoded})) | [
"def",
"login_token",
"(",
"api",
",",
"username",
",",
"password",
")",
":",
"sentence",
"=",
"api",
"(",
"'/login'",
")",
"token",
"=",
"tuple",
"(",
"sentence",
")",
"[",
"0",
"]",
"[",
"'ret'",
"]",
"encoded",
"=",
"encode_password",
"(",
"token",
... | Login using pre routeros 6.43 authorization method. | [
"Login",
"using",
"pre",
"routeros",
"6",
".",
"43",
"authorization",
"method",
"."
] | 59293eb49c07a339af87b0416e4619e78ca5176d | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/login.py#L15-L20 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.check_relations | def check_relations(self, relations):
"""Recursive function which checks if a relation is valid."""
for rel in relations:
if not rel:
continue
fields = rel.split('.', 1)
local_field = fields[0]
if local_field not in self.fields:
... | python | def check_relations(self, relations):
"""Recursive function which checks if a relation is valid."""
for rel in relations:
if not rel:
continue
fields = rel.split('.', 1)
local_field = fields[0]
if local_field not in self.fields:
... | [
"def",
"check_relations",
"(",
"self",
",",
"relations",
")",
":",
"for",
"rel",
"in",
"relations",
":",
"if",
"not",
"rel",
":",
"continue",
"fields",
"=",
"rel",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"local_field",
"=",
"fields",
"[",
"0",
"]",
... | Recursive function which checks if a relation is valid. | [
"Recursive",
"function",
"which",
"checks",
"if",
"a",
"relation",
"is",
"valid",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L102-L120 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.format_json_api_response | def format_json_api_response(self, data, many):
"""Post-dump hook that formats serialized data as a top-level JSON API object.
See: http://jsonapi.org/format/#document-top-level
"""
ret = self.format_items(data, many)
ret = self.wrap_response(ret, many)
ret = self.render... | python | def format_json_api_response(self, data, many):
"""Post-dump hook that formats serialized data as a top-level JSON API object.
See: http://jsonapi.org/format/#document-top-level
"""
ret = self.format_items(data, many)
ret = self.wrap_response(ret, many)
ret = self.render... | [
"def",
"format_json_api_response",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"ret",
"=",
"self",
".",
"format_items",
"(",
"data",
",",
"many",
")",
"ret",
"=",
"self",
".",
"wrap_response",
"(",
"ret",
",",
"many",
")",
"ret",
"=",
"self",
".... | Post-dump hook that formats serialized data as a top-level JSON API object.
See: http://jsonapi.org/format/#document-top-level | [
"Post",
"-",
"dump",
"hook",
"that",
"formats",
"serialized",
"data",
"as",
"a",
"top",
"-",
"level",
"JSON",
"API",
"object",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L123-L132 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema._do_load | def _do_load(self, data, many=None, **kwargs):
"""Override `marshmallow.Schema._do_load` for custom JSON API handling.
Specifically, we do this to format errors as JSON API Error objects,
and to support loading of included data.
"""
many = self.many if many is None else bool(man... | python | def _do_load(self, data, many=None, **kwargs):
"""Override `marshmallow.Schema._do_load` for custom JSON API handling.
Specifically, we do this to format errors as JSON API Error objects,
and to support loading of included data.
"""
many = self.many if many is None else bool(man... | [
"def",
"_do_load",
"(",
"self",
",",
"data",
",",
"many",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"many",
"=",
"self",
".",
"many",
"if",
"many",
"is",
"None",
"else",
"bool",
"(",
"many",
")",
"# Store this on the instance so we have access to the... | Override `marshmallow.Schema._do_load` for custom JSON API handling.
Specifically, we do this to format errors as JSON API Error objects,
and to support loading of included data. | [
"Override",
"marshmallow",
".",
"Schema",
".",
"_do_load",
"for",
"custom",
"JSON",
"API",
"handling",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L229-L260 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema._extract_from_included | def _extract_from_included(self, data):
"""Extract included data matching the items in ``data``.
For each item in ``data``, extract the full data from the included
data.
"""
return (item for item in self.included_data
if item['type'] == data['type'] and
... | python | def _extract_from_included(self, data):
"""Extract included data matching the items in ``data``.
For each item in ``data``, extract the full data from the included
data.
"""
return (item for item in self.included_data
if item['type'] == data['type'] and
... | [
"def",
"_extract_from_included",
"(",
"self",
",",
"data",
")",
":",
"return",
"(",
"item",
"for",
"item",
"in",
"self",
".",
"included_data",
"if",
"item",
"[",
"'type'",
"]",
"==",
"data",
"[",
"'type'",
"]",
"and",
"str",
"(",
"item",
"[",
"'id'",
... | Extract included data matching the items in ``data``.
For each item in ``data``, extract the full data from the included
data. | [
"Extract",
"included",
"data",
"matching",
"the",
"items",
"in",
"data",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L262-L270 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.inflect | def inflect(self, text):
"""Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise
do nothing.
"""
return self.opts.inflect(text) if self.opts.inflect else text | python | def inflect(self, text):
"""Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise
do nothing.
"""
return self.opts.inflect(text) if self.opts.inflect else text | [
"def",
"inflect",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"opts",
".",
"inflect",
"(",
"text",
")",
"if",
"self",
".",
"opts",
".",
"inflect",
"else",
"text"
] | Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise
do nothing. | [
"Inflect",
"text",
"if",
"the",
"inflect",
"class",
"Meta",
"option",
"is",
"defined",
"otherwise",
"do",
"nothing",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L272-L276 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.format_errors | def format_errors(self, errors, many):
"""Format validation errors as JSON Error objects."""
if not errors:
return {}
if isinstance(errors, (list, tuple)):
return {'errors': errors}
formatted_errors = []
if many:
for index, errors in iteritems... | python | def format_errors(self, errors, many):
"""Format validation errors as JSON Error objects."""
if not errors:
return {}
if isinstance(errors, (list, tuple)):
return {'errors': errors}
formatted_errors = []
if many:
for index, errors in iteritems... | [
"def",
"format_errors",
"(",
"self",
",",
"errors",
",",
"many",
")",
":",
"if",
"not",
"errors",
":",
"return",
"{",
"}",
"if",
"isinstance",
"(",
"errors",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"{",
"'errors'",
":",
"errors",
"... | Format validation errors as JSON Error objects. | [
"Format",
"validation",
"errors",
"as",
"JSON",
"Error",
"objects",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L280-L301 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.format_error | def format_error(self, field_name, message, index=None):
"""Override-able hook to format a single error message as an Error object.
See: http://jsonapi.org/format/#error-objects
"""
pointer = ['/data']
if index is not None:
pointer.append(str(index))
relati... | python | def format_error(self, field_name, message, index=None):
"""Override-able hook to format a single error message as an Error object.
See: http://jsonapi.org/format/#error-objects
"""
pointer = ['/data']
if index is not None:
pointer.append(str(index))
relati... | [
"def",
"format_error",
"(",
"self",
",",
"field_name",
",",
"message",
",",
"index",
"=",
"None",
")",
":",
"pointer",
"=",
"[",
"'/data'",
"]",
"if",
"index",
"is",
"not",
"None",
":",
"pointer",
".",
"append",
"(",
"str",
"(",
"index",
")",
")",
... | Override-able hook to format a single error message as an Error object.
See: http://jsonapi.org/format/#error-objects | [
"Override",
"-",
"able",
"hook",
"to",
"format",
"a",
"single",
"error",
"message",
"as",
"an",
"Error",
"object",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L303-L332 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.format_item | def format_item(self, item):
"""Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
"""
# http://jsonapi.org/format/#document-top-level
# Primary data MUST be either... a single resource object, a single resource
# identi... | python | def format_item(self, item):
"""Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
"""
# http://jsonapi.org/format/#document-top-level
# Primary data MUST be either... a single resource object, a single resource
# identi... | [
"def",
"format_item",
"(",
"self",
",",
"item",
")",
":",
"# http://jsonapi.org/format/#document-top-level",
"# Primary data MUST be either... a single resource object, a single resource",
"# identifier object, or null, for requests that target single resources",
"if",
"not",
"item",
":"... | Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects | [
"Format",
"a",
"single",
"datum",
"as",
"a",
"Resource",
"object",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L334-L379 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.format_items | def format_items(self, data, many):
"""Format data as a Resource object or list of Resource objects.
See: http://jsonapi.org/format/#document-resource-objects
"""
if many:
return [self.format_item(item) for item in data]
else:
return self.format_item(data... | python | def format_items(self, data, many):
"""Format data as a Resource object or list of Resource objects.
See: http://jsonapi.org/format/#document-resource-objects
"""
if many:
return [self.format_item(item) for item in data]
else:
return self.format_item(data... | [
"def",
"format_items",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"if",
"many",
":",
"return",
"[",
"self",
".",
"format_item",
"(",
"item",
")",
"for",
"item",
"in",
"data",
"]",
"else",
":",
"return",
"self",
".",
"format_item",
"(",
"data",
... | Format data as a Resource object or list of Resource objects.
See: http://jsonapi.org/format/#document-resource-objects | [
"Format",
"data",
"as",
"a",
"Resource",
"object",
"or",
"list",
"of",
"Resource",
"objects",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L381-L389 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.get_top_level_links | def get_top_level_links(self, data, many):
"""Hook for adding links to the root of the response data."""
self_link = None
if many:
if self.opts.self_url_many:
self_link = self.generate_url(self.opts.self_url_many)
else:
if self.opts.self_url:
... | python | def get_top_level_links(self, data, many):
"""Hook for adding links to the root of the response data."""
self_link = None
if many:
if self.opts.self_url_many:
self_link = self.generate_url(self.opts.self_url_many)
else:
if self.opts.self_url:
... | [
"def",
"get_top_level_links",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"self_link",
"=",
"None",
"if",
"many",
":",
"if",
"self",
".",
"opts",
".",
"self_url_many",
":",
"self_link",
"=",
"self",
".",
"generate_url",
"(",
"self",
".",
"opts",
"... | Hook for adding links to the root of the response data. | [
"Hook",
"for",
"adding",
"links",
"to",
"the",
"root",
"of",
"the",
"response",
"data",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L391-L402 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.get_resource_links | def get_resource_links(self, item):
"""Hook for adding links to a resource object."""
if self.opts.self_url:
ret = self.dict_class()
kwargs = resolve_params(item, self.opts.self_url_kwargs or {})
ret['self'] = self.generate_url(self.opts.self_url, **kwargs)
... | python | def get_resource_links(self, item):
"""Hook for adding links to a resource object."""
if self.opts.self_url:
ret = self.dict_class()
kwargs = resolve_params(item, self.opts.self_url_kwargs or {})
ret['self'] = self.generate_url(self.opts.self_url, **kwargs)
... | [
"def",
"get_resource_links",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"opts",
".",
"self_url",
":",
"ret",
"=",
"self",
".",
"dict_class",
"(",
")",
"kwargs",
"=",
"resolve_params",
"(",
"item",
",",
"self",
".",
"opts",
".",
"self_url_kw... | Hook for adding links to a resource object. | [
"Hook",
"for",
"adding",
"links",
"to",
"a",
"resource",
"object",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L404-L411 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/schema.py | Schema.wrap_response | def wrap_response(self, data, many):
"""Wrap data and links according to the JSON API """
ret = {'data': data}
# self_url_many is still valid when there isn't any data, but self_url
# may only be included if there is data in the ret
if many or data:
top_level_links = ... | python | def wrap_response(self, data, many):
"""Wrap data and links according to the JSON API """
ret = {'data': data}
# self_url_many is still valid when there isn't any data, but self_url
# may only be included if there is data in the ret
if many or data:
top_level_links = ... | [
"def",
"wrap_response",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"ret",
"=",
"{",
"'data'",
":",
"data",
"}",
"# self_url_many is still valid when there isn't any data, but self_url",
"# may only be included if there is data in the ret",
"if",
"many",
"or",
"data"... | Wrap data and links according to the JSON API | [
"Wrap",
"data",
"and",
"links",
"according",
"to",
"the",
"JSON",
"API"
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L413-L422 | train |
marshmallow-code/marshmallow-jsonapi | marshmallow_jsonapi/fields.py | Relationship.extract_value | def extract_value(self, data):
"""Extract the id key and validate the request structure."""
errors = []
if 'id' not in data:
errors.append('Must have an `id` field')
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self... | python | def extract_value(self, data):
"""Extract the id key and validate the request structure."""
errors = []
if 'id' not in data:
errors.append('Must have an `id` field')
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self... | [
"def",
"extract_value",
"(",
"self",
",",
"data",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"'id'",
"not",
"in",
"data",
":",
"errors",
".",
"append",
"(",
"'Must have an `id` field'",
")",
"if",
"'type'",
"not",
"in",
"data",
":",
"errors",
".",
"appen... | Extract the id key and validate the request structure. | [
"Extract",
"the",
"id",
"key",
"and",
"validate",
"the",
"request",
"structure",
"."
] | 7183c9bb5cdeace4143e6678bab48d433ac439a1 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/fields.py#L183-L208 | train |
thoth-station/python | thoth/python/helpers.py | fill_package_digests | def fill_package_digests(generated_project: Project) -> Project:
"""Temporary fill package digests stated in Pipfile.lock."""
for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages):
if package_version.hashes:
# Already filled from t... | python | def fill_package_digests(generated_project: Project) -> Project:
"""Temporary fill package digests stated in Pipfile.lock."""
for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages):
if package_version.hashes:
# Already filled from t... | [
"def",
"fill_package_digests",
"(",
"generated_project",
":",
"Project",
")",
"->",
"Project",
":",
"for",
"package_version",
"in",
"chain",
"(",
"generated_project",
".",
"pipfile_lock",
".",
"packages",
",",
"generated_project",
".",
"pipfile_lock",
".",
"dev_pack... | Temporary fill package digests stated in Pipfile.lock. | [
"Temporary",
"fill",
"package",
"digests",
"stated",
"in",
"Pipfile",
".",
"lock",
"."
] | bd2a4a4f552faf54834ce9febea4e2834a1d0bab | https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/helpers.py#L26-L50 | train |
thoth-station/python | thoth/python/digests_fetcher.py | PythonDigestsFetcher.fetch_digests | def fetch_digests(self, package_name: str, package_version: str) -> dict:
"""Fetch digests for the given package in specified version from the given package index."""
report = {}
for source in self._sources:
try:
report[source.url] = source.get_package_hashes(package... | python | def fetch_digests(self, package_name: str, package_version: str) -> dict:
"""Fetch digests for the given package in specified version from the given package index."""
report = {}
for source in self._sources:
try:
report[source.url] = source.get_package_hashes(package... | [
"def",
"fetch_digests",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"package_version",
":",
"str",
")",
"->",
"dict",
":",
"report",
"=",
"{",
"}",
"for",
"source",
"in",
"self",
".",
"_sources",
":",
"try",
":",
"report",
"[",
"source",
".",
... | Fetch digests for the given package in specified version from the given package index. | [
"Fetch",
"digests",
"for",
"the",
"given",
"package",
"in",
"specified",
"version",
"from",
"the",
"given",
"package",
"index",
"."
] | bd2a4a4f552faf54834ce9febea4e2834a1d0bab | https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/digests_fetcher.py#L44-L57 | train |
blockstack/pybitcoin | pybitcoin/passphrases/legacy.py | random_passphrase_from_wordlist | def random_passphrase_from_wordlist(phrase_length, wordlist):
""" An extremely entropy efficient passphrase generator.
This function:
-Pulls entropy from the safer alternative to /dev/urandom: /dev/random
-Doesn't rely on random.seed (words are selected right from the entropy)
-Only... | python | def random_passphrase_from_wordlist(phrase_length, wordlist):
""" An extremely entropy efficient passphrase generator.
This function:
-Pulls entropy from the safer alternative to /dev/urandom: /dev/random
-Doesn't rely on random.seed (words are selected right from the entropy)
-Only... | [
"def",
"random_passphrase_from_wordlist",
"(",
"phrase_length",
",",
"wordlist",
")",
":",
"passphrase_words",
"=",
"[",
"]",
"numbytes_of_entropy",
"=",
"phrase_length",
"*",
"2",
"entropy",
"=",
"list",
"(",
"dev_random_entropy",
"(",
"numbytes_of_entropy",
",",
"... | An extremely entropy efficient passphrase generator.
This function:
-Pulls entropy from the safer alternative to /dev/urandom: /dev/random
-Doesn't rely on random.seed (words are selected right from the entropy)
-Only requires 2 entropy bytes/word for word lists of up to 65536 words | [
"An",
"extremely",
"entropy",
"efficient",
"passphrase",
"generator",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/legacy.py#L15-L41 | train |
blockstack/pybitcoin | pybitcoin/hash.py | reverse_hash | def reverse_hash(hash, hex_format=True):
""" hash is in hex or binary format
"""
if not hex_format:
hash = hexlify(hash)
return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)])) | python | def reverse_hash(hash, hex_format=True):
""" hash is in hex or binary format
"""
if not hex_format:
hash = hexlify(hash)
return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)])) | [
"def",
"reverse_hash",
"(",
"hash",
",",
"hex_format",
"=",
"True",
")",
":",
"if",
"not",
"hex_format",
":",
"hash",
"=",
"hexlify",
"(",
"hash",
")",
"return",
"\"\"",
".",
"join",
"(",
"reversed",
"(",
"[",
"hash",
"[",
"i",
":",
"i",
"+",
"2",
... | hash is in hex or binary format | [
"hash",
"is",
"in",
"hex",
"or",
"binary",
"format"
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/hash.py#L45-L50 | train |
blockstack/pybitcoin | pybitcoin/passphrases/passphrase.py | get_num_words_with_entropy | def get_num_words_with_entropy(bits_of_entropy, wordlist):
""" Gets the number of words randomly selected from a given wordlist that
would result in the number of bits of entropy specified.
"""
entropy_per_word = math.log(len(wordlist))/math.log(2)
num_words = int(math.ceil(bits_of_entropy/entro... | python | def get_num_words_with_entropy(bits_of_entropy, wordlist):
""" Gets the number of words randomly selected from a given wordlist that
would result in the number of bits of entropy specified.
"""
entropy_per_word = math.log(len(wordlist))/math.log(2)
num_words = int(math.ceil(bits_of_entropy/entro... | [
"def",
"get_num_words_with_entropy",
"(",
"bits_of_entropy",
",",
"wordlist",
")",
":",
"entropy_per_word",
"=",
"math",
".",
"log",
"(",
"len",
"(",
"wordlist",
")",
")",
"/",
"math",
".",
"log",
"(",
"2",
")",
"num_words",
"=",
"int",
"(",
"math",
".",... | Gets the number of words randomly selected from a given wordlist that
would result in the number of bits of entropy specified. | [
"Gets",
"the",
"number",
"of",
"words",
"randomly",
"selected",
"from",
"a",
"given",
"wordlist",
"that",
"would",
"result",
"in",
"the",
"number",
"of",
"bits",
"of",
"entropy",
"specified",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L29-L35 | train |
blockstack/pybitcoin | pybitcoin/passphrases/passphrase.py | create_passphrase | def create_passphrase(bits_of_entropy=None, num_words=None,
language='english', word_source='wiktionary'):
""" Creates a passphrase that has a certain number of bits of entropy OR
a certain number of words.
"""
wordlist = get_wordlist(language, word_source)
if not num_word... | python | def create_passphrase(bits_of_entropy=None, num_words=None,
language='english', word_source='wiktionary'):
""" Creates a passphrase that has a certain number of bits of entropy OR
a certain number of words.
"""
wordlist = get_wordlist(language, word_source)
if not num_word... | [
"def",
"create_passphrase",
"(",
"bits_of_entropy",
"=",
"None",
",",
"num_words",
"=",
"None",
",",
"language",
"=",
"'english'",
",",
"word_source",
"=",
"'wiktionary'",
")",
":",
"wordlist",
"=",
"get_wordlist",
"(",
"language",
",",
"word_source",
")",
"if... | Creates a passphrase that has a certain number of bits of entropy OR
a certain number of words. | [
"Creates",
"a",
"passphrase",
"that",
"has",
"a",
"certain",
"number",
"of",
"bits",
"of",
"entropy",
"OR",
"a",
"certain",
"number",
"of",
"words",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L42-L54 | train |
blockstack/pybitcoin | pybitcoin/transactions/serialize.py | serialize_input | def serialize_input(input, signature_script_hex=''):
""" Serializes a transaction input.
"""
if not (isinstance(input, dict) and 'transaction_hash' in input \
and 'output_index' in input):
raise Exception('Required parameters: transaction_hash, output_index')
if is_hex(str(input['tr... | python | def serialize_input(input, signature_script_hex=''):
""" Serializes a transaction input.
"""
if not (isinstance(input, dict) and 'transaction_hash' in input \
and 'output_index' in input):
raise Exception('Required parameters: transaction_hash, output_index')
if is_hex(str(input['tr... | [
"def",
"serialize_input",
"(",
"input",
",",
"signature_script_hex",
"=",
"''",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"input",
",",
"dict",
")",
"and",
"'transaction_hash'",
"in",
"input",
"and",
"'output_index'",
"in",
"input",
")",
":",
"raise",
... | Serializes a transaction input. | [
"Serializes",
"a",
"transaction",
"input",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L20-L42 | train |
blockstack/pybitcoin | pybitcoin/transactions/serialize.py | serialize_output | def serialize_output(output):
""" Serializes a transaction output.
"""
if not ('value' in output and 'script_hex' in output):
raise Exception('Invalid output')
return ''.join([
hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites
hexlify(variable_length_int(len(outpu... | python | def serialize_output(output):
""" Serializes a transaction output.
"""
if not ('value' in output and 'script_hex' in output):
raise Exception('Invalid output')
return ''.join([
hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites
hexlify(variable_length_int(len(outpu... | [
"def",
"serialize_output",
"(",
"output",
")",
":",
"if",
"not",
"(",
"'value'",
"in",
"output",
"and",
"'script_hex'",
"in",
"output",
")",
":",
"raise",
"Exception",
"(",
"'Invalid output'",
")",
"return",
"''",
".",
"join",
"(",
"[",
"hexlify",
"(",
"... | Serializes a transaction output. | [
"Serializes",
"a",
"transaction",
"output",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L45-L55 | train |
blockstack/pybitcoin | pybitcoin/transactions/serialize.py | serialize_transaction | def serialize_transaction(inputs, outputs, lock_time=0, version=1):
""" Serializes a transaction.
"""
# add in the inputs
serialized_inputs = ''.join([serialize_input(input) for input in inputs])
# add in the outputs
serialized_outputs = ''.join([serialize_output(output) for output in outputs]... | python | def serialize_transaction(inputs, outputs, lock_time=0, version=1):
""" Serializes a transaction.
"""
# add in the inputs
serialized_inputs = ''.join([serialize_input(input) for input in inputs])
# add in the outputs
serialized_outputs = ''.join([serialize_output(output) for output in outputs]... | [
"def",
"serialize_transaction",
"(",
"inputs",
",",
"outputs",
",",
"lock_time",
"=",
"0",
",",
"version",
"=",
"1",
")",
":",
"# add in the inputs",
"serialized_inputs",
"=",
"''",
".",
"join",
"(",
"[",
"serialize_input",
"(",
"input",
")",
"for",
"input",... | Serializes a transaction. | [
"Serializes",
"a",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L58-L81 | train |
blockstack/pybitcoin | pybitcoin/transactions/serialize.py | deserialize_transaction | def deserialize_transaction(tx_hex):
"""
Given a serialized transaction, return its inputs, outputs,
locktime, and version
Each input will have:
* transaction_hash: string
* output_index: int
* [optional] sequence: int
* [optional] script_sig: string
... | python | def deserialize_transaction(tx_hex):
"""
Given a serialized transaction, return its inputs, outputs,
locktime, and version
Each input will have:
* transaction_hash: string
* output_index: int
* [optional] sequence: int
* [optional] script_sig: string
... | [
"def",
"deserialize_transaction",
"(",
"tx_hex",
")",
":",
"tx",
"=",
"bitcoin",
".",
"deserialize",
"(",
"str",
"(",
"tx_hex",
")",
")",
"inputs",
"=",
"tx",
"[",
"\"ins\"",
"]",
"outputs",
"=",
"tx",
"[",
"\"outs\"",
"]",
"ret_inputs",
"=",
"[",
"]",... | Given a serialized transaction, return its inputs, outputs,
locktime, and version
Each input will have:
* transaction_hash: string
* output_index: int
* [optional] sequence: int
* [optional] script_sig: string
Each output will have:
* value: int
... | [
"Given",
"a",
"serialized",
"transaction",
"return",
"its",
"inputs",
"outputs",
"locktime",
"and",
"version"
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L84-L130 | train |
blockstack/pybitcoin | pybitcoin/transactions/utils.py | variable_length_int | def variable_length_int(i):
""" Encodes integers into variable length integers, which are used in
Bitcoin in order to save space.
"""
if not isinstance(i, (int,long)):
raise Exception('i must be an integer')
if i < (2**8-3):
return chr(i) # pack the integer into one byte
eli... | python | def variable_length_int(i):
""" Encodes integers into variable length integers, which are used in
Bitcoin in order to save space.
"""
if not isinstance(i, (int,long)):
raise Exception('i must be an integer')
if i < (2**8-3):
return chr(i) # pack the integer into one byte
eli... | [
"def",
"variable_length_int",
"(",
"i",
")",
":",
"if",
"not",
"isinstance",
"(",
"i",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"Exception",
"(",
"'i must be an integer'",
")",
"if",
"i",
"<",
"(",
"2",
"**",
"8",
"-",
"3",
")",
":",
... | Encodes integers into variable length integers, which are used in
Bitcoin in order to save space. | [
"Encodes",
"integers",
"into",
"variable",
"length",
"integers",
"which",
"are",
"used",
"in",
"Bitcoin",
"in",
"order",
"to",
"save",
"space",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/utils.py#L25-L41 | train |
blockstack/pybitcoin | pybitcoin/transactions/scripts.py | make_pay_to_address_script | def make_pay_to_address_script(address):
""" Takes in an address and returns the script
"""
hash160 = hexlify(b58check_decode(address))
script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160
return script_to_hex(script_string) | python | def make_pay_to_address_script(address):
""" Takes in an address and returns the script
"""
hash160 = hexlify(b58check_decode(address))
script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160
return script_to_hex(script_string) | [
"def",
"make_pay_to_address_script",
"(",
"address",
")",
":",
"hash160",
"=",
"hexlify",
"(",
"b58check_decode",
"(",
"address",
")",
")",
"script_string",
"=",
"'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG'",
"%",
"hash160",
"return",
"script_to_hex",
"(",
"script... | Takes in an address and returns the script | [
"Takes",
"in",
"an",
"address",
"and",
"returns",
"the",
"script"
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L37-L42 | train |
blockstack/pybitcoin | pybitcoin/transactions/scripts.py | make_op_return_script | def make_op_return_script(data, format='bin'):
""" Takes in raw ascii data to be embedded and returns a script.
"""
if format == 'hex':
assert(is_hex(data))
hex_data = data
elif format == 'bin':
hex_data = hexlify(data)
else:
raise Exception("Format must be either 'he... | python | def make_op_return_script(data, format='bin'):
""" Takes in raw ascii data to be embedded and returns a script.
"""
if format == 'hex':
assert(is_hex(data))
hex_data = data
elif format == 'bin':
hex_data = hexlify(data)
else:
raise Exception("Format must be either 'he... | [
"def",
"make_op_return_script",
"(",
"data",
",",
"format",
"=",
"'bin'",
")",
":",
"if",
"format",
"==",
"'hex'",
":",
"assert",
"(",
"is_hex",
"(",
"data",
")",
")",
"hex_data",
"=",
"data",
"elif",
"format",
"==",
"'bin'",
":",
"hex_data",
"=",
"hex... | Takes in raw ascii data to be embedded and returns a script. | [
"Takes",
"in",
"raw",
"ascii",
"data",
"to",
"be",
"embedded",
"and",
"returns",
"a",
"script",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L44-L60 | train |
blockstack/pybitcoin | pybitcoin/services/bitcoind.py | create_bitcoind_service_proxy | def create_bitcoind_service_proxy(
rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False):
""" create a bitcoind service proxy
"""
protocol = 'https' if use_https else 'http'
uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password,
server, port)
return AuthS... | python | def create_bitcoind_service_proxy(
rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False):
""" create a bitcoind service proxy
"""
protocol = 'https' if use_https else 'http'
uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password,
server, port)
return AuthS... | [
"def",
"create_bitcoind_service_proxy",
"(",
"rpc_username",
",",
"rpc_password",
",",
"server",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8332",
",",
"use_https",
"=",
"False",
")",
":",
"protocol",
"=",
"'https'",
"if",
"use_https",
"else",
"'http'",
"uri",
"="... | create a bitcoind service proxy | [
"create",
"a",
"bitcoind",
"service",
"proxy"
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/services/bitcoind.py#L21-L28 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | get_unspents | def get_unspents(address, blockchain_client=BlockchainInfoClient()):
""" Gets the unspent outputs for a given address.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
... | python | def get_unspents(address, blockchain_client=BlockchainInfoClient()):
""" Gets the unspent outputs for a given address.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
... | [
"def",
"get_unspents",
"(",
"address",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"blockchain_client",
",",
"BlockcypherClient",
")",
":",
"return",
"blockcypher",
".",
"get_unspents",
"(",
"address",
",",
... | Gets the unspent outputs for a given address. | [
"Gets",
"the",
"unspent",
"outputs",
"for",
"a",
"given",
"address",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L32-L48 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | broadcast_transaction | def broadcast_transaction(hex_tx, blockchain_client):
""" Dispatches a raw hex transaction to the network.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
... | python | def broadcast_transaction(hex_tx, blockchain_client):
""" Dispatches a raw hex transaction to the network.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
... | [
"def",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
":",
"if",
"isinstance",
"(",
"blockchain_client",
",",
"BlockcypherClient",
")",
":",
"return",
"blockcypher",
".",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
... | Dispatches a raw hex transaction to the network. | [
"Dispatches",
"a",
"raw",
"hex",
"transaction",
"to",
"the",
"network",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L51-L67 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | make_send_to_address_tx | def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, f... | python | def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, f... | [
"def",
"make_send_to_address_tx",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"STANDARD_FEE",
",",
"change_address",
"=",
"None",
")",
":",
"# get out the private key ob... | Builds and signs a "send to address" transaction. | [
"Builds",
"and",
"signs",
"a",
"send",
"to",
"address",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L87-L110 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | make_op_return_tx | def make_op_return_tx(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds and signs an OP_RETURN transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs... | python | def make_op_return_tx(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds and signs an OP_RETURN transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs... | [
"def",
"make_op_return_tx",
"(",
"data",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"change_address",
"=",
"None",
",",
"format",
"=",
"'bin'",
")",
":",
"# get out the private key ob... | Builds and signs an OP_RETURN transaction. | [
"Builds",
"and",
"signs",
"an",
"OP_RETURN",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L113-L136 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | send_to_address | def send_to_address(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds, signs, and dispatches a "send to address" transaction.
"""
# build and sign the tx
signed_tx = make_send_to_address_tx(recipient_addre... | python | def send_to_address(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds, signs, and dispatches a "send to address" transaction.
"""
# build and sign the tx
signed_tx = make_send_to_address_tx(recipient_addre... | [
"def",
"send_to_address",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"STANDARD_FEE",
",",
"change_address",
"=",
"None",
")",
":",
"# build and sign the tx",
"signed_... | Builds, signs, and dispatches a "send to address" transaction. | [
"Builds",
"signs",
"and",
"dispatches",
"a",
"send",
"to",
"address",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L139-L151 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | embed_data_in_blockchain | def embed_data_in_blockchain(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds, signs, and dispatches an OP_RETURN transaction.
"""
# build and sign the tx
signed_tx = make_op_return_tx(data, private_key, blockc... | python | def embed_data_in_blockchain(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds, signs, and dispatches an OP_RETURN transaction.
"""
# build and sign the tx
signed_tx = make_op_return_tx(data, private_key, blockc... | [
"def",
"embed_data_in_blockchain",
"(",
"data",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"change_address",
"=",
"None",
",",
"format",
"=",
"'bin'",
")",
":",
"# build and sign the ... | Builds, signs, and dispatches an OP_RETURN transaction. | [
"Builds",
"signs",
"and",
"dispatches",
"an",
"OP_RETURN",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L154-L165 | train |
blockstack/pybitcoin | pybitcoin/transactions/network.py | sign_all_unsigned_inputs | def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex):
"""
Sign a serialized transaction's unsigned inputs
@hex_privkey: private key that should sign inputs
@unsigned_tx_hex: hex transaction with unsigned inputs
Returns: signed hex transaction
"""
inputs, outputs, lock... | python | def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex):
"""
Sign a serialized transaction's unsigned inputs
@hex_privkey: private key that should sign inputs
@unsigned_tx_hex: hex transaction with unsigned inputs
Returns: signed hex transaction
"""
inputs, outputs, lock... | [
"def",
"sign_all_unsigned_inputs",
"(",
"hex_privkey",
",",
"unsigned_tx_hex",
")",
":",
"inputs",
",",
"outputs",
",",
"locktime",
",",
"version",
"=",
"deserialize_transaction",
"(",
"unsigned_tx_hex",
")",
"tx_hex",
"=",
"unsigned_tx_hex",
"for",
"index",
"in",
... | Sign a serialized transaction's unsigned inputs
@hex_privkey: private key that should sign inputs
@unsigned_tx_hex: hex transaction with unsigned inputs
Returns: signed hex transaction | [
"Sign",
"a",
"serialized",
"transaction",
"s",
"unsigned",
"inputs"
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L187-L205 | train |
blockstack/pybitcoin | pybitcoin/merkle.py | calculate_merkle_root | def calculate_merkle_root(hashes, hash_function=bin_double_sha256,
hex_format=True):
""" takes in a list of binary hashes, returns a binary hash
"""
if hex_format:
hashes = hex_to_bin_reversed_hashes(hashes)
# keep moving up the merkle tree, constructing one row at a ti... | python | def calculate_merkle_root(hashes, hash_function=bin_double_sha256,
hex_format=True):
""" takes in a list of binary hashes, returns a binary hash
"""
if hex_format:
hashes = hex_to_bin_reversed_hashes(hashes)
# keep moving up the merkle tree, constructing one row at a ti... | [
"def",
"calculate_merkle_root",
"(",
"hashes",
",",
"hash_function",
"=",
"bin_double_sha256",
",",
"hex_format",
"=",
"True",
")",
":",
"if",
"hex_format",
":",
"hashes",
"=",
"hex_to_bin_reversed_hashes",
"(",
"hashes",
")",
"# keep moving up the merkle tree, construc... | takes in a list of binary hashes, returns a binary hash | [
"takes",
"in",
"a",
"list",
"of",
"binary",
"hashes",
"returns",
"a",
"binary",
"hash"
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/merkle.py#L23-L38 | train |
blockstack/pybitcoin | pybitcoin/b58check.py | b58check_encode | def b58check_encode(bin_s, version_byte=0):
""" Takes in a binary string and converts it to a base 58 check string. """
# append the version byte to the beginning
bin_s = chr(int(version_byte)) + bin_s
# calculate the number of leading zeros
num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0... | python | def b58check_encode(bin_s, version_byte=0):
""" Takes in a binary string and converts it to a base 58 check string. """
# append the version byte to the beginning
bin_s = chr(int(version_byte)) + bin_s
# calculate the number of leading zeros
num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0... | [
"def",
"b58check_encode",
"(",
"bin_s",
",",
"version_byte",
"=",
"0",
")",
":",
"# append the version byte to the beginning",
"bin_s",
"=",
"chr",
"(",
"int",
"(",
"version_byte",
")",
")",
"+",
"bin_s",
"# calculate the number of leading zeros",
"num_leading_zeros",
... | Takes in a binary string and converts it to a base 58 check string. | [
"Takes",
"in",
"a",
"binary",
"string",
"and",
"converts",
"it",
"to",
"a",
"base",
"58",
"check",
"string",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/b58check.py#L20-L33 | train |
blockstack/pybitcoin | pybitcoin/transactions/outputs.py | make_pay_to_address_outputs | def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address,
fee=STANDARD_FEE):
""" Builds the outputs for a "pay to address" transaction.
"""
return [
# main output
{ "script_hex": make_pay_to_address_script(to_address), "value": send_amou... | python | def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address,
fee=STANDARD_FEE):
""" Builds the outputs for a "pay to address" transaction.
"""
return [
# main output
{ "script_hex": make_pay_to_address_script(to_address), "value": send_amou... | [
"def",
"make_pay_to_address_outputs",
"(",
"to_address",
",",
"send_amount",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"STANDARD_FEE",
")",
":",
"return",
"[",
"# main output",
"{",
"\"script_hex\"",
":",
"make_pay_to_address_script",
"(",
"to_address",
... | Builds the outputs for a "pay to address" transaction. | [
"Builds",
"the",
"outputs",
"for",
"a",
"pay",
"to",
"address",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L23-L34 | train |
blockstack/pybitcoin | pybitcoin/transactions/outputs.py | make_op_return_outputs | def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amoun... | python | def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amoun... | [
"def",
"make_op_return_outputs",
"(",
"data",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"send_amount",
"=",
"0",
",",
"format",
"=",
"'bin'",
")",
":",
"return",
"[",
"# main output",
"{",
"\"script_hex\"",
":",
"make_op_retu... | Builds the outputs for an OP_RETURN transaction. | [
"Builds",
"the",
"outputs",
"for",
"an",
"OP_RETURN",
"transaction",
"."
] | 92c8da63c40f7418594b1ce395990c3f5a4787cc | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L36-L47 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | add_timezone | def add_timezone(value, tz=None):
"""If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
"""
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
... | python | def add_timezone(value, tz=None):
"""If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
"""
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
... | [
"def",
"add_timezone",
"(",
"value",
",",
"tz",
"=",
"None",
")",
":",
"tz",
"=",
"tz",
"or",
"timezone",
".",
"get_current_timezone",
"(",
")",
"try",
":",
"if",
"timezone",
".",
"is_naive",
"(",
"value",
")",
":",
"return",
"timezone",
".",
"make_awa... | If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used. | [
"If",
"the",
"value",
"is",
"naive",
"then",
"the",
"timezone",
"is",
"added",
"to",
"it",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L16-L28 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | get_active_entry | def get_active_entry(user, select_for_update=False):
"""Returns the user's currently-active entry, or None."""
entries = apps.get_model('entries', 'Entry').no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not e... | python | def get_active_entry(user, select_for_update=False):
"""Returns the user's currently-active entry, or None."""
entries = apps.get_model('entries', 'Entry').no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not e... | [
"def",
"get_active_entry",
"(",
"user",
",",
"select_for_update",
"=",
"False",
")",
":",
"entries",
"=",
"apps",
".",
"get_model",
"(",
"'entries'",
",",
"'Entry'",
")",
".",
"no_join",
"if",
"select_for_update",
":",
"entries",
"=",
"entries",
".",
"select... | Returns the user's currently-active entry, or None. | [
"Returns",
"the",
"user",
"s",
"currently",
"-",
"active",
"entry",
"or",
"None",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L31-L42 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | get_month_start | def get_month_start(day=None):
"""Returns the first day of the given month."""
day = add_timezone(day or datetime.date.today())
return day.replace(day=1) | python | def get_month_start(day=None):
"""Returns the first day of the given month."""
day = add_timezone(day or datetime.date.today())
return day.replace(day=1) | [
"def",
"get_month_start",
"(",
"day",
"=",
"None",
")",
":",
"day",
"=",
"add_timezone",
"(",
"day",
"or",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"return",
"day",
".",
"replace",
"(",
"day",
"=",
"1",
")"
] | Returns the first day of the given month. | [
"Returns",
"the",
"first",
"day",
"of",
"the",
"given",
"month",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L64-L67 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | get_setting | def get_setting(name, **kwargs):
"""Returns the user-defined value for the setting, or a default value."""
if hasattr(settings, name): # Try user-defined settings first.
return getattr(settings, name)
if 'default' in kwargs: # Fall back to a specified default value.
return kwargs['default'... | python | def get_setting(name, **kwargs):
"""Returns the user-defined value for the setting, or a default value."""
if hasattr(settings, name): # Try user-defined settings first.
return getattr(settings, name)
if 'default' in kwargs: # Fall back to a specified default value.
return kwargs['default'... | [
"def",
"get_setting",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"name",
")",
":",
"# Try user-defined settings first.",
"return",
"getattr",
"(",
"settings",
",",
"name",
")",
"if",
"'default'",
"in",
"kwargs",
... | Returns the user-defined value for the setting, or a default value. | [
"Returns",
"the",
"user",
"-",
"defined",
"value",
"for",
"the",
"setting",
"or",
"a",
"default",
"value",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L73-L82 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | get_week_start | def get_week_start(day=None):
"""Returns the Monday of the given week."""
day = add_timezone(day or datetime.date.today())
days_since_monday = day.weekday()
if days_since_monday != 0:
day = day - relativedelta(days=days_since_monday)
return day | python | def get_week_start(day=None):
"""Returns the Monday of the given week."""
day = add_timezone(day or datetime.date.today())
days_since_monday = day.weekday()
if days_since_monday != 0:
day = day - relativedelta(days=days_since_monday)
return day | [
"def",
"get_week_start",
"(",
"day",
"=",
"None",
")",
":",
"day",
"=",
"add_timezone",
"(",
"day",
"or",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"days_since_monday",
"=",
"day",
".",
"weekday",
"(",
")",
"if",
"days_since_monday",
"!=",
... | Returns the Monday of the given week. | [
"Returns",
"the",
"Monday",
"of",
"the",
"given",
"week",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L85-L91 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | get_year_start | def get_year_start(day=None):
"""Returns January 1 of the given year."""
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1) | python | def get_year_start(day=None):
"""Returns January 1 of the given year."""
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1) | [
"def",
"get_year_start",
"(",
"day",
"=",
"None",
")",
":",
"day",
"=",
"add_timezone",
"(",
"day",
"or",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"return",
"day",
".",
"replace",
"(",
"month",
"=",
"1",
")",
".",
"replace",
"(",
"day"... | Returns January 1 of the given year. | [
"Returns",
"January",
"1",
"of",
"the",
"given",
"year",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L94-L97 | train |
caktus/django-timepiece | timepiece/utils/__init__.py | to_datetime | def to_datetime(date):
"""Transforms a date or datetime object into a date object."""
return datetime.datetime(date.year, date.month, date.day) | python | def to_datetime(date):
"""Transforms a date or datetime object into a date object."""
return datetime.datetime(date.year, date.month, date.day) | [
"def",
"to_datetime",
"(",
"date",
")",
":",
"return",
"datetime",
".",
"datetime",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
")"
] | Transforms a date or datetime object into a date object. | [
"Transforms",
"a",
"date",
"or",
"datetime",
"object",
"into",
"a",
"date",
"object",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L100-L102 | train |
caktus/django-timepiece | timepiece/reports/views.py | report_estimation_accuracy | def report_estimation_accuracy(request):
"""
Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.
"""
contracts = ProjectContract.objects.filter(
status=ProjectContract.STATUS_COMPLETE,
type=ProjectContract.PROJECT_FIXED
)
data = [('Target (hrs)', 'Ac... | python | def report_estimation_accuracy(request):
"""
Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.
"""
contracts = ProjectContract.objects.filter(
status=ProjectContract.STATUS_COMPLETE,
type=ProjectContract.PROJECT_FIXED
)
data = [('Target (hrs)', 'Ac... | [
"def",
"report_estimation_accuracy",
"(",
"request",
")",
":",
"contracts",
"=",
"ProjectContract",
".",
"objects",
".",
"filter",
"(",
"status",
"=",
"ProjectContract",
".",
"STATUS_COMPLETE",
",",
"type",
"=",
"ProjectContract",
".",
"PROJECT_FIXED",
")",
"data"... | Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3. | [
"Idea",
"from",
"Software",
"Estimation",
"Demystifying",
"the",
"Black",
"Art",
"McConnel",
"2006",
"Fig",
"3",
"-",
"3",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L468-L487 | train |
caktus/django-timepiece | timepiece/reports/views.py | ReportMixin.get_context_data | def get_context_data(self, **kwargs):
"""Processes form data to get relevant entries & date_headers."""
context = super(ReportMixin, self).get_context_data(**kwargs)
form = self.get_form()
if form.is_valid():
data = form.cleaned_data
start, end = form.save()
... | python | def get_context_data(self, **kwargs):
"""Processes form data to get relevant entries & date_headers."""
context = super(ReportMixin, self).get_context_data(**kwargs)
form = self.get_form()
if form.is_valid():
data = form.cleaned_data
start, end = form.save()
... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"ReportMixin",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"form",
"=",
"self",
".",
"get_form",
"(",
")",
"if",
"fo... | Processes form data to get relevant entries & date_headers. | [
"Processes",
"form",
"data",
"to",
"get",
"relevant",
"entries",
"&",
"date_headers",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L36-L74 | train |
caktus/django-timepiece | timepiece/reports/views.py | ReportMixin.get_entry_query | def get_entry_query(self, start, end, data):
"""Builds Entry query from form data."""
# Entry types.
incl_billable = data.get('billable', True)
incl_nonbillable = data.get('non_billable', True)
incl_leave = data.get('paid_leave', True)
# If no types are selected, shortcu... | python | def get_entry_query(self, start, end, data):
"""Builds Entry query from form data."""
# Entry types.
incl_billable = data.get('billable', True)
incl_nonbillable = data.get('non_billable', True)
incl_leave = data.get('paid_leave', True)
# If no types are selected, shortcu... | [
"def",
"get_entry_query",
"(",
"self",
",",
"start",
",",
"end",
",",
"data",
")",
":",
"# Entry types.",
"incl_billable",
"=",
"data",
".",
"get",
"(",
"'billable'",
",",
"True",
")",
"incl_nonbillable",
"=",
"data",
".",
"get",
"(",
"'non_billable'",
","... | Builds Entry query from form data. | [
"Builds",
"Entry",
"query",
"from",
"form",
"data",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L76-L121 | train |
caktus/django-timepiece | timepiece/reports/views.py | ReportMixin.get_headers | def get_headers(self, date_headers, from_date, to_date, trunc):
"""Adjust date headers & get range headers."""
date_headers = list(date_headers)
# Earliest date should be no earlier than from_date.
if date_headers and date_headers[0] < from_date:
date_headers[0] = from_date
... | python | def get_headers(self, date_headers, from_date, to_date, trunc):
"""Adjust date headers & get range headers."""
date_headers = list(date_headers)
# Earliest date should be no earlier than from_date.
if date_headers and date_headers[0] < from_date:
date_headers[0] = from_date
... | [
"def",
"get_headers",
"(",
"self",
",",
"date_headers",
",",
"from_date",
",",
"to_date",
",",
"trunc",
")",
":",
"date_headers",
"=",
"list",
"(",
"date_headers",
")",
"# Earliest date should be no earlier than from_date.",
"if",
"date_headers",
"and",
"date_headers"... | Adjust date headers & get range headers. | [
"Adjust",
"date",
"headers",
"&",
"get",
"range",
"headers",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L123-L142 | train |
caktus/django-timepiece | timepiece/reports/views.py | ReportMixin.get_previous_month | def get_previous_month(self):
"""Returns date range for the previous full month."""
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(end)
start = utils.get_month_start(end)
return start, end | python | def get_previous_month(self):
"""Returns date range for the previous full month."""
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(end)
start = utils.get_month_start(end)
return start, end | [
"def",
"get_previous_month",
"(",
"self",
")",
":",
"end",
"=",
"utils",
".",
"get_month_start",
"(",
")",
"-",
"relativedelta",
"(",
"days",
"=",
"1",
")",
"end",
"=",
"utils",
".",
"to_datetime",
"(",
"end",
")",
"start",
"=",
"utils",
".",
"get_mont... | Returns date range for the previous full month. | [
"Returns",
"date",
"range",
"for",
"the",
"previous",
"full",
"month",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L144-L149 | train |
caktus/django-timepiece | timepiece/reports/views.py | HourlyReport.convert_context_to_csv | def convert_context_to_csv(self, context):
"""Convert the context dictionary into a CSV file."""
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
co... | python | def convert_context_to_csv(self, context):
"""Convert the context dictionary into a CSV file."""
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
co... | [
"def",
"convert_context_to_csv",
"(",
"self",
",",
"context",
")",
":",
"content",
"=",
"[",
"]",
"date_headers",
"=",
"context",
"[",
"'date_headers'",
"]",
"headers",
"=",
"[",
"'Name'",
"]",
"headers",
".",
"extend",
"(",
"[",
"date",
".",
"strftime",
... | Convert the context dictionary into a CSV file. | [
"Convert",
"the",
"context",
"dictionary",
"into",
"a",
"CSV",
"file",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L155-L177 | train |
caktus/django-timepiece | timepiece/reports/views.py | HourlyReport.defaults | def defaults(self):
"""Default filter form data when no GET data is provided."""
# Set default date span to previous week.
(start, end) = get_week_window(timezone.now() - relativedelta(days=7))
return {
'from_date': start,
'to_date': end,
'billable': T... | python | def defaults(self):
"""Default filter form data when no GET data is provided."""
# Set default date span to previous week.
(start, end) = get_week_window(timezone.now() - relativedelta(days=7))
return {
'from_date': start,
'to_date': end,
'billable': T... | [
"def",
"defaults",
"(",
"self",
")",
":",
"# Set default date span to previous week.",
"(",
"start",
",",
"end",
")",
"=",
"get_week_window",
"(",
"timezone",
".",
"now",
"(",
")",
"-",
"relativedelta",
"(",
"days",
"=",
"7",
")",
")",
"return",
"{",
"'fro... | Default filter form data when no GET data is provided. | [
"Default",
"filter",
"form",
"data",
"when",
"no",
"GET",
"data",
"is",
"provided",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L180-L192 | train |
caktus/django-timepiece | timepiece/reports/views.py | BillableHours.get_hours_data | def get_hours_data(self, entries, date_headers):
"""Sum billable and non-billable hours across all users."""
project_totals = get_project_totals(
entries, date_headers, total_column=False) if entries else []
data_map = {}
for rows, totals in project_totals:
for u... | python | def get_hours_data(self, entries, date_headers):
"""Sum billable and non-billable hours across all users."""
project_totals = get_project_totals(
entries, date_headers, total_column=False) if entries else []
data_map = {}
for rows, totals in project_totals:
for u... | [
"def",
"get_hours_data",
"(",
"self",
",",
"entries",
",",
"date_headers",
")",
":",
"project_totals",
"=",
"get_project_totals",
"(",
"entries",
",",
"date_headers",
",",
"total_column",
"=",
"False",
")",
"if",
"entries",
"else",
"[",
"]",
"data_map",
"=",
... | Sum billable and non-billable hours across all users. | [
"Sum",
"billable",
"and",
"non",
"-",
"billable",
"hours",
"across",
"all",
"users",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L314-L329 | train |
caktus/django-timepiece | timepiece/templatetags/timepiece_tags.py | add_parameters | def add_parameters(url, parameters):
"""
Appends URL-encoded parameters to the base URL. It appends after '&' if
'?' is found in the URL; otherwise it appends using '?'. Keep in mind that
this tag does not take into account the value of existing params; it is
therefore possible to add another value ... | python | def add_parameters(url, parameters):
"""
Appends URL-encoded parameters to the base URL. It appends after '&' if
'?' is found in the URL; otherwise it appends using '?'. Keep in mind that
this tag does not take into account the value of existing params; it is
therefore possible to add another value ... | [
"def",
"add_parameters",
"(",
"url",
",",
"parameters",
")",
":",
"if",
"parameters",
":",
"sep",
"=",
"'&'",
"if",
"'?'",
"in",
"url",
"else",
"'?'",
"return",
"'{0}{1}{2}'",
".",
"format",
"(",
"url",
",",
"sep",
",",
"urlencode",
"(",
"parameters",
... | Appends URL-encoded parameters to the base URL. It appends after '&' if
'?' is found in the URL; otherwise it appends using '?'. Keep in mind that
this tag does not take into account the value of existing params; it is
therefore possible to add another value for a pre-existing parameter.
For example::
... | [
"Appends",
"URL",
"-",
"encoded",
"parameters",
"to",
"the",
"base",
"URL",
".",
"It",
"appends",
"after",
"&",
"if",
"?",
"is",
"found",
"in",
"the",
"URL",
";",
"otherwise",
"it",
"appends",
"using",
"?",
".",
"Keep",
"in",
"mind",
"that",
"this",
... | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L22-L41 | train |
caktus/django-timepiece | timepiece/templatetags/timepiece_tags.py | get_max_hours | def get_max_hours(context):
"""Return the largest number of hours worked or assigned on any project."""
progress = context['project_progress']
return max([0] + [max(p['worked'], p['assigned']) for p in progress]) | python | def get_max_hours(context):
"""Return the largest number of hours worked or assigned on any project."""
progress = context['project_progress']
return max([0] + [max(p['worked'], p['assigned']) for p in progress]) | [
"def",
"get_max_hours",
"(",
"context",
")",
":",
"progress",
"=",
"context",
"[",
"'project_progress'",
"]",
"return",
"max",
"(",
"[",
"0",
"]",
"+",
"[",
"max",
"(",
"p",
"[",
"'worked'",
"]",
",",
"p",
"[",
"'assigned'",
"]",
")",
"for",
"p",
"... | Return the largest number of hours worked or assigned on any project. | [
"Return",
"the",
"largest",
"number",
"of",
"hours",
"worked",
"or",
"assigned",
"on",
"any",
"project",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L109-L112 | train |
caktus/django-timepiece | timepiece/templatetags/timepiece_tags.py | get_uninvoiced_hours | def get_uninvoiced_hours(entries, billable=None):
"""Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
"""
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
... | python | def get_uninvoiced_hours(entries, billable=None):
"""Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries.
"""
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
... | [
"def",
"get_uninvoiced_hours",
"(",
"entries",
",",
"billable",
"=",
"None",
")",
":",
"statuses",
"=",
"(",
"'invoiced'",
",",
"'not-invoiced'",
")",
"if",
"billable",
"is",
"not",
"None",
":",
"billable",
"=",
"(",
"billable",
".",
"lower",
"(",
")",
"... | Given an iterable of entries, return the total hours that have
not been invoiced. If billable is passed as 'billable' or 'nonbillable',
limit to the corresponding entries. | [
"Given",
"an",
"iterable",
"of",
"entries",
"return",
"the",
"total",
"hours",
"that",
"have",
"not",
"been",
"invoiced",
".",
"If",
"billable",
"is",
"passed",
"as",
"billable",
"or",
"nonbillable",
"limit",
"to",
"the",
"corresponding",
"entries",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L116-L126 | train |
caktus/django-timepiece | timepiece/templatetags/timepiece_tags.py | humanize_hours | def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
negative_frmt=None):
"""Given time in hours, return a string representing the time."""
seconds = int(float(total_hours) * 3600)
return humanize_seconds(seconds, frmt, negative_frmt) | python | def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
negative_frmt=None):
"""Given time in hours, return a string representing the time."""
seconds = int(float(total_hours) * 3600)
return humanize_seconds(seconds, frmt, negative_frmt) | [
"def",
"humanize_hours",
"(",
"total_hours",
",",
"frmt",
"=",
"'{hours:02d}:{minutes:02d}:{seconds:02d}'",
",",
"negative_frmt",
"=",
"None",
")",
":",
"seconds",
"=",
"int",
"(",
"float",
"(",
"total_hours",
")",
"*",
"3600",
")",
"return",
"humanize_seconds",
... | Given time in hours, return a string representing the time. | [
"Given",
"time",
"in",
"hours",
"return",
"a",
"string",
"representing",
"the",
"time",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L130-L134 | train |
caktus/django-timepiece | timepiece/templatetags/timepiece_tags.py | _timesheet_url | def _timesheet_url(url_name, pk, date=None):
"""Utility to create a time sheet URL with optional date parameters."""
url = reverse(url_name, args=(pk,))
if date:
params = {'month': date.month, 'year': date.year}
return '?'.join((url, urlencode(params)))
return url | python | def _timesheet_url(url_name, pk, date=None):
"""Utility to create a time sheet URL with optional date parameters."""
url = reverse(url_name, args=(pk,))
if date:
params = {'month': date.month, 'year': date.year}
return '?'.join((url, urlencode(params)))
return url | [
"def",
"_timesheet_url",
"(",
"url_name",
",",
"pk",
",",
"date",
"=",
"None",
")",
":",
"url",
"=",
"reverse",
"(",
"url_name",
",",
"args",
"=",
"(",
"pk",
",",
")",
")",
"if",
"date",
":",
"params",
"=",
"{",
"'month'",
":",
"date",
".",
"mont... | Utility to create a time sheet URL with optional date parameters. | [
"Utility",
"to",
"create",
"a",
"time",
"sheet",
"URL",
"with",
"optional",
"date",
"parameters",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L222-L228 | train |
caktus/django-timepiece | timepiece/crm/views.py | reject_user_timesheet | def reject_user_timesheet(request, user_id):
"""
This allows admins to reject all entries, instead of just one
"""
form = YearMonthForm(request.GET or request.POST)
user = User.objects.get(pk=user_id)
if form.is_valid():
from_date, to_date = form.save()
entries = Entry.no_join.fi... | python | def reject_user_timesheet(request, user_id):
"""
This allows admins to reject all entries, instead of just one
"""
form = YearMonthForm(request.GET or request.POST)
user = User.objects.get(pk=user_id)
if form.is_valid():
from_date, to_date = form.save()
entries = Entry.no_join.fi... | [
"def",
"reject_user_timesheet",
"(",
"request",
",",
"user_id",
")",
":",
"form",
"=",
"YearMonthForm",
"(",
"request",
".",
"GET",
"or",
"request",
".",
"POST",
")",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"user_id",
")",
"if"... | This allows admins to reject all entries, instead of just one | [
"This",
"allows",
"admins",
"to",
"reject",
"all",
"entries",
"instead",
"of",
"just",
"one"
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/crm/views.py#L47-L77 | train |
caktus/django-timepiece | setup.py | _is_requirement | def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#")) | python | def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#")) | [
"def",
"_is_requirement",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"return",
"line",
"and",
"not",
"(",
"line",
".",
"startswith",
"(",
"\"-r\"",
")",
"or",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
")"
] | Returns whether the line is a valid package requirement. | [
"Returns",
"whether",
"the",
"line",
"is",
"a",
"valid",
"package",
"requirement",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/setup.py#L4-L7 | train |
caktus/django-timepiece | timepiece/utils/search.py | SearchMixin.render_to_response | def render_to_response(self, context):
"""
When the user makes a search and there is only one result, redirect
to the result's detail page rather than rendering the list.
"""
if self.redirect_if_one_result:
if self.object_list.count() == 1 and self.form.is_bound:
... | python | def render_to_response(self, context):
"""
When the user makes a search and there is only one result, redirect
to the result's detail page rather than rendering the list.
"""
if self.redirect_if_one_result:
if self.object_list.count() == 1 and self.form.is_bound:
... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"redirect_if_one_result",
":",
"if",
"self",
".",
"object_list",
".",
"count",
"(",
")",
"==",
"1",
"and",
"self",
".",
"form",
".",
"is_bound",
":",
"return",
"redire... | When the user makes a search and there is only one result, redirect
to the result's detail page rather than rendering the list. | [
"When",
"the",
"user",
"makes",
"a",
"search",
"and",
"there",
"is",
"only",
"one",
"result",
"redirect",
"to",
"the",
"result",
"s",
"detail",
"page",
"rather",
"than",
"rendering",
"the",
"list",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/search.py#L61-L69 | train |
caktus/django-timepiece | timepiece/entries/forms.py | ClockInForm.clean_start_time | def clean_start_time(self):
"""
Make sure that the start time doesn't come before the active entry
"""
start = self.cleaned_data.get('start_time')
if not start:
return start
active_entries = self.user.timepiece_entries.filter(
start_time__gte=start... | python | def clean_start_time(self):
"""
Make sure that the start time doesn't come before the active entry
"""
start = self.cleaned_data.get('start_time')
if not start:
return start
active_entries = self.user.timepiece_entries.filter(
start_time__gte=start... | [
"def",
"clean_start_time",
"(",
"self",
")",
":",
"start",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'start_time'",
")",
"if",
"not",
"start",
":",
"return",
"start",
"active_entries",
"=",
"self",
".",
"user",
".",
"timepiece_entries",
".",
"fil... | Make sure that the start time doesn't come before the active entry | [
"Make",
"sure",
"that",
"the",
"start",
"time",
"doesn",
"t",
"come",
"before",
"the",
"active",
"entry"
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/forms.py#L64-L78 | train |
caktus/django-timepiece | timepiece/entries/forms.py | AddUpdateEntryForm.clean | def clean(self):
"""
If we're not editing the active entry, ensure that this entry doesn't
conflict with or come after the active entry.
"""
active = utils.get_active_entry(self.user)
start_time = self.cleaned_data.get('start_time', None)
end_time = self.cleaned_d... | python | def clean(self):
"""
If we're not editing the active entry, ensure that this entry doesn't
conflict with or come after the active entry.
"""
active = utils.get_active_entry(self.user)
start_time = self.cleaned_data.get('start_time', None)
end_time = self.cleaned_d... | [
"def",
"clean",
"(",
"self",
")",
":",
"active",
"=",
"utils",
".",
"get_active_entry",
"(",
"self",
".",
"user",
")",
"start_time",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'start_time'",
",",
"None",
")",
"end_time",
"=",
"self",
".",
"cle... | If we're not editing the active entry, ensure that this entry doesn't
conflict with or come after the active entry. | [
"If",
"we",
"re",
"not",
"editing",
"the",
"active",
"entry",
"ensure",
"that",
"this",
"entry",
"doesn",
"t",
"conflict",
"with",
"or",
"come",
"after",
"the",
"active",
"entry",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/forms.py#L145-L181 | train |
caktus/django-timepiece | timepiece/entries/views.py | clock_in | def clock_in(request):
"""For clocking the user into a project."""
user = request.user
# Lock the active entry for the duration of this transaction, to prevent
# creating multiple active entries.
active_entry = utils.get_active_entry(user, select_for_update=True)
initial = dict([(k, v) for k, v... | python | def clock_in(request):
"""For clocking the user into a project."""
user = request.user
# Lock the active entry for the duration of this transaction, to prevent
# creating multiple active entries.
active_entry = utils.get_active_entry(user, select_for_update=True)
initial = dict([(k, v) for k, v... | [
"def",
"clock_in",
"(",
"request",
")",
":",
"user",
"=",
"request",
".",
"user",
"# Lock the active entry for the duration of this transaction, to prevent",
"# creating multiple active entries.",
"active_entry",
"=",
"utils",
".",
"get_active_entry",
"(",
"user",
",",
"sel... | For clocking the user into a project. | [
"For",
"clocking",
"the",
"user",
"into",
"a",
"project",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L139-L159 | train |
caktus/django-timepiece | timepiece/entries/views.py | toggle_pause | def toggle_pause(request):
"""Allow the user to pause and unpause the active entry."""
entry = utils.get_active_entry(request.user)
if not entry:
raise Http404
# toggle the paused state
entry.toggle_paused()
entry.save()
# create a message that can be displayed to the user
acti... | python | def toggle_pause(request):
"""Allow the user to pause and unpause the active entry."""
entry = utils.get_active_entry(request.user)
if not entry:
raise Http404
# toggle the paused state
entry.toggle_paused()
entry.save()
# create a message that can be displayed to the user
acti... | [
"def",
"toggle_pause",
"(",
"request",
")",
":",
"entry",
"=",
"utils",
".",
"get_active_entry",
"(",
"request",
".",
"user",
")",
"if",
"not",
"entry",
":",
"raise",
"Http404",
"# toggle the paused state",
"entry",
".",
"toggle_paused",
"(",
")",
"entry",
"... | Allow the user to pause and unpause the active entry. | [
"Allow",
"the",
"user",
"to",
"pause",
"and",
"unpause",
"the",
"active",
"entry",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L189-L206 | train |
caktus/django-timepiece | timepiece/entries/views.py | reject_entry | def reject_entry(request, entry_id):
"""
Admins can reject an entry that has been verified or approved but not
invoiced to set its status to 'unverified' for the user to fix.
"""
return_url = request.GET.get('next', reverse('dashboard'))
try:
entry = Entry.no_join.get(pk=entry_id)
ex... | python | def reject_entry(request, entry_id):
"""
Admins can reject an entry that has been verified or approved but not
invoiced to set its status to 'unverified' for the user to fix.
"""
return_url = request.GET.get('next', reverse('dashboard'))
try:
entry = Entry.no_join.get(pk=entry_id)
ex... | [
"def",
"reject_entry",
"(",
"request",
",",
"entry_id",
")",
":",
"return_url",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"reverse",
"(",
"'dashboard'",
")",
")",
"try",
":",
"entry",
"=",
"Entry",
".",
"no_join",
".",
"get",
"(",
"... | Admins can reject an entry that has been verified or approved but not
invoiced to set its status to 'unverified' for the user to fix. | [
"Admins",
"can",
"reject",
"an",
"entry",
"that",
"has",
"been",
"verified",
"or",
"approved",
"but",
"not",
"invoiced",
"to",
"set",
"its",
"status",
"to",
"unverified",
"for",
"the",
"user",
"to",
"fix",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L255-L282 | train |
caktus/django-timepiece | timepiece/entries/views.py | delete_entry | def delete_entry(request, entry_id):
"""
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry wi... | python | def delete_entry(request, entry_id):
"""
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry wi... | [
"def",
"delete_entry",
"(",
"request",
",",
"entry_id",
")",
":",
"try",
":",
"entry",
"=",
"Entry",
".",
"no_join",
".",
"get",
"(",
"pk",
"=",
"entry_id",
",",
"user",
"=",
"request",
".",
"user",
")",
"except",
"Entry",
".",
"DoesNotExist",
":",
"... | Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry will be deleted. | [
"Give",
"the",
"user",
"the",
"ability",
"to",
"delete",
"a",
"log",
"entry",
"with",
"a",
"confirmation",
"beforehand",
".",
"If",
"this",
"method",
"is",
"invoked",
"via",
"a",
"GET",
"request",
"a",
"form",
"asking",
"for",
"a",
"confirmation",
"of",
... | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L286-L315 | train |
caktus/django-timepiece | timepiece/entries/views.py | Dashboard.get_hours_per_week | def get_hours_per_week(self, user=None):
"""Retrieves the number of hours the user should work per week."""
try:
profile = UserProfile.objects.get(user=user or self.user)
except UserProfile.DoesNotExist:
profile = None
return profile.hours_per_week if profile else... | python | def get_hours_per_week(self, user=None):
"""Retrieves the number of hours the user should work per week."""
try:
profile = UserProfile.objects.get(user=user or self.user)
except UserProfile.DoesNotExist:
profile = None
return profile.hours_per_week if profile else... | [
"def",
"get_hours_per_week",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"try",
":",
"profile",
"=",
"UserProfile",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"user",
"or",
"self",
".",
"user",
")",
"except",
"UserProfile",
".",
"DoesNotExist",
... | Retrieves the number of hours the user should work per week. | [
"Retrieves",
"the",
"number",
"of",
"hours",
"the",
"user",
"should",
"work",
"per",
"week",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L57-L63 | train |
caktus/django-timepiece | timepiece/entries/views.py | ScheduleMixin.get_hours_for_week | def get_hours_for_week(self, week_start=None):
"""
Gets all ProjectHours entries in the 7-day period beginning on
week_start.
"""
week_start = week_start if week_start else self.week_start
week_end = week_start + relativedelta(days=7)
return ProjectHours.objects.... | python | def get_hours_for_week(self, week_start=None):
"""
Gets all ProjectHours entries in the 7-day period beginning on
week_start.
"""
week_start = week_start if week_start else self.week_start
week_end = week_start + relativedelta(days=7)
return ProjectHours.objects.... | [
"def",
"get_hours_for_week",
"(",
"self",
",",
"week_start",
"=",
"None",
")",
":",
"week_start",
"=",
"week_start",
"if",
"week_start",
"else",
"self",
".",
"week_start",
"week_end",
"=",
"week_start",
"+",
"relativedelta",
"(",
"days",
"=",
"7",
")",
"retu... | Gets all ProjectHours entries in the 7-day period beginning on
week_start. | [
"Gets",
"all",
"ProjectHours",
"entries",
"in",
"the",
"7",
"-",
"day",
"period",
"beginning",
"on",
"week_start",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L336-L345 | train |
caktus/django-timepiece | timepiece/entries/views.py | ScheduleView.get_users_from_project_hours | def get_users_from_project_hours(self, project_hours):
"""
Gets a list of the distinct users included in the project hours
entries, ordered by name.
"""
name = ('user__first_name', 'user__last_name')
users = project_hours.values_list('user__id', *name).distinct()\
... | python | def get_users_from_project_hours(self, project_hours):
"""
Gets a list of the distinct users included in the project hours
entries, ordered by name.
"""
name = ('user__first_name', 'user__last_name')
users = project_hours.values_list('user__id', *name).distinct()\
... | [
"def",
"get_users_from_project_hours",
"(",
"self",
",",
"project_hours",
")",
":",
"name",
"=",
"(",
"'user__first_name'",
",",
"'user__last_name'",
")",
"users",
"=",
"project_hours",
".",
"values_list",
"(",
"'user__id'",
",",
"*",
"name",
")",
".",
"distinct... | Gets a list of the distinct users included in the project hours
entries, ordered by name. | [
"Gets",
"a",
"list",
"of",
"the",
"distinct",
"users",
"included",
"in",
"the",
"project",
"hours",
"entries",
"ordered",
"by",
"name",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L357-L365 | train |
caktus/django-timepiece | timepiece/management/commands/check_entries.py | Command.check_all | def check_all(self, all_entries, *args, **kwargs):
"""
Go through lists of entries, find overlaps among each, return the total
"""
all_overlaps = 0
while True:
try:
user_entries = all_entries.next()
except StopIteration:
ret... | python | def check_all(self, all_entries, *args, **kwargs):
"""
Go through lists of entries, find overlaps among each, return the total
"""
all_overlaps = 0
while True:
try:
user_entries = all_entries.next()
except StopIteration:
ret... | [
"def",
"check_all",
"(",
"self",
",",
"all_entries",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_overlaps",
"=",
"0",
"while",
"True",
":",
"try",
":",
"user_entries",
"=",
"all_entries",
".",
"next",
"(",
")",
"except",
"StopIteration",
... | Go through lists of entries, find overlaps among each, return the total | [
"Go",
"through",
"lists",
"of",
"entries",
"find",
"overlaps",
"among",
"each",
"return",
"the",
"total"
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L69-L82 | train |
caktus/django-timepiece | timepiece/management/commands/check_entries.py | Command.check_entry | def check_entry(self, entries, *args, **kwargs):
"""
With a list of entries, check each entry against every other
"""
verbosity = kwargs.get('verbosity', 1)
user_total_overlaps = 0
user = ''
for index_a, entry_a in enumerate(entries):
# Show the name t... | python | def check_entry(self, entries, *args, **kwargs):
"""
With a list of entries, check each entry against every other
"""
verbosity = kwargs.get('verbosity', 1)
user_total_overlaps = 0
user = ''
for index_a, entry_a in enumerate(entries):
# Show the name t... | [
"def",
"check_entry",
"(",
"self",
",",
"entries",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"verbosity",
"=",
"kwargs",
".",
"get",
"(",
"'verbosity'",
",",
"1",
")",
"user_total_overlaps",
"=",
"0",
"user",
"=",
"''",
"for",
"index_a",
"... | With a list of entries, check each entry against every other | [
"With",
"a",
"list",
"of",
"entries",
"check",
"each",
"entry",
"against",
"every",
"other"
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L84-L110 | train |
caktus/django-timepiece | timepiece/management/commands/check_entries.py | Command.find_start | def find_start(self, **kwargs):
"""
Determine the starting point of the query using CLI keyword arguments
"""
week = kwargs.get('week', False)
month = kwargs.get('month', False)
year = kwargs.get('year', False)
days = kwargs.get('days', 0)
# If no flags ar... | python | def find_start(self, **kwargs):
"""
Determine the starting point of the query using CLI keyword arguments
"""
week = kwargs.get('week', False)
month = kwargs.get('month', False)
year = kwargs.get('year', False)
days = kwargs.get('days', 0)
# If no flags ar... | [
"def",
"find_start",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"week",
"=",
"kwargs",
".",
"get",
"(",
"'week'",
",",
"False",
")",
"month",
"=",
"kwargs",
".",
"get",
"(",
"'month'",
",",
"False",
")",
"year",
"=",
"kwargs",
".",
"get",
"(... | Determine the starting point of the query using CLI keyword arguments | [
"Determine",
"the",
"starting",
"point",
"of",
"the",
"query",
"using",
"CLI",
"keyword",
"arguments"
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L112-L133 | train |
caktus/django-timepiece | timepiece/management/commands/check_entries.py | Command.find_users | def find_users(self, *args):
"""
Returns the users to search given names as args.
Return all users if there are no args provided.
"""
if args:
names = reduce(lambda query, arg: query |
(Q(first_name__icontains=arg) | Q(last_name__icontains=arg)),
... | python | def find_users(self, *args):
"""
Returns the users to search given names as args.
Return all users if there are no args provided.
"""
if args:
names = reduce(lambda query, arg: query |
(Q(first_name__icontains=arg) | Q(last_name__icontains=arg)),
... | [
"def",
"find_users",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"names",
"=",
"reduce",
"(",
"lambda",
"query",
",",
"arg",
":",
"query",
"|",
"(",
"Q",
"(",
"first_name__icontains",
"=",
"arg",
")",
"|",
"Q",
"(",
"last_name__iconta... | Returns the users to search given names as args.
Return all users if there are no args provided. | [
"Returns",
"the",
"users",
"to",
"search",
"given",
"names",
"as",
"args",
".",
"Return",
"all",
"users",
"if",
"there",
"are",
"no",
"args",
"provided",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L135-L155 | train |
caktus/django-timepiece | timepiece/management/commands/check_entries.py | Command.find_entries | def find_entries(self, users, start, *args, **kwargs):
"""
Find all entries for all users, from a given starting point.
If no starting point is provided, all entries are returned.
"""
forever = kwargs.get('all', False)
for user in users:
if forever:
... | python | def find_entries(self, users, start, *args, **kwargs):
"""
Find all entries for all users, from a given starting point.
If no starting point is provided, all entries are returned.
"""
forever = kwargs.get('all', False)
for user in users:
if forever:
... | [
"def",
"find_entries",
"(",
"self",
",",
"users",
",",
"start",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"forever",
"=",
"kwargs",
".",
"get",
"(",
"'all'",
",",
"False",
")",
"for",
"user",
"in",
"users",
":",
"if",
"forever",
":",
"... | Find all entries for all users, from a given starting point.
If no starting point is provided, all entries are returned. | [
"Find",
"all",
"entries",
"for",
"all",
"users",
"from",
"a",
"given",
"starting",
"point",
".",
"If",
"no",
"starting",
"point",
"is",
"provided",
"all",
"entries",
"are",
"returned",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L157-L170 | train |
caktus/django-timepiece | timepiece/utils/views.py | cbv_decorator | def cbv_decorator(function_decorator):
"""Allows a function-based decorator to be used on a CBV."""
def class_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return class_decorator | python | def cbv_decorator(function_decorator):
"""Allows a function-based decorator to be used on a CBV."""
def class_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return class_decorator | [
"def",
"cbv_decorator",
"(",
"function_decorator",
")",
":",
"def",
"class_decorator",
"(",
"View",
")",
":",
"View",
".",
"dispatch",
"=",
"method_decorator",
"(",
"function_decorator",
")",
"(",
"View",
".",
"dispatch",
")",
"return",
"View",
"return",
"clas... | Allows a function-based decorator to be used on a CBV. | [
"Allows",
"a",
"function",
"-",
"based",
"decorator",
"to",
"be",
"used",
"on",
"a",
"CBV",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/views.py#L4-L10 | train |
caktus/django-timepiece | timepiece/reports/utils.py | date_totals | def date_totals(entries, by):
"""Yield a user's name and a dictionary of their hours"""
date_dict = {}
for date, date_entries in groupby(entries, lambda x: x['date']):
if isinstance(date, datetime.datetime):
date = date.date()
d_entries = list(date_entries)
if by == 'use... | python | def date_totals(entries, by):
"""Yield a user's name and a dictionary of their hours"""
date_dict = {}
for date, date_entries in groupby(entries, lambda x: x['date']):
if isinstance(date, datetime.datetime):
date = date.date()
d_entries = list(date_entries)
if by == 'use... | [
"def",
"date_totals",
"(",
"entries",
",",
"by",
")",
":",
"date_dict",
"=",
"{",
"}",
"for",
"date",
",",
"date_entries",
"in",
"groupby",
"(",
"entries",
",",
"lambda",
"x",
":",
"x",
"[",
"'date'",
"]",
")",
":",
"if",
"isinstance",
"(",
"date",
... | Yield a user's name and a dictionary of their hours | [
"Yield",
"a",
"user",
"s",
"name",
"and",
"a",
"dictionary",
"of",
"their",
"hours"
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/utils.py#L12-L31 | train |
caktus/django-timepiece | timepiece/reports/utils.py | get_project_totals | def get_project_totals(entries, date_headers, hour_type=None, overtime=False,
total_column=False, by='user'):
"""
Yield hour totals grouped by user and date. Optionally including overtime.
"""
totals = [0 for date in date_headers]
rows = []
for thing, thing_entries in grou... | python | def get_project_totals(entries, date_headers, hour_type=None, overtime=False,
total_column=False, by='user'):
"""
Yield hour totals grouped by user and date. Optionally including overtime.
"""
totals = [0 for date in date_headers]
rows = []
for thing, thing_entries in grou... | [
"def",
"get_project_totals",
"(",
"entries",
",",
"date_headers",
",",
"hour_type",
"=",
"None",
",",
"overtime",
"=",
"False",
",",
"total_column",
"=",
"False",
",",
"by",
"=",
"'user'",
")",
":",
"totals",
"=",
"[",
"0",
"for",
"date",
"in",
"date_hea... | Yield hour totals grouped by user and date. Optionally including overtime. | [
"Yield",
"hour",
"totals",
"grouped",
"by",
"user",
"and",
"date",
".",
"Optionally",
"including",
"overtime",
"."
] | 52515dec027664890efbc535429e1ba1ee152f40 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/utils.py#L57-L93 | train |
stanfordnlp/stanza | stanza/research/learner.py | Learner.validate | def validate(self, validation_instances, metrics, iteration=None):
'''
Evaluate this model on `validation_instances` during training and
output a report.
:param validation_instances: The data to use to validate the model.
:type validation_instances: list(instance.Instance)
... | python | def validate(self, validation_instances, metrics, iteration=None):
'''
Evaluate this model on `validation_instances` during training and
output a report.
:param validation_instances: The data to use to validate the model.
:type validation_instances: list(instance.Instance)
... | [
"def",
"validate",
"(",
"self",
",",
"validation_instances",
",",
"metrics",
",",
"iteration",
"=",
"None",
")",
":",
"if",
"not",
"validation_instances",
"or",
"not",
"metrics",
":",
"return",
"{",
"}",
"split_id",
"=",
"'val%s'",
"%",
"iteration",
"if",
... | Evaluate this model on `validation_instances` during training and
output a report.
:param validation_instances: The data to use to validate the model.
:type validation_instances: list(instance.Instance)
:param metrics: Functions like those found in the `metrics` module
for ... | [
"Evaluate",
"this",
"model",
"on",
"validation_instances",
"during",
"training",
"and",
"output",
"a",
"report",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L34-L55 | train |
stanfordnlp/stanza | stanza/research/learner.py | Learner.predict_and_score | def predict_and_score(self, eval_instances, random=False, verbosity=0):
'''
Return most likely outputs and scores for the particular set of
outputs given in `eval_instances`, as a tuple. Return value should
be equivalent to the default implementation of
return (self.predict(... | python | def predict_and_score(self, eval_instances, random=False, verbosity=0):
'''
Return most likely outputs and scores for the particular set of
outputs given in `eval_instances`, as a tuple. Return value should
be equivalent to the default implementation of
return (self.predict(... | [
"def",
"predict_and_score",
"(",
"self",
",",
"eval_instances",
",",
"random",
"=",
"False",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_using_default_separate'",
")",
"and",
"self",
".",
"_using_default_separate",
":",
"raise",... | Return most likely outputs and scores for the particular set of
outputs given in `eval_instances`, as a tuple. Return value should
be equivalent to the default implementation of
return (self.predict(eval_instances), self.score(eval_instances))
but subclasses can override this to co... | [
"Return",
"most",
"likely",
"outputs",
"and",
"scores",
"for",
"the",
"particular",
"set",
"of",
"outputs",
"given",
"in",
"eval_instances",
"as",
"a",
"tuple",
".",
"Return",
"value",
"should",
"be",
"equivalent",
"to",
"the",
"default",
"implementation",
"of... | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L104-L135 | train |
stanfordnlp/stanza | stanza/research/learner.py | Learner.load | def load(self, infile):
'''
Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
seriali... | python | def load(self, infile):
'''
Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
seriali... | [
"def",
"load",
"(",
"self",
",",
"infile",
")",
":",
"model",
"=",
"pickle",
".",
"load",
"(",
"infile",
")",
"self",
".",
"__dict__",
".",
"update",
"(",
"model",
".",
"__dict__",
")"
] | Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
serialized model. | [
"Deserialize",
"a",
"model",
"from",
"a",
"stored",
"file",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L153-L164 | train |
stanfordnlp/stanza | stanza/research/iterators.py | iter_batches | def iter_batches(iterable, batch_size):
'''
Given a sequence or iterable, yield batches from that iterable until it
runs out. Note that this function returns a generator, and also each
batch will be a generator.
:param iterable: The sequence or iterable to split into batches
:param int batch_si... | python | def iter_batches(iterable, batch_size):
'''
Given a sequence or iterable, yield batches from that iterable until it
runs out. Note that this function returns a generator, and also each
batch will be a generator.
:param iterable: The sequence or iterable to split into batches
:param int batch_si... | [
"def",
"iter_batches",
"(",
"iterable",
",",
"batch_size",
")",
":",
"# http://stackoverflow.com/a/8290514/4481448",
"sourceiter",
"=",
"iter",
"(",
"iterable",
")",
"while",
"True",
":",
"batchiter",
"=",
"islice",
"(",
"sourceiter",
",",
"batch_size",
")",
"yiel... | Given a sequence or iterable, yield batches from that iterable until it
runs out. Note that this function returns a generator, and also each
batch will be a generator.
:param iterable: The sequence or iterable to split into batches
:param int batch_size: The number of elements of `iterable` to iterate ... | [
"Given",
"a",
"sequence",
"or",
"iterable",
"yield",
"batches",
"from",
"that",
"iterable",
"until",
"it",
"runs",
"out",
".",
"Note",
"that",
"this",
"function",
"returns",
"a",
"generator",
"and",
"also",
"each",
"batch",
"will",
"be",
"a",
"generator",
... | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L4-L44 | train |
stanfordnlp/stanza | stanza/research/iterators.py | gen_batches | def gen_batches(iterable, batch_size):
'''
Returns a generator object that yields batches from `iterable`.
See `iter_batches` for more details and caveats.
Note that `iter_batches` returns an iterator, which never supports `len()`,
`gen_batches` returns an iterable which supports `len()` if and onl... | python | def gen_batches(iterable, batch_size):
'''
Returns a generator object that yields batches from `iterable`.
See `iter_batches` for more details and caveats.
Note that `iter_batches` returns an iterator, which never supports `len()`,
`gen_batches` returns an iterable which supports `len()` if and onl... | [
"def",
"gen_batches",
"(",
"iterable",
",",
"batch_size",
")",
":",
"def",
"batches_thunk",
"(",
")",
":",
"return",
"iter_batches",
"(",
"iterable",
",",
"batch_size",
")",
"try",
":",
"length",
"=",
"len",
"(",
"iterable",
")",
"except",
"TypeError",
":"... | Returns a generator object that yields batches from `iterable`.
See `iter_batches` for more details and caveats.
Note that `iter_batches` returns an iterator, which never supports `len()`,
`gen_batches` returns an iterable which supports `len()` if and only if
`iterable` does. This *may* be an iterator... | [
"Returns",
"a",
"generator",
"object",
"that",
"yields",
"batches",
"from",
"iterable",
".",
"See",
"iter_batches",
"for",
"more",
"details",
"and",
"caveats",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L47-L76 | train |
stanfordnlp/stanza | stanza/research/instance.py | Instance.inverted | def inverted(self):
'''
Return a version of this instance with inputs replaced by outputs and vice versa.
'''
return Instance(input=self.output, output=self.input,
annotated_input=self.annotated_output,
annotated_output=self.annotated_input... | python | def inverted(self):
'''
Return a version of this instance with inputs replaced by outputs and vice versa.
'''
return Instance(input=self.output, output=self.input,
annotated_input=self.annotated_output,
annotated_output=self.annotated_input... | [
"def",
"inverted",
"(",
"self",
")",
":",
"return",
"Instance",
"(",
"input",
"=",
"self",
".",
"output",
",",
"output",
"=",
"self",
".",
"input",
",",
"annotated_input",
"=",
"self",
".",
"annotated_output",
",",
"annotated_output",
"=",
"self",
".",
"... | Return a version of this instance with inputs replaced by outputs and vice versa. | [
"Return",
"a",
"version",
"of",
"this",
"instance",
"with",
"inputs",
"replaced",
"by",
"outputs",
"and",
"vice",
"versa",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/instance.py#L36-L45 | train |
stanfordnlp/stanza | stanza/util/resource.py | get_data_or_download | def get_data_or_download(dir_name, file_name, url='', size='unknown'):
"""Returns the data. if the data hasn't been downloaded, then first download the data.
:param dir_name: directory to look in
:param file_name: file name to retrieve
:param url: if the file is not found, then download it from this ur... | python | def get_data_or_download(dir_name, file_name, url='', size='unknown'):
"""Returns the data. if the data hasn't been downloaded, then first download the data.
:param dir_name: directory to look in
:param file_name: file name to retrieve
:param url: if the file is not found, then download it from this ur... | [
"def",
"get_data_or_download",
"(",
"dir_name",
",",
"file_name",
",",
"url",
"=",
"''",
",",
"size",
"=",
"'unknown'",
")",
":",
"dname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"stanza",
".",
"DATA_DIR",
",",
"dir_name",
")",
"fname",
"=",
"os",
... | Returns the data. if the data hasn't been downloaded, then first download the data.
:param dir_name: directory to look in
:param file_name: file name to retrieve
:param url: if the file is not found, then download it from this url
:param size: the expected size
:return: path to the requested file | [
"Returns",
"the",
"data",
".",
"if",
"the",
"data",
"hasn",
"t",
"been",
"downloaded",
"then",
"first",
"download",
"the",
"data",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/util/resource.py#L16-L35 | train |
stanfordnlp/stanza | stanza/text/vocab.py | Vocab.add | def add(self, word, count=1):
"""Add a word to the vocabulary and return its index.
:param word: word to add to the dictionary.
:param count: how many times to add the word.
:return: index of the added word.
WARNING: this function assumes that if the Vocab currently has N wor... | python | def add(self, word, count=1):
"""Add a word to the vocabulary and return its index.
:param word: word to add to the dictionary.
:param count: how many times to add the word.
:return: index of the added word.
WARNING: this function assumes that if the Vocab currently has N wor... | [
"def",
"add",
"(",
"self",
",",
"word",
",",
"count",
"=",
"1",
")",
":",
"if",
"word",
"not",
"in",
"self",
":",
"super",
"(",
"Vocab",
",",
"self",
")",
".",
"__setitem__",
"(",
"word",
",",
"len",
"(",
"self",
")",
")",
"self",
".",
"_counts... | Add a word to the vocabulary and return its index.
:param word: word to add to the dictionary.
:param count: how many times to add the word.
:return: index of the added word.
WARNING: this function assumes that if the Vocab currently has N words, then
there is a perfect bijec... | [
"Add",
"a",
"word",
"to",
"the",
"vocabulary",
"and",
"return",
"its",
"index",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L93-L108 | train |
stanfordnlp/stanza | stanza/text/vocab.py | Vocab.subset | def subset(self, words):
"""Get a new Vocab containing only the specified subset of words.
If w is in words, but not in the original vocab, it will NOT be in the subset vocab.
Indices will be in the order of `words`. Counts from the original vocab are preserved.
:return (Vocab): a new ... | python | def subset(self, words):
"""Get a new Vocab containing only the specified subset of words.
If w is in words, but not in the original vocab, it will NOT be in the subset vocab.
Indices will be in the order of `words`. Counts from the original vocab are preserved.
:return (Vocab): a new ... | [
"def",
"subset",
"(",
"self",
",",
"words",
")",
":",
"v",
"=",
"self",
".",
"__class__",
"(",
"unk",
"=",
"self",
".",
"_unk",
")",
"unique",
"=",
"lambda",
"seq",
":",
"len",
"(",
"set",
"(",
"seq",
")",
")",
"==",
"len",
"(",
"seq",
")",
"... | Get a new Vocab containing only the specified subset of words.
If w is in words, but not in the original vocab, it will NOT be in the subset vocab.
Indices will be in the order of `words`. Counts from the original vocab are preserved.
:return (Vocab): a new Vocab object | [
"Get",
"a",
"new",
"Vocab",
"containing",
"only",
"the",
"specified",
"subset",
"of",
"words",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L136-L150 | train |
stanfordnlp/stanza | stanza/text/vocab.py | Vocab._index2word | def _index2word(self):
"""Mapping from indices to words.
WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab.
:return: a list of strings
"""
# TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable
... | python | def _index2word(self):
"""Mapping from indices to words.
WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab.
:return: a list of strings
"""
# TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable
... | [
"def",
"_index2word",
"(",
"self",
")",
":",
"# TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable",
"compute_index2word",
"=",
"lambda",
":",
"self",
".",
"keys",
"(",
")",
"# this works because self is an OrderedDict",
"# crea... | Mapping from indices to words.
WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab.
:return: a list of strings | [
"Mapping",
"from",
"indices",
"to",
"words",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L153-L174 | train |
stanfordnlp/stanza | stanza/text/vocab.py | Vocab.from_dict | def from_dict(cls, word2index, unk, counts=None):
"""Create Vocab from an existing string to integer dictionary.
All counts are set to 0.
:param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1.
UNK must be assigned the 0 index.
... | python | def from_dict(cls, word2index, unk, counts=None):
"""Create Vocab from an existing string to integer dictionary.
All counts are set to 0.
:param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1.
UNK must be assigned the 0 index.
... | [
"def",
"from_dict",
"(",
"cls",
",",
"word2index",
",",
"unk",
",",
"counts",
"=",
"None",
")",
":",
"try",
":",
"if",
"word2index",
"[",
"unk",
"]",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'unk must be assigned index 0'",
")",
"except",
"KeyError",
... | Create Vocab from an existing string to integer dictionary.
All counts are set to 0.
:param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1.
UNK must be assigned the 0 index.
:param unk: the string representing unk in word2index.
... | [
"Create",
"Vocab",
"from",
"an",
"existing",
"string",
"to",
"integer",
"dictionary",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L205-L246 | train |
stanfordnlp/stanza | stanza/text/vocab.py | Vocab.to_file | def to_file(self, f):
"""Write vocab to a file.
:param (file) f: a file object, e.g. as returned by calling `open`
File format:
word0<TAB>count0
word1<TAB>count1
...
word with index 0 is on the 0th line and so on...
"""
for word in s... | python | def to_file(self, f):
"""Write vocab to a file.
:param (file) f: a file object, e.g. as returned by calling `open`
File format:
word0<TAB>count0
word1<TAB>count1
...
word with index 0 is on the 0th line and so on...
"""
for word in s... | [
"def",
"to_file",
"(",
"self",
",",
"f",
")",
":",
"for",
"word",
"in",
"self",
".",
"_index2word",
":",
"count",
"=",
"self",
".",
"_counts",
"[",
"word",
"]",
"f",
".",
"write",
"(",
"u'{}\\t{}\\n'",
".",
"format",
"(",
"word",
",",
"count",
")",... | Write vocab to a file.
:param (file) f: a file object, e.g. as returned by calling `open`
File format:
word0<TAB>count0
word1<TAB>count1
...
word with index 0 is on the 0th line and so on... | [
"Write",
"vocab",
"to",
"a",
"file",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L248-L262 | train |
stanfordnlp/stanza | stanza/text/vocab.py | EmbeddedVocab.backfill_unk_emb | def backfill_unk_emb(self, E, filled_words):
""" Backfills an embedding matrix with the embedding for the unknown token.
:param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`.
:param filled_words: these words will not be backfilled with unk.
NOTE: this function is f... | python | def backfill_unk_emb(self, E, filled_words):
""" Backfills an embedding matrix with the embedding for the unknown token.
:param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`.
:param filled_words: these words will not be backfilled with unk.
NOTE: this function is f... | [
"def",
"backfill_unk_emb",
"(",
"self",
",",
"E",
",",
"filled_words",
")",
":",
"unk_emb",
"=",
"E",
"[",
"self",
"[",
"self",
".",
"_unk",
"]",
"]",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"word",
"not",
"in",
"... | Backfills an embedding matrix with the embedding for the unknown token.
:param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`.
:param filled_words: these words will not be backfilled with unk.
NOTE: this function is for internal use. | [
"Backfills",
"an",
"embedding",
"matrix",
"with",
"the",
"embedding",
"for",
"the",
"unknown",
"token",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L304-L315 | train |
stanfordnlp/stanza | stanza/cluster/pick_gpu.py | best_gpu | def best_gpu(max_usage=USAGE_THRESHOLD, verbose=False):
'''
Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',...
The least-used GPU with usage under the constant threshold will be chosen;
ties are broken randomly.
'''
try:
proc = subprocess.Popen("nvidia-smi", stdout=su... | python | def best_gpu(max_usage=USAGE_THRESHOLD, verbose=False):
'''
Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',...
The least-used GPU with usage under the constant threshold will be chosen;
ties are broken randomly.
'''
try:
proc = subprocess.Popen("nvidia-smi", stdout=su... | [
"def",
"best_gpu",
"(",
"max_usage",
"=",
"USAGE_THRESHOLD",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"\"nvidia-smi\"",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess"... | Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',...
The least-used GPU with usage under the constant threshold will be chosen;
ties are broken randomly. | [
"Return",
"the",
"name",
"of",
"a",
"device",
"to",
"use",
"either",
"cpu",
"or",
"gpu0",
"gpu1",
"...",
"The",
"least",
"-",
"used",
"GPU",
"with",
"usage",
"under",
"the",
"constant",
"threshold",
"will",
"be",
"chosen",
";",
"ties",
"are",
"broken",
... | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/cluster/pick_gpu.py#L28-L67 | train |
stanfordnlp/stanza | stanza/research/evaluate.py | evaluate | def evaluate(learner, eval_data, metrics, metric_names=None, split_id=None,
write_data=False):
'''
Evaluate `learner` on the instances in `eval_data` according to each
metric in `metric`, and return a dictionary summarizing the values of
the metrics.
Dump the predictions, scores, and m... | python | def evaluate(learner, eval_data, metrics, metric_names=None, split_id=None,
write_data=False):
'''
Evaluate `learner` on the instances in `eval_data` according to each
metric in `metric`, and return a dictionary summarizing the values of
the metrics.
Dump the predictions, scores, and m... | [
"def",
"evaluate",
"(",
"learner",
",",
"eval_data",
",",
"metrics",
",",
"metric_names",
"=",
"None",
",",
"split_id",
"=",
"None",
",",
"write_data",
"=",
"False",
")",
":",
"if",
"metric_names",
"is",
"None",
":",
"metric_names",
"=",
"[",
"(",
"metri... | Evaluate `learner` on the instances in `eval_data` according to each
metric in `metric`, and return a dictionary summarizing the values of
the metrics.
Dump the predictions, scores, and metric summaries in JSON format
to "{predictions|scores|results}.`split_id`.json" in the run directory.
:param l... | [
"Evaluate",
"learner",
"on",
"the",
"instances",
"in",
"eval_data",
"according",
"to",
"each",
"metric",
"in",
"metric",
"and",
"return",
"a",
"dictionary",
"summarizing",
"the",
"values",
"of",
"the",
"metrics",
"."
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/evaluate.py#L7-L78 | train |
stanfordnlp/stanza | stanza/nlp/protobuf_json.py | json2pb | def json2pb(pb, js, useFieldNumber=False):
''' convert JSON string to google.protobuf.descriptor instance '''
for field in pb.DESCRIPTOR.fields:
if useFieldNumber:
key = field.number
else:
key = field.name
if key not in js:
continue
if field.ty... | python | def json2pb(pb, js, useFieldNumber=False):
''' convert JSON string to google.protobuf.descriptor instance '''
for field in pb.DESCRIPTOR.fields:
if useFieldNumber:
key = field.number
else:
key = field.name
if key not in js:
continue
if field.ty... | [
"def",
"json2pb",
"(",
"pb",
",",
"js",
",",
"useFieldNumber",
"=",
"False",
")",
":",
"for",
"field",
"in",
"pb",
".",
"DESCRIPTOR",
".",
"fields",
":",
"if",
"useFieldNumber",
":",
"key",
"=",
"field",
".",
"number",
"else",
":",
"key",
"=",
"field... | convert JSON string to google.protobuf.descriptor instance | [
"convert",
"JSON",
"string",
"to",
"google",
".",
"protobuf",
".",
"descriptor",
"instance"
] | 920c55d8eaa1e7105971059c66eb448a74c100d6 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/nlp/protobuf_json.py#L51-L79 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.