repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
jpscaletti/moar | moar/storage.py | Storage.get_thumbsdir | def get_thumbsdir(self, path):
"""
path:
path of the source image
"""
# Thumbsdir could be a callable
# In that case, the path is built on the fly, based on the source path
thumbsdir = self.thumbsdir
if callable(self.thumbsdir):
thumbsdir =... | python | def get_thumbsdir(self, path):
"""
path:
path of the source image
"""
# Thumbsdir could be a callable
# In that case, the path is built on the fly, based on the source path
thumbsdir = self.thumbsdir
if callable(self.thumbsdir):
thumbsdir =... | [
"def",
"get_thumbsdir",
"(",
"self",
",",
"path",
")",
":",
"# Thumbsdir could be a callable",
"# In that case, the path is built on the fly, based on the source path",
"thumbsdir",
"=",
"self",
".",
"thumbsdir",
"if",
"callable",
"(",
"self",
".",
"thumbsdir",
")",
":",
... | path:
path of the source image | [
"path",
":",
"path",
"of",
"the",
"source",
"image"
] | train | https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/storage.py#L100-L110 |
jpscaletti/moar | moar/storage.py | Storage.save | def save(self, path, key, format, data):
"""Save a newly generated thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension
data:
thumbnail's binary data
"""
thumbpath =... | python | def save(self, path, key, format, data):
"""Save a newly generated thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension
data:
thumbnail's binary data
"""
thumbpath =... | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"key",
",",
"format",
",",
"data",
")",
":",
"thumbpath",
"=",
"self",
".",
"get_thumbpath",
"(",
"path",
",",
"key",
",",
"format",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
... | Save a newly generated thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension
data:
thumbnail's binary data | [
"Save",
"a",
"newly",
"generated",
"thumbnail",
"."
] | train | https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/storage.py#L112-L129 |
Vito2015/pyextend | pyextend/core/log.py | add_handler | def add_handler(cls, level, fmt, colorful, **kwargs):
"""Add a configured handler to the global logger."""
global g_logger
if isinstance(level, str):
level = getattr(logging, level.upper(), logging.DEBUG)
handler = cls(**kwargs)
handler.setLevel(level)
if colorful:
formatte... | python | def add_handler(cls, level, fmt, colorful, **kwargs):
"""Add a configured handler to the global logger."""
global g_logger
if isinstance(level, str):
level = getattr(logging, level.upper(), logging.DEBUG)
handler = cls(**kwargs)
handler.setLevel(level)
if colorful:
formatte... | [
"def",
"add_handler",
"(",
"cls",
",",
"level",
",",
"fmt",
",",
"colorful",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"g_logger",
"if",
"isinstance",
"(",
"level",
",",
"str",
")",
":",
"level",
"=",
"getattr",
"(",
"logging",
",",
"level",
".",
... | Add a configured handler to the global logger. | [
"Add",
"a",
"configured",
"handler",
"to",
"the",
"global",
"logger",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L115-L133 |
Vito2015/pyextend | pyextend/core/log.py | add_filehandler | def add_filehandler(level, fmt, filename, mode, backup_count, limit, when):
"""Add a file handler to the global logger."""
kwargs = {}
# If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename ... | python | def add_filehandler(level, fmt, filename, mode, backup_count, limit, when):
"""Add a file handler to the global logger."""
kwargs = {}
# If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename ... | [
"def",
"add_filehandler",
"(",
"level",
",",
"fmt",
",",
"filename",
",",
"mode",
",",
"backup_count",
",",
"limit",
",",
"when",
")",
":",
"kwargs",
"=",
"{",
"}",
"# If the filename is not set, use the default filename",
"if",
"filename",
"is",
"None",
":",
... | Add a file handler to the global logger. | [
"Add",
"a",
"file",
"handler",
"to",
"the",
"global",
"logger",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L141-L171 |
Vito2015/pyextend | pyextend/core/log.py | init_logger | def init_logger(name=None):
"""Reload the global logger."""
global g_logger
if g_logger is None:
g_logger = logging.getLogger(name=name)
else:
logging.shutdown()
g_logger.handlers = []
g_logger.setLevel(logging.DEBUG) | python | def init_logger(name=None):
"""Reload the global logger."""
global g_logger
if g_logger is None:
g_logger = logging.getLogger(name=name)
else:
logging.shutdown()
g_logger.handlers = []
g_logger.setLevel(logging.DEBUG) | [
"def",
"init_logger",
"(",
"name",
"=",
"None",
")",
":",
"global",
"g_logger",
"if",
"g_logger",
"is",
"None",
":",
"g_logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
"=",
"name",
")",
"else",
":",
"logging",
".",
"shutdown",
"(",
")",
"g_logg... | Reload the global logger. | [
"Reload",
"the",
"global",
"logger",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L174-L184 |
Vito2015/pyextend | pyextend/core/log.py | set_logger | def set_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET',
fmt=
'%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s',
# fmt='[%(levelname)s] %(asctime)s %(message)s',
backup_count=5, limit=20480,... | python | def set_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET',
fmt=
'%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s',
# fmt='[%(levelname)s] %(asctime)s %(message)s',
backup_count=5, limit=20480,... | [
"def",
"set_logger",
"(",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"mode",
"=",
"'a'",
",",
"level",
"=",
"'NOTSET:NOTSET'",
",",
"fmt",
"=",
"'%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s'",
",",
"#... | Configure the global logger. | [
"Configure",
"the",
"global",
"logger",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L192-L212 |
Vito2015/pyextend | pyextend/core/log.py | import_log_funcs | def import_log_funcs():
"""Import the common log functions from the global logger to the module."""
global g_logger
curr_mod = sys.modules[__name__]
for func_name in _logging_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) | python | def import_log_funcs():
"""Import the common log functions from the global logger to the module."""
global g_logger
curr_mod = sys.modules[__name__]
for func_name in _logging_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) | [
"def",
"import_log_funcs",
"(",
")",
":",
"global",
"g_logger",
"curr_mod",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"for",
"func_name",
"in",
"_logging_funcs",
":",
"func",
"=",
"getattr",
"(",
"g_logger",
",",
"func_name",
")",
"setattr",
"(",
"... | Import the common log functions from the global logger to the module. | [
"Import",
"the",
"common",
"log",
"functions",
"from",
"the",
"global",
"logger",
"to",
"the",
"module",
"."
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/core/log.py#L215-L223 |
lvh/maxims | maxims/indirection.py | powerupIndirector | def powerupIndirector(interface):
"""
A decorator for a powerup indirector from a single interface to a single
in-memory implementation.
The in-memory implementation that is being indirected to must be created
in the ``activate`` callback, and then assigned to ``self.indirected``,
which is an `... | python | def powerupIndirector(interface):
"""
A decorator for a powerup indirector from a single interface to a single
in-memory implementation.
The in-memory implementation that is being indirected to must be created
in the ``activate`` callback, and then assigned to ``self.indirected``,
which is an `... | [
"def",
"powerupIndirector",
"(",
"interface",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"zi",
".",
"implementer",
"(",
"iaxiom",
".",
"IPowerupIndirector",
")",
"(",
"cls",
")",
"cls",
".",
"powerupInterfaces",
"=",
"[",
"interface",
"]",
"cls",
... | A decorator for a powerup indirector from a single interface to a single
in-memory implementation.
The in-memory implementation that is being indirected to must be created
in the ``activate`` callback, and then assigned to ``self.indirected``,
which is an ``inmemory`` attribute. | [
"A",
"decorator",
"for",
"a",
"powerup",
"indirector",
"from",
"a",
"single",
"interface",
"to",
"a",
"single",
"in",
"-",
"memory",
"implementation",
"."
] | train | https://github.com/lvh/maxims/blob/5c53b25d2cc4ccecbfe90193ade9ce0dbfbe4623/maxims/indirection.py#L8-L23 |
pavelsof/ipalint | ipalint/core.py | Core.lint | def lint(self, dataset=None, col=None, no_header=False,
ignore_nfd=False, ignore_ws=False, linewise=False, no_lines=False):
"""
Returns a string containing all the issues found in the dataset
defined by the given file path.
"""
reader = Reader(dataset, has_header=not no_header, ipa_col=col)
recog = Rec... | python | def lint(self, dataset=None, col=None, no_header=False,
ignore_nfd=False, ignore_ws=False, linewise=False, no_lines=False):
"""
Returns a string containing all the issues found in the dataset
defined by the given file path.
"""
reader = Reader(dataset, has_header=not no_header, ipa_col=col)
recog = Rec... | [
"def",
"lint",
"(",
"self",
",",
"dataset",
"=",
"None",
",",
"col",
"=",
"None",
",",
"no_header",
"=",
"False",
",",
"ignore_nfd",
"=",
"False",
",",
"ignore_ws",
"=",
"False",
",",
"linewise",
"=",
"False",
",",
"no_lines",
"=",
"False",
")",
":",... | Returns a string containing all the issues found in the dataset
defined by the given file path. | [
"Returns",
"a",
"string",
"containing",
"all",
"the",
"issues",
"found",
"in",
"the",
"dataset",
"defined",
"by",
"the",
"given",
"file",
"path",
"."
] | train | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/core.py#L58-L77 |
jordanncg/Bison | bison/main.py | main | def main():
"""d"""
config = Common.open_file(F_CONFIG)
# Delete the complete .build folder
Common.clean_build(config['p_build'])
# Create main folders
Common.make_dir(config['p_build'])
for language in config['languages']:
Common.make_dir(config['p_build'] + language) | python | def main():
"""d"""
config = Common.open_file(F_CONFIG)
# Delete the complete .build folder
Common.clean_build(config['p_build'])
# Create main folders
Common.make_dir(config['p_build'])
for language in config['languages']:
Common.make_dir(config['p_build'] + language) | [
"def",
"main",
"(",
")",
":",
"config",
"=",
"Common",
".",
"open_file",
"(",
"F_CONFIG",
")",
"# Delete the complete .build folder",
"Common",
".",
"clean_build",
"(",
"config",
"[",
"'p_build'",
"]",
")",
"# Create main folders",
"Common",
".",
"make_dir",
"("... | d | [
"d"
] | train | https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/main.py#L23-L33 |
Naught0/lolrune | lolrune/utils.py | parse_rune_links | def parse_rune_links(html: str) -> dict:
"""A function which parses the main Runeforge website into dict format.
Parameters
----------
html : str
The string representation of the html obtained via a GET request.
Returns
-------
dict
The nested rune_links champ rune pages fr... | python | def parse_rune_links(html: str) -> dict:
"""A function which parses the main Runeforge website into dict format.
Parameters
----------
html : str
The string representation of the html obtained via a GET request.
Returns
-------
dict
The nested rune_links champ rune pages fr... | [
"def",
"parse_rune_links",
"(",
"html",
":",
"str",
")",
"->",
"dict",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'lxml'",
")",
"# Champs with only a single runepage",
"single_page_raw",
"=",
"soup",
".",
"find_all",
"(",
"'li'",
",",
"class_",
"=",... | A function which parses the main Runeforge website into dict format.
Parameters
----------
html : str
The string representation of the html obtained via a GET request.
Returns
-------
dict
The nested rune_links champ rune pages from runeforge. | [
"A",
"function",
"which",
"parses",
"the",
"main",
"Runeforge",
"website",
"into",
"dict",
"format",
"."
] | train | https://github.com/Naught0/lolrune/blob/99f67b9137e42a78198ba369ceb371e473759f11/lolrune/utils.py#L7-L39 |
Naught0/lolrune | lolrune/utils.py | parse_rune_html | def parse_rune_html(html: str, url: str) -> dict:
"""A function that returns a dict representation of the Runeforge.gg page for a specific champ
Parameters
----------
html : str
The string representation of the html obtained via a GET request
url : str
The URL for the runeforge pag... | python | def parse_rune_html(html: str, url: str) -> dict:
"""A function that returns a dict representation of the Runeforge.gg page for a specific champ
Parameters
----------
html : str
The string representation of the html obtained via a GET request
url : str
The URL for the runeforge pag... | [
"def",
"parse_rune_html",
"(",
"html",
":",
"str",
",",
"url",
":",
"str",
")",
"->",
"dict",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'lxml'",
")",
"# The soup stuff",
"champ",
"=",
"soup",
".",
"find",
"(",
"'h1'",
",",
"class_",
"=",
... | A function that returns a dict representation of the Runeforge.gg page for a specific champ
Parameters
----------
html : str
The string representation of the html obtained via a GET request
url : str
The URL for the runeforge page being parsed.
Returns
-------
dict
... | [
"A",
"function",
"that",
"returns",
"a",
"dict",
"representation",
"of",
"the",
"Runeforge",
".",
"gg",
"page",
"for",
"a",
"specific",
"champ"
] | train | https://github.com/Naught0/lolrune/blob/99f67b9137e42a78198ba369ceb371e473759f11/lolrune/utils.py#L42-L77 |
fdb/aufmachen | aufmachen/websites/immoweb.py | find_string | def find_string(regex, s):
"""Find a string using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
s - The string to search.
regex - A string containing the regular expressi... | python | def find_string(regex, s):
"""Find a string using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
s - The string to search.
regex - A string containing the regular expressi... | [
"def",
"find_string",
"(",
"regex",
",",
"s",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"s",
")",
"if",
"m",
"is",
"None",
":",
"return",
"None",
"return",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]"
] | Find a string using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
s - The string to search.
regex - A string containing the regular expression.
Returns a unicode str... | [
"Find",
"a",
"string",
"using",
"a",
"given",
"regular",
"expression",
".",
"If",
"the",
"string",
"cannot",
"be",
"found",
"returns",
"None",
".",
"The",
"regex",
"should",
"contain",
"one",
"matching",
"group",
"as",
"only",
"the",
"result",
"of",
"the",... | train | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/websites/immoweb.py#L99-L113 |
fdb/aufmachen | aufmachen/websites/immoweb.py | find_number | def find_number(regex, s):
"""Find a number using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
The group should only contain numeric characters ([0-9]+).
s - The stri... | python | def find_number(regex, s):
"""Find a number using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
The group should only contain numeric characters ([0-9]+).
s - The stri... | [
"def",
"find_number",
"(",
"regex",
",",
"s",
")",
":",
"result",
"=",
"find_string",
"(",
"regex",
",",
"s",
")",
"if",
"result",
"is",
"None",
":",
"return",
"None",
"return",
"int",
"(",
"result",
")"
] | Find a number using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
The group should only contain numeric characters ([0-9]+).
s - The string to search.
regex - A string... | [
"Find",
"a",
"number",
"using",
"a",
"given",
"regular",
"expression",
".",
"If",
"the",
"string",
"cannot",
"be",
"found",
"returns",
"None",
".",
"The",
"regex",
"should",
"contain",
"one",
"matching",
"group",
"as",
"only",
"the",
"result",
"of",
"the",... | train | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/websites/immoweb.py#L115-L130 |
fdb/aufmachen | aufmachen/websites/immoweb.py | parse_first_number | def parse_first_number(s):
"""Parse the first number in the string we encounter.
s - The string to parse.
parse_first_number('123')
>>> 123
parse_first_number(' 12 meters')
>>> 12
parse_first_number('area: 156 meters')
>>> 156
parse_first_numbe... | python | def parse_first_number(s):
"""Parse the first number in the string we encounter.
s - The string to parse.
parse_first_number('123')
>>> 123
parse_first_number(' 12 meters')
>>> 12
parse_first_number('area: 156 meters')
>>> 156
parse_first_numbe... | [
"def",
"parse_first_number",
"(",
"s",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"'\\s*.*?(\\d+)'",
",",
"s",
")",
"if",
"m",
"is",
"None",
":",
"return",
"None",
"return",
"int",
"(",
"m",
".",
"groups",
"(",
"1",
")",
"[",
"0",
"]",
")"
] | Parse the first number in the string we encounter.
s - The string to parse.
parse_first_number('123')
>>> 123
parse_first_number(' 12 meters')
>>> 12
parse_first_number('area: 156 meters')
>>> 156
parse_first_number(' 1 2 3')
>> 1
p... | [
"Parse",
"the",
"first",
"number",
"in",
"the",
"string",
"we",
"encounter",
".",
"s",
"-",
"The",
"string",
"to",
"parse",
".",
"parse_first_number",
"(",
"123",
")",
">>>",
"123",
"parse_first_number",
"(",
"12",
"meters",
")",
">>>",
"12",
"parse_first_... | train | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/websites/immoweb.py#L132-L152 |
fdb/aufmachen | aufmachen/websites/immoweb.py | clean_text | def clean_text(s):
"""Removes all cruft from the text."""
SPACES_RE = re.compile(r'\s+')
SPECIAL_CHARS_RE = re.compile(r'[^\w\s\.\-\(\)]')
s = SPACES_RE.sub(' ', s)
s = s.strip()
s = SPECIAL_CHARS_RE.sub('', s)
return s | python | def clean_text(s):
"""Removes all cruft from the text."""
SPACES_RE = re.compile(r'\s+')
SPECIAL_CHARS_RE = re.compile(r'[^\w\s\.\-\(\)]')
s = SPACES_RE.sub(' ', s)
s = s.strip()
s = SPECIAL_CHARS_RE.sub('', s)
return s | [
"def",
"clean_text",
"(",
"s",
")",
":",
"SPACES_RE",
"=",
"re",
".",
"compile",
"(",
"r'\\s+'",
")",
"SPECIAL_CHARS_RE",
"=",
"re",
".",
"compile",
"(",
"r'[^\\w\\s\\.\\-\\(\\)]'",
")",
"s",
"=",
"SPACES_RE",
".",
"sub",
"(",
"' '",
",",
"s",
")",
"s"... | Removes all cruft from the text. | [
"Removes",
"all",
"cruft",
"from",
"the",
"text",
"."
] | train | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/websites/immoweb.py#L154-L161 |
fdb/aufmachen | aufmachen/websites/immoweb.py | parse_immoweb_link | def parse_immoweb_link(url):
"""Parses an Immoweb estate detail URL and returns the Immoweb estate id.
Returns a string with the Immoweb estate id.
"""
IMMOWEB_ID_RE = re.compile(r'.*?IdBien=([0-9]+).*?')
return IMMOWEB_ID_RE.match(url).groups()[0] | python | def parse_immoweb_link(url):
"""Parses an Immoweb estate detail URL and returns the Immoweb estate id.
Returns a string with the Immoweb estate id.
"""
IMMOWEB_ID_RE = re.compile(r'.*?IdBien=([0-9]+).*?')
return IMMOWEB_ID_RE.match(url).groups()[0] | [
"def",
"parse_immoweb_link",
"(",
"url",
")",
":",
"IMMOWEB_ID_RE",
"=",
"re",
".",
"compile",
"(",
"r'.*?IdBien=([0-9]+).*?'",
")",
"return",
"IMMOWEB_ID_RE",
".",
"match",
"(",
"url",
")",
".",
"groups",
"(",
")",
"[",
"0",
"]"
] | Parses an Immoweb estate detail URL and returns the Immoweb estate id.
Returns a string with the Immoweb estate id. | [
"Parses",
"an",
"Immoweb",
"estate",
"detail",
"URL",
"and",
"returns",
"the",
"Immoweb",
"estate",
"id",
"."
] | train | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/websites/immoweb.py#L163-L169 |
fdb/aufmachen | aufmachen/websites/immoweb.py | parse_number | def parse_number(d, key, regex, s):
"""Find a number using a given regular expression.
If the number is found, sets it under the key in the given dictionary.
d - The dictionary that will contain the data.
key - The key into the dictionary.
regex - A string containing the regular expression.
... | python | def parse_number(d, key, regex, s):
"""Find a number using a given regular expression.
If the number is found, sets it under the key in the given dictionary.
d - The dictionary that will contain the data.
key - The key into the dictionary.
regex - A string containing the regular expression.
... | [
"def",
"parse_number",
"(",
"d",
",",
"key",
",",
"regex",
",",
"s",
")",
":",
"result",
"=",
"find_number",
"(",
"regex",
",",
"s",
")",
"if",
"result",
"is",
"not",
"None",
":",
"d",
"[",
"key",
"]",
"=",
"result"
] | Find a number using a given regular expression.
If the number is found, sets it under the key in the given dictionary.
d - The dictionary that will contain the data.
key - The key into the dictionary.
regex - A string containing the regular expression.
s - The string to search. | [
"Find",
"a",
"number",
"using",
"a",
"given",
"regular",
"expression",
".",
"If",
"the",
"number",
"is",
"found",
"sets",
"it",
"under",
"the",
"key",
"in",
"the",
"given",
"dictionary",
".",
"d",
"-",
"The",
"dictionary",
"that",
"will",
"contain",
"the... | train | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/websites/immoweb.py#L171-L182 |
casebeer/factual | factual/common/category_helpers.py | make_category_filter | def make_category_filter(categories, blank=True):
'''
Generates a dict representing a Factual filter matching any of the categories
passed.
The resulting filter uses $bw "begins with" operators to return all matching
subcategories. Because of this, passing a top level category removes the need
to pass any of it... | python | def make_category_filter(categories, blank=True):
'''
Generates a dict representing a Factual filter matching any of the categories
passed.
The resulting filter uses $bw "begins with" operators to return all matching
subcategories. Because of this, passing a top level category removes the need
to pass any of it... | [
"def",
"make_category_filter",
"(",
"categories",
",",
"blank",
"=",
"True",
")",
":",
"categories",
"=",
"[",
"category",
".",
"strip",
"(",
")",
"for",
"category",
"in",
"categories",
"]",
"# find shortest prefixes",
"categories",
".",
"sort",
"(",
")",
"r... | Generates a dict representing a Factual filter matching any of the categories
passed.
The resulting filter uses $bw "begins with" operators to return all matching
subcategories. Because of this, passing a top level category removes the need
to pass any of its subcategories.
Conversely, specifying subcategories... | [
"Generates",
"a",
"dict",
"representing",
"a",
"Factual",
"filter",
"matching",
"any",
"of",
"the",
"categories",
"passed",
"."
] | train | https://github.com/casebeer/factual/blob/f2795a8c9fd447c5d62887ae0f960481ce13be84/factual/common/category_helpers.py#L11-L54 |
bioasp/ingranalyze | src/bioquali.py | readGraph | def readGraph(filename):
p = graph_parser.Parser()
"""
input: string, name of a file containing a Bioquali-like graph description
output: asp.TermSet, with atoms matching the contents of the input file
Parses a Bioquali-like graph description, and returns
a TermSet object.
Written using ori... | python | def readGraph(filename):
p = graph_parser.Parser()
"""
input: string, name of a file containing a Bioquali-like graph description
output: asp.TermSet, with atoms matching the contents of the input file
Parses a Bioquali-like graph description, and returns
a TermSet object.
Written using ori... | [
"def",
"readGraph",
"(",
"filename",
")",
":",
"p",
"=",
"graph_parser",
".",
"Parser",
"(",
")",
"accu",
"=",
"TermSet",
"(",
")",
"file",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"s",
"=",
"file",
".",
"readline",
"(",
")",
"while",
"s",
... | input: string, name of a file containing a Bioquali-like graph description
output: asp.TermSet, with atoms matching the contents of the input file
Parses a Bioquali-like graph description, and returns
a TermSet object.
Written using original Bioquali | [
"input",
":",
"string",
"name",
"of",
"a",
"file",
"containing",
"a",
"Bioquali",
"-",
"like",
"graph",
"description",
"output",
":",
"asp",
".",
"TermSet",
"with",
"atoms",
"matching",
"the",
"contents",
"of",
"the",
"input",
"file"
] | train | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/bioquali.py#L46-L67 |
limix/chiscore | chiscore/_davies.py | davies_pvalue | def davies_pvalue(q, w):
r"""Joint significance of statistics derived from chi2-squared distributions.
Parameters
----------
q : float
Test statistics.
w : array_like
Weights of the linear combination.
Returns
-------
float
Estimated p-value.
"""
q = as... | python | def davies_pvalue(q, w):
r"""Joint significance of statistics derived from chi2-squared distributions.
Parameters
----------
q : float
Test statistics.
w : array_like
Weights of the linear combination.
Returns
-------
float
Estimated p-value.
"""
q = as... | [
"def",
"davies_pvalue",
"(",
"q",
",",
"w",
")",
":",
"q",
"=",
"asarray",
"(",
"atleast_1d",
"(",
"q",
")",
",",
"float",
")",
"w",
"=",
"asarray",
"(",
"w",
",",
"float",
")",
"re",
"=",
"_pvalue_lambda",
"(",
"_lambda",
"(",
"w",
")",
",",
"... | r"""Joint significance of statistics derived from chi2-squared distributions.
Parameters
----------
q : float
Test statistics.
w : array_like
Weights of the linear combination.
Returns
-------
float
Estimated p-value. | [
"r",
"Joint",
"significance",
"of",
"statistics",
"derived",
"from",
"chi2",
"-",
"squared",
"distributions",
"."
] | train | https://github.com/limix/chiscore/blob/c3e774648b8166a5161df86e6bcad34af3cec95c/chiscore/_davies.py#L10-L34 |
fr33jc/bang | bang/deployers/deployer.py | Deployer.run | def run(self, action):
"""
Runs through the phases defined by :attr:`action`.
:param str action: Either ``deploy`` or ``inventory``.
"""
deployer = self.__class__.__name__
log.info('Running %s...' % deployer)
try:
if action == 'deploy':
... | python | def run(self, action):
"""
Runs through the phases defined by :attr:`action`.
:param str action: Either ``deploy`` or ``inventory``.
"""
deployer = self.__class__.__name__
log.info('Running %s...' % deployer)
try:
if action == 'deploy':
... | [
"def",
"run",
"(",
"self",
",",
"action",
")",
":",
"deployer",
"=",
"self",
".",
"__class__",
".",
"__name__",
"log",
".",
"info",
"(",
"'Running %s...'",
"%",
"deployer",
")",
"try",
":",
"if",
"action",
"==",
"'deploy'",
":",
"self",
".",
"deploy",
... | Runs through the phases defined by :attr:`action`.
:param str action: Either ``deploy`` or ``inventory``. | [
"Runs",
"through",
"the",
"phases",
"defined",
"by",
":",
"attr",
":",
"action",
"."
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/deployers/deployer.py#L61-L78 |
ANCIR/granoloader | granoloader/mapping.py | ObjectMapper.convert_type | def convert_type(self, value, spec):
""" Some well-educated format guessing. """
data_type = spec.get('type', 'string').lower().strip()
if data_type in ['bool', 'boolean']:
return value.lower() in BOOL_TRUISH
elif data_type in ['int', 'integer']:
try:
... | python | def convert_type(self, value, spec):
""" Some well-educated format guessing. """
data_type = spec.get('type', 'string').lower().strip()
if data_type in ['bool', 'boolean']:
return value.lower() in BOOL_TRUISH
elif data_type in ['int', 'integer']:
try:
... | [
"def",
"convert_type",
"(",
"self",
",",
"value",
",",
"spec",
")",
":",
"data_type",
"=",
"spec",
".",
"get",
"(",
"'type'",
",",
"'string'",
")",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"data_type",
"in",
"[",
"'bool'",
",",
"'boole... | Some well-educated format guessing. | [
"Some",
"well",
"-",
"educated",
"format",
"guessing",
"."
] | train | https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/mapping.py#L31-L71 |
ANCIR/granoloader | granoloader/mapping.py | ObjectMapper.get_value | def get_value(self, spec, row):
""" Returns the value or a dict with a 'value' entry plus extra fields. """
column = spec.get('column')
default = spec.get('default')
if column is None:
if default is not None:
return self.convert_type(default, spec)
... | python | def get_value(self, spec, row):
""" Returns the value or a dict with a 'value' entry plus extra fields. """
column = spec.get('column')
default = spec.get('default')
if column is None:
if default is not None:
return self.convert_type(default, spec)
... | [
"def",
"get_value",
"(",
"self",
",",
"spec",
",",
"row",
")",
":",
"column",
"=",
"spec",
".",
"get",
"(",
"'column'",
")",
"default",
"=",
"spec",
".",
"get",
"(",
"'default'",
")",
"if",
"column",
"is",
"None",
":",
"if",
"default",
"is",
"not",... | Returns the value or a dict with a 'value' entry plus extra fields. | [
"Returns",
"the",
"value",
"or",
"a",
"dict",
"with",
"a",
"value",
"entry",
"plus",
"extra",
"fields",
"."
] | train | https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/mapping.py#L109-L122 |
ANCIR/granoloader | granoloader/mapping.py | ObjectMapper.get_source | def get_source(self, spec, row):
""" Sources can be specified as plain strings or as a reference to a column. """
value = self.get_value({'column': spec.get('source_url_column')}, row)
if value is not None:
return value
return spec.get('source_url') | python | def get_source(self, spec, row):
""" Sources can be specified as plain strings or as a reference to a column. """
value = self.get_value({'column': spec.get('source_url_column')}, row)
if value is not None:
return value
return spec.get('source_url') | [
"def",
"get_source",
"(",
"self",
",",
"spec",
",",
"row",
")",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"{",
"'column'",
":",
"spec",
".",
"get",
"(",
"'source_url_column'",
")",
"}",
",",
"row",
")",
"if",
"value",
"is",
"not",
"None",
"... | Sources can be specified as plain strings or as a reference to a column. | [
"Sources",
"can",
"be",
"specified",
"as",
"plain",
"strings",
"or",
"as",
"a",
"reference",
"to",
"a",
"column",
"."
] | train | https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/mapping.py#L124-L129 |
ANCIR/granoloader | granoloader/mapping.py | MappingLoader.load | def load(self, data):
""" Load a single row of data and convert it into entities and
relations. """
objs = {}
for mapper in self.entities:
objs[mapper.name] = mapper.load(self.loader, data)
for mapper in self.relations:
objs[mapper.name] = mapper.load(sel... | python | def load(self, data):
""" Load a single row of data and convert it into entities and
relations. """
objs = {}
for mapper in self.entities:
objs[mapper.name] = mapper.load(self.loader, data)
for mapper in self.relations:
objs[mapper.name] = mapper.load(sel... | [
"def",
"load",
"(",
"self",
",",
"data",
")",
":",
"objs",
"=",
"{",
"}",
"for",
"mapper",
"in",
"self",
".",
"entities",
":",
"objs",
"[",
"mapper",
".",
"name",
"]",
"=",
"mapper",
".",
"load",
"(",
"self",
".",
"loader",
",",
"data",
")",
"f... | Load a single row of data and convert it into entities and
relations. | [
"Load",
"a",
"single",
"row",
"of",
"data",
"and",
"convert",
"it",
"into",
"entities",
"and",
"relations",
"."
] | train | https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/mapping.py#L210-L218 |
olsoneric/pedemath | pedemath/vec3.py | add_v3 | def add_v3(vec1, m):
"""Return a new Vec3 containing the sum of our x, y, z, and arg.
If argument is a float or vec, addt it to our x, y, and z.
Otherwise, treat it as a Vec3 and add arg.x, arg.y, and arg.z from
our own x, y, and z.
"""
if type(m) in NUMERIC_TYPES:
return Vec3(vec1.x +... | python | def add_v3(vec1, m):
"""Return a new Vec3 containing the sum of our x, y, z, and arg.
If argument is a float or vec, addt it to our x, y, and z.
Otherwise, treat it as a Vec3 and add arg.x, arg.y, and arg.z from
our own x, y, and z.
"""
if type(m) in NUMERIC_TYPES:
return Vec3(vec1.x +... | [
"def",
"add_v3",
"(",
"vec1",
",",
"m",
")",
":",
"if",
"type",
"(",
"m",
")",
"in",
"NUMERIC_TYPES",
":",
"return",
"Vec3",
"(",
"vec1",
".",
"x",
"+",
"m",
",",
"vec1",
".",
"y",
"+",
"m",
",",
"vec1",
".",
"z",
"+",
"m",
")",
"else",
":"... | Return a new Vec3 containing the sum of our x, y, z, and arg.
If argument is a float or vec, addt it to our x, y, and z.
Otherwise, treat it as a Vec3 and add arg.x, arg.y, and arg.z from
our own x, y, and z. | [
"Return",
"a",
"new",
"Vec3",
"containing",
"the",
"sum",
"of",
"our",
"x",
"y",
"z",
"and",
"arg",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L22-L32 |
olsoneric/pedemath | pedemath/vec3.py | translate_v3 | def translate_v3(vec, amount):
"""Return a new Vec3 that is translated version of vec."""
return Vec3(vec.x+amount, vec.y+amount, vec.z+amount) | python | def translate_v3(vec, amount):
"""Return a new Vec3 that is translated version of vec."""
return Vec3(vec.x+amount, vec.y+amount, vec.z+amount) | [
"def",
"translate_v3",
"(",
"vec",
",",
"amount",
")",
":",
"return",
"Vec3",
"(",
"vec",
".",
"x",
"+",
"amount",
",",
"vec",
".",
"y",
"+",
"amount",
",",
"vec",
".",
"z",
"+",
"amount",
")"
] | Return a new Vec3 that is translated version of vec. | [
"Return",
"a",
"new",
"Vec3",
"that",
"is",
"translated",
"version",
"of",
"vec",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L55-L58 |
olsoneric/pedemath | pedemath/vec3.py | scale_v3 | def scale_v3(vec, amount):
"""Return a new Vec3 that is a scaled version of vec."""
return Vec3(vec.x*amount, vec.y*amount, vec.z*amount) | python | def scale_v3(vec, amount):
"""Return a new Vec3 that is a scaled version of vec."""
return Vec3(vec.x*amount, vec.y*amount, vec.z*amount) | [
"def",
"scale_v3",
"(",
"vec",
",",
"amount",
")",
":",
"return",
"Vec3",
"(",
"vec",
".",
"x",
"*",
"amount",
",",
"vec",
".",
"y",
"*",
"amount",
",",
"vec",
".",
"z",
"*",
"amount",
")"
] | Return a new Vec3 that is a scaled version of vec. | [
"Return",
"a",
"new",
"Vec3",
"that",
"is",
"a",
"scaled",
"version",
"of",
"vec",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L61-L64 |
olsoneric/pedemath | pedemath/vec3.py | dot_v3 | def dot_v3(v, w):
"""Return the dotproduct of two vectors."""
return sum([x * y for x, y in zip(v, w)]) | python | def dot_v3(v, w):
"""Return the dotproduct of two vectors."""
return sum([x * y for x, y in zip(v, w)]) | [
"def",
"dot_v3",
"(",
"v",
",",
"w",
")",
":",
"return",
"sum",
"(",
"[",
"x",
"*",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"v",
",",
"w",
")",
"]",
")"
] | Return the dotproduct of two vectors. | [
"Return",
"the",
"dotproduct",
"of",
"two",
"vectors",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L73-L76 |
olsoneric/pedemath | pedemath/vec3.py | projection_as_vec_v3 | def projection_as_vec_v3(v, w):
"""Return the signed length of the projection of vector v on vector w.
Returns the full vector result of projection_v3().
"""
proj_len = projection_v3(v, w)
return scale_v3(v, proj_len) | python | def projection_as_vec_v3(v, w):
"""Return the signed length of the projection of vector v on vector w.
Returns the full vector result of projection_v3().
"""
proj_len = projection_v3(v, w)
return scale_v3(v, proj_len) | [
"def",
"projection_as_vec_v3",
"(",
"v",
",",
"w",
")",
":",
"proj_len",
"=",
"projection_v3",
"(",
"v",
",",
"w",
")",
"return",
"scale_v3",
"(",
"v",
",",
"proj_len",
")"
] | Return the signed length of the projection of vector v on vector w.
Returns the full vector result of projection_v3(). | [
"Return",
"the",
"signed",
"length",
"of",
"the",
"projection",
"of",
"vector",
"v",
"on",
"vector",
"w",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L96-L102 |
olsoneric/pedemath | pedemath/vec3.py | point_to_line | def point_to_line(point, segment_start, segment_end):
"""Given a point and a line segment, return the vector from the point to
the closest point on the segment.
"""
# TODO: Needs unittests.
segment_vec = segment_end - segment_start
# t is distance along line
t = -(segment_start - point).dot... | python | def point_to_line(point, segment_start, segment_end):
"""Given a point and a line segment, return the vector from the point to
the closest point on the segment.
"""
# TODO: Needs unittests.
segment_vec = segment_end - segment_start
# t is distance along line
t = -(segment_start - point).dot... | [
"def",
"point_to_line",
"(",
"point",
",",
"segment_start",
",",
"segment_end",
")",
":",
"# TODO: Needs unittests.",
"segment_vec",
"=",
"segment_end",
"-",
"segment_start",
"# t is distance along line",
"t",
"=",
"-",
"(",
"segment_start",
"-",
"point",
")",
".",
... | Given a point and a line segment, return the vector from the point to
the closest point on the segment. | [
"Given",
"a",
"point",
"and",
"a",
"line",
"segment",
"return",
"the",
"vector",
"from",
"the",
"point",
"to",
"the",
"closest",
"point",
"on",
"the",
"segment",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L105-L117 |
olsoneric/pedemath | pedemath/vec3.py | cross_v3 | def cross_v3(vec_a, vec_b):
"""Return the crossproduct between vec_a and vec_b."""
return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y,
vec_a.z * vec_b.x - vec_a.x * vec_b.z,
vec_a.x * vec_b.y - vec_a.y * vec_b.x) | python | def cross_v3(vec_a, vec_b):
"""Return the crossproduct between vec_a and vec_b."""
return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y,
vec_a.z * vec_b.x - vec_a.x * vec_b.z,
vec_a.x * vec_b.y - vec_a.y * vec_b.x) | [
"def",
"cross_v3",
"(",
"vec_a",
",",
"vec_b",
")",
":",
"return",
"Vec3",
"(",
"vec_a",
".",
"y",
"*",
"vec_b",
".",
"z",
"-",
"vec_a",
".",
"z",
"*",
"vec_b",
".",
"y",
",",
"vec_a",
".",
"z",
"*",
"vec_b",
".",
"x",
"-",
"vec_a",
".",
"x",... | Return the crossproduct between vec_a and vec_b. | [
"Return",
"the",
"crossproduct",
"between",
"vec_a",
"and",
"vec_b",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L120-L125 |
olsoneric/pedemath | pedemath/vec3.py | rotate_around_vector_v3 | def rotate_around_vector_v3(v, angle_rad, norm_vec):
""" rotate v around norm_vec by angle_rad."""
cos_val = math.cos(angle_rad)
sin_val = math.sin(angle_rad)
## (v * cosVal) +
## ((normVec * v) * (1.0 - cosVal)) * normVec +
## (v ^ normVec) * sinVal)
#line1: scaleV3(v,cosVal)
#line2: do... | python | def rotate_around_vector_v3(v, angle_rad, norm_vec):
""" rotate v around norm_vec by angle_rad."""
cos_val = math.cos(angle_rad)
sin_val = math.sin(angle_rad)
## (v * cosVal) +
## ((normVec * v) * (1.0 - cosVal)) * normVec +
## (v ^ normVec) * sinVal)
#line1: scaleV3(v,cosVal)
#line2: do... | [
"def",
"rotate_around_vector_v3",
"(",
"v",
",",
"angle_rad",
",",
"norm_vec",
")",
":",
"cos_val",
"=",
"math",
".",
"cos",
"(",
"angle_rad",
")",
"sin_val",
"=",
"math",
".",
"sin",
"(",
"angle_rad",
")",
"## (v * cosVal) +",
"## ((normVec * v) * (1.0 - cosVal... | rotate v around norm_vec by angle_rad. | [
"rotate",
"v",
"around",
"norm_vec",
"by",
"angle_rad",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L136-L153 |
olsoneric/pedemath | pedemath/vec3.py | ave_list_v3 | def ave_list_v3(vec_list):
"""Return the average vector of a list of vectors."""
vec = Vec3(0, 0, 0)
for v in vec_list:
vec += v
num_vecs = float(len(vec_list))
vec = Vec3(vec.x / num_vecs, vec.y / num_vecs, vec.z / num_vecs)
return vec | python | def ave_list_v3(vec_list):
"""Return the average vector of a list of vectors."""
vec = Vec3(0, 0, 0)
for v in vec_list:
vec += v
num_vecs = float(len(vec_list))
vec = Vec3(vec.x / num_vecs, vec.y / num_vecs, vec.z / num_vecs)
return vec | [
"def",
"ave_list_v3",
"(",
"vec_list",
")",
":",
"vec",
"=",
"Vec3",
"(",
"0",
",",
"0",
",",
"0",
")",
"for",
"v",
"in",
"vec_list",
":",
"vec",
"+=",
"v",
"num_vecs",
"=",
"float",
"(",
"len",
"(",
"vec_list",
")",
")",
"vec",
"=",
"Vec3",
"(... | Return the average vector of a list of vectors. | [
"Return",
"the",
"average",
"vector",
"of",
"a",
"list",
"of",
"vectors",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L156-L164 |
olsoneric/pedemath | pedemath/vec3.py | _float_almost_equal | def _float_almost_equal(float1, float2, places=7):
"""Return True if two numbers are equal up to the
specified number of "places" after the decimal point.
"""
if round(abs(float2 - float1), places) == 0:
return True
return False | python | def _float_almost_equal(float1, float2, places=7):
"""Return True if two numbers are equal up to the
specified number of "places" after the decimal point.
"""
if round(abs(float2 - float1), places) == 0:
return True
return False | [
"def",
"_float_almost_equal",
"(",
"float1",
",",
"float2",
",",
"places",
"=",
"7",
")",
":",
"if",
"round",
"(",
"abs",
"(",
"float2",
"-",
"float1",
")",
",",
"places",
")",
"==",
"0",
":",
"return",
"True",
"return",
"False"
] | Return True if two numbers are equal up to the
specified number of "places" after the decimal point. | [
"Return",
"True",
"if",
"two",
"numbers",
"are",
"equal",
"up",
"to",
"the",
"specified",
"number",
"of",
"places",
"after",
"the",
"decimal",
"point",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L428-L436 |
olsoneric/pedemath | pedemath/vec3.py | Vec3.almost_equal | def almost_equal(self, v2, places=7):
"""When comparing for equality, compare floats up to
a limited precision specified by "places".
"""
try:
return (
len(self) == len(v2) and
_float_almost_equal(self.x, v2.x, places) and
_flo... | python | def almost_equal(self, v2, places=7):
"""When comparing for equality, compare floats up to
a limited precision specified by "places".
"""
try:
return (
len(self) == len(v2) and
_float_almost_equal(self.x, v2.x, places) and
_flo... | [
"def",
"almost_equal",
"(",
"self",
",",
"v2",
",",
"places",
"=",
"7",
")",
":",
"try",
":",
"return",
"(",
"len",
"(",
"self",
")",
"==",
"len",
"(",
"v2",
")",
"and",
"_float_almost_equal",
"(",
"self",
".",
"x",
",",
"v2",
".",
"x",
",",
"p... | When comparing for equality, compare floats up to
a limited precision specified by "places". | [
"When",
"comparing",
"for",
"equality",
"compare",
"floats",
"up",
"to",
"a",
"limited",
"precision",
"specified",
"by",
"places",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L291-L303 |
olsoneric/pedemath | pedemath/vec3.py | Vec3.dot | def dot(self, w):
"""Return the dotproduct between self and another vector."""
return sum([x * y for x, y in zip(self, w)]) | python | def dot(self, w):
"""Return the dotproduct between self and another vector."""
return sum([x * y for x, y in zip(self, w)]) | [
"def",
"dot",
"(",
"self",
",",
"w",
")",
":",
"return",
"sum",
"(",
"[",
"x",
"*",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
",",
"w",
")",
"]",
")"
] | Return the dotproduct between self and another vector. | [
"Return",
"the",
"dotproduct",
"between",
"self",
"and",
"another",
"vector",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L321-L324 |
olsoneric/pedemath | pedemath/vec3.py | Vec3.cross | def cross(self, vec):
"""Return the crossproduct between self and vec."""
return Vec3(self.y * vec.z - self.z * vec.y,
self.z * vec.x - self.x * vec.z,
self.x * vec.y - self.y * vec.x) | python | def cross(self, vec):
"""Return the crossproduct between self and vec."""
return Vec3(self.y * vec.z - self.z * vec.y,
self.z * vec.x - self.x * vec.z,
self.x * vec.y - self.y * vec.x) | [
"def",
"cross",
"(",
"self",
",",
"vec",
")",
":",
"return",
"Vec3",
"(",
"self",
".",
"y",
"*",
"vec",
".",
"z",
"-",
"self",
".",
"z",
"*",
"vec",
".",
"y",
",",
"self",
".",
"z",
"*",
"vec",
".",
"x",
"-",
"self",
".",
"x",
"*",
"vec",... | Return the crossproduct between self and vec. | [
"Return",
"the",
"crossproduct",
"between",
"self",
"and",
"vec",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L326-L331 |
olsoneric/pedemath | pedemath/vec3.py | Vec3.set | def set(self, x, y, z):
"""Set x, y, and z components.
Also return self.
"""
self.x = x
self.y = y
self.z = z
return self | python | def set(self, x, y, z):
"""Set x, y, and z components.
Also return self.
"""
self.x = x
self.y = y
self.z = z
return self | [
"def",
"set",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"self",
".",
"x",
"=",
"x",
"self",
".",
"y",
"=",
"y",
"self",
".",
"z",
"=",
"z",
"return",
"self"
] | Set x, y, and z components.
Also return self. | [
"Set",
"x",
"y",
"and",
"z",
"components",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L333-L342 |
olsoneric/pedemath | pedemath/vec3.py | Vec3.neg | def neg(self):
"""Negative value of all components."""
self.x = -self.x
self.y = -self.y
self.z = -self.z | python | def neg(self):
"""Negative value of all components."""
self.x = -self.x
self.y = -self.y
self.z = -self.z | [
"def",
"neg",
"(",
"self",
")",
":",
"self",
".",
"x",
"=",
"-",
"self",
".",
"x",
"self",
".",
"y",
"=",
"-",
"self",
".",
"y",
"self",
".",
"z",
"=",
"-",
"self",
".",
"z"
] | Negative value of all components. | [
"Negative",
"value",
"of",
"all",
"components",
"."
] | train | https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L344-L348 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCache.put | def put(self, source, rel_path, metadata=None):
'''Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository
'''
# This case should probably be deprecated.
i... | python | def put(self, source, rel_path, metadata=None):
'''Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository
'''
# This case should probably be deprecated.
i... | [
"def",
"put",
"(",
"self",
",",
"source",
",",
"rel_path",
",",
"metadata",
"=",
"None",
")",
":",
"# This case should probably be deprecated.",
"if",
"not",
"isinstance",
"(",
"rel_path",
",",
"basestring",
")",
":",
"rel_path",
"=",
"rel_path",
".",
"cache_k... | Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository | [
"Copy",
"a",
"file",
"to",
"the",
"repository"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L70-L95 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCache.put_stream | def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller
is responsibile for closing the stream
"""
from io import IOBase
if not isinstance(rel_path, basestring):
rel_path = rel_path.cache_key
repo_p... | python | def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller
is responsibile for closing the stream
"""
from io import IOBase
if not isinstance(rel_path, basestring):
rel_path = rel_path.cache_key
repo_p... | [
"def",
"put_stream",
"(",
"self",
",",
"rel_path",
",",
"metadata",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"from",
"io",
"import",
"IOBase",
"if",
"not",
"isinstance",
"(",
"rel_path",
",",
"basestring",
")",
":",
"rel_path",
"=",
"rel_path",
"... | return a file object to write into the cache. The caller
is responsibile for closing the stream | [
"return",
"a",
"file",
"object",
"to",
"write",
"into",
"the",
"cache",
".",
"The",
"caller",
"is",
"responsibile",
"for",
"closing",
"the",
"stream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L97-L161 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCache.get | def get(self, rel_path, cb=None):
'''Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure.
'''
import shutil
global_logger.debug("FC {} get looking f... | python | def get(self, rel_path, cb=None):
'''Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure.
'''
import shutil
global_logger.debug("FC {} get looking f... | [
"def",
"get",
"(",
"self",
",",
"rel_path",
",",
"cb",
"=",
"None",
")",
":",
"import",
"shutil",
"global_logger",
".",
"debug",
"(",
"\"FC {} get looking for {}\"",
".",
"format",
"(",
"self",
".",
"repo_id",
",",
"rel_path",
")",
")",
"path",
"=",
"os"... | Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure. | [
"Return",
"the",
"file",
"path",
"referenced",
"but",
"rel_path",
"or",
"None",
"if",
"it",
"can",
"t",
"be",
"found",
".",
"If",
"an",
"upstream",
"is",
"declared",
"it",
"will",
"try",
"to",
"get",
"the",
"file",
"from",
"the",
"upstream",
"before",
... | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L167-L225 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCache.list | def list(self, path=None, with_metadata=False, include_partitions=False):
'''get a list of all of the files in the repository'''
from os import walk
import json
l = {}
if not path:
start_path = self.cache_dir
else:
start_path = os.path.join(self.... | python | def list(self, path=None, with_metadata=False, include_partitions=False):
'''get a list of all of the files in the repository'''
from os import walk
import json
l = {}
if not path:
start_path = self.cache_dir
else:
start_path = os.path.join(self.... | [
"def",
"list",
"(",
"self",
",",
"path",
"=",
"None",
",",
"with_metadata",
"=",
"False",
",",
"include_partitions",
"=",
"False",
")",
":",
"from",
"os",
"import",
"walk",
"import",
"json",
"l",
"=",
"{",
"}",
"if",
"not",
"path",
":",
"start_path",
... | get a list of all of the files in the repository | [
"get",
"a",
"list",
"of",
"all",
"of",
"the",
"files",
"in",
"the",
"repository"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L243-L284 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCache.remove | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
repo_path = os.path.join(self.cache_dir, rel_path)
if os.path.exists(repo_path):
os.remove(repo_path)
if self.upstream and propagate:
self.upstream.remove(re... | python | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
repo_path = os.path.join(self.cache_dir, rel_path)
if os.path.exists(repo_path):
os.remove(repo_path)
if self.upstream and propagate:
self.upstream.remove(re... | [
"def",
"remove",
"(",
"self",
",",
"rel_path",
",",
"propagate",
"=",
"False",
")",
":",
"repo_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"rel_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"repo_path",
... | Delete the file from the cache, and from the upstream | [
"Delete",
"the",
"file",
"from",
"the",
"cache",
"and",
"from",
"the",
"upstream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L354-L362 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.size | def size(self):
'''Return the size of all of the files referenced in the database'''
c = self.database.cursor()
r = c.execute("SELECT sum(size) FROM files")
try:
size = int(r.fetchone()[0])
except TypeError:
size = 0
return size | python | def size(self):
'''Return the size of all of the files referenced in the database'''
c = self.database.cursor()
r = c.execute("SELECT sum(size) FROM files")
try:
size = int(r.fetchone()[0])
except TypeError:
size = 0
return size | [
"def",
"size",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
")",
"r",
"=",
"c",
".",
"execute",
"(",
"\"SELECT sum(size) FROM files\"",
")",
"try",
":",
"size",
"=",
"int",
"(",
"r",
".",
"fetchone",
"(",
")",
"[",
... | Return the size of all of the files referenced in the database | [
"Return",
"the",
"size",
"of",
"all",
"of",
"the",
"files",
"referenced",
"in",
"the",
"database"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L496-L506 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache._free_up_space | def _free_up_space(self, size, this_rel_path=None):
'''If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it.
'''
# Amount of space w... | python | def _free_up_space(self, size, this_rel_path=None):
'''If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it.
'''
# Amount of space w... | [
"def",
"_free_up_space",
"(",
"self",
",",
"size",
",",
"this_rel_path",
"=",
"None",
")",
":",
"# Amount of space we are over ( bytes ) for next put",
"space",
"=",
"self",
".",
"size",
"+",
"size",
"-",
"self",
".",
"maxsize",
"if",
"space",
"<=",
"0",
":",
... | If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it. | [
"If",
"there",
"are",
"not",
"size",
"bytes",
"of",
"space",
"left",
"delete",
"files",
"until",
"there",
"is"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L508-L537 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.verify | def verify(self):
'''Check that the database accurately describes the state of the repository'''
c = self.database.cursor()
non_exist = set()
no_db_entry = set(os.listdir(self.cache_dir))
try:
no_db_entry.remove('file_database.db')
no_db_entry.remove('fi... | python | def verify(self):
'''Check that the database accurately describes the state of the repository'''
c = self.database.cursor()
non_exist = set()
no_db_entry = set(os.listdir(self.cache_dir))
try:
no_db_entry.remove('file_database.db')
no_db_entry.remove('fi... | [
"def",
"verify",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
")",
"non_exist",
"=",
"set",
"(",
")",
"no_db_entry",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"self",
".",
"cache_dir",
")",
")",
"try",
":",
"no_... | Check that the database accurately describes the state of the repository | [
"Check",
"that",
"the",
"database",
"accurately",
"describes",
"the",
"state",
"of",
"the",
"repository"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L552-L583 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.get | def get(self, rel_path, cb=None):
'''Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure.
'''
import shutil
global_logger.debug(
"LC {} ... | python | def get(self, rel_path, cb=None):
'''Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure.
'''
import shutil
global_logger.debug(
"LC {} ... | [
"def",
"get",
"(",
"self",
",",
"rel_path",
",",
"cb",
"=",
"None",
")",
":",
"import",
"shutil",
"global_logger",
".",
"debug",
"(",
"\"LC {} get looking for {}\"",
".",
"format",
"(",
"self",
".",
"repo_id",
",",
"rel_path",
")",
")",
"path",
"=",
"os"... | Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure. | [
"Return",
"the",
"file",
"path",
"referenced",
"but",
"rel_path",
"or",
"None",
"if",
"it",
"can",
"t",
"be",
"found",
".",
"If",
"an",
"upstream",
"is",
"declared",
"it",
"will",
"try",
"to",
"get",
"the",
"file",
"from",
"the",
"upstream",
"before",
... | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L597-L657 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.put_stream | def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller
is responsibile for closing the stream. Bad things happen
if you dont close the stream
"""
class flo:
def __init__(self, this, sink, upstream, repo_pa... | python | def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller
is responsibile for closing the stream. Bad things happen
if you dont close the stream
"""
class flo:
def __init__(self, this, sink, upstream, repo_pa... | [
"def",
"put_stream",
"(",
"self",
",",
"rel_path",
",",
"metadata",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"class",
"flo",
":",
"def",
"__init__",
"(",
"self",
",",
"this",
",",
"sink",
",",
"upstream",
",",
"repo_path",
")",
":",
"self",
"... | return a file object to write into the cache. The caller
is responsibile for closing the stream. Bad things happen
if you dont close the stream | [
"return",
"a",
"file",
"object",
"to",
"write",
"into",
"the",
"cache",
".",
"The",
"caller",
"is",
"responsibile",
"for",
"closing",
"the",
"stream",
".",
"Bad",
"things",
"happen",
"if",
"you",
"dont",
"close",
"the",
"stream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L687-L747 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.find | def find(self, query):
'''Passes the query to the upstream, if it exists'''
if self.upstream:
return self.upstream.find(query)
else:
return False | python | def find(self, query):
'''Passes the query to the upstream, if it exists'''
if self.upstream:
return self.upstream.find(query)
else:
return False | [
"def",
"find",
"(",
"self",
",",
"query",
")",
":",
"if",
"self",
".",
"upstream",
":",
"return",
"self",
".",
"upstream",
".",
"find",
"(",
"query",
")",
"else",
":",
"return",
"False"
] | Passes the query to the upstream, if it exists | [
"Passes",
"the",
"query",
"to",
"the",
"upstream",
"if",
"it",
"exists"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L749-L754 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.remove | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
repo_path = os.path.join(self.cache_dir, rel_path)
c = self.database.cursor()
c.execute("DELETE FROM files WHERE path = ?", (rel_path,))
if os.path.exists(repo_path):
... | python | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
repo_path = os.path.join(self.cache_dir, rel_path)
c = self.database.cursor()
c.execute("DELETE FROM files WHERE path = ?", (rel_path,))
if os.path.exists(repo_path):
... | [
"def",
"remove",
"(",
"self",
",",
"rel_path",
",",
"propagate",
"=",
"False",
")",
":",
"repo_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"rel_path",
")",
"c",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
"... | Delete the file from the cache, and from the upstream | [
"Delete",
"the",
"file",
"from",
"the",
"cache",
"and",
"from",
"the",
"upstream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L756-L769 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsLimitedCache.list | def list(self, path=None, with_metadata=False):
'''get a list of all of the files in the repository'''
path = path.strip('/') if path else ''
if self.upstream:
return self.upstream.list(path, with_metadata=with_metadata)
else:
raise NotImplementedError() | python | def list(self, path=None, with_metadata=False):
'''get a list of all of the files in the repository'''
path = path.strip('/') if path else ''
if self.upstream:
return self.upstream.list(path, with_metadata=with_metadata)
else:
raise NotImplementedError() | [
"def",
"list",
"(",
"self",
",",
"path",
"=",
"None",
",",
"with_metadata",
"=",
"False",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
"if",
"path",
"else",
"''",
"if",
"self",
".",
"upstream",
":",
"return",
"self",
".",
"upstream... | get a list of all of the files in the repository | [
"get",
"a",
"list",
"of",
"all",
"of",
"the",
"files",
"in",
"the",
"repository"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L771-L779 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCompressionCache.find | def find(self, query):
'''Passes the query to the upstream, if it exists'''
if not self.upstream:
raise Exception("CompressionCache must have an upstream")
return self.upstream.find(query) | python | def find(self, query):
'''Passes the query to the upstream, if it exists'''
if not self.upstream:
raise Exception("CompressionCache must have an upstream")
return self.upstream.find(query) | [
"def",
"find",
"(",
"self",
",",
"query",
")",
":",
"if",
"not",
"self",
".",
"upstream",
":",
"raise",
"Exception",
"(",
"\"CompressionCache must have an upstream\"",
")",
"return",
"self",
".",
"upstream",
".",
"find",
"(",
"query",
")"
] | Passes the query to the upstream, if it exists | [
"Passes",
"the",
"query",
"to",
"the",
"upstream",
"if",
"it",
"exists"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L924-L929 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCompressionCache.remove | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
if not self.upstream:
raise Exception("CompressionCache must have an upstream")
# Must always propagate, since this is really just a filter.
self.upstream.remove(self._r... | python | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
if not self.upstream:
raise Exception("CompressionCache must have an upstream")
# Must always propagate, since this is really just a filter.
self.upstream.remove(self._r... | [
"def",
"remove",
"(",
"self",
",",
"rel_path",
",",
"propagate",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"upstream",
":",
"raise",
"Exception",
"(",
"\"CompressionCache must have an upstream\"",
")",
"# Must always propagate, since this is really just a filter... | Delete the file from the cache, and from the upstream | [
"Delete",
"the",
"file",
"from",
"the",
"cache",
"and",
"from",
"the",
"upstream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L935-L947 |
CivicSpleen/ckcache | ckcache/filesystem.py | FsCompressionCache.list | def list(self, path=None, with_metadata=False, include_partitions=False):
'''get a list of all of the files in the repository'''
l = self.upstream.list(
path,
with_metadata=with_metadata,
include_partitions=include_partitions)
lp = {}
for k, v in l.it... | python | def list(self, path=None, with_metadata=False, include_partitions=False):
'''get a list of all of the files in the repository'''
l = self.upstream.list(
path,
with_metadata=with_metadata,
include_partitions=include_partitions)
lp = {}
for k, v in l.it... | [
"def",
"list",
"(",
"self",
",",
"path",
"=",
"None",
",",
"with_metadata",
"=",
"False",
",",
"include_partitions",
"=",
"False",
")",
":",
"l",
"=",
"self",
".",
"upstream",
".",
"list",
"(",
"path",
",",
"with_metadata",
"=",
"with_metadata",
",",
"... | get a list of all of the files in the repository | [
"get",
"a",
"list",
"of",
"all",
"of",
"the",
"files",
"in",
"the",
"repository"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/filesystem.py#L970-L981 |
edeposit/edeposit.amqp.ltp | src/edeposit/amqp/ltp/__init__.py | reactToAMQPMessage | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | python | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | [
"def",
"reactToAMQPMessage",
"(",
"message",
",",
"send_back",
")",
":",
"if",
"_instanceof",
"(",
"message",
",",
"ExportRequest",
")",
":",
"tmp_folder",
"=",
"ltp",
".",
"create_ltp_package",
"(",
"aleph_record",
"=",
"message",
".",
"aleph_record",
",",
"b... | React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
:mod:`.structures`.
send_back (fn reference)... | [
"React",
"to",
"given",
"(",
"AMQP",
")",
"message",
".",
"message",
"is",
"expected",
"to",
"be",
":",
"py",
":",
"func",
":",
"collections",
".",
"namedtuple",
"structure",
"from",
":",
"mod",
":",
".",
"structures",
"filled",
"with",
"all",
"necessary... | train | https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/__init__.py#L28-L95 |
sigvaldm/frmt | frmt.py | format_fit | def format_fit(text, width=None, align='<', suffix="..."):
"""
Fits a piece of text to ``width`` characters by truncating too long text and
padding too short text with spaces. Defaults to terminal width. Truncation
is indicated by a customizable suffix. ``align`` specifies the alignment of
the conte... | python | def format_fit(text, width=None, align='<', suffix="..."):
"""
Fits a piece of text to ``width`` characters by truncating too long text and
padding too short text with spaces. Defaults to terminal width. Truncation
is indicated by a customizable suffix. ``align`` specifies the alignment of
the conte... | [
"def",
"format_fit",
"(",
"text",
",",
"width",
"=",
"None",
",",
"align",
"=",
"'<'",
",",
"suffix",
"=",
"\"...\"",
")",
":",
"if",
"width",
"==",
"None",
":",
"width",
"=",
"get_terminal_size",
"(",
")",
".",
"columns",
"if",
"len",
"(",
"text",
... | Fits a piece of text to ``width`` characters by truncating too long text and
padding too short text with spaces. Defaults to terminal width. Truncation
is indicated by a customizable suffix. ``align`` specifies the alignment of
the contents if it is padded, and can be:
* ``<`` - Left aligned (default)
... | [
"Fits",
"a",
"piece",
"of",
"text",
"to",
"width",
"characters",
"by",
"truncating",
"too",
"long",
"text",
"and",
"padding",
"too",
"short",
"text",
"with",
"spaces",
".",
"Defaults",
"to",
"terminal",
"width",
".",
"Truncation",
"is",
"indicated",
"by",
... | train | https://github.com/sigvaldm/frmt/blob/d077af06c83a7a0533ca2218be55ce086df274b7/frmt.py#L28-L49 |
sigvaldm/frmt | frmt.py | format_time | def format_time(seconds):
"""
Formats a string from time given in seconds. For large times
(``abs(seconds) >= 60``) the format is::
dd:hh:mm:ss
For small times (``abs(seconds) < 60``), the result is given in 3
significant figures, with units given in seconds and a suitable SI-prefix.
"... | python | def format_time(seconds):
"""
Formats a string from time given in seconds. For large times
(``abs(seconds) >= 60``) the format is::
dd:hh:mm:ss
For small times (``abs(seconds) < 60``), the result is given in 3
significant figures, with units given in seconds and a suitable SI-prefix.
"... | [
"def",
"format_time",
"(",
"seconds",
")",
":",
"if",
"not",
"isinstance",
"(",
"seconds",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"str",
"(",
"seconds",
")",
"if",
"math",
".",
"isnan",
"(",
"seconds",
")",
":",
"return",
"\"-\"",
... | Formats a string from time given in seconds. For large times
(``abs(seconds) >= 60``) the format is::
dd:hh:mm:ss
For small times (``abs(seconds) < 60``), the result is given in 3
significant figures, with units given in seconds and a suitable SI-prefix. | [
"Formats",
"a",
"string",
"from",
"time",
"given",
"in",
"seconds",
".",
"For",
"large",
"times",
"(",
"abs",
"(",
"seconds",
")",
">",
"=",
"60",
")",
"the",
"format",
"is",
"::"
] | train | https://github.com/sigvaldm/frmt/blob/d077af06c83a7a0533ca2218be55ce086df274b7/frmt.py#L51-L71 |
sigvaldm/frmt | frmt.py | format_time_small | def format_time_small(seconds):
"""
Same as format_time() but always uses SI-prefix and 3 significant figures.
"""
if not isinstance(seconds, (int, float)):
return str(seconds)
if math.isnan(seconds):
return "-"
if abs(seconds)<1:
milliseconds = 1000*seconds
if... | python | def format_time_small(seconds):
"""
Same as format_time() but always uses SI-prefix and 3 significant figures.
"""
if not isinstance(seconds, (int, float)):
return str(seconds)
if math.isnan(seconds):
return "-"
if abs(seconds)<1:
milliseconds = 1000*seconds
if... | [
"def",
"format_time_small",
"(",
"seconds",
")",
":",
"if",
"not",
"isinstance",
"(",
"seconds",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"str",
"(",
"seconds",
")",
"if",
"math",
".",
"isnan",
"(",
"seconds",
")",
":",
"return",
"\"-\... | Same as format_time() but always uses SI-prefix and 3 significant figures. | [
"Same",
"as",
"format_time",
"()",
"but",
"always",
"uses",
"SI",
"-",
"prefix",
"and",
"3",
"significant",
"figures",
"."
] | train | https://github.com/sigvaldm/frmt/blob/d077af06c83a7a0533ca2218be55ce086df274b7/frmt.py#L73-L111 |
sigvaldm/frmt | frmt.py | format_time_large | def format_time_large(seconds):
"""
Same as format_time() but always uses the format dd:hh:mm:ss.
"""
if not isinstance(seconds, (int, float)):
return str(seconds)
if math.isnan(seconds):
return "-"
seconds = int(round(seconds))
if abs(seconds)<60:
return "{:d}".fo... | python | def format_time_large(seconds):
"""
Same as format_time() but always uses the format dd:hh:mm:ss.
"""
if not isinstance(seconds, (int, float)):
return str(seconds)
if math.isnan(seconds):
return "-"
seconds = int(round(seconds))
if abs(seconds)<60:
return "{:d}".fo... | [
"def",
"format_time_large",
"(",
"seconds",
")",
":",
"if",
"not",
"isinstance",
"(",
"seconds",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"str",
"(",
"seconds",
")",
"if",
"math",
".",
"isnan",
"(",
"seconds",
")",
":",
"return",
"\"-\... | Same as format_time() but always uses the format dd:hh:mm:ss. | [
"Same",
"as",
"format_time",
"()",
"but",
"always",
"uses",
"the",
"format",
"dd",
":",
"hh",
":",
"mm",
":",
"ss",
"."
] | train | https://github.com/sigvaldm/frmt/blob/d077af06c83a7a0533ca2218be55ce086df274b7/frmt.py#L113-L141 |
sigvaldm/frmt | frmt.py | format_table | def format_table(table,
align='<',
format='{:.3g}',
colwidth=None,
maxwidth=None,
spacing=2,
truncate=0,
suffix="..."
):
"""
Formats a table represented as an iterable of iterab... | python | def format_table(table,
align='<',
format='{:.3g}',
colwidth=None,
maxwidth=None,
spacing=2,
truncate=0,
suffix="..."
):
"""
Formats a table represented as an iterable of iterab... | [
"def",
"format_table",
"(",
"table",
",",
"align",
"=",
"'<'",
",",
"format",
"=",
"'{:.3g}'",
",",
"colwidth",
"=",
"None",
",",
"maxwidth",
"=",
"None",
",",
"spacing",
"=",
"2",
",",
"truncate",
"=",
"0",
",",
"suffix",
"=",
"\"...\"",
")",
":",
... | Formats a table represented as an iterable of iterable into a nice big string
suitable for printing.
Parameters:
-----------
align : string or list of strings
Alignment of cell contents. Each character in a string specifies
the alignment of one column.
* ``<`` - Le... | [
"Formats",
"a",
"table",
"represented",
"as",
"an",
"iterable",
"of",
"iterable",
"into",
"a",
"nice",
"big",
"string",
"suitable",
"for",
"printing",
"."
] | train | https://github.com/sigvaldm/frmt/blob/d077af06c83a7a0533ca2218be55ce086df274b7/frmt.py#L143-L277 |
DirectlineDev/python-myeventhub | myeventhub/client.py | Client._call | def _call(self, method, **kwargs):
""" Вызов метода API
"""
kwargs.update(dict(
partnerid=self.partner_id,
partnerkey=self.partner_key,
method=method,
))
url = options.ENDPOINT_URL + '?' + parse.urlencode(kwargs)
try:
raw_j... | python | def _call(self, method, **kwargs):
""" Вызов метода API
"""
kwargs.update(dict(
partnerid=self.partner_id,
partnerkey=self.partner_key,
method=method,
))
url = options.ENDPOINT_URL + '?' + parse.urlencode(kwargs)
try:
raw_j... | [
"def",
"_call",
"(",
"self",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"dict",
"(",
"partnerid",
"=",
"self",
".",
"partner_id",
",",
"partnerkey",
"=",
"self",
".",
"partner_key",
",",
"method",
"=",
"method",
"... | Вызов метода API | [
"Вызов",
"метода",
"API"
] | train | https://github.com/DirectlineDev/python-myeventhub/blob/7d3351cbe22d9cb490f67fac66391a27b1c9e9e1/myeventhub/client.py#L25-L45 |
DirectlineDev/python-myeventhub | myeventhub/client.py | Client.get_action_list | def get_action_list(self, page=1):
""" Получение списка событий
:param page: (опционально) номер страницы, начинается с 1
:param filter: todo
:return:
"""
kw = {}
if page:
kw['inum'] = page
actions, _ = self._call('getactionlist', **kw)
... | python | def get_action_list(self, page=1):
""" Получение списка событий
:param page: (опционально) номер страницы, начинается с 1
:param filter: todo
:return:
"""
kw = {}
if page:
kw['inum'] = page
actions, _ = self._call('getactionlist', **kw)
... | [
"def",
"get_action_list",
"(",
"self",
",",
"page",
"=",
"1",
")",
":",
"kw",
"=",
"{",
"}",
"if",
"page",
":",
"kw",
"[",
"'inum'",
"]",
"=",
"page",
"actions",
",",
"_",
"=",
"self",
".",
"_call",
"(",
"'getactionlist'",
",",
"*",
"*",
"kw",
... | Получение списка событий
:param page: (опционально) номер страницы, начинается с 1
:param filter: todo
:return: | [
"Получение",
"списка",
"событий",
":",
"param",
"page",
":",
"(",
"опционально",
")",
"номер",
"страницы",
"начинается",
"с",
"1",
":",
"param",
"filter",
":",
"todo",
":",
"return",
":"
] | train | https://github.com/DirectlineDev/python-myeventhub/blob/7d3351cbe22d9cb490f67fac66391a27b1c9e9e1/myeventhub/client.py#L53-L66 |
DirectlineDev/python-myeventhub | myeventhub/client.py | Client.get_action_by_id | def get_action_by_id(self, action_id):
""" Получение детального описания события
"""
parsed_json, raw_json = self._call('getactionbyid', element_id=action_id)
action = Action.object_from_api(parsed_json, raw_json)
return action | python | def get_action_by_id(self, action_id):
""" Получение детального описания события
"""
parsed_json, raw_json = self._call('getactionbyid', element_id=action_id)
action = Action.object_from_api(parsed_json, raw_json)
return action | [
"def",
"get_action_by_id",
"(",
"self",
",",
"action_id",
")",
":",
"parsed_json",
",",
"raw_json",
"=",
"self",
".",
"_call",
"(",
"'getactionbyid'",
",",
"element_id",
"=",
"action_id",
")",
"action",
"=",
"Action",
".",
"object_from_api",
"(",
"parsed_json"... | Получение детального описания события | [
"Получение",
"детального",
"описания",
"события"
] | train | https://github.com/DirectlineDev/python-myeventhub/blob/7d3351cbe22d9cb490f67fac66391a27b1c9e9e1/myeventhub/client.py#L68-L73 |
DirectlineDev/python-myeventhub | myeventhub/client.py | Client.all_actions | def all_actions(self):
""" Генератор, возвращающий все события
"""
count = self.get_count_action()
page = 1
while True: # не цикл for, потому как не уверен, что всё норм будет с API
actions = self.get_action_list(page=page)
for action in actions:
... | python | def all_actions(self):
""" Генератор, возвращающий все события
"""
count = self.get_count_action()
page = 1
while True: # не цикл for, потому как не уверен, что всё норм будет с API
actions = self.get_action_list(page=page)
for action in actions:
... | [
"def",
"all_actions",
"(",
"self",
")",
":",
"count",
"=",
"self",
".",
"get_count_action",
"(",
")",
"page",
"=",
"1",
"while",
"True",
":",
"# не цикл for, потому как не уверен, что всё норм будет с API",
"actions",
"=",
"self",
".",
"get_action_list",
"(",
"pag... | Генератор, возвращающий все события | [
"Генератор",
"возвращающий",
"все",
"события"
] | train | https://github.com/DirectlineDev/python-myeventhub/blob/7d3351cbe22d9cb490f67fac66391a27b1c9e9e1/myeventhub/client.py#L75-L86 |
waltermoreira/tartpy | tartpy/membrane.py | MembraneFactory.create_proxy | def create_proxy(self, this, message):
"""Create proxy for an actor.
`message` has the form::
{'tag': 'create_proxy',
'actor': ...,
'customer': ...
}
"""
actor = message['actor']
proxy = self._create_proxy(this, actor)
... | python | def create_proxy(self, this, message):
"""Create proxy for an actor.
`message` has the form::
{'tag': 'create_proxy',
'actor': ...,
'customer': ...
}
"""
actor = message['actor']
proxy = self._create_proxy(this, actor)
... | [
"def",
"create_proxy",
"(",
"self",
",",
"this",
",",
"message",
")",
":",
"actor",
"=",
"message",
"[",
"'actor'",
"]",
"proxy",
"=",
"self",
".",
"_create_proxy",
"(",
"this",
",",
"actor",
")",
"message",
"[",
"'customer'",
"]",
"<<",
"proxy"
] | Create proxy for an actor.
`message` has the form::
{'tag': 'create_proxy',
'actor': ...,
'customer': ...
} | [
"Create",
"proxy",
"for",
"an",
"actor",
"."
] | train | https://github.com/waltermoreira/tartpy/blob/d9f66c8b373bd55a7b055c0fd39b516490bb0235/tartpy/membrane.py#L47-L60 |
francois-vincent/clingon | examples/example3.py | my_func | def my_func(p1, p2,
first_option='default_value',
second_option=5,
third_option=[],
last_option=False,
*args):
"""Help docstring
"""
print('%s %s %s %s %s %s %s' % (p1, p2, args, first_option, second_option, third_option, last_option))
# this w... | python | def my_func(p1, p2,
first_option='default_value',
second_option=5,
third_option=[],
last_option=False,
*args):
"""Help docstring
"""
print('%s %s %s %s %s %s %s' % (p1, p2, args, first_option, second_option, third_option, last_option))
# this w... | [
"def",
"my_func",
"(",
"p1",
",",
"p2",
",",
"first_option",
"=",
"'default_value'",
",",
"second_option",
"=",
"5",
",",
"third_option",
"=",
"[",
"]",
",",
"last_option",
"=",
"False",
",",
"*",
"args",
")",
":",
"print",
"(",
"'%s %s %s %s %s %s %s'",
... | Help docstring | [
"Help",
"docstring"
] | train | https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/examples/example3.py#L16-L26 |
hobson/pug-invest | pug/invest/models.py | get_dataframes | def get_dataframes(symbols=("sne", "goog", "tsla"), source='yahoo', refresh=False):
"""Retreive table of market data ("Close", "Volume", "Adj Close") for each symbol requested
>>> dfdict = get_dataframes('GOOG', 'SNE')
"""
symbols = util.make_symbols(list(symbols))
if refresh:
symbols_to_re... | python | def get_dataframes(symbols=("sne", "goog", "tsla"), source='yahoo', refresh=False):
"""Retreive table of market data ("Close", "Volume", "Adj Close") for each symbol requested
>>> dfdict = get_dataframes('GOOG', 'SNE')
"""
symbols = util.make_symbols(list(symbols))
if refresh:
symbols_to_re... | [
"def",
"get_dataframes",
"(",
"symbols",
"=",
"(",
"\"sne\"",
",",
"\"goog\"",
",",
"\"tsla\"",
")",
",",
"source",
"=",
"'yahoo'",
",",
"refresh",
"=",
"False",
")",
":",
"symbols",
"=",
"util",
".",
"make_symbols",
"(",
"list",
"(",
"symbols",
")",
"... | Retreive table of market data ("Close", "Volume", "Adj Close") for each symbol requested
>>> dfdict = get_dataframes('GOOG', 'SNE') | [
"Retreive",
"table",
"of",
"market",
"data",
"(",
"Close",
"Volume",
"Adj",
"Close",
")",
"for",
"each",
"symbol",
"requested"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/models.py#L37-L76 |
hobson/pug-invest | pug/invest/models.py | price_dataframe | def price_dataframe(symbols=('sne',),
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31),
price_type='actual_close',
cleaner=util.clean_dataframe,
):
"""Retrieve the prices of a list of equities as a DataFrame (columns = symbols)
Arguments:
symbols (list of str):... | python | def price_dataframe(symbols=('sne',),
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31),
price_type='actual_close',
cleaner=util.clean_dataframe,
):
"""Retrieve the prices of a list of equities as a DataFrame (columns = symbols)
Arguments:
symbols (list of str):... | [
"def",
"price_dataframe",
"(",
"symbols",
"=",
"(",
"'sne'",
",",
")",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2008",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2009",
",",
"12",
",",
"31",
")",
","... | Retrieve the prices of a list of equities as a DataFrame (columns = symbols)
Arguments:
symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc
e.g. ["AAPL", " slv ", GLD", "GOOG", "$SPX", "XOM", "msft"]
start (datetime): The date at the start of the period being analyzed.
end (dat... | [
"Retrieve",
"the",
"prices",
"of",
"a",
"list",
"of",
"equities",
"as",
"a",
"DataFrame",
"(",
"columns",
"=",
"symbols",
")"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/models.py#L83-L109 |
jalanb/pysyte | pysyte/dictionaries.py | get_caselessly | def get_caselessly(dictionary, sought):
"""Find the sought key in the given dictionary regardless of case
>>> things = {'Fred' : 9}
>>> print(get_caselessly(things, 'fred'))
9
"""
try:
return dictionary[sought]
except KeyError:
caseless_keys = {k.lower(): k for k in dictiona... | python | def get_caselessly(dictionary, sought):
"""Find the sought key in the given dictionary regardless of case
>>> things = {'Fred' : 9}
>>> print(get_caselessly(things, 'fred'))
9
"""
try:
return dictionary[sought]
except KeyError:
caseless_keys = {k.lower(): k for k in dictiona... | [
"def",
"get_caselessly",
"(",
"dictionary",
",",
"sought",
")",
":",
"try",
":",
"return",
"dictionary",
"[",
"sought",
"]",
"except",
"KeyError",
":",
"caseless_keys",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"k",
"for",
"k",
"in",
"dictionary",
".... | Find the sought key in the given dictionary regardless of case
>>> things = {'Fred' : 9}
>>> print(get_caselessly(things, 'fred'))
9 | [
"Find",
"the",
"sought",
"key",
"in",
"the",
"given",
"dictionary",
"regardless",
"of",
"case"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/dictionaries.py#L8-L20 |
jalanb/pysyte | pysyte/dictionaries.py | append_value | def append_value(dictionary, key, item):
"""Append those items to the values for that key"""
items = dictionary.get(key, [])
items.append(item)
dictionary[key] = items | python | def append_value(dictionary, key, item):
"""Append those items to the values for that key"""
items = dictionary.get(key, [])
items.append(item)
dictionary[key] = items | [
"def",
"append_value",
"(",
"dictionary",
",",
"key",
",",
"item",
")",
":",
"items",
"=",
"dictionary",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
"items",
".",
"append",
"(",
"item",
")",
"dictionary",
"[",
"key",
"]",
"=",
"items"
] | Append those items to the values for that key | [
"Append",
"those",
"items",
"to",
"the",
"values",
"for",
"that",
"key"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/dictionaries.py#L34-L38 |
jalanb/pysyte | pysyte/dictionaries.py | extend_values | def extend_values(dictionary, key, items):
"""Extend the values for that key with the items"""
values = dictionary.get(key, [])
try:
values.extend(items)
except TypeError:
raise TypeError('Expected a list, got: %r' % items)
dictionary[key] = values | python | def extend_values(dictionary, key, items):
"""Extend the values for that key with the items"""
values = dictionary.get(key, [])
try:
values.extend(items)
except TypeError:
raise TypeError('Expected a list, got: %r' % items)
dictionary[key] = values | [
"def",
"extend_values",
"(",
"dictionary",
",",
"key",
",",
"items",
")",
":",
"values",
"=",
"dictionary",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
"try",
":",
"values",
".",
"extend",
"(",
"items",
")",
"except",
"TypeError",
":",
"raise",
"Type... | Extend the values for that key with the items | [
"Extend",
"the",
"values",
"for",
"that",
"key",
"with",
"the",
"items"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/dictionaries.py#L41-L48 |
jalanb/pysyte | pysyte/dictionaries.py | group_list | def group_list(items):
"""Items in the list are grouped into a dictionary
Items should be a list of (key, value) pairs
>>> grouped = group_list([(1,0), (2,0), (1,1)])
>>> grouped[1] == [0,1]
True
"""
groups = defaultdict(list)
for key, value in items:
groups[key].append(value)
... | python | def group_list(items):
"""Items in the list are grouped into a dictionary
Items should be a list of (key, value) pairs
>>> grouped = group_list([(1,0), (2,0), (1,1)])
>>> grouped[1] == [0,1]
True
"""
groups = defaultdict(list)
for key, value in items:
groups[key].append(value)
... | [
"def",
"group_list",
"(",
"items",
")",
":",
"groups",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"key",
",",
"value",
"in",
"items",
":",
"groups",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")",
"return",
"groups"
] | Items in the list are grouped into a dictionary
Items should be a list of (key, value) pairs
>>> grouped = group_list([(1,0), (2,0), (1,1)])
>>> grouped[1] == [0,1]
True | [
"Items",
"in",
"the",
"list",
"are",
"grouped",
"into",
"a",
"dictionary"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/dictionaries.py#L51-L63 |
jalanb/pysyte | pysyte/dictionaries.py | group_list_by | def group_list_by(items, key_from_item):
"""Items in the list are grouped into a dictionary
key_from_item is a method to get the key from the item
>>> items = [(1,9), (2,8), (1,7)]
>>> key_from_item = lambda x: 'a' if x[0] == 1 else 'b'
>>> grouped = group_list_by(items, key_from_item)
>>> gro... | python | def group_list_by(items, key_from_item):
"""Items in the list are grouped into a dictionary
key_from_item is a method to get the key from the item
>>> items = [(1,9), (2,8), (1,7)]
>>> key_from_item = lambda x: 'a' if x[0] == 1 else 'b'
>>> grouped = group_list_by(items, key_from_item)
>>> gro... | [
"def",
"group_list_by",
"(",
"items",
",",
"key_from_item",
")",
":",
"groups",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"items",
":",
"key",
"=",
"key_from_item",
"(",
"item",
")",
"groups",
"[",
"key",
"]",
".",
"append",
"(",
"item... | Items in the list are grouped into a dictionary
key_from_item is a method to get the key from the item
>>> items = [(1,9), (2,8), (1,7)]
>>> key_from_item = lambda x: 'a' if x[0] == 1 else 'b'
>>> grouped = group_list_by(items, key_from_item)
>>> grouped['a'] == [(1, 9), (1, 7)]
True | [
"Items",
"in",
"the",
"list",
"are",
"grouped",
"into",
"a",
"dictionary"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/dictionaries.py#L66-L81 |
diffeo/rejester | rejester/workers.py | run_worker | def run_worker(worker_class, *args, **kwargs):
'''Bridge function to run a worker under :mod:`multiprocessing`.
The :mod:`multiprocessing` module cannot
:meth:`~multiprocessing.Pool.apply_async` to a class constructor,
even if the ``__init__`` calls ``.run()``, so this simple wrapper
calls ``worker... | python | def run_worker(worker_class, *args, **kwargs):
'''Bridge function to run a worker under :mod:`multiprocessing`.
The :mod:`multiprocessing` module cannot
:meth:`~multiprocessing.Pool.apply_async` to a class constructor,
even if the ``__init__`` calls ``.run()``, so this simple wrapper
calls ``worker... | [
"def",
"run_worker",
"(",
"worker_class",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"worker",
"=",
"worker_class",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"logger",
".",
"critical",
"(",
"'fa... | Bridge function to run a worker under :mod:`multiprocessing`.
The :mod:`multiprocessing` module cannot
:meth:`~multiprocessing.Pool.apply_async` to a class constructor,
even if the ``__init__`` calls ``.run()``, so this simple wrapper
calls ``worker_class(*args, **kwargs)`` and logs any exceptions
... | [
"Bridge",
"function",
"to",
"run",
"a",
"worker",
"under",
":",
"mod",
":",
"multiprocessing",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L81-L122 |
diffeo/rejester | rejester/workers.py | MultiWorker._get_and_start_work | def _get_and_start_work(self):
"return (async_result, work_unit) or (None, None)"
worker_id = nice_identifier()
work_unit = self.task_master.get_work(worker_id, available_gb=self.available_gb())
if work_unit is None:
return None, None
async_result = self.pool.apply_as... | python | def _get_and_start_work(self):
"return (async_result, work_unit) or (None, None)"
worker_id = nice_identifier()
work_unit = self.task_master.get_work(worker_id, available_gb=self.available_gb())
if work_unit is None:
return None, None
async_result = self.pool.apply_as... | [
"def",
"_get_and_start_work",
"(",
"self",
")",
":",
"worker_id",
"=",
"nice_identifier",
"(",
")",
"work_unit",
"=",
"self",
".",
"task_master",
".",
"get_work",
"(",
"worker_id",
",",
"available_gb",
"=",
"self",
".",
"available_gb",
"(",
")",
")",
"if",
... | return (async_result, work_unit) or (None, None) | [
"return",
"(",
"async_result",
"work_unit",
")",
"or",
"(",
"None",
"None",
")"
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L258-L271 |
diffeo/rejester | rejester/workers.py | MultiWorker.run | def run(self):
'''Fetch and dispatch jobs as long as the system is running.
This periodically checks the :class:`rejester.TaskMaster` mode
and asks it for more work. It will normally run forever in a
loop until the mode becomes
:attr:`~rejester.TaskMaster.TERMINATE`, at which p... | python | def run(self):
'''Fetch and dispatch jobs as long as the system is running.
This periodically checks the :class:`rejester.TaskMaster` mode
and asks it for more work. It will normally run forever in a
loop until the mode becomes
:attr:`~rejester.TaskMaster.TERMINATE`, at which p... | [
"def",
"run",
"(",
"self",
")",
":",
"tm",
"=",
"self",
".",
"task_master",
"num_workers",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"if",
"'tasks_per_cpu'",
"in",
"self",
".",
"config",
":",
"num_workers",
"*=",
"self",
".",
"config",
".",
"ge... | Fetch and dispatch jobs as long as the system is running.
This periodically checks the :class:`rejester.TaskMaster` mode
and asks it for more work. It will normally run forever in a
loop until the mode becomes
:attr:`~rejester.TaskMaster.TERMINATE`, at which point it
waits for ... | [
"Fetch",
"and",
"dispatch",
"jobs",
"as",
"long",
"as",
"the",
"system",
"is",
"running",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L291-L346 |
diffeo/rejester | rejester/workers.py | SingleWorker.run_one | def run_one(self, set_title=False):
'''Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMI... | python | def run_one(self, set_title=False):
'''Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMI... | [
"def",
"run_one",
"(",
"self",
",",
"set_title",
"=",
"False",
")",
":",
"available_gb",
"=",
"MultiWorker",
".",
"available_gb",
"(",
")",
"unit",
"=",
"self",
".",
"task_master",
".",
"get_work",
"(",
"self",
".",
"worker_id",
",",
"available_gb",
",",
... | Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMINATE`.
:param set_title: if true, set ... | [
"Get",
"exactly",
"one",
"job",
"run",
"it",
"and",
"return",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L375-L407 |
diffeo/rejester | rejester/workers.py | SingleWorker.as_child | def as_child(cls, global_config, parent=None):
'''Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did.
'''
try:
setproctitle('rejester worker')
random.seed() # otherwi... | python | def as_child(cls, global_config, parent=None):
'''Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did.
'''
try:
setproctitle('rejester worker')
random.seed() # otherwi... | [
"def",
"as_child",
"(",
"cls",
",",
"global_config",
",",
"parent",
"=",
"None",
")",
":",
"try",
":",
"setproctitle",
"(",
"'rejester worker'",
")",
"random",
".",
"seed",
"(",
")",
"# otherwise everyone inherits the same seed",
"yakonfig",
".",
"set_default_conf... | Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did. | [
"Run",
"a",
"single",
"job",
"in",
"a",
"child",
"process",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L433-L460 |
diffeo/rejester | rejester/workers.py | ForkWorker.set_signal_handlers | def set_signal_handlers(self):
'''Set some signal handlers.
These react reasonably to shutdown requests, and keep the
logging child alive.
'''
def handler(f):
def wrapper(signum, backtrace):
return f()
return wrapper
self.old_sig... | python | def set_signal_handlers(self):
'''Set some signal handlers.
These react reasonably to shutdown requests, and keep the
logging child alive.
'''
def handler(f):
def wrapper(signum, backtrace):
return f()
return wrapper
self.old_sig... | [
"def",
"set_signal_handlers",
"(",
"self",
")",
":",
"def",
"handler",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"signum",
",",
"backtrace",
")",
":",
"return",
"f",
"(",
")",
"return",
"wrapper",
"self",
".",
"old_sigabrt",
"=",
"signal",
".",
"signa... | Set some signal handlers.
These react reasonably to shutdown requests, and keep the
logging child alive. | [
"Set",
"some",
"signal",
"handlers",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L668-L688 |
diffeo/rejester | rejester/workers.py | ForkWorker.clear_signal_handlers | def clear_signal_handlers(self):
'''Undo :meth:`set_signal_handlers`.
Not only must this be done on shutdown, but after every fork
call too.
'''
signal.signal(signal.SIGABRT, self.old_sigabrt)
signal.signal(signal.SIGINT, self.old_sigint)
signal.signal(signal.SI... | python | def clear_signal_handlers(self):
'''Undo :meth:`set_signal_handlers`.
Not only must this be done on shutdown, but after every fork
call too.
'''
signal.signal(signal.SIGABRT, self.old_sigabrt)
signal.signal(signal.SIGINT, self.old_sigint)
signal.signal(signal.SI... | [
"def",
"clear_signal_handlers",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGABRT",
",",
"self",
".",
"old_sigabrt",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"old_sigint",
")",
"signal",
"."... | Undo :meth:`set_signal_handlers`.
Not only must this be done on shutdown, but after every fork
call too. | [
"Undo",
":",
"meth",
":",
"set_signal_handlers",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L690-L700 |
diffeo/rejester | rejester/workers.py | ForkWorker.log | def log(self, level, message):
'''Write a log message via the child process.
The child process must already exist; call :meth:`live_log_child`
to make sure. If it has died in a way we don't expect then
this will raise :const:`signal.SIGPIPE`.
'''
if self.log_fd is not ... | python | def log(self, level, message):
'''Write a log message via the child process.
The child process must already exist; call :meth:`live_log_child`
to make sure. If it has died in a way we don't expect then
this will raise :const:`signal.SIGPIPE`.
'''
if self.log_fd is not ... | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"message",
")",
":",
"if",
"self",
".",
"log_fd",
"is",
"not",
"None",
":",
"prefix",
"=",
"struct",
".",
"pack",
"(",
"'ii'",
",",
"level",
",",
"len",
"(",
"message",
")",
")",
"os",
".",
"write",
... | Write a log message via the child process.
The child process must already exist; call :meth:`live_log_child`
to make sure. If it has died in a way we don't expect then
this will raise :const:`signal.SIGPIPE`. | [
"Write",
"a",
"log",
"message",
"via",
"the",
"child",
"process",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L702-L713 |
diffeo/rejester | rejester/workers.py | ForkWorker.debug | def debug(self, group, message):
'''Maybe write a debug-level log message.
In particular, this gets written if the hidden `debug_worker`
option contains `group`.
'''
if group in self.debug_worker:
if 'stdout' in self.debug_worker:
print message
... | python | def debug(self, group, message):
'''Maybe write a debug-level log message.
In particular, this gets written if the hidden `debug_worker`
option contains `group`.
'''
if group in self.debug_worker:
if 'stdout' in self.debug_worker:
print message
... | [
"def",
"debug",
"(",
"self",
",",
"group",
",",
"message",
")",
":",
"if",
"group",
"in",
"self",
".",
"debug_worker",
":",
"if",
"'stdout'",
"in",
"self",
".",
"debug_worker",
":",
"print",
"message",
"self",
".",
"log",
"(",
"logging",
".",
"DEBUG",
... | Maybe write a debug-level log message.
In particular, this gets written if the hidden `debug_worker`
option contains `group`. | [
"Maybe",
"write",
"a",
"debug",
"-",
"level",
"log",
"message",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L715-L725 |
diffeo/rejester | rejester/workers.py | ForkWorker.log_spewer | def log_spewer(self, gconfig, fd):
'''Child process to manage logging.
This reads pairs of lines from `fd`, which are alternating
priority (Python integer) and message (unformatted string).
'''
setproctitle('rejester fork_worker log task')
yakonfig.set_default_config([y... | python | def log_spewer(self, gconfig, fd):
'''Child process to manage logging.
This reads pairs of lines from `fd`, which are alternating
priority (Python integer) and message (unformatted string).
'''
setproctitle('rejester fork_worker log task')
yakonfig.set_default_config([y... | [
"def",
"log_spewer",
"(",
"self",
",",
"gconfig",
",",
"fd",
")",
":",
"setproctitle",
"(",
"'rejester fork_worker log task'",
")",
"yakonfig",
".",
"set_default_config",
"(",
"[",
"yakonfig",
",",
"dblogger",
"]",
",",
"config",
"=",
"gconfig",
")",
"try",
... | Child process to manage logging.
This reads pairs of lines from `fd`, which are alternating
priority (Python integer) and message (unformatted string). | [
"Child",
"process",
"to",
"manage",
"logging",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L727-L744 |
diffeo/rejester | rejester/workers.py | ForkWorker.start_log_child | def start_log_child(self):
'''Start the logging child process.'''
self.stop_log_child()
gconfig = yakonfig.get_global_config()
read_end, write_end = os.pipe()
pid = os.fork()
if pid == 0:
# We are the child
self.clear_signal_handlers()
... | python | def start_log_child(self):
'''Start the logging child process.'''
self.stop_log_child()
gconfig = yakonfig.get_global_config()
read_end, write_end = os.pipe()
pid = os.fork()
if pid == 0:
# We are the child
self.clear_signal_handlers()
... | [
"def",
"start_log_child",
"(",
"self",
")",
":",
"self",
".",
"stop_log_child",
"(",
")",
"gconfig",
"=",
"yakonfig",
".",
"get_global_config",
"(",
")",
"read_end",
",",
"write_end",
"=",
"os",
".",
"pipe",
"(",
")",
"pid",
"=",
"os",
".",
"fork",
"("... | Start the logging child process. | [
"Start",
"the",
"logging",
"child",
"process",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L746-L764 |
diffeo/rejester | rejester/workers.py | ForkWorker.stop_log_child | def stop_log_child(self):
'''Stop the logging child process.'''
if self.log_fd:
os.close(self.log_fd)
self.log_fd = None
if self.log_child:
try:
self.debug('children', 'stopping log child with pid {0}'
.format(self.lo... | python | def stop_log_child(self):
'''Stop the logging child process.'''
if self.log_fd:
os.close(self.log_fd)
self.log_fd = None
if self.log_child:
try:
self.debug('children', 'stopping log child with pid {0}'
.format(self.lo... | [
"def",
"stop_log_child",
"(",
"self",
")",
":",
"if",
"self",
".",
"log_fd",
":",
"os",
".",
"close",
"(",
"self",
".",
"log_fd",
")",
"self",
".",
"log_fd",
"=",
"None",
"if",
"self",
".",
"log_child",
":",
"try",
":",
"self",
".",
"debug",
"(",
... | Stop the logging child process. | [
"Stop",
"the",
"logging",
"child",
"process",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L766-L783 |
diffeo/rejester | rejester/workers.py | ForkWorker.live_log_child | def live_log_child(self):
'''Start the logging child process if it died.'''
if not (self.log_child and self.pid_is_alive(self.log_child)):
self.start_log_child() | python | def live_log_child(self):
'''Start the logging child process if it died.'''
if not (self.log_child and self.pid_is_alive(self.log_child)):
self.start_log_child() | [
"def",
"live_log_child",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"log_child",
"and",
"self",
".",
"pid_is_alive",
"(",
"self",
".",
"log_child",
")",
")",
":",
"self",
".",
"start_log_child",
"(",
")"
] | Start the logging child process if it died. | [
"Start",
"the",
"logging",
"child",
"process",
"if",
"it",
"died",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L785-L788 |
diffeo/rejester | rejester/workers.py | ForkWorker.do_some_work | def do_some_work(self, can_start_more):
'''Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one chil... | python | def do_some_work(self, can_start_more):
'''Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one chil... | [
"def",
"do_some_work",
"(",
"self",
",",
"can_start_more",
")",
":",
"any_happy_children",
"=",
"False",
"any_sad_children",
"=",
"False",
"any_bored_children",
"=",
"False",
"self",
".",
"debug",
"(",
"'loop'",
",",
"'starting work loop, can_start_more={0!r}'",
".",
... | Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one child.
:param bool can_start_more: Allowed to ... | [
"Run",
"one",
"cycle",
"of",
"the",
"main",
"loop",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L790-L893 |
diffeo/rejester | rejester/workers.py | ForkWorker.check_spinning_children | def check_spinning_children(self):
'''Stop children that are working on overdue jobs.'''
child_jobs = self.task_master.get_child_work_units(self.worker_id)
# We will kill off any jobs that are due before "now". This
# isn't really now now, but now plus a grace period to make
# s... | python | def check_spinning_children(self):
'''Stop children that are working on overdue jobs.'''
child_jobs = self.task_master.get_child_work_units(self.worker_id)
# We will kill off any jobs that are due before "now". This
# isn't really now now, but now plus a grace period to make
# s... | [
"def",
"check_spinning_children",
"(",
"self",
")",
":",
"child_jobs",
"=",
"self",
".",
"task_master",
".",
"get_child_work_units",
"(",
"self",
".",
"worker_id",
")",
"# We will kill off any jobs that are due before \"now\". This",
"# isn't really now now, but now plus a gra... | Stop children that are working on overdue jobs. | [
"Stop",
"children",
"that",
"are",
"working",
"on",
"overdue",
"jobs",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L895-L932 |
diffeo/rejester | rejester/workers.py | ForkWorker.stop_gracefully | def stop_gracefully(self):
'''Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
'''
if self.shutting_down:
self.log(logging.INFO,
... | python | def stop_gracefully(self):
'''Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
'''
if self.shutting_down:
self.log(logging.INFO,
... | [
"def",
"stop_gracefully",
"(",
"self",
")",
":",
"if",
"self",
".",
"shutting_down",
":",
"self",
".",
"log",
"(",
"logging",
".",
"INFO",
",",
"'second shutdown request, shutting down now'",
")",
"self",
".",
"scram",
"(",
")",
"else",
":",
"self",
".",
"... | Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this. | [
"Refuse",
"to",
"start",
"more",
"processes",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L934-L948 |
diffeo/rejester | rejester/workers.py | ForkWorker.stop_all_children | def stop_all_children(self):
'''Kill all workers.'''
# There's an unfortunate race condition if we try to log this
# case: we can't depend on the logging child actually receiving
# the log message before we kill it off. C'est la vie...
self.stop_log_child()
for pid in se... | python | def stop_all_children(self):
'''Kill all workers.'''
# There's an unfortunate race condition if we try to log this
# case: we can't depend on the logging child actually receiving
# the log message before we kill it off. C'est la vie...
self.stop_log_child()
for pid in se... | [
"def",
"stop_all_children",
"(",
"self",
")",
":",
"# There's an unfortunate race condition if we try to log this",
"# case: we can't depend on the logging child actually receiving",
"# the log message before we kill it off. C'est la vie...",
"self",
".",
"stop_log_child",
"(",
")",
"fo... | Kill all workers. | [
"Kill",
"all",
"workers",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L950-L965 |
diffeo/rejester | rejester/workers.py | ForkWorker.scram | def scram(self):
'''Kill all workers and die ourselves.
This runs in response to SIGABRT, from a specific invocation
of the ``kill`` command. It also runs if
:meth:`stop_gracefully` is called more than once.
'''
self.stop_all_children()
signal.signal(signal.SIG... | python | def scram(self):
'''Kill all workers and die ourselves.
This runs in response to SIGABRT, from a specific invocation
of the ``kill`` command. It also runs if
:meth:`stop_gracefully` is called more than once.
'''
self.stop_all_children()
signal.signal(signal.SIG... | [
"def",
"scram",
"(",
"self",
")",
":",
"self",
".",
"stop_all_children",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIG_DFL",
")",
"sys",
".",
"exit",
"(",
"2",
")"
] | Kill all workers and die ourselves.
This runs in response to SIGABRT, from a specific invocation
of the ``kill`` command. It also runs if
:meth:`stop_gracefully` is called more than once. | [
"Kill",
"all",
"workers",
"and",
"die",
"ourselves",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L967-L977 |
diffeo/rejester | rejester/workers.py | ForkWorker.run | def run(self):
'''Run the main loop.
This is fairly invasive: it sets a bunch of signal handlers
and spawns off a bunch of child processes.
'''
setproctitle('rejester fork_worker for namespace {0}'
.format(self.config.get('namespace', None)))
self.s... | python | def run(self):
'''Run the main loop.
This is fairly invasive: it sets a bunch of signal handlers
and spawns off a bunch of child processes.
'''
setproctitle('rejester fork_worker for namespace {0}'
.format(self.config.get('namespace', None)))
self.s... | [
"def",
"run",
"(",
"self",
")",
":",
"setproctitle",
"(",
"'rejester fork_worker for namespace {0}'",
".",
"format",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'namespace'",
",",
"None",
")",
")",
")",
"self",
".",
"set_signal_handlers",
"(",
")",
"try",
... | Run the main loop.
This is fairly invasive: it sets a bunch of signal handlers
and spawns off a bunch of child processes. | [
"Run",
"the",
"main",
"loop",
"."
] | train | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L979-L1025 |
hobson/pug-dj | pug/dj/crawlnmine/fabfile/django_fabric_aws.py | instance | def instance():
"""
Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server
with nginx + gunicorn
"""
# Record the starting time and print a starting message
start_time = time.time()
print(_green("Started..."))
# Use boto to create an EC2 instance
env.host_st... | python | def instance():
"""
Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server
with nginx + gunicorn
"""
# Record the starting time and print a starting message
start_time = time.time()
print(_green("Started..."))
# Use boto to create an EC2 instance
env.host_st... | [
"def",
"instance",
"(",
")",
":",
"# Record the starting time and print a starting message",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"print",
"(",
"_green",
"(",
"\"Started...\"",
")",
")",
"# Use boto to create an EC2 instance",
"env",
".",
"host_string",
"... | Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server
with nginx + gunicorn | [
"Creates",
"an",
"EC2",
"instance",
"from",
"an",
"Ubuntu",
"AMI",
"and",
"configures",
"it",
"as",
"a",
"Django",
"server",
"with",
"nginx",
"+",
"gunicorn"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/fabfile/django_fabric_aws.py#L64-L93 |
hobson/pug-dj | pug/dj/crawlnmine/fabfile/django_fabric_aws.py | _run_task | def _run_task(task, start_message, finished_message):
"""
Tasks a task from tasks.py and runs through the commands on the server
"""
# Get the hosts and record the start time
env.hosts = fabconf['EC2_INSTANCES']
start = time.time()
# Check if any hosts exist
if env.hosts == []:
... | python | def _run_task(task, start_message, finished_message):
"""
Tasks a task from tasks.py and runs through the commands on the server
"""
# Get the hosts and record the start time
env.hosts = fabconf['EC2_INSTANCES']
start = time.time()
# Check if any hosts exist
if env.hosts == []:
... | [
"def",
"_run_task",
"(",
"task",
",",
"start_message",
",",
"finished_message",
")",
":",
"# Get the hosts and record the start time",
"env",
".",
"hosts",
"=",
"fabconf",
"[",
"'EC2_INSTANCES'",
"]",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# Check if any ho... | Tasks a task from tasks.py and runs through the commands on the server | [
"Tasks",
"a",
"task",
"from",
"tasks",
".",
"py",
"and",
"runs",
"through",
"the",
"commands",
"on",
"the",
"server"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/fabfile/django_fabric_aws.py#L143-L170 |
hobson/pug-dj | pug/dj/crawlnmine/fabfile/django_fabric_aws.py | _create_ec2_instance | def _create_ec2_instance():
"""
Creates EC2 Instance
"""
print(_yellow("Creating instance"))
conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=fabconf['AWS_ACCESS_KEY'], aws_secret_access_key=fabconf['AWS_SECRET_KEY'])
image = conn.get_all_images(ec2_amis)
reservation = image... | python | def _create_ec2_instance():
"""
Creates EC2 Instance
"""
print(_yellow("Creating instance"))
conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=fabconf['AWS_ACCESS_KEY'], aws_secret_access_key=fabconf['AWS_SECRET_KEY'])
image = conn.get_all_images(ec2_amis)
reservation = image... | [
"def",
"_create_ec2_instance",
"(",
")",
":",
"print",
"(",
"_yellow",
"(",
"\"Creating instance\"",
")",
")",
"conn",
"=",
"boto",
".",
"ec2",
".",
"connect_to_region",
"(",
"ec2_region",
",",
"aws_access_key_id",
"=",
"fabconf",
"[",
"'AWS_ACCESS_KEY'",
"]",
... | Creates EC2 Instance | [
"Creates",
"EC2",
"Instance"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/fabfile/django_fabric_aws.py#L172-L195 |
hobson/pug-dj | pug/dj/crawlnmine/fabfile/django_fabric_aws.py | _put_template | def _put_template(params):
"""
Same as _put() but it loads a file and does variable replacement
"""
f = open(_render(params['template']), 'r')
template = f.read()
run(_write_to(_render(template), _render(params['destination']))) | python | def _put_template(params):
"""
Same as _put() but it loads a file and does variable replacement
"""
f = open(_render(params['template']), 'r')
template = f.read()
run(_write_to(_render(template), _render(params['destination']))) | [
"def",
"_put_template",
"(",
"params",
")",
":",
"f",
"=",
"open",
"(",
"_render",
"(",
"params",
"[",
"'template'",
"]",
")",
",",
"'r'",
")",
"template",
"=",
"f",
".",
"read",
"(",
")",
"run",
"(",
"_write_to",
"(",
"_render",
"(",
"template",
"... | Same as _put() but it loads a file and does variable replacement | [
"Same",
"as",
"_put",
"()",
"but",
"it",
"loads",
"a",
"file",
"and",
"does",
"variable",
"replacement"
] | train | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/fabfile/django_fabric_aws.py#L239-L246 |
waltermoreira/tartpy | tartpy/tools.py | dict_map | def dict_map(f, primitive, dic):
"""Map a function f:{primitive} -> B to a dictionary."""
if primitive(dic):
return f(dic)
if isinstance(dic, Mapping):
return {dict_map(f, primitive, key): dict_map(f, primitive, value)
for key, value in dic.items()}
if isinstance(dic, st... | python | def dict_map(f, primitive, dic):
"""Map a function f:{primitive} -> B to a dictionary."""
if primitive(dic):
return f(dic)
if isinstance(dic, Mapping):
return {dict_map(f, primitive, key): dict_map(f, primitive, value)
for key, value in dic.items()}
if isinstance(dic, st... | [
"def",
"dict_map",
"(",
"f",
",",
"primitive",
",",
"dic",
")",
":",
"if",
"primitive",
"(",
"dic",
")",
":",
"return",
"f",
"(",
"dic",
")",
"if",
"isinstance",
"(",
"dic",
",",
"Mapping",
")",
":",
"return",
"{",
"dict_map",
"(",
"f",
",",
"pri... | Map a function f:{primitive} -> B to a dictionary. | [
"Map",
"a",
"function",
"f",
":",
"{",
"primitive",
"}",
"-",
">",
"B",
"to",
"a",
"dictionary",
"."
] | train | https://github.com/waltermoreira/tartpy/blob/d9f66c8b373bd55a7b055c0fd39b516490bb0235/tartpy/tools.py#L50-L62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.