Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
GeneratePassword
(length=8, include_symbols=False)
Generates a random password.
Generates a random password.
def GeneratePassword(length=8, include_symbols=False): """Generates a random password.""" if length < MIN_LENGTH: raise InputError('Password length must be at least %d' % MIN_LENGTH) candidates = (CANDIDATES_WITH_SYMBOLS if include_symbols else CANDIDATES_WITHOUT_SYMBOLS) categories = (CATE...
[ "def", "GeneratePassword", "(", "length", "=", "8", ",", "include_symbols", "=", "False", ")", ":", "if", "length", "<", "MIN_LENGTH", ":", "raise", "InputError", "(", "'Password length must be at least %d'", "%", "MIN_LENGTH", ")", "candidates", "=", "(", "CAND...
[ 87, 0 ]
[ 105, 27 ]
python
en
['en', 'ca', 'en']
True
_InsertAndEnsureSatisfaction
(generated, required, all_candidates)
Inserts 1 char into generated, satisfying required if not already. If the required characters are not already in the generated string, one will be inserted. If any required character is already in the generated string, a random character from all_candidates will be inserted. The insertion happens at a random l...
Inserts 1 char into generated, satisfying required if not already.
def _InsertAndEnsureSatisfaction(generated, required, all_candidates): """Inserts 1 char into generated, satisfying required if not already. If the required characters are not already in the generated string, one will be inserted. If any required character is already in the generated string, a random character...
[ "def", "_InsertAndEnsureSatisfaction", "(", "generated", ",", "required", ",", "all_candidates", ")", ":", "if", "set", "(", "generated", ")", ".", "isdisjoint", "(", "required", ")", ":", "# Not yet satisfied. Insert a required candidate.", "_InsertInto", "(", "gener...
[ 108, 0 ]
[ 127, 42 ]
python
en
['en', 'en', 'en']
True
_InsertInto
(generated, candidates)
Inserts a random candidate into a random non-zero index of generated.
Inserts a random candidate into a random non-zero index of generated.
def _InsertInto(generated, candidates): """Inserts a random candidate into a random non-zero index of generated.""" # Avoids inserting at index 0, since the first character follows its own rule. generated.insert(random.randint(1, len(generated) - 1), random.choice(candidates))
[ "def", "_InsertInto", "(", "generated", ",", "candidates", ")", ":", "# Avoids inserting at index 0, since the first character follows its own rule.", "generated", ".", "insert", "(", "random", ".", "randint", "(", "1", ",", "len", "(", "generated", ")", "-", "1", "...
[ 130, 0 ]
[ 134, 45 ]
python
en
['en', 'en', 'en']
True
GUICalculator.create_button_layout
(self)
Creates the grid of calculator buttons.
Creates the grid of calculator buttons.
def create_button_layout(self): "Creates the grid of calculator buttons." labels = ["exit", "mrc", "m+", "m-", "clear", "(", ")", "!", "sqrt", "pow", "%", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3"...
[ "def", "create_button_layout", "(", "self", ")", ":", "labels", "=", "[", "\"exit\"", ",", "\"mrc\"", ",", "\"m+\"", ",", "\"m-\"", ",", "\"clear\"", ",", "\"(\"", ",", "\")\"", ",", "\"!\"", ",", "\"sqrt\"", ",", "\"pow\"", ",", "\"%\"", ",", "\"/\"", ...
[ 38, 4 ]
[ 62, 21 ]
python
en
['en', 'en', 'en']
True
SplitDatabase.__init__
(self, input_file, dir_folds=None, n_splits=10, sep_read='\t', sep_write='\t', header=None, names=None, as_binary=False, binary_col=None, write_mode='w')
Given a database, this class is responsible for creating a training and test sets for k folds with well-known strategies: - k-fold cross-validation - ShuffleSplit Usage: >> SplitDatabase(input_file=database, dir_folds=dir_path, n_folds=10).kfoldcrossvalidation() ...
Given a database, this class is responsible for creating a training and test sets for k folds with well-known strategies:
def __init__(self, input_file, dir_folds=None, n_splits=10, sep_read='\t', sep_write='\t', header=None, names=None, as_binary=False, binary_col=None, write_mode='w'): """ Given a database, this class is responsible for creating a training and test sets for k folds with well-know...
[ "def", "__init__", "(", "self", ",", "input_file", ",", "dir_folds", "=", "None", ",", "n_splits", "=", "10", ",", "sep_read", "=", "'\\t'", ",", "sep_write", "=", "'\\t'", ",", "header", "=", "None", ",", "names", "=", "None", ",", "as_binary", "=", ...
[ 19, 4 ]
[ 78, 31 ]
python
en
['en', 'error', 'th']
False
SplitDatabase.kfoldcrossvalidation
(self, shuffle=True, random_state=None)
k-fold cross-validation In k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k − 1 subsamples are used as traini...
k-fold cross-validation
def kfoldcrossvalidation(self, shuffle=True, random_state=None): """ k-fold cross-validation In k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for test...
[ "def", "kfoldcrossvalidation", "(", "self", ",", "shuffle", "=", "True", ",", "random_state", "=", "None", ")", ":", "kfold", "=", "KFold", "(", "n_splits", "=", "self", ".", "n_splits", ",", "shuffle", "=", "shuffle", ",", "random_state", "=", "random_sta...
[ 106, 4 ]
[ 134, 28 ]
python
en
['en', 'error', 'th']
False
SplitDatabase.shuffle_split
(self, test_size=0.1, random_state=None)
Shuffle Split Random permutation cross-validator Yields indices to split data into training and test sets. Note: contrary to other cross-validation strategies, random splits do not guarantee that all folds will be different, although this is still very likely for sizeable dat...
Shuffle Split
def shuffle_split(self, test_size=0.1, random_state=None): """ Shuffle Split Random permutation cross-validator Yields indices to split data into training and test sets. Note: contrary to other cross-validation strategies, random splits do not guarantee that all folds ...
[ "def", "shuffle_split", "(", "self", ",", "test_size", "=", "0.1", ",", "random_state", "=", "None", ")", ":", "ss", "=", "ShuffleSplit", "(", "n_splits", "=", "self", ".", "n_splits", ",", "test_size", "=", "test_size", ",", "random_state", "=", "random_s...
[ 136, 4 ]
[ 161, 28 ]
python
en
['en', 'error', 'th']
False
compute_hex_hash
(s, algorithm=SIGNATURE_SHA1)
Computes string hash using specified algorithm and return HEX string representation of hash. :param s: String to compute hash for :param algorithm: The name of algorithm to use for computing hash :return: HEX string of computed hash value
Computes string hash using specified algorithm and return HEX string representation of hash.
def compute_hex_hash(s, algorithm=SIGNATURE_SHA1): """ Computes string hash using specified algorithm and return HEX string representation of hash. :param s: String to compute hash for :param algorithm: The name of algorithm to use for computing hash :return: HEX string of computed hash va...
[ "def", "compute_hex_hash", "(", "s", ",", "algorithm", "=", "SIGNATURE_SHA1", ")", ":", "try", ":", "hash_fn", "=", "signature_algorithms", "[", "algorithm", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Unsupported hash algorithm: {}'", ".", "form...
[ 140, 0 ]
[ 153, 43 ]
python
en
['en', 'error', 'th']
False
build_list_of_dicts
(val)
Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"}, {"k2","v2"}] - JSON decodable string: '{"k": "v"}', or '[{"k": "v"}]' ...
Converts a value that can be presented as a list of dict.
def build_list_of_dicts(val): """ Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"}, {"k2","v2"}] - JSON decodable stri...
[ "def", "build_list_of_dicts", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "[", "]", "if", "isinstance", "(", "val", ",", "str", ")", ":", "# use OrderedDict to preserve order", "val", "=", "json", ".", "loads", "(", "val", ",", "objec...
[ 165, 0 ]
[ 204, 14 ]
python
en
['en', 'error', 'th']
False
normalize_context_value
(value)
Escape "=" and "|" delimiter characters and json encode lists :param value: Value to escape :type value: int or str or list or tuple :return: The normalized value :rtype: str
Escape "=" and "|" delimiter characters and json encode lists
def normalize_context_value(value): """ Escape "=" and "|" delimiter characters and json encode lists :param value: Value to escape :type value: int or str or list or tuple :return: The normalized value :rtype: str """ if isinstance(value, (list, tuple)): value = json_encode(v...
[ "def", "normalize_context_value", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "value", "=", "json_encode", "(", "value", ")", "return", "str", "(", "value", ")", ".", "replace", "(", "\"=\"",...
[ 226, 0 ]
[ 240, 61 ]
python
en
['en', 'error', 'th']
False
encode_context
(context)
Encode metadata fields based on incoming value. List and tuple values are encoded to json strings. :param context: dict of context to be encoded :return: a joined string of all keys and values properly escaped and separated by a pipe character
Encode metadata fields based on incoming value.
def encode_context(context): """ Encode metadata fields based on incoming value. List and tuple values are encoded to json strings. :param context: dict of context to be encoded :return: a joined string of all keys and values properly escaped and separated by a pipe character """ if not i...
[ "def", "encode_context", "(", "context", ")", ":", "if", "not", "isinstance", "(", "context", ",", "dict", ")", ":", "return", "context", "return", "\"|\"", ".", "join", "(", "(", "\"{}={}\"", ".", "format", "(", "k", ",", "normalize_context_value", "(", ...
[ 243, 0 ]
[ 256, 99 ]
python
en
['en', 'error', 'th']
False
json_encode
(value)
Converts value to a json encoded string :param value: value to be encoded :return: JSON encoded string
Converts value to a json encoded string
def json_encode(value): """ Converts value to a json encoded string :param value: value to be encoded :return: JSON encoded string """ return json.dumps(value, default=__json_serializer, separators=(',', ':'))
[ "def", "json_encode", "(", "value", ")", ":", "return", "json", ".", "dumps", "(", "value", ",", "default", "=", "__json_serializer", ",", "separators", "=", "(", "','", ",", "':'", ")", ")" ]
[ 259, 0 ]
[ 267, 78 ]
python
en
['en', 'error', 'th']
False
encode_date_to_usage_api_format
(date_obj)
Encodes date object to `dd-mm-yyyy` format string :param date_obj: datetime.date object to encode :return: Encoded date as a string
Encodes date object to `dd-mm-yyyy` format string
def encode_date_to_usage_api_format(date_obj): """ Encodes date object to `dd-mm-yyyy` format string :param date_obj: datetime.date object to encode :return: Encoded date as a string """ return date_obj.strftime('%d-%m-%Y')
[ "def", "encode_date_to_usage_api_format", "(", "date_obj", ")", ":", "return", "date_obj", ".", "strftime", "(", "'%d-%m-%Y'", ")" ]
[ 270, 0 ]
[ 278, 40 ]
python
en
['en', 'error', 'th']
False
patch_fetch_format
(options)
When upload type is fetch, remove the format options. In addition, set the fetch_format options to the format value unless it was already set. Mutates the options parameter! :param options: URL and transformation options
When upload type is fetch, remove the format options. In addition, set the fetch_format options to the format value unless it was already set. Mutates the options parameter!
def patch_fetch_format(options): """ When upload type is fetch, remove the format options. In addition, set the fetch_format options to the format value unless it was already set. Mutates the options parameter! :param options: URL and transformation options """ if options.get("type", "uploa...
[ "def", "patch_fetch_format", "(", "options", ")", ":", "if", "options", ".", "get", "(", "\"type\"", ",", "\"upload\"", ")", "!=", "\"fetch\"", ":", "return", "resource_format", "=", "options", ".", "pop", "(", "\"format\"", ",", "None", ")", "if", "\"fetc...
[ 281, 0 ]
[ 294, 49 ]
python
en
['en', 'error', 'th']
False
chain_transformations
(options, transformations)
Helper function, allows chaining transformations to the end of transformations list The result of this function is an updated options parameter :param options: Original options :param transformations: Transformations to chain at the end :return: Resulting options
Helper function, allows chaining transformations to the end of transformations list
def chain_transformations(options, transformations): """ Helper function, allows chaining transformations to the end of transformations list The result of this function is an updated options parameter :param options: Original options :param transformations: Transformations to chain at the ...
[ "def", "chain_transformations", "(", "options", ",", "transformations", ")", ":", "transformations", "=", "copy", ".", "deepcopy", "(", "transformations", ")", "transformations", "=", "build_array", "(", "transformations", ")", "# preserve url options", "url_options", ...
[ 460, 0 ]
[ 482, 22 ]
python
en
['en', 'error', 'th']
False
unsigned_download_url_prefix
(source, cloud_name, private_cdn, cdn_subdomain, secure_cdn_subdomain, cname, secure, secure_distribution)
cdn_subdomain and secure_cdn_subdomain 1) Customers in shared distribution (e.g. res.cloudinary.com) if cdn_domain is true uses res-[1-5].cloudinary.com for both http and https. Setting secure_cdn_subdomain to false disables this for https. 2) Customers with private cdn if cdn_domain is true u...
cdn_subdomain and secure_cdn_subdomain 1) Customers in shared distribution (e.g. res.cloudinary.com) if cdn_domain is true uses res-[1-5].cloudinary.com for both http and https. Setting secure_cdn_subdomain to false disables this for https. 2) Customers with private cdn if cdn_domain is true u...
def unsigned_download_url_prefix(source, cloud_name, private_cdn, cdn_subdomain, secure_cdn_subdomain, cname, secure, secure_distribution): """cdn_subdomain and secure_cdn_subdomain 1) Customers in shared distribution (e.g. res.cloudinary.com) if cdn_domain is true uses re...
[ "def", "unsigned_download_url_prefix", "(", "source", ",", "cloud_name", ",", "private_cdn", ",", "cdn_subdomain", ",", "secure_cdn_subdomain", ",", "cname", ",", "secure", ",", "secure_distribution", ")", ":", "shared_domain", "=", "not", "private_cdn", "shard", "=...
[ 646, 0 ]
[ 687, 17 ]
python
en
['en', 'gd', 'en']
True
cloudinary_scaled_url
(source, width, transformation, options)
Generates a cloudinary url scaled to specified width. :param source: The resource :param width: Width in pixels of the srcset item :param transformation: Custom transformation that overrides transformations provided in options :param options: A dict with additional opti...
Generates a cloudinary url scaled to specified width.
def cloudinary_scaled_url(source, width, transformation, options): """ Generates a cloudinary url scaled to specified width. :param source: The resource :param width: Width in pixels of the srcset item :param transformation: Custom transformation that overrides transformations p...
[ "def", "cloudinary_scaled_url", "(", "source", ",", "width", ",", "transformation", ",", "options", ")", ":", "# preserve options from being destructed", "options", "=", "copy", ".", "deepcopy", "(", "options", ")", "if", "transformation", ":", "if", "isinstance", ...
[ 814, 0 ]
[ 843, 51 ]
python
en
['en', 'error', 'th']
False
smart_escape
(source, unsafe=r"([^a-zA-Z0-9_.\-\/:]+)")
Based on ruby's CGI::unescape. In addition does not escape / : :param source: Source string to escape :param unsafe: Unsafe characters :return: Escaped string
Based on ruby's CGI::unescape. In addition does not escape / :
def smart_escape(source, unsafe=r"([^a-zA-Z0-9_.\-\/:]+)"): """ Based on ruby's CGI::unescape. In addition does not escape / : :param source: Source string to escape :param unsafe: Unsafe characters :return: Escaped string """ def pack(m): return to_bytes('%' + "%".join( ...
[ "def", "smart_escape", "(", "source", ",", "unsafe", "=", "r\"([^a-zA-Z0-9_.\\-\\/:]+)\"", ")", ":", "def", "pack", "(", "m", ")", ":", "return", "to_bytes", "(", "'%'", "+", "\"%\"", ".", "join", "(", "[", "\"%02X\"", "%", "x", "for", "x", "in", "stru...
[ 846, 0 ]
[ 860, 70 ]
python
en
['en', 'error', 'th']
False
download_folder
(folder_path, **options)
Creates and returns a URL that when invoked creates an archive of a folder. :param folder_path: The full path from the root that is used to generate download url. :type folder_path: str :param options: Additional options. :type options: dict, optional :return: Signed URL to...
Creates and returns a URL that when invoked creates an archive of a folder. :param folder_path: The full path from the root that is used to generate download url. :type folder_path: str :param options: Additional options. :type options: dict, optional :return: Signed URL to...
def download_folder(folder_path, **options): """ Creates and returns a URL that when invoked creates an archive of a folder. :param folder_path: The full path from the root that is used to generate download url. :type folder_path: str :param options: Additional options. :type options: ...
[ "def", "download_folder", "(", "folder_path", ",", "*", "*", "options", ")", ":", "options", "[", "\"prefixes\"", "]", "=", "folder_path", "options", ".", "setdefault", "(", "\"resource_type\"", ",", "\"all\"", ")", "return", "download_archive_url", "(", "*", ...
[ 921, 0 ]
[ 934, 42 ]
python
en
['en', 'error', 'th']
False
download_backedup_asset
(asset_id, version_id, **options)
The returned url allows downloading the backedup asset based on the the asset ID and the version ID. Parameters asset_id and version_id are returned with api.resource(<PUBLIC_ID1>, versions=True) API call. :param asset_id: The asset ID of the asset. :type asset_id: str :param version_id: ...
The returned url allows downloading the backedup asset based on the the asset ID and the version ID.
def download_backedup_asset(asset_id, version_id, **options): """ The returned url allows downloading the backedup asset based on the the asset ID and the version ID. Parameters asset_id and version_id are returned with api.resource(<PUBLIC_ID1>, versions=True) API call. :param asset_id: The asset ...
[ "def", "download_backedup_asset", "(", "asset_id", ",", "version_id", ",", "*", "*", "options", ")", ":", "params", "=", "{", "\"timestamp\"", ":", "options", ".", "get", "(", "\"timestamp\"", ",", "now", "(", ")", ")", ",", "\"asset_id\"", ":", "asset_id"...
[ 937, 0 ]
[ 959, 112 ]
python
en
['en', 'error', 'th']
False
build_single_eager
(options)
Builds a single eager transformation which consists of transformation and (optionally) format joined by "/" :param options: Options containing transformation parameters and (optionally) a "format" key format can be a string value (jpg, gif, etc) or can be set to "" (empty string). The latter l...
Builds a single eager transformation which consists of transformation and (optionally) format joined by "/"
def build_single_eager(options): """ Builds a single eager transformation which consists of transformation and (optionally) format joined by "/" :param options: Options containing transformation parameters and (optionally) a "format" key format can be a string value (jpg, gif, etc) or can be set to...
[ "def", "build_single_eager", "(", "options", ")", ":", "if", "isinstance", "(", "options", ",", "string_types", ")", ":", "return", "options", "trans_str", "=", "generate_transformation_string", "(", "*", "*", "options", ")", "[", "0", "]", "if", "not", "tra...
[ 1006, 0 ]
[ 1027, 77 ]
python
en
['en', 'error', 'th']
False
build_multi_and_sprite_params
(**options)
Build params for multi, download_multi, generate_sprite, and download_generated_sprite methods
Build params for multi, download_multi, generate_sprite, and download_generated_sprite methods
def build_multi_and_sprite_params(**options): """ Build params for multi, download_multi, generate_sprite, and download_generated_sprite methods """ tag = options.get("tag") urls = options.get("urls") if bool(tag) == bool(urls): raise ValueError("Either 'tag' or 'urls' parameter has to b...
[ "def", "build_multi_and_sprite_params", "(", "*", "*", "options", ")", ":", "tag", "=", "options", ".", "get", "(", "\"tag\"", ")", "urls", "=", "options", ".", "get", "(", "\"urls\"", ")", "if", "bool", "(", "tag", ")", "==", "bool", "(", "urls", ")...
[ 1070, 0 ]
[ 1087, 17 ]
python
en
['en', 'error', 'th']
False
process_fps
(fps)
Serializes fps transformation parameter :param fps: A single number, a list of mixed type, a string, including open-ended and closed range values Examples: '24-29.97', 24, 24.973, '-24', [24, 29.97] :return: string
Serializes fps transformation parameter
def process_fps(fps): """ Serializes fps transformation parameter :param fps: A single number, a list of mixed type, a string, including open-ended and closed range values Examples: '24-29.97', 24, 24.973, '-24', [24, 29.97] :return: string """ if not isinstance(fps, (list, tup...
[ "def", "process_fps", "(", "fps", ")", ":", "if", "not", "isinstance", "(", "fps", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "fps", "return", "\"-\"", ".", "join", "(", "normalize_expression", "(", "f", ")", "for", "f", "in", "fps", ...
[ 1277, 0 ]
[ 1289, 57 ]
python
en
['en', 'error', 'th']
False
process_ki
(ki)
Serializes keyframe_interval parameter :param ki: Keyframe interval. Should be either a string or a positive real number. :return: string
Serializes keyframe_interval parameter :param ki: Keyframe interval. Should be either a string or a positive real number. :return: string
def process_ki(ki): """ Serializes keyframe_interval parameter :param ki: Keyframe interval. Should be either a string or a positive real number. :return: string """ if ki is None: return None if isinstance(ki, string_types): return ki if not isinstance(ki, Number): ...
[ "def", "process_ki", "(", "ki", ")", ":", "if", "ki", "is", "None", ":", "return", "None", "if", "isinstance", "(", "ki", ",", "string_types", ")", ":", "return", "ki", "if", "not", "isinstance", "(", "ki", ",", "Number", ")", ":", "raise", "ValueErr...
[ 1292, 0 ]
[ 1306, 25 ]
python
en
['en', 'error', 'th']
False
base64_encode_url
(url)
Returns the Base64-decoded version of url. The method tries to unquote the url because quoting it :param str url: the url to encode. the value is URIdecoded and then re-encoded before converting to base64 representation
Returns the Base64-decoded version of url. The method tries to unquote the url because quoting it
def base64_encode_url(url): """ Returns the Base64-decoded version of url. The method tries to unquote the url because quoting it :param str url: the url to encode. the value is URIdecoded and then re-encoded before converting to base64 representation """ try: url = un...
[ "def", "base64_encode_url", "(", "url", ")", ":", "try", ":", "url", "=", "unquote", "(", "url", ")", "except", "Exception", ":", "pass", "url", "=", "smart_escape", "(", "url", ")", "b64", "=", "base64", ".", "b64encode", "(", "url", ".", "encode", ...
[ 1356, 0 ]
[ 1373, 30 ]
python
en
['en', 'error', 'th']
False
base64url_encode
(data)
Url safe version of urlsafe_b64encode with stripped `=` sign at the end. :param data: input data :return: Base64 URL safe encoded string
Url safe version of urlsafe_b64encode with stripped `=` sign at the end.
def base64url_encode(data): """ Url safe version of urlsafe_b64encode with stripped `=` sign at the end. :param data: input data :return: Base64 URL safe encoded string """ return to_string(base64.urlsafe_b64encode(to_bytes(data)))
[ "def", "base64url_encode", "(", "data", ")", ":", "return", "to_string", "(", "base64", ".", "urlsafe_b64encode", "(", "to_bytes", "(", "data", ")", ")", ")" ]
[ 1376, 0 ]
[ 1384, 62 ]
python
en
['en', 'error', 'th']
False
encode_unicode_url
(url_str)
Quote and encode possible unicode url string (applicable for python2) :param url_str: Url string to encode :return: Encoded string
Quote and encode possible unicode url string (applicable for python2)
def encode_unicode_url(url_str): """ Quote and encode possible unicode url string (applicable for python2) :param url_str: Url string to encode :return: Encoded string """ if six.PY2: url_str = urllib.quote(url_str.encode('utf-8'), ":/?#[]@!$&'()*+,;=") return url_str
[ "def", "encode_unicode_url", "(", "url_str", ")", ":", "if", "six", ".", "PY2", ":", "url_str", "=", "urllib", ".", "quote", "(", "url_str", ".", "encode", "(", "'utf-8'", ")", ",", "\":/?#[]@!$&'()*+,;=\"", ")", "return", "url_str" ]
[ 1387, 0 ]
[ 1398, 18 ]
python
en
['en', 'error', 'th']
False
__json_serializer
(obj)
JSON serializer for objects not serializable by default json code
JSON serializer for objects not serializable by default json code
def __json_serializer(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError("Object of type %s is not JSON serializable" % type(obj))
[ "def", "__json_serializer", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "datetime", ",", "date", ")", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "raise", "TypeError", "(", "\"Object of type %s is not JSON serializable\"", "%", ...
[ 1401, 0 ]
[ 1405, 77 ]
python
en
['en', 'en', 'en']
True
is_remote_url
(file)
Basic URL scheme check to define if it's remote URL
Basic URL scheme check to define if it's remote URL
def is_remote_url(file): """Basic URL scheme check to define if it's remote URL""" return isinstance(file, string_types) and re.match(REMOTE_URL_RE, file)
[ "def", "is_remote_url", "(", "file", ")", ":", "return", "isinstance", "(", "file", ",", "string_types", ")", "and", "re", ".", "match", "(", "REMOTE_URL_RE", ",", "file", ")" ]
[ 1408, 0 ]
[ 1410, 75 ]
python
de
['it', 'de', 'en']
False
file_io_size
(file_io)
Helper function for getting file-like object size(suitable for both files and streams) :param file_io: io.IOBase :return: size
Helper function for getting file-like object size(suitable for both files and streams)
def file_io_size(file_io): """ Helper function for getting file-like object size(suitable for both files and streams) :param file_io: io.IOBase :return: size """ initial_position = file_io.tell() file_io.seek(0, os.SEEK_END) size = file_io.tell() file_io.seek(initial_position, os.S...
[ "def", "file_io_size", "(", "file_io", ")", ":", "initial_position", "=", "file_io", ".", "tell", "(", ")", "file_io", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", "size", "=", "file_io", ".", "tell", "(", ")", "file_io", ".", "seek", "(",...
[ 1413, 0 ]
[ 1426, 15 ]
python
en
['en', 'error', 'th']
False
check_property_enabled
(f)
Used as a class method decorator to check whether class is enabled(self.enabled is True) :param f: function to call :return: None if not enabled, otherwise calls function f
Used as a class method decorator to check whether class is enabled(self.enabled is True)
def check_property_enabled(f): """ Used as a class method decorator to check whether class is enabled(self.enabled is True) :param f: function to call :return: None if not enabled, otherwise calls function f """ def wrapper(*args, **kwargs): if not args[0].enabled: return N...
[ "def", "check_property_enabled", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", "[", "0", "]", ".", "enabled", ":", "return", "None", "return", "f", "(", "*", "args", ",", "*", "*",...
[ 1429, 0 ]
[ 1442, 18 ]
python
en
['en', 'error', 'th']
False
verify_api_response_signature
(public_id, version, signature, algorithm=None)
Verifies the authenticity of an API response signature :param public_id: The public id of the asset as returned in the API response :param version: The version of the asset as returned in the API response :param signature: Actual signature. Can be retrieved from the X-Cld-Signature header :param...
Verifies the authenticity of an API response signature
def verify_api_response_signature(public_id, version, signature, algorithm=None): """ Verifies the authenticity of an API response signature :param public_id: The public id of the asset as returned in the API response :param version: The version of the asset as returned in the API response :param...
[ "def", "verify_api_response_signature", "(", "public_id", ",", "version", ",", "signature", ",", "algorithm", "=", "None", ")", ":", "if", "not", "cloudinary", ".", "config", "(", ")", ".", "api_secret", ":", "raise", "Exception", "(", "'Api secret key is empty'...
[ 1445, 0 ]
[ 1467, 5 ]
python
en
['en', 'error', 'th']
False
verify_notification_signature
(body, timestamp, signature, valid_for=7200, algorithm=None)
Verifies the authenticity of a notification signature :param body: Json of the request's body :param timestamp: Unix timestamp. Can be retrieved from the X-Cld-Timestamp header :param signature: Actual signature. Can be retrieved from the X-Cld-Signature header :param valid_for: The desired time i...
Verifies the authenticity of a notification signature
def verify_notification_signature(body, timestamp, signature, valid_for=7200, algorithm=None): """ Verifies the authenticity of a notification signature :param body: Json of the request's body :param timestamp: Unix timestamp. Can be retrieved from the X-Cld-Timestamp header :param signature: Actua...
[ "def", "verify_notification_signature", "(", "body", ",", "timestamp", ",", "signature", ",", "valid_for", "=", "7200", ",", "algorithm", "=", "None", ")", ":", "if", "not", "cloudinary", ".", "config", "(", ")", ".", "api_secret", ":", "raise", "Exception",...
[ 1470, 0 ]
[ 1494, 61 ]
python
en
['en', 'error', 'th']
False
get_http_connector
(conf, options)
Used to create http connector, depends on api_proxy configuration parameter :param conf: configuration object :param options: additional options :return: ProxyManager if api_proxy is set, otherwise PoolManager object
Used to create http connector, depends on api_proxy configuration parameter
def get_http_connector(conf, options): """ Used to create http connector, depends on api_proxy configuration parameter :param conf: configuration object :param options: additional options :return: ProxyManager if api_proxy is set, otherwise PoolManager object """ if conf.api_proxy: ...
[ "def", "get_http_connector", "(", "conf", ",", "options", ")", ":", "if", "conf", ".", "api_proxy", ":", "return", "ProxyManager", "(", "conf", ".", "api_proxy", ",", "*", "*", "options", ")", "else", ":", "return", "PoolManager", "(", "*", "*", "options...
[ 1497, 0 ]
[ 1509, 37 ]
python
en
['en', 'error', 'th']
False
safe_cast
(val, casting_fn, default=None)
Attempts to cast a value to another using a given casting function Will return a default value if casting fails (configurable, defaults to None) :param val: The value to cast :param casting_fn: The casting function that will receive the value to cast :param default: The return value if casting fai...
Attempts to cast a value to another using a given casting function Will return a default value if casting fails (configurable, defaults to None)
def safe_cast(val, casting_fn, default=None): """ Attempts to cast a value to another using a given casting function Will return a default value if casting fails (configurable, defaults to None) :param val: The value to cast :param casting_fn: The casting function that will receive the value to cas...
[ "def", "safe_cast", "(", "val", ",", "casting_fn", ",", "default", "=", "None", ")", ":", "try", ":", "return", "casting_fn", "(", "val", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "default" ]
[ 1518, 0 ]
[ 1532, 22 ]
python
en
['en', 'error', 'th']
False
compute_power_of_solutions
(template_eval, template_tasks, tier)
Compute power for each solution in eval stats. Solution power is how many tasks an action solves.
Compute power for each solution in eval stats.
def compute_power_of_solutions(template_eval, template_tasks, tier): """Compute power for each solution in eval stats. Solution power is how many tasks an action solves. """ template_tasks = set(template_tasks) actions_on_tasks = template_eval['solution_power'][tier]['actions_on_tasks'] task_id...
[ "def", "compute_power_of_solutions", "(", "template_eval", ",", "template_tasks", ",", "tier", ")", ":", "template_tasks", "=", "set", "(", "template_tasks", ")", "actions_on_tasks", "=", "template_eval", "[", "'solution_power'", "]", "[", "tier", "]", "[", "'acti...
[ 47, 0 ]
[ 60, 32 ]
python
en
['en', 'en', 'en']
True
RequirementTracker.add
(self, req: InstallRequirement)
Add an InstallRequirement to build tracking.
Add an InstallRequirement to build tracking.
def add(self, req: InstallRequirement) -> None: """Add an InstallRequirement to build tracking. """ assert req.link # Get the file to write information about this requirement. entry_path = self._entry_path(req.link) # Try reading from the file. If it exists and can be r...
[ "def", "add", "(", "self", ",", "req", ":", "InstallRequirement", ")", "->", "None", ":", "assert", "req", ".", "link", "# Get the file to write information about this requirement.", "entry_path", "=", "self", ".", "_entry_path", "(", "req", ".", "link", ")", "#...
[ 78, 4 ]
[ 106, 69 ]
python
en
['en', 'en', 'en']
True
RequirementTracker.remove
(self, req: InstallRequirement)
Remove an InstallRequirement from build tracking.
Remove an InstallRequirement from build tracking.
def remove(self, req: InstallRequirement) -> None: """Remove an InstallRequirement from build tracking. """ assert req.link # Delete the created file and the corresponding entries. os.unlink(self._entry_path(req.link)) self._entries.remove(req) logger.debug('Rem...
[ "def", "remove", "(", "self", ",", "req", ":", "InstallRequirement", ")", "->", "None", ":", "assert", "req", ".", "link", "# Delete the created file and the corresponding entries.", "os", ".", "unlink", "(", "self", ".", "_entry_path", "(", "req", ".", "link", ...
[ 108, 4 ]
[ 117, 73 ]
python
en
['en', 'en', 'en']
True
identity_block
(input_tensor, kernel_size, filters, stage, block)
The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label...
The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label...
def identity_block(input_tensor, kernel_size, filters, stage, block): """The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the fil...
[ "def", "identity_block", "(", "input_tensor", ",", "kernel_size", ",", "filters", ",", "stage", ",", "block", ")", ":", "filters1", ",", "filters2", ",", "filters3", "=", "filters", "conv_name_base", "=", "'res'", "+", "str", "(", "stage", ")", "+", "block...
[ 7, 0 ]
[ 43, 10 ]
python
en
['en', 'en', 'en']
True
conv_block
(input_tensor, kernel_size, filters, stage, block, strides=(2, 2))
A block that has a conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating lay...
A block that has a conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, current stage label, used for generating lay...
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): """A block that has a conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle co...
[ "def", "conv_block", "(", "input_tensor", ",", "kernel_size", ",", "filters", ",", "stage", ",", "block", ",", "strides", "=", "(", "2", ",", "2", ")", ")", ":", "filters1", ",", "filters2", ",", "filters3", "=", "filters", "conv_name_base", "=", "'res'"...
[ 46, 0 ]
[ 96, 10 ]
python
en
['en', 'ca', 'en']
True
register_handler
(handler)
Install application-specific WMF image handler. :param handler: Handler object.
Install application-specific WMF image handler.
def register_handler(handler): """ Install application-specific WMF image handler. :param handler: Handler object. """ global _handler _handler = handler
[ "def", "register_handler", "(", "handler", ")", ":", "global", "_handler", "_handler", "=", "handler" ]
[ 30, 0 ]
[ 37, 22 ]
python
en
['en', 'error', 'th']
False
LazySettings._setup
(self, name=None)
Load the settings module pointed to by the environment variable. This is used the first time settings are needed, if the user hasn't configured settings manually.
Load the settings module pointed to by the environment variable. This is used the first time settings are needed, if the user hasn't configured settings manually.
def _setup(self, name=None): """ Load the settings module pointed to by the environment variable. This is used the first time settings are needed, if the user hasn't configured settings manually. """ settings_module = os.environ.get(ENVIRONMENT_VARIABLE) if not se...
[ "def", "_setup", "(", "self", ",", "name", "=", "None", ")", ":", "settings_module", "=", "os", ".", "environ", ".", "get", "(", "ENVIRONMENT_VARIABLE", ")", "if", "not", "settings_module", ":", "desc", "=", "(", "\"setting %s\"", "%", "name", ")", "if",...
[ 53, 4 ]
[ 68, 49 ]
python
en
['en', 'error', 'th']
False
LazySettings.__getattr__
(self, name)
Return the value of a setting and cache it in self.__dict__.
Return the value of a setting and cache it in self.__dict__.
def __getattr__(self, name): """Return the value of a setting and cache it in self.__dict__.""" if self._wrapped is empty: self._setup(name) val = getattr(self._wrapped, name) # Special case some settings which require further modification. # This is done here for pe...
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_wrapped", "is", "empty", ":", "self", ".", "_setup", "(", "name", ")", "val", "=", "getattr", "(", "self", ".", "_wrapped", ",", "name", ")", "# Special case some settings whi...
[ 78, 4 ]
[ 92, 18 ]
python
en
['en', 'en', 'en']
True
LazySettings.__setattr__
(self, name, value)
Set the value of setting. Clear all cached values if _wrapped changes (@override_settings does this) or clear single values when set.
Set the value of setting. Clear all cached values if _wrapped changes (
def __setattr__(self, name, value): """ Set the value of setting. Clear all cached values if _wrapped changes (@override_settings does this) or clear single values when set. """ if name == '_wrapped': self.__dict__.clear() else: self.__dict__.pop(n...
[ "def", "__setattr__", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "==", "'_wrapped'", ":", "self", ".", "__dict__", ".", "clear", "(", ")", "else", ":", "self", ".", "__dict__", ".", "pop", "(", "name", ",", "None", ")", "super"...
[ 94, 4 ]
[ 103, 40 ]
python
en
['en', 'error', 'th']
False
LazySettings.__delattr__
(self, name)
Delete a setting and clear it from cache if needed.
Delete a setting and clear it from cache if needed.
def __delattr__(self, name): """Delete a setting and clear it from cache if needed.""" super().__delattr__(name) self.__dict__.pop(name, None)
[ "def", "__delattr__", "(", "self", ",", "name", ")", ":", "super", "(", ")", ".", "__delattr__", "(", "name", ")", "self", ".", "__dict__", ".", "pop", "(", "name", ",", "None", ")" ]
[ 105, 4 ]
[ 108, 37 ]
python
en
['en', 'en', 'en']
True
LazySettings.configure
(self, default_settings=global_settings, **options)
Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)).
Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)).
def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._wr...
[ "def", "configure", "(", "self", ",", "default_settings", "=", "global_settings", ",", "*", "*", "options", ")", ":", "if", "self", ".", "_wrapped", "is", "not", "empty", ":", "raise", "RuntimeError", "(", "'Settings already configured.'", ")", "holder", "=", ...
[ 110, 4 ]
[ 123, 30 ]
python
en
['en', 'error', 'th']
False
LazySettings._add_script_prefix
(value)
Add SCRIPT_NAME prefix to relative paths. Useful when the app is being served at a subpath and manually prefixing subpath to STATIC_URL and MEDIA_URL in settings is inconvenient.
Add SCRIPT_NAME prefix to relative paths.
def _add_script_prefix(value): """ Add SCRIPT_NAME prefix to relative paths. Useful when the app is being served at a subpath and manually prefixing subpath to STATIC_URL and MEDIA_URL in settings is inconvenient. """ # Don't apply prefix to absolute paths and URLs. ...
[ "def", "_add_script_prefix", "(", "value", ")", ":", "# Don't apply prefix to absolute paths and URLs.", "if", "value", ".", "startswith", "(", "(", "'http://'", ",", "'https://'", ",", "'/'", ")", ")", ":", "return", "value", "from", "django", ".", "urls", "imp...
[ 126, 4 ]
[ 137, 52 ]
python
en
['en', 'error', 'th']
False
LazySettings.configured
(self)
Return True if the settings have already been configured.
Return True if the settings have already been configured.
def configured(self): """Return True if the settings have already been configured.""" return self._wrapped is not empty
[ "def", "configured", "(", "self", ")", ":", "return", "self", ".", "_wrapped", "is", "not", "empty" ]
[ 140, 4 ]
[ 142, 41 ]
python
en
['en', 'en', 'en']
True
UserSettingsHolder.__init__
(self, default_settings)
Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible).
Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible).
def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings
[ "def", "__init__", "(", "self", ",", "default_settings", ")", ":", "self", ".", "__dict__", "[", "'_deleted'", "]", "=", "set", "(", ")", "self", ".", "default_settings", "=", "default_settings" ]
[ 227, 4 ]
[ 233, 48 ]
python
en
['en', 'error', 'th']
False
HealpyModel.__init__
(self, network, input_shape=None, optimizer=None, save_dir=None, restore_point=None, summary_dir=None, init_step=0, is_chief=True)
Initializes a base model :param network: The underlying network of the model (expected to be either a tf.keras.Sequential or a subclass of it) :param input_shape: Optional input shape of the network, necessary if one wants to restore the model :param optimizer: O...
Initializes a base model :param network: The underlying network of the model (expected to be either a tf.keras.Sequential or a subclass of it) :param input_shape: Optional input shape of the network, necessary if one wants to restore the model :param optimizer: O...
def __init__(self, network, input_shape=None, optimizer=None, save_dir=None, restore_point=None, summary_dir=None, init_step=0, is_chief=True): """ Initializes a base model :param network: The underlying network of the model (expected to be either a tf.keras.Sequential or a subc...
[ "def", "__init__", "(", "self", ",", "network", ",", "input_shape", "=", "None", ",", "optimizer", "=", "None", ",", "save_dir", "=", "None", ",", "restore_point", "=", "None", ",", "summary_dir", "=", "None", ",", "init_step", "=", "0", ",", "is_chief",...
[ 19, 4 ]
[ 90, 29 ]
python
en
['en', 'error', 'th']
False
HealpyModel.clean_summaries
(self, force=False)
Removes redundant summary directories... :param force: force the removal even if the worker is not chief
Removes redundant summary directories... :param force: force the removal even if the worker is not chief
def clean_summaries(self, force=False): """ Removes redundant summary directories... :param force: force the removal even if the worker is not chief """ if self.is_chief or force: try: num_workers = hvd.size() except ValueError: ...
[ "def", "clean_summaries", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "is_chief", "or", "force", ":", "try", ":", "num_workers", "=", "hvd", ".", "size", "(", ")", "except", "ValueError", ":", "print", "(", "\"Nothing to clean, ...
[ 92, 4 ]
[ 109, 103 ]
python
en
['en', 'error', 'th']
False
HealpyModel.update_step
(self)
increments the train step of the model by 1
increments the train step of the model by 1
def update_step(self): """ increments the train step of the model by 1 """ self.train_step.assign(self.train_step + 1)
[ "def", "update_step", "(", "self", ")", ":", "self", ".", "train_step", ".", "assign", "(", "self", ".", "train_step", "+", "1", ")" ]
[ 111, 4 ]
[ 115, 51 ]
python
en
['en', 'error', 'th']
False
HealpyModel.set_step
(self, step)
Sets the current training step of the model to a given value :param step: The new step (int)
Sets the current training step of the model to a given value :param step: The new step (int)
def set_step(self, step): """ Sets the current training step of the model to a given value :param step: The new step (int) """ self.train_step.assign(step)
[ "def", "set_step", "(", "self", ",", "step", ")", ":", "self", ".", "train_step", ".", "assign", "(", "step", ")" ]
[ 117, 4 ]
[ 122, 36 ]
python
en
['en', 'error', 'th']
False
HealpyModel.restore_model
(self, restore_point=None)
Restores the weights of the network given a restore point :param restore_point: either a directory that includes checkpoints (of which the most recent will be chosen) or the path to a specific checkpoint to restore from, default to value at init of model
Restores the weights of the network given a restore point :param restore_point: either a directory that includes checkpoints (of which the most recent will be chosen) or the path to a specific checkpoint to restore from, default to value at init of model
def restore_model(self, restore_point=None): """ Restores the weights of the network given a restore point :param restore_point: either a directory that includes checkpoints (of which the most recent will be chosen) or the path to a specific checkpoint to restore fr...
[ "def", "restore_model", "(", "self", ",", "restore_point", "=", "None", ")", ":", "if", "restore_point", "is", "None", "and", "self", ".", "restore_point", "is", "None", ":", "raise", "ValueError", "(", "\"No restore point was provided in the initialization or as argu...
[ 124, 4 ]
[ 156, 80 ]
python
en
['en', 'error', 'th']
False
HealpyModel.save_model
(self, save_dir=None, force=False)
Saves the weights of the model into a given directory, this function won't do anything if the model is not chief :param save_dir: the path where to save the weights, defaults to the value at init of model :param force: write the checkpoint even if the model is not chief, this can lead to errors...
Saves the weights of the model into a given directory, this function won't do anything if the model is not chief :param save_dir: the path where to save the weights, defaults to the value at init of model :param force: write the checkpoint even if the model is not chief, this can lead to errors...
def save_model(self, save_dir=None, force=False): """ Saves the weights of the model into a given directory, this function won't do anything if the model is not chief :param save_dir: the path where to save the weights, defaults to the value at init of model :param force: write the check...
[ "def", "save_model", "(", "self", ",", "save_dir", "=", "None", ",", "force", "=", "False", ")", ":", "if", "self", ".", "is_chief", "or", "force", ":", "if", "save_dir", "is", "None", "and", "self", ".", "save_dir", "is", "None", ":", "raise", "Valu...
[ 158, 4 ]
[ 181, 103 ]
python
en
['en', 'error', 'th']
False
HealpyModel.build_network
(self, input_shape)
Builds the internal HealpyGCNN with a given input shape :param input_shape: input shape of the netork
Builds the internal HealpyGCNN with a given input shape :param input_shape: input shape of the netork
def build_network(self, input_shape): """ Builds the internal HealpyGCNN with a given input shape :param input_shape: input shape of the netork """ self.network.build(input_shape=input_shape)
[ "def", "build_network", "(", "self", ",", "input_shape", ")", ":", "self", ".", "network", ".", "build", "(", "input_shape", "=", "input_shape", ")" ]
[ 183, 4 ]
[ 188, 51 ]
python
en
['en', 'error', 'th']
False
HealpyModel.print_summary
(self, **kwargs)
Prints the summary of the internal network :param kwargs: passed to HealpyGCNN.summary
Prints the summary of the internal network :param kwargs: passed to HealpyGCNN.summary
def print_summary(self, **kwargs): """ Prints the summary of the internal network :param kwargs: passed to HealpyGCNN.summary """ self.network.summary(**kwargs)
[ "def", "print_summary", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "network", ".", "summary", "(", "*", "*", "kwargs", ")" ]
[ 190, 4 ]
[ 195, 38 ]
python
en
['en', 'error', 'th']
False
HealpyModel.base_train_step
(self, input_tensor, loss_function, input_labels=None, clip_by_value=None, clip_by_norm=None, clip_by_global_norm=None, training=True, num_workers=None, train_indices=None, return_loss=False)
A base train step given a loss funtion and an input tensor it evaluates the network and performs a single gradient decent step, if multiple clippings are requested the order will be: * by value * by norm * by global norm :param input_tensor: The input of the ...
A base train step given a loss funtion and an input tensor it evaluates the network and performs a single gradient decent step, if multiple clippings are requested the order will be: * by value * by norm * by global norm :param input_tensor: The input of the ...
def base_train_step(self, input_tensor, loss_function, input_labels=None, clip_by_value=None, clip_by_norm=None, clip_by_global_norm=None, training=True, num_workers=None, train_indices=None, return_loss=False): """ A base train step given a loss funtion a...
[ "def", "base_train_step", "(", "self", ",", "input_tensor", ",", "loss_function", ",", "input_labels", "=", "None", ",", "clip_by_value", "=", "None", ",", "clip_by_norm", "=", "None", ",", "clip_by_global_norm", "=", "None", ",", "training", "=", "True", ",",...
[ 197, 4 ]
[ 261, 27 ]
python
en
['en', 'error', 'th']
False
HealpyModel.setup_delta_loss_step
(self, batch_size, off_sets, n_points=1, n_channels=1, n_output=None, jac_weight=0.0, force_params=None, force_weight=1.0, jac_cond_weight=None, use_log_det=True, no_correlations=False, tikhonov_regu=False, weights=None, eps=1e-32, n_partial=None, ...
This sets up a function that performs one training step with the delta loss, which tries to maximize the information of the summary statistics. Note it needs the maps need to be ordered in a specific way: * The shape of the maps is (n_points*n_same*(2*n_params+1), len(indices), n_channels)...
This sets up a function that performs one training step with the delta loss, which tries to maximize the information of the summary statistics. Note it needs the maps need to be ordered in a specific way: * The shape of the maps is (n_points*n_same*(2*n_params+1), len(indices), n_channels)...
def setup_delta_loss_step(self, batch_size, off_sets, n_points=1, n_channels=1, n_output=None, jac_weight=0.0, force_params=None, force_weight=1.0, jac_cond_weight=None, use_log_det=True, no_correlations=False, tikhonov_regu=False, weights=None, eps=1e-32, n_p...
[ "def", "setup_delta_loss_step", "(", "self", ",", "batch_size", ",", "off_sets", ",", "n_points", "=", "1", ",", "n_channels", "=", "1", ",", "n_output", "=", "None", ",", "jac_weight", "=", "0.0", ",", "force_params", "=", "None", ",", "force_weight", "="...
[ 264, 4 ]
[ 367, 92 ]
python
en
['en', 'error', 'th']
False
HealpyModel.broadcast_variables
(self)
boradcasts the variables from the chief to all other workers from the network and optimizer
boradcasts the variables from the chief to all other workers from the network and optimizer
def broadcast_variables(self): """ boradcasts the variables from the chief to all other workers from the network and optimizer """ hvd.broadcast_variables(self.network.weights, root_rank=0) hvd.broadcast_variables(self.optimizer.variables(), root_rank=0)
[ "def", "broadcast_variables", "(", "self", ")", ":", "hvd", ".", "broadcast_variables", "(", "self", ".", "network", ".", "weights", ",", "root_rank", "=", "0", ")", "hvd", ".", "broadcast_variables", "(", "self", ".", "optimizer", ".", "variables", "(", "...
[ 369, 4 ]
[ 374, 72 ]
python
en
['en', 'error', 'th']
False
HealpyModel.setup_1st_order_estimator
(self, dset, fidu_param, off_sets, print_params=False, tf_dtype=tf.float32, tikohnov=0.0, layer=None, dset_is_sims=False)
Sets up a first order estimator from a given dataset that will be evaluated :param dset: The dataset that will be evaluated :param fidu_param: the fiducial parameter of the estimator :param off_sets: the offsets used for the perturbations :param print_params: print the calculate...
Sets up a first order estimator from a given dataset that will be evaluated :param dset: The dataset that will be evaluated :param fidu_param: the fiducial parameter of the estimator :param off_sets: the offsets used for the perturbations :param print_params: print the calculate...
def setup_1st_order_estimator(self, dset, fidu_param, off_sets, print_params=False, tf_dtype=tf.float32, tikohnov=0.0, layer=None, dset_is_sims=False): """ Sets up a first order estimator from a given dataset that will be evaluated :param dset: The dataset that wi...
[ "def", "setup_1st_order_estimator", "(", "self", ",", "dset", ",", "fidu_param", ",", "off_sets", ",", "print_params", "=", "False", ",", "tf_dtype", "=", "tf", ".", "float32", ",", "tikohnov", "=", "0.0", ",", "layer", "=", "None", ",", "dset_is_sims", "=...
[ 376, 4 ]
[ 409, 109 ]
python
en
['en', 'error', 'th']
False
HealpyModel.estimate
(self, input_tensor)
Calculates the first order estimates of the underlying model parameter given a network input :param input_tensor: The input to feed in the network :return: The parameter estimates
Calculates the first order estimates of the underlying model parameter given a network input :param input_tensor: The input to feed in the network :return: The parameter estimates
def estimate(self, input_tensor): """ Calculates the first order estimates of the underlying model parameter given a network input :param input_tensor: The input to feed in the network :return: The parameter estimates """ if self.estimator is None: raise Valu...
[ "def", "estimate", "(", "self", ",", "input_tensor", ")", ":", "if", "self", ".", "estimator", "is", "None", ":", "raise", "ValueError", "(", "\"First order estimator not set! Call <setup_1st_order_estimator> first!\"", ")", "preds", "=", "self", ".", "__call__", "(...
[ 411, 4 ]
[ 422, 36 ]
python
en
['en', 'error', 'th']
False
HealpyModel.__call__
(self, input_tensor, training=False, numpy=False, layer=None, *args, **kwargs)
Calls the underlying network :param input_tensor: the tensor (or array) to call on :param training: whether we are training or evaluating (e.g. necessary gor batch norm) :param args: additional arguments passed to the network :param kwargs: additional keyword arguments passed to...
Calls the underlying network :param input_tensor: the tensor (or array) to call on :param training: whether we are training or evaluating (e.g. necessary gor batch norm) :param args: additional arguments passed to the network :param kwargs: additional keyword arguments passed to...
def __call__(self, input_tensor, training=False, numpy=False, layer=None, *args, **kwargs): """ Calls the underlying network :param input_tensor: the tensor (or array) to call on :param training: whether we are training or evaluating (e.g. necessary gor batch norm) :param args: a...
[ "def", "__call__", "(", "self", ",", "input_tensor", ",", "training", "=", "False", ",", "numpy", "=", "False", ",", "layer", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "layer", "is", "None", ":", "preds", "=", "self", ...
[ 424, 4 ]
[ 445, 24 ]
python
en
['en', 'error', 'th']
False
UserNSVD1.__init__
(self, train_file=None, test_file=None, metadata_file=None, output_file=None, epochs=30, learn_rate=0.01, delta=0.015, factors=10, init_mean=0, init_stdev=0.1, stop_criteria=0.001, batch=False, n2=10, learn_rate2=0.01, delta2=0.015, sep='\t', output_sep='\t', metadata_sep='\t', ...
UserNSVD1 for rating prediction Usage:: >> UserNSVD1(train, test, metadata_file='user_metadata.dat').compute() >> UserNSVD1(train, test, metadata_file='user_metadata.dat', batch=True).compute() :param train_file: File which contains the train set. This file needs to h...
UserNSVD1 for rating prediction
def __init__(self, train_file=None, test_file=None, metadata_file=None, output_file=None, epochs=30, learn_rate=0.01, delta=0.015, factors=10, init_mean=0, init_stdev=0.1, stop_criteria=0.001, batch=False, n2=10, learn_rate2=0.01, delta2=0.015, sep='\t', output_sep='\t', metadata_sep='...
[ "def", "__init__", "(", "self", ",", "train_file", "=", "None", ",", "test_file", "=", "None", ",", "metadata_file", "=", "None", ",", "output_file", "=", "None", ",", "epochs", "=", "30", ",", "learn_rate", "=", "0.01", ",", "delta", "=", "0.015", ","...
[ 27, 4 ]
[ 125, 21 ]
python
en
['en', 'error', 'th']
False
UserNSVD1.init_model
(self)
Method to treat and initialize the model. Extends init_model from BaseNSVD1
Method to treat and initialize the model. Extends init_model from BaseNSVD1
def init_model(self): """ Method to treat and initialize the model. Extends init_model from BaseNSVD1 """ super(UserNSVD1, self).init_model() self.non_zero_x = [] self.d = [] self.metadata = ReadFile(self.metadata_file, sep=self.metadata_sep, as_binary=self.me...
[ "def", "init_model", "(", "self", ")", ":", "super", "(", "UserNSVD1", ",", "self", ")", ".", "init_model", "(", ")", "self", ".", "non_zero_x", "=", "[", "]", "self", ".", "d", "=", "[", "]", "self", ".", "metadata", "=", "ReadFile", "(", "self", ...
[ 127, 4 ]
[ 168, 29 ]
python
en
['en', 'error', 'th']
False
UserNSVD1.fit
(self)
This method performs iterations of stochastic gradient ascent over the training data.
This method performs iterations of stochastic gradient ascent over the training data.
def fit(self): """ This method performs iterations of stochastic gradient ascent over the training data. """ for k in range(self.epochs): rmse = 0 count_error = 0 if self.batch: self.p = np.dot(self.x, self.w) for u...
[ "def", "fit", "(", "self", ")", ":", "for", "k", "in", "range", "(", "self", ".", "epochs", ")", ":", "rmse", "=", "0", "count_error", "=", "0", "if", "self", ".", "batch", ":", "self", ".", "p", "=", "np", ".", "dot", "(", "self", ".", "x", ...
[ 170, 4 ]
[ 215, 37 ]
python
en
['en', 'error', 'th']
False
UserNSVD1.update_factors
(self, user, u)
Update latent factors according to the stochastic gradient descent update rule :param user: User :type user: int :param u: User ID from self.users :type u: int :return: error and count
Update latent factors according to the stochastic gradient descent update rule
def update_factors(self, user, u): """ Update latent factors according to the stochastic gradient descent update rule :param user: User :type user: int :param u: User ID from self.users :type u: int :return: error and count """ c, e = 0, 0 ...
[ "def", "update_factors", "(", "self", ",", "user", ",", "u", ")", ":", "c", ",", "e", "=", "0", ",", "0", "for", "item", "in", "self", ".", "train_set", "[", "'items_seen_by_user'", "]", ".", "get", "(", "user", ",", "[", "]", ")", ":", "i", "=...
[ 217, 4 ]
[ 246, 19 ]
python
en
['en', 'error', 'th']
False
UserNSVD1.compute
(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t')
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default True :param metrics: List of evaluation measures :type metrics: list, default None :param verb...
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm
def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'): """ Extends compute method from BaseRatingPrediction. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default True ...
[ "def", "compute", "(", "self", ",", "verbose", "=", "True", ",", "metrics", "=", "None", ",", "verbose_evaluation", "=", "True", ",", "as_table", "=", "False", ",", "table_sep", "=", "'\\t'", ")", ":", "super", "(", "UserNSVD1", ",", "self", ")", ".", ...
[ 248, 4 ]
[ 288, 94 ]
python
en
['en', 'error', 'th']
False
newer_pairwise_group
(sources_groups, targets)
Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'.
Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'.
def newer_pairwise_group(sources_groups, targets): """Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'. """ if ...
[ "def", "newer_pairwise_group", "(", "sources_groups", ",", "targets", ")", ":", "if", "len", "(", "sources_groups", ")", "!=", "len", "(", "targets", ")", ":", "raise", "ValueError", "(", "\"'sources_group' and 'targets' must be the same length\"", ")", "# build a pai...
[ 5, 0 ]
[ 22, 31 ]
python
en
['en', 'en', 'en']
True
_parse_arguments
(argv)
Parses command-line arguments.
Parses command-line arguments.
def _parse_arguments(argv): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--epochs', help='The number of epochs to train', type=int, default=5) parser.add_argument( '--steps_per_epoch', help='The number of steps per ...
[ "def", "_parse_arguments", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--epochs'", ",", "help", "=", "'The number of epochs to train'", ",", "type", "=", "int", ",", "default", "=", ...
[ 11, 0 ]
[ 42, 40 ]
python
en
['en', 'fr', 'en']
True
main
()
Parses command line arguments and kicks off model training.
Parses command line arguments and kicks off model training.
def main(): """Parses command line arguments and kicks off model training.""" args = _parse_arguments(sys.argv[1:])[0] # TODO: define a TPU strategy resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=args.tpu_address) tf.config.experimental_connect_to_cluster(resolver) ...
[ "def", "main", "(", ")", ":", "args", "=", "_parse_arguments", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "[", "0", "]", "# TODO: define a TPU strategy", "resolver", "=", "tf", ".", "distribute", ".", "cluster_resolver", ".", "TPUClusterResolver", "...
[ 45, 0 ]
[ 63, 44 ]
python
en
['en', 'en', 'en']
True
_have_cython
()
Return True if Cython can be imported.
Return True if Cython can be imported.
def _have_cython(): """ Return True if Cython can be imported. """ cython_impl = 'Cython.Distutils.build_ext' try: # from (cython_impl) import build_ext __import__(cython_impl, fromlist=['build_ext']).build_ext return True except Exception: pass return False
[ "def", "_have_cython", "(", ")", ":", "cython_impl", "=", "'Cython.Distutils.build_ext'", "try", ":", "# from (cython_impl) import build_ext", "__import__", "(", "cython_impl", ",", "fromlist", "=", "[", "'build_ext'", "]", ")", ".", "build_ext", "return", "True", "...
[ 11, 0 ]
[ 22, 16 ]
python
en
['en', 'error', 'th']
False
Extension._convert_pyx_sources_to_lang
(self)
Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources.
Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources.
def _convert_pyx_sources_to_lang(self): """ Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources. """ if _have_cython(): # the ...
[ "def", "_convert_pyx_sources_to_lang", "(", "self", ")", ":", "if", "_have_cython", "(", ")", ":", "# the build has Cython, so allow it to compile the .pyx files", "return", "lang", "=", "self", ".", "language", "or", "''", "target_ext", "=", "'.cpp'", "if", "lang", ...
[ 40, 4 ]
[ 52, 51 ]
python
en
['en', 'error', 'th']
False
CrossValidation.__init__
(self, input_file, recommender, dir_folds, k_folds=10, header=None, sep='\t', write_predictions=False, write_sep='\t', recommender_verbose=False, evaluation_in_fold_verbose=True, metrics=None, as_table=False, table_sep='\t', del_folds=False, random_seed=None)
Cross Validation This strategy is responsible to divide the database in K folds, in which each fold contain a train and a test set. Its also responsible to run and evaluate the recommender results in each fold and calculate the mean and the standard deviation. Usage: ...
Cross Validation
def __init__(self, input_file, recommender, dir_folds, k_folds=10, header=None, sep='\t', write_predictions=False, write_sep='\t', recommender_verbose=False, evaluation_in_fold_verbose=True, metrics=None, as_table=False, table_sep='\t', del_folds=False, random_seed=None): """ ...
[ "def", "__init__", "(", "self", ",", "input_file", ",", "recommender", ",", "dir_folds", ",", "k_folds", "=", "10", ",", "header", "=", "None", ",", "sep", "=", "'\\t'", ",", "write_predictions", "=", "False", ",", "write_sep", "=", "'\\t'", ",", "recomm...
[ 18, 4 ]
[ 96, 46 ]
python
en
['en', 'error', 'th']
False
CrossValidation.generate_folds
(self)
Method to generate folds with k fold cross validation
Method to generate folds with k fold cross validation
def generate_folds(self): """ Method to generate folds with k fold cross validation """ SplitDatabase(input_file=self.input_file, n_splits=self.k_folds, dir_folds=self.dir_folds, sep_read=self.sep, header=self.header).kfoldcrossvalidation(random_state=self.random_...
[ "def", "generate_folds", "(", "self", ")", ":", "SplitDatabase", "(", "input_file", "=", "self", ".", "input_file", ",", "n_splits", "=", "self", ".", "k_folds", ",", "dir_folds", "=", "self", ".", "dir_folds", ",", "sep_read", "=", "self", ".", "sep", "...
[ 98, 4 ]
[ 105, 112 ]
python
en
['en', 'error', 'th']
False
CrossValidation.execute_algorithm
(self)
Method to run recommender algorithm in k folds
Method to run recommender algorithm in k folds
def execute_algorithm(self): """ Method to run recommender algorithm in k folds """ for k in range(self.k_folds): train_file = self.dir_folds + 'folds/%d/train.dat' % k test_file = self.dir_folds + 'folds/%d/test.dat' % k self.recommender.train_file...
[ "def", "execute_algorithm", "(", "self", ")", ":", "for", "k", "in", "range", "(", "self", ".", "k_folds", ")", ":", "train_file", "=", "self", ".", "dir_folds", "+", "'folds/%d/train.dat'", "%", "k", "test_file", "=", "self", ".", "dir_folds", "+", "'fo...
[ 107, 4 ]
[ 131, 110 ]
python
en
['en', 'error', 'th']
False
CrossValidation.evaluate
(self, verbose=True)
Method to evaluate folds results and generate mean and standard deviation :param verbose: If True, print evaluation results :type verbose: bool, default True
Method to evaluate folds results and generate mean and standard deviation
def evaluate(self, verbose=True): """ Method to evaluate folds results and generate mean and standard deviation :param verbose: If True, print evaluation results :type verbose: bool, default True """ mean_dict = defaultdict(dict) std_dict = defaultdict(dict) ...
[ "def", "evaluate", "(", "self", ",", "verbose", "=", "True", ")", ":", "mean_dict", "=", "defaultdict", "(", "dict", ")", "std_dict", "=", "defaultdict", "(", "dict", ")", "for", "metric", "in", "self", ".", "metrics", ":", "mean_dict", "[", "metric", ...
[ 133, 4 ]
[ 168, 37 ]
python
en
['en', 'error', 'th']
False
CrossValidation.erase_folds
(self)
Method to delete folds after evaluation
Method to delete folds after evaluation
def erase_folds(self): """ Method to delete folds after evaluation """ folds = self.dir_folds + 'folds/' shutil.rmtree(folds)
[ "def", "erase_folds", "(", "self", ")", ":", "folds", "=", "self", ".", "dir_folds", "+", "'folds/'", "shutil", ".", "rmtree", "(", "folds", ")" ]
[ 170, 4 ]
[ 177, 28 ]
python
en
['en', 'error', 'th']
False
CrossValidation.compute
(self, verbose=True)
Method to run the cross validation :param verbose: If True, print header :type verbose: bool, default True
Method to run the cross validation
def compute(self, verbose=True): """ Method to run the cross validation :param verbose: If True, print header :type verbose: bool, default True """ if verbose: print("[Case Recommender: Cross Validation]\n") print("Database:: %s \nRecommender A...
[ "def", "compute", "(", "self", ",", "verbose", "=", "True", ")", ":", "if", "verbose", ":", "print", "(", "\"[Case Recommender: Cross Validation]\\n\"", ")", "print", "(", "\"Database:: %s \\nRecommender Algorithm:: %s | K Folds: %d\\n\"", "%", "(", "self", ".", "inpu...
[ 179, 4 ]
[ 200, 30 ]
python
en
['en', 'error', 'th']
False
Greatest.as_sqlite
(self, compiler, connection, **extra_context)
Use the MAX function on SQLite.
Use the MAX function on SQLite.
def as_sqlite(self, compiler, connection, **extra_context): """Use the MAX function on SQLite.""" return super().as_sqlite(compiler, connection, function='MAX', **extra_context)
[ "def", "as_sqlite", "(", "self", ",", "compiler", ",", "connection", ",", "*", "*", "extra_context", ")", ":", "return", "super", "(", ")", ".", "as_sqlite", "(", "compiler", ",", "connection", ",", "function", "=", "'MAX'", ",", "*", "*", "extra_context...
[ 105, 4 ]
[ 107, 87 ]
python
en
['en', 'en', 'en']
True
Least.as_sqlite
(self, compiler, connection, **extra_context)
Use the MIN function on SQLite.
Use the MIN function on SQLite.
def as_sqlite(self, compiler, connection, **extra_context): """Use the MIN function on SQLite.""" return super().as_sqlite(compiler, connection, function='MIN', **extra_context)
[ "def", "as_sqlite", "(", "self", ",", "compiler", ",", "connection", ",", "*", "*", "extra_context", ")", ":", "return", "super", "(", ")", ".", "as_sqlite", "(", "compiler", ",", "connection", ",", "function", "=", "'MIN'", ",", "*", "*", "extra_context...
[ 165, 4 ]
[ 167, 87 ]
python
en
['en', 'en', 'en']
True
UserKNN.__init__
(self, train_file=None, test_file=None, output_file=None, similarity_metric="cosine", k_neighbors=None, as_similar_first=False, sep='\t', output_sep='\t')
UserKNN for rating prediction This algorithm predicts ratings for each user based on the similar items that his neighbors (similar users) consumed. Usage:: >> UserKNN(train, test).compute() >> UserKNN(train, test, ranking_file, as_similar_first=True, k_neighbo...
UserKNN for rating prediction
def __init__(self, train_file=None, test_file=None, output_file=None, similarity_metric="cosine", k_neighbors=None, as_similar_first=False, sep='\t', output_sep='\t'): """ UserKNN for rating prediction This algorithm predicts ratings for each user based on the similar items tha...
[ "def", "__init__", "(", "self", ",", "train_file", "=", "None", ",", "test_file", "=", "None", ",", "output_file", "=", "None", ",", "similarity_metric", "=", "\"cosine\"", ",", "k_neighbors", "=", "None", ",", "as_similar_first", "=", "False", ",", "sep", ...
[ 24, 4 ]
[ 77, 40 ]
python
en
['en', 'error', 'th']
False
UserKNN.init_model
(self)
Method to initialize the model. Compute similarity matrix based on user (user x user)
Method to initialize the model. Compute similarity matrix based on user (user x user)
def init_model(self): """ Method to initialize the model. Compute similarity matrix based on user (user x user) """ super(UserKNN, self).init_model() self.users_id_viewed_item = {} # Set the value for k if self.k_neighbors is None: self.k_neighbors...
[ "def", "init_model", "(", "self", ")", ":", "super", "(", "UserKNN", ",", "self", ")", ".", "init_model", "(", ")", "self", ".", "users_id_viewed_item", "=", "{", "}", "# Set the value for k", "if", "self", ".", "k_neighbors", "is", "None", ":", "self", ...
[ 79, 4 ]
[ 98, 97 ]
python
en
['en', 'error', 'th']
False
UserKNN.predict
(self)
Method to predict ratings for all known users in the train set.
Method to predict ratings for all known users in the train set.
def predict(self): """ Method to predict ratings for all known users in the train set. """ for user in self.users: if len(self.train_set['feedback'].get(user, [])) != 0: if self.test_file is not None: if self.as_similar_first: ...
[ "def", "predict", "(", "self", ")", ":", "for", "user", "in", "self", ".", "users", ":", "if", "len", "(", "self", ".", "train_set", "[", "'feedback'", "]", ".", "get", "(", "user", ",", "[", "]", ")", ")", "!=", "0", ":", "if", "self", ".", ...
[ 100, 4 ]
[ 127, 20 ]
python
en
['en', 'error', 'th']
False
UserKNN.predict_scores
(self, user, unpredicted_items)
In this implementation, for each unknown item, which will be predicted, we first look for users that seen that item and calculate the similarity between them and the user. Then we sort these similarities and get the most similar k's. Finally, the score of the unknown item will be the su...
In this implementation, for each unknown item, which will be predicted, we first look for users that seen that item and calculate the similarity between them and the user. Then we sort these similarities and get the most similar k's. Finally, the score of the unknown item will be the su...
def predict_scores(self, user, unpredicted_items): """ In this implementation, for each unknown item, which will be predicted, we first look for users that seen that item and calculate the similarity between them and the user. Then we sort these similarities and get the most similar k's....
[ "def", "predict_scores", "(", "self", ",", "user", ",", "unpredicted_items", ")", ":", "u_id", "=", "self", ".", "user_to_user_id", "[", "user", "]", "predictions", "=", "[", "]", "for", "item", "in", "unpredicted_items", ":", "neighbors", "=", "[", "]", ...
[ 129, 4 ]
[ 179, 54 ]
python
en
['en', 'error', 'th']
False
UserKNN.predict_similar_first_scores
(self, user, unpredicted_items)
In this implementation, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. Finally, the score of the unknown item will be the sum of the similarities. rui = bui + (sum((rvi - bvi...
In this implementation, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. Finally, the score of the unknown item will be the sum of the similarities.
def predict_similar_first_scores(self, user, unpredicted_items): """ In this implementation, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. Finally, the score of the unknown ite...
[ "def", "predict_similar_first_scores", "(", "self", ",", "user", ",", "unpredicted_items", ")", ":", "u_id", "=", "self", ".", "user_to_user_id", "[", "user", "]", "predictions", "=", "[", "]", "# Select user neighbors, sorting user similarity vector. Returns a list with ...
[ 181, 4 ]
[ 234, 54 ]
python
en
['en', 'error', 'th']
False
UserKNN.compute
(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t')
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default True :param metrics: List of evaluation metrics :type metrics: list, default None :param ver...
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm
def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'): """ Extends compute method from BaseItemRecommendation. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default Tru...
[ "def", "compute", "(", "self", ",", "verbose", "=", "True", ",", "metrics", "=", "None", ",", "verbose_evaluation", "=", "True", ",", "as_table", "=", "False", ",", "table_sep", "=", "'\\t'", ")", ":", "super", "(", "UserKNN", ",", "self", ")", ".", ...
[ 236, 4 ]
[ 276, 94 ]
python
en
['en', 'error', 'th']
False
get_all_headers
(message, key)
Given an HTTPMessage, return all headers matching a given key.
Given an HTTPMessage, return all headers matching a given key.
def get_all_headers(message, key): """ Given an HTTPMessage, return all headers matching a given key. """ return message.get_all(key)
[ "def", "get_all_headers", "(", "message", ",", "key", ")", ":", "return", "message", ".", "get_all", "(", "key", ")" ]
[ 9, 0 ]
[ 13, 31 ]
python
en
['en', 'error', 'th']
False
_convert_vcf_to_table
(vcf_filename: Path)
Converts all records in a vcf file into a list of dictionaries.
Converts all records in a vcf file into a list of dictionaries.
def _convert_vcf_to_table(vcf_filename: Path) -> List[Dict[str, Any]]: """Converts all records in a vcf file into a list of dictionaries.""" table: List[Dict[str, str]] = list() seen_positions = set() with vcf_filename.open('r') as file1: vcf_reader = vcf.Reader(file1) for record in vcf_reader: data = _conve...
[ "def", "_convert_vcf_to_table", "(", "vcf_filename", ":", "Path", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "table", ":", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "list", "(", ")", "seen_positions", "...
[ 36, 0 ]
[ 50, 13 ]
python
en
['en', 'en', 'en']
True
parse_vcf_file
(filename: Path, set_index: bool = True)
Converts the VCF file generated by breseq into a pandas Dataframe. Parameters ---------- filename: Path Either a folder containing a single breseq run or a path to the vcf file itself. set_index:bool; default True Whether to set the index of the dataframe. Returns ------- pandas.DataFrame - Index -> (VC...
Converts the VCF file generated by breseq into a pandas Dataframe. Parameters ---------- filename: Path Either a folder containing a single breseq run or a path to the vcf file itself. set_index:bool; default True Whether to set the index of the dataframe. Returns ------- pandas.DataFrame - Index -> (VC...
def parse_vcf_file(filename: Path, set_index: bool = True) -> pandas.DataFrame: """ Converts the VCF file generated by breseq into a pandas Dataframe. Parameters ---------- filename: Path Either a folder containing a single breseq run or a path to the vcf file itself. set_index:bool; default True Whether to ...
[ "def", "parse_vcf_file", "(", "filename", ":", "Path", ",", "set_index", ":", "bool", "=", "True", ")", "->", "pandas", ".", "DataFrame", ":", "table", "=", "_convert_vcf_to_table", "(", "filename", ")", "# Columns are defined in VCFColumns", "vcf_df", ":", "pan...
[ 53, 0 ]
[ 80, 19 ]
python
en
['en', 'error', 'th']
False
split_unquoted_newlines
(stmt)
Split a string on all unquoted newlines. Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite character is inside of a string.
Split a string on all unquoted newlines.
def split_unquoted_newlines(stmt): """Split a string on all unquoted newlines. Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite character is inside of a string.""" text = str(stmt) lines = SPLIT_REGEX.split(text) outputlines = [''] for line in lines: if not lin...
[ "def", "split_unquoted_newlines", "(", "stmt", ")", ":", "text", "=", "str", "(", "stmt", ")", "lines", "=", "SPLIT_REGEX", ".", "split", "(", "text", ")", "outputlines", "=", "[", "''", "]", "for", "line", "in", "lines", ":", "if", "not", "line", ":...
[ 35, 0 ]
[ 50, 22 ]
python
en
['en', 'en', 'en']
True
remove_quotes
(val)
Helper that removes surrounding quotes from strings.
Helper that removes surrounding quotes from strings.
def remove_quotes(val): """Helper that removes surrounding quotes from strings.""" if val is None: return if val[0] in ('"', "'") and val[0] == val[-1]: val = val[1:-1] return val
[ "def", "remove_quotes", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "if", "val", "[", "0", "]", "in", "(", "'\"'", ",", "\"'\"", ")", "and", "val", "[", "0", "]", "==", "val", "[", "-", "1", "]", ":", "val", "=", "val", ...
[ 53, 0 ]
[ 59, 14 ]
python
en
['en', 'en', 'en']
True
recurse
(*cls)
Function decorator to help with recursion :param cls: Classes to not recurse over :return: function
Function decorator to help with recursion
def recurse(*cls): """Function decorator to help with recursion :param cls: Classes to not recurse over :return: function """ def wrap(f): def wrapped_f(tlist): for sgroup in tlist.get_sublists(): if not isinstance(sgroup, cls): wrapped_f(sgro...
[ "def", "recurse", "(", "*", "cls", ")", ":", "def", "wrap", "(", "f", ")", ":", "def", "wrapped_f", "(", "tlist", ")", ":", "for", "sgroup", "in", "tlist", ".", "get_sublists", "(", ")", ":", "if", "not", "isinstance", "(", "sgroup", ",", "cls", ...
[ 62, 0 ]
[ 77, 15 ]
python
en
['en', 'en', 'en']
True
imt
(token, i=None, m=None, t=None)
Helper function to simplify comparisons Instance, Match and TokenType :param token: :param i: Class or Tuple/List of Classes :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple :param t: TokenType or Tuple/List of TokenTypes :return: bool
Helper function to simplify comparisons Instance, Match and TokenType :param token: :param i: Class or Tuple/List of Classes :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple :param t: TokenType or Tuple/List of TokenTypes :return: bool
def imt(token, i=None, m=None, t=None): """Helper function to simplify comparisons Instance, Match and TokenType :param token: :param i: Class or Tuple/List of Classes :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple :param t: TokenType or Tuple/List of TokenTypes :return:...
[ "def", "imt", "(", "token", ",", "i", "=", "None", ",", "m", "=", "None", ",", "t", "=", "None", ")", ":", "clss", "=", "i", "types", "=", "[", "t", ",", "]", "if", "t", "and", "not", "isinstance", "(", "t", ",", "list", ")", "else", "t", ...
[ 80, 0 ]
[ 101, 20 ]
python
en
['en', 'en', 'en']
True
consume
(iterator, n)
Advance the iterator n-steps ahead. If n is none, consume entirely.
Advance the iterator n-steps ahead. If n is none, consume entirely.
def consume(iterator, n): """Advance the iterator n-steps ahead. If n is none, consume entirely.""" deque(itertools.islice(iterator, n), maxlen=0)
[ "def", "consume", "(", "iterator", ",", "n", ")", ":", "deque", "(", "itertools", ".", "islice", "(", "iterator", ",", "n", ")", ",", "maxlen", "=", "0", ")" ]
[ 104, 0 ]
[ 106, 50 ]
python
en
['en', 'en', 'en']
True
private_to_public
()
Reads a private key and outputs the corresponding public key.
Reads a private key and outputs the corresponding public key.
def private_to_public(): """Reads a private key and outputs the corresponding public key.""" # Parse the CLI options parser = OptionParser(usage='usage: %prog [options]', description='Reads a private key and outputs the ' 'corresponding public...
[ "def", "private_to_public", "(", ")", ":", "# Parse the CLI options", "parser", "=", "OptionParser", "(", "usage", "=", "'usage: %prog [options]'", ",", "description", "=", "'Reads a private key and outputs the '", "'corresponding public key. Both private and public keys use '", ...
[ 26, 0 ]
[ 78, 50 ]
python
en
['en', 'en', 'en']
True
main
()
Entry point for the GUI-version of Blockify.
Entry point for the GUI-version of Blockify.
def main(): "Entry point for the GUI-version of Blockify." # Edit this for less or more logging. Loglevel 0 is least verbose. blockify.init_logger(logpath=None, loglevel=2, quiet=False) ui = BlockifyUI() gtk.main()
[ "def", "main", "(", ")", ":", "# Edit this for less or more logging. Loglevel 0 is least verbose.", "blockify", ".", "init_logger", "(", "logpath", "=", "None", ",", "loglevel", "=", "2", ",", "quiet", "=", "False", ")", "ui", "=", "BlockifyUI", "(", ")", "gtk",...
[ 426, 0 ]
[ 431, 14 ]
python
en
['en', 'en', 'en']
True
Notepad.create_keybinds
(self)
Register Ctrl+Q/W to quit and Ctrl+S to save the blocklist.
Register Ctrl+Q/W to quit and Ctrl+S to save the blocklist.
def create_keybinds(self): "Register Ctrl+Q/W to quit and Ctrl+S to save the blocklist." quit_group = gtk.AccelGroup() quit_group.connect_group(ord("q"), gtk.gdk.CONTROL_MASK, gtk.ACCEL_LOCKED, self.destroy) quit_group.connect_group(ord("w"), gtk.gdk.CONT...
[ "def", "create_keybinds", "(", "self", ")", ":", "quit_group", "=", "gtk", ".", "AccelGroup", "(", ")", "quit_group", ".", "connect_group", "(", "ord", "(", "\"q\"", ")", ",", "gtk", ".", "gdk", ".", "CONTROL_MASK", ",", "gtk", ".", "ACCEL_LOCKED", ",", ...
[ 75, 4 ]
[ 87, 40 ]
python
en
['en', 'en', 'en']
True
Notepad.destroy
(self, *args)
Overloading destroy to untoggle the Open List button.
Overloading destroy to untoggle the Open List button.
def destroy(self, *args): "Overloading destroy to untoggle the Open List button." super(Notepad, self).destroy() self.parentw.togglelist.set_active(False)
[ "def", "destroy", "(", "self", ",", "*", "args", ")", ":", "super", "(", "Notepad", ",", "self", ")", ".", "destroy", "(", ")", "self", ".", "parentw", ".", "togglelist", ".", "set_active", "(", "False", ")" ]
[ 89, 4 ]
[ 92, 49 ]
python
en
['en', 'en', 'en']
True
BlockifyUI.update
(self)
Main GUI loop, 250ms interval (self.update_interval).
Main GUI loop, 250ms interval (self.update_interval).
def update(self): "Main GUI loop, 250ms interval (self.update_interval)." # Call the main update function of blockify and assign return value # (True/False) depending on whether a song to be blocked was found. self.found = self.b.update() # Correct the automute state, if necessa...
[ "def", "update", "(", "self", ")", ":", "# Call the main update function of blockify and assign return value", "# (True/False) depending on whether a song to be blocked was found.", "self", ".", "found", "=", "self", ".", "b", ".", "update", "(", ")", "# Correct the automute st...
[ 200, 4 ]
[ 216, 19 ]
python
en
['en', 'af', 'en']
True