repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.__download_from_s3 | def __download_from_s3(self, key, dest_dir):
"""Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the spec... | python | def __download_from_s3(self, key, dest_dir):
"""Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the spec... | [
"def",
"__download_from_s3",
"(",
"self",
",",
"key",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.__download_from_s3'",
")",
"filename",
"=",
"key",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
... | Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param key: (str) S3... | [
"Private",
"method",
"for",
"downloading",
"from",
"S3"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L133-L179 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.download_file_by_key | def download_file_by_key(self, key, dest_dir):
"""Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be th... | python | def download_file_by_key(self, key, dest_dir):
"""Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be th... | [
"def",
"download_file_by_key",
"(",
"self",
",",
"key",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.download_file_by_key'",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"basestring",
")",
... | Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be the
same as it is on S3.
:param key: (str) ... | [
"Downloads",
"a",
"file",
"by",
"key",
"from",
"the",
"specified",
"S3",
"bucket"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L181-L208 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.download_file | def download_file(self, regex, dest_dir):
"""Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
... | python | def download_file(self, regex, dest_dir):
"""Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
... | [
"def",
"download_file",
"(",
"self",
",",
"regex",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.download_file'",
")",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"lo... | Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
to be the same as it is on S3.
:param reg... | [
"Downloads",
"a",
"file",
"by",
"regex",
"from",
"the",
"specified",
"S3",
"bucket"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L210-L238 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.find_key | def find_key(self, regex):
"""Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expressi... | python | def find_key(self, regex):
"""Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expressi... | [
"def",
"find_key",
"(",
"self",
",",
"regex",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.find_key'",
")",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
... | Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expression for an S3 key
:return: (str... | [
"Attempts",
"to",
"find",
"a",
"single",
"S3",
"key",
"based",
"on",
"the",
"passed",
"regex"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L240-L270 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.find_keys | def find_keys(self, regex, bucket_name=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: ... | python | def find_keys(self, regex, bucket_name=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: ... | [
"def",
"find_keys",
"(",
"self",
",",
"regex",
",",
"bucket_name",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.find_keys'",
")",
"matched_keys",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
... | Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str) Regular expression to use is the key search
... | [
"Finds",
"a",
"list",
"of",
"S3",
"keys",
"matching",
"the",
"passed",
"regex"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L272-L303 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.upload_file | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
... | python | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
... | [
"def",
"upload_file",
"(",
"self",
",",
"filepath",
",",
"key",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.upload_file'",
")",
"log",
".",
"info",
"(",
"'Attempting to upload file %s to S3 bucket %s as key %s...'",
... | Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
:return: True if upload is successful, Fals... | [
"Uploads",
"a",
"file",
"using",
"the",
"passed",
"S3",
"key"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L305-L341 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.delete_key | def delete_key(self, key_to_delete):
"""Deletes the specified key
:param key_to_delete:
:return:
"""
log = logging.getLogger(self.cls_logger + '.delete_key')
log.info('Attempting to delete key: {k}'.format(k=key_to_delete))
try:
self.s3client.delete_... | python | def delete_key(self, key_to_delete):
"""Deletes the specified key
:param key_to_delete:
:return:
"""
log = logging.getLogger(self.cls_logger + '.delete_key')
log.info('Attempting to delete key: {k}'.format(k=key_to_delete))
try:
self.s3client.delete_... | [
"def",
"delete_key",
"(",
"self",
",",
"key_to_delete",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.delete_key'",
")",
"log",
".",
"info",
"(",
"'Attempting to delete key: {k}'",
".",
"format",
"(",
"k",
"=",
... | Deletes the specified key
:param key_to_delete:
:return: | [
"Deletes",
"the",
"specified",
"key"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L343-L360 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | assert_branch_type | def assert_branch_type(branch_type):
# type: (str) -> None
""" Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format.
"""
branch = git.current_branch(refr... | python | def assert_branch_type(branch_type):
# type: (str) -> None
""" Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format.
"""
branch = git.current_branch(refr... | [
"def",
"assert_branch_type",
"(",
"branch_type",
")",
":",
"# type: (str) -> None",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"if",
"branch",
".",
"type",
"!=",
"branch_type",
":",
"if",
"context",
".",
"get",
"(",
"'pret... | Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format. | [
"Print",
"error",
"and",
"exit",
"if",
"the",
"current",
"branch",
"is",
"not",
"of",
"a",
"given",
"type",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L38-L58 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | assert_on_branch | def assert_on_branch(branch_name):
# type: (str) -> None
""" Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch.
"""
branch = git.current_branch(refresh=True)
if branch.name != branch_name:
... | python | def assert_on_branch(branch_name):
# type: (str) -> None
""" Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch.
"""
branch = git.current_branch(refresh=True)
if branch.name != branch_name:
... | [
"def",
"assert_on_branch",
"(",
"branch_name",
")",
":",
"# type: (str) -> None",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"if",
"branch",
".",
"name",
"!=",
"branch_name",
":",
"if",
"context",
".",
"get",
"(",
"'preten... | Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch. | [
"Print",
"error",
"and",
"exit",
"if",
"*",
"branch_name",
"*",
"is",
"not",
"the",
"current",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L61-L77 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_branch_delete | def git_branch_delete(branch_name):
# type: (str) -> None
""" Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete.
"""
if branch_name not in git.protected_branches():
log.info("Deleting branch <33>{}", branch_name)
shell.run('git branch... | python | def git_branch_delete(branch_name):
# type: (str) -> None
""" Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete.
"""
if branch_name not in git.protected_branches():
log.info("Deleting branch <33>{}", branch_name)
shell.run('git branch... | [
"def",
"git_branch_delete",
"(",
"branch_name",
")",
":",
"# type: (str) -> None",
"if",
"branch_name",
"not",
"in",
"git",
".",
"protected_branches",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Deleting branch <33>{}\"",
",",
"branch_name",
")",
"shell",
".",
"r... | Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete. | [
"Delete",
"the",
"given",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L80-L90 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_branch_rename | def git_branch_rename(new_name):
# type: (str) -> None
""" Rename the current branch
Args:
new_name (str):
New name for the current branch.
"""
curr_name = git.current_branch(refresh=True).name
if curr_name not in git.protected_branches():
log.info("Renaming branch ... | python | def git_branch_rename(new_name):
# type: (str) -> None
""" Rename the current branch
Args:
new_name (str):
New name for the current branch.
"""
curr_name = git.current_branch(refresh=True).name
if curr_name not in git.protected_branches():
log.info("Renaming branch ... | [
"def",
"git_branch_rename",
"(",
"new_name",
")",
":",
"# type: (str) -> None",
"curr_name",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
".",
"name",
"if",
"curr_name",
"not",
"in",
"git",
".",
"protected_branches",
"(",
")",
":",
"l... | Rename the current branch
Args:
new_name (str):
New name for the current branch. | [
"Rename",
"the",
"current",
"branch"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L93-L107 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_checkout | def git_checkout(branch_name, create=False):
# type: (str, bool) -> None
""" Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
... | python | def git_checkout(branch_name, create=False):
# type: (str, bool) -> None
""" Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
... | [
"def",
"git_checkout",
"(",
"branch_name",
",",
"create",
"=",
"False",
")",
":",
"# type: (str, bool) -> None",
"log",
".",
"info",
"(",
"\"Checking out <33>{}\"",
".",
"format",
"(",
"branch_name",
")",
")",
"shell",
".",
"run",
"(",
"'git checkout {} {}'",
".... | Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out. | [
"Checkout",
"or",
"create",
"a",
"given",
"branch"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L110-L122 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_merge | def git_merge(base, head, no_ff=False):
# type: (str, str, bool) -> None
""" Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
... | python | def git_merge(base, head, no_ff=False):
# type: (str, str, bool) -> None
""" Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
... | [
"def",
"git_merge",
"(",
"base",
",",
"head",
",",
"no_ff",
"=",
"False",
")",
":",
"# type: (str, str, bool) -> None",
"pretend",
"=",
"context",
".",
"get",
"(",
"'pretend'",
",",
"False",
")",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
... | Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
If set to **True** it will force git to create merge commit. If set
to *... | [
"Merge",
"*",
"head",
"*",
"into",
"*",
"base",
"*",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L137-L168 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | get_base_branch | def get_base_branch():
# type: () -> str
""" Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current bra... | python | def get_base_branch():
# type: () -> str
""" Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current bra... | [
"def",
"get_base_branch",
"(",
")",
":",
"# type: () -> str",
"base_branch",
"=",
"git",
".",
"guess_base_branch",
"(",
")",
"if",
"base_branch",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Can't guess the base branch, you have to pick one yourself:\"",
")",
"base_... | Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current branch is based on. | [
"Return",
"the",
"base",
"branch",
"for",
"the",
"current",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L178-L194 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | choose_branch | def choose_branch(exclude=None):
# type: (List[str]) -> str
""" Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branche... | python | def choose_branch(exclude=None):
# type: (List[str]) -> str
""" Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branche... | [
"def",
"choose_branch",
"(",
"exclude",
"=",
"None",
")",
":",
"# type: (List[str]) -> str",
"if",
"exclude",
"is",
"None",
":",
"master",
"=",
"conf",
".",
"get",
"(",
"'git.master_branch'",
",",
"'master'",
")",
"develop",
"=",
"conf",
".",
"get",
"(",
"... | Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branches pass an
empty array here.
Returns:
str: The n... | [
"Show",
"the",
"user",
"a",
"menu",
"to",
"pick",
"a",
"branch",
"from",
"the",
"existing",
"ones",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L197-L234 |
Varkal/chuda | chuda/decorators.py | autorun | def autorun():
'''
Call the run method of the decorated class if the current file is the main file
'''
def wrapper(cls):
import inspect
if inspect.getmodule(cls).__name__ == "__main__":
cls().run()
return cls
return wrapper | python | def autorun():
'''
Call the run method of the decorated class if the current file is the main file
'''
def wrapper(cls):
import inspect
if inspect.getmodule(cls).__name__ == "__main__":
cls().run()
return cls
return wrapper | [
"def",
"autorun",
"(",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"import",
"inspect",
"if",
"inspect",
".",
"getmodule",
"(",
"cls",
")",
".",
"__name__",
"==",
"\"__main__\"",
":",
"cls",
"(",
")",
".",
"run",
"(",
")",
"return",
"cls",
"r... | Call the run method of the decorated class if the current file is the main file | [
"Call",
"the",
"run",
"method",
"of",
"the",
"decorated",
"class",
"if",
"the",
"current",
"file",
"is",
"the",
"main",
"file"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/decorators.py#L1-L12 |
jaredLunde/vital-tools | vital/tools/lists.py | unique_list | def unique_list(seq):
""" Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | python | def unique_list(seq):
""" Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"def",
"unique_list",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen_add",
"(",
"x",
")",
")",
"]"
] | Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list | [
"Removes",
"duplicate",
"elements",
"from",
"given",
"@seq"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/lists.py#L17-L26 |
jaredLunde/vital-tools | vital/tools/lists.py | flatten | def flatten(*seqs):
""" Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
..
"""
for seq in seqs:
... | python | def flatten(*seqs):
""" Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
..
"""
for seq in seqs:
... | [
"def",
"flatten",
"(",
"*",
"seqs",
")",
":",
"for",
"seq",
"in",
"seqs",
":",
"for",
"item",
"in",
"seq",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"tuple",
",",
"list",
",",
"UserList",
")",
")",
":",
"for",
"subitem",
"in",
"flatten",
"(... | Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
.. | [
"Flattens",
"a",
"sequence",
"e",
".",
"g",
".",
"|",
"[",
"(",
"1",
"2",
")",
"(",
"3",
"(",
"4",
"5",
"))",
"]",
"-",
">",
"[",
"1",
"2",
"3",
"4",
"5",
"]",
"|"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/lists.py#L59-L78 |
jaredLunde/vital-tools | vital/tools/lists.py | randrange | def randrange(seq):
""" Yields random values from @seq until @seq is empty """
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y | python | def randrange(seq):
""" Yields random values from @seq until @seq is empty """
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y | [
"def",
"randrange",
"(",
"seq",
")",
":",
"seq",
"=",
"seq",
".",
"copy",
"(",
")",
"choose",
"=",
"rng",
"(",
")",
".",
"choice",
"remove",
"=",
"seq",
".",
"remove",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"seq",
")",
")",
":",
"y",
"="... | Yields random values from @seq until @seq is empty | [
"Yields",
"random",
"values",
"from"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/lists.py#L91-L99 |
Vital-Fernandez/dazer | bin/lib/ssp_functions/ssp_Hector_Fit3D_tools.py | linear_least_squares | def linear_least_squares(a, b, residuals=False):
"""
Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number... | python | def linear_least_squares(a, b, residuals=False):
"""
Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number... | [
"def",
"linear_least_squares",
"(",
"a",
",",
"b",
",",
"residuals",
"=",
"False",
")",
":",
"# Copyright (c) 2013 Alexandre Drouin. All rights reserved.",
"# From https://gist.github.com/aldro61/5889795",
"from",
"warnings",
"import",
"warn",
"# from scipy.linalg.fblas impo... | Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent rows of `a` can be less than, eq... | [
"Return",
"the",
"least",
"-",
"squares",
"solution",
"to",
"a",
"linear",
"matrix",
"equation",
".",
"Solves",
"the",
"equation",
"a",
"x",
"=",
"b",
"by",
"computing",
"a",
"vector",
"x",
"that",
"minimizes",
"the",
"Euclidean",
"2",
"-",
"norm",
"||",... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/ssp_functions/ssp_Hector_Fit3D_tools.py#L14-L55 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | validate_ip_address | def validate_ip_address(ip_address):
"""Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
"""
# Validate the IP address
log = logging.getLogger(mod_logger + '.validate_ip_address')
if not isinstance(ip_address, basestring):
l... | python | def validate_ip_address(ip_address):
"""Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
"""
# Validate the IP address
log = logging.getLogger(mod_logger + '.validate_ip_address')
if not isinstance(ip_address, basestring):
l... | [
"def",
"validate_ip_address",
"(",
"ip_address",
")",
":",
"# Validate the IP address",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.validate_ip_address'",
")",
"if",
"not",
"isinstance",
"(",
"ip_address",
",",
"basestring",
")",
":",
"log"... | Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid | [
"Validate",
"the",
"ip_address"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L32-L61 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | ip_addr | def ip_addr():
"""Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address
"""
log = logging.getLogger(mod_logger + '.ip_addr')
log.debug('Running the ip addr command...')
ip_addr_output = {}
command = ['ip', 'addr']
try:
ip_add... | python | def ip_addr():
"""Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address
"""
log = logging.getLogger(mod_logger + '.ip_addr')
log.debug('Running the ip addr command...')
ip_addr_output = {}
command = ['ip', 'addr']
try:
ip_add... | [
"def",
"ip_addr",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.ip_addr'",
")",
"log",
".",
"debug",
"(",
"'Running the ip addr command...'",
")",
"ip_addr_output",
"=",
"{",
"}",
"command",
"=",
"[",
"'ip'",
",",
"'add... | Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address | [
"Uses",
"the",
"ip",
"addr",
"command",
"to",
"enumerate",
"IP",
"addresses",
"by",
"device"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L64-L103 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | alias_ip_address | def alias_ip_address(ip_address, interface, aws=False):
"""Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, i... | python | def alias_ip_address(ip_address, interface, aws=False):
"""Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, i... | [
"def",
"alias_ip_address",
"(",
"ip_address",
",",
"interface",
",",
"aws",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.alias_ip_address'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"ip_address",
",... | Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, if
an int is provided assumes the device name is eth<i>
... | [
"Adds",
"an",
"IP",
"alias",
"to",
"a",
"specific",
"interface"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L106-L263 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | set_source_ip_for_interface | def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0):
"""Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet... | python | def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0):
"""Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet... | [
"def",
"set_source_ip_for_interface",
"(",
"source_ip_address",
",",
"desired_source_ip_address",
",",
"device_num",
"=",
"0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.set_source_ip_for_interface'",
")",
"if",
"not",
"isinstance",
... | Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets
:param device_num: (int) Integer interface device number to configure
:return: None
:r... | [
"Configures",
"the",
"source",
"IP",
"address",
"for",
"a",
"Linux",
"interface"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L266-L328 |
ktsstudio/tornkts | tornkts/handlers/object_handler.py | ObjectHandler.save_logic | def save_logic(self, some_object):
"""
Перед сохранением в методе save вызывается этот метод
:param some_object: сохраненный объект
"""
some_object.validate_model()
some_object.save()
self.send_success_response(data=some_object.to_dict()) | python | def save_logic(self, some_object):
"""
Перед сохранением в методе save вызывается этот метод
:param some_object: сохраненный объект
"""
some_object.validate_model()
some_object.save()
self.send_success_response(data=some_object.to_dict()) | [
"def",
"save_logic",
"(",
"self",
",",
"some_object",
")",
":",
"some_object",
".",
"validate_model",
"(",
")",
"some_object",
".",
"save",
"(",
")",
"self",
".",
"send_success_response",
"(",
"data",
"=",
"some_object",
".",
"to_dict",
"(",
")",
")"
] | Перед сохранением в методе save вызывается этот метод
:param some_object: сохраненный объект | [
"Перед",
"сохранением",
"в",
"методе",
"save",
"вызывается",
"этот",
"метод",
":",
"param",
"some_object",
":",
"сохраненный",
"объект"
] | train | https://github.com/ktsstudio/tornkts/blob/db47e4550426282960a7e4486dcc4399c8d52e02/tornkts/handlers/object_handler.py#L80-L87 |
novopl/peltak | src/peltak/core/shell.py | fmt | def fmt(msg, *args, **kw):
# type: (str, *Any, **Any) -> str
""" Generate shell color opcodes from a pretty coloring syntax. """
global is_tty
if len(args) or len(kw):
msg = msg.format(*args, **kw)
opcode_subst = '\x1b[\\1m' if is_tty else ''
return re.sub(r'<(\d{1,2})>', opcode_subst,... | python | def fmt(msg, *args, **kw):
# type: (str, *Any, **Any) -> str
""" Generate shell color opcodes from a pretty coloring syntax. """
global is_tty
if len(args) or len(kw):
msg = msg.format(*args, **kw)
opcode_subst = '\x1b[\\1m' if is_tty else ''
return re.sub(r'<(\d{1,2})>', opcode_subst,... | [
"def",
"fmt",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# type: (str, *Any, **Any) -> str",
"global",
"is_tty",
"if",
"len",
"(",
"args",
")",
"or",
"len",
"(",
"kw",
")",
":",
"msg",
"=",
"msg",
".",
"format",
"(",
"*",
"args",... | Generate shell color opcodes from a pretty coloring syntax. | [
"Generate",
"shell",
"color",
"opcodes",
"from",
"a",
"pretty",
"coloring",
"syntax",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L55-L64 |
novopl/peltak | src/peltak/core/shell.py | cprint | def cprint(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Print colored message to stdout. """
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(msg))) | python | def cprint(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Print colored message to stdout. """
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(msg))) | [
"def",
"cprint",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# type: (str, *Any, **Any) -> None",
"if",
"len",
"(",
"args",
")",
"or",
"len",
"(",
"kw",
")",
":",
"msg",
"=",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*"... | Print colored message to stdout. | [
"Print",
"colored",
"message",
"to",
"stdout",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L67-L73 |
novopl/peltak | src/peltak/core/shell.py | run | def run(cmd,
capture=False,
shell=True,
env=None,
exit_on_error=None,
never_pretend=False):
# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult
""" Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):... | python | def run(cmd,
capture=False,
shell=True,
env=None,
exit_on_error=None,
never_pretend=False):
# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult
""" Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):... | [
"def",
"run",
"(",
"cmd",
",",
"capture",
"=",
"False",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"None",
",",
"exit_on_error",
"=",
"None",
",",
"never_pretend",
"=",
"False",
")",
":",
"# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult",
"if",
... | Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):
Same as in `subprocess.Popen`.
capture (bool):
If set to True, it will capture the standard input/error instead of
just piping it to the caller stdout/stderr.
... | [
"Run",
"a",
"shell",
"command",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L76-L164 |
bitesofcode/pyramid_restful | pyramid_restful/utils.py | get_payload | def get_payload(request):
"""
Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-valu... | python | def get_payload(request):
"""
Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-valu... | [
"def",
"get_payload",
"(",
"request",
")",
":",
"# always extract values from the URL",
"payload",
"=",
"dict",
"(",
"request",
".",
"params",
".",
"mixed",
"(",
")",
")",
"# provide override capability from the JSON body",
"try",
":",
"json_data",
"=",
"request",
"... | Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-value map, if it is not, then an HTTPBadRe... | [
"Extracts",
"the",
"request",
"s",
"payload",
"information",
".",
"This",
"method",
"will",
"merge",
"the",
"URL",
"parameter",
"information",
"and",
"the",
"JSON",
"body",
"of",
"the",
"request",
"together",
"to",
"generate",
"a",
"dictionary",
"of",
"key<",
... | train | https://github.com/bitesofcode/pyramid_restful/blob/0f1eccb2c61b9bd6add03b461d4e4d7901c957da/pyramid_restful/utils.py#L4-L37 |
cons3rt/pycons3rt | pycons3rt/assetmailer.py | main | def main():
"""Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This module... | python | def main():
"""Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This module... | [
"def",
"main",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.main'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'This module allows sending email messages.'",
")",
"parser",
".",
"add_arg... | Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None | [
"Handles",
"external",
"calling",
"for",
"this",
"module"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L178-L212 |
cons3rt/pycons3rt | pycons3rt/assetmailer.py | AssetMailer.send_cons3rt_agent_logs | def send_cons3rt_agent_logs(self):
"""Send the cons3rt agent log file
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
if self.cons3rt_agent_log_dir is None:
log.warn('There is not CONS3RT agent log directory on this system')
... | python | def send_cons3rt_agent_logs(self):
"""Send the cons3rt agent log file
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
if self.cons3rt_agent_log_dir is None:
log.warn('There is not CONS3RT agent log directory on this system')
... | [
"def",
"send_cons3rt_agent_logs",
"(",
"self",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.send_cons3rt_agent_logs'",
")",
"if",
"self",
".",
"cons3rt_agent_log_dir",
"is",
"None",
":",
"log",
".",
"warn",
"(",
... | Send the cons3rt agent log file
:return: | [
"Send",
"the",
"cons3rt",
"agent",
"log",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L63-L87 |
cons3rt/pycons3rt | pycons3rt/assetmailer.py | AssetMailer.send_text_file | def send_text_file(self, text_file, sender=None, recipient=None):
"""Sends an email with the contents of the provided text file
:return: None
"""
log = logging.getLogger(self.cls_logger + '.send_text_file')
if not isinstance(text_file, basestring):
msg = 'arg text_f... | python | def send_text_file(self, text_file, sender=None, recipient=None):
"""Sends an email with the contents of the provided text file
:return: None
"""
log = logging.getLogger(self.cls_logger + '.send_text_file')
if not isinstance(text_file, basestring):
msg = 'arg text_f... | [
"def",
"send_text_file",
"(",
"self",
",",
"text_file",
",",
"sender",
"=",
"None",
",",
"recipient",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.send_text_file'",
")",
"if",
"not",
"isinstance",
... | Sends an email with the contents of the provided text file
:return: None | [
"Sends",
"an",
"email",
"with",
"the",
"contents",
"of",
"the",
"provided",
"text",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L89-L175 |
kajala/django-jutil | jutil/command.py | get_date_range_by_name | def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime):
"""
:param name: yesterday, last_month
:param today: Optional current datetime. Default is now().
:param tz: Optional timezone. Default is UTC.
:return: datetime (begin, end)
"""
if today is None:
... | python | def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime):
"""
:param name: yesterday, last_month
:param today: Optional current datetime. Default is now().
:param tz: Optional timezone. Default is UTC.
:return: datetime (begin, end)
"""
if today is None:
... | [
"def",
"get_date_range_by_name",
"(",
"name",
":",
"str",
",",
"today",
":",
"datetime",
"=",
"None",
",",
"tz",
"=",
"None",
")",
"->",
"(",
"datetime",
",",
"datetime",
")",
":",
"if",
"today",
"is",
"None",
":",
"today",
"=",
"datetime",
".",
"utc... | :param name: yesterday, last_month
:param today: Optional current datetime. Default is now().
:param tz: Optional timezone. Default is UTC.
:return: datetime (begin, end) | [
":",
"param",
"name",
":",
"yesterday",
"last_month",
":",
"param",
"today",
":",
"Optional",
"current",
"datetime",
".",
"Default",
"is",
"now",
"()",
".",
":",
"param",
"tz",
":",
"Optional",
"timezone",
".",
"Default",
"is",
"UTC",
".",
":",
"return",... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/command.py#L50-L86 |
kajala/django-jutil | jutil/command.py | parse_date_range_arguments | def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list):
"""
:param options:
:param default_range: Default datetime range to return if no other selected
:return: begin, end, [(begin1,end1), (begin2,end2), ...]
"""
begin, end = get_date_range_by_nam... | python | def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list):
"""
:param options:
:param default_range: Default datetime range to return if no other selected
:return: begin, end, [(begin1,end1), (begin2,end2), ...]
"""
begin, end = get_date_range_by_nam... | [
"def",
"parse_date_range_arguments",
"(",
"options",
":",
"dict",
",",
"default_range",
"=",
"'last_month'",
")",
"->",
"(",
"datetime",
",",
"datetime",
",",
"list",
")",
":",
"begin",
",",
"end",
"=",
"get_date_range_by_name",
"(",
"default_range",
")",
"for... | :param options:
:param default_range: Default datetime range to return if no other selected
:return: begin, end, [(begin1,end1), (begin2,end2), ...] | [
":",
"param",
"options",
":",
":",
"param",
"default_range",
":",
"Default",
"datetime",
"range",
"to",
"return",
"if",
"no",
"other",
"selected",
":",
"return",
":",
"begin",
"end",
"[",
"(",
"begin1",
"end1",
")",
"(",
"begin2",
"end2",
")",
"...",
"... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/command.py#L89-L123 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/Abundances_Class.py | Chemical_Analysis_pyneb.load_elements | def load_elements(self):
#Set atomic data
#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')
atomicData.setDataFile('s_iii_coll_HRS12.dat')
#Default: 's_iii_atom_PKW09.dat'
'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'
... | python | def load_elements(self):
#Set atomic data
#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')
atomicData.setDataFile('s_iii_coll_HRS12.dat')
#Default: 's_iii_atom_PKW09.dat'
'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'
... | [
"def",
"load_elements",
"(",
"self",
")",
":",
"#Set atomic data ",
"#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')",
"atomicData",
".",
"setDataFile",
"(",
"'s_iii_coll_HRS12.dat'",
")",
"#Default: 's_iii_atom_PKW09.dat' ",
"'S3: collision strengths: Tayal & Gupta 1999, ApJ, 526... | S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol. | [
"S3",
":",
"All",
"energy",
"and",
"A",
"values",
":",
"Podobedova",
"Kelleher",
"and",
"Wiese",
"2009",
"J",
".",
"Phys",
".",
"Chem",
".",
"Ref",
".",
"Data",
"Vol",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/Abundances_Class.py#L23-L87 |
cons3rt/pycons3rt | pycons3rt/pygit.py | git_clone | def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30,
git_cmd=None):
"""Clones a git url
:param url: (str) Git URL in https or ssh
:param clone_dir: (str) Path to the desired destination dir
:param branch: (str) branch to clone
:par... | python | def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30,
git_cmd=None):
"""Clones a git url
:param url: (str) Git URL in https or ssh
:param clone_dir: (str) Path to the desired destination dir
:param branch: (str) branch to clone
:par... | [
"def",
"git_clone",
"(",
"url",
",",
"clone_dir",
",",
"branch",
"=",
"'master'",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"max_retries",
"=",
"10",
",",
"retry_sec",
"=",
"30",
",",
"git_cmd",
"=",
"None",
")",
":",
"log",
"=... | Clones a git url
:param url: (str) Git URL in https or ssh
:param clone_dir: (str) Path to the desired destination dir
:param branch: (str) branch to clone
:param username: (str) username for the git repo
:param password: (str) password for the git repo
:param max_retries: (int) the number of a... | [
"Clones",
"a",
"git",
"url"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L30-L134 |
cons3rt/pycons3rt | pycons3rt/pygit.py | encode_password | def encode_password(password):
"""Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password
"""
log = logging.getLogger(mod_logger + '.password_encoder')
log.debug('Encoding password: {p}'.format(p=password))
encoded_password = ''
for ... | python | def encode_password(password):
"""Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password
"""
log = logging.getLogger(mod_logger + '.password_encoder')
log.debug('Encoding password: {p}'.format(p=password))
encoded_password = ''
for ... | [
"def",
"encode_password",
"(",
"password",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.password_encoder'",
")",
"log",
".",
"debug",
"(",
"'Encoding password: {p}'",
".",
"format",
"(",
"p",
"=",
"password",
")",
")",
"encod... | Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password | [
"Performs",
"URL",
"encoding",
"for",
"passwords"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L137-L149 |
cons3rt/pycons3rt | pycons3rt/pygit.py | encode_character | def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
... | python | def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
... | [
"def",
"encode_character",
"(",
"char",
")",
":",
"if",
"char",
"==",
"'!'",
":",
"return",
"'%21'",
"elif",
"char",
"==",
"'\"'",
":",
"return",
"'%22'",
"elif",
"char",
"==",
"'#'",
":",
"return",
"'%23'",
"elif",
"char",
"==",
"'$'",
":",
"return",
... | Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character | [
"Returns",
"URL",
"encoding",
"for",
"a",
"single",
"character"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L152-L191 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/samples/results_parser.py | search_tags_as_filters | def search_tags_as_filters(tags):
"""Get different tags as dicts ready to use as dropdown lists."""
# set dicts
actions = {}
contacts = {}
formats = {}
inspire = {}
keywords = {}
licenses = {}
md_types = dict()
owners = defaultdict(str)
srs = {}
unused = {}
# 0/1 valu... | python | def search_tags_as_filters(tags):
"""Get different tags as dicts ready to use as dropdown lists."""
# set dicts
actions = {}
contacts = {}
formats = {}
inspire = {}
keywords = {}
licenses = {}
md_types = dict()
owners = defaultdict(str)
srs = {}
unused = {}
# 0/1 valu... | [
"def",
"search_tags_as_filters",
"(",
"tags",
")",
":",
"# set dicts",
"actions",
"=",
"{",
"}",
"contacts",
"=",
"{",
"}",
"formats",
"=",
"{",
"}",
"inspire",
"=",
"{",
"}",
"keywords",
"=",
"{",
"}",
"licenses",
"=",
"{",
"}",
"md_types",
"=",
"di... | Get different tags as dicts ready to use as dropdown lists. | [
"Get",
"different",
"tags",
"as",
"dicts",
"ready",
"to",
"use",
"as",
"dropdown",
"lists",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/samples/results_parser.py#L28-L141 |
ktsstudio/tornkts | tornkts/modules/verification/verification_model.py | Verification.generate | def generate(self, verified, keygen):
"""
:param verified: телефон или email (verified_entity)
:param keygen: функция генерации ключа
:return:
"""
return Verification(
verified_entity=verified,
key=keygen(),
verified=False
) | python | def generate(self, verified, keygen):
"""
:param verified: телефон или email (verified_entity)
:param keygen: функция генерации ключа
:return:
"""
return Verification(
verified_entity=verified,
key=keygen(),
verified=False
) | [
"def",
"generate",
"(",
"self",
",",
"verified",
",",
"keygen",
")",
":",
"return",
"Verification",
"(",
"verified_entity",
"=",
"verified",
",",
"key",
"=",
"keygen",
"(",
")",
",",
"verified",
"=",
"False",
")"
] | :param verified: телефон или email (verified_entity)
:param keygen: функция генерации ключа
:return: | [
":",
"param",
"verified",
":",
"телефон",
"или",
"email",
"(",
"verified_entity",
")",
":",
"param",
"keygen",
":",
"функция",
"генерации",
"ключа",
":",
"return",
":"
] | train | https://github.com/ktsstudio/tornkts/blob/db47e4550426282960a7e4486dcc4399c8d52e02/tornkts/modules/verification/verification_model.py#L12-L22 |
kajala/django-jutil | jutil/validators.py | iban_bank_info | def iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found / unsupported country
"""
v = iban_filter(v)
if v[:2] == 'FI':
return fi_iban_bank_info(v)
else:
... | python | def iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found / unsupported country
"""
v = iban_filter(v)
if v[:2] == 'FI':
return fi_iban_bank_info(v)
else:
... | [
"def",
"iban_bank_info",
"(",
"v",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"v",
"=",
"iban_filter",
"(",
"v",
")",
"if",
"v",
"[",
":",
"2",
"]",
"==",
"'FI'",
":",
"return",
"fi_iban_bank_info",
"(",
"v",
")",
"else",
":",
"re... | Returns BIC code and bank name from IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found / unsupported country | [
"Returns",
"BIC",
"code",
"and",
"bank",
"name",
"from",
"IBAN",
"number",
".",
":",
"param",
"v",
":",
"IBAN",
"account",
"number",
":",
"return",
":",
"(",
"BIC",
"code",
"bank",
"name",
")",
"or",
"(",
")",
"if",
"not",
"found",
"/",
"unsupported"... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L116-L126 |
kajala/django-jutil | jutil/validators.py | fi_payment_reference_number | def fi_payment_reference_number(num: str):
"""
Appends Finland reference number checksum to existing number.
:param num: At least 3 digits
:return: Number plus checksum
"""
assert isinstance(num, str)
num = STRIP_WHITESPACE.sub('', num)
num = re.sub(r'^0+', '', num)
assert len(num) >... | python | def fi_payment_reference_number(num: str):
"""
Appends Finland reference number checksum to existing number.
:param num: At least 3 digits
:return: Number plus checksum
"""
assert isinstance(num, str)
num = STRIP_WHITESPACE.sub('', num)
num = re.sub(r'^0+', '', num)
assert len(num) >... | [
"def",
"fi_payment_reference_number",
"(",
"num",
":",
"str",
")",
":",
"assert",
"isinstance",
"(",
"num",
",",
"str",
")",
"num",
"=",
"STRIP_WHITESPACE",
".",
"sub",
"(",
"''",
",",
"num",
")",
"num",
"=",
"re",
".",
"sub",
"(",
"r'^0+'",
",",
"''... | Appends Finland reference number checksum to existing number.
:param num: At least 3 digits
:return: Number plus checksum | [
"Appends",
"Finland",
"reference",
"number",
"checksum",
"to",
"existing",
"number",
".",
":",
"param",
"num",
":",
"At",
"least",
"3",
"digits",
":",
"return",
":",
"Number",
"plus",
"checksum"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L154-L169 |
kajala/django-jutil | jutil/validators.py | iso_payment_reference_validator | def iso_payment_reference_validator(v: str):
"""
Validates ISO reference number checksum.
:param v: Reference number
"""
num = ''
v = STRIP_WHITESPACE.sub('', v)
for ch in v[4:] + v[0:4]:
x = ord(ch)
if ord('0') <= x <= ord('9'):
num += ch
else:
... | python | def iso_payment_reference_validator(v: str):
"""
Validates ISO reference number checksum.
:param v: Reference number
"""
num = ''
v = STRIP_WHITESPACE.sub('', v)
for ch in v[4:] + v[0:4]:
x = ord(ch)
if ord('0') <= x <= ord('9'):
num += ch
else:
... | [
"def",
"iso_payment_reference_validator",
"(",
"v",
":",
"str",
")",
":",
"num",
"=",
"''",
"v",
"=",
"STRIP_WHITESPACE",
".",
"sub",
"(",
"''",
",",
"v",
")",
"for",
"ch",
"in",
"v",
"[",
"4",
":",
"]",
"+",
"v",
"[",
"0",
":",
"4",
"]",
":",
... | Validates ISO reference number checksum.
:param v: Reference number | [
"Validates",
"ISO",
"reference",
"number",
"checksum",
".",
":",
"param",
"v",
":",
"Reference",
"number"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L178-L196 |
kajala/django-jutil | jutil/validators.py | fi_iban_bank_info | def fi_iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from FI IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found
"""
from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC
v = iban_filter(v)
... | python | def fi_iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from FI IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found
"""
from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC
v = iban_filter(v)
... | [
"def",
"fi_iban_bank_info",
"(",
"v",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"from",
"jutil",
".",
"bank_const_fi",
"import",
"FI_BIC_BY_ACCOUNT_NUMBER",
",",
"FI_BANK_NAME_BY_BIC",
"v",
"=",
"iban_filter",
"(",
"v",
")",
"bic",
"=",
"FI_... | Returns BIC code and bank name from FI IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found | [
"Returns",
"BIC",
"code",
"and",
"bank",
"name",
"from",
"FI",
"IBAN",
"number",
".",
":",
"param",
"v",
":",
"IBAN",
"account",
"number",
":",
"return",
":",
"(",
"BIC",
"code",
"bank",
"name",
")",
"or",
"(",
")",
"if",
"not",
"found"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L203-L212 |
kajala/django-jutil | jutil/validators.py | se_clearing_code_bank_info | def se_clearing_code_bank_info(clearing: str) -> (str, int):
"""
Returns Sweden bank info by clearning code.
:param clearing: 4-digit clearing code
:return: (Bank name, account digit count) or ('', None) if not found
"""
from jutil.bank_const_se import SE_BANK_CLEARING_LIST
for name, begin, ... | python | def se_clearing_code_bank_info(clearing: str) -> (str, int):
"""
Returns Sweden bank info by clearning code.
:param clearing: 4-digit clearing code
:return: (Bank name, account digit count) or ('', None) if not found
"""
from jutil.bank_const_se import SE_BANK_CLEARING_LIST
for name, begin, ... | [
"def",
"se_clearing_code_bank_info",
"(",
"clearing",
":",
"str",
")",
"->",
"(",
"str",
",",
"int",
")",
":",
"from",
"jutil",
".",
"bank_const_se",
"import",
"SE_BANK_CLEARING_LIST",
"for",
"name",
",",
"begin",
",",
"end",
",",
"acc_digits",
"in",
"SE_BAN... | Returns Sweden bank info by clearning code.
:param clearing: 4-digit clearing code
:return: (Bank name, account digit count) or ('', None) if not found | [
"Returns",
"Sweden",
"bank",
"info",
"by",
"clearning",
"code",
".",
":",
"param",
"clearing",
":",
"4",
"-",
"digit",
"clearing",
"code",
":",
"return",
":",
"(",
"Bank",
"name",
"account",
"digit",
"count",
")",
"or",
"(",
"None",
")",
"if",
"not",
... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L323-L333 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/spectrum_fitting/plot_tools.py | _histplot_bins | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | [
"def",
"_histplot_bins",
"(",
"column",
",",
"bins",
"=",
"100",
")",
":",
"col_min",
"=",
"np",
".",
"min",
"(",
"column",
")",
"col_max",
"=",
"np",
".",
"max",
"(",
"column",
")",
"return",
"range",
"(",
"col_min",
",",
"col_max",
"+",
"2",
",",... | Helper to get bins for histplot. | [
"Helper",
"to",
"get",
"bins",
"for",
"histplot",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/spectrum_fitting/plot_tools.py#L27-L31 |
jaredLunde/vital-tools | vital/tools/http.py | http_date | def http_date(value):
""" Formats the @value in required HTTP style
@value: :class:datetime.datetime, #int, #float, #str time-like object
-> #str HTTP-style formatted date
(c)2014, Marcel Hellkamp
"""
if isinstance(value, datetime.datetime):
value = value.utctimetuple()
... | python | def http_date(value):
""" Formats the @value in required HTTP style
@value: :class:datetime.datetime, #int, #float, #str time-like object
-> #str HTTP-style formatted date
(c)2014, Marcel Hellkamp
"""
if isinstance(value, datetime.datetime):
value = value.utctimetuple()
... | [
"def",
"http_date",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"value",
"=",
"value",
".",
"utctimetuple",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")... | Formats the @value in required HTTP style
@value: :class:datetime.datetime, #int, #float, #str time-like object
-> #str HTTP-style formatted date
(c)2014, Marcel Hellkamp | [
"Formats",
"the",
"@value",
"in",
"required",
"HTTP",
"style"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/http.py#L25-L40 |
jaredLunde/vital-tools | vital/tools/http.py | parse_auth | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return
(user,pass) tuple or None
(c)2014, Marcel Hellkamp
"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
data = base64.b64decode(uniorbytes(data, b... | python | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return
(user,pass) tuple or None
(c)2014, Marcel Hellkamp
"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
data = base64.b64decode(uniorbytes(data, b... | [
"def",
"parse_auth",
"(",
"header",
")",
":",
"try",
":",
"method",
",",
"data",
"=",
"header",
".",
"split",
"(",
"None",
",",
"1",
")",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'basic'",
":",
"data",
"=",
"base64",
".",
"b64decode",
"(",
... | Parse rfc2617 HTTP authentication header string (basic) and return
(user,pass) tuple or None
(c)2014, Marcel Hellkamp | [
"Parse",
"rfc2617",
"HTTP",
"authentication",
"header",
"string",
"(",
"basic",
")",
"and",
"return",
"(",
"user",
"pass",
")",
"tuple",
"or",
"None",
"(",
"c",
")",
"2014",
"Marcel",
"Hellkamp"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/http.py#L54-L66 |
azaghal/django-pydenticon | django_pydenticon/views.py | image | def image(request, data):
"""
Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already... | python | def image(request, data):
"""
Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already... | [
"def",
"image",
"(",
"request",
",",
"data",
")",
":",
"# Get image width, height, padding, and format from GET parameters, or",
"# fall-back to default values from settings.",
"try",
":",
"width",
"=",
"int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"\"w\"",
",",
... | Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already, the digest will be
used as-is.... | [
"Generates",
"identicon",
"image",
"based",
"on",
"passed",
"data",
"."
] | train | https://github.com/azaghal/django-pydenticon/blob/dd21a87693505614eb5ce1da6ff1b6146d341b2c/django_pydenticon/views.py#L14-L85 |
novopl/peltak | src/peltak/extra/gitflow/commands/hotfix.py | rename | def rename(name):
# type: (str) -> None
""" Give the currently developed hotfix a new name. """
from peltak.extra.gitflow import logic
if name is None:
name = click.prompt('Hotfix name')
logic.hotfix.rename(name) | python | def rename(name):
# type: (str) -> None
""" Give the currently developed hotfix a new name. """
from peltak.extra.gitflow import logic
if name is None:
name = click.prompt('Hotfix name')
logic.hotfix.rename(name) | [
"def",
"rename",
"(",
"name",
")",
":",
"# type: (str) -> None",
"from",
"peltak",
".",
"extra",
".",
"gitflow",
"import",
"logic",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"click",
".",
"prompt",
"(",
"'Hotfix name'",
")",
"logic",
".",
"hotfix",
"... | Give the currently developed hotfix a new name. | [
"Give",
"the",
"currently",
"developed",
"hotfix",
"a",
"new",
"name",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/commands/hotfix.py#L53-L61 |
jaredLunde/vital-tools | vital/cache/decorators.py | local_lru | def local_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
... | python | def local_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
... | [
"def",
"local_lru",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"args",
"[",
"0",
"]",
"lru_size",
"=",
"instance",
".",
"_cache_size",
"if",
"lru_siz... | Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
self._cache_size... | [
"Property",
"that",
"maps",
"to",
"a",
"key",
"in",
"a",
"local",
"dict",
"-",
"like",
"attribute",
".",
"self",
".",
"_cache",
"must",
"be",
"an",
"OrderedDict",
"self",
".",
"_cache_size",
"must",
"be",
"defined",
"as",
"LRU",
"size",
"..",
"class",
... | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L42-L74 |
jaredLunde/vital-tools | vital/cache/decorators.py | typed_lru | def typed_lru(maxsize, types=None):
""" :func:functools.lru_cache wrapper which allows you to prevent object
types outside of @types from being cached.
The main use case for this is preventing unhashable type errors when
you still want to cache some results.
..
from vita... | python | def typed_lru(maxsize, types=None):
""" :func:functools.lru_cache wrapper which allows you to prevent object
types outside of @types from being cached.
The main use case for this is preventing unhashable type errors when
you still want to cache some results.
..
from vita... | [
"def",
"typed_lru",
"(",
"maxsize",
",",
"types",
"=",
"None",
")",
":",
"types",
"=",
"types",
"or",
"collections",
".",
"Hashable",
"def",
"lru",
"(",
"obj",
")",
":",
"@",
"lru_cache",
"(",
"maxsize",
")",
"def",
"_lru_cache",
"(",
"*",
"args",
",... | :func:functools.lru_cache wrapper which allows you to prevent object
types outside of @types from being cached.
The main use case for this is preventing unhashable type errors when
you still want to cache some results.
..
from vital.cache import typed_lru
@typed... | [
":",
"func",
":",
"functools",
".",
"lru_cache",
"wrapper",
"which",
"allows",
"you",
"to",
"prevent",
"object",
"types",
"outside",
"of",
"@types",
"from",
"being",
"cached",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L77-L124 |
jaredLunde/vital-tools | vital/cache/decorators.py | local_expiring_lru | def local_expiring_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
self._cache_ttl is the expiration time in seconds
..
class Foo(object):
def __init__(self,... | python | def local_expiring_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
self._cache_ttl is the expiration time in seconds
..
class Foo(object):
def __init__(self,... | [
"def",
"local_expiring_lru",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"args",
"[",
"0",
"]",
"lru_size",
"=",
"instance",
".",
"_cache_size",
"cache_... | Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
self._cache_ttl is the expiration time in seconds
..
class Foo(object):
def __init__(self, cache_size=5000, cache_ttl=600):
... | [
"Property",
"that",
"maps",
"to",
"a",
"key",
"in",
"a",
"local",
"dict",
"-",
"like",
"attribute",
".",
"self",
".",
"_cache",
"must",
"be",
"an",
"OrderedDict",
"self",
".",
"_cache_size",
"must",
"be",
"defined",
"as",
"LRU",
"size",
"self",
".",
"_... | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L127-L172 |
novopl/peltak | src/peltak/core/context.py | GlobalContext.get | def get(self, name, *default):
# type: (str, Any) -> Any
""" Get context value with the given name and optional default.
Args:
name (str):
The name of the context value.
*default (Any):
If given and the key doesn't not exist, this will be ... | python | def get(self, name, *default):
# type: (str, Any) -> Any
""" Get context value with the given name and optional default.
Args:
name (str):
The name of the context value.
*default (Any):
If given and the key doesn't not exist, this will be ... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"*",
"default",
")",
":",
"# type: (str, Any) -> Any",
"curr",
"=",
"self",
".",
"values",
"for",
"part",
"in",
"name",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"part",
"in",
"curr",
":",
"curr",
"=",
"... | Get context value with the given name and optional default.
Args:
name (str):
The name of the context value.
*default (Any):
If given and the key doesn't not exist, this will be returned
instead. If it's not given and the context value doe... | [
"Get",
"context",
"value",
"with",
"the",
"given",
"name",
"and",
"optional",
"default",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/context.py#L57-L90 |
novopl/peltak | src/peltak/core/context.py | GlobalContext.set | def set(self, name, value):
""" Set context value.
Args:
name (str):
The name of the context value to change.
value (Any):
The new value for the selected context value
"""
curr = self.values
parts = name.split('.')
... | python | def set(self, name, value):
""" Set context value.
Args:
name (str):
The name of the context value to change.
value (Any):
The new value for the selected context value
"""
curr = self.values
parts = name.split('.')
... | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"curr",
"=",
"self",
".",
"values",
"parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
",",
"part",
"in",
"enumerate",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"... | Set context value.
Args:
name (str):
The name of the context value to change.
value (Any):
The new value for the selected context value | [
"Set",
"context",
"value",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/context.py#L92-L113 |
cons3rt/pycons3rt | pycons3rt/pyjavakeys.py | alias_exists | def alias_exists(alias, keystore_path=None, keystore_password='changeit'):
"""Checks if an alias already exists in a keystore
:param alias:
:param keystore_path:
:param keystore_password:
:return: (bool) True when the alias already exists in the keystore
:raises: OSError
"""
log = loggi... | python | def alias_exists(alias, keystore_path=None, keystore_password='changeit'):
"""Checks if an alias already exists in a keystore
:param alias:
:param keystore_path:
:param keystore_password:
:return: (bool) True when the alias already exists in the keystore
:raises: OSError
"""
log = loggi... | [
"def",
"alias_exists",
"(",
"alias",
",",
"keystore_path",
"=",
"None",
",",
"keystore_password",
"=",
"'changeit'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.alias_exists'",
")",
"if",
"not",
"isinstance",
"(",
"alias",
"... | Checks if an alias already exists in a keystore
:param alias:
:param keystore_path:
:param keystore_password:
:return: (bool) True when the alias already exists in the keystore
:raises: OSError | [
"Checks",
"if",
"an",
"alias",
"already",
"exists",
"in",
"a",
"keystore"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pyjavakeys.py#L34-L103 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | TreeNode.filter | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Define the filter function that every node must to implement.
:param query: The sqlalchemy query.
:type query: Query
:param entity: The entity model.
:type entity: type
:return: The filtered query.
... | python | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Define the filter function that every node must to implement.
:param query: The sqlalchemy query.
:type query: Query
:param entity: The entity model.
:type entity: type
:return: The filtered query.
... | [
"def",
"filter",
"(",
"self",
",",
"query",
":",
"Query",
",",
"entity",
":",
"type",
")",
"->",
"Tuple",
"[",
"Query",
",",
"Any",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'You must implement this.'",
")"
] | Define the filter function that every node must to implement.
:param query: The sqlalchemy query.
:type query: Query
:param entity: The entity model.
:type entity: type
:return: The filtered query.
:rtype: Tuple[Query, Any] | [
"Define",
"the",
"filter",
"function",
"that",
"every",
"node",
"must",
"to",
"implement",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L50-L62 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseOperationalNode._extract_relations | def _extract_relations(self, attribute: str) -> Tuple[List[str], str]:
"""Split and return the list of relation(s) and the attribute.
:param attribute:
:type attribute: str
:return: A tuple where the first element is the list of related
entities and the second is the attrib... | python | def _extract_relations(self, attribute: str) -> Tuple[List[str], str]:
"""Split and return the list of relation(s) and the attribute.
:param attribute:
:type attribute: str
:return: A tuple where the first element is the list of related
entities and the second is the attrib... | [
"def",
"_extract_relations",
"(",
"self",
",",
"attribute",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"str",
"]",
":",
"splitted",
"=",
"attribute",
".",
"split",
"(",
"self",
".",
"_attr_sep",
")",
"return",
"(",
"splitted",
... | Split and return the list of relation(s) and the attribute.
:param attribute:
:type attribute: str
:return: A tuple where the first element is the list of related
entities and the second is the attribute.
:rtype: Tuple[List[str], str] | [
"Split",
"and",
"return",
"the",
"list",
"of",
"relation",
"(",
"s",
")",
"and",
"the",
"attribute",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L104-L115 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseOperationalNode._get_relation | def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]:
"""Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the ... | python | def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]:
"""Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the ... | [
"def",
"_get_relation",
"(",
"self",
",",
"related_model",
":",
"type",
",",
"relations",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"List",
"[",
"type",
"]",
"]",
",",
"Optional",
"[",
"type",
"]",
"]",
":",
"relations_l... | Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the `_extract_relations`.
:type relations: List[str]
:return: Tuple with the list of relations (class) and the se... | [
"Transform",
"the",
"list",
"of",
"relation",
"to",
"list",
"of",
"class",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L117-L137 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseOperationalNode._join_tables | def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query:
"""Method to make the join when relation is found.
:param query: The sqlalchemy query.
:type query: Query
:param join_models: The list of joined models get from the method
`_get_relation`.
... | python | def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query:
"""Method to make the join when relation is found.
:param query: The sqlalchemy query.
:type query: Query
:param join_models: The list of joined models get from the method
`_get_relation`.
... | [
"def",
"_join_tables",
"(",
"self",
",",
"query",
":",
"Query",
",",
"join_models",
":",
"Optional",
"[",
"List",
"[",
"type",
"]",
"]",
")",
"->",
"Query",
":",
"joined_query",
"=",
"query",
"# Create the list of already joined entities",
"joined_tables",
"=",
... | Method to make the join when relation is found.
:param query: The sqlalchemy query.
:type query: Query
:param join_models: The list of joined models get from the method
`_get_relation`.
:type join_models: Optional[List[type]]
:return: The new Query with the joined ... | [
"Method",
"to",
"make",
"the",
"join",
"when",
"relation",
"is",
"found",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L139-L160 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseLogicalNode.filter | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in ... | python | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in ... | [
"def",
"filter",
"(",
"self",
",",
"query",
":",
"Query",
",",
"entity",
":",
"type",
")",
"->",
"Tuple",
"[",
"Query",
",",
"Any",
"]",
":",
"new_query",
"=",
"query",
"c_filter_list",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"_childs",
"... | Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in first place the updated query and in second
place the list of filt... | [
"Apply",
"the",
"_method",
"to",
"all",
"childs",
"of",
"the",
"node",
".",
":",
"param",
"query",
":",
"The",
"sqlachemy",
"query",
".",
":",
"type",
"query",
":",
"Query"
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L207-L228 |
kajala/django-jutil | jutil/sms.py | send_sms | def send_sms(phone: str, message: str, sender: str='', **kw):
"""
Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access.
:param phone: Phone number
:param message: Message to be esnd
:param sender: Sender (max 11 characters)
:param kw: Variable key-value pairs to be sent to SMS ... | python | def send_sms(phone: str, message: str, sender: str='', **kw):
"""
Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access.
:param phone: Phone number
:param message: Message to be esnd
:param sender: Sender (max 11 characters)
:param kw: Variable key-value pairs to be sent to SMS ... | [
"def",
"send_sms",
"(",
"phone",
":",
"str",
",",
"message",
":",
"str",
",",
"sender",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"hasattr",
"(",
"settings",
",",
"'SMS_TOKEN'",
")",
":",
"raise",
"Exception",
"(",
"'Invali... | Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access.
:param phone: Phone number
:param message: Message to be esnd
:param sender: Sender (max 11 characters)
:param kw: Variable key-value pairs to be sent to SMS API
:return: Response from requests.post | [
"Sends",
"SMS",
"via",
"Kajala",
"Group",
"SMS",
"API",
".",
"Contact",
"info"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/sms.py#L6-L32 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/samples/dev_perfs_sync_async.py | _meta_get_resource_sync | def _meta_get_resource_sync(md_uuid):
"""Just a meta func to get execution time"""
isogeo.resource(id_resource=md_uuid)
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(md_uuid, time_completed_at))
return | python | def _meta_get_resource_sync(md_uuid):
"""Just a meta func to get execution time"""
isogeo.resource(id_resource=md_uuid)
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(md_uuid, time_completed_at))
return | [
"def",
"_meta_get_resource_sync",
"(",
"md_uuid",
")",
":",
"isogeo",
".",
"resource",
"(",
"id_resource",
"=",
"md_uuid",
")",
"elapsed",
"=",
"default_timer",
"(",
")",
"-",
"START_TIME",
"time_completed_at",
"=",
"\"{:5.2f}s\"",
".",
"format",
"(",
"elapsed",... | Just a meta func to get execution time | [
"Just",
"a",
"meta",
"func",
"to",
"get",
"execution",
"time"
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/samples/dev_perfs_sync_async.py#L35-L43 |
Varkal/chuda | chuda/commands.py | Command.setup | def setup(self, app):
'''
Setup properties from parent app on the command
'''
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = sel... | python | def setup(self, app):
'''
Setup properties from parent app on the command
'''
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = sel... | [
"def",
"setup",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"logger",
"=",
"app",
".",
"logger",
"self",
".",
"shell",
".",
"logger",
"=",
"self",
".",
"logger",
"if",
"not",
"self",
".",
"command_name",
":",
"raise",
"EmptyCommandNameException",
"... | Setup properties from parent app on the command | [
"Setup",
"properties",
"from",
"parent",
"app",
"on",
"the",
"command"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/commands.py#L92-L109 |
kajala/django-jutil | jutil/middleware.py | LogExceptionMiddleware.process_exception | def process_exception(self, request, e):
"""
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
"""
from jutil.email import send_email
assert isinstance(request, Ht... | python | def process_exception(self, request, e):
"""
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
"""
from jutil.email import send_email
assert isinstance(request, Ht... | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"e",
")",
":",
"from",
"jutil",
".",
"email",
"import",
"send_email",
"assert",
"isinstance",
"(",
"request",
",",
"HttpRequest",
")",
"full_path",
"=",
"request",
".",
"get_full_path",
"(",
")",
... | Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception | [
"Logs",
"exception",
"error",
"message",
"and",
"sends",
"email",
"to",
"ADMINS",
"if",
"hostname",
"is",
"not",
"testserver",
"and",
"DEBUG",
"=",
"False",
".",
":",
"param",
"request",
":",
"HttpRequest",
":",
"param",
"e",
":",
"Exception"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/middleware.py#L47-L63 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | get_first_builder_window | def get_first_builder_window(builder):
"""Get the first toplevel widget in a Gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation.
"""
for obj in builder.get_objects():
if isinstance(obj, Gtk.Window):
#... | python | def get_first_builder_window(builder):
"""Get the first toplevel widget in a Gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation.
"""
for obj in builder.get_objects():
if isinstance(obj, Gtk.Window):
#... | [
"def",
"get_first_builder_window",
"(",
"builder",
")",
":",
"for",
"obj",
"in",
"builder",
".",
"get_objects",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Gtk",
".",
"Window",
")",
":",
"# first window",
"return",
"obj"
] | Get the first toplevel widget in a Gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation. | [
"Get",
"the",
"first",
"toplevel",
"widget",
"in",
"a",
"Gtk",
".",
"Builder",
"hierarchy",
"."
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L20-L29 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | BaseDelegate.add_slave | def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate
"""
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
'Container name must be a member of the delegate')
cont.add(slave.widget)
self.sl... | python | def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate
"""
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
'Container name must be a member of the delegate')
cont.add(slave.widget)
self.sl... | [
"def",
"add_slave",
"(",
"self",
",",
"slave",
",",
"container_name",
"=",
"\"widget\"",
")",
":",
"cont",
"=",
"getattr",
"(",
"self",
",",
"container_name",
",",
"None",
")",
"if",
"cont",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'Container na... | Add a slave delegate | [
"Add",
"a",
"slave",
"delegate"
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L103-L112 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | SlaveView.get_builder_toplevel | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The slave view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, the
first toplevel widget is discovered in the Builder file... | python | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The slave view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, the
first toplevel widget is discovered in the Builder file... | [
"def",
"get_builder_toplevel",
"(",
"self",
",",
"builder",
")",
":",
"toplevel",
"=",
"builder",
".",
"get_object",
"(",
"self",
".",
"toplevel_name",
")",
"if",
"toplevel",
"is",
"None",
":",
"toplevel",
"=",
"get_first_builder_window",
"(",
"builder",
")",
... | Get the toplevel widget from a Gtk.Builder file.
The slave view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, the
first toplevel widget is discovered in the Builder file, and it's
immediate child is used as the to... | [
"Get",
"the",
"toplevel",
"widget",
"from",
"a",
"Gtk",
".",
"Builder",
"file",
"."
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L231-L246 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | SlaveView.show_and_run | def show_and_run(self):
"""Show the main widget in a window and run the gtk loop"""
if not self._ui_ready:
self.prepare_ui()
self.display_widget = Gtk.Window()
self.display_widget.add(self.widget)
self.display_widget.show()
self.display_widget.connect('destroy... | python | def show_and_run(self):
"""Show the main widget in a window and run the gtk loop"""
if not self._ui_ready:
self.prepare_ui()
self.display_widget = Gtk.Window()
self.display_widget.add(self.widget)
self.display_widget.show()
self.display_widget.connect('destroy... | [
"def",
"show_and_run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ui_ready",
":",
"self",
".",
"prepare_ui",
"(",
")",
"self",
".",
"display_widget",
"=",
"Gtk",
".",
"Window",
"(",
")",
"self",
".",
"display_widget",
".",
"add",
"(",
"self",
... | Show the main widget in a window and run the gtk loop | [
"Show",
"the",
"main",
"widget",
"in",
"a",
"window",
"and",
"run",
"the",
"gtk",
"loop"
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L251-L259 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | ToplevelView.get_builder_toplevel | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the ... | python | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the ... | [
"def",
"get_builder_toplevel",
"(",
"self",
",",
"builder",
")",
":",
"toplevel",
"=",
"builder",
".",
"get_object",
"(",
"self",
".",
"toplevel_name",
")",
"if",
"not",
"GObject",
".",
"type_is_a",
"(",
"toplevel",
",",
"Gtk",
".",
"Window",
")",
":",
"... | Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the Gtk.Builder is
used. | [
"Get",
"the",
"toplevel",
"widget",
"from",
"a",
"Gtk",
".",
"Builder",
"file",
"."
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L265-L278 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | round_sig | def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1) | python | def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1) | [
"def",
"round_sig",
"(",
"x",
",",
"sig",
")",
":",
"return",
"round",
"(",
"x",
",",
"sig",
"-",
"int",
"(",
"floor",
"(",
"log10",
"(",
"abs",
"(",
"x",
")",
")",
")",
")",
"-",
"1",
")"
] | Round the number to the specified number of significant figures | [
"Round",
"the",
"number",
"to",
"the",
"specified",
"number",
"of",
"significant",
"figures"
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L30-L32 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | open_file | def open_file(filename, as_text=False):
"""Open the file gunzipping it if it ends with .gz.
If as_text the file is opened in text mode,
otherwise the file's opened in binary mode."""
if filename.lower().endswith('.gz'):
if as_text:
return gzip.open(filename, 'rt')
else:
... | python | def open_file(filename, as_text=False):
"""Open the file gunzipping it if it ends with .gz.
If as_text the file is opened in text mode,
otherwise the file's opened in binary mode."""
if filename.lower().endswith('.gz'):
if as_text:
return gzip.open(filename, 'rt')
else:
... | [
"def",
"open_file",
"(",
"filename",
",",
"as_text",
"=",
"False",
")",
":",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"if",
"as_text",
":",
"return",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rt'",
")",
... | Open the file gunzipping it if it ends with .gz.
If as_text the file is opened in text mode,
otherwise the file's opened in binary mode. | [
"Open",
"the",
"file",
"gunzipping",
"it",
"if",
"it",
"ends",
"with",
".",
"gz",
".",
"If",
"as_text",
"the",
"file",
"is",
"opened",
"in",
"text",
"mode",
"otherwise",
"the",
"file",
"s",
"opened",
"in",
"binary",
"mode",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L35-L48 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | create_simple_writer | def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames,
compress=True, valueClassMappings=None,
datasetMetaProps=None, fieldMetaProps=None):
"""Create a simple writer suitable for writing flat data
e.g. as BasicObject or TSV."""
if not ... | python | def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames,
compress=True, valueClassMappings=None,
datasetMetaProps=None, fieldMetaProps=None):
"""Create a simple writer suitable for writing flat data
e.g. as BasicObject or TSV."""
if not ... | [
"def",
"create_simple_writer",
"(",
"outputDef",
",",
"defaultOutput",
",",
"outputFormat",
",",
"fieldNames",
",",
"compress",
"=",
"True",
",",
"valueClassMappings",
"=",
"None",
",",
"datasetMetaProps",
"=",
"None",
",",
"fieldMetaProps",
"=",
"None",
")",
":... | Create a simple writer suitable for writing flat data
e.g. as BasicObject or TSV. | [
"Create",
"a",
"simple",
"writer",
"suitable",
"for",
"writing",
"flat",
"data",
"e",
".",
"g",
".",
"as",
"BasicObject",
"or",
"TSV",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L51-L71 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | write_squonk_datasetmetadata | def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name fo... | python | def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name fo... | [
"def",
"write_squonk_datasetmetadata",
"(",
"outputBase",
",",
"thinOutput",
",",
"valueClassMappings",
",",
"datasetMetaProps",
",",
"fieldMetaProps",
")",
":",
"meta",
"=",
"{",
"}",
"props",
"=",
"{",
"}",
"# TODO add created property - how to handle date formats?",
... | This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name for the file to write to
:param thinOutput: Write only new data, not structures. Result type will be BasicObject
... | [
"This",
"is",
"a",
"temp",
"hack",
"to",
"write",
"the",
"minimal",
"metadata",
"that",
"Squonk",
"needs",
".",
"Will",
"needs",
"to",
"be",
"replaced",
"with",
"something",
"that",
"allows",
"something",
"more",
"complete",
"to",
"be",
"written",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L90-L124 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | write_metrics | def write_metrics(baseName, values):
"""Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write
"""
m = open(baseName + '_metrics.txt', 'w')
for key in values:... | python | def write_metrics(baseName, values):
"""Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write
"""
m = open(baseName + '_metrics.txt', 'w')
for key in values:... | [
"def",
"write_metrics",
"(",
"baseName",
",",
"values",
")",
":",
"m",
"=",
"open",
"(",
"baseName",
"+",
"'_metrics.txt'",
",",
"'w'",
")",
"for",
"key",
"in",
"values",
":",
"m",
".",
"write",
"(",
"key",
"+",
"'='",
"+",
"str",
"(",
"values",
"[... | Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write | [
"Write",
"the",
"metrics",
"data"
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L127-L138 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | generate_molecule_object_dict | def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of v... | python | def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of v... | [
"def",
"generate_molecule_object_dict",
"(",
"source",
",",
"format",
",",
"values",
")",
":",
"m",
"=",
"{",
"\"uuid\"",
":",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"\"source\"",
":",
"source",
",",
"\"format\"",
":",
"format",
"}",
"if... | Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of values (properties) for the MoleculeObject | [
"Generate",
"a",
"dictionary",
"that",
"represents",
"a",
"Squonk",
"MoleculeObject",
"when",
"written",
"as",
"JSON"
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L141-L152 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | get_undecorated_calling_module | def get_undecorated_calling_module():
"""Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this ... | python | def get_undecorated_calling_module():
"""Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this ... | [
"def",
"get_undecorated_calling_module",
"(",
")",
":",
"frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
"# Return the module's file and its path",
"# and omit the exten... | Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this does not work for decorated functions. | [
"Returns",
"the",
"module",
"name",
"of",
"the",
"caller",
"s",
"calling",
"module",
".",
"If",
"a",
".",
"py",
"makes",
"a",
"call",
"to",
"b",
"()",
"in",
"b",
".",
"py",
"b",
"()",
"can",
"get",
"the",
"name",
"of",
"the",
"calling",
"module",
... | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L155-L169 |
cons3rt/pycons3rt | pycons3rt/nexus.py | query_nexus | def query_nexus(query_url, timeout_sec, basic_auth=None):
"""Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError
"""
log = logging... | python | def query_nexus(query_url, timeout_sec, basic_auth=None):
"""Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError
"""
log = logging... | [
"def",
"query_nexus",
"(",
"query_url",
",",
"timeout_sec",
",",
"basic_auth",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.query_nexus'",
")",
"# Attempt to query Nexus",
"retry_sec",
"=",
"5",
"max_retries",
"=",
... | Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError | [
"Queries",
"Nexus",
"for",
"an",
"artifact"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L39-L93 |
cons3rt/pycons3rt | pycons3rt/nexus.py | get_artifact | def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True,
username=None, password=None, **kwargs):
"""Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of t... | python | def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True,
username=None, password=None, **kwargs):
"""Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of t... | [
"def",
"get_artifact",
"(",
"suppress_status",
"=",
"False",
",",
"nexus_url",
"=",
"sample_nexus_url",
",",
"timeout_sec",
"=",
"600",
",",
"overwrite",
"=",
"True",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",... | Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of the Nexus Server
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites... | [
"Retrieves",
"an",
"artifact",
"from",
"Nexus"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L96-L299 |
cons3rt/pycons3rt | pycons3rt/nexus.py | get_artifact_nexus3 | def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None,
timeout_sec=600, overwrite=True, username=None, password=None, **kwargs):
"""Retrieves an artifact from the Nexus 3 ReST API
:param suppress_status: (bool) Set to True to suppress print... | python | def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None,
timeout_sec=600, overwrite=True, username=None, password=None, **kwargs):
"""Retrieves an artifact from the Nexus 3 ReST API
:param suppress_status: (bool) Set to True to suppress print... | [
"def",
"get_artifact_nexus3",
"(",
"suppress_status",
"=",
"False",
",",
"nexus_base_url",
"=",
"sample_nexus_base_url",
",",
"repository",
"=",
"None",
",",
"timeout_sec",
"=",
"600",
",",
"overwrite",
"=",
"True",
",",
"username",
"=",
"None",
",",
"password",... | Retrieves an artifact from the Nexus 3 ReST API
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_base_url: (str) Base URL of the Nexus Server (domain name portion only, see sample)
:param repository: (str) Repository to query (e.g. snapshots) if not provided, wil... | [
"Retrieves",
"an",
"artifact",
"from",
"the",
"Nexus",
"3",
"ReST",
"API"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L302-L553 |
cons3rt/pycons3rt | pycons3rt/nexus.py | main | def main():
"""Handles calling this module as a script
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
... | python | def main():
"""Handles calling this module as a script
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
... | [
"def",
"main",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.main'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'This Python module retrieves artifacts from Nexus.'",
")",
"parser",
".",
... | Handles calling this module as a script
:return: None | [
"Handles",
"calling",
"this",
"module",
"as",
"a",
"script"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L556-L591 |
Josef-Friedrich/phrydy | phrydy/doc.py | get_doc | def get_doc(additional_doc=False,
field_prefix='$',
field_suffix=':',
indent=4):
"""Return a formated string containing documentation about the audio
fields.
"""
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields... | python | def get_doc(additional_doc=False,
field_prefix='$',
field_suffix=':',
indent=4):
"""Return a formated string containing documentation about the audio
fields.
"""
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields... | [
"def",
"get_doc",
"(",
"additional_doc",
"=",
"False",
",",
"field_prefix",
"=",
"'$'",
",",
"field_suffix",
"=",
"':'",
",",
"indent",
"=",
"4",
")",
":",
"if",
"additional_doc",
":",
"f",
"=",
"fields",
".",
"copy",
"(",
")",
"f",
".",
"update",
"(... | Return a formated string containing documentation about the audio
fields. | [
"Return",
"a",
"formated",
"string",
"containing",
"documentation",
"about",
"the",
"audio",
"fields",
"."
] | train | https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/doc.py#L413-L440 |
novopl/peltak | src/peltak/extra/docker/client.py | RegistryClient.list_images | def list_images(self):
# type: () -> List[str]
""" List images stored in the registry.
Returns:
list[str]: List of image names.
"""
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] | python | def list_images(self):
# type: () -> List[str]
""" List images stored in the registry.
Returns:
list[str]: List of image names.
"""
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] | [
"def",
"list_images",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"r",
"=",
"self",
".",
"get",
"(",
"self",
".",
"registry_url",
"+",
"'/v2/_catalog'",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"r",
".",
"json",
"(",
")",
"[",
"'repo... | List images stored in the registry.
Returns:
list[str]: List of image names. | [
"List",
"images",
"stored",
"in",
"the",
"registry",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L53-L61 |
novopl/peltak | src/peltak/extra/docker/client.py | RegistryClient.list_tags | def list_tags(self, image_name):
# type: (str) -> Iterator[str]
""" List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be present on the
registry for this call to return any... | python | def list_tags(self, image_name):
# type: (str) -> Iterator[str]
""" List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be present on the
registry for this call to return any... | [
"def",
"list_tags",
"(",
"self",
",",
"image_name",
")",
":",
"# type: (str) -> Iterator[str]",
"tags_url",
"=",
"self",
".",
"registry_url",
"+",
"'/v2/{}/tags/list'",
"r",
"=",
"self",
".",
"get",
"(",
"tags_url",
".",
"format",
"(",
"image_name",
")",
",",
... | List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be present on the
registry for this call to return any values.
Returns:
list[str]: List of tags for that image. | [
"List",
"all",
"tags",
"for",
"the",
"given",
"image",
"stored",
"in",
"the",
"registry",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L63-L82 |
cons3rt/pycons3rt | pycons3rt/asset.py | validate_asset_structure | def validate_asset_structure(asset_dir_path):
"""Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError
"""
log = logging.getLogger(mod_logger + '.validate_asset_structure')
log.i... | python | def validate_asset_structure(asset_dir_path):
"""Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError
"""
log = logging.getLogger(mod_logger + '.validate_asset_structure')
log.i... | [
"def",
"validate_asset_structure",
"(",
"asset_dir_path",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.validate_asset_structure'",
")",
"log",
".",
"info",
"(",
"'Validating asset directory: {d}'",
".",
"format",
"(",
"d",
"=",
"as... | Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError | [
"Checks",
"asset",
"structure",
"validity"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L122-L253 |
cons3rt/pycons3rt | pycons3rt/asset.py | make_asset_zip | def make_asset_zip(asset_dir_path, destination_directory=None):
"""Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory... | python | def make_asset_zip(asset_dir_path, destination_directory=None):
"""Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory... | [
"def",
"make_asset_zip",
"(",
"asset_dir_path",
",",
"destination_directory",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.make_asset_zip'",
")",
"log",
".",
"info",
"(",
"'Attempting to create an asset zip from directory:... | Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory for
the asset
:return: (str) Path to the asset zip fil... | [
"Given",
"an",
"asset",
"directory",
"path",
"creates",
"an",
"asset",
"zip",
"file",
"in",
"the",
"provided",
"destination",
"directory"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L256-L345 |
cons3rt/pycons3rt | pycons3rt/asset.py | validate | def validate(asset_dir):
"""Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int)
"""
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
... | python | def validate(asset_dir):
"""Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int)
"""
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
... | [
"def",
"validate",
"(",
"asset_dir",
")",
":",
"try",
":",
"asset_name",
"=",
"validate_asset_structure",
"(",
"asset_dir_path",
"=",
"asset_dir",
")",
"except",
"Cons3rtAssetStructureError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",... | Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int) | [
"Command",
"line",
"call",
"to",
"validate",
"an",
"asset",
"structure"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L348-L362 |
cons3rt/pycons3rt | pycons3rt/asset.py | create | def create(asset_dir, dest_dir):
"""Command line call to create an asset zip
:param asset_dir: (full path to the asset dir)
:param dest_dir: (full path to the destination directory)
:return: (int)
"""
val = validate(asset_dir=asset_dir)
if val != 0:
return 1
try:
asset_z... | python | def create(asset_dir, dest_dir):
"""Command line call to create an asset zip
:param asset_dir: (full path to the asset dir)
:param dest_dir: (full path to the destination directory)
:return: (int)
"""
val = validate(asset_dir=asset_dir)
if val != 0:
return 1
try:
asset_z... | [
"def",
"create",
"(",
"asset_dir",
",",
"dest_dir",
")",
":",
"val",
"=",
"validate",
"(",
"asset_dir",
"=",
"asset_dir",
")",
"if",
"val",
"!=",
"0",
":",
"return",
"1",
"try",
":",
"asset_zip",
"=",
"make_asset_zip",
"(",
"asset_dir_path",
"=",
"asset_... | Command line call to create an asset zip
:param asset_dir: (full path to the asset dir)
:param dest_dir: (full path to the destination directory)
:return: (int) | [
"Command",
"line",
"call",
"to",
"create",
"an",
"asset",
"zip"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L365-L383 |
kajala/django-jutil | jutil/model.py | get_object_or_none | def get_object_or_none(cls, **kwargs):
"""
Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None
"""
from django.shortcuts import _get_queryset
qs = _get_queryset(cls)
try:
return qs.get(**kwar... | python | def get_object_or_none(cls, **kwargs):
"""
Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None
"""
from django.shortcuts import _get_queryset
qs = _get_queryset(cls)
try:
return qs.get(**kwar... | [
"def",
"get_object_or_none",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"shortcuts",
"import",
"_get_queryset",
"qs",
"=",
"_get_queryset",
"(",
"cls",
")",
"try",
":",
"return",
"qs",
".",
"get",
"(",
"*",
"*",
"kwargs",
")"... | Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None | [
"Returns",
"model",
"instance",
"or",
"None",
"if",
"not",
"found",
".",
":",
"param",
"cls",
":",
"Class",
"or",
"queryset",
":",
"param",
"kwargs",
":",
"Filters",
"for",
"get",
"()",
"call",
":",
"return",
":",
"Object",
"or",
"None"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L5-L17 |
kajala/django-jutil | jutil/model.py | get_model_field_label_and_value | def get_model_field_label_and_value(instance, field_name) -> (str, str):
"""
Returns model field label and value.
:param instance: Model instance
:param field_name: Model attribute name
:return: (label, value) tuple
"""
label = field_name
value = str(getattr(instance, field_name))
fo... | python | def get_model_field_label_and_value(instance, field_name) -> (str, str):
"""
Returns model field label and value.
:param instance: Model instance
:param field_name: Model attribute name
:return: (label, value) tuple
"""
label = field_name
value = str(getattr(instance, field_name))
fo... | [
"def",
"get_model_field_label_and_value",
"(",
"instance",
",",
"field_name",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"label",
"=",
"field_name",
"value",
"=",
"str",
"(",
"getattr",
"(",
"instance",
",",
"field_name",
")",
")",
"for",
"f",
"in",
"i... | Returns model field label and value.
:param instance: Model instance
:param field_name: Model attribute name
:return: (label, value) tuple | [
"Returns",
"model",
"field",
"label",
"and",
"value",
".",
":",
"param",
"instance",
":",
"Model",
"instance",
":",
"param",
"field_name",
":",
"Model",
"attribute",
"name",
":",
"return",
":",
"(",
"label",
"value",
")",
"tuple"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L20-L35 |
kajala/django-jutil | jutil/model.py | clone_model | def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw):
"""
Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class na... | python | def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw):
"""
Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class na... | [
"def",
"clone_model",
"(",
"instance",
",",
"cls",
",",
"commit",
":",
"bool",
"=",
"True",
",",
"exclude_fields",
":",
"tuple",
"=",
"(",
"'id'",
",",
")",
",",
"base_class_suffix",
":",
"str",
"=",
"'_ptr'",
",",
"*",
"*",
"kw",
")",
":",
"keys",
... | Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class name
:param commit: Save or not
:param exclude_fields: List of fields to exclude
:param base_class_suffix: End of name fo... | [
"Assigns",
"model",
"fields",
"to",
"new",
"object",
".",
"Ignores",
"exclude_fields",
"list",
"and",
"attributes",
"ending",
"with",
"pointer",
"suffix",
"(",
"default",
"_ptr",
")",
":",
"param",
"instance",
":",
"Instance",
"to",
"copy",
":",
"param",
"cl... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L38-L58 |
praekeltfoundation/seed-identity-store | identities/views.py | IdentitySearchList.get_queryset | def get_queryset(self):
"""
This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "foo@bar.com"}
A specia... | python | def get_queryset(self):
"""
This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "foo@bar.com"}
A specia... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"query_params",
"=",
"list",
"(",
"self",
".",
"request",
".",
"query_params",
".",
"keys",
"(",
")",
")",
"# variable that stores criteria to filter identities by",
"filter_criteria",
"=",
"{",
"}",
"# variable that sto... | This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "foo@bar.com"}
A special query paramater "include_inactive" can als... | [
"This",
"view",
"should",
"return",
"a",
"list",
"of",
"all",
"the",
"Identities",
"for",
"the",
"supplied",
"query",
"parameters",
".",
"The",
"query",
"parameters",
"should",
"be",
"in",
"the",
"form",
":",
"{",
"address_type",
":",
"address",
"}",
"e",
... | train | https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L131-L210 |
praekeltfoundation/seed-identity-store | identities/views.py | IdentityAddresses.get_queryset | def get_queryset(self):
"""
This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True
"""
identity_id = self.kwargs... | python | def get_queryset(self):
"""
This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True
"""
identity_id = self.kwargs... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"identity_id",
"=",
"self",
".",
"kwargs",
"[",
"\"identity_id\"",
"]",
"address_type",
"=",
"self",
".",
"kwargs",
"[",
"\"address_type\"",
"]",
"use_ct",
"=",
"\"use_communicate_through\"",
"in",
"self",
".",
"re... | This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True | [
"This",
"view",
"should",
"return",
"a",
"list",
"of",
"all",
"the",
"addresses",
"the",
"identity",
"has",
"for",
"the",
"supplied",
"query",
"parameters",
".",
"Currently",
"only",
"supports",
"address_type",
"and",
"default",
"params",
"Always",
"excludes",
... | train | https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L279-L299 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_internet_connection | def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool:
"""Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check
"""
try:
# see if we can reso... | python | def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool:
"""Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check
"""
try:
# see if we can reso... | [
"def",
"check_internet_connection",
"(",
"self",
",",
"remote_server",
":",
"str",
"=",
"\"api.isogeo.com\"",
")",
"->",
"bool",
":",
"try",
":",
"# see if we can resolve the host name -- tells us if there is",
"# a DNS listening",
"host",
"=",
"socket",
".",
"gethostbyna... | Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check | [
"Test",
"if",
"an",
"internet",
"connection",
"is",
"operational",
".",
"Src",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"20913928",
"/",
"2556577",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L109-L125 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_bearer_validity | def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
"""Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if neces... | python | def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
"""Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if neces... | [
"def",
"check_bearer_validity",
"(",
"self",
",",
"token",
":",
"dict",
",",
"connect_mtd",
")",
"->",
"dict",
":",
"warnings",
".",
"warn",
"(",
"\"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.\"",
",",
"DeprecationWarni... | Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
FI: 2... | [
"Check",
"API",
"Bearer",
"token",
"validity",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L127-L154 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_api_response | def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
"""
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400... | python | def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
"""
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400... | [
"def",
"check_api_response",
"(",
"self",
",",
"response",
")",
":",
"# check response",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
"elif",
"response",
".",
"status_code",
">=",
"400",
":",
"logging",
".",
"error",
"(",
"\"{}: ... | Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check | [
"Check",
"API",
"response",
"and",
"raise",
"exceptions",
"if",
"needed",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L156-L173 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_request_parameters | def check_request_parameters(self, parameters: dict = dict):
"""Check parameters passed to avoid errors and help debug.
:param dict response: search request parameters
"""
# -- SEMANTIC QUERY ---------------------------------------------------
li_args = parameters.get("q").split... | python | def check_request_parameters(self, parameters: dict = dict):
"""Check parameters passed to avoid errors and help debug.
:param dict response: search request parameters
"""
# -- SEMANTIC QUERY ---------------------------------------------------
li_args = parameters.get("q").split... | [
"def",
"check_request_parameters",
"(",
"self",
",",
"parameters",
":",
"dict",
"=",
"dict",
")",
":",
"# -- SEMANTIC QUERY ---------------------------------------------------",
"li_args",
"=",
"parameters",
".",
"get",
"(",
"\"q\"",
")",
".",
"split",
"(",
")",
"lo... | Check parameters passed to avoid errors and help debug.
:param dict response: search request parameters | [
"Check",
"parameters",
"passed",
"to",
"avoid",
"errors",
"and",
"help",
"debug",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L175-L281 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_is_uuid | def check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check
"""
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
... | python | def check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check
"""
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
... | [
"def",
"check_is_uuid",
"(",
"self",
",",
"uuid_str",
":",
"str",
")",
":",
"# check uuid type",
"if",
"not",
"isinstance",
"(",
"uuid_str",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'uuid_str' expected a str value.\"",
")",
"else",
":",
"pass",
"# h... | Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check | [
"Check",
"if",
"it",
"s",
"an",
"Isogeo",
"UUID",
"handling",
"specific",
"form",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L283-L306 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_edit_tab | def check_edit_tab(self, tab: str, md_type: str):
"""Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES
"""
... | python | def check_edit_tab(self, tab: str, md_type: str):
"""Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES
"""
... | [
"def",
"check_edit_tab",
"(",
"self",
",",
"tab",
":",
"str",
",",
"md_type",
":",
"str",
")",
":",
"# check parameters types",
"if",
"not",
"isinstance",
"(",
"tab",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'tab' expected a str value.\"",
")",
"e... | Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES | [
"Check",
"if",
"asked",
"tab",
"is",
"part",
"of",
"Isogeo",
"web",
"form",
"and",
"reliable",
"with",
"metadata",
"type",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L308-L349 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker._check_filter_specific_md | def _check_filter_specific_md(self, specific_md: list):
"""Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check
"""
if isinstance(specific_md, list):
if len(specific_md) > 0:
# checking UUIDs and poping bad... | python | def _check_filter_specific_md(self, specific_md: list):
"""Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check
"""
if isinstance(specific_md, list):
if len(specific_md) > 0:
# checking UUIDs and poping bad... | [
"def",
"_check_filter_specific_md",
"(",
"self",
",",
"specific_md",
":",
"list",
")",
":",
"if",
"isinstance",
"(",
"specific_md",
",",
"list",
")",
":",
"if",
"len",
"(",
"specific_md",
")",
">",
"0",
":",
"# checking UUIDs and poping bad ones",
"for",
"md",... | Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check | [
"Check",
"if",
"specific_md",
"parameter",
"is",
"valid",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L352-L370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.