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 |
|---|---|---|---|---|---|---|---|---|---|---|
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/archive_storage.py | search_archives | def search_archives(query):
"""
Return list of :class:`.DBArchive` which match all properties that are
set (``not None``) using AND operator to all of them.
Example:
result = storage_handler.search_publications(
DBArchive(isbn="azgabash")
)
Args:
query (obj): :c... | python | def search_archives(query):
"""
Return list of :class:`.DBArchive` which match all properties that are
set (``not None``) using AND operator to all of them.
Example:
result = storage_handler.search_publications(
DBArchive(isbn="azgabash")
)
Args:
query (obj): :c... | [
"def",
"search_archives",
"(",
"query",
")",
":",
"_assert_obj_type",
"(",
"query",
",",
"name",
"=",
"\"query\"",
",",
"obj_type",
"=",
"DBArchive",
")",
"return",
"_get_handler",
"(",
")",
".",
"search_objects",
"(",
"query",
")"
] | Return list of :class:`.DBArchive` which match all properties that are
set (``not None``) using AND operator to all of them.
Example:
result = storage_handler.search_publications(
DBArchive(isbn="azgabash")
)
Args:
query (obj): :class:`.DBArchive` with `some` of the pro... | [
"Return",
"list",
"of",
":",
"class",
":",
".",
"DBArchive",
"which",
"match",
"all",
"properties",
"that",
"are",
"set",
"(",
"not",
"None",
")",
"using",
"AND",
"operator",
"to",
"all",
"of",
"them",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/archive_storage.py#L51-L73 |
rorr73/LifeSOSpy | lifesospy/__main__.py | main | def main(argv):
"""
Basic command line script for testing library.
"""
# Parse command line arguments
parser = argparse.ArgumentParser(
description="LifeSOSpy v{} - {}".format(
PROJECT_VERSION, PROJECT_DESCRIPTION))
parser.add_argument(
'-H', '--host',
help="... | python | def main(argv):
"""
Basic command line script for testing library.
"""
# Parse command line arguments
parser = argparse.ArgumentParser(
description="LifeSOSpy v{} - {}".format(
PROJECT_VERSION, PROJECT_DESCRIPTION))
parser.add_argument(
'-H', '--host',
help="... | [
"def",
"main",
"(",
"argv",
")",
":",
"# Parse command line arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"LifeSOSpy v{} - {}\"",
".",
"format",
"(",
"PROJECT_VERSION",
",",
"PROJECT_DESCRIPTION",
")",
")",
"parser",
".",
... | Basic command line script for testing library. | [
"Basic",
"command",
"line",
"script",
"for",
"testing",
"library",
"."
] | train | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/__main__.py#L23-L71 |
laysakura/relshell | relshell/timestamp.py | Timestamp.datetime | def datetime(self):
"""Return `datetime` object"""
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) | python | def datetime(self):
"""Return `datetime` object"""
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) | [
"def",
"datetime",
"(",
"self",
")",
":",
"return",
"dt",
".",
"datetime",
"(",
"self",
".",
"year",
"(",
")",
",",
"self",
".",
"month",
"(",
")",
",",
"self",
".",
"day",
"(",
")",
",",
"self",
".",
"hour",
"(",
")",
",",
"self",
".",
"minu... | Return `datetime` object | [
"Return",
"datetime",
"object"
] | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/timestamp.py#L63-L68 |
malthe/pop | src/pop/control.py | CommandConfiguration.get_command | def get_command(self, name):
"""Wrap command class in constructor."""
def command(options):
client = ZookeeperClient(
"%s:%d" % (options.pop('host'), options.pop('port')),
session_timeout=1000
)
path = options.pop('path_prefix')
... | python | def get_command(self, name):
"""Wrap command class in constructor."""
def command(options):
client = ZookeeperClient(
"%s:%d" % (options.pop('host'), options.pop('port')),
session_timeout=1000
)
path = options.pop('path_prefix')
... | [
"def",
"get_command",
"(",
"self",
",",
"name",
")",
":",
"def",
"command",
"(",
"options",
")",
":",
"client",
"=",
"ZookeeperClient",
"(",
"\"%s:%d\"",
"%",
"(",
"options",
".",
"pop",
"(",
"'host'",
")",
",",
"options",
".",
"pop",
"(",
"'port'",
... | Wrap command class in constructor. | [
"Wrap",
"command",
"class",
"in",
"constructor",
"."
] | train | https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/control.py#L61-L83 |
naphatkrit/easyci | easyci/version.py | get_installed_version | def get_installed_version(vcs):
"""Get the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
str - version number
Raises:
VersionNotInstalledError
"""
version_path = _get_version_path(vcs)
if not os.path.exists(version_path):
rais... | python | def get_installed_version(vcs):
"""Get the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
str - version number
Raises:
VersionNotInstalledError
"""
version_path = _get_version_path(vcs)
if not os.path.exists(version_path):
rais... | [
"def",
"get_installed_version",
"(",
"vcs",
")",
":",
"version_path",
"=",
"_get_version_path",
"(",
"vcs",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"version_path",
")",
":",
"raise",
"VersionNotInstalledError",
"with",
"open",
"(",
"version_pa... | Get the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
str - version number
Raises:
VersionNotInstalledError | [
"Get",
"the",
"installed",
"version",
"for",
"this",
"project",
"."
] | train | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/version.py#L12-L28 |
naphatkrit/easyci | easyci/version.py | set_installed_version | def set_installed_version(vcs, version):
"""Set the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
version (str)
"""
version_path = _get_version_path(vcs)
with open(version_path, 'w') as f:
f.write(version) | python | def set_installed_version(vcs, version):
"""Set the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
version (str)
"""
version_path = _get_version_path(vcs)
with open(version_path, 'w') as f:
f.write(version) | [
"def",
"set_installed_version",
"(",
"vcs",
",",
"version",
")",
":",
"version_path",
"=",
"_get_version_path",
"(",
"vcs",
")",
"with",
"open",
"(",
"version_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"version",
")"
] | Set the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
version (str) | [
"Set",
"the",
"installed",
"version",
"for",
"this",
"project",
"."
] | train | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/version.py#L31-L40 |
minhhoit/yacms | yacms/core/sitemaps.py | DisplayableSitemap.get_urls | def get_urls(self, **kwargs):
"""
Ensure the correct host by injecting the current site.
"""
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**kwargs) | python | def get_urls(self, **kwargs):
"""
Ensure the correct host by injecting the current site.
"""
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**kwargs) | [
"def",
"get_urls",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"site\"",
"]",
"=",
"Site",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"current_site_id",
"(",
")",
")",
"return",
"super",
"(",
"DisplayableSitemap",
",",
"self",
"... | Ensure the correct host by injecting the current site. | [
"Ensure",
"the",
"correct",
"host",
"by",
"injecting",
"the",
"current",
"site",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/sitemaps.py#L33-L38 |
dossier/dossier.web | dossier/extraction/usernames.py | usernames | def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
... | python | def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
... | [
"def",
"usernames",
"(",
"urls",
")",
":",
"usernames",
"=",
"StringCounter",
"(",
")",
"for",
"url",
",",
"count",
"in",
"urls",
".",
"items",
"(",
")",
":",
"uparse",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"uparse",
".",
"path",
"hostname",... | Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list. | [
"Take",
"an",
"iterable",
"of",
"urls",
"of",
"normalized",
"URL",
"or",
"file",
"paths",
"and",
"attempt",
"to",
"extract",
"usernames",
".",
"Returns",
"a",
"list",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/extraction/usernames.py#L15-L30 |
PSU-OIT-ARC/elasticmodels | elasticmodels/forms.py | BaseSearchForm.cleaned_data | def cleaned_data(self):
"""
When cleaned_data is initially accessed, we want to ensure the form
gets validated which has the side effect of setting cleaned_data to
something.
"""
if not hasattr(self, "_cleaned_data"):
self._cleaned_data = {}
self.i... | python | def cleaned_data(self):
"""
When cleaned_data is initially accessed, we want to ensure the form
gets validated which has the side effect of setting cleaned_data to
something.
"""
if not hasattr(self, "_cleaned_data"):
self._cleaned_data = {}
self.i... | [
"def",
"cleaned_data",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_cleaned_data\"",
")",
":",
"self",
".",
"_cleaned_data",
"=",
"{",
"}",
"self",
".",
"is_valid",
"(",
")",
"return",
"self",
".",
"_cleaned_data"
] | When cleaned_data is initially accessed, we want to ensure the form
gets validated which has the side effect of setting cleaned_data to
something. | [
"When",
"cleaned_data",
"is",
"initially",
"accessed",
"we",
"want",
"to",
"ensure",
"the",
"form",
"gets",
"validated",
"which",
"has",
"the",
"side",
"effect",
"of",
"setting",
"cleaned_data",
"to",
"something",
"."
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/forms.py#L32-L41 |
PSU-OIT-ARC/elasticmodels | elasticmodels/forms.py | BaseSearchForm.search | def search(self):
"""
This should return an elasticsearch-DSL Search instance, list or
queryset based on the values in self.cleaned_data.
"""
results = self.index.objects.all()
# reduce the results based on the q field
if self.cleaned_data.get("q"):
re... | python | def search(self):
"""
This should return an elasticsearch-DSL Search instance, list or
queryset based on the values in self.cleaned_data.
"""
results = self.index.objects.all()
# reduce the results based on the q field
if self.cleaned_data.get("q"):
re... | [
"def",
"search",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"index",
".",
"objects",
".",
"all",
"(",
")",
"# reduce the results based on the q field",
"if",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"\"q\"",
")",
":",
"results",
"=",
"results... | This should return an elasticsearch-DSL Search instance, list or
queryset based on the values in self.cleaned_data. | [
"This",
"should",
"return",
"an",
"elasticsearch",
"-",
"DSL",
"Search",
"instance",
"list",
"or",
"queryset",
"based",
"on",
"the",
"values",
"in",
"self",
".",
"cleaned_data",
"."
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/forms.py#L62-L79 |
PSU-OIT-ARC/elasticmodels | elasticmodels/forms.py | BaseSearchForm.results | def results(self):
"""
This either returns self.get_queryset(), self.search(), or
self.search() wrapped up in a Pageable.
"""
if not self.in_search_mode():
return self.get_queryset()
# we are doing a search
objects = self.search()
# if object... | python | def results(self):
"""
This either returns self.get_queryset(), self.search(), or
self.search() wrapped up in a Pageable.
"""
if not self.in_search_mode():
return self.get_queryset()
# we are doing a search
objects = self.search()
# if object... | [
"def",
"results",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"in_search_mode",
"(",
")",
":",
"return",
"self",
".",
"get_queryset",
"(",
")",
"# we are doing a search",
"objects",
"=",
"self",
".",
"search",
"(",
")",
"# if objects isn't a Search object... | This either returns self.get_queryset(), self.search(), or
self.search() wrapped up in a Pageable. | [
"This",
"either",
"returns",
"self",
".",
"get_queryset",
"()",
"self",
".",
"search",
"()",
"or",
"self",
".",
"search",
"()",
"wrapped",
"up",
"in",
"a",
"Pageable",
"."
] | train | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/forms.py#L102-L123 |
quasipedia/simpleactors | simpleactors.py | on | def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator | python | def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator | [
"def",
"on",
"(",
"message",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"try",
":",
"function",
".",
"_callback_messages",
".",
"append",
"(",
"message",
")",
"except",
"AttributeError",
":",
"function",
".",
"_callback_messages",
"=",
"[",
"... | Decorator that register a class method as callback for a message. | [
"Decorator",
"that",
"register",
"a",
"class",
"method",
"as",
"callback",
"for",
"a",
"message",
"."
] | train | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L43-L51 |
quasipedia/simpleactors | simpleactors.py | Actor.plug | def plug(self):
'''Add the actor's methods to the callback registry.'''
if self.__plugged:
return
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, '_callback_messages'):
for message in method._callback_messages:
... | python | def plug(self):
'''Add the actor's methods to the callback registry.'''
if self.__plugged:
return
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, '_callback_messages'):
for message in method._callback_messages:
... | [
"def",
"plug",
"(",
"self",
")",
":",
"if",
"self",
".",
"__plugged",
":",
"return",
"for",
"_",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
":",
"if",
"hasattr",
"(",
"metho... | Add the actor's methods to the callback registry. | [
"Add",
"the",
"actor",
"s",
"methods",
"to",
"the",
"callback",
"registry",
"."
] | train | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L74-L82 |
quasipedia/simpleactors | simpleactors.py | Actor.unplug | def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global... | python | def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global... | [
"def",
"unplug",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__plugged",
":",
"return",
"members",
"=",
"set",
"(",
"[",
"method",
"for",
"_",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"predicate",
"=",
"inspect",
"."... | Remove the actor's methods from the callback registry. | [
"Remove",
"the",
"actor",
"s",
"methods",
"from",
"the",
"callback",
"registry",
"."
] | train | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L84-L92 |
quasipedia/simpleactors | simpleactors.py | Actor.emit | def emit(self, message, *args, **kwargs):
'''Emit an event.'''
global_event_queue.append((message, self, args, kwargs)) | python | def emit(self, message, *args, **kwargs):
'''Emit an event.'''
global_event_queue.append((message, self, args, kwargs)) | [
"def",
"emit",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global_event_queue",
".",
"append",
"(",
"(",
"message",
",",
"self",
",",
"args",
",",
"kwargs",
")",
")"
] | Emit an event. | [
"Emit",
"an",
"event",
"."
] | train | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L99-L101 |
quasipedia/simpleactors | simpleactors.py | Director.run | def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_ev... | python | def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_ev... | [
"def",
"run",
"(",
"self",
")",
":",
"# We left-append rather than emit (right-append) because some message",
"# may have been already queued for execution before the director runs.",
"global_event_queue",
".",
"appendleft",
"(",
"(",
"INITIATE",
",",
"self",
",",
"(",
")",
","... | Run until there are no events to be processed. | [
"Run",
"until",
"there",
"are",
"no",
"events",
"to",
"be",
"processed",
"."
] | train | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L115-L121 |
quasipedia/simpleactors | simpleactors.py | Director.halt | def halt(self, message, emitter, *args, **kwargs):
'''Halt the execution of the loop.'''
self.process_event((FINISH, self, (), {}))
global_event_queue.clear() | python | def halt(self, message, emitter, *args, **kwargs):
'''Halt the execution of the loop.'''
self.process_event((FINISH, self, (), {}))
global_event_queue.clear() | [
"def",
"halt",
"(",
"self",
",",
"message",
",",
"emitter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"process_event",
"(",
"(",
"FINISH",
",",
"self",
",",
"(",
")",
",",
"{",
"}",
")",
")",
"global_event_queue",
".",
"cl... | Halt the execution of the loop. | [
"Halt",
"the",
"execution",
"of",
"the",
"loop",
"."
] | train | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L135-L138 |
polysquare/jobstamps | jobstamps/jobstamp_cmd_main.py | _run_cmd | def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(shebang_parts + cmd,
... | python | def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(shebang_parts + cmd,
... | [
"def",
"_run_cmd",
"(",
"cmd",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cmd",
"[",
"0",
"]",
")",
":",
"cmd",
"[",
"0",
"]",
"=",
"shutil",
".",
"which",
"(",
"cmd",
"[",
"0",
"]",
")",
"assert",
"cmd",
"[",
"0",
"]",
... | Run command specified by :cmd: and return stdout, stderr and code. | [
"Run",
"command",
"specified",
"by",
":",
"cmd",
":",
"and",
"return",
"stdout",
"stderr",
"and",
"code",
"."
] | train | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp_cmd_main.py#L36-L52 |
polysquare/jobstamps | jobstamps/jobstamp_cmd_main.py | main | def main(argv=None): # suppress(unused-function)
"""Entry point for jobstamp command.
This will parse arguments and run the specified command in a subprocess. If
the command has already been run, then the last captured stdout and
stderr of the command will be printed on the command line.
"""
a... | python | def main(argv=None): # suppress(unused-function)
"""Entry point for jobstamp command.
This will parse arguments and run the specified command in a subprocess. If
the command has already been run, then the last captured stdout and
stderr of the command will be printed on the command line.
"""
a... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"# suppress(unused-function)",
"argv",
"=",
"argv",
"or",
"sys",
".",
"argv",
"if",
"\"--\"",
"not",
"in",
"argv",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\"\"Must specify command after '--'.\\n\"\"\"... | Entry point for jobstamp command.
This will parse arguments and run the specified command in a subprocess. If
the command has already been run, then the last captured stdout and
stderr of the command will be printed on the command line. | [
"Entry",
"point",
"for",
"jobstamp",
"command",
"."
] | train | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp_cmd_main.py#L55-L117 |
dossier/dossier.web | dossier/web/builder.py | create_injector | def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated... | python | def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated... | [
"def",
"create_injector",
"(",
"param_name",
",",
"fun_param_value",
")",
":",
"class",
"_",
"(",
"object",
")",
":",
"api",
"=",
"2",
"def",
"apply",
"(",
"self",
",",
"callback",
",",
"route",
")",
":",
"if",
"param_name",
"not",
"in",
"inspect",
"."... | Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated.
This is useful for handling thread local services l... | [
"Dependency",
"injection",
"with",
"Bottle",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L295-L327 |
dossier/dossier.web | dossier/web/builder.py | WebBuilder.get_app | def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
... | python | def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
... | [
"def",
"get_app",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
"is",
"None",
":",
"# If the user never sets a config instance, then just create",
"# a default.",
"self",
".",
"config",
"=",
"Config",
"(",
")",
"if",
"self",
".",
"mount_prefix",
"is",
"Non... | Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle` | [
"Eliminate",
"the",
"builder",
"by",
"producing",
"a",
"new",
"Bottle",
"application",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L81-L136 |
dossier/dossier.web | dossier/web/builder.py | WebBuilder.add_search_engine | def add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations... | python | def add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations... | [
"def",
"add_search_engine",
"(",
"self",
",",
"name",
",",
"engine",
")",
":",
"if",
"engine",
"is",
"None",
":",
"self",
".",
"search_engines",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"search_engines",
"[",
"name",
"]",
"=",
"engine",
... | Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations given a query.
The ``engine`` must be a clas... | [
"Adds",
"a",
"search",
"engine",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L164-L189 |
dossier/dossier.web | dossier/web/builder.py | WebBuilder.add_filter | def add_filter(self, name, filter):
'''Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The `... | python | def add_filter(self, name, filter):
'''Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The `... | [
"def",
"add_filter",
"(",
"self",
",",
"name",
",",
"filter",
")",
":",
"if",
"name",
"is",
"None",
":",
"self",
".",
"filters",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"filters",
"[",
"name",
"]",
"=",
"filter",
"return",
"self"
] | Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The ``filter`` must be a class so that its dependenc... | [
"Adds",
"a",
"filter",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L191-L214 |
dossier/dossier.web | dossier/web/builder.py | WebBuilder.add_routes | def add_routes(self, routes):
'''Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder`
'''
# Basically the same as `self.app.merge(rout... | python | def add_routes(self, routes):
'''Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder`
'''
# Basically the same as `self.app.merge(rout... | [
"def",
"add_routes",
"(",
"self",
",",
"routes",
")",
":",
"# Basically the same as `self.app.merge(routes)`, except this",
"# changes the owner of the route so that plugins on `self.app`",
"# apply to the routes given here.",
"if",
"isinstance",
"(",
"routes",
",",
"bottle",
".",
... | Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder` | [
"Merges",
"a",
"Bottle",
"application",
"into",
"this",
"one",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L216-L231 |
dossier/dossier.web | dossier/web/builder.py | WebBuilder.inject | def inject(self, name, closure):
'''Injects ``closure()`` into ``name`` parameters in routes.
This sets up dependency injection for parameters named ``name``.
When a route is invoked that has a parameter ``name``, then
``closure()`` is passed as that parameter's value.
(The clo... | python | def inject(self, name, closure):
'''Injects ``closure()`` into ``name`` parameters in routes.
This sets up dependency injection for parameters named ``name``.
When a route is invoked that has a parameter ``name``, then
``closure()`` is passed as that parameter's value.
(The clo... | [
"def",
"inject",
"(",
"self",
",",
"name",
",",
"closure",
")",
":",
"self",
".",
"app",
".",
"install",
"(",
"create_injector",
"(",
"name",
",",
"closure",
")",
")",
"return",
"self"
] | Injects ``closure()`` into ``name`` parameters in routes.
This sets up dependency injection for parameters named ``name``.
When a route is invoked that has a parameter ``name``, then
``closure()`` is passed as that parameter's value.
(The closure indirection is so the caller can contro... | [
"Injects",
"closure",
"()",
"into",
"name",
"parameters",
"in",
"routes",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L233-L249 |
dossier/dossier.web | dossier/web/builder.py | WebBuilder.enable_cors | def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.resp... | python | def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.resp... | [
"def",
"enable_cors",
"(",
"self",
")",
":",
"def",
"access_control_headers",
"(",
")",
":",
"bottle",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Origin'",
"]",
"=",
"'*'",
"bottle",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-... | Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder` | [
"Enables",
"Cross",
"Origin",
"Resource",
"Sharing",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L251-L282 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.init_properties | def init_properties(self) -> 'PygalleBaseClass':
""" Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance.
"""
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
... | python | def init_properties(self) -> 'PygalleBaseClass':
""" Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance.
"""
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
... | [
"def",
"init_properties",
"(",
"self",
")",
"->",
"'PygalleBaseClass'",
":",
"self",
".",
"_pigalle",
"=",
"{",
"PygalleBaseClass",
".",
"__KEYS",
".",
"INTERNALS",
":",
"dict",
"(",
")",
",",
"PygalleBaseClass",
".",
"__KEYS",
".",
"PUBLIC",
":",
"dict",
... | Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance. | [
"Initialize",
"the",
"Pigalle",
"properties",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L66-L76 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.set | def set(self, key: str, value: Any) -> 'PygalleBaseClass':
""" Define a public property.
:param key:
:param value:
:return:
"""
self.public()[key] = value
return self | python | def set(self, key: str, value: Any) -> 'PygalleBaseClass':
""" Define a public property.
:param key:
:param value:
:return:
"""
self.public()[key] = value
return self | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"'PygalleBaseClass'",
":",
"self",
".",
"public",
"(",
")",
"[",
"key",
"]",
"=",
"value",
"return",
"self"
] | Define a public property.
:param key:
:param value:
:return: | [
"Define",
"a",
"public",
"property",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L121-L129 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.set_class_name | def set_class_name(self) -> 'PygalleBaseClass':
""" Store the class name of the current instance of
:class:`PygalleBaseClass` into internal property.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass`
"""
return self.set_internal(PygalleBaseClass._... | python | def set_class_name(self) -> 'PygalleBaseClass':
""" Store the class name of the current instance of
:class:`PygalleBaseClass` into internal property.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass`
"""
return self.set_internal(PygalleBaseClass._... | [
"def",
"set_class_name",
"(",
"self",
")",
"->",
"'PygalleBaseClass'",
":",
"return",
"self",
".",
"set_internal",
"(",
"PygalleBaseClass",
".",
"__KEYS",
".",
"CLASSNAME",
",",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Store the class name of the current instance of
:class:`PygalleBaseClass` into internal property.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass` | [
"Store",
"the",
"class",
"name",
"of",
"the",
"current",
"instance",
"of",
":",
"class",
":",
"PygalleBaseClass",
"into",
"internal",
"property",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L167-L174 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.set_category | def set_category(self, category: str = None) -> 'PygalleBaseClass':
""" Define the category of the class.
# Arguments
category: The name of category.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass`
"""
return self.set_internal(Pygal... | python | def set_category(self, category: str = None) -> 'PygalleBaseClass':
""" Define the category of the class.
# Arguments
category: The name of category.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass`
"""
return self.set_internal(Pygal... | [
"def",
"set_category",
"(",
"self",
",",
"category",
":",
"str",
"=",
"None",
")",
"->",
"'PygalleBaseClass'",
":",
"return",
"self",
".",
"set_internal",
"(",
"PygalleBaseClass",
".",
"__KEYS",
".",
"CATEGORY",
",",
"category",
")"
] | Define the category of the class.
# Arguments
category: The name of category.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass` | [
"Define",
"the",
"category",
"of",
"the",
"class",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L180-L189 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.instance_of | def instance_of(self, kls: Any) -> bool:
""" Return true if the current object is an instance of passed type.
# Arguments
kls: The class.
# Returns:
bool:
* Return true if the current object is an instance of passed type.
* False else.
... | python | def instance_of(self, kls: Any) -> bool:
""" Return true if the current object is an instance of passed type.
# Arguments
kls: The class.
# Returns:
bool:
* Return true if the current object is an instance of passed type.
* False else.
... | [
"def",
"instance_of",
"(",
"self",
",",
"kls",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"kls",
":",
"raise",
"ValueError",
"return",
"isinstance",
"(",
"self",
",",
"kls",
")"
] | Return true if the current object is an instance of passed type.
# Arguments
kls: The class.
# Returns:
bool:
* Return true if the current object is an instance of passed type.
* False else. | [
"Return",
"true",
"if",
"the",
"current",
"object",
"is",
"an",
"instance",
"of",
"passed",
"type",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L245-L258 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.is_pigalle_class | def is_pigalle_class(kls: ClassVar) -> bool:
""" Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else.
... | python | def is_pigalle_class(kls: ClassVar) -> bool:
""" Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else.
... | [
"def",
"is_pigalle_class",
"(",
"kls",
":",
"ClassVar",
")",
"->",
"bool",
":",
"return",
"(",
"kls",
"is",
"PygalleBaseClass",
")",
"or",
"(",
"issubclass",
"(",
"type",
"(",
"kls",
")",
",",
"PygalleBaseClass",
")",
")"
] | Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else. | [
"Return",
"true",
"if",
"the",
"passed",
"object",
"as",
"argument",
"is",
"a",
"class",
"being",
"to",
"the",
"Pigalle",
"framework",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L276-L287 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.is_pigalle | def is_pigalle(obj: Any) -> bool:
""" Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Piga... | python | def is_pigalle(obj: Any) -> bool:
""" Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Piga... | [
"def",
"is_pigalle",
"(",
"obj",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"PygalleBaseClass",
".",
"is_pigalle_class",
"(",
"obj",
")",
"or",
"PygalleBaseClass",
".",
"is_pigalle_instance",
"(",
"obj",
")"
] | Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Pigalle.
* False else. | [
"Return",
"true",
"if",
"the",
"passed",
"object",
"as",
"argument",
"is",
"a",
"class",
"or",
"an",
"instance",
"of",
"class",
"being",
"to",
"the",
"Pigalle",
"framework",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L290-L303 |
pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.has_method | def has_method(self, key: str) -> bool:
""" Return if a method exists for the current instance.
# Arguments
key: The method name.
# Returns:
bool:
* True if the current instance has the provided method.
* False else.
"""
... | python | def has_method(self, key: str) -> bool:
""" Return if a method exists for the current instance.
# Arguments
key: The method name.
# Returns:
bool:
* True if the current instance has the provided method.
* False else.
"""
... | [
"def",
"has_method",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"bool",
":",
"return",
"hasattr",
"(",
"self",
".",
"__class__",
",",
"key",
")",
"and",
"callable",
"(",
"getattr",
"(",
"self",
".",
"__class__",
",",
"key",
")",
")"
] | Return if a method exists for the current instance.
# Arguments
key: The method name.
# Returns:
bool:
* True if the current instance has the provided method.
* False else. | [
"Return",
"if",
"a",
"method",
"exists",
"for",
"the",
"current",
"instance",
"."
] | train | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L319-L331 |
inspirehep/plotextractor | plotextractor/extractor.py | get_context | def get_context(lines, backwards=False):
"""Get context.
Given a relevant string from a TeX file, this function will extract text
from it as far as it is deemed contextually relevant, either backwards or
forwards in the text.
The level of relevance allowed is configurable. When it reaches some
... | python | def get_context(lines, backwards=False):
"""Get context.
Given a relevant string from a TeX file, this function will extract text
from it as far as it is deemed contextually relevant, either backwards or
forwards in the text.
The level of relevance allowed is configurable. When it reaches some
... | [
"def",
"get_context",
"(",
"lines",
",",
"backwards",
"=",
"False",
")",
":",
"tex_tag",
"=",
"re",
".",
"compile",
"(",
"r\".*\\\\(\\w+).*\"",
")",
"sentence",
"=",
"re",
".",
"compile",
"(",
"r\"(?<=[.?!])[\\s]+(?=[A-Z])\"",
")",
"context",
"=",
"[",
"]",
... | Get context.
Given a relevant string from a TeX file, this function will extract text
from it as far as it is deemed contextually relevant, either backwards or
forwards in the text.
The level of relevance allowed is configurable. When it reaches some
point in the text that is determined to be out o... | [
"Get",
"context",
"."
] | train | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L55-L115 |
inspirehep/plotextractor | plotextractor/extractor.py | extract_context | def extract_context(tex_file, extracted_image_data):
"""Extract context.
Given a .tex file and a label name, this function will extract the text
before and after for all the references made to this label in the text.
The number of characters to extract before and after is configurable.
:param tex_... | python | def extract_context(tex_file, extracted_image_data):
"""Extract context.
Given a .tex file and a label name, this function will extract the text
before and after for all the references made to this label in the text.
The number of characters to extract before and after is configurable.
:param tex_... | [
"def",
"extract_context",
"(",
"tex_file",
",",
"extracted_image_data",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"tex_file",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tex_file",
")",
":",
"return",
"[",
"]",
"lines",
"=",
... | Extract context.
Given a .tex file and a label name, this function will extract the text
before and after for all the references made to this label in the text.
The number of characters to extract before and after is configurable.
:param tex_file (list): path to .tex file
:param extracted_image_da... | [
"Extract",
"context",
"."
] | train | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L118-L165 |
inspirehep/plotextractor | plotextractor/extractor.py | extract_captions | def extract_captions(tex_file, sdir, image_list, primary=True):
"""Extract captions.
Take the TeX file and the list of images in the tarball (which all,
presumably, are used in the TeX file) and figure out which captions
in the text are associated with which images
:param: lines (list): list of lin... | python | def extract_captions(tex_file, sdir, image_list, primary=True):
"""Extract captions.
Take the TeX file and the list of images in the tarball (which all,
presumably, are used in the TeX file) and figure out which captions
in the text are associated with which images
:param: lines (list): list of lin... | [
"def",
"extract_captions",
"(",
"tex_file",
",",
"sdir",
",",
"image_list",
",",
"primary",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"tex_file",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tex_file",
")",
":",
... | Extract captions.
Take the TeX file and the list of images in the tarball (which all,
presumably, are used in the TeX file) and figure out which captions
in the text are associated with which images
:param: lines (list): list of lines of the TeX file
:param: tex_file (string): the name of the TeX ... | [
"Extract",
"captions",
"."
] | train | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L168-L567 |
inspirehep/plotextractor | plotextractor/extractor.py | put_it_together | def put_it_together(cur_image, caption, context, extracted_image_data,
line_index, lines):
"""Put it together.
Takes the current image(s) and caption(s) and assembles them into
something useful in the extracted_image_data list.
:param: cur_image (string || list): the image currentl... | python | def put_it_together(cur_image, caption, context, extracted_image_data,
line_index, lines):
"""Put it together.
Takes the current image(s) and caption(s) and assembles them into
something useful in the extracted_image_data list.
:param: cur_image (string || list): the image currentl... | [
"def",
"put_it_together",
"(",
"cur_image",
",",
"caption",
",",
"context",
",",
"extracted_image_data",
",",
"line_index",
",",
"lines",
")",
":",
"if",
"type",
"(",
"cur_image",
")",
"==",
"list",
":",
"if",
"cur_image",
"[",
"MAIN_CAPTION_OR_IMAGE",
"]",
... | Put it together.
Takes the current image(s) and caption(s) and assembles them into
something useful in the extracted_image_data list.
:param: cur_image (string || list): the image currently being dealt with,
or the list of images, in the case of subimages
:param: caption (string || list): the ... | [
"Put",
"it",
"together",
"."
] | train | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L570-L771 |
inspirehep/plotextractor | plotextractor/extractor.py | intelligently_find_filenames | def intelligently_find_filenames(line, TeX=False, ext=False,
commas_okay=False):
"""Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
... | python | def intelligently_find_filenames(line, TeX=False, ext=False,
commas_okay=False):
"""Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
... | [
"def",
"intelligently_find_filenames",
"(",
"line",
",",
"TeX",
"=",
"False",
",",
"ext",
"=",
"False",
",",
"commas_okay",
"=",
"False",
")",
":",
"files_included",
"=",
"[",
"'ERROR'",
"]",
"if",
"commas_okay",
":",
"valid_for_filename",
"=",
"'\\\\s*[A-Za-z... | Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
:return: filename ([string, ...]): what is probably the name of the file(s) | [
"Intelligently",
"find",
"filenames",
"."
] | train | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L774-L869 |
inspirehep/plotextractor | plotextractor/extractor.py | get_lines_from_file | def get_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines."""
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines =... | python | def get_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines."""
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines =... | [
"def",
"get_lines_from_file",
"(",
"filepath",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"try",
":",
"fd",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'r'",
",",
"encoding",
")",
"lines",
"=",
"fd",
".",
"readlines",
"(",
")",
"except",
"Unic... | Return an iterator over lines. | [
"Return",
"an",
"iterator",
"over",
"lines",
"."
] | train | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L872-L883 |
glenbot/campbx | campbx/campbx.py | CampBX.debug_mode | def debug_mode(self, toggle):
"""
Toggle debug mode for more detailed output
obj.debug_mode(True) - Turn debug mode on
obj.debug_mode(False) - Turn debug mode off
"""
if toggle:
self.log.setLevel(logging.DEBUG)
else:
self.log.setLevel(l... | python | def debug_mode(self, toggle):
"""
Toggle debug mode for more detailed output
obj.debug_mode(True) - Turn debug mode on
obj.debug_mode(False) - Turn debug mode off
"""
if toggle:
self.log.setLevel(logging.DEBUG)
else:
self.log.setLevel(l... | [
"def",
"debug_mode",
"(",
"self",
",",
"toggle",
")",
":",
"if",
"toggle",
":",
"self",
".",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"else",
":",
"self",
".",
"log",
".",
"setLevel",
"(",
"logging",
".",
"ERROR",
")"
] | Toggle debug mode for more detailed output
obj.debug_mode(True) - Turn debug mode on
obj.debug_mode(False) - Turn debug mode off | [
"Toggle",
"debug",
"mode",
"for",
"more",
"detailed",
"output",
"obj",
".",
"debug_mode",
"(",
"True",
")",
"-",
"Turn",
"debug",
"mode",
"on",
"obj",
".",
"debug_mode",
"(",
"False",
")",
"-",
"Turn",
"debug",
"mode",
"off"
] | train | https://github.com/glenbot/campbx/blob/b2e34c59ac1d645969e3a56551a1dcd755516094/campbx/campbx.py#L70-L79 |
glenbot/campbx | campbx/campbx.py | CampBX._make_request | def _make_request(self, conf, post_params={}):
"""Make a request to the API and return data in a pythonic object"""
endpoint, requires_auth = conf
# setup the url and the request objects
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
req... | python | def _make_request(self, conf, post_params={}):
"""Make a request to the API and return data in a pythonic object"""
endpoint, requires_auth = conf
# setup the url and the request objects
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
req... | [
"def",
"_make_request",
"(",
"self",
",",
"conf",
",",
"post_params",
"=",
"{",
"}",
")",
":",
"endpoint",
",",
"requires_auth",
"=",
"conf",
"# setup the url and the request objects",
"url",
"=",
"'%s%s.php'",
"%",
"(",
"self",
".",
"api_url",
",",
"endpoint"... | Make a request to the API and return data in a pythonic object | [
"Make",
"a",
"request",
"to",
"the",
"API",
"and",
"return",
"data",
"in",
"a",
"pythonic",
"object"
] | train | https://github.com/glenbot/campbx/blob/b2e34c59ac1d645969e3a56551a1dcd755516094/campbx/campbx.py#L81-L112 |
glenbot/campbx | campbx/campbx.py | CampBX._create_endpoints | def _create_endpoints(self):
"""Create all api endpoints using self.endpoint and partial from functools"""
for k, v in self.endpoints.items():
_repr = '%s.%s' % (self.__class__.__name__, k)
self.__dict__[k] = EndPointPartial(self._make_request, v, _repr) | python | def _create_endpoints(self):
"""Create all api endpoints using self.endpoint and partial from functools"""
for k, v in self.endpoints.items():
_repr = '%s.%s' % (self.__class__.__name__, k)
self.__dict__[k] = EndPointPartial(self._make_request, v, _repr) | [
"def",
"_create_endpoints",
"(",
"self",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"endpoints",
".",
"items",
"(",
")",
":",
"_repr",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"k",
")",
"self",
".",
"__dict_... | Create all api endpoints using self.endpoint and partial from functools | [
"Create",
"all",
"api",
"endpoints",
"using",
"self",
".",
"endpoint",
"and",
"partial",
"from",
"functools"
] | train | https://github.com/glenbot/campbx/blob/b2e34c59ac1d645969e3a56551a1dcd755516094/campbx/campbx.py#L114-L118 |
monkeython/scriba | scriba/content_types/scriba_zip.py | parse | def parse(binary, **params):
"""Turns a ZIP file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with zipfile.ZipFile(binary, 'r') as zip_:
for zip_info in zip_.infolist():
content_type, encoding = mimetypes.guess_type(zip_info.filename)
content =... | python | def parse(binary, **params):
"""Turns a ZIP file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with zipfile.ZipFile(binary, 'r') as zip_:
for zip_info in zip_.infolist():
content_type, encoding = mimetypes.guess_type(zip_info.filename)
content =... | [
"def",
"parse",
"(",
"binary",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
"binary",
")",
"collection",
"=",
"list",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"binary",
",",
"'r'",
")",
"as",
"zip_",
":",
... | Turns a ZIP file into a frozen sample. | [
"Turns",
"a",
"ZIP",
"file",
"into",
"a",
"frozen",
"sample",
"."
] | train | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_zip.py#L13-L24 |
monkeython/scriba | scriba/content_types/scriba_zip.py | format | def format(collection, **params):
"""Truns a python object into a ZIP file."""
binary = io.BytesIO()
with zipfile.ZipFile(binary, 'w') as zip_:
now = datetime.datetime.utcnow().timetuple()
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(filename... | python | def format(collection, **params):
"""Truns a python object into a ZIP file."""
binary = io.BytesIO()
with zipfile.ZipFile(binary, 'w') as zip_:
now = datetime.datetime.utcnow().timetuple()
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(filename... | [
"def",
"format",
"(",
"collection",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"binary",
",",
"'w'",
")",
"as",
"zip_",
":",
"now",
"=",
"datetime",
".",
"datetime",
"."... | Truns a python object into a ZIP file. | [
"Truns",
"a",
"python",
"object",
"into",
"a",
"ZIP",
"file",
"."
] | train | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_zip.py#L27-L40 |
minhhoit/yacms | yacms/generic/templatetags/keyword_tags.py | keywords_for | def keywords_for(*args):
"""
Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud.
"""
# Handle a model i... | python | def keywords_for(*args):
"""
Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud.
"""
# Handle a model i... | [
"def",
"keywords_for",
"(",
"*",
"args",
")",
":",
"# Handle a model instance.",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Model",
")",
":",
"obj",
"=",
"args",
"[",
"0",
"]",
"if",
"getattr",
"(",
"obj",
",",
"\"content_model\"",
",",
"Non... | Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud. | [
"Return",
"a",
"list",
"of",
"Keyword",
"objects",
"for",
"the",
"given",
"model",
"instance",
"or",
"a",
"model",
"class",
".",
"In",
"the",
"case",
"of",
"a",
"model",
"class",
"retrieve",
"all",
"keywords",
"for",
"all",
"instances",
"of",
"the",
"mod... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/keyword_tags.py#L16-L57 |
tBaxter/tango-comments | build/lib/tango_comments/views/moderation.py | flag | def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment
the flagged `comments.comment` object
"""
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk... | python | def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment
the flagged `comments.comment` object
"""
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk... | [
"def",
"flag",
"(",
"request",
",",
"comment_id",
",",
"next",
"=",
"None",
")",
":",
"comment",
"=",
"get_object_or_404",
"(",
"comments",
".",
"get_model",
"(",
")",
",",
"pk",
"=",
"comment_id",
",",
"site__pk",
"=",
"settings",
".",
"SITE_ID",
")",
... | Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment
the flagged `comments.comment` object | [
"Flags",
"a",
"comment",
".",
"Confirmation",
"on",
"GET",
"action",
"on",
"POST",
"."
] | train | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/moderation.py#L15-L37 |
tBaxter/tango-comments | build/lib/tango_comments/views/moderation.py | perform_flag | def perform_flag(request, comment):
"""
Actually perform the flagging of a comment from a request.
"""
flag, created = comments.models.CommentFlag.objects.get_or_create(
comment = comment,
user = request.user,
flag = comments.models.CommentFlag.SUGGEST_REMOVAL
)
sig... | python | def perform_flag(request, comment):
"""
Actually perform the flagging of a comment from a request.
"""
flag, created = comments.models.CommentFlag.objects.get_or_create(
comment = comment,
user = request.user,
flag = comments.models.CommentFlag.SUGGEST_REMOVAL
)
sig... | [
"def",
"perform_flag",
"(",
"request",
",",
"comment",
")",
":",
"flag",
",",
"created",
"=",
"comments",
".",
"models",
".",
"CommentFlag",
".",
"objects",
".",
"get_or_create",
"(",
"comment",
"=",
"comment",
",",
"user",
"=",
"request",
".",
"user",
"... | Actually perform the flagging of a comment from a request. | [
"Actually",
"perform",
"the",
"flagging",
"of",
"a",
"comment",
"from",
"a",
"request",
"."
] | train | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/moderation.py#L99-L114 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onConnect | def onConnect(self, request):
"""
Called when a client opens a websocket connection
"""
logger.debug("Connection opened ({peer})".format(peer=self.peer))
self.storage = {}
self._client_id = str(uuid1()) | python | def onConnect(self, request):
"""
Called when a client opens a websocket connection
"""
logger.debug("Connection opened ({peer})".format(peer=self.peer))
self.storage = {}
self._client_id = str(uuid1()) | [
"def",
"onConnect",
"(",
"self",
",",
"request",
")",
":",
"logger",
".",
"debug",
"(",
"\"Connection opened ({peer})\"",
".",
"format",
"(",
"peer",
"=",
"self",
".",
"peer",
")",
")",
"self",
".",
"storage",
"=",
"{",
"}",
"self",
".",
"_client_id",
... | Called when a client opens a websocket connection | [
"Called",
"when",
"a",
"client",
"opens",
"a",
"websocket",
"connection"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L18-L25 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onOpen | def onOpen(self):
"""
Called when a client has opened a websocket connection
"""
self.factory.add_client(self)
# Publish ON_OPEN message
self.factory.mease.publisher.publish(
message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage) | python | def onOpen(self):
"""
Called when a client has opened a websocket connection
"""
self.factory.add_client(self)
# Publish ON_OPEN message
self.factory.mease.publisher.publish(
message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage) | [
"def",
"onOpen",
"(",
"self",
")",
":",
"self",
".",
"factory",
".",
"add_client",
"(",
"self",
")",
"# Publish ON_OPEN message",
"self",
".",
"factory",
".",
"mease",
".",
"publisher",
".",
"publish",
"(",
"message_type",
"=",
"ON_OPEN",
",",
"client_id",
... | Called when a client has opened a websocket connection | [
"Called",
"when",
"a",
"client",
"has",
"opened",
"a",
"websocket",
"connection"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L27-L35 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onClose | def onClose(self, was_clean, code, reason):
"""
Called when a client closes a websocket connection
"""
logger.debug("Connection closed ({peer})".format(peer=self.peer))
# Publish ON_CLOSE message
self.factory.mease.publisher.publish(
message_type=ON_CLOSE, cl... | python | def onClose(self, was_clean, code, reason):
"""
Called when a client closes a websocket connection
"""
logger.debug("Connection closed ({peer})".format(peer=self.peer))
# Publish ON_CLOSE message
self.factory.mease.publisher.publish(
message_type=ON_CLOSE, cl... | [
"def",
"onClose",
"(",
"self",
",",
"was_clean",
",",
"code",
",",
"reason",
")",
":",
"logger",
".",
"debug",
"(",
"\"Connection closed ({peer})\"",
".",
"format",
"(",
"peer",
"=",
"self",
".",
"peer",
")",
")",
"# Publish ON_CLOSE message",
"self",
".",
... | Called when a client closes a websocket connection | [
"Called",
"when",
"a",
"client",
"closes",
"a",
"websocket",
"connection"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L37-L47 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onMessage | def onMessage(self, payload, is_binary):
"""
Called when a client sends a message
"""
if not is_binary:
payload = payload.decode('utf-8')
logger.debug("Incoming message ({peer}) : {message}".format(
peer=self.peer, message=payload))
#... | python | def onMessage(self, payload, is_binary):
"""
Called when a client sends a message
"""
if not is_binary:
payload = payload.decode('utf-8')
logger.debug("Incoming message ({peer}) : {message}".format(
peer=self.peer, message=payload))
#... | [
"def",
"onMessage",
"(",
"self",
",",
"payload",
",",
"is_binary",
")",
":",
"if",
"not",
"is_binary",
":",
"payload",
"=",
"payload",
".",
"decode",
"(",
"'utf-8'",
")",
"logger",
".",
"debug",
"(",
"\"Incoming message ({peer}) : {message}\"",
".",
"format",
... | Called when a client sends a message | [
"Called",
"when",
"a",
"client",
"sends",
"a",
"message"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L49-L64 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.sendMessage | def sendMessage(self, payload, *args, **kwargs):
"""
Logs message
"""
logger.debug("Outgoing message for ({peer}) : {message}".format(
peer=self.peer, message=payload))
WebSocketServerProtocol.sendMessage(self, payload, *args, **kwargs) | python | def sendMessage(self, payload, *args, **kwargs):
"""
Logs message
"""
logger.debug("Outgoing message for ({peer}) : {message}".format(
peer=self.peer, message=payload))
WebSocketServerProtocol.sendMessage(self, payload, *args, **kwargs) | [
"def",
"sendMessage",
"(",
"self",
",",
"payload",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"Outgoing message for ({peer}) : {message}\"",
".",
"format",
"(",
"peer",
"=",
"self",
".",
"peer",
",",
"message",
"=",... | Logs message | [
"Logs",
"message"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L66-L73 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.send | def send(self, payload, *args, **kwargs):
"""
Alias for WebSocketServerProtocol `sendMessage` method
"""
if isinstance(payload, (list, dict)):
payload = json.dumps(payload)
self.sendMessage(payload.encode(), *args, **kwargs) | python | def send(self, payload, *args, **kwargs):
"""
Alias for WebSocketServerProtocol `sendMessage` method
"""
if isinstance(payload, (list, dict)):
payload = json.dumps(payload)
self.sendMessage(payload.encode(), *args, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"payload",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"payload",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"payload",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"self",
... | Alias for WebSocketServerProtocol `sendMessage` method | [
"Alias",
"for",
"WebSocketServerProtocol",
"sendMessage",
"method"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L75-L82 |
florianpaquet/mease | mease/server.py | MeaseWebSocketServerFactory.run_server | def run_server(self):
"""
Runs the WebSocket server
"""
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)
logger.info("Websocket server listening on {address}".format(
address=self.address))
... | python | def run_server(self):
"""
Runs the WebSocket server
"""
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)
logger.info("Websocket server listening on {address}".format(
address=self.address))
... | [
"def",
"run_server",
"(",
"self",
")",
":",
"self",
".",
"protocol",
"=",
"MeaseWebSocketServerProtocol",
"reactor",
".",
"listenTCP",
"(",
"port",
"=",
"self",
".",
"port",
",",
"factory",
"=",
"self",
",",
"interface",
"=",
"self",
".",
"host",
")",
"l... | Runs the WebSocket server | [
"Runs",
"the",
"WebSocket",
"server"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L129-L140 |
blubberdiblub/eztemplate | eztemplate/engines/empy_engine.py | SubsystemWrapper.open | def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs) | python | def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs) | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"basedir",
"is",
"not",
"None",
":",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"basedir",
",",
"name",
")",
... | Open file, possibly relative to a base directory. | [
"Open",
"file",
"possibly",
"relative",
"to",
"a",
"base",
"directory",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/empy_engine.py#L32-L37 |
blubberdiblub/eztemplate | eztemplate/engines/empy_engine.py | EmpyEngine.apply | def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
self.output.seek(0)
self.output.truncate(0)
self.interpreter.string(self.template, locals=mapping)
return self.output.getvalue() | python | def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
self.output.seek(0)
self.output.truncate(0)
self.interpreter.string(self.template, locals=mapping)
return self.output.getvalue() | [
"def",
"apply",
"(",
"self",
",",
"mapping",
")",
":",
"self",
".",
"output",
".",
"seek",
"(",
"0",
")",
"self",
".",
"output",
".",
"truncate",
"(",
"0",
")",
"self",
".",
"interpreter",
".",
"string",
"(",
"self",
".",
"template",
",",
"locals",... | Apply a mapping of name-value-pairs to a template. | [
"Apply",
"a",
"mapping",
"of",
"name",
"-",
"value",
"-",
"pairs",
"to",
"a",
"template",
"."
] | train | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/empy_engine.py#L59-L64 |
Aslan11/wilos-cli | wilos/main.py | get_live_weather | def get_live_weather(lat, lon, writer):
"""Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
req = requests.get(requrl)
if req.status_code == requests.codes.ok:
weather = req.json()
if not weather['currently']:
c... | python | def get_live_weather(lat, lon, writer):
"""Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
req = requests.get(requrl)
if req.status_code == requests.codes.ok:
weather = req.json()
if not weather['currently']:
c... | [
"def",
"get_live_weather",
"(",
"lat",
",",
"lon",
",",
"writer",
")",
":",
"requrl",
"=",
"FORECAST_BASE_URL",
"+",
"forecast_api_token",
"+",
"'/'",
"+",
"str",
"(",
"lat",
")",
"+",
"','",
"+",
"str",
"(",
"lon",
")",
"req",
"=",
"requests",
".",
... | Gets the live weather via lat and long | [
"Gets",
"the",
"live",
"weather",
"via",
"lat",
"and",
"long"
] | train | https://github.com/Aslan11/wilos-cli/blob/2c3da3589f685e95b4f73237a1bfe56373ea4574/wilos/main.py#L53-L64 |
Aslan11/wilos-cli | wilos/main.py | main | def main(lat, lon, loc):
"""W.I.L.O.S: What's it like outside?"""
writer = get_writer()
try:
if (not lat or not lon) and (not loc):
raise IncorrectParametersException('Please specify a latitude, longitude, or location'
'Example: wilos --lat... | python | def main(lat, lon, loc):
"""W.I.L.O.S: What's it like outside?"""
writer = get_writer()
try:
if (not lat or not lon) and (not loc):
raise IncorrectParametersException('Please specify a latitude, longitude, or location'
'Example: wilos --lat... | [
"def",
"main",
"(",
"lat",
",",
"lon",
",",
"loc",
")",
":",
"writer",
"=",
"get_writer",
"(",
")",
"try",
":",
"if",
"(",
"not",
"lat",
"or",
"not",
"lon",
")",
"and",
"(",
"not",
"loc",
")",
":",
"raise",
"IncorrectParametersException",
"(",
"'Pl... | W.I.L.O.S: What's it like outside? | [
"W",
".",
"I",
".",
"L",
".",
"O",
".",
"S",
":",
"What",
"s",
"it",
"like",
"outside?"
] | train | https://github.com/Aslan11/wilos-cli/blob/2c3da3589f685e95b4f73237a1bfe56373ea4574/wilos/main.py#L70-L88 |
KnowledgeLinks/rdfframework | rdfframework/datamergers/bftopic_merger.py | SparqlMerger.create_same_as_file | def create_same_as_file(self):
""" creates a local data file with all of the owl:sameAs tags """
def find_preferred_uri(uri_list):
index = None
for i, uri in enumerate(uri_list):
if uri.startswith("<http://id.loc.gov/authorities/subjects/"):
... | python | def create_same_as_file(self):
""" creates a local data file with all of the owl:sameAs tags """
def find_preferred_uri(uri_list):
index = None
for i, uri in enumerate(uri_list):
if uri.startswith("<http://id.loc.gov/authorities/subjects/"):
... | [
"def",
"create_same_as_file",
"(",
"self",
")",
":",
"def",
"find_preferred_uri",
"(",
"uri_list",
")",
":",
"index",
"=",
"None",
"for",
"i",
",",
"uri",
"in",
"enumerate",
"(",
"uri_list",
")",
":",
"if",
"uri",
".",
"startswith",
"(",
"\"<http://id.loc.... | creates a local data file with all of the owl:sameAs tags | [
"creates",
"a",
"local",
"data",
"file",
"with",
"all",
"of",
"the",
"owl",
":",
"sameAs",
"tags"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datamergers/bftopic_merger.py#L127-L158 |
markomanninen/abnum | romanize/grc.py | preprocess | def preprocess(string):
"""
Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return:
"""
string = unicode(string, encoding="utf-8")
# convert diacritics to simpler forms
string = regex1.sub(lambda x: accents[x.group()... | python | def preprocess(string):
"""
Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return:
"""
string = unicode(string, encoding="utf-8")
# convert diacritics to simpler forms
string = regex1.sub(lambda x: accents[x.group()... | [
"def",
"preprocess",
"(",
"string",
")",
":",
"string",
"=",
"unicode",
"(",
"string",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"# convert diacritics to simpler forms",
"string",
"=",
"regex1",
".",
"sub",
"(",
"lambda",
"x",
":",
"accents",
"[",
"x",
".",
... | Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return: | [
"Preprocess",
"string",
"to",
"transform",
"all",
"diacritics",
"and",
"remove",
"other",
"special",
"characters",
"than",
"appropriate",
":",
"param",
"string",
":",
":",
"return",
":"
] | train | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/romanize/grc.py#L191-L202 |
markomanninen/abnum | romanize/grc.py | convert | def convert(string, sanitize=False):
"""
Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return:
"""
return r.convert(string, (preprocess if sanitize else False)) | python | def convert(string, sanitize=False):
"""
Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return:
"""
return r.convert(string, (preprocess if sanitize else False)) | [
"def",
"convert",
"(",
"string",
",",
"sanitize",
"=",
"False",
")",
":",
"return",
"r",
".",
"convert",
"(",
"string",
",",
"(",
"preprocess",
"if",
"sanitize",
"else",
"False",
")",
")"
] | Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return: | [
"Swap",
"characters",
"from",
"script",
"to",
"transliterated",
"version",
"and",
"vice",
"versa",
".",
"Optionally",
"sanitize",
"string",
"by",
"using",
"preprocess",
"function",
"."
] | train | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/romanize/grc.py#L204-L213 |
kubernauts/pyk | pyk/util.py | load_yaml | def load_yaml(filename):
"""
Loads a YAML-formatted file.
"""
with open(filename) as f:
ydoc = yaml.safe_load(f.read())
return (ydoc, serialize_tojson(ydoc)) | python | def load_yaml(filename):
"""
Loads a YAML-formatted file.
"""
with open(filename) as f:
ydoc = yaml.safe_load(f.read())
return (ydoc, serialize_tojson(ydoc)) | [
"def",
"load_yaml",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"ydoc",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"(",
"ydoc",
",",
"serialize_tojson",
"(",
"ydoc",
")",
")"
... | Loads a YAML-formatted file. | [
"Loads",
"a",
"YAML",
"-",
"formatted",
"file",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/util.py#L12-L18 |
kubernauts/pyk | pyk/util.py | serialize_yaml_tofile | def serialize_yaml_tofile(filename, resource):
"""
Serializes a K8S resource to YAML-formatted file.
"""
stream = file(filename, "w")
yaml.dump(resource, stream, default_flow_style=False) | python | def serialize_yaml_tofile(filename, resource):
"""
Serializes a K8S resource to YAML-formatted file.
"""
stream = file(filename, "w")
yaml.dump(resource, stream, default_flow_style=False) | [
"def",
"serialize_yaml_tofile",
"(",
"filename",
",",
"resource",
")",
":",
"stream",
"=",
"file",
"(",
"filename",
",",
"\"w\"",
")",
"yaml",
".",
"dump",
"(",
"resource",
",",
"stream",
",",
"default_flow_style",
"=",
"False",
")"
] | Serializes a K8S resource to YAML-formatted file. | [
"Serializes",
"a",
"K8S",
"resource",
"to",
"YAML",
"-",
"formatted",
"file",
"."
] | train | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/util.py#L20-L25 |
monkeython/scriba | scriba/content_types/scriba_json.py | parse | def parse(binary, **params):
"""Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8')
return json.loads(binary, encoding=encoding) | python | def parse(binary, **params):
"""Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8')
return json.loads(binary, encoding=encoding) | [
"def",
"parse",
"(",
"binary",
",",
"*",
"*",
"params",
")",
":",
"encoding",
"=",
"params",
".",
"get",
"(",
"'charset'",
",",
"'UTF-8'",
")",
"return",
"json",
".",
"loads",
"(",
"binary",
",",
"encoding",
"=",
"encoding",
")"
] | Turns a JSON structure into a python object. | [
"Turns",
"a",
"JSON",
"structure",
"into",
"a",
"python",
"object",
"."
] | train | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_json.py#L6-L9 |
monkeython/scriba | scriba/content_types/scriba_json.py | format | def format(item, **params):
"""Truns a python object into a JSON structure."""
encoding = params.get('charset', 'UTF-8')
return json.dumps(item, encoding=encoding) | python | def format(item, **params):
"""Truns a python object into a JSON structure."""
encoding = params.get('charset', 'UTF-8')
return json.dumps(item, encoding=encoding) | [
"def",
"format",
"(",
"item",
",",
"*",
"*",
"params",
")",
":",
"encoding",
"=",
"params",
".",
"get",
"(",
"'charset'",
",",
"'UTF-8'",
")",
"return",
"json",
".",
"dumps",
"(",
"item",
",",
"encoding",
"=",
"encoding",
")"
] | Truns a python object into a JSON structure. | [
"Truns",
"a",
"python",
"object",
"into",
"a",
"JSON",
"structure",
"."
] | train | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_json.py#L12-L15 |
encukou/czech-sort | czech_sort/impl.py | key | def key(string):
"""Return a Czech sort key for the given string
:param string: string (unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order, i.e.
``key(s1) < key(s2)`` <=> ``s1`` comes before ``s... | python | def key(string):
"""Return a Czech sort key for the given string
:param string: string (unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order, i.e.
``key(s1) < key(s2)`` <=> ``s1`` comes before ``s... | [
"def",
"key",
"(",
"string",
")",
":",
"# The multi-level key is a nested tuple containing strings and ints.",
"# The tuple contains sub-keys that roughly correspond to levels in",
"# UTS #10 (http://unicode.org/reports/tr10/). Except for fallback strings",
"# at the end, each contains a tuple of ... | Return a Czech sort key for the given string
:param string: string (unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order, i.e.
``key(s1) < key(s2)`` <=> ``s1`` comes before ``s2``
The structure o... | [
"Return",
"a",
"Czech",
"sort",
"key",
"for",
"the",
"given",
"string"
] | train | https://github.com/encukou/czech-sort/blob/e181c76421d374139a0cd6a35ecd649aeb5aa48e/czech_sort/impl.py#L36-L166 |
naphatkrit/easyci | easyci/results.py | save_results | def save_results(vcs, signature, result_path, patterns):
"""Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
... | python | def save_results(vcs, signature, result_path, patterns):
"""Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
... | [
"def",
"save_results",
"(",
"vcs",
",",
"signature",
",",
"result_path",
",",
"patterns",
")",
":",
"results_directory",
"=",
"_get_results_directory",
"(",
"vcs",
",",
"signature",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_directory",
... | Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
result_path (str) - the path containing the result, usually
... | [
"Save",
"results",
"matching",
"patterns",
"at",
"result_path",
"."
] | train | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L14-L38 |
naphatkrit/easyci | easyci/results.py | sync_results | def sync_results(vcs, signature):
"""Sync the saved results for `signature` back to the project.
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_dire... | python | def sync_results(vcs, signature):
"""Sync the saved results for `signature` back to the project.
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_dire... | [
"def",
"sync_results",
"(",
"vcs",
",",
"signature",
")",
":",
"results_directory",
"=",
"_get_results_directory",
"(",
"vcs",
",",
"signature",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_directory",
")",
":",
"raise",
"ResultsNotFoundEr... | Sync the saved results for `signature` back to the project.
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError | [
"Sync",
"the",
"saved",
"results",
"for",
"signature",
"back",
"to",
"the",
"project",
"."
] | train | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L41-L61 |
naphatkrit/easyci | easyci/results.py | remove_results | def remove_results(vcs, signature):
"""Removed saved results for this signature
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
r... | python | def remove_results(vcs, signature):
"""Removed saved results for this signature
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
r... | [
"def",
"remove_results",
"(",
"vcs",
",",
"signature",
")",
":",
"results_directory",
"=",
"_get_results_directory",
"(",
"vcs",
",",
"signature",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_directory",
")",
":",
"raise",
"ResultsNotFound... | Removed saved results for this signature
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError | [
"Removed",
"saved",
"results",
"for",
"this",
"signature"
] | train | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L64-L76 |
naphatkrit/easyci | easyci/results.py | get_signatures_with_results | def get_signatures_with_results(vcs):
"""Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str]
"""
results_dir = os.path.join(vcs.private_dir(), 'results')
if not os.path.exists(results_dir):
return []
re... | python | def get_signatures_with_results(vcs):
"""Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str]
"""
results_dir = os.path.join(vcs.private_dir(), 'results')
if not os.path.exists(results_dir):
return []
re... | [
"def",
"get_signatures_with_results",
"(",
"vcs",
")",
":",
"results_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vcs",
".",
"private_dir",
"(",
")",
",",
"'results'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_dir",
")",
":"... | Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str] | [
"Returns",
"the",
"list",
"of",
"signatures",
"for",
"which",
"test",
"results",
"are",
"saved",
"."
] | train | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L79-L92 |
dossier/dossier.web | dossier/web/label_folders.py | nub | def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
'''
seen = set()
for v in it:
h = hash(v)
if h in seen:
continue
seen.add(h)
yield v | python | def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
'''
seen = set()
for v in it:
h = hash(v)
if h in seen:
continue
seen.add(h)
yield v | [
"def",
"nub",
"(",
"it",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"it",
":",
"h",
"=",
"hash",
"(",
"v",
")",
"if",
"h",
"in",
"seen",
":",
"continue",
"seen",
".",
"add",
"(",
"h",
")",
"yield",
"v"
] | Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``. | [
"Dedups",
"an",
"iterable",
"in",
"arbitrary",
"order",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L292-L303 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.folders | def folders(self, ann_id=None):
'''Yields an unordered generator for all available folders.
By default (with ``ann_id=None``), folders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only folders owned by that user.
... | python | def folders(self, ann_id=None):
'''Yields an unordered generator for all available folders.
By default (with ``ann_id=None``), folders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only folders owned by that user.
... | [
"def",
"folders",
"(",
"self",
",",
"ann_id",
"=",
"None",
")",
":",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"if",
"len",
"(",
"self",
".",
"prefix",
")",
">",
"0",
":",
"prefix",
"=",
"'|'",
".",
"join",
"(",
"[",
"urllib",... | Yields an unordered generator for all available folders.
By default (with ``ann_id=None``), folders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only folders owned by that user.
:param str ann_id: Username
:rtyp... | [
"Yields",
"an",
"unordered",
"generator",
"for",
"all",
"available",
"folders",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L92-L110 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.subfolders | def subfolders(self, folder_id, ann_id=None):
'''Yields an unodered generator of subfolders in a folder.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subfolders owned by... | python | def subfolders(self, folder_id, ann_id=None):
'''Yields an unodered generator of subfolders in a folder.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subfolders owned by... | [
"def",
"subfolders",
"(",
"self",
",",
"folder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"folder_cid",
"=",
"self",
".",
"wrap_fold... | Yields an unodered generator of subfolders in a folder.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subfolders owned by that user.
:param str folder_id: Folder id
... | [
"Yields",
"an",
"unodered",
"generator",
"of",
"subfolders",
"in",
"a",
"folder",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L112-L129 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.parent_subfolders | def parent_subfolders(self, ident, ann_id=None):
'''An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifie... | python | def parent_subfolders(self, ident, ann_id=None):
'''An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifie... | [
"def",
"parent_subfolders",
"(",
"self",
",",
"ident",
",",
"ann_id",
"=",
"None",
")",
":",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"cid",
",",
"_",
"=",
"normalize_ident",
"(",
"ident",
")",
"for",
"lab",
"in",
"self",
".",
"l... | An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifier
:type ident: ``str`` or ``(str, str)``
:pa... | [
"An",
"unordered",
"generator",
"of",
"parent",
"subfolders",
"for",
"ident",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L131-L155 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.items | def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | python | def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | [
"def",
"items",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"self",
".",
"assert_valid_folder_id",
"(",
"subfolder_id",
")",
"ann_id",
"=",
"self",
".... | Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous us... | [
"Yields",
"an",
"unodered",
"generator",
"of",
"items",
"in",
"a",
"subfolder",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L157-L185 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.grouped_items | def grouped_items(self, folder_id, subfolder_id, ann_id=None):
'''Returns a dictionary from content ids to subtopic ids.
Namely, the mapping is ``content_id |--> list of subtopic id``.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id... | python | def grouped_items(self, folder_id, subfolder_id, ann_id=None):
'''Returns a dictionary from content ids to subtopic ids.
Namely, the mapping is ``content_id |--> list of subtopic id``.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id... | [
"def",
"grouped_items",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"cid",
",",
"subid",
"in",
"self",
".",
"items",
"(",
"folder_id",
",",
"subfolder_id",
... | Returns a dictionary from content ids to subtopic ids.
Namely, the mapping is ``content_id |--> list of subtopic id``.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subf... | [
"Returns",
"a",
"dictionary",
"from",
"content",
"ids",
"to",
"subtopic",
"ids",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L187-L204 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.add_folder | def add_folder(self, folder_id, ann_id=None):
'''Add a folder.
If ``ann_id`` is set, then the folder is owned by the given user.
Otherwise, the folder is owned and viewable by all anonymous
users.
:param str folder_id: Folder id
:param str ann_id: Username
'''
... | python | def add_folder(self, folder_id, ann_id=None):
'''Add a folder.
If ``ann_id`` is set, then the folder is owned by the given user.
Otherwise, the folder is owned and viewable by all anonymous
users.
:param str folder_id: Folder id
:param str ann_id: Username
'''
... | [
"def",
"add_folder",
"(",
"self",
",",
"folder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"cid",
"=",
"self",
".",
"wrap_folder_cont... | Add a folder.
If ``ann_id`` is set, then the folder is owned by the given user.
Otherwise, the folder is owned and viewable by all anonymous
users.
:param str folder_id: Folder id
:param str ann_id: Username | [
"Add",
"a",
"folder",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L206-L220 |
dossier/dossier.web | dossier/web/label_folders.py | Folders.add_item | def add_item(self, folder_id, subfolder_id, content_id, subtopic_id=None,
ann_id=None):
'''Add an item to a subfolder.
The format of ``content_id`` and ``subtopic_id`` is
unspecified. It is application specific.
If ``ann_id`` is set, then the item is owned by the given... | python | def add_item(self, folder_id, subfolder_id, content_id, subtopic_id=None,
ann_id=None):
'''Add an item to a subfolder.
The format of ``content_id`` and ``subtopic_id`` is
unspecified. It is application specific.
If ``ann_id`` is set, then the item is owned by the given... | [
"def",
"add_item",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"content_id",
",",
"subtopic_id",
"=",
"None",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"self",
".",
"assert_valid_folder_id"... | Add an item to a subfolder.
The format of ``content_id`` and ``subtopic_id`` is
unspecified. It is application specific.
If ``ann_id`` is set, then the item is owned by the given user.
Otherwise, the item is owned and viewable by all anonymous
users.
:param str folder_... | [
"Add",
"an",
"item",
"to",
"a",
"subfolder",
"."
] | train | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L222-L253 |
timmartin19/pystatuschecker | status_checker.py | StatusChecker.status | def status(self, *args, **kwargs):
"""
Call this method to get a dictionary that will
describe the status of all components. The `*args`
and `**kwargs` will be passed to the function
:param list args: args to pass to all of the component checkers
:param dict kwargs: key... | python | def status(self, *args, **kwargs):
"""
Call this method to get a dictionary that will
describe the status of all components. The `*args`
and `**kwargs` will be passed to the function
:param list args: args to pass to all of the component checkers
:param dict kwargs: key... | [
"def",
"status",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"{",
"}",
"available",
"=",
"True",
"fail_count",
"=",
"0",
"for",
"component_name",
",",
"checker",
"in",
"self",
".",
"_component_checkers",
".",
"items",... | Call this method to get a dictionary that will
describe the status of all components. The `*args`
and `**kwargs` will be passed to the function
:param list args: args to pass to all of the component checkers
:param dict kwargs: keyword arguments to pass to
all of the compon... | [
"Call",
"this",
"method",
"to",
"get",
"a",
"dictionary",
"that",
"will",
"describe",
"the",
"status",
"of",
"all",
"components",
".",
"The",
"*",
"args",
"and",
"**",
"kwargs",
"will",
"be",
"passed",
"to",
"the",
"function"
] | train | https://github.com/timmartin19/pystatuschecker/blob/35e3bff2fc82cf71b8651cb958c7fc6a003d30e5/status_checker.py#L40-L67 |
timmartin19/pystatuschecker | status_checker.py | StatusChecker._check_status | def _check_status(func, read_exception, *args, **kwargs):
"""
Checks the status of a single component by
calling the func with the args. The func is expected to
return a dict with at least an `available=<bool>` key
value pair
:param func func: The function to call
... | python | def _check_status(func, read_exception, *args, **kwargs):
"""
Checks the status of a single component by
calling the func with the args. The func is expected to
return a dict with at least an `available=<bool>` key
value pair
:param func func: The function to call
... | [
"def",
"_check_status",
"(",
"func",
",",
"read_exception",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"_LOG",
".",
"exce... | Checks the status of a single component by
calling the func with the args. The func is expected to
return a dict with at least an `available=<bool>` key
value pair
:param func func: The function to call
:param read_exception: If an exception is thrown
should the exc... | [
"Checks",
"the",
"status",
"of",
"a",
"single",
"component",
"by",
"calling",
"the",
"func",
"with",
"the",
"args",
".",
"The",
"func",
"is",
"expected",
"to",
"return",
"a",
"dict",
"with",
"at",
"least",
"an",
"available",
"=",
"<bool",
">",
"key",
"... | train | https://github.com/timmartin19/pystatuschecker/blob/35e3bff2fc82cf71b8651cb958c7fc6a003d30e5/status_checker.py#L70-L96 |
treycucco/bidon | lib/generate_models.py | parse_args | def parse_args():
"""Parses command line arguments."""
parser = ArgumentParser(description="ModelBase builder")
subparsers = parser.add_subparsers()
sql_parser = subparsers.add_parser(
"get-query",
description="Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " +
... | python | def parse_args():
"""Parses command line arguments."""
parser = ArgumentParser(description="ModelBase builder")
subparsers = parser.add_subparsers()
sql_parser = subparsers.add_parser(
"get-query",
description="Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " +
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"ModelBase builder\"",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"sql_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"get-query\"",
",... | Parses command line arguments. | [
"Parses",
"command",
"line",
"arguments",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L21-L46 |
treycucco/bidon | lib/generate_models.py | generate_models | def generate_models(args):
"""Generates models from the script input."""
data_table = get_data_table(args.filename)
tables = to_tables(data_table.rows_to_dicts())
attr_indent = "\n" + args.indent * 2
attr_sep = "," + attr_indent
for tname, cols in tables.items():
model_name = table_to_model_name(tname,... | python | def generate_models(args):
"""Generates models from the script input."""
data_table = get_data_table(args.filename)
tables = to_tables(data_table.rows_to_dicts())
attr_indent = "\n" + args.indent * 2
attr_sep = "," + attr_indent
for tname, cols in tables.items():
model_name = table_to_model_name(tname,... | [
"def",
"generate_models",
"(",
"args",
")",
":",
"data_table",
"=",
"get_data_table",
"(",
"args",
".",
"filename",
")",
"tables",
"=",
"to_tables",
"(",
"data_table",
".",
"rows_to_dicts",
"(",
")",
")",
"attr_indent",
"=",
"\"\\n\"",
"+",
"args",
".",
"i... | Generates models from the script input. | [
"Generates",
"models",
"from",
"the",
"script",
"input",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L55-L82 |
treycucco/bidon | lib/generate_models.py | get_data_table | def get_data_table(filename):
"""Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | python | def get_data_table(filename):
"""Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | [
"def",
"get_data_table",
"(",
"filename",
")",
":",
"with",
"get_file_object",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"rf",
":",
"return",
"DataTable",
"(",
"list",
"(",
"csv",
".",
"reader",
"(",
"rf",
")",
")",
")"
] | Returns a DataTable instance built from either the filename, or STDIN if filename is None. | [
"Returns",
"a",
"DataTable",
"instance",
"built",
"from",
"either",
"the",
"filename",
"or",
"STDIN",
"if",
"filename",
"is",
"None",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L85-L88 |
treycucco/bidon | lib/generate_models.py | to_tables | def to_tables(cols):
"""Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose
keys are column names and values are the col objects from which the definition is derived.
"""
tables = OrderedDict()
for col in cols:
tname = col["table_name"]
if tname not in tables:
... | python | def to_tables(cols):
"""Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose
keys are column names and values are the col objects from which the definition is derived.
"""
tables = OrderedDict()
for col in cols:
tname = col["table_name"]
if tname not in tables:
... | [
"def",
"to_tables",
"(",
"cols",
")",
":",
"tables",
"=",
"OrderedDict",
"(",
")",
"for",
"col",
"in",
"cols",
":",
"tname",
"=",
"col",
"[",
"\"table_name\"",
"]",
"if",
"tname",
"not",
"in",
"tables",
":",
"tables",
"[",
"tname",
"]",
"=",
"Ordered... | Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose
keys are column names and values are the col objects from which the definition is derived. | [
"Builds",
"and",
"returns",
"a",
"Dictionary",
"whose",
"keys",
"are",
"table",
"names",
"and",
"values",
"are",
"OrderedDicts",
"whose",
"keys",
"are",
"column",
"names",
"and",
"values",
"are",
"the",
"col",
"objects",
"from",
"which",
"the",
"definition",
... | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L91-L101 |
treycucco/bidon | lib/generate_models.py | snake_to_pascal | def snake_to_pascal(name, singularize=False):
"""Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing
each part of the resulting name.
"""
parts = name.split("_")
if singularize:
return "".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts... | python | def snake_to_pascal(name, singularize=False):
"""Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing
each part of the resulting name.
"""
parts = name.split("_")
if singularize:
return "".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts... | [
"def",
"snake_to_pascal",
"(",
"name",
",",
"singularize",
"=",
"False",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\"_\"",
")",
"if",
"singularize",
":",
"return",
"\"\"",
".",
"join",
"(",
"p",
".",
"upper",
"(",
")",
"if",
"p",
"in",
"_... | Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing
each part of the resulting name. | [
"Converts",
"snake_case",
"to",
"PascalCase",
".",
"If",
"singularize",
"is",
"True",
"an",
"attempt",
"is",
"made",
"at",
"singularizing",
"each",
"part",
"of",
"the",
"resulting",
"name",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L109-L117 |
treycucco/bidon | lib/generate_models.py | to_singular | def to_singular(word):
"""Attempts to singularize a word."""
if word[-1] != "s":
return word
elif word.endswith("ies"):
return word[:-3] + "y"
elif word.endswith("ses"):
return word[:-2]
else:
return word[:-1] | python | def to_singular(word):
"""Attempts to singularize a word."""
if word[-1] != "s":
return word
elif word.endswith("ies"):
return word[:-3] + "y"
elif word.endswith("ses"):
return word[:-2]
else:
return word[:-1] | [
"def",
"to_singular",
"(",
"word",
")",
":",
"if",
"word",
"[",
"-",
"1",
"]",
"!=",
"\"s\"",
":",
"return",
"word",
"elif",
"word",
".",
"endswith",
"(",
"\"ies\"",
")",
":",
"return",
"word",
"[",
":",
"-",
"3",
"]",
"+",
"\"y\"",
"elif",
"word... | Attempts to singularize a word. | [
"Attempts",
"to",
"singularize",
"a",
"word",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L120-L129 |
treycucco/bidon | lib/generate_models.py | split_pks | def split_pks(cols):
"""Returns a 2-tuple of tuples of ((primary_key_cols), (non_primary_key_cols))."""
pks = []
others = []
for name, col in cols.items():
if col["is_primary_key"] == "t":
pks.append(name)
else:
others.append(name)
return (tuple(pks), tuple(others)) | python | def split_pks(cols):
"""Returns a 2-tuple of tuples of ((primary_key_cols), (non_primary_key_cols))."""
pks = []
others = []
for name, col in cols.items():
if col["is_primary_key"] == "t":
pks.append(name)
else:
others.append(name)
return (tuple(pks), tuple(others)) | [
"def",
"split_pks",
"(",
"cols",
")",
":",
"pks",
"=",
"[",
"]",
"others",
"=",
"[",
"]",
"for",
"name",
",",
"col",
"in",
"cols",
".",
"items",
"(",
")",
":",
"if",
"col",
"[",
"\"is_primary_key\"",
"]",
"==",
"\"t\"",
":",
"pks",
".",
"append",... | Returns a 2-tuple of tuples of ((primary_key_cols), (non_primary_key_cols)). | [
"Returns",
"a",
"2",
"-",
"tuple",
"of",
"tuples",
"of",
"((",
"primary_key_cols",
")",
"(",
"non_primary_key_cols",
"))",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L132-L142 |
treycucco/bidon | lib/generate_models.py | get_timestamps | def get_timestamps(cols, created_name, updated_name):
"""Returns a 2-tuple of the timestamp columns that were found on the table definition."""
has_created = created_name in cols
has_updated = updated_name in cols
return (created_name if has_created else None, updated_name if has_updated else None) | python | def get_timestamps(cols, created_name, updated_name):
"""Returns a 2-tuple of the timestamp columns that were found on the table definition."""
has_created = created_name in cols
has_updated = updated_name in cols
return (created_name if has_created else None, updated_name if has_updated else None) | [
"def",
"get_timestamps",
"(",
"cols",
",",
"created_name",
",",
"updated_name",
")",
":",
"has_created",
"=",
"created_name",
"in",
"cols",
"has_updated",
"=",
"updated_name",
"in",
"cols",
"return",
"(",
"created_name",
"if",
"has_created",
"else",
"None",
",",... | Returns a 2-tuple of the timestamp columns that were found on the table definition. | [
"Returns",
"a",
"2",
"-",
"tuple",
"of",
"the",
"timestamp",
"columns",
"that",
"were",
"found",
"on",
"the",
"table",
"definition",
"."
] | train | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L145-L149 |
Tinche/django-bower-cache | registry/gitwrapper.py | pull_from_origin | def pull_from_origin(repo_path):
"""Execute 'git pull' at the provided repo_path."""
LOG.info("Pulling from origin at %s." % repo_path)
command = GIT_PULL_CMD.format(repo_path)
resp = envoy.run(command)
if resp.status_code != 0:
LOG.exception("Pull failed.")
raise GitException(resp.s... | python | def pull_from_origin(repo_path):
"""Execute 'git pull' at the provided repo_path."""
LOG.info("Pulling from origin at %s." % repo_path)
command = GIT_PULL_CMD.format(repo_path)
resp = envoy.run(command)
if resp.status_code != 0:
LOG.exception("Pull failed.")
raise GitException(resp.s... | [
"def",
"pull_from_origin",
"(",
"repo_path",
")",
":",
"LOG",
".",
"info",
"(",
"\"Pulling from origin at %s.\"",
"%",
"repo_path",
")",
"command",
"=",
"GIT_PULL_CMD",
".",
"format",
"(",
"repo_path",
")",
"resp",
"=",
"envoy",
".",
"run",
"(",
"command",
"... | Execute 'git pull' at the provided repo_path. | [
"Execute",
"git",
"pull",
"at",
"the",
"provided",
"repo_path",
"."
] | train | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L26-L35 |
Tinche/django-bower-cache | registry/gitwrapper.py | read_remote_origin | def read_remote_origin(repo_dir):
"""Read the remote origin URL from the given git repo, or None if unset."""
conf = ConfigParser()
conf.read(os.path.join(repo_dir, '.git/config'))
return conf.get('remote "origin"', 'url') | python | def read_remote_origin(repo_dir):
"""Read the remote origin URL from the given git repo, or None if unset."""
conf = ConfigParser()
conf.read(os.path.join(repo_dir, '.git/config'))
return conf.get('remote "origin"', 'url') | [
"def",
"read_remote_origin",
"(",
"repo_dir",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo_dir",
",",
"'.git/config'",
")",
")",
"return",
"conf",
".",
"get",
"(",
"'remote \"origin... | Read the remote origin URL from the given git repo, or None if unset. | [
"Read",
"the",
"remote",
"origin",
"URL",
"from",
"the",
"given",
"git",
"repo",
"or",
"None",
"if",
"unset",
"."
] | train | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L38-L42 |
Tinche/django-bower-cache | registry/gitwrapper.py | clone_from | def clone_from(repo_url, repo_dir):
"""Clone a remote git repo into a local directory."""
repo_url = _fix_repo_url(repo_url)
LOG.info("Cloning %s into %s." % (repo_url, repo_dir))
cmd = GIT_CLONE_CMD.format(repo_url, repo_dir)
resp = envoy.run(cmd)
if resp.status_code != 0:
LOG.error("Cl... | python | def clone_from(repo_url, repo_dir):
"""Clone a remote git repo into a local directory."""
repo_url = _fix_repo_url(repo_url)
LOG.info("Cloning %s into %s." % (repo_url, repo_dir))
cmd = GIT_CLONE_CMD.format(repo_url, repo_dir)
resp = envoy.run(cmd)
if resp.status_code != 0:
LOG.error("Cl... | [
"def",
"clone_from",
"(",
"repo_url",
",",
"repo_dir",
")",
":",
"repo_url",
"=",
"_fix_repo_url",
"(",
"repo_url",
")",
"LOG",
".",
"info",
"(",
"\"Cloning %s into %s.\"",
"%",
"(",
"repo_url",
",",
"repo_dir",
")",
")",
"cmd",
"=",
"GIT_CLONE_CMD",
".",
... | Clone a remote git repo into a local directory. | [
"Clone",
"a",
"remote",
"git",
"repo",
"into",
"a",
"local",
"directory",
"."
] | train | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L45-L54 |
Tinche/django-bower-cache | registry/gitwrapper.py | _fix_repo_url | def _fix_repo_url(repo_url):
"""Add empty credentials to a repo URL if not set, but only for HTTP/HTTPS.
This is to make git not hang while trying to read the username and
password from standard input."""
parsed = urlparse.urlparse(repo_url)
if parsed.scheme not in ('http', 'https'):
... | python | def _fix_repo_url(repo_url):
"""Add empty credentials to a repo URL if not set, but only for HTTP/HTTPS.
This is to make git not hang while trying to read the username and
password from standard input."""
parsed = urlparse.urlparse(repo_url)
if parsed.scheme not in ('http', 'https'):
... | [
"def",
"_fix_repo_url",
"(",
"repo_url",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"repo_url",
")",
"if",
"parsed",
".",
"scheme",
"not",
"in",
"(",
"'http'",
",",
"'https'",
")",
":",
"# Fix only for http and https.",
"return",
"repo_url",
... | Add empty credentials to a repo URL if not set, but only for HTTP/HTTPS.
This is to make git not hang while trying to read the username and
password from standard input. | [
"Add",
"empty",
"credentials",
"to",
"a",
"repo",
"URL",
"if",
"not",
"set",
"but",
"only",
"for",
"HTTP",
"/",
"HTTPS",
"."
] | train | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L57-L74 |
rkday/nose2dep | nose2dep/core.py | NoseDepUtils.calculate_dependencies | def calculate_dependencies():
"""Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities.
"""
order = []
for group in toposort(dependencies):
priority_sorted_group = so... | python | def calculate_dependencies():
"""Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities.
"""
order = []
for group in toposort(dependencies):
priority_sorted_group = so... | [
"def",
"calculate_dependencies",
"(",
")",
":",
"order",
"=",
"[",
"]",
"for",
"group",
"in",
"toposort",
"(",
"dependencies",
")",
":",
"priority_sorted_group",
"=",
"sorted",
"(",
"group",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"priorities",
"[",
"x... | Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities. | [
"Calculate",
"test",
"dependencies",
"First",
"do",
"a",
"topological",
"sorting",
"based",
"on",
"the",
"dependencies",
".",
"Then",
"sort",
"the",
"different",
"dependency",
"groups",
"based",
"on",
"priorities",
"."
] | train | https://github.com/rkday/nose2dep/blob/135a529a6c930862deec0276a054412c2056cef9/nose2dep/core.py#L126-L136 |
rkday/nose2dep | nose2dep/core.py | NoseDepUtils.dependency_failed | def dependency_failed(test, results):
"""Returns an error string if any of the dependencies failed"""
for d in (NoseDepUtils.test_name(i) for i in dependencies[test]):
if results.get(d) and results.get(d) != 'passed':
return "Required test '{}' {}".format(d, results.get(d).up... | python | def dependency_failed(test, results):
"""Returns an error string if any of the dependencies failed"""
for d in (NoseDepUtils.test_name(i) for i in dependencies[test]):
if results.get(d) and results.get(d) != 'passed':
return "Required test '{}' {}".format(d, results.get(d).up... | [
"def",
"dependency_failed",
"(",
"test",
",",
"results",
")",
":",
"for",
"d",
"in",
"(",
"NoseDepUtils",
".",
"test_name",
"(",
"i",
")",
"for",
"i",
"in",
"dependencies",
"[",
"test",
"]",
")",
":",
"if",
"results",
".",
"get",
"(",
"d",
")",
"an... | Returns an error string if any of the dependencies failed | [
"Returns",
"an",
"error",
"string",
"if",
"any",
"of",
"the",
"dependencies",
"failed"
] | train | https://github.com/rkday/nose2dep/blob/135a529a6c930862deec0276a054412c2056cef9/nose2dep/core.py#L159-L164 |
thespacedoctor/qubits | qubits/surveysim.py | survey_cadence_arrays | def survey_cadence_arrays(
log,
surveyCadenceSettings,
pathToOutputDirectory,
pathToOutputPlotDirectory,
plot=False):
"""
*Generate the survey cadence arrays for each filter*
**Key Arguments:**
- ``log`` -- logger
- ``surveyCadenceSettings`` -- the su... | python | def survey_cadence_arrays(
log,
surveyCadenceSettings,
pathToOutputDirectory,
pathToOutputPlotDirectory,
plot=False):
"""
*Generate the survey cadence arrays for each filter*
**Key Arguments:**
- ``log`` -- logger
- ``surveyCadenceSettings`` -- the su... | [
"def",
"survey_cadence_arrays",
"(",
"log",
",",
"surveyCadenceSettings",
",",
"pathToOutputDirectory",
",",
"pathToOutputPlotDirectory",
",",
"plot",
"=",
"False",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"## THIRD PARTY ##",
"## LOCAL APP... | *Generate the survey cadence arrays for each filter*
**Key Arguments:**
- ``log`` -- logger
- ``surveyCadenceSettings`` -- the survey cadence parameters as set in the simulation settings file
- ``pathToOutputDirectory`` -- path to the output directory (provided by the user)
- ``path... | [
"*",
"Generate",
"the",
"survey",
"cadence",
"arrays",
"for",
"each",
"filter",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/surveysim.py#L34-L176 |
thespacedoctor/qubits | qubits/surveysim.py | determine_if_sne_are_discoverable | def determine_if_sne_are_discoverable(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
pathToOutputDirectory,
pathToOutputPlotDirectory,
plot=True):
"""
*Given the observe frame lightcurve, determine if the SNe are discoverable by the survey... | python | def determine_if_sne_are_discoverable(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
pathToOutputDirectory,
pathToOutputPlotDirectory,
plot=True):
"""
*Given the observe frame lightcurve, determine if the SNe are discoverable by the survey... | [
"def",
"determine_if_sne_are_discoverable",
"(",
"log",
",",
"redshiftArray",
",",
"limitingMags",
",",
"observedFrameLightCurveInfo",
",",
"pathToOutputDirectory",
",",
"pathToOutputPlotDirectory",
",",
"plot",
"=",
"True",
")",
":",
"################ > IMPORTS #############... | *Given the observe frame lightcurve, determine if the SNe are discoverable by the survey or not.*
**Key Arguments:**
- ``log`` -- logger
- ``redshiftArray`` -- the array of random redshifts
- ``observedFrameLightCurveInfo`` -- the observed franme lightcurve info (dictionary)
- ``pat... | [
"*",
"Given",
"the",
"observe",
"frame",
"lightcurve",
"determine",
"if",
"the",
"SNe",
"are",
"discoverable",
"by",
"the",
"survey",
"or",
"not",
".",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/surveysim.py#L182-L262 |
thespacedoctor/qubits | qubits/surveysim.py | determine_when_sne_are_ripe_for_discovery | def determine_when_sne_are_ripe_for_discovery(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
discoverableList,
plot=True):
"""
*Given the observe frame lightcurve, determine if the SNe are discoverable by the survey or not.*
**Key Arguments:*... | python | def determine_when_sne_are_ripe_for_discovery(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
discoverableList,
plot=True):
"""
*Given the observe frame lightcurve, determine if the SNe are discoverable by the survey or not.*
**Key Arguments:*... | [
"def",
"determine_when_sne_are_ripe_for_discovery",
"(",
"log",
",",
"redshiftArray",
",",
"limitingMags",
",",
"observedFrameLightCurveInfo",
",",
"discoverableList",
",",
"plot",
"=",
"True",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"im... | *Given the observe frame lightcurve, determine if the SNe are discoverable by the survey or not.*
**Key Arguments:**
- ``log`` -- logger
- ``redshiftArray`` -- the array of random redshifts
- ``observedFrameLightCurveInfo`` -- the observed franme lightcurve info (dictionary)
- ``dis... | [
"*",
"Given",
"the",
"observe",
"frame",
"lightcurve",
"determine",
"if",
"the",
"SNe",
"are",
"discoverable",
"by",
"the",
"survey",
"or",
"not",
".",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/surveysim.py#L268-L352 |
thespacedoctor/qubits | qubits/surveysim.py | determine_when_discovered_sne_disappear | def determine_when_discovered_sne_disappear(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
ripeDayList,
plot=True):
"""
*Given the observed frame lightcurve, determine when the discovered SNe become too faint to be detected.*
**Key Arguments:... | python | def determine_when_discovered_sne_disappear(
log,
redshiftArray,
limitingMags,
observedFrameLightCurveInfo,
ripeDayList,
plot=True):
"""
*Given the observed frame lightcurve, determine when the discovered SNe become too faint to be detected.*
**Key Arguments:... | [
"def",
"determine_when_discovered_sne_disappear",
"(",
"log",
",",
"redshiftArray",
",",
"limitingMags",
",",
"observedFrameLightCurveInfo",
",",
"ripeDayList",
",",
"plot",
"=",
"True",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"import",
... | *Given the observed frame lightcurve, determine when the discovered SNe become too faint to be detected.*
**Key Arguments:**
- ``log`` -- logger
- ``redshiftArray`` -- the array of random redshifts
- ``observedFrameLightCurveInfo`` -- the observed franme lightcurve info (dictionary)
... | [
"*",
"Given",
"the",
"observed",
"frame",
"lightcurve",
"determine",
"when",
"the",
"discovered",
"SNe",
"become",
"too",
"faint",
"to",
"be",
"detected",
".",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/surveysim.py#L358-L449 |
thespacedoctor/qubits | qubits/surveysim.py | determine_if_sne_are_discovered | def determine_if_sne_are_discovered(
log,
limitingMags,
ripeDayList,
cadenceDictionary,
observedFrameLightCurveInfo,
extraSurveyConstraints,
plot=True):
"""
*Generate a list of dictionaries which describe if and when a SN is discovered in each and any filt... | python | def determine_if_sne_are_discovered(
log,
limitingMags,
ripeDayList,
cadenceDictionary,
observedFrameLightCurveInfo,
extraSurveyConstraints,
plot=True):
"""
*Generate a list of dictionaries which describe if and when a SN is discovered in each and any filt... | [
"def",
"determine_if_sne_are_discovered",
"(",
"log",
",",
"limitingMags",
",",
"ripeDayList",
",",
"cadenceDictionary",
",",
"observedFrameLightCurveInfo",
",",
"extraSurveyConstraints",
",",
"plot",
"=",
"True",
")",
":",
"################ > IMPORTS ################",
"##... | *Generate a list of dictionaries which describe if and when a SN is discovered in each and any filter.*
**Key Arguments:**
- ``log`` -- logger
- ``limitingMags`` -- the limiting magnitudes of the survey
- ``ripeDayList`` -- a list of dictionaries describing the time relative to peak that th... | [
"*",
"Generate",
"a",
"list",
"of",
"dictionaries",
"which",
"describe",
"if",
"and",
"when",
"a",
"SN",
"is",
"discovered",
"in",
"each",
"and",
"any",
"filter",
".",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/surveysim.py#L455-L587 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.