id int32 0 252k | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,800 | hactar-is/frink | frink/orm.py | ORMLayer.filter | def filter(self, order_by=None, limit=0, **kwargs):
"""
Fetch a list of instances.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
:param limit: How many rows to fetch.
:param kwargs: keyword args on w... | python | def filter(self, order_by=None, limit=0, **kwargs):
"""
Fetch a list of instances.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
:param limit: How many rows to fetch.
:param kwargs: keyword args on w... | [
"def",
"filter",
"(",
"self",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"ValueError",
"try",... | Fetch a list of instances.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
:param limit: How many rows to fetch.
:param kwargs: keyword args on which to filter, column=value | [
"Fetch",
"a",
"list",
"of",
"instances",
"."
] | 0d2c11daca8ef6d4365e98914bdc0bc65478ae72 | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L180-L215 |
241,801 | hactar-is/frink | frink/orm.py | ORMLayer.all | def all(self, order_by=None, limit=0):
"""
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
"""
with rconnect() as conn:
try:
... | python | def all(self, order_by=None, limit=0):
"""
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
"""
with rconnect() as conn:
try:
... | [
"def",
"all",
"(",
"self",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"0",
")",
":",
"with",
"rconnect",
"(",
")",
"as",
"conn",
":",
"try",
":",
"query",
"=",
"self",
".",
"_base",
"(",
")",
"if",
"order_by",
"is",
"not",
"None",
":",
"q... | Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >. | [
"Fetch",
"all",
"items",
"."
] | 0d2c11daca8ef6d4365e98914bdc0bc65478ae72 | https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L320-L344 |
241,802 | dusty-phillips/opterator | opterator.py | opterate | def opterate(func):
'''A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory ... | python | def opterate(func):
'''A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory ... | [
"def",
"opterate",
"(",
"func",
")",
":",
"(",
"positional_params",
",",
"kw_params",
",",
"varargs",
",",
"defaults",
",",
"annotations",
")",
"=",
"portable_argspec",
"(",
"func",
")",
"description",
"=",
"''",
"param_docs",
"=",
"{",
"}",
"if",
"func",
... | A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory arguments that store a stri... | [
"A",
"decorator",
"for",
"a",
"main",
"function",
"entry",
"point",
"to",
"a",
"script",
".",
"It",
"automatically",
"generates",
"the",
"options",
"for",
"the",
"main",
"entry",
"point",
"based",
"on",
"the",
"arguments",
"keyword",
"arguments",
"and",
"doc... | 84fe31f22c73dc0a3666ed82c179461b1799c257 | https://github.com/dusty-phillips/opterator/blob/84fe31f22c73dc0a3666ed82c179461b1799c257/opterator.py#L81-L175 |
241,803 | mayfield/shellish | shellish/command/contrib/syscomplete.py | SystemCompletion.show_setup | def show_setup(self):
""" Provide a helper script for the user to setup completion. """
shell = os.getenv('SHELL')
if not shell:
raise SystemError("No $SHELL env var found")
shell = os.path.basename(shell)
if shell not in self.script_body:
raise SystemErro... | python | def show_setup(self):
""" Provide a helper script for the user to setup completion. """
shell = os.getenv('SHELL')
if not shell:
raise SystemError("No $SHELL env var found")
shell = os.path.basename(shell)
if shell not in self.script_body:
raise SystemErro... | [
"def",
"show_setup",
"(",
"self",
")",
":",
"shell",
"=",
"os",
".",
"getenv",
"(",
"'SHELL'",
")",
"if",
"not",
"shell",
":",
"raise",
"SystemError",
"(",
"\"No $SHELL env var found\"",
")",
"shell",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"shell"... | Provide a helper script for the user to setup completion. | [
"Provide",
"a",
"helper",
"script",
"for",
"the",
"user",
"to",
"setup",
"completion",
"."
] | df0f0e4612d138c34d8cb99b66ab5b8e47f1414a | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/contrib/syscomplete.py#L84-L99 |
241,804 | mayfield/shellish | shellish/command/contrib/syscomplete.py | SystemCompletion.trim | def trim(self, text):
""" Trim whitespace indentation from text. """
lines = text.splitlines()
firstline = lines[0] or lines[1]
indent = len(firstline) - len(firstline.lstrip())
return '\n'.join(x[indent:] for x in lines if x.strip()) | python | def trim(self, text):
""" Trim whitespace indentation from text. """
lines = text.splitlines()
firstline = lines[0] or lines[1]
indent = len(firstline) - len(firstline.lstrip())
return '\n'.join(x[indent:] for x in lines if x.strip()) | [
"def",
"trim",
"(",
"self",
",",
"text",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"firstline",
"=",
"lines",
"[",
"0",
"]",
"or",
"lines",
"[",
"1",
"]",
"indent",
"=",
"len",
"(",
"firstline",
")",
"-",
"len",
"(",
"firstline... | Trim whitespace indentation from text. | [
"Trim",
"whitespace",
"indentation",
"from",
"text",
"."
] | df0f0e4612d138c34d8cb99b66ab5b8e47f1414a | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/contrib/syscomplete.py#L101-L106 |
241,805 | holmes-app/holmes-alf | holmesalf/wrapper.py | AlfAuthNZWrapper.sync_client | def sync_client(self):
"""Synchronous OAuth 2.0 Bearer client"""
if not self._sync_client:
self._sync_client = AlfSyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secret=se... | python | def sync_client(self):
"""Synchronous OAuth 2.0 Bearer client"""
if not self._sync_client:
self._sync_client = AlfSyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secret=se... | [
"def",
"sync_client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sync_client",
":",
"self",
".",
"_sync_client",
"=",
"AlfSyncClient",
"(",
"token_endpoint",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'OAUTH_TOKEN_ENDPOINT'",
")",
",",
"client_id"... | Synchronous OAuth 2.0 Bearer client | [
"Synchronous",
"OAuth",
"2",
".",
"0",
"Bearer",
"client"
] | 4bf891831390ecfae818cf37d8ffc3a76fe9f1ec | https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L26-L34 |
241,806 | holmes-app/holmes-alf | holmesalf/wrapper.py | AlfAuthNZWrapper.async_client | def async_client(self):
"""Asynchronous OAuth 2.0 Bearer client"""
if not self._async_client:
self._async_client = AlfAsyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secr... | python | def async_client(self):
"""Asynchronous OAuth 2.0 Bearer client"""
if not self._async_client:
self._async_client = AlfAsyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secr... | [
"def",
"async_client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_async_client",
":",
"self",
".",
"_async_client",
"=",
"AlfAsyncClient",
"(",
"token_endpoint",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'OAUTH_TOKEN_ENDPOINT'",
")",
",",
"client... | Asynchronous OAuth 2.0 Bearer client | [
"Asynchronous",
"OAuth",
"2",
".",
"0",
"Bearer",
"client"
] | 4bf891831390ecfae818cf37d8ffc3a76fe9f1ec | https://github.com/holmes-app/holmes-alf/blob/4bf891831390ecfae818cf37d8ffc3a76fe9f1ec/holmesalf/wrapper.py#L37-L45 |
241,807 | thwehner/python-firepit | setup.py | get_package_version | def get_package_version():
"""returns package version without importing it"""
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "firepit/__init__.py")) as pkg:
for line in pkg:
m = version.match(line.strip())
if not m:
continue
... | python | def get_package_version():
"""returns package version without importing it"""
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "firepit/__init__.py")) as pkg:
for line in pkg:
m = version.match(line.strip())
if not m:
continue
... | [
"def",
"get_package_version",
"(",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"\"firepit/__init__... | returns package version without importing it | [
"returns",
"package",
"version",
"without",
"importing",
"it"
] | 68aa3b9c9e034e6a9a3498d997ac8d9a03f8c0f9 | https://github.com/thwehner/python-firepit/blob/68aa3b9c9e034e6a9a3498d997ac8d9a03f8c0f9/setup.py#L12-L20 |
241,808 | pavelsof/ipalint | ipalint/ipa.py | Recogniser.recognise | def recognise(self, string, line_num):
"""
Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string.
"""
symbols = []
unknown = []
for char in string:
if char == SPACE:
continue
try:
name = u... | python | def recognise(self, string, line_num):
"""
Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string.
"""
symbols = []
unknown = []
for char in string:
if char == SPACE:
continue
try:
name = u... | [
"def",
"recognise",
"(",
"self",
",",
"string",
",",
"line_num",
")",
":",
"symbols",
"=",
"[",
"]",
"unknown",
"=",
"[",
"]",
"for",
"char",
"in",
"string",
":",
"if",
"char",
"==",
"SPACE",
":",
"continue",
"try",
":",
"name",
"=",
"unicodedata",
... | Splits the string into chars and distributes these into the buckets of
IPA and non-IPA symbols. Expects that there are no precomposed chars in
the string. | [
"Splits",
"the",
"string",
"into",
"chars",
"and",
"distributes",
"these",
"into",
"the",
"buckets",
"of",
"IPA",
"and",
"non",
"-",
"IPA",
"symbols",
".",
"Expects",
"that",
"there",
"are",
"no",
"precomposed",
"chars",
"in",
"the",
"string",
"."
] | 763e5979ede6980cbfc746b06fd007b379762eeb | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L158-L185 |
241,809 | pavelsof/ipalint | ipalint/ipa.py | Recogniser.report | def report(self, reporter):
"""
Adds the problems that have been found so far to the given Reporter
instance.
"""
for symbol in sorted(self.unk_symbols.keys()):
err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name)
if symbol.char in self.common_err:
repl = self.common_err[symbol.char]... | python | def report(self, reporter):
"""
Adds the problems that have been found so far to the given Reporter
instance.
"""
for symbol in sorted(self.unk_symbols.keys()):
err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name)
if symbol.char in self.common_err:
repl = self.common_err[symbol.char]... | [
"def",
"report",
"(",
"self",
",",
"reporter",
")",
":",
"for",
"symbol",
"in",
"sorted",
"(",
"self",
".",
"unk_symbols",
".",
"keys",
"(",
")",
")",
":",
"err",
"=",
"'{} ({}) is not part of IPA'",
".",
"format",
"(",
"symbol",
".",
"char",
",",
"sym... | Adds the problems that have been found so far to the given Reporter
instance. | [
"Adds",
"the",
"problems",
"that",
"have",
"been",
"found",
"so",
"far",
"to",
"the",
"given",
"Reporter",
"instance",
"."
] | 763e5979ede6980cbfc746b06fd007b379762eeb | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/ipa.py#L188-L202 |
241,810 | mrstephenneal/dirutility | dirutility/gui.py | WalkGUI.parsing | def parsing(self):
"""Parameters for parsing directory trees"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')],
... | python | def parsing(self):
"""Parameters for parsing directory trees"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')],
... | [
"def",
"parsing",
"(",
"self",
")",
":",
"with",
"gui",
".",
"FlexForm",
"(",
"self",
".",
"title",
",",
"auto_size_text",
"=",
"True",
",",
"default_element_size",
"=",
"(",
"40",
",",
"1",
")",
")",
"as",
"form",
":",
"layout",
"=",
"[",
"[",
"gu... | Parameters for parsing directory trees | [
"Parameters",
"for",
"parsing",
"directory",
"trees"
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/gui.py#L51-L114 |
241,811 | mrstephenneal/dirutility | dirutility/gui.py | BackupZipGUI.source | def source(self):
"""Parameters for saving zip backups"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')],
[gui.Text(... | python | def source(self):
"""Parameters for saving zip backups"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')],
[gui.Text(... | [
"def",
"source",
"(",
"self",
")",
":",
"with",
"gui",
".",
"FlexForm",
"(",
"self",
".",
"title",
",",
"auto_size_text",
"=",
"True",
",",
"default_element_size",
"=",
"(",
"40",
",",
"1",
")",
")",
"as",
"form",
":",
"layout",
"=",
"[",
"[",
"gui... | Parameters for saving zip backups | [
"Parameters",
"for",
"saving",
"zip",
"backups"
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/gui.py#L123-L143 |
241,812 | Pertino/pertino-sdk-python | pertinosdk/__init__.py | QueryBuilder.contains | def contains(self, desired):
'''Return the filter closure fully constructed.'''
field = self.__field
def aFilter(testDictionary):
return (desired in testDictionary[field])
return aFilter | python | def contains(self, desired):
'''Return the filter closure fully constructed.'''
field = self.__field
def aFilter(testDictionary):
return (desired in testDictionary[field])
return aFilter | [
"def",
"contains",
"(",
"self",
",",
"desired",
")",
":",
"field",
"=",
"self",
".",
"__field",
"def",
"aFilter",
"(",
"testDictionary",
")",
":",
"return",
"(",
"desired",
"in",
"testDictionary",
"[",
"field",
"]",
")",
"return",
"aFilter"
] | Return the filter closure fully constructed. | [
"Return",
"the",
"filter",
"closure",
"fully",
"constructed",
"."
] | d7d75bd374b7f44967ae6f1626a6520507be3a54 | https://github.com/Pertino/pertino-sdk-python/blob/d7d75bd374b7f44967ae6f1626a6520507be3a54/pertinosdk/__init__.py#L20-L25 |
241,813 | marccarre/py_sak | py_sak/validation.py | is_valid_file | def is_valid_file(path):
''' Returns True if provided file exists and is a file, or False otherwise. '''
return os.path.exists(path) and os.path.isfile(path) | python | def is_valid_file(path):
''' Returns True if provided file exists and is a file, or False otherwise. '''
return os.path.exists(path) and os.path.isfile(path) | [
"def",
"is_valid_file",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")"
] | Returns True if provided file exists and is a file, or False otherwise. | [
"Returns",
"True",
"if",
"provided",
"file",
"exists",
"and",
"is",
"a",
"file",
"or",
"False",
"otherwise",
"."
] | 8ad4cafbd725d2700a31b50526804c0330d828dd | https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L42-L44 |
241,814 | marccarre/py_sak | py_sak/validation.py | is_valid_dir | def is_valid_dir(path):
''' Returns True if provided directory exists and is a directory, or False otherwise. '''
return os.path.exists(path) and os.path.isdir(path) | python | def is_valid_dir(path):
''' Returns True if provided directory exists and is a directory, or False otherwise. '''
return os.path.exists(path) and os.path.isdir(path) | [
"def",
"is_valid_dir",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")"
] | Returns True if provided directory exists and is a directory, or False otherwise. | [
"Returns",
"True",
"if",
"provided",
"directory",
"exists",
"and",
"is",
"a",
"directory",
"or",
"False",
"otherwise",
"."
] | 8ad4cafbd725d2700a31b50526804c0330d828dd | https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L47-L49 |
241,815 | marccarre/py_sak | py_sak/validation.py | is_readable | def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) | python | def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) | [
"def",
"is_readable",
"(",
"path",
")",
":",
"return",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
",",
"os",
".",
"R_OK",
")"
] | Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise. | [
"Returns",
"True",
"if",
"provided",
"file",
"or",
"directory",
"exists",
"and",
"can",
"be",
"read",
"with",
"the",
"current",
"user",
".",
"Returns",
"False",
"otherwise",
"."
] | 8ad4cafbd725d2700a31b50526804c0330d828dd | https://github.com/marccarre/py_sak/blob/8ad4cafbd725d2700a31b50526804c0330d828dd/py_sak/validation.py#L52-L57 |
241,816 | jlesquembre/doc2git | doc2git/cmdline.py | run | def run(command, get_output=False, cwd=None):
"""By default, run all commands at GITPATH directory.
If command fails, stop program execution.
"""
if cwd is None:
cwd = GITPATH
cprint('===')
cprint('=== Command: ', command)
cprint('=== CWD: ', cwd)
cprint('===')
if get... | python | def run(command, get_output=False, cwd=None):
"""By default, run all commands at GITPATH directory.
If command fails, stop program execution.
"""
if cwd is None:
cwd = GITPATH
cprint('===')
cprint('=== Command: ', command)
cprint('=== CWD: ', cwd)
cprint('===')
if get... | [
"def",
"run",
"(",
"command",
",",
"get_output",
"=",
"False",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"cwd",
"is",
"None",
":",
"cwd",
"=",
"GITPATH",
"cprint",
"(",
"'==='",
")",
"cprint",
"(",
"'=== Command: '",
",",
"command",
")",
"cprint",
"(... | By default, run all commands at GITPATH directory.
If command fails, stop program execution. | [
"By",
"default",
"run",
"all",
"commands",
"at",
"GITPATH",
"directory",
".",
"If",
"command",
"fails",
"stop",
"program",
"execution",
"."
] | 9aa5b0d220ae018573375f50bb035e700e2ca56e | https://github.com/jlesquembre/doc2git/blob/9aa5b0d220ae018573375f50bb035e700e2ca56e/doc2git/cmdline.py#L85-L105 |
241,817 | CognitionGuidedSurgery/pyclictk | clictk/argparseutil.py | build_argument_parser | def build_argument_parser(executable):
"""creates an argument parser from the given `executable` model.
An argument '__xml__' for "--xml" is added independently.
:param executable: CLI Model
:type executable: clictk.model.Executable
:return:
"""
a = ArgumentParser()
a.add_argument("--... | python | def build_argument_parser(executable):
"""creates an argument parser from the given `executable` model.
An argument '__xml__' for "--xml" is added independently.
:param executable: CLI Model
:type executable: clictk.model.Executable
:return:
"""
a = ArgumentParser()
a.add_argument("--... | [
"def",
"build_argument_parser",
"(",
"executable",
")",
":",
"a",
"=",
"ArgumentParser",
"(",
")",
"a",
".",
"add_argument",
"(",
"\"--xml\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"__xml__\"",
",",
"help",
"=",
"\"show cli xml\"",
")",
"... | creates an argument parser from the given `executable` model.
An argument '__xml__' for "--xml" is added independently.
:param executable: CLI Model
:type executable: clictk.model.Executable
:return: | [
"creates",
"an",
"argument",
"parser",
"from",
"the",
"given",
"executable",
"model",
"."
] | 74915098a24a33adb46d8738f9c4746d91ecc1dc | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/argparseutil.py#L13-L38 |
241,818 | the01/python-paps | paps/person.py | Person.from_dict | def from_dict(self, d):
"""
Set this person from dict
:param d: Dictionary representing a person ('sitting'[, 'id'])
:type d: dict
:rtype: Person
:raises KeyError: 'sitting' not set
"""
self.sitting = d['sitting']
self.id = d.get('id', None)
... | python | def from_dict(self, d):
"""
Set this person from dict
:param d: Dictionary representing a person ('sitting'[, 'id'])
:type d: dict
:rtype: Person
:raises KeyError: 'sitting' not set
"""
self.sitting = d['sitting']
self.id = d.get('id', None)
... | [
"def",
"from_dict",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"sitting",
"=",
"d",
"[",
"'sitting'",
"]",
"self",
".",
"id",
"=",
"d",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"return",
"self"
] | Set this person from dict
:param d: Dictionary representing a person ('sitting'[, 'id'])
:type d: dict
:rtype: Person
:raises KeyError: 'sitting' not set | [
"Set",
"this",
"person",
"from",
"dict"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L53-L64 |
241,819 | the01/python-paps | paps/person.py | Person.from_tuple | def from_tuple(self, t):
"""
Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person
"""
if len(t) > 1:
self.id = t[0]
self.sitting = t[1]
... | python | def from_tuple(self, t):
"""
Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person
"""
if len(t) > 1:
self.id = t[0]
self.sitting = t[1]
... | [
"def",
"from_tuple",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
">",
"1",
":",
"self",
".",
"id",
"=",
"t",
"[",
"0",
"]",
"self",
".",
"sitting",
"=",
"t",
"[",
"1",
"]",
"else",
":",
"self",
".",
"sitting",
"=",
"t",
"... | Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person | [
"Set",
"this",
"person",
"from",
"tuple"
] | 2dde5a71913e4c7b22901cf05c6ecedd890919c4 | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L75-L89 |
241,820 | hobson/pug-dj | pug/dj/explore.py | meta_bar_chart | def meta_bar_chart(series=None, N=20):
"Each column in the series is a dict of dicts"
if not series or isinstance(series, basestring):
series = json.load(load_app_meta)
if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping):
rows_received = series['# Received'].items()
... | python | def meta_bar_chart(series=None, N=20):
"Each column in the series is a dict of dicts"
if not series or isinstance(series, basestring):
series = json.load(load_app_meta)
if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping):
rows_received = series['# Received'].items()
... | [
"def",
"meta_bar_chart",
"(",
"series",
"=",
"None",
",",
"N",
"=",
"20",
")",
":",
"if",
"not",
"series",
"or",
"isinstance",
"(",
"series",
",",
"basestring",
")",
":",
"series",
"=",
"json",
".",
"load",
"(",
"load_app_meta",
")",
"if",
"isinstance"... | Each column in the series is a dict of dicts | [
"Each",
"column",
"in",
"the",
"series",
"is",
"a",
"dict",
"of",
"dicts"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L105-L138 |
241,821 | hobson/pug-dj | pug/dj/explore.py | index_with_dupes | def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1):
'''Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (... | python | def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1):
'''Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (... | [
"def",
"index_with_dupes",
"(",
"values_list",
",",
"unique_together",
"=",
"2",
",",
"model_number_i",
"=",
"0",
",",
"serial_number_i",
"=",
"1",
",",
"verbosity",
"=",
"1",
")",
":",
"try",
":",
"N",
"=",
"values_list",
".",
"count",
"(",
")",
"except... | Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]})
True | [
"Create",
"dict",
"from",
"values_list",
"with",
"first",
"N",
"values",
"as",
"a",
"compound",
"key",
"."
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L421-L461 |
241,822 | hobson/pug-dj | pug/dj/explore.py | index_model_field_batches | def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'],
key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'),
value_formatter=lambda x: str.strip(str(x)), batch_len=10000,
limit=100000000, verbosity=1):
'''Like index_model_field e... | python | def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'],
key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'),
value_formatter=lambda x: str.strip(str(x)), batch_len=10000,
limit=100000000, verbosity=1):
'''Like index_model_field e... | [
"def",
"index_model_field_batches",
"(",
"model_or_queryset",
",",
"key_fields",
"=",
"[",
"'model_number'",
",",
"'serial_number'",
"]",
",",
"value_fields",
"=",
"[",
"'pk'",
"]",
",",
"key_formatter",
"=",
"lambda",
"x",
":",
"str",
".",
"lstrip",
"(",
"str... | Like index_model_field except uses 50x less memory and 10x more processing cycles
Returns 2 dicts where both the keys and values are tuples:
target_index = {(<key_fields[0]>, <key_fields[1]>, ...): (<value_fields[0]>,)} for all distinct model-serial pairs in the Sales queryset
target_dupes = {(<key_fields... | [
"Like",
"index_model_field",
"except",
"uses",
"50x",
"less",
"memory",
"and",
"10x",
"more",
"processing",
"cycles"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L516-L577 |
241,823 | hobson/pug-dj | pug/dj/explore.py | find_index | def find_index(model_meta, weights=None, verbosity=0):
"""Return a tuple of index metadata for the model metadata dict provided
return value format is:
(
field_name,
{
'primary_key': boolean representing whether it's the primary key,
'unique': ... | python | def find_index(model_meta, weights=None, verbosity=0):
"""Return a tuple of index metadata for the model metadata dict provided
return value format is:
(
field_name,
{
'primary_key': boolean representing whether it's the primary key,
'unique': ... | [
"def",
"find_index",
"(",
"model_meta",
",",
"weights",
"=",
"None",
",",
"verbosity",
"=",
"0",
")",
":",
"weights",
"=",
"weights",
"or",
"find_index",
".",
"default_weights",
"N",
"=",
"model_meta",
"[",
"'Meta'",
"]",
".",
"get",
"(",
"'count'",
",",... | Return a tuple of index metadata for the model metadata dict provided
return value format is:
(
field_name,
{
'primary_key': boolean representing whether it's the primary key,
'unique': boolean representing whether it's a unique index
... | [
"Return",
"a",
"tuple",
"of",
"index",
"metadata",
"for",
"the",
"model",
"metadata",
"dict",
"provided"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L580-L641 |
241,824 | hobson/pug-dj | pug/dj/explore.py | count_unique | def count_unique(table, field=-1):
"""Use the Django ORM or collections.Counter to count unique values of a field in a table
`table` is one of:
1. An iterable of Django model instances for a database table (e.g. a Django queryset)
2. An iterable of dicts or lists with elements accessed by row[field] wh... | python | def count_unique(table, field=-1):
"""Use the Django ORM or collections.Counter to count unique values of a field in a table
`table` is one of:
1. An iterable of Django model instances for a database table (e.g. a Django queryset)
2. An iterable of dicts or lists with elements accessed by row[field] wh... | [
"def",
"count_unique",
"(",
"table",
",",
"field",
"=",
"-",
"1",
")",
":",
"from",
"collections",
"import",
"Counter",
"# try/except only happens once, and fastest route (straight to db) tried first",
"try",
":",
"ans",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
... | Use the Django ORM or collections.Counter to count unique values of a field in a table
`table` is one of:
1. An iterable of Django model instances for a database table (e.g. a Django queryset)
2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string
... | [
"Use",
"the",
"Django",
"ORM",
"or",
"collections",
".",
"Counter",
"to",
"count",
"unique",
"values",
"of",
"a",
"field",
"in",
"a",
"table"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L913-L941 |
241,825 | ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.startGraph | def startGraph(self):
"""Starts RDF graph and bing namespaces"""
g = r.Graph()
g.namespace_manager.bind("rdf", r.namespace.RDF)
g.namespace_manager.bind("foaf", r.namespace.FOAF)
g.namespace_manager.bind("xsd", r.namespace.XSD)
g.namespace_manager.bind("opa", ... | python | def startGraph(self):
"""Starts RDF graph and bing namespaces"""
g = r.Graph()
g.namespace_manager.bind("rdf", r.namespace.RDF)
g.namespace_manager.bind("foaf", r.namespace.FOAF)
g.namespace_manager.bind("xsd", r.namespace.XSD)
g.namespace_manager.bind("opa", ... | [
"def",
"startGraph",
"(",
"self",
")",
":",
"g",
"=",
"r",
".",
"Graph",
"(",
")",
"g",
".",
"namespace_manager",
".",
"bind",
"(",
"\"rdf\"",
",",
"r",
".",
"namespace",
".",
"RDF",
")",
"g",
".",
"namespace_manager",
".",
"bind",
"(",
"\"foaf\"",
... | Starts RDF graph and bing namespaces | [
"Starts",
"RDF",
"graph",
"and",
"bing",
"namespaces"
] | d78975038a64ea018120889d019a559409dae631 | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L102-L117 |
241,826 | ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.triplifyPortalInfo | def triplifyPortalInfo(self):
"""Make triples with information about the portal.
"""
uri=self.P.opa.ParticipationPortal+self.separator+"participabr"
self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal)
self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,s... | python | def triplifyPortalInfo(self):
"""Make triples with information about the portal.
"""
uri=self.P.opa.ParticipationPortal+self.separator+"participabr"
self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal)
self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,s... | [
"def",
"triplifyPortalInfo",
"(",
"self",
")",
":",
"uri",
"=",
"self",
".",
"P",
".",
"opa",
".",
"ParticipationPortal",
"+",
"self",
".",
"separator",
"+",
"\"participabr\"",
"self",
".",
"X",
".",
"G",
"(",
"uri",
",",
"self",
".",
"P",
".",
"rdf"... | Make triples with information about the portal. | [
"Make",
"triples",
"with",
"information",
"about",
"the",
"portal",
"."
] | d78975038a64ea018120889d019a559409dae631 | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L150-L156 |
241,827 | ttm/participationLegacy | participation/triplification/participaTriplification.py | ParticipaTriplification.triplifyOverallStructures | def triplifyOverallStructures(self):
"""Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human net... | python | def triplifyOverallStructures(self):
"""Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human net... | [
"def",
"triplifyOverallStructures",
"(",
"self",
")",
":",
"if",
"self",
".",
"compute_networks",
":",
"self",
".",
"computeNetworks",
"(",
")",
"if",
"self",
".",
"compute_bows",
":",
"self",
".",
"computeBows",
"(",
")"
] | Insert into RDF graph the textual and network structures.
Ideally, one should be able to make bag of words related to
each item (communities, users, posts, comments, tags, etc).
Interaction and friendship networks should be made.
Human networks mediated by co-ocurrance (time os posts,
... | [
"Insert",
"into",
"RDF",
"graph",
"the",
"textual",
"and",
"network",
"structures",
"."
] | d78975038a64ea018120889d019a559409dae631 | https://github.com/ttm/participationLegacy/blob/d78975038a64ea018120889d019a559409dae631/participation/triplification/participaTriplification.py#L157-L170 |
241,828 | rehandalal/buchner | buchner/project-template/manage.py | db_create | def db_create():
"""Create the database"""
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' | python | def db_create():
"""Create the database"""
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' | [
"def",
"db_create",
"(",
")",
":",
"try",
":",
"migrate_api",
".",
"version_control",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
")",
"db_upgrade",
"(",
")",
"except",
"DatabaseAlreadyControlledError",
":",
"print",
"'ERROR: Database is already ... | Create the database | [
"Create",
"the",
"database"
] | dc22a61c493b9d4a74d76e8b42a319aa13e385f3 | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L30-L36 |
241,829 | rehandalal/buchner | buchner/project-template/manage.py | db_downgrade | def db_downgrade(version):
"""Downgrade the database"""
v1 = get_db_version()
migrate_api.downgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'No changes made.'
else:
print 'Downgraded: %s ... %s' % (v1, v2) | python | def db_downgrade(version):
"""Downgrade the database"""
v1 = get_db_version()
migrate_api.downgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'No changes made.'
else:
print 'Downgraded: %s ... %s' % (v1, v2) | [
"def",
"db_downgrade",
"(",
"version",
")",
":",
"v1",
"=",
"get_db_version",
"(",
")",
"migrate_api",
".",
"downgrade",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
",",
"version",
"=",
"version",
")",
"v2",
"=",
"get_db_version",
"(",
... | Downgrade the database | [
"Downgrade",
"the",
"database"
] | dc22a61c493b9d4a74d76e8b42a319aa13e385f3 | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L40-L49 |
241,830 | rehandalal/buchner | buchner/project-template/manage.py | db_upgrade | def db_upgrade(version=None):
"""Upgrade the database"""
v1 = get_db_version()
migrate_api.upgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'Database already up-to-date.'
else:
print 'Upgraded: %s ... %s' % (v1, v2) | python | def db_upgrade(version=None):
"""Upgrade the database"""
v1 = get_db_version()
migrate_api.upgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'Database already up-to-date.'
else:
print 'Upgraded: %s ... %s' % (v1, v2) | [
"def",
"db_upgrade",
"(",
"version",
"=",
"None",
")",
":",
"v1",
"=",
"get_db_version",
"(",
")",
"migrate_api",
".",
"upgrade",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
",",
"version",
"=",
"version",
")",
"v2",
"=",
"get_db_versio... | Upgrade the database | [
"Upgrade",
"the",
"database"
] | dc22a61c493b9d4a74d76e8b42a319aa13e385f3 | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L53-L62 |
241,831 | rehandalal/buchner | buchner/project-template/manage.py | install_npm_modules | def install_npm_modules():
"""Uses npm to dependencies in node.json"""
# This is a little weird, but we do it this way because if you
# have package.json, then heroku thinks this might be a node.js
# app.
call_command('cp node.json package.json', verbose=True)
call_command('npm install', verbose... | python | def install_npm_modules():
"""Uses npm to dependencies in node.json"""
# This is a little weird, but we do it this way because if you
# have package.json, then heroku thinks this might be a node.js
# app.
call_command('cp node.json package.json', verbose=True)
call_command('npm install', verbose... | [
"def",
"install_npm_modules",
"(",
")",
":",
"# This is a little weird, but we do it this way because if you",
"# have package.json, then heroku thinks this might be a node.js",
"# app.",
"call_command",
"(",
"'cp node.json package.json'",
",",
"verbose",
"=",
"True",
")",
"call_comm... | Uses npm to dependencies in node.json | [
"Uses",
"npm",
"to",
"dependencies",
"in",
"node",
".",
"json"
] | dc22a61c493b9d4a74d76e8b42a319aa13e385f3 | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L79-L86 |
241,832 | asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | ITime.defer | def defer(
self,
func: typing.Callable[[], typing.Any],
until: typing.Union[int, float]=-1,
) -> typing.Any:
"""Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
... | python | def defer(
self,
func: typing.Callable[[], typing.Any],
until: typing.Union[int, float]=-1,
) -> typing.Any:
"""Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
... | [
"def",
"defer",
"(",
"self",
",",
"func",
":",
"typing",
".",
"Callable",
"[",
"[",
"]",
",",
"typing",
".",
"Any",
"]",
",",
"until",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"-",
"1",
",",
")",
"->",
"typing",
".",
"... | Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
arguments. All return values are ignored.
until (typing.Union[int, float]): A numeric value that represents
the clock time w... | [
"Defer",
"the",
"execution",
"of",
"a",
"function",
"until",
"some",
"clock",
"value",
"."
] | 17c589c6ab158e3d9977a6d9da6d5ecd44844285 | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L24-L50 |
241,833 | asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | ITime.delay | def delay(
self,
identifier: typing.Any,
until: typing.Union[int, float]=-1,
) -> bool:
"""Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
... | python | def delay(
self,
identifier: typing.Any,
until: typing.Union[int, float]=-1,
) -> bool:
"""Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
... | [
"def",
"delay",
"(",
"self",
",",
"identifier",
":",
"typing",
".",
"Any",
",",
"until",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"-",
"1",
",",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
until (typing.Union[int, float]): A numeric value that represents
the clock time when the callback becomes available ... | [
"Delay",
"a",
"deferred",
"function",
"until",
"the",
"given",
"time",
"."
] | 17c589c6ab158e3d9977a6d9da6d5ecd44844285 | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L76-L95 |
241,834 | davidmiller/letter | letter/contrib/contact.py | EmailForm.send_email | def send_email(self, to):
"""
Do work.
"""
body = self.body()
subject = self.subject()
import letter
class Message(letter.Letter):
Postie = letter.DjangoPostman()
From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com')
... | python | def send_email(self, to):
"""
Do work.
"""
body = self.body()
subject = self.subject()
import letter
class Message(letter.Letter):
Postie = letter.DjangoPostman()
From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com')
... | [
"def",
"send_email",
"(",
"self",
",",
"to",
")",
":",
"body",
"=",
"self",
".",
"body",
"(",
")",
"subject",
"=",
"self",
".",
"subject",
"(",
")",
"import",
"letter",
"class",
"Message",
"(",
"letter",
".",
"Letter",
")",
":",
"Postie",
"=",
"let... | Do work. | [
"Do",
"work",
"."
] | c0c66ae2c6a792106e9a8374a01421817c8a8ae0 | https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L24-L45 |
241,835 | davidmiller/letter | letter/contrib/contact.py | EmailView.form_valid | def form_valid(self, form):
"""
Praise be, someone has spammed us.
"""
form.send_email(to=self.to_addr)
return super(EmailView, self).form_valid(form) | python | def form_valid(self, form):
"""
Praise be, someone has spammed us.
"""
form.send_email(to=self.to_addr)
return super(EmailView, self).form_valid(form) | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"form",
".",
"send_email",
"(",
"to",
"=",
"self",
".",
"to_addr",
")",
"return",
"super",
"(",
"EmailView",
",",
"self",
")",
".",
"form_valid",
"(",
"form",
")"
] | Praise be, someone has spammed us. | [
"Praise",
"be",
"someone",
"has",
"spammed",
"us",
"."
] | c0c66ae2c6a792106e9a8374a01421817c8a8ae0 | https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/contrib/contact.py#L87-L92 |
241,836 | tevino/mongu | mongu.py | Client.register_model | def register_model(self, model_cls):
"""Decorator for registering model."""
if not getattr(model_cls, '_database_'):
raise ModelAttributeError('_database_ missing '
'on %s!' % model_cls.__name__)
if not getattr(model_cls, '_collection_'):
... | python | def register_model(self, model_cls):
"""Decorator for registering model."""
if not getattr(model_cls, '_database_'):
raise ModelAttributeError('_database_ missing '
'on %s!' % model_cls.__name__)
if not getattr(model_cls, '_collection_'):
... | [
"def",
"register_model",
"(",
"self",
",",
"model_cls",
")",
":",
"if",
"not",
"getattr",
"(",
"model_cls",
",",
"'_database_'",
")",
":",
"raise",
"ModelAttributeError",
"(",
"'_database_ missing '",
"'on %s!'",
"%",
"model_cls",
".",
"__name__",
")",
"if",
"... | Decorator for registering model. | [
"Decorator",
"for",
"registering",
"model",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L34-L46 |
241,837 | tevino/mongu | mongu.py | Client.enable_counter | def enable_counter(self, base=None, database='counter',
collection='counters'):
"""Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
... | python | def enable_counter(self, base=None, database='counter',
collection='counters'):
"""Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
... | [
"def",
"enable_counter",
"(",
"self",
",",
"base",
"=",
"None",
",",
"database",
"=",
"'counter'",
",",
"collection",
"=",
"'counters'",
")",
":",
"Counter",
".",
"_database_",
"=",
"database",
"Counter",
".",
"_collection_",
"=",
"collection",
"bases",
"=",... | Register the builtin counter model, return the registered Counter
class and the corresponding ``CounterMixin`` class.
The ``CounterMixin`` automatically increases and decreases the counter
after model creation(save without ``_id``) and deletion.
It contains a classmethod ``count()`` wh... | [
"Register",
"the",
"builtin",
"counter",
"model",
"return",
"the",
"registered",
"Counter",
"class",
"and",
"the",
"corresponding",
"CounterMixin",
"class",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L48-L100 |
241,838 | tevino/mongu | mongu.py | Model.by_id | def by_id(cls, oid):
"""Find a model object by its ``ObjectId``,
``oid`` can be string or ObjectId"""
if oid:
d = cls.collection.find_one(ObjectId(oid))
if d:
return cls(**d) | python | def by_id(cls, oid):
"""Find a model object by its ``ObjectId``,
``oid`` can be string or ObjectId"""
if oid:
d = cls.collection.find_one(ObjectId(oid))
if d:
return cls(**d) | [
"def",
"by_id",
"(",
"cls",
",",
"oid",
")",
":",
"if",
"oid",
":",
"d",
"=",
"cls",
".",
"collection",
".",
"find_one",
"(",
"ObjectId",
"(",
"oid",
")",
")",
"if",
"d",
":",
"return",
"cls",
"(",
"*",
"*",
"d",
")"
] | Find a model object by its ``ObjectId``,
``oid`` can be string or ObjectId | [
"Find",
"a",
"model",
"object",
"by",
"its",
"ObjectId",
"oid",
"can",
"be",
"string",
"or",
"ObjectId"
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L164-L170 |
241,839 | tevino/mongu | mongu.py | Model.from_dict | def from_dict(cls, d):
"""Build model object from a dict. Will be removed in v1.0"""
warnings.warn(
'from_dict is deprecated and will be removed in v1.0!',
stacklevel=2)
d = d or {}
return cls(**d) | python | def from_dict(cls, d):
"""Build model object from a dict. Will be removed in v1.0"""
warnings.warn(
'from_dict is deprecated and will be removed in v1.0!',
stacklevel=2)
d = d or {}
return cls(**d) | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"warnings",
".",
"warn",
"(",
"'from_dict is deprecated and will be removed in v1.0!'",
",",
"stacklevel",
"=",
"2",
")",
"d",
"=",
"d",
"or",
"{",
"}",
"return",
"cls",
"(",
"*",
"*",
"d",
")"
] | Build model object from a dict. Will be removed in v1.0 | [
"Build",
"model",
"object",
"from",
"a",
"dict",
".",
"Will",
"be",
"removed",
"in",
"v1",
".",
"0"
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L180-L186 |
241,840 | tevino/mongu | mongu.py | Model.find | def find(cls, *args, **kwargs):
"""Same as ``collection.find``, returns model object instead of dict."""
return cls.from_cursor(cls.collection.find(*args, **kwargs)) | python | def find(cls, *args, **kwargs):
"""Same as ``collection.find``, returns model object instead of dict."""
return cls.from_cursor(cls.collection.find(*args, **kwargs)) | [
"def",
"find",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"from_cursor",
"(",
"cls",
".",
"collection",
".",
"find",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Same as ``collection.find``, returns model object instead of dict. | [
"Same",
"as",
"collection",
".",
"find",
"returns",
"model",
"object",
"instead",
"of",
"dict",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L195-L197 |
241,841 | tevino/mongu | mongu.py | Model.find_one | def find_one(cls, *args, **kwargs):
"""Same as ``collection.find_one``, returns model object instead of
dict."""
d = cls.collection.find_one(*args, **kwargs)
if d:
return cls(**d) | python | def find_one(cls, *args, **kwargs):
"""Same as ``collection.find_one``, returns model object instead of
dict."""
d = cls.collection.find_one(*args, **kwargs)
if d:
return cls(**d) | [
"def",
"find_one",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"cls",
".",
"collection",
".",
"find_one",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"d",
":",
"return",
"cls",
"(",
"*",
"*",
"d",
")"
... | Same as ``collection.find_one``, returns model object instead of
dict. | [
"Same",
"as",
"collection",
".",
"find_one",
"returns",
"model",
"object",
"instead",
"of",
"dict",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L200-L205 |
241,842 | tevino/mongu | mongu.py | Model.reload | def reload(self, d=None):
"""Reload model from given dict or database."""
if d:
self.clear()
self.update(d)
elif self.id:
new_dict = self.by_id(self._id)
self.clear()
self.update(new_dict)
else:
# should I raise an e... | python | def reload(self, d=None):
"""Reload model from given dict or database."""
if d:
self.clear()
self.update(d)
elif self.id:
new_dict = self.by_id(self._id)
self.clear()
self.update(new_dict)
else:
# should I raise an e... | [
"def",
"reload",
"(",
"self",
",",
"d",
"=",
"None",
")",
":",
"if",
"d",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"update",
"(",
"d",
")",
"elif",
"self",
".",
"id",
":",
"new_dict",
"=",
"self",
".",
"by_id",
"(",
"self",
".",
"_id... | Reload model from given dict or database. | [
"Reload",
"model",
"from",
"given",
"dict",
"or",
"database",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L213-L225 |
241,843 | tevino/mongu | mongu.py | Model.save | def save(self):
"""Save model object to database."""
d = dict(self)
old_dict = d.copy()
_id = self.collection.save(d)
self._id = _id
self.on_save(old_dict)
return self._id | python | def save(self):
"""Save model object to database."""
d = dict(self)
old_dict = d.copy()
_id = self.collection.save(d)
self._id = _id
self.on_save(old_dict)
return self._id | [
"def",
"save",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"self",
")",
"old_dict",
"=",
"d",
".",
"copy",
"(",
")",
"_id",
"=",
"self",
".",
"collection",
".",
"save",
"(",
"d",
")",
"self",
".",
"_id",
"=",
"_id",
"self",
".",
"on_save",
... | Save model object to database. | [
"Save",
"model",
"object",
"to",
"database",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L231-L238 |
241,844 | tevino/mongu | mongu.py | Model.delete | def delete(self):
"""Remove from database."""
if not self.id:
return
self.collection.remove({'_id': self._id})
self.on_delete(self) | python | def delete(self):
"""Remove from database."""
if not self.id:
return
self.collection.remove({'_id': self._id})
self.on_delete(self) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"id",
":",
"return",
"self",
".",
"collection",
".",
"remove",
"(",
"{",
"'_id'",
":",
"self",
".",
"_id",
"}",
")",
"self",
".",
"on_delete",
"(",
"self",
")"
] | Remove from database. | [
"Remove",
"from",
"database",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L244-L249 |
241,845 | tevino/mongu | mongu.py | Counter.set_to | def set_to(cls, name, num):
"""Set counter of ``name`` to ``num``."""
if num < 0:
raise CounterValueError('Counter[%s] can not be set to %s' % (
name, num))
else:
counter = cls.collection.find_and_modify(
{'name': name},... | python | def set_to(cls, name, num):
"""Set counter of ``name`` to ``num``."""
if num < 0:
raise CounterValueError('Counter[%s] can not be set to %s' % (
name, num))
else:
counter = cls.collection.find_and_modify(
{'name': name},... | [
"def",
"set_to",
"(",
"cls",
",",
"name",
",",
"num",
")",
":",
"if",
"num",
"<",
"0",
":",
"raise",
"CounterValueError",
"(",
"'Counter[%s] can not be set to %s'",
"%",
"(",
"name",
",",
"num",
")",
")",
"else",
":",
"counter",
"=",
"cls",
".",
"colle... | Set counter of ``name`` to ``num``. | [
"Set",
"counter",
"of",
"name",
"to",
"num",
"."
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L255-L267 |
241,846 | tevino/mongu | mongu.py | Counter.count | def count(cls, name):
"""Return the count of ``name``"""
counter = cls.collection.find_one({'name': name}) or {}
return counter.get('seq', 0) | python | def count(cls, name):
"""Return the count of ``name``"""
counter = cls.collection.find_one({'name': name}) or {}
return counter.get('seq', 0) | [
"def",
"count",
"(",
"cls",
",",
"name",
")",
":",
"counter",
"=",
"cls",
".",
"collection",
".",
"find_one",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"or",
"{",
"}",
"return",
"counter",
".",
"get",
"(",
"'seq'",
",",
"0",
")"
] | Return the count of ``name`` | [
"Return",
"the",
"count",
"of",
"name"
] | 98f15cdb9e5906062f2d5088c7bf774ab007c6e5 | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L296-L299 |
241,847 | gear11/pypelogs | pypein/wikip.py | geo_filter | def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates."""
page = d["page"]
if not "revision" in page:
return None
... | python | def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates."""
page = d["page"]
if not "revision" in page:
return None
... | [
"def",
"geo_filter",
"(",
"d",
")",
":",
"page",
"=",
"d",
"[",
"\"page\"",
"]",
"if",
"not",
"\"revision\"",
"in",
"page",
":",
"return",
"None",
"title",
"=",
"page",
"[",
"\"title\"",
"]",
"if",
"skip_article",
"(",
"title",
")",
":",
"LOG",
".",
... | Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates. | [
"Inspects",
"the",
"given",
"Wikipedia",
"article",
"dict",
"for",
"geo",
"-",
"coordinates",
"."
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L76-L111 |
241,848 | gear11/pypelogs | pypein/wikip.py | depipe | def depipe(s):
"""Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees"""
n = 0
for i in reversed(s.split('|')):
n = n / 60.0 + float(i)
return n | python | def depipe(s):
"""Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees"""
n = 0
for i in reversed(s.split('|')):
n = n / 60.0 + float(i)
return n | [
"def",
"depipe",
"(",
"s",
")",
":",
"n",
"=",
"0",
"for",
"i",
"in",
"reversed",
"(",
"s",
".",
"split",
"(",
"'|'",
")",
")",
":",
"n",
"=",
"n",
"/",
"60.0",
"+",
"float",
"(",
"i",
")",
"return",
"n"
] | Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees | [
"Convert",
"a",
"string",
"of",
"the",
"form",
"DD",
"or",
"DD|MM",
"or",
"DD|MM|SS",
"to",
"decimal",
"degrees"
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L179-L184 |
241,849 | gear11/pypelogs | pypein/wikip.py | skip_coords | def skip_coords(c):
"""Skip coordinate strings that are not valid"""
if c == "{{coord|LAT|LONG|display=inline,title}}": # Unpopulated coord template
return True
if c.find("globe:") >= 0 and c.find("globe:earth") == -1: # Moon, venus, etc.
return True
return False | python | def skip_coords(c):
"""Skip coordinate strings that are not valid"""
if c == "{{coord|LAT|LONG|display=inline,title}}": # Unpopulated coord template
return True
if c.find("globe:") >= 0 and c.find("globe:earth") == -1: # Moon, venus, etc.
return True
return False | [
"def",
"skip_coords",
"(",
"c",
")",
":",
"if",
"c",
"==",
"\"{{coord|LAT|LONG|display=inline,title}}\"",
":",
"# Unpopulated coord template",
"return",
"True",
"if",
"c",
".",
"find",
"(",
"\"globe:\"",
")",
">=",
"0",
"and",
"c",
".",
"find",
"(",
"\"globe:e... | Skip coordinate strings that are not valid | [
"Skip",
"coordinate",
"strings",
"that",
"are",
"not",
"valid"
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/wikip.py#L186-L192 |
241,850 | lukaszb/porunga | porunga/procme.py | Command.iter_output | def iter_output(self, pause=0.05):
"""
Returns iterator of chunked output.
:param cmd: command that would be passed to ``subprocess.Popen``
:param shell: Tells if process should be run within a shell. Default: False
:param timeout: If command exceeds given ``timeout`` in seconds... | python | def iter_output(self, pause=0.05):
"""
Returns iterator of chunked output.
:param cmd: command that would be passed to ``subprocess.Popen``
:param shell: Tells if process should be run within a shell. Default: False
:param timeout: If command exceeds given ``timeout`` in seconds... | [
"def",
"iter_output",
"(",
"self",
",",
"pause",
"=",
"0.05",
")",
":",
"with",
"self",
".",
"stream",
"as",
"temp",
":",
"for",
"chunk",
"in",
"self",
".",
"iter_output_for_stream",
"(",
"temp",
",",
"pause",
"=",
"pause",
")",
":",
"yield",
"chunk"
] | Returns iterator of chunked output.
:param cmd: command that would be passed to ``subprocess.Popen``
:param shell: Tells if process should be run within a shell. Default: False
:param timeout: If command exceeds given ``timeout`` in seconds,
``TimeoutExceeded`` exception would be raised... | [
"Returns",
"iterator",
"of",
"chunked",
"output",
"."
] | 13177ff9bc654ac25cf09def6b526eb38e40e483 | https://github.com/lukaszb/porunga/blob/13177ff9bc654ac25cf09def6b526eb38e40e483/porunga/procme.py#L74-L93 |
241,851 | peepall/FancyLogger | FancyLogger/__init__.py | FancyLogger.terminate | def terminate(self):
"""
Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some
messages of progresses that have not been displayed yet. This method blocks until logger process has stopped.
"""
self.queue.put(dill.dumps(ExitComma... | python | def terminate(self):
"""
Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some
messages of progresses that have not been displayed yet. This method blocks until logger process has stopped.
"""
self.queue.put(dill.dumps(ExitComma... | [
"def",
"terminate",
"(",
"self",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"dill",
".",
"dumps",
"(",
"ExitCommand",
"(",
")",
")",
")",
"if",
"self",
".",
"process",
":",
"self",
".",
"process",
".",
"join",
"(",
")"
] | Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some
messages of progresses that have not been displayed yet. This method blocks until logger process has stopped. | [
"Tells",
"the",
"logger",
"process",
"to",
"exit",
"immediately",
".",
"If",
"you",
"do",
"not",
"call",
"flush",
"method",
"before",
"you",
"may",
"lose",
"some",
"messages",
"of",
"progresses",
"that",
"have",
"not",
"been",
"displayed",
"yet",
".",
"Thi... | 7f13f1397e76ed768fb6b6358194118831fafc6d | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L217-L225 |
241,852 | alkivi-sas/python-alkivi-logger | alkivi/logger/handlers.py | AlkiviEmailHandler.generate_mail | def generate_mail(self):
"""Generate the email as MIMEText
"""
# Script info
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n"
msg = msg + "%-9s: %s" % ('User', USER) + "\r\n"
msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n"
... | python | def generate_mail(self):
"""Generate the email as MIMEText
"""
# Script info
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n"
msg = msg + "%-9s: %s" % ('User', USER) + "\r\n"
msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n"
... | [
"def",
"generate_mail",
"(",
"self",
")",
":",
"# Script info",
"msg",
"=",
"\"Script info : \\r\\n\"",
"msg",
"=",
"msg",
"+",
"\"%-9s: %s\"",
"%",
"(",
"'Script'",
",",
"SOURCEDIR",
")",
"+",
"\"\\r\\n\"",
"msg",
"=",
"msg",
"+",
"\"%-9s: %s\"",
"%",
"(",
... | Generate the email as MIMEText | [
"Generate",
"the",
"email",
"as",
"MIMEText"
] | e96d5a987a5c8789c51d4fa7541709e05b1f51e1 | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/handlers.py#L57-L100 |
241,853 | alkivi-sas/python-alkivi-logger | alkivi/logger/handlers.py | AlkiviEmailHandler.get_subject | def get_subject(self):
"""Generate the subject."""
level = logging.getLevelName(self.flush_level)
message = self.current_buffer[0].split("\n")[0]
message = message.split(']')[-1]
return '{0} : {1}{2}'.format(level, SOURCE, message) | python | def get_subject(self):
"""Generate the subject."""
level = logging.getLevelName(self.flush_level)
message = self.current_buffer[0].split("\n")[0]
message = message.split(']')[-1]
return '{0} : {1}{2}'.format(level, SOURCE, message) | [
"def",
"get_subject",
"(",
"self",
")",
":",
"level",
"=",
"logging",
".",
"getLevelName",
"(",
"self",
".",
"flush_level",
")",
"message",
"=",
"self",
".",
"current_buffer",
"[",
"0",
"]",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"0",
"]",
"message",
... | Generate the subject. | [
"Generate",
"the",
"subject",
"."
] | e96d5a987a5c8789c51d4fa7541709e05b1f51e1 | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/handlers.py#L102-L107 |
241,854 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigEntryFormatter.format_query_result | def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None):
""" Formats the query result based on the return type requested.
:param query_result: (dict or str or list), yaml query result
:param query_path: (str, list(str)), representing query path
:p... | python | def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None):
""" Formats the query result based on the return type requested.
:param query_result: (dict or str or list), yaml query result
:param query_path: (str, list(str)), representing query path
:p... | [
"def",
"format_query_result",
"(",
"self",
",",
"query_result",
",",
"query_path",
",",
"return_type",
"=",
"list",
",",
"preceding_depth",
"=",
"None",
")",
":",
"if",
"type",
"(",
"query_result",
")",
"!=",
"return_type",
":",
"converted_result",
"=",
"self"... | Formats the query result based on the return type requested.
:param query_result: (dict or str or list), yaml query result
:param query_path: (str, list(str)), representing query path
:param return_type: type, return type of object user desires
:param preceding_depth: int, the depth to ... | [
"Formats",
"the",
"query",
"result",
"based",
"on",
"the",
"return",
"type",
"requested",
"."
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L13-L29 |
241,855 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigEntryFormatter.format_with_handler | def format_with_handler(self, query_result, return_type):
""" Uses the callable handler to format the query result to the desired return type
:param query_result: the result value of our query
:param return_type: desired return type
:return: type, the query value as the return type requ... | python | def format_with_handler(self, query_result, return_type):
""" Uses the callable handler to format the query result to the desired return type
:param query_result: the result value of our query
:param return_type: desired return type
:return: type, the query value as the return type requ... | [
"def",
"format_with_handler",
"(",
"self",
",",
"query_result",
",",
"return_type",
")",
":",
"handler",
"=",
"self",
".",
"get_handler",
"(",
"type",
"(",
"query_result",
")",
",",
"return_type",
")",
"return",
"handler",
".",
"format_result",
"(",
"query_res... | Uses the callable handler to format the query result to the desired return type
:param query_result: the result value of our query
:param return_type: desired return type
:return: type, the query value as the return type requested | [
"Uses",
"the",
"callable",
"handler",
"to",
"format",
"the",
"query",
"result",
"to",
"the",
"desired",
"return",
"type"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L31-L39 |
241,856 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigEntryFormatter.get_handler | def get_handler(query_result_type, return_type):
""" Find the appropriate return type handler to convert the query result to the desired return type
:param query_result_type: type, desired return type
:param return_type: type, actual return type
:return: callable, function that will han... | python | def get_handler(query_result_type, return_type):
""" Find the appropriate return type handler to convert the query result to the desired return type
:param query_result_type: type, desired return type
:param return_type: type, actual return type
:return: callable, function that will han... | [
"def",
"get_handler",
"(",
"query_result_type",
",",
"return_type",
")",
":",
"try",
":",
"return",
"FormatterRegistry",
".",
"get_by_take_and_return_type",
"(",
"query_result_type",
",",
"return_type",
")",
"except",
"(",
"IndexError",
",",
"AttributeError",
",",
"... | Find the appropriate return type handler to convert the query result to the desired return type
:param query_result_type: type, desired return type
:param return_type: type, actual return type
:return: callable, function that will handle the conversion | [
"Find",
"the",
"appropriate",
"return",
"type",
"handler",
"to",
"convert",
"the",
"query",
"result",
"to",
"the",
"desired",
"return",
"type"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L42-L54 |
241,857 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigEntryFormatter.add_preceding_dict | def add_preceding_dict(config_entry, query_path, preceding_depth):
""" Adds the preceeding config keys to the config_entry to simulate the original full path to the config entry
:param config_entry: object, the entry that was requested and returned from the config
:param query_path: (str, list(... | python | def add_preceding_dict(config_entry, query_path, preceding_depth):
""" Adds the preceeding config keys to the config_entry to simulate the original full path to the config entry
:param config_entry: object, the entry that was requested and returned from the config
:param query_path: (str, list(... | [
"def",
"add_preceding_dict",
"(",
"config_entry",
",",
"query_path",
",",
"preceding_depth",
")",
":",
"if",
"preceding_depth",
"is",
"None",
":",
"return",
"config_entry",
"preceding_dict",
"=",
"{",
"query_path",
"[",
"-",
"1",
"]",
":",
"config_entry",
"}",
... | Adds the preceeding config keys to the config_entry to simulate the original full path to the config entry
:param config_entry: object, the entry that was requested and returned from the config
:param query_path: (str, list(str)), the original path to the config_entry
:param preceding_depth: in... | [
"Adds",
"the",
"preceeding",
"config",
"keys",
"to",
"the",
"config_entry",
"to",
"simulate",
"the",
"original",
"full",
"path",
"to",
"the",
"config",
"entry"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L57-L75 |
241,858 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigParse.rebuild_config_cache | def rebuild_config_cache(self, config_filepath):
""" Loads from file and caches all data from the config file in the form of an OrderedDict to self.data
:param config_filepath: str, the full filepath to the config file
:return: bool, success status
"""
self.validate_config_file(... | python | def rebuild_config_cache(self, config_filepath):
""" Loads from file and caches all data from the config file in the form of an OrderedDict to self.data
:param config_filepath: str, the full filepath to the config file
:return: bool, success status
"""
self.validate_config_file(... | [
"def",
"rebuild_config_cache",
"(",
"self",
",",
"config_filepath",
")",
":",
"self",
".",
"validate_config_file",
"(",
"config_filepath",
")",
"config_data",
"=",
"None",
"try",
":",
"with",
"open",
"(",
"config_filepath",
",",
"'r'",
")",
"as",
"f",
":",
"... | Loads from file and caches all data from the config file in the form of an OrderedDict to self.data
:param config_filepath: str, the full filepath to the config file
:return: bool, success status | [
"Loads",
"from",
"file",
"and",
"caches",
"all",
"data",
"from",
"the",
"config",
"file",
"in",
"the",
"form",
"of",
"an",
"OrderedDict",
"to",
"self",
".",
"data"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L111-L128 |
241,859 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigParse.get | def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False):
""" Traverses the list of query paths to find the data requested
:param query_path: (list(str), str), list of query path branches or query string
Default b... | python | def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False):
""" Traverses the list of query paths to find the data requested
:param query_path: (list(str), str), list of query path branches or query string
Default b... | [
"def",
"get",
"(",
"self",
",",
"query_path",
"=",
"None",
",",
"return_type",
"=",
"list",
",",
"preceding_depth",
"=",
"None",
",",
"throw_null_return_error",
"=",
"False",
")",
":",
"function_type_lookup",
"=",
"{",
"str",
":",
"self",
".",
"_get_path_ent... | Traverses the list of query paths to find the data requested
:param query_path: (list(str), str), list of query path branches or query string
Default behavior: returns list(str) of possible config headers
:param return_type: (list, str, dict, OrderedDict), d... | [
"Traverses",
"the",
"list",
"of",
"query",
"paths",
"to",
"find",
"the",
"data",
"requested"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L130-L158 |
241,860 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigParse._get_path_entry_from_string | def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False):
""" Parses a string to form a list of strings that represents a possible config entry header
:param query_string: str, query string we are looking for
:param first_found: bool, return first found entry or en... | python | def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False):
""" Parses a string to form a list of strings that represents a possible config entry header
:param query_string: str, query string we are looking for
:param first_found: bool, return first found entry or en... | [
"def",
"_get_path_entry_from_string",
"(",
"self",
",",
"query_string",
",",
"first_found",
"=",
"True",
",",
"full_path",
"=",
"False",
")",
":",
"iter_matches",
"=",
"gen_dict_key_matches",
"(",
"query_string",
",",
"self",
".",
"config_file_contents",
",",
"ful... | Parses a string to form a list of strings that represents a possible config entry header
:param query_string: str, query string we are looking for
:param first_found: bool, return first found entry or entire list
:param full_path: bool, whether to return each entry with their corresponding conf... | [
"Parses",
"a",
"string",
"to",
"form",
"a",
"list",
"of",
"strings",
"that",
"represents",
"a",
"possible",
"config",
"entry",
"header"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L160-L174 |
241,861 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigParse._get_path_entry_from_list | def _get_path_entry_from_list(self, query_path):
""" Returns the config entry at query path
:param query_path: list(str), config header path to follow for entry
:return: (list, str, dict, OrderedDict), config entry requested
:raises: exceptions.ResourceNotFoundError
"""
... | python | def _get_path_entry_from_list(self, query_path):
""" Returns the config entry at query path
:param query_path: list(str), config header path to follow for entry
:return: (list, str, dict, OrderedDict), config entry requested
:raises: exceptions.ResourceNotFoundError
"""
... | [
"def",
"_get_path_entry_from_list",
"(",
"self",
",",
"query_path",
")",
":",
"cur_data",
"=",
"self",
".",
"config_file_contents",
"try",
":",
"for",
"child",
"in",
"query_path",
":",
"cur_data",
"=",
"cur_data",
"[",
"child",
"]",
"return",
"cur_data",
"exce... | Returns the config entry at query path
:param query_path: list(str), config header path to follow for entry
:return: (list, str, dict, OrderedDict), config entry requested
:raises: exceptions.ResourceNotFoundError | [
"Returns",
"the",
"config",
"entry",
"at",
"query",
"path"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L176-L190 |
241,862 | AndresMWeber/Nomenclate | nomenclate/core/configurator.py | ConfigParse.validate_config_file | def validate_config_file(cls, config_filepath):
""" Validates the filepath to the config. Detects whether it is a true YAML file + existance
:param config_filepath: str, file path to the config file to query
:return: None
:raises: IOError
"""
is_file = os.path.isfile(co... | python | def validate_config_file(cls, config_filepath):
""" Validates the filepath to the config. Detects whether it is a true YAML file + existance
:param config_filepath: str, file path to the config file to query
:return: None
:raises: IOError
"""
is_file = os.path.isfile(co... | [
"def",
"validate_config_file",
"(",
"cls",
",",
"config_filepath",
")",
":",
"is_file",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"config_filepath",
")",
"if",
"not",
"is_file",
"and",
"os",
".",
"path",
".",
"isabs",
"(",
"config_filepath",
")",
":",
... | Validates the filepath to the config. Detects whether it is a true YAML file + existance
:param config_filepath: str, file path to the config file to query
:return: None
:raises: IOError | [
"Validates",
"the",
"filepath",
"to",
"the",
"config",
".",
"Detects",
"whether",
"it",
"is",
"a",
"true",
"YAML",
"file",
"+",
"existance"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L203-L220 |
241,863 | luismasuelli/python-cantrips | cantrips/features.py | Feature.import_it | def import_it(cls):
"""
Performs the import only once.
"""
if not cls in cls._FEATURES:
try:
cls._FEATURES[cls] = cls._import_it()
except ImportError:
raise cls.Error(cls._import_error_message(), cls.Error.UNSATISFIED_IMPORT_REQ)
... | python | def import_it(cls):
"""
Performs the import only once.
"""
if not cls in cls._FEATURES:
try:
cls._FEATURES[cls] = cls._import_it()
except ImportError:
raise cls.Error(cls._import_error_message(), cls.Error.UNSATISFIED_IMPORT_REQ)
... | [
"def",
"import_it",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
"in",
"cls",
".",
"_FEATURES",
":",
"try",
":",
"cls",
".",
"_FEATURES",
"[",
"cls",
"]",
"=",
"cls",
".",
"_import_it",
"(",
")",
"except",
"ImportError",
":",
"raise",
"cls",
".",
"Err... | Performs the import only once. | [
"Performs",
"the",
"import",
"only",
"once",
"."
] | dba2742c1d1a60863bb65f4a291464f6e68eb2ee | https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/features.py#L12-L21 |
241,864 | goldsborough/li | li/cache.py | read | def read(author, kind):
"""
Attempts to read the cache to fetch missing arguments.
This method will attempt to find a '.license' file in the
'CACHE_DIRECTORY', to read any arguments that were not passed to the
license utility.
Arguments:
author (str): The author passed, if any.
k... | python | def read(author, kind):
"""
Attempts to read the cache to fetch missing arguments.
This method will attempt to find a '.license' file in the
'CACHE_DIRECTORY', to read any arguments that were not passed to the
license utility.
Arguments:
author (str): The author passed, if any.
k... | [
"def",
"read",
"(",
"author",
",",
"kind",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"CACHE_PATH",
")",
":",
"raise",
"LicenseError",
"(",
"'No cache found. You must '",
"'supply at least -a and -k.'",
")",
"cache",
"=",
"read_cache",
"(",
... | Attempts to read the cache to fetch missing arguments.
This method will attempt to find a '.license' file in the
'CACHE_DIRECTORY', to read any arguments that were not passed to the
license utility.
Arguments:
author (str): The author passed, if any.
kind (str): The kind of license pas... | [
"Attempts",
"to",
"read",
"the",
"cache",
"to",
"fetch",
"missing",
"arguments",
"."
] | 8ea4f8b55183aadaa96bc70cfcfcb7b198874319 | https://github.com/goldsborough/li/blob/8ea4f8b55183aadaa96bc70cfcfcb7b198874319/li/cache.py#L26-L53 |
241,865 | Baguage/django-auth-pubtkt | django_auth_pubtkt/auth_pubtkt.py | Authpubtkt.verify_ticket_signature | def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
... | python | def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
... | [
"def",
"verify_ticket_signature",
"(",
"self",
",",
"data",
",",
"sig",
")",
":",
"try",
":",
"signature",
"=",
"base64",
".",
"b64decode",
"(",
"sig",
")",
"except",
"TypeError",
"as",
"e",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"debug\"",
")",
":"... | Verify ticket signature. | [
"Verify",
"ticket",
"signature",
"."
] | d3f4284212ffbfdc3588929a31e36a4cc7f39786 | https://github.com/Baguage/django-auth-pubtkt/blob/d3f4284212ffbfdc3588929a31e36a4cc7f39786/django_auth_pubtkt/auth_pubtkt.py#L45-L73 |
241,866 | krukas/Trionyx | trionyx/trionyx/apps.py | Config.ready | def ready(self):
"""Auto load Trionyx"""
models_config.auto_load_configs()
self.auto_load_app_modules(['layouts', 'signals'])
app_menu.auto_load_model_menu()
auto_register_search_models()
tabs.auto_generate_missing_tabs() | python | def ready(self):
"""Auto load Trionyx"""
models_config.auto_load_configs()
self.auto_load_app_modules(['layouts', 'signals'])
app_menu.auto_load_model_menu()
auto_register_search_models()
tabs.auto_generate_missing_tabs() | [
"def",
"ready",
"(",
"self",
")",
":",
"models_config",
".",
"auto_load_configs",
"(",
")",
"self",
".",
"auto_load_app_modules",
"(",
"[",
"'layouts'",
",",
"'signals'",
"]",
")",
"app_menu",
".",
"auto_load_model_menu",
"(",
")",
"auto_register_search_models",
... | Auto load Trionyx | [
"Auto",
"load",
"Trionyx"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/apps.py#L36-L45 |
241,867 | krukas/Trionyx | trionyx/trionyx/apps.py | Config.auto_load_app_modules | def auto_load_app_modules(self, modules):
"""Auto load app modules"""
for app in apps.get_app_configs():
for module in modules:
try:
import_module('{}.{}'.format(app.module.__package__, module))
except ImportError:
pass | python | def auto_load_app_modules(self, modules):
"""Auto load app modules"""
for app in apps.get_app_configs():
for module in modules:
try:
import_module('{}.{}'.format(app.module.__package__, module))
except ImportError:
pass | [
"def",
"auto_load_app_modules",
"(",
"self",
",",
"modules",
")",
":",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"for",
"module",
"in",
"modules",
":",
"try",
":",
"import_module",
"(",
"'{}.{}'",
".",
"format",
"(",
"app",
".",
... | Auto load app modules | [
"Auto",
"load",
"app",
"modules"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/apps.py#L47-L54 |
241,868 | goldsborough/li | scripts/bump.py | bump | def bump(match):
"""Bumps the version"""
before, old_version, after = match.groups()
major, minor, patch = map(int, old_version.split('.'))
patch += 1
if patch == 10:
patch = 0
minor += 1
if minor == 10:
minor = 0
major += 1
new_version = '{0}.{1}.{2}'.format(major, minor, patch)
print('{0} => {1}'.... | python | def bump(match):
"""Bumps the version"""
before, old_version, after = match.groups()
major, minor, patch = map(int, old_version.split('.'))
patch += 1
if patch == 10:
patch = 0
minor += 1
if minor == 10:
minor = 0
major += 1
new_version = '{0}.{1}.{2}'.format(major, minor, patch)
print('{0} => {1}'.... | [
"def",
"bump",
"(",
"match",
")",
":",
"before",
",",
"old_version",
",",
"after",
"=",
"match",
".",
"groups",
"(",
")",
"major",
",",
"minor",
",",
"patch",
"=",
"map",
"(",
"int",
",",
"old_version",
".",
"split",
"(",
"'.'",
")",
")",
"patch",
... | Bumps the version | [
"Bumps",
"the",
"version"
] | 8ea4f8b55183aadaa96bc70cfcfcb7b198874319 | https://github.com/goldsborough/li/blob/8ea4f8b55183aadaa96bc70cfcfcb7b198874319/scripts/bump.py#L11-L26 |
241,869 | wadoon/ansitagcolor | ansitagcolor.py | term._write_raw | def _write_raw(self, suffix):
"""
writes a the suffix prefixed by the CSI to the handle
"""
if not self.enabled: return
self.buffer.write(CSI)
self.buffer.write(suffix) | python | def _write_raw(self, suffix):
"""
writes a the suffix prefixed by the CSI to the handle
"""
if not self.enabled: return
self.buffer.write(CSI)
self.buffer.write(suffix) | [
"def",
"_write_raw",
"(",
"self",
",",
"suffix",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"return",
"self",
".",
"buffer",
".",
"write",
"(",
"CSI",
")",
"self",
".",
"buffer",
".",
"write",
"(",
"suffix",
")"
] | writes a the suffix prefixed by the CSI to the handle | [
"writes",
"a",
"the",
"suffix",
"prefixed",
"by",
"the",
"CSI",
"to",
"the",
"handle"
] | 7247ee8ec3b91590a07c68a7889ec87c5137b82d | https://github.com/wadoon/ansitagcolor/blob/7247ee8ec3b91590a07c68a7889ec87c5137b82d/ansitagcolor.py#L191-L198 |
241,870 | Kopachris/seshet | seshet/config.py | build_db_tables | def build_db_tables(db):
"""Build Seshet's basic database schema. Requires one parameter,
`db` as `pydal.DAL` instance.
"""
if not isinstance(db, DAL) or not db._uri:
raise Exception("Need valid DAL object to define tables")
# event log - self-explanatory, logs all events
db.define... | python | def build_db_tables(db):
"""Build Seshet's basic database schema. Requires one parameter,
`db` as `pydal.DAL` instance.
"""
if not isinstance(db, DAL) or not db._uri:
raise Exception("Need valid DAL object to define tables")
# event log - self-explanatory, logs all events
db.define... | [
"def",
"build_db_tables",
"(",
"db",
")",
":",
"if",
"not",
"isinstance",
"(",
"db",
",",
"DAL",
")",
"or",
"not",
"db",
".",
"_uri",
":",
"raise",
"Exception",
"(",
"\"Need valid DAL object to define tables\"",
")",
"# event log - self-explanatory, logs all events"... | Build Seshet's basic database schema. Requires one parameter,
`db` as `pydal.DAL` instance. | [
"Build",
"Seshet",
"s",
"basic",
"database",
"schema",
".",
"Requires",
"one",
"parameter",
"db",
"as",
"pydal",
".",
"DAL",
"instance",
"."
] | d55bae01cff56762c5467138474145a2c17d1932 | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/config.py#L121-L153 |
241,871 | dschien/PyExcelModelingHelper | excel_helper/__init__.py | DistributionFunctionGenerator.generate_values | def generate_values(self, *args, **kwargs):
"""
Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg.
If `self.sample_mean_value == True` the sample will contain "size" times the mean value.
:param args:
:par... | python | def generate_values(self, *args, **kwargs):
"""
Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg.
If `self.sample_mean_value == True` the sample will contain "size" times the mean value.
:param args:
:par... | [
"def",
"generate_values",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sample_size",
"=",
"kwargs",
".",
"get",
"(",
"'size'",
",",
"self",
".",
"size",
")",
"f",
"=",
"self",
".",
"instantiate_distribution_function",
"(",
"self",
... | Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg.
If `self.sample_mean_value == True` the sample will contain "size" times the mean value.
:param args:
:param kwargs:
:return: sample as vector of given size | [
"Generate",
"a",
"sample",
"of",
"values",
"by",
"sampling",
"from",
"a",
"distribution",
".",
"The",
"size",
"of",
"the",
"sample",
"can",
"be",
"overriden",
"with",
"the",
"size",
"kwarg",
"."
] | d00d98ae2f28ad71cfcd2a365c3045e439517df2 | https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L112-L132 |
241,872 | dschien/PyExcelModelingHelper | excel_helper/__init__.py | ParameterScenarioSet.add_scenario | def add_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario):
"""
Add a scenario for this parameter.
:param scenario_name:
:param parameter:
:return:
"""
self.scenarios[scenario_name] = parameter | python | def add_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario):
"""
Add a scenario for this parameter.
:param scenario_name:
:param parameter:
:return:
"""
self.scenarios[scenario_name] = parameter | [
"def",
"add_scenario",
"(",
"self",
",",
"parameter",
":",
"'Parameter'",
",",
"scenario_name",
":",
"str",
"=",
"default_scenario",
")",
":",
"self",
".",
"scenarios",
"[",
"scenario_name",
"]",
"=",
"parameter"
] | Add a scenario for this parameter.
:param scenario_name:
:param parameter:
:return: | [
"Add",
"a",
"scenario",
"for",
"this",
"parameter",
"."
] | d00d98ae2f28ad71cfcd2a365c3045e439517df2 | https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L438-L446 |
241,873 | dschien/PyExcelModelingHelper | excel_helper/__init__.py | ParameterRepository.fill_missing_attributes_from_default_parameter | def fill_missing_attributes_from_default_parameter(self, param):
"""
Empty fields in Parameter definitions in scenarios are populated with default values.
E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar.
| name | scenario ... | python | def fill_missing_attributes_from_default_parameter(self, param):
"""
Empty fields in Parameter definitions in scenarios are populated with default values.
E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar.
| name | scenario ... | [
"def",
"fill_missing_attributes_from_default_parameter",
"(",
"self",
",",
"param",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"param",
".",
"name",
")",
"or",
"not",
"ParameterScenarioSet",
".",
"default_scenario",
"in",
"self",
".",
"parameter_sets",
"... | Empty fields in Parameter definitions in scenarios are populated with default values.
E.g. in the example below, the source for the Power_TV variable in the 8K scenario would also be EnergyStar.
| name | scenario | val | tags | source |
|----------|----------|-----|--------|---------... | [
"Empty",
"fields",
"in",
"Parameter",
"definitions",
"in",
"scenarios",
"are",
"populated",
"with",
"default",
"values",
"."
] | d00d98ae2f28ad71cfcd2a365c3045e439517df2 | https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L506-L541 |
241,874 | dschien/PyExcelModelingHelper | excel_helper/__init__.py | ParameterRepository.find_by_tag | def find_by_tag(self, tag) -> Dict[str, Set[Parameter]]:
"""
Get all registered dicts that are registered for a tag
:param tag: str - single tag
:return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for
all parameter names with a given tag
... | python | def find_by_tag(self, tag) -> Dict[str, Set[Parameter]]:
"""
Get all registered dicts that are registered for a tag
:param tag: str - single tag
:return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for
all parameter names with a given tag
... | [
"def",
"find_by_tag",
"(",
"self",
",",
"tag",
")",
"->",
"Dict",
"[",
"str",
",",
"Set",
"[",
"Parameter",
"]",
"]",
":",
"return",
"self",
".",
"tags",
"[",
"tag",
"]"
] | Get all registered dicts that are registered for a tag
:param tag: str - single tag
:return: a dict of {param name: set[Parameter]} that contains all ParameterScenarioSets for
all parameter names with a given tag | [
"Get",
"all",
"registered",
"dicts",
"that",
"are",
"registered",
"for",
"a",
"tag"
] | d00d98ae2f28ad71cfcd2a365c3045e439517df2 | https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L560-L568 |
241,875 | dschien/PyExcelModelingHelper | excel_helper/__init__.py | ExcelParameterLoader.load_parameter_definitions | def load_parameter_definitions(self, sheet_name: str = None):
"""
Load variable text from rows in excel file.
If no spreadsheet arg is given, all spreadsheets are loaded.
The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored.
... | python | def load_parameter_definitions(self, sheet_name: str = None):
"""
Load variable text from rows in excel file.
If no spreadsheet arg is given, all spreadsheets are loaded.
The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored.
... | [
"def",
"load_parameter_definitions",
"(",
"self",
",",
"sheet_name",
":",
"str",
"=",
"None",
")",
":",
"definitions",
"=",
"self",
".",
"excel_handler",
".",
"load_definitions",
"(",
"sheet_name",
",",
"filename",
"=",
"self",
".",
"filename",
")",
"self",
... | Load variable text from rows in excel file.
If no spreadsheet arg is given, all spreadsheets are loaded.
The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored.
Any cells used as titles (with no associated value) are also added to the return... | [
"Load",
"variable",
"text",
"from",
"rows",
"in",
"excel",
"file",
".",
"If",
"no",
"spreadsheet",
"arg",
"is",
"given",
"all",
"spreadsheets",
"are",
"loaded",
".",
"The",
"first",
"cell",
"in",
"the",
"first",
"row",
"in",
"a",
"spreadsheet",
"must",
"... | d00d98ae2f28ad71cfcd2a365c3045e439517df2 | https://github.com/dschien/PyExcelModelingHelper/blob/d00d98ae2f28ad71cfcd2a365c3045e439517df2/excel_helper/__init__.py#L787-L812 |
241,876 | Naught0/lolrune | lolrune/runeclient.py | RuneClient._get | def _get(self, url: str) -> str:
"""A small wrapper method which makes a quick GET request.
Parameters
----------
url : str
The URL to get.
Returns
-------
str
The raw html of the requested page.
Raises
------
Run... | python | def _get(self, url: str) -> str:
"""A small wrapper method which makes a quick GET request.
Parameters
----------
url : str
The URL to get.
Returns
-------
str
The raw html of the requested page.
Raises
------
Run... | [
"def",
"_get",
"(",
"self",
",",
"url",
":",
"str",
")",
"->",
"str",
":",
"resp",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"HEADERS",
")",
"if",
"resp",
".",
"status_code",
"is",
"200",
":",
"return"... | A small wrapper method which makes a quick GET request.
Parameters
----------
url : str
The URL to get.
Returns
-------
str
The raw html of the requested page.
Raises
------
RuneConnectionError
If the GET resp... | [
"A",
"small",
"wrapper",
"method",
"which",
"makes",
"a",
"quick",
"GET",
"request",
"."
] | 99f67b9137e42a78198ba369ceb371e473759f11 | https://github.com/Naught0/lolrune/blob/99f67b9137e42a78198ba369ceb371e473759f11/lolrune/runeclient.py#L52-L74 |
241,877 | edwards-lab/libGWAS | libgwas/__init__.py | sys_call | def sys_call(cmd):
"""Execute cmd and capture stdout and stderr
:param cmd: command to be executed
:return: (stdout, stderr)
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
return p.stdout.readlines(), p.stderr.readlines() | python | def sys_call(cmd):
"""Execute cmd and capture stdout and stderr
:param cmd: command to be executed
:return: (stdout, stderr)
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
return p.stdout.readlines(), p.stderr.readlines() | [
"def",
"sys_call",
"(",
"cmd",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"close_fds",
"=",
"True",
")",
... | Execute cmd and capture stdout and stderr
:param cmd: command to be executed
:return: (stdout, stderr) | [
"Execute",
"cmd",
"and",
"capture",
"stdout",
"and",
"stderr"
] | d68c9a083d443dfa5d7c5112de29010909cfe23f | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/__init__.py#L51-L58 |
241,878 | AndresMWeber/Nomenclate | nomenclate/core/rendering.py | InputRenderer._get_alphanumeric_index | def _get_alphanumeric_index(query_string):
""" Given an input string of either int or char, returns what index in the alphabet and case it is
:param query_string: str, query string
:return: (int, str), list of the index and type
"""
# TODO: could probably rework this. it works, ... | python | def _get_alphanumeric_index(query_string):
""" Given an input string of either int or char, returns what index in the alphabet and case it is
:param query_string: str, query string
:return: (int, str), list of the index and type
"""
# TODO: could probably rework this. it works, ... | [
"def",
"_get_alphanumeric_index",
"(",
"query_string",
")",
":",
"# TODO: could probably rework this. it works, but it's ugly as hell.",
"try",
":",
"return",
"[",
"int",
"(",
"query_string",
")",
",",
"'int'",
"]",
"except",
"ValueError",
":",
"if",
"len",
"(",
"quer... | Given an input string of either int or char, returns what index in the alphabet and case it is
:param query_string: str, query string
:return: (int, str), list of the index and type | [
"Given",
"an",
"input",
"string",
"of",
"either",
"int",
"or",
"char",
"returns",
"what",
"index",
"in",
"the",
"alphabet",
"and",
"case",
"it",
"is"
] | e6d6fc28beac042bad588e56fbe77531d2de6b6f | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/rendering.py#L105-L121 |
241,879 | honzamach/pynspect | pynspect/traversers.py | _to_numeric | def _to_numeric(val):
"""
Helper function for conversion of various data types into numeric representation.
"""
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):
return val
return float(val) | python | def _to_numeric(val):
"""
Helper function for conversion of various data types into numeric representation.
"""
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):
return val
return float(val) | [
"def",
"_to_numeric",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"datetime",
".",
"datetime",
",",
"datetime",
".",
"timedelta",
")",
")",
":",
"return",
"val",
"return",
"float",
"(",
"val",
")"
] | Helper function for conversion of various data types into numeric representation. | [
"Helper",
"function",
"for",
"conversion",
"of",
"various",
"data",
"types",
"into",
"numeric",
"representation",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L517-L523 |
241,880 | honzamach/pynspect | pynspect/traversers.py | BaseFilteringTreeTraverser.evaluate_binop_logical | def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.... | python | def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.... | [
"def",
"evaluate_binop_logical",
"(",
"self",
",",
"operation",
",",
"left",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"operation",
"in",
"self",
".",
"binops_logical",
":",
"raise",
"ValueError",
"(",
"\"Invalid logical binary operation '{}'... | Evaluate given logical binary operation with given operands. | [
"Evaluate",
"given",
"logical",
"binary",
"operation",
"with",
"given",
"operands",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L642-L649 |
241,881 | honzamach/pynspect | pynspect/traversers.py | BaseFilteringTreeTraverser.evaluate_binop_comparison | def evaluate_binop_comparison(self, operation, left, right, **kwargs):
"""
Evaluate given comparison binary operation with given operands.
"""
if not operation in self.binops_comparison:
raise ValueError("Invalid comparison binary operation '{}'".format(operation))
if... | python | def evaluate_binop_comparison(self, operation, left, right, **kwargs):
"""
Evaluate given comparison binary operation with given operands.
"""
if not operation in self.binops_comparison:
raise ValueError("Invalid comparison binary operation '{}'".format(operation))
if... | [
"def",
"evaluate_binop_comparison",
"(",
"self",
",",
"operation",
",",
"left",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"operation",
"in",
"self",
".",
"binops_comparison",
":",
"raise",
"ValueError",
"(",
"\"Invalid comparison binary opera... | Evaluate given comparison binary operation with given operands. | [
"Evaluate",
"given",
"comparison",
"binary",
"operation",
"with",
"given",
"operands",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L651-L684 |
241,882 | honzamach/pynspect | pynspect/traversers.py | BaseFilteringTreeTraverser._calculate_vector | def _calculate_vector(self, operation, left, right):
"""
Calculate vector result from two list operands with given mathematical operation.
"""
result = []
if len(right) == 1:
right = _to_numeric(right[0])
for iteml in left:
iteml = _to_nume... | python | def _calculate_vector(self, operation, left, right):
"""
Calculate vector result from two list operands with given mathematical operation.
"""
result = []
if len(right) == 1:
right = _to_numeric(right[0])
for iteml in left:
iteml = _to_nume... | [
"def",
"_calculate_vector",
"(",
"self",
",",
"operation",
",",
"left",
",",
"right",
")",
":",
"result",
"=",
"[",
"]",
"if",
"len",
"(",
"right",
")",
"==",
"1",
":",
"right",
"=",
"_to_numeric",
"(",
"right",
"[",
"0",
"]",
")",
"for",
"iteml",
... | Calculate vector result from two list operands with given mathematical operation. | [
"Calculate",
"vector",
"result",
"from",
"two",
"list",
"operands",
"with",
"given",
"mathematical",
"operation",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L686-L708 |
241,883 | honzamach/pynspect | pynspect/traversers.py | BaseFilteringTreeTraverser.evaluate_binop_math | def evaluate_binop_math(self, operation, left, right, **kwargs):
"""
Evaluate given mathematical binary operation with given operands.
"""
if not operation in self.binops_math:
raise ValueError("Invalid math binary operation '{}'".format(operation))
if left is None or... | python | def evaluate_binop_math(self, operation, left, right, **kwargs):
"""
Evaluate given mathematical binary operation with given operands.
"""
if not operation in self.binops_math:
raise ValueError("Invalid math binary operation '{}'".format(operation))
if left is None or... | [
"def",
"evaluate_binop_math",
"(",
"self",
",",
"operation",
",",
"left",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"operation",
"in",
"self",
".",
"binops_math",
":",
"raise",
"ValueError",
"(",
"\"Invalid math binary operation '{}'\"",
".... | Evaluate given mathematical binary operation with given operands. | [
"Evaluate",
"given",
"mathematical",
"binary",
"operation",
"with",
"given",
"operands",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L710-L730 |
241,884 | honzamach/pynspect | pynspect/traversers.py | BaseFilteringTreeTraverser.evaluate_unop | def evaluate_unop(self, operation, right, **kwargs):
"""
Evaluate given unary operation with given operand.
"""
if not operation in self.unops:
raise ValueError("Invalid unary operation '{}'".format(operation))
if right is None:
return None
return ... | python | def evaluate_unop(self, operation, right, **kwargs):
"""
Evaluate given unary operation with given operand.
"""
if not operation in self.unops:
raise ValueError("Invalid unary operation '{}'".format(operation))
if right is None:
return None
return ... | [
"def",
"evaluate_unop",
"(",
"self",
",",
"operation",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"operation",
"in",
"self",
".",
"unops",
":",
"raise",
"ValueError",
"(",
"\"Invalid unary operation '{}'\"",
".",
"format",
"(",
"operation"... | Evaluate given unary operation with given operand. | [
"Evaluate",
"given",
"unary",
"operation",
"with",
"given",
"operand",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L732-L740 |
241,885 | honzamach/pynspect | pynspect/traversers.py | BaseFilteringTreeTraverser.decorate_function | def decorate_function(self, name, decorator):
"""
Decorate function with given name with given decorator.
:param str name: Name of the function.
:param callable decorator: Decorator callback.
"""
self.functions[name] = decorator(self.functions[name]) | python | def decorate_function(self, name, decorator):
"""
Decorate function with given name with given decorator.
:param str name: Name of the function.
:param callable decorator: Decorator callback.
"""
self.functions[name] = decorator(self.functions[name]) | [
"def",
"decorate_function",
"(",
"self",
",",
"name",
",",
"decorator",
")",
":",
"self",
".",
"functions",
"[",
"name",
"]",
"=",
"decorator",
"(",
"self",
".",
"functions",
"[",
"name",
"]",
")"
] | Decorate function with given name with given decorator.
:param str name: Name of the function.
:param callable decorator: Decorator callback. | [
"Decorate",
"function",
"with",
"given",
"name",
"with",
"given",
"decorator",
"."
] | 0582dcc1f7aafe50e25a21c792ea1b3367ea5881 | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L753-L760 |
241,886 | a1fred/django-model-render | model_render/__init__.py | ModelRenderMixin.render | def render(self, template=None, additional=None):
"""
Render single model to its html representation.
You may set template path in render function argument,
or model's variable named 'template_path',
or get default name: $app_label$/models/$model_name$.html
Sett... | python | def render(self, template=None, additional=None):
"""
Render single model to its html representation.
You may set template path in render function argument,
or model's variable named 'template_path',
or get default name: $app_label$/models/$model_name$.html
Sett... | [
"def",
"render",
"(",
"self",
",",
"template",
"=",
"None",
",",
"additional",
"=",
"None",
")",
":",
"template_path",
"=",
"template",
"or",
"self",
".",
"get_template_path",
"(",
")",
"template_vars",
"=",
"{",
"'model'",
":",
"self",
"}",
"if",
"addit... | Render single model to its html representation.
You may set template path in render function argument,
or model's variable named 'template_path',
or get default name: $app_label$/models/$model_name$.html
Settings:
* MODEL_RENDER_DEFAULT_EXTENSION
set default... | [
"Render",
"single",
"model",
"to",
"its",
"html",
"representation",
"."
] | 0912b2ec9d33bada8875a57f7af9eb18d24e1e84 | https://github.com/a1fred/django-model-render/blob/0912b2ec9d33bada8875a57f7af9eb18d24e1e84/model_render/__init__.py#L18-L40 |
241,887 | mrstephenneal/dirutility | dirutility/system.py | SystemCommand.execute | def execute(self):
"""Execute a system command."""
if self._decode_output:
# Capture and decode system output
with Popen(self.command, shell=True, stdout=PIPE) as process:
self._output = [i.decode("utf-8").strip() for i in process.stdout]
self._suc... | python | def execute(self):
"""Execute a system command."""
if self._decode_output:
# Capture and decode system output
with Popen(self.command, shell=True, stdout=PIPE) as process:
self._output = [i.decode("utf-8").strip() for i in process.stdout]
self._suc... | [
"def",
"execute",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decode_output",
":",
"# Capture and decode system output",
"with",
"Popen",
"(",
"self",
".",
"command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
")",
"as",
"process",
":",
"self",... | Execute a system command. | [
"Execute",
"a",
"system",
"command",
"."
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/system.py#L51-L62 |
241,888 | Vito2015/pyextend | pyextend/core/wrappers/accepts.py | accepts | def accepts(exception=TypeError, **types):
"""
A wrapper of function for checking function parameters type
Example 1:
@accepts(a=int, b='__iter__', c=str)
def test(a, b=None, c=None):
print('accepts OK')
test(13, b=[], c='abc') -- OK
test('aaa', b=(), c='abc') ... | python | def accepts(exception=TypeError, **types):
"""
A wrapper of function for checking function parameters type
Example 1:
@accepts(a=int, b='__iter__', c=str)
def test(a, b=None, c=None):
print('accepts OK')
test(13, b=[], c='abc') -- OK
test('aaa', b=(), c='abc') ... | [
"def",
"accepts",
"(",
"exception",
"=",
"TypeError",
",",
"*",
"*",
"types",
")",
":",
"def",
"check_param",
"(",
"v",
",",
"type_or_funcname",
")",
":",
"if",
"isinstance",
"(",
"type_or_funcname",
",",
"tuple",
")",
":",
"results1",
"=",
"[",
"check_p... | A wrapper of function for checking function parameters type
Example 1:
@accepts(a=int, b='__iter__', c=str)
def test(a, b=None, c=None):
print('accepts OK')
test(13, b=[], c='abc') -- OK
test('aaa', b=(), c='abc') --Failed
Example 2:
@accepts(a=int, b=('__... | [
"A",
"wrapper",
"of",
"function",
"for",
"checking",
"function",
"parameters",
"type"
] | 36861dfe1087e437ffe9b5a1da9345c85b4fa4a1 | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/wrappers/accepts.py#L15-L77 |
241,889 | radhermit/vimball | vimball/base.py | is_vimball | def is_vimball(fd):
"""Test for vimball archive format compliance.
Simple check to see if the first line of the file starts with standard
vimball archive header.
"""
fd.seek(0)
try:
header = fd.readline()
except UnicodeDecodeError:
# binary files will raise exceptions when t... | python | def is_vimball(fd):
"""Test for vimball archive format compliance.
Simple check to see if the first line of the file starts with standard
vimball archive header.
"""
fd.seek(0)
try:
header = fd.readline()
except UnicodeDecodeError:
# binary files will raise exceptions when t... | [
"def",
"is_vimball",
"(",
"fd",
")",
":",
"fd",
".",
"seek",
"(",
"0",
")",
"try",
":",
"header",
"=",
"fd",
".",
"readline",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"# binary files will raise exceptions when trying to decode raw bytes to",
"# str objects in ... | Test for vimball archive format compliance.
Simple check to see if the first line of the file starts with standard
vimball archive header. | [
"Test",
"for",
"vimball",
"archive",
"format",
"compliance",
"."
] | 3998bdb8d8c4852a388a259778f971f562f9ef37 | https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L24-L39 |
241,890 | radhermit/vimball | vimball/base.py | Vimball.files | def files(self):
"""Yields archive file information."""
# try new file header format first, then fallback on old
for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"):
header = re.compile(header)
filename = None
self.fd.seek(0)
line = self.readline()
... | python | def files(self):
"""Yields archive file information."""
# try new file header format first, then fallback on old
for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"):
header = re.compile(header)
filename = None
self.fd.seek(0)
line = self.readline()
... | [
"def",
"files",
"(",
"self",
")",
":",
"# try new file header format first, then fallback on old",
"for",
"header",
"in",
"(",
"r\"(.*)\\t\\[\\[\\[1\\n\"",
",",
"r\"^(\\d+)\\n$\"",
")",
":",
"header",
"=",
"re",
".",
"compile",
"(",
"header",
")",
"filename",
"=",
... | Yields archive file information. | [
"Yields",
"archive",
"file",
"information",
"."
] | 3998bdb8d8c4852a388a259778f971f562f9ef37 | https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L82-L102 |
241,891 | radhermit/vimball | vimball/base.py | Vimball.extract | def extract(self, extractdir=None, verbose=False):
"""Extract archive files to a directory."""
if extractdir is None:
filebase, ext = os.path.splitext(self.path)
if ext in ('.gz', '.bz2', '.xz'):
filebase, _ext = os.path.splitext(filebase)
extractdir =... | python | def extract(self, extractdir=None, verbose=False):
"""Extract archive files to a directory."""
if extractdir is None:
filebase, ext = os.path.splitext(self.path)
if ext in ('.gz', '.bz2', '.xz'):
filebase, _ext = os.path.splitext(filebase)
extractdir =... | [
"def",
"extract",
"(",
"self",
",",
"extractdir",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"extractdir",
"is",
"None",
":",
"filebase",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"path",
")",
"if",
"ext... | Extract archive files to a directory. | [
"Extract",
"archive",
"files",
"to",
"a",
"directory",
"."
] | 3998bdb8d8c4852a388a259778f971f562f9ef37 | https://github.com/radhermit/vimball/blob/3998bdb8d8c4852a388a259778f971f562f9ef37/vimball/base.py#L104-L128 |
241,892 | Fuyukai/ConfigMaster | configmaster/INIConfigFile.py | ini_dump_hook | def ini_dump_hook(cfg, text: bool=False):
"""
Dumps all the data into a INI file.
This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned.
"""
data = cfg.config.dump()
# Load data back into the goddamned ini file.
ndict = {}
for ke... | python | def ini_dump_hook(cfg, text: bool=False):
"""
Dumps all the data into a INI file.
This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned.
"""
data = cfg.config.dump()
# Load data back into the goddamned ini file.
ndict = {}
for ke... | [
"def",
"ini_dump_hook",
"(",
"cfg",
",",
"text",
":",
"bool",
"=",
"False",
")",
":",
"data",
"=",
"cfg",
".",
"config",
".",
"dump",
"(",
")",
"# Load data back into the goddamned ini file.",
"ndict",
"=",
"{",
"}",
"for",
"key",
",",
"item",
"in",
"dat... | Dumps all the data into a INI file.
This will automatically kill anything with a '_' in the keyname, replacing it with a dot. You have been warned. | [
"Dumps",
"all",
"the",
"data",
"into",
"a",
"INI",
"file",
"."
] | 8018aa415da55c84edaa8a49664f674758a14edd | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/INIConfigFile.py#L40-L60 |
241,893 | waltermoreira/tartpy | tartpy/runtime.py | exception_message | def exception_message():
"""Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
return {'exception': {'type': exc_type,
'value': exc_value,
'traceback': exc_tb},
'traceback': traceback.form... | python | def exception_message():
"""Create a message with details on the exception."""
exc_type, exc_value, exc_tb = exc_info = sys.exc_info()
return {'exception': {'type': exc_type,
'value': exc_value,
'traceback': exc_tb},
'traceback': traceback.form... | [
"def",
"exception_message",
"(",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_tb",
"=",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"return",
"{",
"'exception'",
":",
"{",
"'type'",
":",
"exc_type",
",",
"'value'",
":",
"exc_value",
",",
"'tr... | Create a message with details on the exception. | [
"Create",
"a",
"message",
"with",
"details",
"on",
"the",
"exception",
"."
] | d9f66c8b373bd55a7b055c0fd39b516490bb0235 | https://github.com/waltermoreira/tartpy/blob/d9f66c8b373bd55a7b055c0fd39b516490bb0235/tartpy/runtime.py#L97-L103 |
241,894 | waltermoreira/tartpy | tartpy/runtime.py | behavior | def behavior(f):
"""Decorator for declaring a function as behavior.
Use as::
@behavior
def fun(x, y, self, msg):
...
And create or become this behavior by passing the two arguments
`x` and `y`.
"""
@wraps(f)
def wrapper(*args):
message = args[-1]
... | python | def behavior(f):
"""Decorator for declaring a function as behavior.
Use as::
@behavior
def fun(x, y, self, msg):
...
And create or become this behavior by passing the two arguments
`x` and `y`.
"""
@wraps(f)
def wrapper(*args):
message = args[-1]
... | [
"def",
"behavior",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"message",
"=",
"args",
"[",
"-",
"1",
"]",
"if",
"isinstance",
"(",
"message",
",",
"MutableMapping",
")",
":",
"message",
"=",
"Me... | Decorator for declaring a function as behavior.
Use as::
@behavior
def fun(x, y, self, msg):
...
And create or become this behavior by passing the two arguments
`x` and `y`. | [
"Decorator",
"for",
"declaring",
"a",
"function",
"as",
"behavior",
"."
] | d9f66c8b373bd55a7b055c0fd39b516490bb0235 | https://github.com/waltermoreira/tartpy/blob/d9f66c8b373bd55a7b055c0fd39b516490bb0235/tartpy/runtime.py#L148-L167 |
241,895 | MacHu-GWU/angora-project | angora/math/interp.py | fromtimestamp | def fromtimestamp(timestamp):
"""Because python doesn't support negative timestamp to datetime
so we have to implement my own method
"""
if timestamp >= 0:
return datetime.fromtimestamp(timestamp)
else:
return datetime(1969, 12, 31, 20, 0) + timedelta(seconds=timestamp) | python | def fromtimestamp(timestamp):
"""Because python doesn't support negative timestamp to datetime
so we have to implement my own method
"""
if timestamp >= 0:
return datetime.fromtimestamp(timestamp)
else:
return datetime(1969, 12, 31, 20, 0) + timedelta(seconds=timestamp) | [
"def",
"fromtimestamp",
"(",
"timestamp",
")",
":",
"if",
"timestamp",
">=",
"0",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
")",
"else",
":",
"return",
"datetime",
"(",
"1969",
",",
"12",
",",
"31",
",",
"20",
",",
"0",
")",
... | Because python doesn't support negative timestamp to datetime
so we have to implement my own method | [
"Because",
"python",
"doesn",
"t",
"support",
"negative",
"timestamp",
"to",
"datetime",
"so",
"we",
"have",
"to",
"implement",
"my",
"own",
"method"
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L111-L118 |
241,896 | MacHu-GWU/angora-project | angora/math/interp.py | rigid_linear_interpolate_by_datetime | def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):
"""A datetime-version that takes datetime object list as x_axis.
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in datetime_axis
]
numeric_datetime_new_axis = [
totimestamp(a_da... | python | def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):
"""A datetime-version that takes datetime object list as x_axis.
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in datetime_axis
]
numeric_datetime_new_axis = [
totimestamp(a_da... | [
"def",
"rigid_linear_interpolate_by_datetime",
"(",
"datetime_axis",
",",
"y_axis",
",",
"datetime_new_axis",
")",
":",
"numeric_datetime_axis",
"=",
"[",
"totimestamp",
"(",
"a_datetime",
")",
"for",
"a_datetime",
"in",
"datetime_axis",
"]",
"numeric_datetime_new_axis",
... | A datetime-version that takes datetime object list as x_axis. | [
"A",
"datetime",
"-",
"version",
"that",
"takes",
"datetime",
"object",
"list",
"as",
"x_axis",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L146-L158 |
241,897 | MacHu-GWU/angora-project | angora/math/interp.py | exam_reliability_by_datetime | def exam_reliability_by_datetime(
datetime_axis, datetime_new_axis, reliable_distance):
"""A datetime-version that takes datetime object list as x_axis
reliable_distance equals to the time difference in seconds.
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in date... | python | def exam_reliability_by_datetime(
datetime_axis, datetime_new_axis, reliable_distance):
"""A datetime-version that takes datetime object list as x_axis
reliable_distance equals to the time difference in seconds.
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in date... | [
"def",
"exam_reliability_by_datetime",
"(",
"datetime_axis",
",",
"datetime_new_axis",
",",
"reliable_distance",
")",
":",
"numeric_datetime_axis",
"=",
"[",
"totimestamp",
"(",
"a_datetime",
")",
"for",
"a_datetime",
"in",
"datetime_axis",
"]",
"numeric_datetime_new_axis... | A datetime-version that takes datetime object list as x_axis
reliable_distance equals to the time difference in seconds. | [
"A",
"datetime",
"-",
"version",
"that",
"takes",
"datetime",
"object",
"list",
"as",
"x_axis",
"reliable_distance",
"equals",
"to",
"the",
"time",
"difference",
"in",
"seconds",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/interp.py#L265-L279 |
241,898 | krukas/Trionyx | trionyx/utils.py | import_object_by_string | def import_object_by_string(namespace):
"""Import object by complete namespace"""
segments = namespace.split('.')
module = importlib.import_module('.'.join(segments[:-1]))
return getattr(module, segments[-1]) | python | def import_object_by_string(namespace):
"""Import object by complete namespace"""
segments = namespace.split('.')
module = importlib.import_module('.'.join(segments[:-1]))
return getattr(module, segments[-1]) | [
"def",
"import_object_by_string",
"(",
"namespace",
")",
":",
"segments",
"=",
"namespace",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"'.'",
".",
"join",
"(",
"segments",
"[",
":",
"-",
"1",
"]",
")",
")",
"r... | Import object by complete namespace | [
"Import",
"object",
"by",
"complete",
"namespace"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/utils.py#L24-L28 |
241,899 | krukas/Trionyx | trionyx/utils.py | create_celerybeat_schedule | def create_celerybeat_schedule(apps):
"""Create Celery beat schedule by get schedule from every installed app"""
beat_schedule = {}
for app in apps:
try:
config = import_object_by_string(app)
module = importlib.import_module('{}.cron'.format(config.name))
except Excep... | python | def create_celerybeat_schedule(apps):
"""Create Celery beat schedule by get schedule from every installed app"""
beat_schedule = {}
for app in apps:
try:
config = import_object_by_string(app)
module = importlib.import_module('{}.cron'.format(config.name))
except Excep... | [
"def",
"create_celerybeat_schedule",
"(",
"apps",
")",
":",
"beat_schedule",
"=",
"{",
"}",
"for",
"app",
"in",
"apps",
":",
"try",
":",
"config",
"=",
"import_object_by_string",
"(",
"app",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"'{}.cr... | Create Celery beat schedule by get schedule from every installed app | [
"Create",
"Celery",
"beat",
"schedule",
"by",
"get",
"schedule",
"from",
"every",
"installed",
"app"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/utils.py#L31-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.