repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
awickert/gFlex | gflex/base.py | Flexure.SAS | def SAS(self):
"""
Set-up for the rectangularly-gridded superposition of analytical solutions
method for solving flexure
"""
if self.x is None:
self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx)
if self.filename:
# Define the (scalar) elastic thickness
self.Te... | python | def SAS(self):
"""
Set-up for the rectangularly-gridded superposition of analytical solutions
method for solving flexure
"""
if self.x is None:
self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx)
if self.filename:
# Define the (scalar) elastic thickness
self.Te... | [
"def",
"SAS",
"(",
"self",
")",
":",
"if",
"self",
".",
"x",
"is",
"None",
":",
"self",
".",
"x",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"dx",
"/",
"2.",
",",
"self",
".",
"dx",
"*",
"self",
".",
"qs",
".",
"shape",
"[",
"0",
"]",
",... | Set-up for the rectangularly-gridded superposition of analytical solutions
method for solving flexure | [
"Set",
"-",
"up",
"for",
"the",
"rectangularly",
"-",
"gridded",
"superposition",
"of",
"analytical",
"solutions",
"method",
"for",
"solving",
"flexure"
] | 3ac32249375b0f8d342a142585d86ea4d905a5a0 | https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L1017-L1045 | train |
awickert/gFlex | gflex/base.py | Flexure.SAS_NG | def SAS_NG(self):
"""
Set-up for the ungridded superposition of analytical solutions
method for solving flexure
"""
if self.filename:
# Define the (scalar) elastic thickness
self.Te = self.configGet("float", "input", "ElasticThickness")
# See if it wants to be run in lat/lon
... | python | def SAS_NG(self):
"""
Set-up for the ungridded superposition of analytical solutions
method for solving flexure
"""
if self.filename:
# Define the (scalar) elastic thickness
self.Te = self.configGet("float", "input", "ElasticThickness")
# See if it wants to be run in lat/lon
... | [
"def",
"SAS_NG",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
":",
"self",
".",
"Te",
"=",
"self",
".",
"configGet",
"(",
"\"float\"",
",",
"\"input\"",
",",
"\"ElasticThickness\"",
")",
"self",
".",
"latlon",
"=",
"self",
".",
"configGet",
"(... | Set-up for the ungridded superposition of analytical solutions
method for solving flexure | [
"Set",
"-",
"up",
"for",
"the",
"ungridded",
"superposition",
"of",
"analytical",
"solutions",
"method",
"for",
"solving",
"flexure"
] | 3ac32249375b0f8d342a142585d86ea4d905a5a0 | https://github.com/awickert/gFlex/blob/3ac32249375b0f8d342a142585d86ea4d905a5a0/gflex/base.py#L1047-L1138 | train |
bionikspoon/pureyaml | pureyaml/_compat/singledispatch.py | _c3_mro | def _c3_mro(cls, abcs=None):
"""Computes the method resolution order using extended C3 linearization.
If no *abcs* are given, the algorithm works exactly like the built-in C3
linearization used for method resolution.
If given, *abcs* is a list of abstract base classes that should be inserted
into ... | python | def _c3_mro(cls, abcs=None):
"""Computes the method resolution order using extended C3 linearization.
If no *abcs* are given, the algorithm works exactly like the built-in C3
linearization used for method resolution.
If given, *abcs* is a list of abstract base classes that should be inserted
into ... | [
"def",
"_c3_mro",
"(",
"cls",
",",
"abcs",
"=",
"None",
")",
":",
"for",
"i",
",",
"base",
"in",
"enumerate",
"(",
"reversed",
"(",
"cls",
".",
"__bases__",
")",
")",
":",
"if",
"hasattr",
"(",
"base",
",",
"'__abstractmethods__'",
")",
":",
"boundar... | Computes the method resolution order using extended C3 linearization.
If no *abcs* are given, the algorithm works exactly like the built-in C3
linearization used for method resolution.
If given, *abcs* is a list of abstract base classes that should be inserted
into the resulting MRO. Unrelated ABCs ar... | [
"Computes",
"the",
"method",
"resolution",
"order",
"using",
"extended",
"C3",
"linearization",
"."
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/_compat/singledispatch.py#L49-L88 | train |
bionikspoon/pureyaml | pureyaml/_compat/singledispatch.py | singledispatch | def singledispatch(function): # noqa
"""Single-dispatch generic function decorator.
Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementa... | python | def singledispatch(function): # noqa
"""Single-dispatch generic function decorator.
Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementa... | [
"def",
"singledispatch",
"(",
"function",
")",
":",
"registry",
"=",
"{",
"}",
"dispatch_cache",
"=",
"WeakKeyDictionary",
"(",
")",
"def",
"ns",
"(",
")",
":",
"pass",
"ns",
".",
"cache_token",
"=",
"None",
"def",
"dispatch",
"(",
"cls",
")",
":",
"if... | Single-dispatch generic function decorator.
Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementations can be registered using the register() ... | [
"Single",
"-",
"dispatch",
"generic",
"function",
"decorator",
"."
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/_compat/singledispatch.py#L170-L235 | train |
MasterOdin/pylint_runner | pylint_runner/main.py | Runner._parse_args | def _parse_args(self, args):
"""Parses any supplied command-line args and provides help text. """
parser = ArgumentParser(description="Runs pylint recursively on a directory")
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_... | python | def _parse_args(self, args):
"""Parses any supplied command-line args and provides help text. """
parser = ArgumentParser(description="Runs pylint recursively on a directory")
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_... | [
"def",
"_parse_args",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Runs pylint recursively on a directory\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-v\"",
",",
"\"--verbose\"",
",",
"dest",
"=",
"\"verbose\... | Parses any supplied command-line args and provides help text. | [
"Parses",
"any",
"supplied",
"command",
"-",
"line",
"args",
"and",
"provides",
"help",
"text",
"."
] | b8ec3324e568e172d38fc0b6fa6f5551b229de07 | https://github.com/MasterOdin/pylint_runner/blob/b8ec3324e568e172d38fc0b6fa6f5551b229de07/pylint_runner/main.py#L39-L78 | train |
MasterOdin/pylint_runner | pylint_runner/main.py | Runner._parse_ignores | def _parse_ignores(self):
""" Parse the ignores setting from the pylintrc file if available. """
error_message = (
colorama.Fore.RED
+ "{} does not appear to be a valid pylintrc file".format(self.rcfile)
+ colorama.Fore.RESET
)
if not os.path.isfile(... | python | def _parse_ignores(self):
""" Parse the ignores setting from the pylintrc file if available. """
error_message = (
colorama.Fore.RED
+ "{} does not appear to be a valid pylintrc file".format(self.rcfile)
+ colorama.Fore.RESET
)
if not os.path.isfile(... | [
"def",
"_parse_ignores",
"(",
"self",
")",
":",
"error_message",
"=",
"(",
"colorama",
".",
"Fore",
".",
"RED",
"+",
"\"{} does not appear to be a valid pylintrc file\"",
".",
"format",
"(",
"self",
".",
"rcfile",
")",
"+",
"colorama",
".",
"Fore",
".",
"RESET... | Parse the ignores setting from the pylintrc file if available. | [
"Parse",
"the",
"ignores",
"setting",
"from",
"the",
"pylintrc",
"file",
"if",
"available",
"."
] | b8ec3324e568e172d38fc0b6fa6f5551b229de07 | https://github.com/MasterOdin/pylint_runner/blob/b8ec3324e568e172d38fc0b6fa6f5551b229de07/pylint_runner/main.py#L80-L104 | train |
MasterOdin/pylint_runner | pylint_runner/main.py | Runner.run | def run(self, output=None, error=None):
""" Runs pylint on all python files in the current directory """
pylint_output = output if output is not None else sys.stdout
pylint_error = error if error is not None else sys.stderr
savedout, savederr = sys.__stdout__, sys.__stderr__
sys... | python | def run(self, output=None, error=None):
""" Runs pylint on all python files in the current directory """
pylint_output = output if output is not None else sys.stdout
pylint_error = error if error is not None else sys.stderr
savedout, savederr = sys.__stdout__, sys.__stderr__
sys... | [
"def",
"run",
"(",
"self",
",",
"output",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"pylint_output",
"=",
"output",
"if",
"output",
"is",
"not",
"None",
"else",
"sys",
".",
"stdout",
"pylint_error",
"=",
"error",
"if",
"error",
"is",
"not",
"... | Runs pylint on all python files in the current directory | [
"Runs",
"pylint",
"on",
"all",
"python",
"files",
"in",
"the",
"current",
"directory"
] | b8ec3324e568e172d38fc0b6fa6f5551b229de07 | https://github.com/MasterOdin/pylint_runner/blob/b8ec3324e568e172d38fc0b6fa6f5551b229de07/pylint_runner/main.py#L145-L184 | train |
bionikspoon/pureyaml | pureyaml/grammar/utils.py | strict | def strict(*types):
"""Decorator, type check production rule output"""
def decorate(func):
@wraps(func)
def wrapper(self, p):
func(self, p)
if not isinstance(p[0], types):
raise YAMLStrictTypeError(p[0], types, func)
wrapper.co_firstlineno = func... | python | def strict(*types):
"""Decorator, type check production rule output"""
def decorate(func):
@wraps(func)
def wrapper(self, p):
func(self, p)
if not isinstance(p[0], types):
raise YAMLStrictTypeError(p[0], types, func)
wrapper.co_firstlineno = func... | [
"def",
"strict",
"(",
"*",
"types",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"p",
")",
":",
"func",
"(",
"self",
",",
"p",
")",
"if",
"not",
"isinstance",
"(",
"p",
... | Decorator, type check production rule output | [
"Decorator",
"type",
"check",
"production",
"rule",
"output"
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/grammar/utils.py#L11-L24 | train |
bionikspoon/pureyaml | pureyaml/grammar/utils.py | find_column | def find_column(t):
"""Get cursor position, based on previous newline"""
pos = t.lexer.lexpos
data = t.lexer.lexdata
last_cr = data.rfind('\n', 0, pos)
if last_cr < 0:
last_cr = -1
column = pos - last_cr
return column | python | def find_column(t):
"""Get cursor position, based on previous newline"""
pos = t.lexer.lexpos
data = t.lexer.lexdata
last_cr = data.rfind('\n', 0, pos)
if last_cr < 0:
last_cr = -1
column = pos - last_cr
return column | [
"def",
"find_column",
"(",
"t",
")",
":",
"pos",
"=",
"t",
".",
"lexer",
".",
"lexpos",
"data",
"=",
"t",
".",
"lexer",
".",
"lexdata",
"last_cr",
"=",
"data",
".",
"rfind",
"(",
"'\\n'",
",",
"0",
",",
"pos",
")",
"if",
"last_cr",
"<",
"0",
":... | Get cursor position, based on previous newline | [
"Get",
"cursor",
"position",
"based",
"on",
"previous",
"newline"
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/grammar/utils.py#L27-L35 | train |
jaraco/jaraco.windows | jaraco/windows/power.py | no_sleep | def no_sleep():
"""
Context that prevents the computer from going to sleep.
"""
mode = power.ES.continuous | power.ES.system_required
handle_nonzero_success(power.SetThreadExecutionState(mode))
try:
yield
finally:
handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous)) | python | def no_sleep():
"""
Context that prevents the computer from going to sleep.
"""
mode = power.ES.continuous | power.ES.system_required
handle_nonzero_success(power.SetThreadExecutionState(mode))
try:
yield
finally:
handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous)) | [
"def",
"no_sleep",
"(",
")",
":",
"mode",
"=",
"power",
".",
"ES",
".",
"continuous",
"|",
"power",
".",
"ES",
".",
"system_required",
"handle_nonzero_success",
"(",
"power",
".",
"SetThreadExecutionState",
"(",
"mode",
")",
")",
"try",
":",
"yield",
"fina... | Context that prevents the computer from going to sleep. | [
"Context",
"that",
"prevents",
"the",
"computer",
"from",
"going",
"to",
"sleep",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/power.py#L68-L77 | train |
theno/fabsetup | fabsetup/fabfile/setup/service/selfoss.py | selfoss | def selfoss(reset_password=False):
'''Install, update and set up selfoss.
This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx.
The connection is https-only and secured by a letsencrypt certificate. This
certificate must be created separately with task setup.server_letsencrypt.... | python | def selfoss(reset_password=False):
'''Install, update and set up selfoss.
This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx.
The connection is https-only and secured by a letsencrypt certificate. This
certificate must be created separately with task setup.server_letsencrypt.... | [
"def",
"selfoss",
"(",
"reset_password",
"=",
"False",
")",
":",
"hostname",
"=",
"re",
".",
"sub",
"(",
"r'^[^@]+@'",
",",
"''",
",",
"env",
".",
"host",
")",
"sitename",
"=",
"query_input",
"(",
"question",
"=",
"'\\nEnter site-name of Your trac web service'... | Install, update and set up selfoss.
This selfoss installation uses sqlite (selfoss-default), php5-fpm and nginx.
The connection is https-only and secured by a letsencrypt certificate. This
certificate must be created separately with task setup.server_letsencrypt.
More infos:
https://selfoss.ad... | [
"Install",
"update",
"and",
"set",
"up",
"selfoss",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/service/selfoss.py#L19-L54 | train |
NearHuscarl/py-currency | currency/cache.py | get_cache_path | def get_cache_path(filename):
""" get file path """
cwd = os.path.dirname(os.path.realpath(__file__))
return os.path.join(cwd, filename) | python | def get_cache_path(filename):
""" get file path """
cwd = os.path.dirname(os.path.realpath(__file__))
return os.path.join(cwd, filename) | [
"def",
"get_cache_path",
"(",
"filename",
")",
":",
"cwd",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"filename",
")"
] | get file path | [
"get",
"file",
"path"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/cache.py#L8-L11 | train |
jaraco/jaraco.windows | jaraco/windows/privilege.py | get_process_token | def get_process_token():
"""
Get the current process token
"""
token = wintypes.HANDLE()
res = process.OpenProcessToken(
process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token)
if not res > 0:
raise RuntimeError("Couldn't get process token")
return token | python | def get_process_token():
"""
Get the current process token
"""
token = wintypes.HANDLE()
res = process.OpenProcessToken(
process.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token)
if not res > 0:
raise RuntimeError("Couldn't get process token")
return token | [
"def",
"get_process_token",
"(",
")",
":",
"token",
"=",
"wintypes",
".",
"HANDLE",
"(",
")",
"res",
"=",
"process",
".",
"OpenProcessToken",
"(",
"process",
".",
"GetCurrentProcess",
"(",
")",
",",
"process",
".",
"TOKEN_ALL_ACCESS",
",",
"token",
")",
"i... | Get the current process token | [
"Get",
"the",
"current",
"process",
"token"
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L11-L20 | train |
jaraco/jaraco.windows | jaraco/windows/privilege.py | get_symlink_luid | def get_symlink_luid():
"""
Get the LUID for the SeCreateSymbolicLinkPrivilege
"""
symlink_luid = privilege.LUID()
res = privilege.LookupPrivilegeValue(
None, "SeCreateSymbolicLinkPrivilege", symlink_luid)
if not res > 0:
raise RuntimeError("Couldn't lookup privilege value")
return symlink_luid | python | def get_symlink_luid():
"""
Get the LUID for the SeCreateSymbolicLinkPrivilege
"""
symlink_luid = privilege.LUID()
res = privilege.LookupPrivilegeValue(
None, "SeCreateSymbolicLinkPrivilege", symlink_luid)
if not res > 0:
raise RuntimeError("Couldn't lookup privilege value")
return symlink_luid | [
"def",
"get_symlink_luid",
"(",
")",
":",
"symlink_luid",
"=",
"privilege",
".",
"LUID",
"(",
")",
"res",
"=",
"privilege",
".",
"LookupPrivilegeValue",
"(",
"None",
",",
"\"SeCreateSymbolicLinkPrivilege\"",
",",
"symlink_luid",
")",
"if",
"not",
"res",
">",
"... | Get the LUID for the SeCreateSymbolicLinkPrivilege | [
"Get",
"the",
"LUID",
"for",
"the",
"SeCreateSymbolicLinkPrivilege"
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L23-L32 | train |
jaraco/jaraco.windows | jaraco/windows/privilege.py | get_privilege_information | def get_privilege_information():
"""
Get all privileges associated with the current process.
"""
# first call with zero length to determine what size buffer we need
return_length = wintypes.DWORD()
params = [
get_process_token(),
privilege.TOKEN_INFORMATION_CLASS.TokenPrivileges,
None,
0,
return_length... | python | def get_privilege_information():
"""
Get all privileges associated with the current process.
"""
# first call with zero length to determine what size buffer we need
return_length = wintypes.DWORD()
params = [
get_process_token(),
privilege.TOKEN_INFORMATION_CLASS.TokenPrivileges,
None,
0,
return_length... | [
"def",
"get_privilege_information",
"(",
")",
":",
"return_length",
"=",
"wintypes",
".",
"DWORD",
"(",
")",
"params",
"=",
"[",
"get_process_token",
"(",
")",
",",
"privilege",
".",
"TOKEN_INFORMATION_CLASS",
".",
"TokenPrivileges",
",",
"None",
",",
"0",
","... | Get all privileges associated with the current process. | [
"Get",
"all",
"privileges",
"associated",
"with",
"the",
"current",
"process",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L35-L63 | train |
jaraco/jaraco.windows | jaraco/windows/privilege.py | enable_symlink_privilege | def enable_symlink_privilege():
"""
Try to assign the symlink privilege to the current process token.
Return True if the assignment is successful.
"""
# create a space in memory for a TOKEN_PRIVILEGES structure
# with one element
size = ctypes.sizeof(privilege.TOKEN_PRIVILEGES)
size += ctypes.sizeof(privilege.... | python | def enable_symlink_privilege():
"""
Try to assign the symlink privilege to the current process token.
Return True if the assignment is successful.
"""
# create a space in memory for a TOKEN_PRIVILEGES structure
# with one element
size = ctypes.sizeof(privilege.TOKEN_PRIVILEGES)
size += ctypes.sizeof(privilege.... | [
"def",
"enable_symlink_privilege",
"(",
")",
":",
"size",
"=",
"ctypes",
".",
"sizeof",
"(",
"privilege",
".",
"TOKEN_PRIVILEGES",
")",
"size",
"+=",
"ctypes",
".",
"sizeof",
"(",
"privilege",
".",
"LUID_AND_ATTRIBUTES",
")",
"buffer",
"=",
"ctypes",
".",
"c... | Try to assign the symlink privilege to the current process token.
Return True if the assignment is successful. | [
"Try",
"to",
"assign",
"the",
"symlink",
"privilege",
"to",
"the",
"current",
"process",
"token",
".",
"Return",
"True",
"if",
"the",
"assignment",
"is",
"successful",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L75-L95 | train |
jaraco/jaraco.windows | jaraco/windows/privilege.py | grant_symlink_privilege | def grant_symlink_privilege(who, machine=''):
"""
Grant the 'create symlink' privilege to who.
Based on http://support.microsoft.com/kb/132958
"""
flags = security.POLICY_CREATE_ACCOUNT | security.POLICY_LOOKUP_NAMES
policy = OpenPolicy(machine, flags)
return policy | python | def grant_symlink_privilege(who, machine=''):
"""
Grant the 'create symlink' privilege to who.
Based on http://support.microsoft.com/kb/132958
"""
flags = security.POLICY_CREATE_ACCOUNT | security.POLICY_LOOKUP_NAMES
policy = OpenPolicy(machine, flags)
return policy | [
"def",
"grant_symlink_privilege",
"(",
"who",
",",
"machine",
"=",
"''",
")",
":",
"flags",
"=",
"security",
".",
"POLICY_CREATE_ACCOUNT",
"|",
"security",
".",
"POLICY_LOOKUP_NAMES",
"policy",
"=",
"OpenPolicy",
"(",
"machine",
",",
"flags",
")",
"return",
"p... | Grant the 'create symlink' privilege to who.
Based on http://support.microsoft.com/kb/132958 | [
"Grant",
"the",
"create",
"symlink",
"privilege",
"to",
"who",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/privilege.py#L123-L131 | train |
theno/fabsetup | fabsetup/addons.py | add_tasks_r | def add_tasks_r(addon_module, package_module, package_name):
'''Recursively iterate through 'package_module' and add every fabric task
to the 'addon_module' keeping the task hierarchy.
Args:
addon_module(types.ModuleType)
package_module(types.ModuleType)
package_name(str): Required,... | python | def add_tasks_r(addon_module, package_module, package_name):
'''Recursively iterate through 'package_module' and add every fabric task
to the 'addon_module' keeping the task hierarchy.
Args:
addon_module(types.ModuleType)
package_module(types.ModuleType)
package_name(str): Required,... | [
"def",
"add_tasks_r",
"(",
"addon_module",
",",
"package_module",
",",
"package_name",
")",
":",
"module_dict",
"=",
"package_module",
".",
"__dict__",
"for",
"attr_name",
",",
"attr_val",
"in",
"module_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"... | Recursively iterate through 'package_module' and add every fabric task
to the 'addon_module' keeping the task hierarchy.
Args:
addon_module(types.ModuleType)
package_module(types.ModuleType)
package_name(str): Required, to avoid redundant addition of tasks
Return: None | [
"Recursively",
"iterate",
"through",
"package_module",
"and",
"add",
"every",
"fabric",
"task",
"to",
"the",
"addon_module",
"keeping",
"the",
"task",
"hierarchy",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L50-L77 | train |
theno/fabsetup | fabsetup/addons.py | load_addon | def load_addon(username, package_name, _globals):
'''Load an fabsetup addon given by 'package_name' and hook it in the
base task namespace 'username'.
Args:
username(str)
package_name(str)
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
ad... | python | def load_addon(username, package_name, _globals):
'''Load an fabsetup addon given by 'package_name' and hook it in the
base task namespace 'username'.
Args:
username(str)
package_name(str)
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
ad... | [
"def",
"load_addon",
"(",
"username",
",",
"package_name",
",",
"_globals",
")",
":",
"addon_module",
"=",
"get_or_create_module_r",
"(",
"username",
")",
"package_module",
"=",
"__import__",
"(",
"package_name",
")",
"add_tasks_r",
"(",
"addon_module",
",",
"pack... | Load an fabsetup addon given by 'package_name' and hook it in the
base task namespace 'username'.
Args:
username(str)
package_name(str)
_globals(dict): the globals() namespace of the fabric script.
Return: None | [
"Load",
"an",
"fabsetup",
"addon",
"given",
"by",
"package_name",
"and",
"hook",
"it",
"in",
"the",
"base",
"task",
"namespace",
"username",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L80-L96 | train |
theno/fabsetup | fabsetup/addons.py | load_pip_addons | def load_pip_addons(_globals):
'''Load all known fabsetup addons which are installed as pypi pip-packages.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
for package_name in known_pip_addons:
_, username = package_username(package_name)
... | python | def load_pip_addons(_globals):
'''Load all known fabsetup addons which are installed as pypi pip-packages.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
for package_name in known_pip_addons:
_, username = package_username(package_name)
... | [
"def",
"load_pip_addons",
"(",
"_globals",
")",
":",
"for",
"package_name",
"in",
"known_pip_addons",
":",
"_",
",",
"username",
"=",
"package_username",
"(",
"package_name",
")",
"try",
":",
"load_addon",
"(",
"username",
",",
"package_name",
".",
"replace",
... | Load all known fabsetup addons which are installed as pypi pip-packages.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None | [
"Load",
"all",
"known",
"fabsetup",
"addons",
"which",
"are",
"installed",
"as",
"pypi",
"pip",
"-",
"packages",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L99-L112 | train |
jaraco/jaraco.windows | jaraco/windows/lib.py | find_lib | def find_lib(lib):
r"""
Find the DLL for a given library.
Accepts a string or loaded module
>>> print(find_lib('kernel32').lower())
c:\windows\system32\kernel32.dll
"""
if isinstance(lib, str):
lib = getattr(ctypes.windll, lib)
size = 1024
result = ctypes.create_unicode_buffer(size)
library.GetModuleFile... | python | def find_lib(lib):
r"""
Find the DLL for a given library.
Accepts a string or loaded module
>>> print(find_lib('kernel32').lower())
c:\windows\system32\kernel32.dll
"""
if isinstance(lib, str):
lib = getattr(ctypes.windll, lib)
size = 1024
result = ctypes.create_unicode_buffer(size)
library.GetModuleFile... | [
"def",
"find_lib",
"(",
"lib",
")",
":",
"r",
"if",
"isinstance",
"(",
"lib",
",",
"str",
")",
":",
"lib",
"=",
"getattr",
"(",
"ctypes",
".",
"windll",
",",
"lib",
")",
"size",
"=",
"1024",
"result",
"=",
"ctypes",
".",
"create_unicode_buffer",
"(",... | r"""
Find the DLL for a given library.
Accepts a string or loaded module
>>> print(find_lib('kernel32').lower())
c:\windows\system32\kernel32.dll | [
"r",
"Find",
"the",
"DLL",
"for",
"a",
"given",
"library",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/lib.py#L6-L21 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.getScienceMetadataRDF | def getScienceMetadataRDF(self, pid):
""" Get science metadata for a resource in XML+RDF format
:param pid: The HydroShare ID of the resource
:raises: HydroShareNotAuthorized if the user is not authorized to view the metadata.
:raises: HydroShareNotFound if the resource was not found.
... | python | def getScienceMetadataRDF(self, pid):
""" Get science metadata for a resource in XML+RDF format
:param pid: The HydroShare ID of the resource
:raises: HydroShareNotAuthorized if the user is not authorized to view the metadata.
:raises: HydroShareNotFound if the resource was not found.
... | [
"def",
"getScienceMetadataRDF",
"(",
"self",
",",
"pid",
")",
":",
"url",
"=",
"\"{url_base}/scimeta/{pid}/\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",
"url_base",
",",
"pid",
"=",
"pid",
")",
"r",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",... | Get science metadata for a resource in XML+RDF format
:param pid: The HydroShare ID of the resource
:raises: HydroShareNotAuthorized if the user is not authorized to view the metadata.
:raises: HydroShareNotFound if the resource was not found.
:raises: HydroShareHTTPException to signal ... | [
"Get",
"science",
"metadata",
"for",
"a",
"resource",
"in",
"XML",
"+",
"RDF",
"format"
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L245-L358 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.getResource | def getResource(self, pid, destination=None, unzip=False, wait_for_bag_creation=True):
""" Get a resource in BagIt format
:param pid: The HydroShare ID of the resource
:param destination: String representing the directory to save bag to. Bag will be saved to file named
$(PID).zip in... | python | def getResource(self, pid, destination=None, unzip=False, wait_for_bag_creation=True):
""" Get a resource in BagIt format
:param pid: The HydroShare ID of the resource
:param destination: String representing the directory to save bag to. Bag will be saved to file named
$(PID).zip in... | [
"def",
"getResource",
"(",
"self",
",",
"pid",
",",
"destination",
"=",
"None",
",",
"unzip",
"=",
"False",
",",
"wait_for_bag_creation",
"=",
"True",
")",
":",
"stream",
"=",
"self",
".",
"_getBagStream",
"(",
"pid",
",",
"wait_for_bag_creation",
")",
"if... | Get a resource in BagIt format
:param pid: The HydroShare ID of the resource
:param destination: String representing the directory to save bag to. Bag will be saved to file named
$(PID).zip in destination; existing file of the same name will be overwritten. If None, a stream to the
... | [
"Get",
"a",
"resource",
"in",
"BagIt",
"format"
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L567-L594 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.getResourceTypes | def getResourceTypes(self):
""" Get the list of resource types supported by the HydroShare server
:return: A set of strings representing the HydroShare resource types
:raises: HydroShareHTTPException to signal an HTTP error
"""
url = "{url_base}/resource/types".format(url_base=... | python | def getResourceTypes(self):
""" Get the list of resource types supported by the HydroShare server
:return: A set of strings representing the HydroShare resource types
:raises: HydroShareHTTPException to signal an HTTP error
"""
url = "{url_base}/resource/types".format(url_base=... | [
"def",
"getResourceTypes",
"(",
"self",
")",
":",
"url",
"=",
"\"{url_base}/resource/types\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",
"url_base",
")",
"r",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"url",
")",
"if",
"r",
".",
"status_co... | Get the list of resource types supported by the HydroShare server
:return: A set of strings representing the HydroShare resource types
:raises: HydroShareHTTPException to signal an HTTP error | [
"Get",
"the",
"list",
"of",
"resource",
"types",
"supported",
"by",
"the",
"HydroShare",
"server"
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L668-L682 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.createResource | def createResource(self, resource_type, title, resource_file=None, resource_filename=None,
abstract=None, keywords=None,
edit_users=None, view_users=None, edit_groups=None, view_groups=None,
metadata=None, extra_metadata=None, progress_callback=None):... | python | def createResource(self, resource_type, title, resource_file=None, resource_filename=None,
abstract=None, keywords=None,
edit_users=None, view_users=None, edit_groups=None, view_groups=None,
metadata=None, extra_metadata=None, progress_callback=None):... | [
"def",
"createResource",
"(",
"self",
",",
"resource_type",
",",
"title",
",",
"resource_file",
"=",
"None",
",",
"resource_filename",
"=",
"None",
",",
"abstract",
"=",
"None",
",",
"keywords",
"=",
"None",
",",
"edit_users",
"=",
"None",
",",
"view_users",... | Create a new resource.
:param resource_type: string representing the a HydroShare resource type recognized by this
server.
:param title: string representing the title of the new resource
:param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a ... | [
"Create",
"a",
"new",
"resource",
"."
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L684-L773 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.setAccessRules | def setAccessRules(self, pid, public=False):
"""
Set access rules for a resource. Current only allows for setting the public or private setting.
:param pid: The HydroShare ID of the resource
:param public: True if the resource should be made public.
"""
url = "{url_base... | python | def setAccessRules(self, pid, public=False):
"""
Set access rules for a resource. Current only allows for setting the public or private setting.
:param pid: The HydroShare ID of the resource
:param public: True if the resource should be made public.
"""
url = "{url_base... | [
"def",
"setAccessRules",
"(",
"self",
",",
"pid",
",",
"public",
"=",
"False",
")",
":",
"url",
"=",
"\"{url_base}/resource/accessRules/{pid}/\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",
"url_base",
",",
"pid",
"=",
"pid",
")",
"params",
"=",
"{"... | Set access rules for a resource. Current only allows for setting the public or private setting.
:param pid: The HydroShare ID of the resource
:param public: True if the resource should be made public. | [
"Set",
"access",
"rules",
"for",
"a",
"resource",
".",
"Current",
"only",
"allows",
"for",
"setting",
"the",
"public",
"or",
"private",
"setting",
"."
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L797-L819 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.addResourceFile | def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None):
""" Add a new file to an existing resource
:param pid: The HydroShare ID of the resource
:param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string
... | python | def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None):
""" Add a new file to an existing resource
:param pid: The HydroShare ID of the resource
:param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string
... | [
"def",
"addResourceFile",
"(",
"self",
",",
"pid",
",",
"resource_file",
",",
"resource_filename",
"=",
"None",
",",
"progress_callback",
"=",
"None",
")",
":",
"url",
"=",
"\"{url_base}/resource/{pid}/files/\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",... | Add a new file to an existing resource
:param pid: The HydroShare ID of the resource
:param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string
representing path to file to be uploaded as part of the new resource
:param resource_filename: ... | [
"Add",
"a",
"new",
"file",
"to",
"an",
"existing",
"resource"
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L821-L870 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.getResourceFile | def getResourceFile(self, pid, filename, destination=None):
""" Get a file within a resource.
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to get.
:param destination: String representing the directory to save the resour... | python | def getResourceFile(self, pid, filename, destination=None):
""" Get a file within a resource.
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to get.
:param destination: String representing the directory to save the resour... | [
"def",
"getResourceFile",
"(",
"self",
",",
"pid",
",",
"filename",
",",
"destination",
"=",
"None",
")",
":",
"url",
"=",
"\"{url_base}/resource/{pid}/files/{filename}\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",
"url_base",
",",
"pid",
"=",
"pid",
... | Get a file within a resource.
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to get.
:param destination: String representing the directory to save the resource file to. If None, a stream
to the resource file will be r... | [
"Get",
"a",
"file",
"within",
"a",
"resource",
"."
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L872-L913 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.deleteResourceFile | def deleteResourceFile(self, pid, filename):
"""
Delete a resource file
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to delete
:return: Dictionary containing 'resource_id' the ID of the resource from which the ... | python | def deleteResourceFile(self, pid, filename):
"""
Delete a resource file
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to delete
:return: Dictionary containing 'resource_id' the ID of the resource from which the ... | [
"def",
"deleteResourceFile",
"(",
"self",
",",
"pid",
",",
"filename",
")",
":",
"url",
"=",
"\"{url_base}/resource/{pid}/files/{filename}\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",
"url_base",
",",
"pid",
"=",
"pid",
",",
"filename",
"=",
"filename... | Delete a resource file
:param pid: The HydroShare ID of the resource
:param filename: String representing the name of the resource file to delete
:return: Dictionary containing 'resource_id' the ID of the resource from which the file was deleted, and
'file_name' the filename of the... | [
"Delete",
"a",
"resource",
"file"
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L915-L944 | train |
hydroshare/hs_restclient | hs_restclient/__init__.py | HydroShare.getResourceFileList | def getResourceFileList(self, pid):
""" Get a listing of files within a resource.
:param pid: The HydroShare ID of the resource whose resource files are to be listed.
:raises: HydroShareArgumentException if any parameters are invalid.
:raises: HydroShareNotAuthorized if user is not aut... | python | def getResourceFileList(self, pid):
""" Get a listing of files within a resource.
:param pid: The HydroShare ID of the resource whose resource files are to be listed.
:raises: HydroShareArgumentException if any parameters are invalid.
:raises: HydroShareNotAuthorized if user is not aut... | [
"def",
"getResourceFileList",
"(",
"self",
",",
"pid",
")",
":",
"url",
"=",
"\"{url_base}/resource/{pid}/files/\"",
".",
"format",
"(",
"url_base",
"=",
"self",
".",
"url_base",
",",
"pid",
"=",
"pid",
")",
"return",
"resultsListGenerator",
"(",
"self",
",",
... | Get a listing of files within a resource.
:param pid: The HydroShare ID of the resource whose resource files are to be listed.
:raises: HydroShareArgumentException if any parameters are invalid.
:raises: HydroShareNotAuthorized if user is not authorized to perform action.
:raises: Hydr... | [
"Get",
"a",
"listing",
"of",
"files",
"within",
"a",
"resource",
"."
] | 9cd106238b512e01ecd3e33425fe48c13b7f63d5 | https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L946-L994 | train |
muckamuck/stackility | stackility/utility/get_ssm_parameter.py | get_ssm_parameter | def get_ssm_parameter(parameter_name):
'''
Get the decrypted value of an SSM parameter
Args:
parameter_name - the name of the stored parameter of interest
Return:
Value if allowed and present else None
'''
try:
response = boto3.client('ssm').get_parameters(
... | python | def get_ssm_parameter(parameter_name):
'''
Get the decrypted value of an SSM parameter
Args:
parameter_name - the name of the stored parameter of interest
Return:
Value if allowed and present else None
'''
try:
response = boto3.client('ssm').get_parameters(
... | [
"def",
"get_ssm_parameter",
"(",
"parameter_name",
")",
":",
"try",
":",
"response",
"=",
"boto3",
".",
"client",
"(",
"'ssm'",
")",
".",
"get_parameters",
"(",
"Names",
"=",
"[",
"parameter_name",
"]",
",",
"WithDecryption",
"=",
"True",
")",
"return",
"r... | Get the decrypted value of an SSM parameter
Args:
parameter_name - the name of the stored parameter of interest
Return:
Value if allowed and present else None | [
"Get",
"the",
"decrypted",
"value",
"of",
"an",
"SSM",
"parameter"
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/utility/get_ssm_parameter.py#L6-L26 | train |
theno/fabsetup | fabsetup/fabfile/setup/powerline.py | powerline | def powerline():
'''Install and set up powerline for vim, bash, tmux, and i3.
It uses pip (python2) and the most up to date powerline version (trunk) from
the github repository.
More infos:
https://github.com/powerline/powerline
https://powerline.readthedocs.io/en/latest/installation.html
... | python | def powerline():
'''Install and set up powerline for vim, bash, tmux, and i3.
It uses pip (python2) and the most up to date powerline version (trunk) from
the github repository.
More infos:
https://github.com/powerline/powerline
https://powerline.readthedocs.io/en/latest/installation.html
... | [
"def",
"powerline",
"(",
")",
":",
"bindings_dir",
",",
"scripts_dir",
"=",
"install_upgrade_powerline",
"(",
")",
"set_up_powerline_fonts",
"(",
")",
"set_up_powerline_daemon",
"(",
"scripts_dir",
")",
"powerline_for_vim",
"(",
"bindings_dir",
")",
"powerline_for_bash_... | Install and set up powerline for vim, bash, tmux, and i3.
It uses pip (python2) and the most up to date powerline version (trunk) from
the github repository.
More infos:
https://github.com/powerline/powerline
https://powerline.readthedocs.io/en/latest/installation.html
https://github.com... | [
"Install",
"and",
"set",
"up",
"powerline",
"for",
"vim",
"bash",
"tmux",
"and",
"i3",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/powerline.py#L16-L36 | train |
marcuswhybrow/django-lineage | lineage/templatetags/lineage.py | ifancestor | def ifancestor(parser, token):
"""
Returns the contents of the tag if the provided path consitutes the
base of the current pages path.
There are two ways to provide arguments to this tag. Firstly one may
provide a single argument that starts with a forward slash. e.g.
{% ifancestor '/path/... | python | def ifancestor(parser, token):
"""
Returns the contents of the tag if the provided path consitutes the
base of the current pages path.
There are two ways to provide arguments to this tag. Firstly one may
provide a single argument that starts with a forward slash. e.g.
{% ifancestor '/path/... | [
"def",
"ifancestor",
"(",
"parser",
",",
"token",
")",
":",
"contents",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endifancestor'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
... | Returns the contents of the tag if the provided path consitutes the
base of the current pages path.
There are two ways to provide arguments to this tag. Firstly one may
provide a single argument that starts with a forward slash. e.g.
{% ifancestor '/path/to/page' %}...{% endifancestor}
{% ... | [
"Returns",
"the",
"contents",
"of",
"the",
"tag",
"if",
"the",
"provided",
"path",
"consitutes",
"the",
"base",
"of",
"the",
"current",
"pages",
"path",
"."
] | 2bd18b54f721dd39bacf5fe5e7f07e7e99b75b5e | https://github.com/marcuswhybrow/django-lineage/blob/2bd18b54f721dd39bacf5fe5e7f07e7e99b75b5e/lineage/templatetags/lineage.py#L14-L54 | train |
yahoo/serviceping | serviceping/cli.py | exit_statistics | def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
"""
Print ping exit statistics
"""
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.mi... | python | def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
"""
Print ping exit statistics
"""
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.mi... | [
"def",
"exit_statistics",
"(",
"hostname",
",",
"start_time",
",",
"count_sent",
",",
"count_received",
",",
"min_time",
",",
"avg_time",
",",
"max_time",
",",
"deviation",
")",
":",
"end_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"durati... | Print ping exit statistics | [
"Print",
"ping",
"exit",
"statistics"
] | 1f9df5ee5b3cba466426b1164262278472ba4977 | https://github.com/yahoo/serviceping/blob/1f9df5ee5b3cba466426b1164262278472ba4977/serviceping/cli.py#L23-L45 | train |
jaraco/jaraco.windows | jaraco/windows/filesystem/change.py | Notifier._filtered_walk | def _filtered_walk(path, file_filter):
"""
static method that calls os.walk, but filters out
anything that doesn't match the filter
"""
for root, dirs, files in os.walk(path):
log.debug('looking in %s', root)
log.debug('files is %s', files)
file_filter.set_root(root)
files = filter(file_filter, fi... | python | def _filtered_walk(path, file_filter):
"""
static method that calls os.walk, but filters out
anything that doesn't match the filter
"""
for root, dirs, files in os.walk(path):
log.debug('looking in %s', root)
log.debug('files is %s', files)
file_filter.set_root(root)
files = filter(file_filter, fi... | [
"def",
"_filtered_walk",
"(",
"path",
",",
"file_filter",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"'looking in %s'",
",",
"root",
")",
"log",
".",
"debug",
"(",
"... | static method that calls os.walk, but filters out
anything that doesn't match the filter | [
"static",
"method",
"that",
"calls",
"os",
".",
"walk",
"but",
"filters",
"out",
"anything",
"that",
"doesn",
"t",
"match",
"the",
"filter"
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/change.py#L171-L182 | train |
pmac/django-redirect-urls | redirect_urls/decorators.py | cache_control_expires | def cache_control_expires(num_hours):
"""
Set the appropriate Cache-Control and Expires headers for the given
number of hours.
"""
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *... | python | def cache_control_expires(num_hours):
"""
Set the appropriate Cache-Control and Expires headers for the given
number of hours.
"""
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *... | [
"def",
"cache_control_expires",
"(",
"num_hours",
")",
":",
"num_seconds",
"=",
"int",
"(",
"num_hours",
"*",
"60",
"*",
"60",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"request",
",",
"*",
"... | Set the appropriate Cache-Control and Expires headers for the given
number of hours. | [
"Set",
"the",
"appropriate",
"Cache",
"-",
"Control",
"and",
"Expires",
"headers",
"for",
"the",
"given",
"number",
"of",
"hours",
"."
] | 21495194b0b2a2bdd1013e13ec0d54d34dd7f750 | https://github.com/pmac/django-redirect-urls/blob/21495194b0b2a2bdd1013e13ec0d54d34dd7f750/redirect_urls/decorators.py#L10-L26 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility.upsert | def upsert(self):
"""
The main event of the utility. Create or update a Cloud Formation
stack. Injecting properties where needed
Args:
None
Returns:
True if the stack create/update is started successfully else
False if the start goes off in t... | python | def upsert(self):
"""
The main event of the utility. Create or update a Cloud Formation
stack. Injecting properties where needed
Args:
None
Returns:
True if the stack create/update is started successfully else
False if the start goes off in t... | [
"def",
"upsert",
"(",
"self",
")",
":",
"required_parameters",
"=",
"[",
"]",
"self",
".",
"_stackParameters",
"=",
"[",
"]",
"try",
":",
"self",
".",
"_initialize_upsert",
"(",
")",
"except",
"Exception",
":",
"return",
"False",
"try",
":",
"available_par... | The main event of the utility. Create or update a Cloud Formation
stack. Injecting properties where needed
Args:
None
Returns:
True if the stack create/update is started successfully else
False if the start goes off in the weeds.
Exits:
... | [
"The",
"main",
"event",
"of",
"the",
"utility",
".",
"Create",
"or",
"update",
"a",
"Cloud",
"Formation",
"stack",
".",
"Injecting",
"properties",
"where",
"needed"
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L89-L179 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility.list | def list(self):
"""
List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_list()
int... | python | def list(self):
"""
List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_list()
int... | [
"def",
"list",
"(",
"self",
")",
":",
"self",
".",
"_initialize_list",
"(",
")",
"interested",
"=",
"True",
"response",
"=",
"self",
".",
"_cloudFormation",
".",
"list_stacks",
"(",
")",
"print",
"(",
"'Stack(s):'",
")",
"while",
"interested",
":",
"if",
... | List the existing stacks in the indicated region
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems. | [
"List",
"the",
"existing",
"stacks",
"in",
"the",
"indicated",
"region"
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L321-L353 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility.smash | def smash(self):
"""
Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_smash()
try:
stack_name ... | python | def smash(self):
"""
Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems.
"""
self._initialize_smash()
try:
stack_name ... | [
"def",
"smash",
"(",
"self",
")",
":",
"self",
".",
"_initialize_smash",
"(",
")",
"try",
":",
"stack_name",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'environment'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'stack_name'",
",",
"None",
")",
"respon... | Smash the given stack
Args:
None
Returns:
True if True
Todo:
Figure out what could go wrong and take steps
to hanlde problems. | [
"Smash",
"the",
"given",
"stack"
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L355-L388 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility._init_boto3_clients | def _init_boto3_clients(self):
"""
The utililty requires boto3 clients to Cloud Formation and S3. Here is
where we make them.
Args:
None
Returns:
Good or Bad; True or False
"""
try:
profile = self._config.get('environment', {}... | python | def _init_boto3_clients(self):
"""
The utililty requires boto3 clients to Cloud Formation and S3. Here is
where we make them.
Args:
None
Returns:
Good or Bad; True or False
"""
try:
profile = self._config.get('environment', {}... | [
"def",
"_init_boto3_clients",
"(",
"self",
")",
":",
"try",
":",
"profile",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'environment'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'profile'",
")",
"region",
"=",
"self",
".",
"_config",
".",
"get",
"(",
... | The utililty requires boto3 clients to Cloud Formation and S3. Here is
where we make them.
Args:
None
Returns:
Good or Bad; True or False | [
"The",
"utililty",
"requires",
"boto3",
"clients",
"to",
"Cloud",
"Formation",
"and",
"S3",
".",
"Here",
"is",
"where",
"we",
"make",
"them",
"."
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L390-L417 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility._get_ssm_parameter | def _get_ssm_parameter(self, p):
"""
Get parameters from Simple Systems Manager
Args:
p - a parameter name
Returns:
a value, decrypted if needed, if successful or None if things go
sideways.
"""
try:
response = self._ssm.g... | python | def _get_ssm_parameter(self, p):
"""
Get parameters from Simple Systems Manager
Args:
p - a parameter name
Returns:
a value, decrypted if needed, if successful or None if things go
sideways.
"""
try:
response = self._ssm.g... | [
"def",
"_get_ssm_parameter",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"_ssm",
".",
"get_parameter",
"(",
"Name",
"=",
"p",
",",
"WithDecryption",
"=",
"True",
")",
"return",
"response",
".",
"get",
"(",
"'Parameter'",
... | Get parameters from Simple Systems Manager
Args:
p - a parameter name
Returns:
a value, decrypted if needed, if successful or None if things go
sideways. | [
"Get",
"parameters",
"from",
"Simple",
"Systems",
"Manager"
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L434-L451 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility._fill_parameters | def _fill_parameters(self):
"""
Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist.
"""
... | python | def _fill_parameters(self):
"""
Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist.
"""
... | [
"def",
"_fill_parameters",
"(",
"self",
")",
":",
"self",
".",
"_parameters",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'parameters'",
",",
"{",
"}",
")",
"self",
".",
"_fill_defaults",
"(",
")",
"for",
"k",
"in",
"self",
".",
"_parameters",
".",
... | Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist. | [
"Fill",
"in",
"the",
"_parameters",
"dict",
"from",
"the",
"properties",
"file",
"."
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L453-L498 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility._read_tags | def _read_tags(self):
"""
Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist.
"""
tags = self._co... | python | def _read_tags(self):
"""
Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist.
"""
tags = self._co... | [
"def",
"_read_tags",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'tags'",
",",
"{",
"}",
")",
"logging",
".",
"info",
"(",
"'Tags:'",
")",
"for",
"tag_name",
"in",
"tags",
".",
"keys",
"(",
")",
":",
"tag",
"=",
... | Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist. | [
"Fill",
"in",
"the",
"_tags",
"dict",
"from",
"the",
"tags",
"file",
"."
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L500-L528 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility._set_update | def _set_update(self):
"""
Determine if we are creating a new stack or updating and existing one.
The update member is set as you would expect at the end of this query.
Args:
None
Returns:
True
"""
try:
self._updateStack = Fal... | python | def _set_update(self):
"""
Determine if we are creating a new stack or updating and existing one.
The update member is set as you would expect at the end of this query.
Args:
None
Returns:
True
"""
try:
self._updateStack = Fal... | [
"def",
"_set_update",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_updateStack",
"=",
"False",
"stack_name",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'environment'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'stack_name'",
",",
"None",
")",
"r... | Determine if we are creating a new stack or updating and existing one.
The update member is set as you would expect at the end of this query.
Args:
None
Returns:
True | [
"Determine",
"if",
"we",
"are",
"creating",
"a",
"new",
"stack",
"or",
"updating",
"and",
"existing",
"one",
".",
"The",
"update",
"member",
"is",
"set",
"as",
"you",
"would",
"expect",
"at",
"the",
"end",
"of",
"this",
"query",
"."
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L530-L561 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility._craft_s3_keys | def _craft_s3_keys(self):
"""
We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key
... | python | def _craft_s3_keys(self):
"""
We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key
... | [
"def",
"_craft_s3_keys",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"gmtime",
"(",
")",
"stub",
"=",
"\"templates/{stack_name}/{version}\"",
".",
"format",
"(",
"stack_name",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'environment'",
",",
"{",
"}"... | We are putting stuff into S3, were supplied the bucket. Here we
craft the key of the elements we are putting up there in the
internet clouds.
Args:
None
Returns:
a tuple of teplate file key and property file key | [
"We",
"are",
"putting",
"stuff",
"into",
"S3",
"were",
"supplied",
"the",
"bucket",
".",
"Here",
"we",
"craft",
"the",
"key",
"of",
"the",
"elements",
"we",
"are",
"putting",
"up",
"there",
"in",
"the",
"internet",
"clouds",
"."
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L605-L636 | train |
muckamuck/stackility | stackility/CloudStackUtility.py | CloudStackUtility.poll_stack | def poll_stack(self):
"""
Spin in a loop while the Cloud Formation process either fails or succeeds
Args:
None
Returns:
Good or bad; True or False
"""
logging.info('polling stack status, POLL_INTERVAL={}'.format(POLL_INTERVAL))
time.sleep... | python | def poll_stack(self):
"""
Spin in a loop while the Cloud Formation process either fails or succeeds
Args:
None
Returns:
Good or bad; True or False
"""
logging.info('polling stack status, POLL_INTERVAL={}'.format(POLL_INTERVAL))
time.sleep... | [
"def",
"poll_stack",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'polling stack status, POLL_INTERVAL={}'",
".",
"format",
"(",
"POLL_INTERVAL",
")",
")",
"time",
".",
"sleep",
"(",
"POLL_INTERVAL",
")",
"completed_states",
"=",
"[",
"'CREATE_COMPLETE'",
... | Spin in a loop while the Cloud Formation process either fails or succeeds
Args:
None
Returns:
Good or bad; True or False | [
"Spin",
"in",
"a",
"loop",
"while",
"the",
"Cloud",
"Formation",
"process",
"either",
"fails",
"or",
"succeeds"
] | b1696f02661134d31b99b4dea7c0d21d09482d33 | https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L638-L680 | train |
theno/fabsetup | fabsetup/fabfile-data/presetting-fabsetup-custom/fabfile_/__init__.py | setup_desktop | def setup_desktop():
'''Run setup tasks to set up a nicely configured desktop pc.
This is highly biased on my personal preference.
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.md
'''
run('sudo apt-get u... | python | def setup_desktop():
'''Run setup tasks to set up a nicely configured desktop pc.
This is highly biased on my personal preference.
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.md
'''
run('sudo apt-get u... | [
"def",
"setup_desktop",
"(",
")",
":",
"run",
"(",
"'sudo apt-get update'",
")",
"install_packages",
"(",
"packages_desktop",
")",
"execute",
"(",
"custom",
".",
"latex",
")",
"execute",
"(",
"setup",
".",
"ripping_of_cds",
")",
"execute",
"(",
"setup",
".",
... | Run setup tasks to set up a nicely configured desktop pc.
This is highly biased on my personal preference.
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.md | [
"Run",
"setup",
"tasks",
"to",
"set",
"up",
"a",
"nicely",
"configured",
"desktop",
"pc",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile-data/presetting-fabsetup-custom/fabfile_/__init__.py#L52-L73 | train |
theno/fabsetup | fabsetup/fabfile-data/presetting-fabsetup-custom/fabfile_/__init__.py | setup_webserver | def setup_webserver():
'''Run setup tasks to set up a nicely configured webserver.
Features:
* owncloud service
* fdroid repository
* certificates via letsencrypt
* and more
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your o... | python | def setup_webserver():
'''Run setup tasks to set up a nicely configured webserver.
Features:
* owncloud service
* fdroid repository
* certificates via letsencrypt
* and more
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your o... | [
"def",
"setup_webserver",
"(",
")",
":",
"run",
"(",
"'sudo apt-get update'",
")",
"install_packages",
"(",
"packages_webserver",
")",
"execute",
"(",
"custom",
".",
"latex",
")",
"execute",
"(",
"setup",
".",
"solarized",
")",
"execute",
"(",
"setup",
".",
... | Run setup tasks to set up a nicely configured webserver.
Features:
* owncloud service
* fdroid repository
* certificates via letsencrypt
* and more
The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py
and could be customized by Your own needs. More info: README.m... | [
"Run",
"setup",
"tasks",
"to",
"set",
"up",
"a",
"nicely",
"configured",
"webserver",
"."
] | ced728abff93551ba5677e63bc1bdc0ef5ca5777 | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile-data/presetting-fabsetup-custom/fabfile_/__init__.py#L77-L101 | train |
John-Lin/snortunsock | snortunsock/snort_listener.py | start_recv | def start_recv(sockfile=None):
'''Open a server on Unix Domain Socket'''
if sockfile is not None:
SOCKFILE = sockfile
else:
# default sockfile
SOCKFILE = "/tmp/snort_alert"
if os.path.exists(SOCKFILE):
os.unlink(SOCKFILE)
unsock = socket.socket(socket.AF_UNIX, socke... | python | def start_recv(sockfile=None):
'''Open a server on Unix Domain Socket'''
if sockfile is not None:
SOCKFILE = sockfile
else:
# default sockfile
SOCKFILE = "/tmp/snort_alert"
if os.path.exists(SOCKFILE):
os.unlink(SOCKFILE)
unsock = socket.socket(socket.AF_UNIX, socke... | [
"def",
"start_recv",
"(",
"sockfile",
"=",
"None",
")",
":",
"if",
"sockfile",
"is",
"not",
"None",
":",
"SOCKFILE",
"=",
"sockfile",
"else",
":",
"SOCKFILE",
"=",
"\"/tmp/snort_alert\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"SOCKFILE",
")",
":",... | Open a server on Unix Domain Socket | [
"Open",
"a",
"server",
"on",
"Unix",
"Domain",
"Socket"
] | f0eb540d76c02b59e3899a16acafada79754dc3e | https://github.com/John-Lin/snortunsock/blob/f0eb540d76c02b59e3899a16acafada79754dc3e/snortunsock/snort_listener.py#L11-L29 | train |
bionikspoon/pureyaml | pureyaml/__init__.py | dump | def dump(obj, fp=None, indent=None, sort_keys=False, **kw):
"""
Dump object to a file like object or string.
:param obj:
:param fp: Open file like object
:param int indent: Indent size, default 2
:param bool sort_keys: Optionally sort dictionary keys.
:return: Yaml serialized data.
"""
... | python | def dump(obj, fp=None, indent=None, sort_keys=False, **kw):
"""
Dump object to a file like object or string.
:param obj:
:param fp: Open file like object
:param int indent: Indent size, default 2
:param bool sort_keys: Optionally sort dictionary keys.
:return: Yaml serialized data.
"""
... | [
"def",
"dump",
"(",
"obj",
",",
"fp",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"sort_keys",
"=",
"False",
",",
"**",
"kw",
")",
":",
"if",
"fp",
":",
"iterable",
"=",
"YAMLEncoder",
"(",
"indent",
"=",
"indent",
",",
"sort_keys",
"=",
"sort_ke... | Dump object to a file like object or string.
:param obj:
:param fp: Open file like object
:param int indent: Indent size, default 2
:param bool sort_keys: Optionally sort dictionary keys.
:return: Yaml serialized data. | [
"Dump",
"object",
"to",
"a",
"file",
"like",
"object",
"or",
"string",
"."
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/__init__.py#L28-L44 | train |
bionikspoon/pureyaml | pureyaml/__init__.py | dumps | def dumps(obj, indent=None, default=None, sort_keys=False, **kw):
"""Dump string."""
return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj) | python | def dumps(obj, indent=None, default=None, sort_keys=False, **kw):
"""Dump string."""
return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj) | [
"def",
"dumps",
"(",
"obj",
",",
"indent",
"=",
"None",
",",
"default",
"=",
"None",
",",
"sort_keys",
"=",
"False",
",",
"**",
"kw",
")",
":",
"return",
"YAMLEncoder",
"(",
"indent",
"=",
"indent",
",",
"default",
"=",
"default",
",",
"sort_keys",
"... | Dump string. | [
"Dump",
"string",
"."
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/__init__.py#L47-L49 | train |
bionikspoon/pureyaml | pureyaml/__init__.py | load | def load(s, **kwargs):
"""Load yaml file"""
try:
return loads(s, **kwargs)
except TypeError:
return loads(s.read(), **kwargs) | python | def load(s, **kwargs):
"""Load yaml file"""
try:
return loads(s, **kwargs)
except TypeError:
return loads(s.read(), **kwargs) | [
"def",
"load",
"(",
"s",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"loads",
"(",
"s",
",",
"**",
"kwargs",
")",
"except",
"TypeError",
":",
"return",
"loads",
"(",
"s",
".",
"read",
"(",
")",
",",
"**",
"kwargs",
")"
] | Load yaml file | [
"Load",
"yaml",
"file"
] | 784830b907ca14525c4cecdb6ae35306f6f8a877 | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/__init__.py#L52-L57 | train |
jaraco/jaraco.windows | jaraco/windows/api/inet.py | MIB_IPADDRROW.address | def address(self):
"The address in big-endian"
_ = struct.pack('L', self.address_num)
return struct.unpack('!L', _)[0] | python | def address(self):
"The address in big-endian"
_ = struct.pack('L', self.address_num)
return struct.unpack('!L', _)[0] | [
"def",
"address",
"(",
"self",
")",
":",
"\"The address in big-endian\"",
"_",
"=",
"struct",
".",
"pack",
"(",
"'L'",
",",
"self",
".",
"address_num",
")",
"return",
"struct",
".",
"unpack",
"(",
"'!L'",
",",
"_",
")",
"[",
"0",
"]"
] | The address in big-endian | [
"The",
"address",
"in",
"big",
"-",
"endian"
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/api/inet.py#L81-L84 | train |
NearHuscarl/py-currency | currency/currency.py | validate_currency | def validate_currency(*currencies):
""" some validation checks before doing anything """
validated_currency = []
if not currencies:
raise CurrencyException('My function need something to run, duh')
for currency in currencies:
currency = currency.upper()
if not isinstance(currency, str):
raise TypeError('Cu... | python | def validate_currency(*currencies):
""" some validation checks before doing anything """
validated_currency = []
if not currencies:
raise CurrencyException('My function need something to run, duh')
for currency in currencies:
currency = currency.upper()
if not isinstance(currency, str):
raise TypeError('Cu... | [
"def",
"validate_currency",
"(",
"*",
"currencies",
")",
":",
"validated_currency",
"=",
"[",
"]",
"if",
"not",
"currencies",
":",
"raise",
"CurrencyException",
"(",
"'My function need something to run, duh'",
")",
"for",
"currency",
"in",
"currencies",
":",
"curren... | some validation checks before doing anything | [
"some",
"validation",
"checks",
"before",
"doing",
"anything"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L35-L47 | train |
NearHuscarl/py-currency | currency/currency.py | validate_price | def validate_price(price):
""" validation checks for price argument """
if isinstance(price, str):
try:
price = int(price)
except ValueError: # fallback if convert to int failed
price = float(price)
if not isinstance(price, (int, float)):
raise TypeError('Price should be a number: ' + repr(price))
retur... | python | def validate_price(price):
""" validation checks for price argument """
if isinstance(price, str):
try:
price = int(price)
except ValueError: # fallback if convert to int failed
price = float(price)
if not isinstance(price, (int, float)):
raise TypeError('Price should be a number: ' + repr(price))
retur... | [
"def",
"validate_price",
"(",
"price",
")",
":",
"if",
"isinstance",
"(",
"price",
",",
"str",
")",
":",
"try",
":",
"price",
"=",
"int",
"(",
"price",
")",
"except",
"ValueError",
":",
"price",
"=",
"float",
"(",
"price",
")",
"if",
"not",
"isinstan... | validation checks for price argument | [
"validation",
"checks",
"for",
"price",
"argument"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L49-L58 | train |
NearHuscarl/py-currency | currency/currency.py | name | def name(currency, *, plural=False):
""" return name of currency """
currency = validate_currency(currency)
if plural:
return _currencies[currency]['name_plural']
return _currencies[currency]['name'] | python | def name(currency, *, plural=False):
""" return name of currency """
currency = validate_currency(currency)
if plural:
return _currencies[currency]['name_plural']
return _currencies[currency]['name'] | [
"def",
"name",
"(",
"currency",
",",
"*",
",",
"plural",
"=",
"False",
")",
":",
"currency",
"=",
"validate_currency",
"(",
"currency",
")",
"if",
"plural",
":",
"return",
"_currencies",
"[",
"currency",
"]",
"[",
"'name_plural'",
"]",
"return",
"_currenci... | return name of currency | [
"return",
"name",
"of",
"currency"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L70-L75 | train |
NearHuscarl/py-currency | currency/currency.py | symbol | def symbol(currency, *, native=True):
""" return symbol of currency """
currency = validate_currency(currency)
if native:
return _currencies[currency]['symbol_native']
return _currencies[currency]['symbol'] | python | def symbol(currency, *, native=True):
""" return symbol of currency """
currency = validate_currency(currency)
if native:
return _currencies[currency]['symbol_native']
return _currencies[currency]['symbol'] | [
"def",
"symbol",
"(",
"currency",
",",
"*",
",",
"native",
"=",
"True",
")",
":",
"currency",
"=",
"validate_currency",
"(",
"currency",
")",
"if",
"native",
":",
"return",
"_currencies",
"[",
"currency",
"]",
"[",
"'symbol_native'",
"]",
"return",
"_curre... | return symbol of currency | [
"return",
"symbol",
"of",
"currency"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L77-L82 | train |
NearHuscarl/py-currency | currency/currency.py | rounding | def rounding(price, currency):
""" rounding currency value based on its max decimal digits """
currency = validate_currency(currency)
price = validate_price(price)
if decimals(currency) == 0:
return round(int(price), decimals(currency))
return round(price, decimals(currency)) | python | def rounding(price, currency):
""" rounding currency value based on its max decimal digits """
currency = validate_currency(currency)
price = validate_price(price)
if decimals(currency) == 0:
return round(int(price), decimals(currency))
return round(price, decimals(currency)) | [
"def",
"rounding",
"(",
"price",
",",
"currency",
")",
":",
"currency",
"=",
"validate_currency",
"(",
"currency",
")",
"price",
"=",
"validate_price",
"(",
"price",
")",
"if",
"decimals",
"(",
"currency",
")",
"==",
"0",
":",
"return",
"round",
"(",
"in... | rounding currency value based on its max decimal digits | [
"rounding",
"currency",
"value",
"based",
"on",
"its",
"max",
"decimal",
"digits"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L94-L100 | train |
NearHuscarl/py-currency | currency/currency.py | check_update | def check_update(from_currency, to_currency):
""" check if last update is over 30 mins ago. if so return True to update, else False """
if from_currency not in ccache: # if currency never get converted before
ccache[from_currency] = {}
if ccache[from_currency].get(to_currency) is None:
ccache[from_currency][to_c... | python | def check_update(from_currency, to_currency):
""" check if last update is over 30 mins ago. if so return True to update, else False """
if from_currency not in ccache: # if currency never get converted before
ccache[from_currency] = {}
if ccache[from_currency].get(to_currency) is None:
ccache[from_currency][to_c... | [
"def",
"check_update",
"(",
"from_currency",
",",
"to_currency",
")",
":",
"if",
"from_currency",
"not",
"in",
"ccache",
":",
"ccache",
"[",
"from_currency",
"]",
"=",
"{",
"}",
"if",
"ccache",
"[",
"from_currency",
"]",
".",
"get",
"(",
"to_currency",
")"... | check if last update is over 30 mins ago. if so return True to update, else False | [
"check",
"if",
"last",
"update",
"is",
"over",
"30",
"mins",
"ago",
".",
"if",
"so",
"return",
"True",
"to",
"update",
"else",
"False"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L133-L142 | train |
NearHuscarl/py-currency | currency/currency.py | update_cache | def update_cache(from_currency, to_currency):
""" update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info """
if check_update(from_currency, to_currency) is True:
ccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currenc... | python | def update_cache(from_currency, to_currency):
""" update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info """
if check_update(from_currency, to_currency) is True:
ccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currenc... | [
"def",
"update_cache",
"(",
"from_currency",
",",
"to_currency",
")",
":",
"if",
"check_update",
"(",
"from_currency",
",",
"to_currency",
")",
"is",
"True",
":",
"ccache",
"[",
"from_currency",
"]",
"[",
"to_currency",
"]",
"[",
"'value'",
"]",
"=",
"conver... | update from_currency to_currency pair in cache if
last update for that pair is over 30 minutes ago by request API info | [
"update",
"from_currency",
"to_currency",
"pair",
"in",
"cache",
"if",
"last",
"update",
"for",
"that",
"pair",
"is",
"over",
"30",
"minutes",
"ago",
"by",
"request",
"API",
"info"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L144-L150 | train |
NearHuscarl/py-currency | currency/currency.py | convert_using_api | def convert_using_api(from_currency, to_currency):
""" convert from from_currency to to_currency by requesting API """
convert_str = from_currency + '_' + to_currency
options = {'compact': 'ultra', 'q': convert_str}
api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
result = requests.get(api_url, par... | python | def convert_using_api(from_currency, to_currency):
""" convert from from_currency to to_currency by requesting API """
convert_str = from_currency + '_' + to_currency
options = {'compact': 'ultra', 'q': convert_str}
api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
result = requests.get(api_url, par... | [
"def",
"convert_using_api",
"(",
"from_currency",
",",
"to_currency",
")",
":",
"convert_str",
"=",
"from_currency",
"+",
"'_'",
"+",
"to_currency",
"options",
"=",
"{",
"'compact'",
":",
"'ultra'",
",",
"'q'",
":",
"convert_str",
"}",
"api_url",
"=",
"'https:... | convert from from_currency to to_currency by requesting API | [
"convert",
"from",
"from_currency",
"to",
"to_currency",
"by",
"requesting",
"API"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L152-L158 | train |
NearHuscarl/py-currency | currency/currency.py | convert | def convert(from_currency, to_currency, from_currency_price=1):
""" convert from from_currency to to_currency using cached info """
get_cache()
from_currency, to_currency = validate_currency(from_currency, to_currency)
update_cache(from_currency, to_currency)
return ccache[from_currency][to_currency]['value'] * fr... | python | def convert(from_currency, to_currency, from_currency_price=1):
""" convert from from_currency to to_currency using cached info """
get_cache()
from_currency, to_currency = validate_currency(from_currency, to_currency)
update_cache(from_currency, to_currency)
return ccache[from_currency][to_currency]['value'] * fr... | [
"def",
"convert",
"(",
"from_currency",
",",
"to_currency",
",",
"from_currency_price",
"=",
"1",
")",
":",
"get_cache",
"(",
")",
"from_currency",
",",
"to_currency",
"=",
"validate_currency",
"(",
"from_currency",
",",
"to_currency",
")",
"update_cache",
"(",
... | convert from from_currency to to_currency using cached info | [
"convert",
"from",
"from_currency",
"to",
"to_currency",
"using",
"cached",
"info"
] | 4e30426399872fd6bfaa4c752a91d67c2d7bf52c | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L160-L165 | train |
jaraco/jaraco.windows | jaraco/windows/timers.py | WaitableTimer.wait_for_signal | def wait_for_signal(self, timeout=None):
"""
wait for the signal; return after the signal has occurred or the
timeout in seconds elapses.
"""
timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE
win32event.WaitForSingleObject(self.signal_event, timeout_ms) | python | def wait_for_signal(self, timeout=None):
"""
wait for the signal; return after the signal has occurred or the
timeout in seconds elapses.
"""
timeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE
win32event.WaitForSingleObject(self.signal_event, timeout_ms) | [
"def",
"wait_for_signal",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"timeout_ms",
"=",
"int",
"(",
"timeout",
"*",
"1000",
")",
"if",
"timeout",
"else",
"win32event",
".",
"INFINITE",
"win32event",
".",
"WaitForSingleObject",
"(",
"self",
".",
"s... | wait for the signal; return after the signal has occurred or the
timeout in seconds elapses. | [
"wait",
"for",
"the",
"signal",
";",
"return",
"after",
"the",
"signal",
"has",
"occurred",
"or",
"the",
"timeout",
"in",
"seconds",
"elapses",
"."
] | 51811efed50b46ad08daa25408a1cc806bc8d519 | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/timers.py#L36-L42 | train |
Genida/django-meerkat | src/meerkat/utils/geolocation.py | ip_geoloc | def ip_geoloc(ip, hit_api=True):
"""
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
"""
from ..logs.models import IPInfoCheck
try... | python | def ip_geoloc(ip, hit_api=True):
"""
Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated.
"""
from ..logs.models import IPInfoCheck
try... | [
"def",
"ip_geoloc",
"(",
"ip",
",",
"hit_api",
"=",
"True",
")",
":",
"from",
".",
".",
"logs",
".",
"models",
"import",
"IPInfoCheck",
"try",
":",
"obj",
"=",
"IPInfoCheck",
".",
"objects",
".",
"get",
"(",
"ip_address",
"=",
"ip",
")",
".",
"ip_inf... | Get IP geolocation.
Args:
ip (str): IP address to use if no data provided.
hit_api (bool): whether to hit api if info not found.
Returns:
str: latitude and longitude, comma-separated. | [
"Get",
"IP",
"geolocation",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L8-L30 | train |
Genida/django-meerkat | src/meerkat/utils/geolocation.py | google_maps_geoloc_link | def google_maps_geoloc_link(data):
"""
Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation.
"""
if isinstance(data, str):
lat_lon ... | python | def google_maps_geoloc_link(data):
"""
Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation.
"""
if isinstance(data, str):
lat_lon ... | [
"def",
"google_maps_geoloc_link",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"lat_lon",
"=",
"ip_geoloc",
"(",
"data",
")",
"if",
"lat_lon",
"is",
"None",
":",
"return",
"''",
"lat",
",",
"lon",
"=",
"lat_lon",
"else"... | Get a link to google maps pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to google maps pointing on this IP's geolocation. | [
"Get",
"a",
"link",
"to",
"google",
"maps",
"pointing",
"on",
"this",
"IP",
"s",
"geolocation",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L33-L53 | train |
Genida/django-meerkat | src/meerkat/utils/geolocation.py | open_street_map_geoloc_link | def open_street_map_geoloc_link(data):
"""
Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation.
"""
if isinstance(data, str):
... | python | def open_street_map_geoloc_link(data):
"""
Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation.
"""
if isinstance(data, str):
... | [
"def",
"open_street_map_geoloc_link",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"lat_lon",
"=",
"ip_geoloc",
"(",
"data",
")",
"if",
"lat_lon",
"is",
"None",
":",
"return",
"''",
"lat",
",",
"lon",
"=",
"lat_lon",
"e... | Get a link to open street map pointing on this IP's geolocation.
Args:
data (str/tuple): IP address or (latitude, longitude).
Returns:
str: a link to open street map pointing on this IP's geolocation. | [
"Get",
"a",
"link",
"to",
"open",
"street",
"map",
"pointing",
"on",
"this",
"IP",
"s",
"geolocation",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L56-L74 | train |
Genida/django-meerkat | src/meerkat/logs/charts.py | status_codes_chart | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | python | def status_codes_chart():
"""Chart for status codes."""
stats = status_codes_stats()
chart_options = {
'chart': {
'type': 'pie'
},
'title': {
'text': ''
},
'subtitle': {
'text': ''
},
'tooltip': {
'formatt... | [
"def",
"status_codes_chart",
"(",
")",
":",
"stats",
"=",
"status_codes_stats",
"(",
")",
"chart_options",
"=",
"{",
"'chart'",
":",
"{",
"'type'",
":",
"'pie'",
"}",
",",
"'title'",
":",
"{",
"'text'",
":",
"''",
"}",
",",
"'subtitle'",
":",
"{",
"'te... | Chart for status codes. | [
"Chart",
"for",
"status",
"codes",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L19-L63 | train |
Genida/django-meerkat | src/meerkat/logs/charts.py | most_visited_pages_legend_chart | def most_visited_pages_legend_chart():
"""Chart for most visited pages legend."""
return {
'chart': {
'type': 'bar',
'height': 200,
},
'title': {
'text': _('Legend')
},
'xAxis': {
'categories': [
_('Project U... | python | def most_visited_pages_legend_chart():
"""Chart for most visited pages legend."""
return {
'chart': {
'type': 'bar',
'height': 200,
},
'title': {
'text': _('Legend')
},
'xAxis': {
'categories': [
_('Project U... | [
"def",
"most_visited_pages_legend_chart",
"(",
")",
":",
"return",
"{",
"'chart'",
":",
"{",
"'type'",
":",
"'bar'",
",",
"'height'",
":",
"200",
",",
"}",
",",
"'title'",
":",
"{",
"'text'",
":",
"_",
"(",
"'Legend'",
")",
"}",
",",
"'xAxis'",
":",
... | Chart for most visited pages legend. | [
"Chart",
"for",
"most",
"visited",
"pages",
"legend",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L100-L154 | train |
dcramer/logan | logan/settings.py | add_settings | def add_settings(mod, allow_extras=True, settings=django_settings):
"""
Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``.
"""
extras = {}
for setting in dir(mod):
... | python | def add_settings(mod, allow_extras=True, settings=django_settings):
"""
Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``.
"""
extras = {}
for setting in dir(mod):
... | [
"def",
"add_settings",
"(",
"mod",
",",
"allow_extras",
"=",
"True",
",",
"settings",
"=",
"django_settings",
")",
":",
"extras",
"=",
"{",
"}",
"for",
"setting",
"in",
"dir",
"(",
"mod",
")",
":",
"if",
"setting",
"==",
"setting",
".",
"upper",
"(",
... | Adds all settings that are part of ``mod`` to the global settings object.
Special cases ``EXTRA_APPS`` to append the specified applications to the
list of ``INSTALLED_APPS``. | [
"Adds",
"all",
"settings",
"that",
"are",
"part",
"of",
"mod",
"to",
"the",
"global",
"settings",
"object",
"."
] | 8b18456802d631a822e2823bf9a4e9810a15a20e | https://github.com/dcramer/logan/blob/8b18456802d631a822e2823bf9a4e9810a15a20e/logan/settings.py#L73-L101 | train |
Genida/django-meerkat | src/meerkat/sites.py | DashboardSite.get_urls | def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... | python | def get_urls(self):
"""
Get urls method.
Returns:
list: the list of url objects.
"""
urls = super(DashboardSite, self).get_urls()
custom_urls = [
url(r'^$',
self.admin_view(HomeView.as_view()),
name='index'),
... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"DashboardSite",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"custom_urls",
"=",
"[",
"url",
"(",
"r'^$'",
",",
"self",
".",
"admin_view",
"(",
"HomeView",
".",
"as_view",
"(",
")"... | Get urls method.
Returns:
list: the list of url objects. | [
"Get",
"urls",
"method",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/sites.py#L23-L41 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | add_form_widget_attr | def add_form_widget_attr(field, attr_name, attr_value, replace=0):
"""
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{... | python | def add_form_widget_attr(field, attr_name, attr_value, replace=0):
"""
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{... | [
"def",
"add_form_widget_attr",
"(",
"field",
",",
"attr_name",
",",
"attr_value",
",",
"replace",
"=",
"0",
")",
":",
"if",
"not",
"replace",
":",
"attr",
"=",
"field",
".",
"field",
".",
"widget",
".",
"attrs",
".",
"get",
"(",
"attr_name",
",",
"''",... | Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{% for field in form.fields %}
{% add_form_widget_attr field 'class'... | [
"Adds",
"widget",
"attributes",
"to",
"a",
"bound",
"form",
"field",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L32-L60 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | block_anyfilter | def block_anyfilter(parser, token):
"""
Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %}
"""
bits = token.co... | python | def block_anyfilter(parser, token):
"""
Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %}
"""
bits = token.co... | [
"def",
"block_anyfilter",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endblockanyfilter'",
",",
")",
")",
"parser",
".",
"delete_first_token",
... | Turn any template filter into a blocktag.
Usage::
{% load libs_tags %}
{% block_anyfilter django.template.defaultfilters.truncatewords_html 15 %}
// Something complex that generates html output
{% endblockanyfilter %} | [
"Turn",
"any",
"template",
"filter",
"into",
"a",
"blocktag",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L64-L79 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | calculate_dimensions | def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
return '{0}x{1}'.format(long_side, short_side)
return '{0}x{1}'.format(short_side, long_side) | python | def calculate_dimensions(image, long_side, short_side):
"""Returns the thumbnail dimensions depending on the images format."""
if image.width >= image.height:
return '{0}x{1}'.format(long_side, short_side)
return '{0}x{1}'.format(short_side, long_side) | [
"def",
"calculate_dimensions",
"(",
"image",
",",
"long_side",
",",
"short_side",
")",
":",
"if",
"image",
".",
"width",
">=",
"image",
".",
"height",
":",
"return",
"'{0}x{1}'",
".",
"format",
"(",
"long_side",
",",
"short_side",
")",
"return",
"'{0}x{1}'",... | Returns the thumbnail dimensions depending on the images format. | [
"Returns",
"the",
"thumbnail",
"dimensions",
"depending",
"on",
"the",
"images",
"format",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L95-L99 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | call | def call(obj, method, *args, **kwargs):
"""
Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'my... | python | def call(obj, method, *args, **kwargs):
"""
Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'my... | [
"def",
"call",
"(",
"obj",
",",
"method",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"function_or_dict_or_member",
"=",
"getattr",
"(",
"obj",
",",
"method",
")",
"if",
"callable",
"(",
"function_or_dict_or_member",
")",
":",
"return",
"function_or_dic... | Allows to call any method of any object with parameters.
Because come on! It's bloody stupid that Django's templating engine doesn't
allow that.
Usage::
{% call myobj 'mymethod' myvar foobar=myvar2 as result %}
{% call myobj 'mydict' 'mykey' as result %}
{% call myobj 'myattribute... | [
"Allows",
"to",
"call",
"any",
"method",
"of",
"any",
"object",
"with",
"parameters",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L103-L129 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | concatenate | def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... | python | def concatenate(*args, **kwargs):
"""
Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar".
"""
... | [
"def",
"concatenate",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"divider",
"=",
"kwargs",
".",
"get",
"(",
"'divider'",
",",
"''",
")",
"result",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"if",
"result",
"==",
"''",
":",
"result",
"+=",
... | Concatenates the given strings.
Usage::
{% load libs_tags %}
{% concatenate "foo" "bar" as new_string %}
{% concatenate "foo" "bar" divider="_" as another_string %}
The above would result in the strings "foobar" and "foo_bar". | [
"Concatenates",
"the",
"given",
"strings",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L133-L153 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_content_type | def get_content_type(obj, field_name=False):
"""
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return.
"""
content_type = ContentType.objects.get_for_model(obj)
if field_name:
return getattr(content_type, field_name, ... | python | def get_content_type(obj, field_name=False):
"""
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return.
"""
content_type = ContentType.objects.get_for_model(obj)
if field_name:
return getattr(content_type, field_name, ... | [
"def",
"get_content_type",
"(",
"obj",
",",
"field_name",
"=",
"False",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"if",
"field_name",
":",
"return",
"getattr",
"(",
"content_type",
",",
"field_name",
... | Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return. | [
"Returns",
"the",
"content",
"type",
"of",
"an",
"object",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L157-L168 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_verbose | def get_verbose(obj, field_name=""):
"""
Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format.
"""
if hasattr(obj, "_meta") and hasattr(obj._meta, "get_field_by_name"):
try:
return obj._me... | python | def get_verbose(obj, field_name=""):
"""
Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format.
"""
if hasattr(obj, "_meta") and hasattr(obj._meta, "get_field_by_name"):
try:
return obj._me... | [
"def",
"get_verbose",
"(",
"obj",
",",
"field_name",
"=",
"\"\"",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"_meta\"",
")",
"and",
"hasattr",
"(",
"obj",
".",
"_meta",
",",
"\"get_field_by_name\"",
")",
":",
"try",
":",
"return",
"obj",
".",
"_meta... | Returns the verbose name of an object's field.
:param obj: A model instance.
:param field_name: The requested field value in string format. | [
"Returns",
"the",
"verbose",
"name",
"of",
"an",
"object",
"s",
"field",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L200-L213 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_query_params | def get_query_params(request, *args):
"""
Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pa... | python | def get_query_params(request, *args):
"""
Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pa... | [
"def",
"get_query_params",
"(",
"request",
",",
"*",
"args",
")",
":",
"query",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"index",
"=",
"1",
"key",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"if",
"index",
"%",
"2",
"!=",
"0",
":",
"k... | Allows to change one of the URL get parameter while keeping all the others.
Usage::
{% load libs_tags %}
{% get_query_params request "page" page_obj.next_page_number as query %}
<a href="?{{ query }}">Next</a>
You can also pass in several pairs of keys and values::
{% get_query_param... | [
"Allows",
"to",
"change",
"one",
"of",
"the",
"URL",
"get",
"parameter",
"while",
"keeping",
"all",
"the",
"others",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L217-L258 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | navactive | def navactive(request, url, exact=0, use_resolver=1):
"""
Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string r... | python | def navactive(request, url, exact=0, use_resolver=1):
"""
Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string r... | [
"def",
"navactive",
"(",
"request",
",",
"url",
",",
"exact",
"=",
"0",
",",
"use_resolver",
"=",
"1",
")",
":",
"if",
"use_resolver",
":",
"try",
":",
"if",
"url",
"==",
"resolve",
"(",
"request",
".",
"path",
")",
".",
"url_name",
":",
"return",
... | Returns ``active`` if the given URL is in the url path, otherwise ''.
Usage::
{% load libs_tags %}
...
<li class="{% navactive request "/news/" exact=1 %}">
:param request: A request instance.
:param url: A string representing a part of the URL that needs to exist
in order f... | [
"Returns",
"active",
"if",
"the",
"given",
"URL",
"is",
"in",
"the",
"url",
"path",
"otherwise",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L290-L331 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | get_range_around | def get_range_around(range_value, current_item, padding):
"""
Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 item... | python | def get_range_around(range_value, current_item, padding):
"""
Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 item... | [
"def",
"get_range_around",
"(",
"range_value",
",",
"current_item",
",",
"padding",
")",
":",
"total_items",
"=",
"1",
"+",
"padding",
"*",
"2",
"left_bound",
"=",
"padding",
"right_bound",
"=",
"range_value",
"-",
"padding",
"if",
"range_value",
"<=",
"total_... | Returns a range of numbers around the given number.
This is useful for pagination, where you might want to show something
like this::
<< < ... 4 5 (6) 7 8 .. > >>
In this example `6` would be the current page and we show 2 items around
that page (including the page itself).
Usage::
... | [
"Returns",
"a",
"range",
"of",
"numbers",
"around",
"the",
"given",
"number",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L364-L420 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | sum | def sum(context, key, value, multiplier=1):
"""
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TO... | python | def sum(context, key, value, multiplier=1):
"""
Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TO... | [
"def",
"sum",
"(",
"context",
",",
"key",
",",
"value",
",",
"multiplier",
"=",
"1",
")",
":",
"if",
"key",
"not",
"in",
"context",
".",
"dicts",
"[",
"0",
"]",
":",
"context",
".",
"dicts",
"[",
"0",
"]",
"[",
"key",
"]",
"=",
"0",
"context",
... | Adds the given value to the total value currently held in ``key``.
Use the multiplier if you want to turn a positive value into a negative
and actually substract from the current total sum.
Usage::
{% sum "MY_TOTAL" 42 -1 %}
{{ MY_TOTAL }} | [
"Adds",
"the",
"given",
"value",
"to",
"the",
"total",
"value",
"currently",
"held",
"in",
"key",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L468-L484 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | verbatim | def verbatim(parser, token):
"""Tag to render x-tmpl templates with Django template code."""
text = []
while 1:
token = parser.tokens.pop(0)
if token.contents == 'endverbatim':
break
if token.token_type == TOKEN_VAR:
text.append('{{ ')
elif token.token... | python | def verbatim(parser, token):
"""Tag to render x-tmpl templates with Django template code."""
text = []
while 1:
token = parser.tokens.pop(0)
if token.contents == 'endverbatim':
break
if token.token_type == TOKEN_VAR:
text.append('{{ ')
elif token.token... | [
"def",
"verbatim",
"(",
"parser",
",",
"token",
")",
":",
"text",
"=",
"[",
"]",
"while",
"1",
":",
"token",
"=",
"parser",
".",
"tokens",
".",
"pop",
"(",
"0",
")",
"if",
"token",
".",
"contents",
"==",
"'endverbatim'",
":",
"break",
"if",
"token"... | Tag to render x-tmpl templates with Django template code. | [
"Tag",
"to",
"render",
"x",
"-",
"tmpl",
"templates",
"with",
"Django",
"template",
"code",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L502-L520 | train |
bitlabstudio/django-libs | django_libs/templatetags/libs_tags.py | append_s | def append_s(value):
"""
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's
"""
if value.endswith('s'):
return u"{0}'".format(value)
else:
return u"{0}'s".format(value) | python | def append_s(value):
"""
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's
"""
if value.endswith('s'):
return u"{0}'".format(value)
else:
return u"{0}'s".format(value) | [
"def",
"append_s",
"(",
"value",
")",
":",
"if",
"value",
".",
"endswith",
"(",
"'s'",
")",
":",
"return",
"u\"{0}'\"",
".",
"format",
"(",
"value",
")",
"else",
":",
"return",
"u\"{0}'s\"",
".",
"format",
"(",
"value",
")"
] | Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's | [
"Adds",
"the",
"possessive",
"s",
"after",
"a",
"string",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/templatetags/libs_tags.py#L566-L577 | train |
Genida/django-meerkat | src/meerkat/logs/urls.py | logs_urlpatterns | def logs_urlpatterns(admin_view=lambda x: x):
"""
Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views.
"""
return [
url(r'^$',
admin_view(Lo... | python | def logs_urlpatterns(admin_view=lambda x: x):
"""
Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views.
"""
return [
url(r'^$',
admin_view(Lo... | [
"def",
"logs_urlpatterns",
"(",
"admin_view",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"[",
"url",
"(",
"r'^$'",
",",
"admin_view",
"(",
"LogsMenu",
".",
"as_view",
"(",
")",
")",
",",
"name",
"=",
"'logs'",
")",
",",
"url",
"(",
"r'^status_... | Return the URL patterns for the logs views.
Args:
admin_view (callable): admin_view method from an AdminSite instance.
Returns:
list: the URL patterns for the logs views. | [
"Return",
"the",
"URL",
"patterns",
"for",
"the",
"logs",
"views",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/urls.py#L11-L34 | train |
Genida/django-meerkat | src/meerkat/utils/ip_info.py | IpInfoHandler._get | def _get(self, ip):
"""
Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started
"""
# Geoloc updated up to once a week:
# http://ipinfo.io/developers/data#geoloc... | python | def _get(self, ip):
"""
Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started
"""
# Geoloc updated up to once a week:
# http://ipinfo.io/developers/data#geoloc... | [
"def",
"_get",
"(",
"self",
",",
"ip",
")",
":",
"retries",
"=",
"10",
"for",
"retry",
"in",
"range",
"(",
"retries",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"'http://ipinfo.io/%s/json'",
"%",
"ip",
",",
"verify",
"=",
"Fa... | Get information about an IP.
Args:
ip (str): an IP (xxx.xxx.xxx.xxx).
Returns:
dict: see http://ipinfo.io/developers/getting-started | [
"Get",
"information",
"about",
"an",
"IP",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/ip_info.py#L100-L122 | train |
flavio/scsgate | scsgate/messages.py | parse | def parse(data):
""" Parses a raw datagram and return the right type of message """
# convert to string
data = data.decode("ascii")
if len(data) == 2 and data == "A5":
return AckMessage()
# split into bytes
raw = [data[i:i+2] for i in range(len(data)) if i % 2 == 0]
if len(raw) !... | python | def parse(data):
""" Parses a raw datagram and return the right type of message """
# convert to string
data = data.decode("ascii")
if len(data) == 2 and data == "A5":
return AckMessage()
# split into bytes
raw = [data[i:i+2] for i in range(len(data)) if i % 2 == 0]
if len(raw) !... | [
"def",
"parse",
"(",
"data",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"\"ascii\"",
")",
"if",
"len",
"(",
"data",
")",
"==",
"2",
"and",
"data",
"==",
"\"A5\"",
":",
"return",
"AckMessage",
"(",
")",
"raw",
"=",
"[",
"data",
"[",
"i",
... | Parses a raw datagram and return the right type of message | [
"Parses",
"a",
"raw",
"datagram",
"and",
"return",
"the",
"right",
"type",
"of",
"message"
] | aad1d181eef4714ab475f4ff7fcfac4a6425fbb4 | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L213-L237 | train |
flavio/scsgate | scsgate/messages.py | checksum_bytes | def checksum_bytes(data):
""" Returns a XOR of all the bytes specified inside of the given list """
int_values = [int(x, 16) for x in data]
int_xor = reduce(lambda x, y: x ^ y, int_values)
hex_xor = "{:X}".format(int_xor)
if len(hex_xor) % 2 != 0:
hex_xor = "0" + hex_xor
return str.enc... | python | def checksum_bytes(data):
""" Returns a XOR of all the bytes specified inside of the given list """
int_values = [int(x, 16) for x in data]
int_xor = reduce(lambda x, y: x ^ y, int_values)
hex_xor = "{:X}".format(int_xor)
if len(hex_xor) % 2 != 0:
hex_xor = "0" + hex_xor
return str.enc... | [
"def",
"checksum_bytes",
"(",
"data",
")",
":",
"int_values",
"=",
"[",
"int",
"(",
"x",
",",
"16",
")",
"for",
"x",
"in",
"data",
"]",
"int_xor",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"^",
"y",
",",
"int_values",
")",
"hex_xor",... | Returns a XOR of all the bytes specified inside of the given list | [
"Returns",
"a",
"XOR",
"of",
"all",
"the",
"bytes",
"specified",
"inside",
"of",
"the",
"given",
"list"
] | aad1d181eef4714ab475f4ff7fcfac4a6425fbb4 | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L240-L249 | train |
flavio/scsgate | scsgate/messages.py | compose_telegram | def compose_telegram(body):
""" Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance)
"""
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) | python | def compose_telegram(body):
""" Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance)
"""
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) | [
"def",
"compose_telegram",
"(",
"body",
")",
":",
"msg",
"=",
"[",
"b\"A8\"",
"]",
"+",
"body",
"+",
"[",
"checksum_bytes",
"(",
"body",
")",
"]",
"+",
"[",
"b\"A3\"",
"]",
"return",
"str",
".",
"encode",
"(",
"\"\"",
".",
"join",
"(",
"[",
"x",
... | Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance) | [
"Compose",
"a",
"SCS",
"message"
] | aad1d181eef4714ab475f4ff7fcfac4a6425fbb4 | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L252-L260 | train |
bitlabstudio/django-libs | django_libs/utils/email.py | send_email | def send_email(request, context, subject_template, body_template,
from_email, recipients, priority="medium", reply_to=None,
headers=None, cc=None, bcc=None):
"""
Sends an email based on templates for subject and body.
:param request: The current request instance.
:param co... | python | def send_email(request, context, subject_template, body_template,
from_email, recipients, priority="medium", reply_to=None,
headers=None, cc=None, bcc=None):
"""
Sends an email based on templates for subject and body.
:param request: The current request instance.
:param co... | [
"def",
"send_email",
"(",
"request",
",",
"context",
",",
"subject_template",
",",
"body_template",
",",
"from_email",
",",
"recipients",
",",
"priority",
"=",
"\"medium\"",
",",
"reply_to",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cc",
"=",
"None",
... | Sends an email based on templates for subject and body.
:param request: The current request instance.
:param context: A dictionary of items that should be added to the
templates' contexts.
:param subject_template: A string representing the path to the template of
of the email's subject.
... | [
"Sends",
"an",
"email",
"based",
"on",
"templates",
"for",
"subject",
"and",
"body",
"."
] | 2c5376cda084bf16edea540e0f6999f1d844afd0 | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/utils/email.py#L18-L92 | train |
Genida/django-meerkat | src/meerkat/utils/url.py | url_is_project | def url_is_project(url, default='not_a_func'):
"""
Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns:
"""
try:
u = resolve(url)
if u and u.func != de... | python | def url_is_project(url, default='not_a_func'):
"""
Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns:
"""
try:
u = resolve(url)
if u and u.func != de... | [
"def",
"url_is_project",
"(",
"url",
",",
"default",
"=",
"'not_a_func'",
")",
":",
"try",
":",
"u",
"=",
"resolve",
"(",
"url",
")",
"if",
"u",
"and",
"u",
".",
"func",
"!=",
"default",
":",
"return",
"True",
"except",
"Resolver404",
":",
"static_url"... | Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns: | [
"Check",
"if",
"URL",
"is",
"part",
"of",
"the",
"current",
"project",
"s",
"URLs",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L14-L40 | train |
Genida/django-meerkat | src/meerkat/utils/url.py | url_is | def url_is(white_list):
"""
Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is...
"""
def func(url):
prefixes = white_list.get('PREFIXES', ())
for prefix in prefixes:
... | python | def url_is(white_list):
"""
Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is...
"""
def func(url):
prefixes = white_list.get('PREFIXES', ())
for prefix in prefixes:
... | [
"def",
"url_is",
"(",
"white_list",
")",
":",
"def",
"func",
"(",
"url",
")",
":",
"prefixes",
"=",
"white_list",
".",
"get",
"(",
"'PREFIXES'",
",",
"(",
")",
")",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"url",
".",
"startswith",
"(",
"prefix"... | Function generator.
Args:
white_list (dict): dict with PREFIXES and CONSTANTS keys (list values).
Returns:
func: a function to check if a URL is... | [
"Function",
"generator",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L43-L63 | train |
gsi-upm/soil | soil/history.py | History.save_records | def save_records(self, records):
'''
Save a collection of records
'''
for record in records:
if not isinstance(record, Record):
record = Record(*record)
self.save_record(*record) | python | def save_records(self, records):
'''
Save a collection of records
'''
for record in records:
if not isinstance(record, Record):
record = Record(*record)
self.save_record(*record) | [
"def",
"save_records",
"(",
"self",
",",
"records",
")",
":",
"for",
"record",
"in",
"records",
":",
"if",
"not",
"isinstance",
"(",
"record",
",",
"Record",
")",
":",
"record",
"=",
"Record",
"(",
"*",
"record",
")",
"self",
".",
"save_record",
"(",
... | Save a collection of records | [
"Save",
"a",
"collection",
"of",
"records"
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L70-L77 | train |
gsi-upm/soil | soil/history.py | History.save_record | def save_record(self, agent_id, t_step, key, value):
'''
Save a collection of records to the database.
Database writes are cached.
'''
value = self.convert(key, value)
self._tups.append(Record(agent_id=agent_id,
t_step=t_step,
... | python | def save_record(self, agent_id, t_step, key, value):
'''
Save a collection of records to the database.
Database writes are cached.
'''
value = self.convert(key, value)
self._tups.append(Record(agent_id=agent_id,
t_step=t_step,
... | [
"def",
"save_record",
"(",
"self",
",",
"agent_id",
",",
"t_step",
",",
"key",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"convert",
"(",
"key",
",",
"value",
")",
"self",
".",
"_tups",
".",
"append",
"(",
"Record",
"(",
"agent_id",
"=",
"a... | Save a collection of records to the database.
Database writes are cached. | [
"Save",
"a",
"collection",
"of",
"records",
"to",
"the",
"database",
".",
"Database",
"writes",
"are",
"cached",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L79-L90 | train |
gsi-upm/soil | soil/history.py | History.convert | def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = uti... | python | def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = uti... | [
"def",
"convert",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"self",
".",
"read_types",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"name",
"=",
"utils",
".",
"name... | Get the serialized value for a given key. | [
"Get",
"the",
"serialized",
"value",
"for",
"a",
"given",
"key",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L92-L103 | train |
gsi-upm/soil | soil/history.py | History.recover | def recover(self, key, value):
"""Get the deserialized value for a given key, and the serialized version."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
raise ValueError("Unknown datatype for {} and {}".format(key, value))
return self... | python | def recover(self, key, value):
"""Get the deserialized value for a given key, and the serialized version."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
raise ValueError("Unknown datatype for {} and {}".format(key, value))
return self... | [
"def",
"recover",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"self",
".",
"read_types",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_dtypes",
":",
"raise",
"ValueError",
"(",
"\"Unk... | Get the deserialized value for a given key, and the serialized version. | [
"Get",
"the",
"deserialized",
"value",
"for",
"a",
"given",
"key",
"and",
"the",
"serialized",
"version",
"."
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L105-L111 | train |
gsi-upm/soil | soil/history.py | History.flush_cache | def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... | python | def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... | [
"def",
"flush_cache",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Flushing cache {}'",
".",
"format",
"(",
"self",
".",
"db_path",
")",
")",
"with",
"self",
".",
"db",
":",
"for",
"rec",
"in",
"self",
".",
"_tups",
":",
"self",
".",
"db",
... | Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed. | [
"Use",
"a",
"cache",
"to",
"save",
"state",
"changes",
"to",
"avoid",
"opening",
"a",
"session",
"for",
"every",
"change",
".",
"The",
"cache",
"will",
"be",
"flushed",
"at",
"the",
"end",
"of",
"the",
"simulation",
"and",
"when",
"history",
"is",
"acces... | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/history.py#L114-L123 | train |
inveniosoftware/invenio-search-ui | examples/app.py | records | def records():
"""Load records."""
import pkg_resources
import uuid
from dojson.contrib.marc21 import marc21
from dojson.contrib.marc21.utils import create_record, split_blob
from invenio_pidstore import current_pidstore
from invenio_records.api import Record
# pkg resources the demodat... | python | def records():
"""Load records."""
import pkg_resources
import uuid
from dojson.contrib.marc21 import marc21
from dojson.contrib.marc21.utils import create_record, split_blob
from invenio_pidstore import current_pidstore
from invenio_records.api import Record
# pkg resources the demodat... | [
"def",
"records",
"(",
")",
":",
"import",
"pkg_resources",
"import",
"uuid",
"from",
"dojson",
".",
"contrib",
".",
"marc21",
"import",
"marc21",
"from",
"dojson",
".",
"contrib",
".",
"marc21",
".",
"utils",
"import",
"create_record",
",",
"split_blob",
"f... | Load records. | [
"Load",
"records",
"."
] | 4b61737f938cbfdc1aad6602a73f3a24d53b3312 | https://github.com/inveniosoftware/invenio-search-ui/blob/4b61737f938cbfdc1aad6602a73f3a24d53b3312/examples/app.py#L206-L233 | train |
gsi-upm/soil | soil/simulation.py | Simulation.run_trial_exceptions | def run_trial_exceptions(self, *args, **kwargs):
'''
A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations
'''
try:
return self.run_trial(*args, **kwargs)
except Exception as ex:
c = ex.__cause__
... | python | def run_trial_exceptions(self, *args, **kwargs):
'''
A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations
'''
try:
return self.run_trial(*args, **kwargs)
except Exception as ex:
c = ex.__cause__
... | [
"def",
"run_trial_exceptions",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"run_trial",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"Exception",
"as",
"ex",
":",
"c",
"=",
"ex",
".",
"_... | A wrapper for run_trial that catches exceptions and returns them.
It is meant for async simulations | [
"A",
"wrapper",
"for",
"run_trial",
"that",
"catches",
"exceptions",
"and",
"returns",
"them",
".",
"It",
"is",
"meant",
"for",
"async",
"simulations"
] | a3ea434f237f039c3cadbc2e0a83ae626d77b818 | https://github.com/gsi-upm/soil/blob/a3ea434f237f039c3cadbc2e0a83ae626d77b818/soil/simulation.py#L196-L206 | train |
pr-omethe-us/PyKED | pyked/orcid.py | search_orcid | def search_orcid(orcid):
"""
Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from ... | python | def search_orcid(orcid):
"""
Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from ... | [
"def",
"search_orcid",
"(",
"orcid",
")",
":",
"url",
"=",
"'https://pub.orcid.org/v2.1/{orcid}/person'",
".",
"format",
"(",
"orcid",
"=",
"orcid",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"if",
"r",
".",
"... | Search the ORCID public API
Specfically, return a dictionary with the personal details
(name, etc.) of the person associated with the given ORCID
Args:
orcid (`str`): The ORCID to be searched
Returns:
`dict`: Dictionary with the JSON response from the API
Raises:
`~reques... | [
"Search",
"the",
"ORCID",
"public",
"API"
] | d9341a068c1099049a3f1de41c512591f342bf64 | https://github.com/pr-omethe-us/PyKED/blob/d9341a068c1099049a3f1de41c512591f342bf64/pyked/orcid.py#L8-L29 | train |
Genida/django-meerkat | src/meerkat/utils/time.py | daterange | def daterange(start_date, end_date):
"""
Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range.
"""
for n in range(int((end_date - start_date).da... | python | def daterange(start_date, end_date):
"""
Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range.
"""
for n in range(int((end_date - start_date).da... | [
"def",
"daterange",
"(",
"start_date",
",",
"end_date",
")",
":",
"for",
"n",
"in",
"range",
"(",
"int",
"(",
"(",
"end_date",
"-",
"start_date",
")",
".",
"days",
")",
")",
":",
"yield",
"start_date",
"+",
"timedelta",
"(",
"n",
")"
] | Yield one date per day from starting date to ending date.
Args:
start_date (date): starting date.
end_date (date): ending date.
Yields:
date: a date for each day within the range. | [
"Yield",
"one",
"date",
"per",
"day",
"from",
"starting",
"date",
"to",
"ending",
"date",
"."
] | 486502a75bb0800266db785fd32717d8c0eb8deb | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/time.py#L21-L33 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.