id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
242,900
|
AliGhahraei/verarandom
|
verarandom/_build_utils.py
|
_set_module_names_for_sphinx
|
def _set_module_names_for_sphinx(modules: List, new_name: str):
""" Trick sphinx into displaying the desired module in these objects' documentation. """
for obj in modules:
obj.__module__ = new_name
|
python
|
def _set_module_names_for_sphinx(modules: List, new_name: str):
""" Trick sphinx into displaying the desired module in these objects' documentation. """
for obj in modules:
obj.__module__ = new_name
|
[
"def",
"_set_module_names_for_sphinx",
"(",
"modules",
":",
"List",
",",
"new_name",
":",
"str",
")",
":",
"for",
"obj",
"in",
"modules",
":",
"obj",
".",
"__module__",
"=",
"new_name"
] |
Trick sphinx into displaying the desired module in these objects' documentation.
|
[
"Trick",
"sphinx",
"into",
"displaying",
"the",
"desired",
"module",
"in",
"these",
"objects",
"documentation",
"."
] |
63d9a5bd2776e40368933f54e58c3f4b4f333f03
|
https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_build_utils.py#L4-L7
|
242,901
|
Archived-Object/ligament
|
ligament/ligament.py
|
run_skeleton
|
def run_skeleton(skeleton_path, tasks, watch=True):
"""loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should be watched for changes and
automatically updated
"""
build_context = load_context_from_skeleton(skeleton_path);
# for t in build_context.tasks:
# print t, str(build_context.tasks[t])
for task in tasks:
build_context.build_task(task)
# print json.dumps(
# dict((name,
# str(task.value)[0:100] + "..."
# if 100 < len(str(task.value))
# else str(task.value))
# for name, task in build_context.tasks.iteritems()),
# indent=2)
if watch:
print
print "resolving watch targets"
# establish watchers
observer = Observer()
buildcontexteventhandler = BuildContextFsEventHandler(build_context)
built_tasks = ((taskname, task)
for taskname, task in build_context.tasks.iteritems()
if task.last_build_time > 0)
for taskname, task in built_tasks:
for f in task.task.file_watch_targets:
if os.path.isdir(f):
print "%s: watching %s" % (taskname, f)
observer.schedule(
buildcontexteventhandler,
f,
recursive=True)
else:
print "%s: watching %s for %s" % (taskname, os.path.dirname(f),
os.path.basename(f))
dirname = os.path.dirname(f)
observer.schedule(
buildcontexteventhandler,
dirname if dirname != "" else ".",
recursive=True)
print
print "watching for changes"
observer.start()
try:
while True:
sleep(0.5)
except KeyboardInterrupt:
observer.stop()
observer.join()
|
python
|
def run_skeleton(skeleton_path, tasks, watch=True):
"""loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should be watched for changes and
automatically updated
"""
build_context = load_context_from_skeleton(skeleton_path);
# for t in build_context.tasks:
# print t, str(build_context.tasks[t])
for task in tasks:
build_context.build_task(task)
# print json.dumps(
# dict((name,
# str(task.value)[0:100] + "..."
# if 100 < len(str(task.value))
# else str(task.value))
# for name, task in build_context.tasks.iteritems()),
# indent=2)
if watch:
print
print "resolving watch targets"
# establish watchers
observer = Observer()
buildcontexteventhandler = BuildContextFsEventHandler(build_context)
built_tasks = ((taskname, task)
for taskname, task in build_context.tasks.iteritems()
if task.last_build_time > 0)
for taskname, task in built_tasks:
for f in task.task.file_watch_targets:
if os.path.isdir(f):
print "%s: watching %s" % (taskname, f)
observer.schedule(
buildcontexteventhandler,
f,
recursive=True)
else:
print "%s: watching %s for %s" % (taskname, os.path.dirname(f),
os.path.basename(f))
dirname = os.path.dirname(f)
observer.schedule(
buildcontexteventhandler,
dirname if dirname != "" else ".",
recursive=True)
print
print "watching for changes"
observer.start()
try:
while True:
sleep(0.5)
except KeyboardInterrupt:
observer.stop()
observer.join()
|
[
"def",
"run_skeleton",
"(",
"skeleton_path",
",",
"tasks",
",",
"watch",
"=",
"True",
")",
":",
"build_context",
"=",
"load_context_from_skeleton",
"(",
"skeleton_path",
")",
"# for t in build_context.tasks:",
"# print t, str(build_context.tasks[t])",
"for",
"task",
"in",
"tasks",
":",
"build_context",
".",
"build_task",
"(",
"task",
")",
"# print json.dumps(",
"# dict((name,",
"# str(task.value)[0:100] + \"...\"",
"# if 100 < len(str(task.value))",
"# else str(task.value))",
"# for name, task in build_context.tasks.iteritems()),",
"# indent=2)",
"if",
"watch",
":",
"print",
"print",
"\"resolving watch targets\"",
"# establish watchers",
"observer",
"=",
"Observer",
"(",
")",
"buildcontexteventhandler",
"=",
"BuildContextFsEventHandler",
"(",
"build_context",
")",
"built_tasks",
"=",
"(",
"(",
"taskname",
",",
"task",
")",
"for",
"taskname",
",",
"task",
"in",
"build_context",
".",
"tasks",
".",
"iteritems",
"(",
")",
"if",
"task",
".",
"last_build_time",
">",
"0",
")",
"for",
"taskname",
",",
"task",
"in",
"built_tasks",
":",
"for",
"f",
"in",
"task",
".",
"task",
".",
"file_watch_targets",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"print",
"\"%s: watching %s\"",
"%",
"(",
"taskname",
",",
"f",
")",
"observer",
".",
"schedule",
"(",
"buildcontexteventhandler",
",",
"f",
",",
"recursive",
"=",
"True",
")",
"else",
":",
"print",
"\"%s: watching %s for %s\"",
"%",
"(",
"taskname",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
"observer",
".",
"schedule",
"(",
"buildcontexteventhandler",
",",
"dirname",
"if",
"dirname",
"!=",
"\"\"",
"else",
"\".\"",
",",
"recursive",
"=",
"True",
")",
"print",
"print",
"\"watching for changes\"",
"observer",
".",
"start",
"(",
")",
"try",
":",
"while",
"True",
":",
"sleep",
"(",
"0.5",
")",
"except",
"KeyboardInterrupt",
":",
"observer",
".",
"stop",
"(",
")",
"observer",
".",
"join",
"(",
")"
] |
loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should be watched for changes and
automatically updated
|
[
"loads",
"and",
"executes",
"tasks",
"from",
"a",
"given",
"skeleton",
"file"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/ligament.py#L50-L118
|
242,902
|
tBaxter/tango-shared-core
|
build/lib/tango_shared/templatetags/tango_site_tags.py
|
get_fresh_content
|
def get_fresh_content(top=4, additional=10, featured=False):
"""
Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned is defined when the tag is called.
The top item type is defined in the sites admin for sites that
have the supersites app enabled.
If "featured" is True, will limit to only featured content.
Usage::
{% get_fresh_content 5 10 %}
Would return five top objects and 10 additional
{% get_fresh_content 4 8 featured %}
Would return four top objects and 8 additional, limited to featured content.
What you get::
'top_item': the top featured item
'top_item_type': the content type for the top item (article, gallery, video)
'featured': Additional featured items.
If you asked for 5 featureed items,
there will be four -- five minus the one that's in `top_item`.
'articles': featured articles, minus the top item
'galleries': featured galleries, minus the top item
'vids': featured video, minus the top item,
'more_articles': A stack of articles, excluding what's in featured,
sliced to the number passed for <num_regular>,
'more_galleries': A stack of galleries, excluding what's in featured,
sliced to the number passed for <num_regular>,
'additional': A mixed list of articles and galleries, excluding what's in featured,
sliced to the number passed for <num_regular>,
"""
from articles.models import Article
from photos.models import Gallery
from video.models import Video
articles = Article.published.only('title', 'summary', 'slug', 'created')
galleries = Gallery.published.only('title', 'summary', 'slug', 'created')
videos = Video.published.only('title', 'summary', 'slug', 'created')
if featured:
articles = articles.filter(featured=True)
galleries = galleries.filter(featured=True)
videos = videos.filter(featured=True)
# now slice to maximum possible for each group
# and go ahead and make them lists for chaining
max_total = top + additional
articles = list(articles[:max_total])
galleries = list(galleries[:max_total])
videos = list(videos[:max_total])
# chain the lists now
content = chain(articles, galleries, videos)
content = sorted(content, key=lambda instance: instance.created)
content.reverse()
top_content = content[:top]
additional_content = content[top:max_total]
return {
'top_content': top_content,
'additional_content': additional_content,
'MEDIA_URL': settings.MEDIA_URL,
}
|
python
|
def get_fresh_content(top=4, additional=10, featured=False):
"""
Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned is defined when the tag is called.
The top item type is defined in the sites admin for sites that
have the supersites app enabled.
If "featured" is True, will limit to only featured content.
Usage::
{% get_fresh_content 5 10 %}
Would return five top objects and 10 additional
{% get_fresh_content 4 8 featured %}
Would return four top objects and 8 additional, limited to featured content.
What you get::
'top_item': the top featured item
'top_item_type': the content type for the top item (article, gallery, video)
'featured': Additional featured items.
If you asked for 5 featureed items,
there will be four -- five minus the one that's in `top_item`.
'articles': featured articles, minus the top item
'galleries': featured galleries, minus the top item
'vids': featured video, minus the top item,
'more_articles': A stack of articles, excluding what's in featured,
sliced to the number passed for <num_regular>,
'more_galleries': A stack of galleries, excluding what's in featured,
sliced to the number passed for <num_regular>,
'additional': A mixed list of articles and galleries, excluding what's in featured,
sliced to the number passed for <num_regular>,
"""
from articles.models import Article
from photos.models import Gallery
from video.models import Video
articles = Article.published.only('title', 'summary', 'slug', 'created')
galleries = Gallery.published.only('title', 'summary', 'slug', 'created')
videos = Video.published.only('title', 'summary', 'slug', 'created')
if featured:
articles = articles.filter(featured=True)
galleries = galleries.filter(featured=True)
videos = videos.filter(featured=True)
# now slice to maximum possible for each group
# and go ahead and make them lists for chaining
max_total = top + additional
articles = list(articles[:max_total])
galleries = list(galleries[:max_total])
videos = list(videos[:max_total])
# chain the lists now
content = chain(articles, galleries, videos)
content = sorted(content, key=lambda instance: instance.created)
content.reverse()
top_content = content[:top]
additional_content = content[top:max_total]
return {
'top_content': top_content,
'additional_content': additional_content,
'MEDIA_URL': settings.MEDIA_URL,
}
|
[
"def",
"get_fresh_content",
"(",
"top",
"=",
"4",
",",
"additional",
"=",
"10",
",",
"featured",
"=",
"False",
")",
":",
"from",
"articles",
".",
"models",
"import",
"Article",
"from",
"photos",
".",
"models",
"import",
"Gallery",
"from",
"video",
".",
"models",
"import",
"Video",
"articles",
"=",
"Article",
".",
"published",
".",
"only",
"(",
"'title'",
",",
"'summary'",
",",
"'slug'",
",",
"'created'",
")",
"galleries",
"=",
"Gallery",
".",
"published",
".",
"only",
"(",
"'title'",
",",
"'summary'",
",",
"'slug'",
",",
"'created'",
")",
"videos",
"=",
"Video",
".",
"published",
".",
"only",
"(",
"'title'",
",",
"'summary'",
",",
"'slug'",
",",
"'created'",
")",
"if",
"featured",
":",
"articles",
"=",
"articles",
".",
"filter",
"(",
"featured",
"=",
"True",
")",
"galleries",
"=",
"galleries",
".",
"filter",
"(",
"featured",
"=",
"True",
")",
"videos",
"=",
"videos",
".",
"filter",
"(",
"featured",
"=",
"True",
")",
"# now slice to maximum possible for each group",
"# and go ahead and make them lists for chaining",
"max_total",
"=",
"top",
"+",
"additional",
"articles",
"=",
"list",
"(",
"articles",
"[",
":",
"max_total",
"]",
")",
"galleries",
"=",
"list",
"(",
"galleries",
"[",
":",
"max_total",
"]",
")",
"videos",
"=",
"list",
"(",
"videos",
"[",
":",
"max_total",
"]",
")",
"# chain the lists now",
"content",
"=",
"chain",
"(",
"articles",
",",
"galleries",
",",
"videos",
")",
"content",
"=",
"sorted",
"(",
"content",
",",
"key",
"=",
"lambda",
"instance",
":",
"instance",
".",
"created",
")",
"content",
".",
"reverse",
"(",
")",
"top_content",
"=",
"content",
"[",
":",
"top",
"]",
"additional_content",
"=",
"content",
"[",
"top",
":",
"max_total",
"]",
"return",
"{",
"'top_content'",
":",
"top_content",
",",
"'additional_content'",
":",
"additional_content",
",",
"'MEDIA_URL'",
":",
"settings",
".",
"MEDIA_URL",
",",
"}"
] |
Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned is defined when the tag is called.
The top item type is defined in the sites admin for sites that
have the supersites app enabled.
If "featured" is True, will limit to only featured content.
Usage::
{% get_fresh_content 5 10 %}
Would return five top objects and 10 additional
{% get_fresh_content 4 8 featured %}
Would return four top objects and 8 additional, limited to featured content.
What you get::
'top_item': the top featured item
'top_item_type': the content type for the top item (article, gallery, video)
'featured': Additional featured items.
If you asked for 5 featureed items,
there will be four -- five minus the one that's in `top_item`.
'articles': featured articles, minus the top item
'galleries': featured galleries, minus the top item
'vids': featured video, minus the top item,
'more_articles': A stack of articles, excluding what's in featured,
sliced to the number passed for <num_regular>,
'more_galleries': A stack of galleries, excluding what's in featured,
sliced to the number passed for <num_regular>,
'additional': A mixed list of articles and galleries, excluding what's in featured,
sliced to the number passed for <num_regular>,
|
[
"Requires",
"articles",
"photos",
"and",
"video",
"packages",
"to",
"be",
"installed",
"."
] |
35fc10aef1ceedcdb4d6d866d44a22efff718812
|
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/tango_site_tags.py#L28-L101
|
242,903
|
tBaxter/tango-shared-core
|
build/lib/tango_shared/templatetags/tango_site_tags.py
|
markdown
|
def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Derived from django.contrib.markdown, which was deprecated from django.
ALWAYS CLEAN INPUT BEFORE TRUSTING IT.
Syntax::
{{ value|markdown:"extension1_name,extension2_name..." }}
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
If the version of Markdown in use does not support extensions,
they will be silently ignored.
"""
import warnings
warnings.warn('The markdown filter has been deprecated',
category=DeprecationWarning)
try:
import markdown
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'markdown' filter: The Python markdown library isn't installed."
)
return force_text(value)
else:
markdown_vers = getattr(markdown, "version_info", 0)
if markdown_vers < (2, 1):
if settings.DEBUG:
raise template.TemplateSyntaxError(
"""
Error in 'markdown' filter:
Django does not support versions of the Python markdown library < 2.1.
"""
)
return force_text(value)
else:
extensions = [e for e in arg.split(",") if e]
if extensions and extensions[0] == "safe":
extensions = extensions[1:]
return mark_safe(markdown.markdown(
force_text(value), extensions, safe_mode=True, enable_attributes=False))
else:
return mark_safe(markdown.markdown(
force_text(value), extensions, safe_mode=False))
|
python
|
def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Derived from django.contrib.markdown, which was deprecated from django.
ALWAYS CLEAN INPUT BEFORE TRUSTING IT.
Syntax::
{{ value|markdown:"extension1_name,extension2_name..." }}
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
If the version of Markdown in use does not support extensions,
they will be silently ignored.
"""
import warnings
warnings.warn('The markdown filter has been deprecated',
category=DeprecationWarning)
try:
import markdown
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'markdown' filter: The Python markdown library isn't installed."
)
return force_text(value)
else:
markdown_vers = getattr(markdown, "version_info", 0)
if markdown_vers < (2, 1):
if settings.DEBUG:
raise template.TemplateSyntaxError(
"""
Error in 'markdown' filter:
Django does not support versions of the Python markdown library < 2.1.
"""
)
return force_text(value)
else:
extensions = [e for e in arg.split(",") if e]
if extensions and extensions[0] == "safe":
extensions = extensions[1:]
return mark_safe(markdown.markdown(
force_text(value), extensions, safe_mode=True, enable_attributes=False))
else:
return mark_safe(markdown.markdown(
force_text(value), extensions, safe_mode=False))
|
[
"def",
"markdown",
"(",
"value",
",",
"arg",
"=",
"''",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'The markdown filter has been deprecated'",
",",
"category",
"=",
"DeprecationWarning",
")",
"try",
":",
"import",
"markdown",
"except",
"ImportError",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"Error in 'markdown' filter: The Python markdown library isn't installed.\"",
")",
"return",
"force_text",
"(",
"value",
")",
"else",
":",
"markdown_vers",
"=",
"getattr",
"(",
"markdown",
",",
"\"version_info\"",
",",
"0",
")",
"if",
"markdown_vers",
"<",
"(",
"2",
",",
"1",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"\"\"\n Error in 'markdown' filter:\n Django does not support versions of the Python markdown library < 2.1.\n \"\"\"",
")",
"return",
"force_text",
"(",
"value",
")",
"else",
":",
"extensions",
"=",
"[",
"e",
"for",
"e",
"in",
"arg",
".",
"split",
"(",
"\",\"",
")",
"if",
"e",
"]",
"if",
"extensions",
"and",
"extensions",
"[",
"0",
"]",
"==",
"\"safe\"",
":",
"extensions",
"=",
"extensions",
"[",
"1",
":",
"]",
"return",
"mark_safe",
"(",
"markdown",
".",
"markdown",
"(",
"force_text",
"(",
"value",
")",
",",
"extensions",
",",
"safe_mode",
"=",
"True",
",",
"enable_attributes",
"=",
"False",
")",
")",
"else",
":",
"return",
"mark_safe",
"(",
"markdown",
".",
"markdown",
"(",
"force_text",
"(",
"value",
")",
",",
"extensions",
",",
"safe_mode",
"=",
"False",
")",
")"
] |
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Derived from django.contrib.markdown, which was deprecated from django.
ALWAYS CLEAN INPUT BEFORE TRUSTING IT.
Syntax::
{{ value|markdown:"extension1_name,extension2_name..." }}
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
If the version of Markdown in use does not support extensions,
they will be silently ignored.
|
[
"Runs",
"Markdown",
"over",
"a",
"given",
"value",
"optionally",
"using",
"various",
"extensions",
"python",
"-",
"markdown",
"supports",
"."
] |
35fc10aef1ceedcdb4d6d866d44a22efff718812
|
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/tango_site_tags.py#L105-L156
|
242,904
|
bretth/djset
|
djset/backends.py
|
UnencryptedKeyring.file_path
|
def file_path(self):
"""
The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level.
"""
return os.path.join(keyring.util.platform.data_root(), self.filename)
|
python
|
def file_path(self):
"""
The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level.
"""
return os.path.join(keyring.util.platform.data_root(), self.filename)
|
[
"def",
"file_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"keyring",
".",
"util",
".",
"platform",
".",
"data_root",
"(",
")",
",",
"self",
".",
"filename",
")"
] |
The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level.
|
[
"The",
"path",
"to",
"the",
"file",
"where",
"passwords",
"are",
"stored",
".",
"This",
"property",
"may",
"be",
"overridden",
"by",
"the",
"subclass",
"or",
"at",
"the",
"instance",
"level",
"."
] |
e04cbcadc311f6edec50a718415d0004aa304034
|
https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/backends.py#L20-L25
|
242,905
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.account
|
def account(self, account=None):
''' Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
'''
for num_of_retries in range(default.max_retry):
if account is None:
account = self.mainaccount
if account == self.checkedaccount:
return self.accountinfo
self.checkedaccount = account
try:
self.accountinfo = self.steem_instance().get_account(account)
except Exception as e:
self.util.retry(("COULD NOT GET ACCOUNT INFO FOR " + str(account)),
e, num_of_retries, default.wait_time)
self.s = None
else:
if self.accountinfo is None:
self.msg.error_message("COULD NOT FIND ACCOUNT: " + str(account))
return False
else:
return self.accountinfo
|
python
|
def account(self, account=None):
''' Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
'''
for num_of_retries in range(default.max_retry):
if account is None:
account = self.mainaccount
if account == self.checkedaccount:
return self.accountinfo
self.checkedaccount = account
try:
self.accountinfo = self.steem_instance().get_account(account)
except Exception as e:
self.util.retry(("COULD NOT GET ACCOUNT INFO FOR " + str(account)),
e, num_of_retries, default.wait_time)
self.s = None
else:
if self.accountinfo is None:
self.msg.error_message("COULD NOT FIND ACCOUNT: " + str(account))
return False
else:
return self.accountinfo
|
[
"def",
"account",
"(",
"self",
",",
"account",
"=",
"None",
")",
":",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"if",
"account",
"is",
"None",
":",
"account",
"=",
"self",
".",
"mainaccount",
"if",
"account",
"==",
"self",
".",
"checkedaccount",
":",
"return",
"self",
".",
"accountinfo",
"self",
".",
"checkedaccount",
"=",
"account",
"try",
":",
"self",
".",
"accountinfo",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_account",
"(",
"account",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"util",
".",
"retry",
"(",
"(",
"\"COULD NOT GET ACCOUNT INFO FOR \"",
"+",
"str",
"(",
"account",
")",
")",
",",
"e",
",",
"num_of_retries",
",",
"default",
".",
"wait_time",
")",
"self",
".",
"s",
"=",
"None",
"else",
":",
"if",
"self",
".",
"accountinfo",
"is",
"None",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT FIND ACCOUNT: \"",
"+",
"str",
"(",
"account",
")",
")",
"return",
"False",
"else",
":",
"return",
"self",
".",
"accountinfo"
] |
Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
|
[
"Fetches",
"account",
"information",
"and",
"stores",
"the",
"result",
"in",
"a",
"class",
"variable",
".",
"Returns",
"that",
"variable",
"if",
"the",
"account",
"has",
"not",
"changed",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L92-L114
|
242,906
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.steem_instance
|
def steem_instance(self):
''' Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
'''
if self.s:
return self.s
for num_of_retries in range(default.max_retry):
node = self.util.goodnode(self.nodes)
try:
self.s = Steem(keys=self.keys,
nodes=[node])
except Exception as e:
self.util.retry("COULD NOT GET STEEM INSTANCE",
e, num_of_retries, default.wait_time)
self.s = None
else:
return self.s
return False
|
python
|
def steem_instance(self):
''' Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
'''
if self.s:
return self.s
for num_of_retries in range(default.max_retry):
node = self.util.goodnode(self.nodes)
try:
self.s = Steem(keys=self.keys,
nodes=[node])
except Exception as e:
self.util.retry("COULD NOT GET STEEM INSTANCE",
e, num_of_retries, default.wait_time)
self.s = None
else:
return self.s
return False
|
[
"def",
"steem_instance",
"(",
"self",
")",
":",
"if",
"self",
".",
"s",
":",
"return",
"self",
".",
"s",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"node",
"=",
"self",
".",
"util",
".",
"goodnode",
"(",
"self",
".",
"nodes",
")",
"try",
":",
"self",
".",
"s",
"=",
"Steem",
"(",
"keys",
"=",
"self",
".",
"keys",
",",
"nodes",
"=",
"[",
"node",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"util",
".",
"retry",
"(",
"\"COULD NOT GET STEEM INSTANCE\"",
",",
"e",
",",
"num_of_retries",
",",
"default",
".",
"wait_time",
")",
"self",
".",
"s",
"=",
"None",
"else",
":",
"return",
"self",
".",
"s",
"return",
"False"
] |
Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
|
[
"Returns",
"the",
"steem",
"instance",
"if",
"it",
"already",
"exists",
"otherwise",
"uses",
"the",
"goodnode",
"method",
"to",
"fetch",
"a",
"node",
"and",
"instantiate",
"the",
"Steem",
"class",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L117-L135
|
242,907
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.verify_key
|
def verify_key (self, acctname=None, tokenkey=None):
''' This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token.
'''
if (re.match( r'^[A-Za-z0-9]+$', tokenkey)
and tokenkey is not None
and len(tokenkey) <= 64
and len(tokenkey) >= 16):
pubkey = PrivateKey(tokenkey).pubkey or 0
pubkey2 = self.account(acctname)
if (str(pubkey)
== str(pubkey2['posting']['key_auths'][0][0])):
self.privatekey = tokenkey
self.refreshtoken = None
self.accesstoken = None
return True
else:
return False
elif (re.match( r'^[A-Za-z0-9\-\_\.]+$', tokenkey)
and tokenkey is not None
and len(tokenkey) > 64):
self.privatekey = None
self.accesstoken = self.connect.get_token(tokenkey)
if self.accesstoken:
self.username = self.connect.username
self.refreshtoken = self.connect.refresh_token
return True
else:
return False
else:
return False
|
python
|
def verify_key (self, acctname=None, tokenkey=None):
''' This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token.
'''
if (re.match( r'^[A-Za-z0-9]+$', tokenkey)
and tokenkey is not None
and len(tokenkey) <= 64
and len(tokenkey) >= 16):
pubkey = PrivateKey(tokenkey).pubkey or 0
pubkey2 = self.account(acctname)
if (str(pubkey)
== str(pubkey2['posting']['key_auths'][0][0])):
self.privatekey = tokenkey
self.refreshtoken = None
self.accesstoken = None
return True
else:
return False
elif (re.match( r'^[A-Za-z0-9\-\_\.]+$', tokenkey)
and tokenkey is not None
and len(tokenkey) > 64):
self.privatekey = None
self.accesstoken = self.connect.get_token(tokenkey)
if self.accesstoken:
self.username = self.connect.username
self.refreshtoken = self.connect.refresh_token
return True
else:
return False
else:
return False
|
[
"def",
"verify_key",
"(",
"self",
",",
"acctname",
"=",
"None",
",",
"tokenkey",
"=",
"None",
")",
":",
"if",
"(",
"re",
".",
"match",
"(",
"r'^[A-Za-z0-9]+$'",
",",
"tokenkey",
")",
"and",
"tokenkey",
"is",
"not",
"None",
"and",
"len",
"(",
"tokenkey",
")",
"<=",
"64",
"and",
"len",
"(",
"tokenkey",
")",
">=",
"16",
")",
":",
"pubkey",
"=",
"PrivateKey",
"(",
"tokenkey",
")",
".",
"pubkey",
"or",
"0",
"pubkey2",
"=",
"self",
".",
"account",
"(",
"acctname",
")",
"if",
"(",
"str",
"(",
"pubkey",
")",
"==",
"str",
"(",
"pubkey2",
"[",
"'posting'",
"]",
"[",
"'key_auths'",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
":",
"self",
".",
"privatekey",
"=",
"tokenkey",
"self",
".",
"refreshtoken",
"=",
"None",
"self",
".",
"accesstoken",
"=",
"None",
"return",
"True",
"else",
":",
"return",
"False",
"elif",
"(",
"re",
".",
"match",
"(",
"r'^[A-Za-z0-9\\-\\_\\.]+$'",
",",
"tokenkey",
")",
"and",
"tokenkey",
"is",
"not",
"None",
"and",
"len",
"(",
"tokenkey",
")",
">",
"64",
")",
":",
"self",
".",
"privatekey",
"=",
"None",
"self",
".",
"accesstoken",
"=",
"self",
".",
"connect",
".",
"get_token",
"(",
"tokenkey",
")",
"if",
"self",
".",
"accesstoken",
":",
"self",
".",
"username",
"=",
"self",
".",
"connect",
".",
"username",
"self",
".",
"refreshtoken",
"=",
"self",
".",
"connect",
".",
"refresh_token",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"False"
] |
This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token.
|
[
"This",
"can",
"be",
"used",
"to",
"verify",
"either",
"a",
"private",
"posting",
"key",
"or",
"to",
"verify",
"a",
"steemconnect",
"refresh",
"token",
"and",
"retreive",
"the",
"access",
"token",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L147-L178
|
242,908
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.reward_pool_balances
|
def reward_pool_balances(self):
''' Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem.
'''
if self.reward_balance > 0:
return self.reward_balance
else:
reward_fund = self.steem_instance().get_reward_fund()
self.reward_balance = Amount(
reward_fund["reward_balance"]).amount
self.recent_claims = float(reward_fund["recent_claims"])
self.base = Amount(
self.steem_instance(
).get_current_median_history_price()["base"]
).amount
return [self.reward_balance, self.recent_claims, self.base]
|
python
|
def reward_pool_balances(self):
''' Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem.
'''
if self.reward_balance > 0:
return self.reward_balance
else:
reward_fund = self.steem_instance().get_reward_fund()
self.reward_balance = Amount(
reward_fund["reward_balance"]).amount
self.recent_claims = float(reward_fund["recent_claims"])
self.base = Amount(
self.steem_instance(
).get_current_median_history_price()["base"]
).amount
return [self.reward_balance, self.recent_claims, self.base]
|
[
"def",
"reward_pool_balances",
"(",
"self",
")",
":",
"if",
"self",
".",
"reward_balance",
">",
"0",
":",
"return",
"self",
".",
"reward_balance",
"else",
":",
"reward_fund",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_reward_fund",
"(",
")",
"self",
".",
"reward_balance",
"=",
"Amount",
"(",
"reward_fund",
"[",
"\"reward_balance\"",
"]",
")",
".",
"amount",
"self",
".",
"recent_claims",
"=",
"float",
"(",
"reward_fund",
"[",
"\"recent_claims\"",
"]",
")",
"self",
".",
"base",
"=",
"Amount",
"(",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_current_median_history_price",
"(",
")",
"[",
"\"base\"",
"]",
")",
".",
"amount",
"return",
"[",
"self",
".",
"reward_balance",
",",
"self",
".",
"recent_claims",
",",
"self",
".",
"base",
"]"
] |
Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem.
|
[
"Fetches",
"and",
"returns",
"the",
"3",
"values",
"needed",
"to",
"calculate",
"the",
"reward",
"pool",
"and",
"other",
"associated",
"values",
"such",
"as",
"rshares",
".",
"Returns",
"the",
"reward",
"balance",
"all",
"recent",
"claims",
"and",
"the",
"current",
"price",
"of",
"steem",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L181-L199
|
242,909
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.rshares_to_steem
|
def rshares_to_steem (self, rshares):
''' Gets the reward pool balances
then calculates rshares to steem
'''
self.reward_pool_balances()
return round(
rshares
* self.reward_balance
/ self.recent_claims
* self.base, 4)
|
python
|
def rshares_to_steem (self, rshares):
''' Gets the reward pool balances
then calculates rshares to steem
'''
self.reward_pool_balances()
return round(
rshares
* self.reward_balance
/ self.recent_claims
* self.base, 4)
|
[
"def",
"rshares_to_steem",
"(",
"self",
",",
"rshares",
")",
":",
"self",
".",
"reward_pool_balances",
"(",
")",
"return",
"round",
"(",
"rshares",
"*",
"self",
".",
"reward_balance",
"/",
"self",
".",
"recent_claims",
"*",
"self",
".",
"base",
",",
"4",
")"
] |
Gets the reward pool balances
then calculates rshares to steem
|
[
"Gets",
"the",
"reward",
"pool",
"balances",
"then",
"calculates",
"rshares",
"to",
"steem"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L202-L211
|
242,910
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.global_props
|
def global_props(self):
''' Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains
steem_instance, so to to preserve heirarchy
and to avoid "spaghetti code", this method
exists in this class.
'''
if self.util.info is None:
self.util.info = self.steem_instance().get_dynamic_global_properties()
self.util.total_vesting_fund_steem = Amount(self.util.info["total_vesting_fund_steem"]).amount
self.util.total_vesting_shares = Amount(self.util.info["total_vesting_shares"]).amount
self.util.vote_power_reserve_rate = self.util.info["vote_power_reserve_rate"]
return self.util.info
|
python
|
def global_props(self):
''' Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains
steem_instance, so to to preserve heirarchy
and to avoid "spaghetti code", this method
exists in this class.
'''
if self.util.info is None:
self.util.info = self.steem_instance().get_dynamic_global_properties()
self.util.total_vesting_fund_steem = Amount(self.util.info["total_vesting_fund_steem"]).amount
self.util.total_vesting_shares = Amount(self.util.info["total_vesting_shares"]).amount
self.util.vote_power_reserve_rate = self.util.info["vote_power_reserve_rate"]
return self.util.info
|
[
"def",
"global_props",
"(",
"self",
")",
":",
"if",
"self",
".",
"util",
".",
"info",
"is",
"None",
":",
"self",
".",
"util",
".",
"info",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_dynamic_global_properties",
"(",
")",
"self",
".",
"util",
".",
"total_vesting_fund_steem",
"=",
"Amount",
"(",
"self",
".",
"util",
".",
"info",
"[",
"\"total_vesting_fund_steem\"",
"]",
")",
".",
"amount",
"self",
".",
"util",
".",
"total_vesting_shares",
"=",
"Amount",
"(",
"self",
".",
"util",
".",
"info",
"[",
"\"total_vesting_shares\"",
"]",
")",
".",
"amount",
"self",
".",
"util",
".",
"vote_power_reserve_rate",
"=",
"self",
".",
"util",
".",
"info",
"[",
"\"vote_power_reserve_rate\"",
"]",
"return",
"self",
".",
"util",
".",
"info"
] |
Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains
steem_instance, so to to preserve heirarchy
and to avoid "spaghetti code", this method
exists in this class.
|
[
"Retrieves",
"the",
"global",
"properties",
"used",
"to",
"determine",
"rates",
"used",
"for",
"calculations",
"in",
"converting",
"steempower",
"to",
"vests",
"etc",
".",
"Stores",
"these",
"in",
"the",
"Utilities",
"class",
"as",
"that",
"is",
"where",
"the",
"conversions",
"take",
"place",
"however",
"SimpleSteem",
"is",
"the",
"class",
"that",
"contains",
"steem_instance",
"so",
"to",
"to",
"preserve",
"heirarchy",
"and",
"to",
"avoid",
"spaghetti",
"code",
"this",
"method",
"exists",
"in",
"this",
"class",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L214-L230
|
242,911
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.current_vote_value
|
def current_vote_value(self, **kwargs):
''' Ensures the needed variables are
created and set to defaults although
a variable number of variables are given.
'''
try:
kwargs.items()
except:
pass
else:
for key, value in kwargs.items():
setattr(self, key, value)
try:
self.lastvotetime
except:
self.lastvotetime=None
try:
self.steempower
except:
self.steempower=0
try:
self.voteweight
except:
self.voteweight=100
try:
self.votepoweroverride
except:
self.votepoweroverride=0
try:
self.accountname
except:
self.accountname=None
if self.accountname is None:
self.accountname = self.mainaccount
if self.check_balances(self.accountname) is not False:
if self.voteweight > 0 and self.voteweight < 101:
self.voteweight = self.util.scale_vote(self.voteweight)
if self.votepoweroverride > 0 and self.votepoweroverride < 101:
self.votepoweroverride = self.util.scale_vote(self.votepoweroverride)
else:
self.votepoweroverride = (self.votepower
+ self.util.calc_regenerated(
self.lastvotetime))
self.vpow = round(self.votepoweroverride / 100, 2)
self.global_props()
self.rshares = self.util.sp_to_rshares(self.steempower,
self.votepoweroverride,
self.voteweight)
self.votevalue = self.rshares_to_steem(self.rshares)
return self.votevalue
return None
|
python
|
def current_vote_value(self, **kwargs):
''' Ensures the needed variables are
created and set to defaults although
a variable number of variables are given.
'''
try:
kwargs.items()
except:
pass
else:
for key, value in kwargs.items():
setattr(self, key, value)
try:
self.lastvotetime
except:
self.lastvotetime=None
try:
self.steempower
except:
self.steempower=0
try:
self.voteweight
except:
self.voteweight=100
try:
self.votepoweroverride
except:
self.votepoweroverride=0
try:
self.accountname
except:
self.accountname=None
if self.accountname is None:
self.accountname = self.mainaccount
if self.check_balances(self.accountname) is not False:
if self.voteweight > 0 and self.voteweight < 101:
self.voteweight = self.util.scale_vote(self.voteweight)
if self.votepoweroverride > 0 and self.votepoweroverride < 101:
self.votepoweroverride = self.util.scale_vote(self.votepoweroverride)
else:
self.votepoweroverride = (self.votepower
+ self.util.calc_regenerated(
self.lastvotetime))
self.vpow = round(self.votepoweroverride / 100, 2)
self.global_props()
self.rshares = self.util.sp_to_rshares(self.steempower,
self.votepoweroverride,
self.voteweight)
self.votevalue = self.rshares_to_steem(self.rshares)
return self.votevalue
return None
|
[
"def",
"current_vote_value",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"kwargs",
".",
"items",
"(",
")",
"except",
":",
"pass",
"else",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"value",
")",
"try",
":",
"self",
".",
"lastvotetime",
"except",
":",
"self",
".",
"lastvotetime",
"=",
"None",
"try",
":",
"self",
".",
"steempower",
"except",
":",
"self",
".",
"steempower",
"=",
"0",
"try",
":",
"self",
".",
"voteweight",
"except",
":",
"self",
".",
"voteweight",
"=",
"100",
"try",
":",
"self",
".",
"votepoweroverride",
"except",
":",
"self",
".",
"votepoweroverride",
"=",
"0",
"try",
":",
"self",
".",
"accountname",
"except",
":",
"self",
".",
"accountname",
"=",
"None",
"if",
"self",
".",
"accountname",
"is",
"None",
":",
"self",
".",
"accountname",
"=",
"self",
".",
"mainaccount",
"if",
"self",
".",
"check_balances",
"(",
"self",
".",
"accountname",
")",
"is",
"not",
"False",
":",
"if",
"self",
".",
"voteweight",
">",
"0",
"and",
"self",
".",
"voteweight",
"<",
"101",
":",
"self",
".",
"voteweight",
"=",
"self",
".",
"util",
".",
"scale_vote",
"(",
"self",
".",
"voteweight",
")",
"if",
"self",
".",
"votepoweroverride",
">",
"0",
"and",
"self",
".",
"votepoweroverride",
"<",
"101",
":",
"self",
".",
"votepoweroverride",
"=",
"self",
".",
"util",
".",
"scale_vote",
"(",
"self",
".",
"votepoweroverride",
")",
"else",
":",
"self",
".",
"votepoweroverride",
"=",
"(",
"self",
".",
"votepower",
"+",
"self",
".",
"util",
".",
"calc_regenerated",
"(",
"self",
".",
"lastvotetime",
")",
")",
"self",
".",
"vpow",
"=",
"round",
"(",
"self",
".",
"votepoweroverride",
"/",
"100",
",",
"2",
")",
"self",
".",
"global_props",
"(",
")",
"self",
".",
"rshares",
"=",
"self",
".",
"util",
".",
"sp_to_rshares",
"(",
"self",
".",
"steempower",
",",
"self",
".",
"votepoweroverride",
",",
"self",
".",
"voteweight",
")",
"self",
".",
"votevalue",
"=",
"self",
".",
"rshares_to_steem",
"(",
"self",
".",
"rshares",
")",
"return",
"self",
".",
"votevalue",
"return",
"None"
] |
Ensures the needed variables are
created and set to defaults although
a variable number of variables are given.
|
[
"Ensures",
"the",
"needed",
"variables",
"are",
"created",
"and",
"set",
"to",
"defaults",
"although",
"a",
"variable",
"number",
"of",
"variables",
"are",
"given",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L233-L283
|
242,912
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.check_balances
|
def check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
if a is not False and a is not None:
self.sbdbal = Amount(a['sbd_balance']).amount
self.steembal = Amount(a['balance']).amount
self.votepower = a['voting_power']
self.lastvotetime = a['last_vote_time']
vs = Amount(a['vesting_shares']).amount
dvests = Amount(a['delegated_vesting_shares']).amount
rvests = Amount(a['received_vesting_shares']).amount
vests = (float(vs) - float(dvests)) + float(rvests)
try:
self.global_props()
self.steempower_delegated = self.util.vests_to_sp(dvests)
self.steempower_raw = self.util.vests_to_sp(vs)
self.steempower = self.util.vests_to_sp(vests)
except Exception as e:
self.msg.error_message(e)
else:
return [self.sbdbal, self.steembal, self.steempower,
self.votepower, self.lastvotetime]
return False
|
python
|
def check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
if a is not False and a is not None:
self.sbdbal = Amount(a['sbd_balance']).amount
self.steembal = Amount(a['balance']).amount
self.votepower = a['voting_power']
self.lastvotetime = a['last_vote_time']
vs = Amount(a['vesting_shares']).amount
dvests = Amount(a['delegated_vesting_shares']).amount
rvests = Amount(a['received_vesting_shares']).amount
vests = (float(vs) - float(dvests)) + float(rvests)
try:
self.global_props()
self.steempower_delegated = self.util.vests_to_sp(dvests)
self.steempower_raw = self.util.vests_to_sp(vs)
self.steempower = self.util.vests_to_sp(vests)
except Exception as e:
self.msg.error_message(e)
else:
return [self.sbdbal, self.steembal, self.steempower,
self.votepower, self.lastvotetime]
return False
|
[
"def",
"check_balances",
"(",
"self",
",",
"account",
"=",
"None",
")",
":",
"a",
"=",
"self",
".",
"account",
"(",
"account",
")",
"if",
"a",
"is",
"not",
"False",
"and",
"a",
"is",
"not",
"None",
":",
"self",
".",
"sbdbal",
"=",
"Amount",
"(",
"a",
"[",
"'sbd_balance'",
"]",
")",
".",
"amount",
"self",
".",
"steembal",
"=",
"Amount",
"(",
"a",
"[",
"'balance'",
"]",
")",
".",
"amount",
"self",
".",
"votepower",
"=",
"a",
"[",
"'voting_power'",
"]",
"self",
".",
"lastvotetime",
"=",
"a",
"[",
"'last_vote_time'",
"]",
"vs",
"=",
"Amount",
"(",
"a",
"[",
"'vesting_shares'",
"]",
")",
".",
"amount",
"dvests",
"=",
"Amount",
"(",
"a",
"[",
"'delegated_vesting_shares'",
"]",
")",
".",
"amount",
"rvests",
"=",
"Amount",
"(",
"a",
"[",
"'received_vesting_shares'",
"]",
")",
".",
"amount",
"vests",
"=",
"(",
"float",
"(",
"vs",
")",
"-",
"float",
"(",
"dvests",
")",
")",
"+",
"float",
"(",
"rvests",
")",
"try",
":",
"self",
".",
"global_props",
"(",
")",
"self",
".",
"steempower_delegated",
"=",
"self",
".",
"util",
".",
"vests_to_sp",
"(",
"dvests",
")",
"self",
".",
"steempower_raw",
"=",
"self",
".",
"util",
".",
"vests_to_sp",
"(",
"vs",
")",
"self",
".",
"steempower",
"=",
"self",
".",
"util",
".",
"vests_to_sp",
"(",
"vests",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"e",
")",
"else",
":",
"return",
"[",
"self",
".",
"sbdbal",
",",
"self",
".",
"steembal",
",",
"self",
".",
"steempower",
",",
"self",
".",
"votepower",
",",
"self",
".",
"lastvotetime",
"]",
"return",
"False"
] |
Fetches an account balance and makes
necessary conversions
|
[
"Fetches",
"an",
"account",
"balance",
"and",
"makes",
"necessary",
"conversions"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L286-L310
|
242,913
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.transfer_funds
|
def transfer_funds(self, to, amount, denom, msg):
''' Transfer SBD or STEEM to the given account
'''
try:
self.steem_instance().commit.transfer(to,
float(amount), denom, msg, self.mainaccount)
except Exception as e:
self.msg.error_message(e)
return False
else:
return True
|
python
|
def transfer_funds(self, to, amount, denom, msg):
''' Transfer SBD or STEEM to the given account
'''
try:
self.steem_instance().commit.transfer(to,
float(amount), denom, msg, self.mainaccount)
except Exception as e:
self.msg.error_message(e)
return False
else:
return True
|
[
"def",
"transfer_funds",
"(",
"self",
",",
"to",
",",
"amount",
",",
"denom",
",",
"msg",
")",
":",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"commit",
".",
"transfer",
"(",
"to",
",",
"float",
"(",
"amount",
")",
",",
"denom",
",",
"msg",
",",
"self",
".",
"mainaccount",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"e",
")",
"return",
"False",
"else",
":",
"return",
"True"
] |
Transfer SBD or STEEM to the given account
|
[
"Transfer",
"SBD",
"or",
"STEEM",
"to",
"the",
"given",
"account"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L313-L323
|
242,914
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.get_my_history
|
def get_my_history(self, account=None, limit=10000):
''' Fetches the account history from
most recent back
'''
if not account:
account = self.mainaccount
try:
h = self.steem_instance().get_account_history(
account, -1, limit)
except Exception as e:
self.msg.error_message(e)
return False
else:
return h
|
python
|
def get_my_history(self, account=None, limit=10000):
''' Fetches the account history from
most recent back
'''
if not account:
account = self.mainaccount
try:
h = self.steem_instance().get_account_history(
account, -1, limit)
except Exception as e:
self.msg.error_message(e)
return False
else:
return h
|
[
"def",
"get_my_history",
"(",
"self",
",",
"account",
"=",
"None",
",",
"limit",
"=",
"10000",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"try",
":",
"h",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_account_history",
"(",
"account",
",",
"-",
"1",
",",
"limit",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"e",
")",
"return",
"False",
"else",
":",
"return",
"h"
] |
Fetches the account history from
most recent back
|
[
"Fetches",
"the",
"account",
"history",
"from",
"most",
"recent",
"back"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L326-L339
|
242,915
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.reply
|
def reply(self, permlink, msgbody):
''' Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
self.steem_instance().post("message",
msgbody,
self.mainaccount,
None,
permlink,
None, None, "",
None, None, False)
except Exception as e:
self.util.retry("COULD NOT REPLY TO " + permlink,
e, num_of_retries, default.wait_time)
self.s = None
else:
self.msg.message("Replied to " + permlink)
time.sleep(20)
return True
|
python
|
def reply(self, permlink, msgbody):
''' Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
self.steem_instance().post("message",
msgbody,
self.mainaccount,
None,
permlink,
None, None, "",
None, None, False)
except Exception as e:
self.util.retry("COULD NOT REPLY TO " + permlink,
e, num_of_retries, default.wait_time)
self.s = None
else:
self.msg.message("Replied to " + permlink)
time.sleep(20)
return True
|
[
"def",
"reply",
"(",
"self",
",",
"permlink",
",",
"msgbody",
")",
":",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"post",
"(",
"\"message\"",
",",
"msgbody",
",",
"self",
".",
"mainaccount",
",",
"None",
",",
"permlink",
",",
"None",
",",
"None",
",",
"\"\"",
",",
"None",
",",
"None",
",",
"False",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"util",
".",
"retry",
"(",
"\"COULD NOT REPLY TO \"",
"+",
"permlink",
",",
"e",
",",
"num_of_retries",
",",
"default",
".",
"wait_time",
")",
"self",
".",
"s",
"=",
"None",
"else",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"Replied to \"",
"+",
"permlink",
")",
"time",
".",
"sleep",
"(",
"20",
")",
"return",
"True"
] |
Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting.
|
[
"Used",
"for",
"creating",
"a",
"reply",
"to",
"a",
"post",
".",
"Waits",
"20",
"seconds",
"after",
"posting",
"as",
"that",
"is",
"the",
"required",
"amount",
"of",
"time",
"between",
"posting",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L377-L399
|
242,916
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.follow
|
def follow(self, author):
''' Follows the given account
'''
try:
self.steem_instance().commit.follow(author,
['blog'], self.mainaccount)
except Exception as e:
self.msg.error_message(e)
return False
else:
return True
|
python
|
def follow(self, author):
''' Follows the given account
'''
try:
self.steem_instance().commit.follow(author,
['blog'], self.mainaccount)
except Exception as e:
self.msg.error_message(e)
return False
else:
return True
|
[
"def",
"follow",
"(",
"self",
",",
"author",
")",
":",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"commit",
".",
"follow",
"(",
"author",
",",
"[",
"'blog'",
"]",
",",
"self",
".",
"mainaccount",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"e",
")",
"return",
"False",
"else",
":",
"return",
"True"
] |
Follows the given account
|
[
"Follows",
"the",
"given",
"account"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L402-L412
|
242,917
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.following
|
def following(self, account=None, limit=100):
''' Gets a list of all the followers
of a given account. If no account is given
the followers of the mainaccount are
returned.
'''
if not account:
account = self.mainaccount
followingnames = []
try:
self.followed = self.steem_instance().get_following(account,
'', 'blog', limit)
except Exception as e:
self.msg.error_message(e)
return False
else:
for a in self.followed:
followingnames.append(a['following'])
return followingnames
|
python
|
def following(self, account=None, limit=100):
''' Gets a list of all the followers
of a given account. If no account is given
the followers of the mainaccount are
returned.
'''
if not account:
account = self.mainaccount
followingnames = []
try:
self.followed = self.steem_instance().get_following(account,
'', 'blog', limit)
except Exception as e:
self.msg.error_message(e)
return False
else:
for a in self.followed:
followingnames.append(a['following'])
return followingnames
|
[
"def",
"following",
"(",
"self",
",",
"account",
"=",
"None",
",",
"limit",
"=",
"100",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"followingnames",
"=",
"[",
"]",
"try",
":",
"self",
".",
"followed",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_following",
"(",
"account",
",",
"''",
",",
"'blog'",
",",
"limit",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"e",
")",
"return",
"False",
"else",
":",
"for",
"a",
"in",
"self",
".",
"followed",
":",
"followingnames",
".",
"append",
"(",
"a",
"[",
"'following'",
"]",
")",
"return",
"followingnames"
] |
Gets a list of all the followers
of a given account. If no account is given
the followers of the mainaccount are
returned.
|
[
"Gets",
"a",
"list",
"of",
"all",
"the",
"followers",
"of",
"a",
"given",
"account",
".",
"If",
"no",
"account",
"is",
"given",
"the",
"followers",
"of",
"the",
"mainaccount",
"are",
"returned",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L428-L446
|
242,918
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.vote_history
|
def vote_history(self, permlink, author=None):
''' Returns the raw vote history of a
given post from a given account
'''
if author is None:
author = self.mainaccount
return self.steem_instance().get_active_votes(author, permlink)
|
python
|
def vote_history(self, permlink, author=None):
''' Returns the raw vote history of a
given post from a given account
'''
if author is None:
author = self.mainaccount
return self.steem_instance().get_active_votes(author, permlink)
|
[
"def",
"vote_history",
"(",
"self",
",",
"permlink",
",",
"author",
"=",
"None",
")",
":",
"if",
"author",
"is",
"None",
":",
"author",
"=",
"self",
".",
"mainaccount",
"return",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_active_votes",
"(",
"author",
",",
"permlink",
")"
] |
Returns the raw vote history of a
given post from a given account
|
[
"Returns",
"the",
"raw",
"vote",
"history",
"of",
"a",
"given",
"post",
"from",
"a",
"given",
"account"
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L487-L493
|
242,919
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.dex_ticker
|
def dex_ticker(self):
''' Simply grabs the ticker using the
steem_instance method and adds it
to a class variable.
'''
self.dex = Dex(self.steem_instance())
self.ticker = self.dex.get_ticker();
return self.ticker
|
python
|
def dex_ticker(self):
''' Simply grabs the ticker using the
steem_instance method and adds it
to a class variable.
'''
self.dex = Dex(self.steem_instance())
self.ticker = self.dex.get_ticker();
return self.ticker
|
[
"def",
"dex_ticker",
"(",
"self",
")",
":",
"self",
".",
"dex",
"=",
"Dex",
"(",
"self",
".",
"steem_instance",
"(",
")",
")",
"self",
".",
"ticker",
"=",
"self",
".",
"dex",
".",
"get_ticker",
"(",
")",
"return",
"self",
".",
"ticker"
] |
Simply grabs the ticker using the
steem_instance method and adds it
to a class variable.
|
[
"Simply",
"grabs",
"the",
"ticker",
"using",
"the",
"steem_instance",
"method",
"and",
"adds",
"it",
"to",
"a",
"class",
"variable",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L539-L546
|
242,920
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.steem_to_sbd
|
def steem_to_sbd(self, steemamt=0, price=0, account=None):
''' Uses the ticker to get the highest bid
and moves the steem at that price.
'''
if not account:
account = self.mainaccount
if self.check_balances(account):
if steemamt == 0:
steemamt = self.steembal
elif steemamt > self.steembal:
self.msg.error_message("INSUFFICIENT FUNDS. CURRENT STEEM BAL: "
+ str(self.steembal))
return False
if price == 0:
price = self.dex_ticker()['highest_bid']
try:
self.dex.sell(steemamt, "STEEM", price, account=account)
except Exception as e:
self.msg.error_message("COULD NOT SELL STEEM FOR SBD: " + str(e))
return False
else:
self.msg.message("TRANSFERED "
+ str(steemamt)
+ " STEEM TO SBD AT THE PRICE OF: $"
+ str(price))
return True
else:
return False
|
python
|
def steem_to_sbd(self, steemamt=0, price=0, account=None):
''' Uses the ticker to get the highest bid
and moves the steem at that price.
'''
if not account:
account = self.mainaccount
if self.check_balances(account):
if steemamt == 0:
steemamt = self.steembal
elif steemamt > self.steembal:
self.msg.error_message("INSUFFICIENT FUNDS. CURRENT STEEM BAL: "
+ str(self.steembal))
return False
if price == 0:
price = self.dex_ticker()['highest_bid']
try:
self.dex.sell(steemamt, "STEEM", price, account=account)
except Exception as e:
self.msg.error_message("COULD NOT SELL STEEM FOR SBD: " + str(e))
return False
else:
self.msg.message("TRANSFERED "
+ str(steemamt)
+ " STEEM TO SBD AT THE PRICE OF: $"
+ str(price))
return True
else:
return False
|
[
"def",
"steem_to_sbd",
"(",
"self",
",",
"steemamt",
"=",
"0",
",",
"price",
"=",
"0",
",",
"account",
"=",
"None",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"if",
"self",
".",
"check_balances",
"(",
"account",
")",
":",
"if",
"steemamt",
"==",
"0",
":",
"steemamt",
"=",
"self",
".",
"steembal",
"elif",
"steemamt",
">",
"self",
".",
"steembal",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"INSUFFICIENT FUNDS. CURRENT STEEM BAL: \"",
"+",
"str",
"(",
"self",
".",
"steembal",
")",
")",
"return",
"False",
"if",
"price",
"==",
"0",
":",
"price",
"=",
"self",
".",
"dex_ticker",
"(",
")",
"[",
"'highest_bid'",
"]",
"try",
":",
"self",
".",
"dex",
".",
"sell",
"(",
"steemamt",
",",
"\"STEEM\"",
",",
"price",
",",
"account",
"=",
"account",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT SELL STEEM FOR SBD: \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"TRANSFERED \"",
"+",
"str",
"(",
"steemamt",
")",
"+",
"\" STEEM TO SBD AT THE PRICE OF: $\"",
"+",
"str",
"(",
"price",
")",
")",
"return",
"True",
"else",
":",
"return",
"False"
] |
Uses the ticker to get the highest bid
and moves the steem at that price.
|
[
"Uses",
"the",
"ticker",
"to",
"get",
"the",
"highest",
"bid",
"and",
"moves",
"the",
"steem",
"at",
"that",
"price",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L549-L576
|
242,921
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.sbd_to_steem
|
def sbd_to_steem(self, sbd=0, price=0, account=None):
''' Uses the ticker to get the lowest ask
and moves the sbd at that price.
'''
if not account:
account = self.mainaccount
if self.check_balances(account):
if sbd == 0:
sbd = self.sbdbal
elif sbd > self.sbdbal:
self.msg.error_message("INSUFFICIENT FUNDS. CURRENT SBD BAL: "
+ str(self.sbdbal))
return False
if price == 0:
price = 1 / self.dex_ticker()['lowest_ask']
try:
self.dex.sell(sbd, "SBD", price, account=account)
except Exception as e:
self.msg.error_message("COULD NOT SELL SBD FOR STEEM: " + str(e))
return False
else:
self.msg.message("TRANSFERED "
+ str(sbd)
+ " SBD TO STEEM AT THE PRICE OF: $"
+ str(price))
return True
else:
return False
|
python
|
def sbd_to_steem(self, sbd=0, price=0, account=None):
''' Uses the ticker to get the lowest ask
and moves the sbd at that price.
'''
if not account:
account = self.mainaccount
if self.check_balances(account):
if sbd == 0:
sbd = self.sbdbal
elif sbd > self.sbdbal:
self.msg.error_message("INSUFFICIENT FUNDS. CURRENT SBD BAL: "
+ str(self.sbdbal))
return False
if price == 0:
price = 1 / self.dex_ticker()['lowest_ask']
try:
self.dex.sell(sbd, "SBD", price, account=account)
except Exception as e:
self.msg.error_message("COULD NOT SELL SBD FOR STEEM: " + str(e))
return False
else:
self.msg.message("TRANSFERED "
+ str(sbd)
+ " SBD TO STEEM AT THE PRICE OF: $"
+ str(price))
return True
else:
return False
|
[
"def",
"sbd_to_steem",
"(",
"self",
",",
"sbd",
"=",
"0",
",",
"price",
"=",
"0",
",",
"account",
"=",
"None",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"if",
"self",
".",
"check_balances",
"(",
"account",
")",
":",
"if",
"sbd",
"==",
"0",
":",
"sbd",
"=",
"self",
".",
"sbdbal",
"elif",
"sbd",
">",
"self",
".",
"sbdbal",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"INSUFFICIENT FUNDS. CURRENT SBD BAL: \"",
"+",
"str",
"(",
"self",
".",
"sbdbal",
")",
")",
"return",
"False",
"if",
"price",
"==",
"0",
":",
"price",
"=",
"1",
"/",
"self",
".",
"dex_ticker",
"(",
")",
"[",
"'lowest_ask'",
"]",
"try",
":",
"self",
".",
"dex",
".",
"sell",
"(",
"sbd",
",",
"\"SBD\"",
",",
"price",
",",
"account",
"=",
"account",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT SELL SBD FOR STEEM: \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"TRANSFERED \"",
"+",
"str",
"(",
"sbd",
")",
"+",
"\" SBD TO STEEM AT THE PRICE OF: $\"",
"+",
"str",
"(",
"price",
")",
")",
"return",
"True",
"else",
":",
"return",
"False"
] |
Uses the ticker to get the lowest ask
and moves the sbd at that price.
|
[
"Uses",
"the",
"ticker",
"to",
"get",
"the",
"lowest",
"ask",
"and",
"moves",
"the",
"sbd",
"at",
"that",
"price",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L579-L606
|
242,922
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.vote_witness
|
def vote_witness(self, witness, account=None):
''' Uses the steem_instance method to
vote on a witness.
'''
if not account:
account = self.mainaccount
try:
self.steem_instance().approve_witness(witness, account=account)
except Exception as e:
self.msg.error_message("COULD NOT VOTE "
+ witness + " AS WITNESS: " + e)
return False
else:
return True
|
python
|
def vote_witness(self, witness, account=None):
''' Uses the steem_instance method to
vote on a witness.
'''
if not account:
account = self.mainaccount
try:
self.steem_instance().approve_witness(witness, account=account)
except Exception as e:
self.msg.error_message("COULD NOT VOTE "
+ witness + " AS WITNESS: " + e)
return False
else:
return True
|
[
"def",
"vote_witness",
"(",
"self",
",",
"witness",
",",
"account",
"=",
"None",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"approve_witness",
"(",
"witness",
",",
"account",
"=",
"account",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT VOTE \"",
"+",
"witness",
"+",
"\" AS WITNESS: \"",
"+",
"e",
")",
"return",
"False",
"else",
":",
"return",
"True"
] |
Uses the steem_instance method to
vote on a witness.
|
[
"Uses",
"the",
"steem_instance",
"method",
"to",
"vote",
"on",
"a",
"witness",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L609-L622
|
242,923
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.unvote_witness
|
def unvote_witness(self, witness, account=None):
''' Uses the steem_instance method to
unvote a witness.
'''
if not account:
account = self.mainaccount
try:
self.steem_instance().disapprove_witness(witness, account=account)
except Exception as e:
self.msg.error_message("COULD NOT UNVOTE "
+ witness + " AS WITNESS: " + e)
return False
else:
return True
|
python
|
def unvote_witness(self, witness, account=None):
''' Uses the steem_instance method to
unvote a witness.
'''
if not account:
account = self.mainaccount
try:
self.steem_instance().disapprove_witness(witness, account=account)
except Exception as e:
self.msg.error_message("COULD NOT UNVOTE "
+ witness + " AS WITNESS: " + e)
return False
else:
return True
|
[
"def",
"unvote_witness",
"(",
"self",
",",
"witness",
",",
"account",
"=",
"None",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"disapprove_witness",
"(",
"witness",
",",
"account",
"=",
"account",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT UNVOTE \"",
"+",
"witness",
"+",
"\" AS WITNESS: \"",
"+",
"e",
")",
"return",
"False",
"else",
":",
"return",
"True"
] |
Uses the steem_instance method to
unvote a witness.
|
[
"Uses",
"the",
"steem_instance",
"method",
"to",
"unvote",
"a",
"witness",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L625-L638
|
242,924
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.voted_me_witness
|
def voted_me_witness(self, account=None, limit=100):
''' Fetches all those a given account is
following and sees if they have voted that
account as witness.
'''
if not account:
account = self.mainaccount
self.has_voted = []
self.has_not_voted = []
following = self.following(account, limit)
for f in following:
wv = self.account(f)['witness_votes']
voted = False
for w in wv:
if w == account:
self.has_voted.append(f)
voted = True
if not voted:
self.has_not_voted.append(f)
return self.has_voted
|
python
|
def voted_me_witness(self, account=None, limit=100):
''' Fetches all those a given account is
following and sees if they have voted that
account as witness.
'''
if not account:
account = self.mainaccount
self.has_voted = []
self.has_not_voted = []
following = self.following(account, limit)
for f in following:
wv = self.account(f)['witness_votes']
voted = False
for w in wv:
if w == account:
self.has_voted.append(f)
voted = True
if not voted:
self.has_not_voted.append(f)
return self.has_voted
|
[
"def",
"voted_me_witness",
"(",
"self",
",",
"account",
"=",
"None",
",",
"limit",
"=",
"100",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"self",
".",
"has_voted",
"=",
"[",
"]",
"self",
".",
"has_not_voted",
"=",
"[",
"]",
"following",
"=",
"self",
".",
"following",
"(",
"account",
",",
"limit",
")",
"for",
"f",
"in",
"following",
":",
"wv",
"=",
"self",
".",
"account",
"(",
"f",
")",
"[",
"'witness_votes'",
"]",
"voted",
"=",
"False",
"for",
"w",
"in",
"wv",
":",
"if",
"w",
"==",
"account",
":",
"self",
".",
"has_voted",
".",
"append",
"(",
"f",
")",
"voted",
"=",
"True",
"if",
"not",
"voted",
":",
"self",
".",
"has_not_voted",
".",
"append",
"(",
"f",
")",
"return",
"self",
".",
"has_voted"
] |
Fetches all those a given account is
following and sees if they have voted that
account as witness.
|
[
"Fetches",
"all",
"those",
"a",
"given",
"account",
"is",
"following",
"and",
"sees",
"if",
"they",
"have",
"voted",
"that",
"account",
"as",
"witness",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L641-L660
|
242,925
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.muted_me
|
def muted_me(self, account=None, limit=100):
''' Fetches all those a given account is
following and sees if they have muted that
account.
'''
self.has_muted = []
if account is None:
account = self.mainaccount
following = self.following(account, limit)
if following is False:
self.msg.error_message("COULD NOT GET FOLLOWING FOR MUTED")
return False
for f in following:
h = self.get_my_history(f)
for a in h:
if a[1]['op'][0] == "custom_json":
j = a[1]['op'][1]['json']
d = json.loads(j)
try:
d[1]
except:
pass
else:
for i in d[1]:
if i == "what":
if len(d[1]['what']) > 0:
if d[1]['what'][0] == "ignore":
if d[1]['follower'] == account:
self.msg.message("MUTED BY " + f)
self.has_muted.append(f)
return self.has_muted
|
python
|
def muted_me(self, account=None, limit=100):
''' Fetches all those a given account is
following and sees if they have muted that
account.
'''
self.has_muted = []
if account is None:
account = self.mainaccount
following = self.following(account, limit)
if following is False:
self.msg.error_message("COULD NOT GET FOLLOWING FOR MUTED")
return False
for f in following:
h = self.get_my_history(f)
for a in h:
if a[1]['op'][0] == "custom_json":
j = a[1]['op'][1]['json']
d = json.loads(j)
try:
d[1]
except:
pass
else:
for i in d[1]:
if i == "what":
if len(d[1]['what']) > 0:
if d[1]['what'][0] == "ignore":
if d[1]['follower'] == account:
self.msg.message("MUTED BY " + f)
self.has_muted.append(f)
return self.has_muted
|
[
"def",
"muted_me",
"(",
"self",
",",
"account",
"=",
"None",
",",
"limit",
"=",
"100",
")",
":",
"self",
".",
"has_muted",
"=",
"[",
"]",
"if",
"account",
"is",
"None",
":",
"account",
"=",
"self",
".",
"mainaccount",
"following",
"=",
"self",
".",
"following",
"(",
"account",
",",
"limit",
")",
"if",
"following",
"is",
"False",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT GET FOLLOWING FOR MUTED\"",
")",
"return",
"False",
"for",
"f",
"in",
"following",
":",
"h",
"=",
"self",
".",
"get_my_history",
"(",
"f",
")",
"for",
"a",
"in",
"h",
":",
"if",
"a",
"[",
"1",
"]",
"[",
"'op'",
"]",
"[",
"0",
"]",
"==",
"\"custom_json\"",
":",
"j",
"=",
"a",
"[",
"1",
"]",
"[",
"'op'",
"]",
"[",
"1",
"]",
"[",
"'json'",
"]",
"d",
"=",
"json",
".",
"loads",
"(",
"j",
")",
"try",
":",
"d",
"[",
"1",
"]",
"except",
":",
"pass",
"else",
":",
"for",
"i",
"in",
"d",
"[",
"1",
"]",
":",
"if",
"i",
"==",
"\"what\"",
":",
"if",
"len",
"(",
"d",
"[",
"1",
"]",
"[",
"'what'",
"]",
")",
">",
"0",
":",
"if",
"d",
"[",
"1",
"]",
"[",
"'what'",
"]",
"[",
"0",
"]",
"==",
"\"ignore\"",
":",
"if",
"d",
"[",
"1",
"]",
"[",
"'follower'",
"]",
"==",
"account",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"MUTED BY \"",
"+",
"f",
")",
"self",
".",
"has_muted",
".",
"append",
"(",
"f",
")",
"return",
"self",
".",
"has_muted"
] |
Fetches all those a given account is
following and sees if they have muted that
account.
|
[
"Fetches",
"all",
"those",
"a",
"given",
"account",
"is",
"following",
"and",
"sees",
"if",
"they",
"have",
"muted",
"that",
"account",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L663-L693
|
242,926
|
ArtoLabs/SimpleSteem
|
simplesteem/simplesteem.py
|
SimpleSteem.delegate
|
def delegate(self, to, steempower):
''' Delegates based on Steem Power rather
than by vests.
'''
self.global_props()
vests = self.util.sp_to_vests(steempower)
strvests = str(vests)
strvests = strvests + " VESTS"
try:
self.steem_instance().commit.delegate_vesting_shares(to,
strvests,
account=self.mainaccount)
except Exception as e:
self.msg.error_message("COULD NOT DELEGATE "
+ str(steempower) + " SP TO "
+ to + ": " + str(e))
return False
else:
self.msg.message("DELEGATED " + str(steempower) + " STEEM POWER TO " + str(to))
return True
|
python
|
def delegate(self, to, steempower):
''' Delegates based on Steem Power rather
than by vests.
'''
self.global_props()
vests = self.util.sp_to_vests(steempower)
strvests = str(vests)
strvests = strvests + " VESTS"
try:
self.steem_instance().commit.delegate_vesting_shares(to,
strvests,
account=self.mainaccount)
except Exception as e:
self.msg.error_message("COULD NOT DELEGATE "
+ str(steempower) + " SP TO "
+ to + ": " + str(e))
return False
else:
self.msg.message("DELEGATED " + str(steempower) + " STEEM POWER TO " + str(to))
return True
|
[
"def",
"delegate",
"(",
"self",
",",
"to",
",",
"steempower",
")",
":",
"self",
".",
"global_props",
"(",
")",
"vests",
"=",
"self",
".",
"util",
".",
"sp_to_vests",
"(",
"steempower",
")",
"strvests",
"=",
"str",
"(",
"vests",
")",
"strvests",
"=",
"strvests",
"+",
"\" VESTS\"",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"commit",
".",
"delegate_vesting_shares",
"(",
"to",
",",
"strvests",
",",
"account",
"=",
"self",
".",
"mainaccount",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"msg",
".",
"error_message",
"(",
"\"COULD NOT DELEGATE \"",
"+",
"str",
"(",
"steempower",
")",
"+",
"\" SP TO \"",
"+",
"to",
"+",
"\": \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"DELEGATED \"",
"+",
"str",
"(",
"steempower",
")",
"+",
"\" STEEM POWER TO \"",
"+",
"str",
"(",
"to",
")",
")",
"return",
"True"
] |
Delegates based on Steem Power rather
than by vests.
|
[
"Delegates",
"based",
"on",
"Steem",
"Power",
"rather",
"than",
"by",
"vests",
"."
] |
ce8be0ae81f8878b460bc156693f1957f7dd34a3
|
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L696-L715
|
242,927
|
diffeo/rejester
|
rejester/run_multi_worker.py
|
start_logging
|
def start_logging(gconfig, logpath):
'''Turn on logging and set up the global config.
This expects the :mod:`yakonfig` global configuration to be unset,
and establishes it. It starts the log system via the :mod:`dblogger`
setup. In addition to :mod:`dblogger`'s defaults, if `logpath` is
provided, a :class:`logging.handlers.RotatingFileHandler` is set to
write log messages to that file.
This should not be called if the target worker is
:class:`rejester.workers.ForkWorker`, since that manages logging on
its own.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param str logpath: optional location to write a log file
'''
yakonfig.set_default_config([rejester, dblogger], config=gconfig)
if logpath:
formatter = dblogger.FixedWidthFormatter()
# TODO: do we want byte-size RotatingFileHandler or TimedRotatingFileHandler?
handler = logging.handlers.RotatingFileHandler(
logpath, maxBytes=10000000, backupCount=3)
handler.setFormatter(formatter)
logging.getLogger('').addHandler(handler)
|
python
|
def start_logging(gconfig, logpath):
'''Turn on logging and set up the global config.
This expects the :mod:`yakonfig` global configuration to be unset,
and establishes it. It starts the log system via the :mod:`dblogger`
setup. In addition to :mod:`dblogger`'s defaults, if `logpath` is
provided, a :class:`logging.handlers.RotatingFileHandler` is set to
write log messages to that file.
This should not be called if the target worker is
:class:`rejester.workers.ForkWorker`, since that manages logging on
its own.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param str logpath: optional location to write a log file
'''
yakonfig.set_default_config([rejester, dblogger], config=gconfig)
if logpath:
formatter = dblogger.FixedWidthFormatter()
# TODO: do we want byte-size RotatingFileHandler or TimedRotatingFileHandler?
handler = logging.handlers.RotatingFileHandler(
logpath, maxBytes=10000000, backupCount=3)
handler.setFormatter(formatter)
logging.getLogger('').addHandler(handler)
|
[
"def",
"start_logging",
"(",
"gconfig",
",",
"logpath",
")",
":",
"yakonfig",
".",
"set_default_config",
"(",
"[",
"rejester",
",",
"dblogger",
"]",
",",
"config",
"=",
"gconfig",
")",
"if",
"logpath",
":",
"formatter",
"=",
"dblogger",
".",
"FixedWidthFormatter",
"(",
")",
"# TODO: do we want byte-size RotatingFileHandler or TimedRotatingFileHandler?",
"handler",
"=",
"logging",
".",
"handlers",
".",
"RotatingFileHandler",
"(",
"logpath",
",",
"maxBytes",
"=",
"10000000",
",",
"backupCount",
"=",
"3",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logging",
".",
"getLogger",
"(",
"''",
")",
".",
"addHandler",
"(",
"handler",
")"
] |
Turn on logging and set up the global config.
This expects the :mod:`yakonfig` global configuration to be unset,
and establishes it. It starts the log system via the :mod:`dblogger`
setup. In addition to :mod:`dblogger`'s defaults, if `logpath` is
provided, a :class:`logging.handlers.RotatingFileHandler` is set to
write log messages to that file.
This should not be called if the target worker is
:class:`rejester.workers.ForkWorker`, since that manages logging on
its own.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param str logpath: optional location to write a log file
|
[
"Turn",
"on",
"logging",
"and",
"set",
"up",
"the",
"global",
"config",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run_multi_worker.py#L53-L77
|
242,928
|
diffeo/rejester
|
rejester/run_multi_worker.py
|
start_worker
|
def start_worker(which_worker, config={}):
'''Start some worker class.
:param str which_worker: name of the worker
:param dict config: ``rejester`` config block
'''
if which_worker == 'multi_worker':
cls = MultiWorker
elif which_worker == 'fork_worker':
cls = ForkWorker
else:
# Don't complain too hard, just fall back
cls = ForkWorker
return run_worker(cls, config)
|
python
|
def start_worker(which_worker, config={}):
'''Start some worker class.
:param str which_worker: name of the worker
:param dict config: ``rejester`` config block
'''
if which_worker == 'multi_worker':
cls = MultiWorker
elif which_worker == 'fork_worker':
cls = ForkWorker
else:
# Don't complain too hard, just fall back
cls = ForkWorker
return run_worker(cls, config)
|
[
"def",
"start_worker",
"(",
"which_worker",
",",
"config",
"=",
"{",
"}",
")",
":",
"if",
"which_worker",
"==",
"'multi_worker'",
":",
"cls",
"=",
"MultiWorker",
"elif",
"which_worker",
"==",
"'fork_worker'",
":",
"cls",
"=",
"ForkWorker",
"else",
":",
"# Don't complain too hard, just fall back",
"cls",
"=",
"ForkWorker",
"return",
"run_worker",
"(",
"cls",
",",
"config",
")"
] |
Start some worker class.
:param str which_worker: name of the worker
:param dict config: ``rejester`` config block
|
[
"Start",
"some",
"worker",
"class",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run_multi_worker.py#L79-L93
|
242,929
|
diffeo/rejester
|
rejester/run_multi_worker.py
|
go
|
def go(gconfig, args):
'''Actually run the worker.
This does some required housekeeping, like setting up logging for
:class:`~rejester.workers.MultiWorker` and establishing the global
:mod:`yakonfig` configuration. This expects to be called with the
:mod:`yakonfig` configuration unset.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line arguments
'''
rconfig = gconfig['rejester']
which_worker = rconfig.get('worker', 'fork_worker')
if which_worker == 'fork_worker':
yakonfig.set_default_config([rejester], config=gconfig)
else:
start_logging(gconfig, args.logpath)
return start_worker(which_worker, rconfig)
|
python
|
def go(gconfig, args):
'''Actually run the worker.
This does some required housekeeping, like setting up logging for
:class:`~rejester.workers.MultiWorker` and establishing the global
:mod:`yakonfig` configuration. This expects to be called with the
:mod:`yakonfig` configuration unset.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line arguments
'''
rconfig = gconfig['rejester']
which_worker = rconfig.get('worker', 'fork_worker')
if which_worker == 'fork_worker':
yakonfig.set_default_config([rejester], config=gconfig)
else:
start_logging(gconfig, args.logpath)
return start_worker(which_worker, rconfig)
|
[
"def",
"go",
"(",
"gconfig",
",",
"args",
")",
":",
"rconfig",
"=",
"gconfig",
"[",
"'rejester'",
"]",
"which_worker",
"=",
"rconfig",
".",
"get",
"(",
"'worker'",
",",
"'fork_worker'",
")",
"if",
"which_worker",
"==",
"'fork_worker'",
":",
"yakonfig",
".",
"set_default_config",
"(",
"[",
"rejester",
"]",
",",
"config",
"=",
"gconfig",
")",
"else",
":",
"start_logging",
"(",
"gconfig",
",",
"args",
".",
"logpath",
")",
"return",
"start_worker",
"(",
"which_worker",
",",
"rconfig",
")"
] |
Actually run the worker.
This does some required housekeeping, like setting up logging for
:class:`~rejester.workers.MultiWorker` and establishing the global
:mod:`yakonfig` configuration. This expects to be called with the
:mod:`yakonfig` configuration unset.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line arguments
|
[
"Actually",
"run",
"the",
"worker",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run_multi_worker.py#L95-L113
|
242,930
|
diffeo/rejester
|
rejester/run_multi_worker.py
|
fork_worker
|
def fork_worker(gconfig, args):
'''Run the worker as a daemon process.
This uses :mod:`daemon` to run the standard double-fork, so it can
return immediately and successfully in the parent process having forked.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line arguments
'''
if args.pidfile:
pidfile_lock = lockfile.FileLock(args.pidfile)
else:
pidfile_lock = None
with daemon.DaemonContext(pidfile=pidfile_lock, detach_process=True):
try:
if args.pidfile:
with open(args.pidfile, 'w') as f:
f.write(str(os.getpid()))
go(gconfig, args)
except Exception, exc:
logp = logpath or os.path.join('/tmp', 'rejester-failure.log')
open(logp, 'a').write(traceback.format_exc(exc))
raise
|
python
|
def fork_worker(gconfig, args):
'''Run the worker as a daemon process.
This uses :mod:`daemon` to run the standard double-fork, so it can
return immediately and successfully in the parent process having forked.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line arguments
'''
if args.pidfile:
pidfile_lock = lockfile.FileLock(args.pidfile)
else:
pidfile_lock = None
with daemon.DaemonContext(pidfile=pidfile_lock, detach_process=True):
try:
if args.pidfile:
with open(args.pidfile, 'w') as f:
f.write(str(os.getpid()))
go(gconfig, args)
except Exception, exc:
logp = logpath or os.path.join('/tmp', 'rejester-failure.log')
open(logp, 'a').write(traceback.format_exc(exc))
raise
|
[
"def",
"fork_worker",
"(",
"gconfig",
",",
"args",
")",
":",
"if",
"args",
".",
"pidfile",
":",
"pidfile_lock",
"=",
"lockfile",
".",
"FileLock",
"(",
"args",
".",
"pidfile",
")",
"else",
":",
"pidfile_lock",
"=",
"None",
"with",
"daemon",
".",
"DaemonContext",
"(",
"pidfile",
"=",
"pidfile_lock",
",",
"detach_process",
"=",
"True",
")",
":",
"try",
":",
"if",
"args",
".",
"pidfile",
":",
"with",
"open",
"(",
"args",
".",
"pidfile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
")",
"go",
"(",
"gconfig",
",",
"args",
")",
"except",
"Exception",
",",
"exc",
":",
"logp",
"=",
"logpath",
"or",
"os",
".",
"path",
".",
"join",
"(",
"'/tmp'",
",",
"'rejester-failure.log'",
")",
"open",
"(",
"logp",
",",
"'a'",
")",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
"exc",
")",
")",
"raise"
] |
Run the worker as a daemon process.
This uses :mod:`daemon` to run the standard double-fork, so it can
return immediately and successfully in the parent process having forked.
:param dict gconfig: the :mod:`yakonfig` global configuration
:param args: command-line arguments
|
[
"Run",
"the",
"worker",
"as",
"a",
"daemon",
"process",
"."
] |
5438a4a18be2801d7826c46e2079ba9639d2ecb4
|
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/run_multi_worker.py#L115-L138
|
242,931
|
pyros-dev/pyros-common
|
pyros_interfaces_common/transient_if_pool.py
|
TransientIfPool.transient_change_detect
|
def transient_change_detect(self, *class_build_args, **class_build_kwargs):
"""
This should be called when we want to detect a change in the status of the system regarding the transient list
This function also applies changes due to regex_set updates if needed
_transient_change_detect -> _transient_change_diff -> _update_transients
"""
transient_detected = set(self.get_transients_available())
#TODO : unify that last_got_set with the *_available. they are essentially the same
tst_gone = self.last_transients_detected - transient_detected
# print("INTERFACING + {transient_detected}".format(**locals()))
# print("INTERFACING - {tst_gone}".format(**locals()))
dt = self.transient_change_diff(
# we start interfacing with new matches,
# but we also need to update old matches that match regex now
transient_appeared=transient_detected,
transient_gone=tst_gone,
*class_build_args,
**class_build_kwargs
)
self.last_transients_detected.update(transient_detected)
if tst_gone:
self.last_transients_detected.difference_update(tst_gone)
return dt
|
python
|
def transient_change_detect(self, *class_build_args, **class_build_kwargs):
"""
This should be called when we want to detect a change in the status of the system regarding the transient list
This function also applies changes due to regex_set updates if needed
_transient_change_detect -> _transient_change_diff -> _update_transients
"""
transient_detected = set(self.get_transients_available())
#TODO : unify that last_got_set with the *_available. they are essentially the same
tst_gone = self.last_transients_detected - transient_detected
# print("INTERFACING + {transient_detected}".format(**locals()))
# print("INTERFACING - {tst_gone}".format(**locals()))
dt = self.transient_change_diff(
# we start interfacing with new matches,
# but we also need to update old matches that match regex now
transient_appeared=transient_detected,
transient_gone=tst_gone,
*class_build_args,
**class_build_kwargs
)
self.last_transients_detected.update(transient_detected)
if tst_gone:
self.last_transients_detected.difference_update(tst_gone)
return dt
|
[
"def",
"transient_change_detect",
"(",
"self",
",",
"*",
"class_build_args",
",",
"*",
"*",
"class_build_kwargs",
")",
":",
"transient_detected",
"=",
"set",
"(",
"self",
".",
"get_transients_available",
"(",
")",
")",
"#TODO : unify that last_got_set with the *_available. they are essentially the same",
"tst_gone",
"=",
"self",
".",
"last_transients_detected",
"-",
"transient_detected",
"# print(\"INTERFACING + {transient_detected}\".format(**locals()))",
"# print(\"INTERFACING - {tst_gone}\".format(**locals()))",
"dt",
"=",
"self",
".",
"transient_change_diff",
"(",
"# we start interfacing with new matches,",
"# but we also need to update old matches that match regex now",
"transient_appeared",
"=",
"transient_detected",
",",
"transient_gone",
"=",
"tst_gone",
",",
"*",
"class_build_args",
",",
"*",
"*",
"class_build_kwargs",
")",
"self",
".",
"last_transients_detected",
".",
"update",
"(",
"transient_detected",
")",
"if",
"tst_gone",
":",
"self",
".",
"last_transients_detected",
".",
"difference_update",
"(",
"tst_gone",
")",
"return",
"dt"
] |
This should be called when we want to detect a change in the status of the system regarding the transient list
This function also applies changes due to regex_set updates if needed
_transient_change_detect -> _transient_change_diff -> _update_transients
|
[
"This",
"should",
"be",
"called",
"when",
"we",
"want",
"to",
"detect",
"a",
"change",
"in",
"the",
"status",
"of",
"the",
"system",
"regarding",
"the",
"transient",
"list",
"This",
"function",
"also",
"applies",
"changes",
"due",
"to",
"regex_set",
"updates",
"if",
"needed",
"_transient_change_detect",
"-",
">",
"_transient_change_diff",
"-",
">",
"_update_transients"
] |
0709538b8777ec055ea31f59cdca5bebaaabb04e
|
https://github.com/pyros-dev/pyros-common/blob/0709538b8777ec055ea31f59cdca5bebaaabb04e/pyros_interfaces_common/transient_if_pool.py#L126-L153
|
242,932
|
pawamoy/python-getdoc
|
src/getdoc/__init__.py
|
get_function_doc
|
def get_function_doc(function, config=default_config):
"""Return doc for a function."""
if config.exclude_function:
for ex in config.exclude_function:
if ex.match(function.__name__):
return None
return _doc_object(function, 'function', config=config)
|
python
|
def get_function_doc(function, config=default_config):
"""Return doc for a function."""
if config.exclude_function:
for ex in config.exclude_function:
if ex.match(function.__name__):
return None
return _doc_object(function, 'function', config=config)
|
[
"def",
"get_function_doc",
"(",
"function",
",",
"config",
"=",
"default_config",
")",
":",
"if",
"config",
".",
"exclude_function",
":",
"for",
"ex",
"in",
"config",
".",
"exclude_function",
":",
"if",
"ex",
".",
"match",
"(",
"function",
".",
"__name__",
")",
":",
"return",
"None",
"return",
"_doc_object",
"(",
"function",
",",
"'function'",
",",
"config",
"=",
"config",
")"
] |
Return doc for a function.
|
[
"Return",
"doc",
"for",
"a",
"function",
"."
] |
7589605be746ecde54f3fb68a46c88242d9b6405
|
https://github.com/pawamoy/python-getdoc/blob/7589605be746ecde54f3fb68a46c88242d9b6405/src/getdoc/__init__.py#L144-L151
|
242,933
|
pawamoy/python-getdoc
|
src/getdoc/__init__.py
|
get_class_doc
|
def get_class_doc(klass, config=default_config):
"""Return doc for a class."""
if config.exclude_class:
for ex in config.exclude_class:
if ex.match(klass.__name__):
return None
nested_doc = []
class_dict = klass.__dict__
for item in dir(klass):
if item in class_dict.keys():
appended = None
if isinstance(class_dict[item], type) and config.nested_class:
appended = get_class_doc(class_dict[item], config)
elif isinstance(class_dict[item], types.FunctionType):
appended = get_function_doc(class_dict[item], config)
if appended is not None:
nested_doc.append(appended)
return _doc_object(klass, 'class', nested_doc, config)
|
python
|
def get_class_doc(klass, config=default_config):
"""Return doc for a class."""
if config.exclude_class:
for ex in config.exclude_class:
if ex.match(klass.__name__):
return None
nested_doc = []
class_dict = klass.__dict__
for item in dir(klass):
if item in class_dict.keys():
appended = None
if isinstance(class_dict[item], type) and config.nested_class:
appended = get_class_doc(class_dict[item], config)
elif isinstance(class_dict[item], types.FunctionType):
appended = get_function_doc(class_dict[item], config)
if appended is not None:
nested_doc.append(appended)
return _doc_object(klass, 'class', nested_doc, config)
|
[
"def",
"get_class_doc",
"(",
"klass",
",",
"config",
"=",
"default_config",
")",
":",
"if",
"config",
".",
"exclude_class",
":",
"for",
"ex",
"in",
"config",
".",
"exclude_class",
":",
"if",
"ex",
".",
"match",
"(",
"klass",
".",
"__name__",
")",
":",
"return",
"None",
"nested_doc",
"=",
"[",
"]",
"class_dict",
"=",
"klass",
".",
"__dict__",
"for",
"item",
"in",
"dir",
"(",
"klass",
")",
":",
"if",
"item",
"in",
"class_dict",
".",
"keys",
"(",
")",
":",
"appended",
"=",
"None",
"if",
"isinstance",
"(",
"class_dict",
"[",
"item",
"]",
",",
"type",
")",
"and",
"config",
".",
"nested_class",
":",
"appended",
"=",
"get_class_doc",
"(",
"class_dict",
"[",
"item",
"]",
",",
"config",
")",
"elif",
"isinstance",
"(",
"class_dict",
"[",
"item",
"]",
",",
"types",
".",
"FunctionType",
")",
":",
"appended",
"=",
"get_function_doc",
"(",
"class_dict",
"[",
"item",
"]",
",",
"config",
")",
"if",
"appended",
"is",
"not",
"None",
":",
"nested_doc",
".",
"append",
"(",
"appended",
")",
"return",
"_doc_object",
"(",
"klass",
",",
"'class'",
",",
"nested_doc",
",",
"config",
")"
] |
Return doc for a class.
|
[
"Return",
"doc",
"for",
"a",
"class",
"."
] |
7589605be746ecde54f3fb68a46c88242d9b6405
|
https://github.com/pawamoy/python-getdoc/blob/7589605be746ecde54f3fb68a46c88242d9b6405/src/getdoc/__init__.py#L154-L174
|
242,934
|
pawamoy/python-getdoc
|
src/getdoc/__init__.py
|
get_module_doc
|
def get_module_doc(module, config=default_config, already_met=None):
"""Return doc for a module."""
# Avoid recursion loops (init)
if already_met is None:
already_met = set()
if config.exclude_module:
for ex in config.exclude_module:
if ex.match(module.__name__):
return None
# Force load submodules into module's dict
if hasattr(module, '__path__'):
subm = [
modname for importer, modname, ispkg
in pkgutil.iter_modules(module.__path__)
]
__import__(module.__name__, fromlist=subm)
# We don't want to include imported items,
# so we parse the code to blacklist them.
# Be sure to parse .py and not .pyc file on Python 2.X
if hasattr(module, '__file__'):
module_file = module.__file__
else:
module_file = inspect.getsourcefile(module)
path, ext = os.path.splitext(module_file)
if ext == '.pyc':
module_file = path + '.py'
try:
code = open(module_file).read()
body = ast.parse(code).body
except SyntaxError:
code = open(module_file).read().encode('utf-8')
body = ast.parse(code).body
imported = []
for node in body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
imported.extend([n.name for n in node.names])
nested_doc = []
module_dict = module.__dict__
for item in dir(module):
if item not in imported and item in module_dict.keys():
# Avoid recursion loops
if id(item) in already_met:
continue
already_met.add(id(item))
appended = None
if isinstance(module_dict[item], types.ModuleType):
appended = get_module_doc(module_dict[item], config, already_met) # noqa
elif isinstance(module_dict[item], type):
appended = get_class_doc(module_dict[item], config)
elif isinstance(module_dict[item], types.FunctionType):
appended = get_function_doc(module_dict[item], config)
if appended is not None:
nested_doc.append(appended)
return _doc_object(module, 'module', nested_doc, config)
|
python
|
def get_module_doc(module, config=default_config, already_met=None):
"""Return doc for a module."""
# Avoid recursion loops (init)
if already_met is None:
already_met = set()
if config.exclude_module:
for ex in config.exclude_module:
if ex.match(module.__name__):
return None
# Force load submodules into module's dict
if hasattr(module, '__path__'):
subm = [
modname for importer, modname, ispkg
in pkgutil.iter_modules(module.__path__)
]
__import__(module.__name__, fromlist=subm)
# We don't want to include imported items,
# so we parse the code to blacklist them.
# Be sure to parse .py and not .pyc file on Python 2.X
if hasattr(module, '__file__'):
module_file = module.__file__
else:
module_file = inspect.getsourcefile(module)
path, ext = os.path.splitext(module_file)
if ext == '.pyc':
module_file = path + '.py'
try:
code = open(module_file).read()
body = ast.parse(code).body
except SyntaxError:
code = open(module_file).read().encode('utf-8')
body = ast.parse(code).body
imported = []
for node in body:
if isinstance(node, (ast.Import, ast.ImportFrom)):
imported.extend([n.name for n in node.names])
nested_doc = []
module_dict = module.__dict__
for item in dir(module):
if item not in imported and item in module_dict.keys():
# Avoid recursion loops
if id(item) in already_met:
continue
already_met.add(id(item))
appended = None
if isinstance(module_dict[item], types.ModuleType):
appended = get_module_doc(module_dict[item], config, already_met) # noqa
elif isinstance(module_dict[item], type):
appended = get_class_doc(module_dict[item], config)
elif isinstance(module_dict[item], types.FunctionType):
appended = get_function_doc(module_dict[item], config)
if appended is not None:
nested_doc.append(appended)
return _doc_object(module, 'module', nested_doc, config)
|
[
"def",
"get_module_doc",
"(",
"module",
",",
"config",
"=",
"default_config",
",",
"already_met",
"=",
"None",
")",
":",
"# Avoid recursion loops (init)",
"if",
"already_met",
"is",
"None",
":",
"already_met",
"=",
"set",
"(",
")",
"if",
"config",
".",
"exclude_module",
":",
"for",
"ex",
"in",
"config",
".",
"exclude_module",
":",
"if",
"ex",
".",
"match",
"(",
"module",
".",
"__name__",
")",
":",
"return",
"None",
"# Force load submodules into module's dict",
"if",
"hasattr",
"(",
"module",
",",
"'__path__'",
")",
":",
"subm",
"=",
"[",
"modname",
"for",
"importer",
",",
"modname",
",",
"ispkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"module",
".",
"__path__",
")",
"]",
"__import__",
"(",
"module",
".",
"__name__",
",",
"fromlist",
"=",
"subm",
")",
"# We don't want to include imported items,",
"# so we parse the code to blacklist them.",
"# Be sure to parse .py and not .pyc file on Python 2.X",
"if",
"hasattr",
"(",
"module",
",",
"'__file__'",
")",
":",
"module_file",
"=",
"module",
".",
"__file__",
"else",
":",
"module_file",
"=",
"inspect",
".",
"getsourcefile",
"(",
"module",
")",
"path",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"module_file",
")",
"if",
"ext",
"==",
"'.pyc'",
":",
"module_file",
"=",
"path",
"+",
"'.py'",
"try",
":",
"code",
"=",
"open",
"(",
"module_file",
")",
".",
"read",
"(",
")",
"body",
"=",
"ast",
".",
"parse",
"(",
"code",
")",
".",
"body",
"except",
"SyntaxError",
":",
"code",
"=",
"open",
"(",
"module_file",
")",
".",
"read",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"body",
"=",
"ast",
".",
"parse",
"(",
"code",
")",
".",
"body",
"imported",
"=",
"[",
"]",
"for",
"node",
"in",
"body",
":",
"if",
"isinstance",
"(",
"node",
",",
"(",
"ast",
".",
"Import",
",",
"ast",
".",
"ImportFrom",
")",
")",
":",
"imported",
".",
"extend",
"(",
"[",
"n",
".",
"name",
"for",
"n",
"in",
"node",
".",
"names",
"]",
")",
"nested_doc",
"=",
"[",
"]",
"module_dict",
"=",
"module",
".",
"__dict__",
"for",
"item",
"in",
"dir",
"(",
"module",
")",
":",
"if",
"item",
"not",
"in",
"imported",
"and",
"item",
"in",
"module_dict",
".",
"keys",
"(",
")",
":",
"# Avoid recursion loops",
"if",
"id",
"(",
"item",
")",
"in",
"already_met",
":",
"continue",
"already_met",
".",
"add",
"(",
"id",
"(",
"item",
")",
")",
"appended",
"=",
"None",
"if",
"isinstance",
"(",
"module_dict",
"[",
"item",
"]",
",",
"types",
".",
"ModuleType",
")",
":",
"appended",
"=",
"get_module_doc",
"(",
"module_dict",
"[",
"item",
"]",
",",
"config",
",",
"already_met",
")",
"# noqa",
"elif",
"isinstance",
"(",
"module_dict",
"[",
"item",
"]",
",",
"type",
")",
":",
"appended",
"=",
"get_class_doc",
"(",
"module_dict",
"[",
"item",
"]",
",",
"config",
")",
"elif",
"isinstance",
"(",
"module_dict",
"[",
"item",
"]",
",",
"types",
".",
"FunctionType",
")",
":",
"appended",
"=",
"get_function_doc",
"(",
"module_dict",
"[",
"item",
"]",
",",
"config",
")",
"if",
"appended",
"is",
"not",
"None",
":",
"nested_doc",
".",
"append",
"(",
"appended",
")",
"return",
"_doc_object",
"(",
"module",
",",
"'module'",
",",
"nested_doc",
",",
"config",
")"
] |
Return doc for a module.
|
[
"Return",
"doc",
"for",
"a",
"module",
"."
] |
7589605be746ecde54f3fb68a46c88242d9b6405
|
https://github.com/pawamoy/python-getdoc/blob/7589605be746ecde54f3fb68a46c88242d9b6405/src/getdoc/__init__.py#L177-L240
|
242,935
|
pawamoy/python-getdoc
|
src/getdoc/__init__.py
|
Ex.match
|
def match(self, name):
"""
Check if given name matches.
Args:
name (str): name to check.
Returns:
bool: matches name.
"""
if self.method == Ex.Method.PREFIX:
return name.startswith(self.value)
elif self.method == Ex.Method.SUFFIX:
return name.endswith(self.value)
elif self.method == Ex.Method.CONTAINS:
return self.value in name
elif self.method == Ex.Method.EXACT:
return self.value == name
elif self.method == Ex.Method.REGEX:
return re.search(self.value, name)
return False
|
python
|
def match(self, name):
"""
Check if given name matches.
Args:
name (str): name to check.
Returns:
bool: matches name.
"""
if self.method == Ex.Method.PREFIX:
return name.startswith(self.value)
elif self.method == Ex.Method.SUFFIX:
return name.endswith(self.value)
elif self.method == Ex.Method.CONTAINS:
return self.value in name
elif self.method == Ex.Method.EXACT:
return self.value == name
elif self.method == Ex.Method.REGEX:
return re.search(self.value, name)
return False
|
[
"def",
"match",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"method",
"==",
"Ex",
".",
"Method",
".",
"PREFIX",
":",
"return",
"name",
".",
"startswith",
"(",
"self",
".",
"value",
")",
"elif",
"self",
".",
"method",
"==",
"Ex",
".",
"Method",
".",
"SUFFIX",
":",
"return",
"name",
".",
"endswith",
"(",
"self",
".",
"value",
")",
"elif",
"self",
".",
"method",
"==",
"Ex",
".",
"Method",
".",
"CONTAINS",
":",
"return",
"self",
".",
"value",
"in",
"name",
"elif",
"self",
".",
"method",
"==",
"Ex",
".",
"Method",
".",
"EXACT",
":",
"return",
"self",
".",
"value",
"==",
"name",
"elif",
"self",
".",
"method",
"==",
"Ex",
".",
"Method",
".",
"REGEX",
":",
"return",
"re",
".",
"search",
"(",
"self",
".",
"value",
",",
"name",
")",
"return",
"False"
] |
Check if given name matches.
Args:
name (str): name to check.
Returns:
bool: matches name.
|
[
"Check",
"if",
"given",
"name",
"matches",
"."
] |
7589605be746ecde54f3fb68a46c88242d9b6405
|
https://github.com/pawamoy/python-getdoc/blob/7589605be746ecde54f3fb68a46c88242d9b6405/src/getdoc/__init__.py#L57-L77
|
242,936
|
mayfield/shellish
|
shellish/command/autocommand.py
|
autocommand
|
def autocommand(func):
""" A simplified decorator for making a single function a Command
instance. In the future this will leverage PEP0484 to do really smart
function parsing and conversion to argparse actions. """
name = func.__name__
title, desc = command.parse_docstring(func)
if not title:
title = 'Auto command for: %s' % name
if not desc:
# Prevent Command from using docstring of AutoCommand
desc = ' '
return AutoCommand(title=title, desc=desc, name=name, func=func)
|
python
|
def autocommand(func):
""" A simplified decorator for making a single function a Command
instance. In the future this will leverage PEP0484 to do really smart
function parsing and conversion to argparse actions. """
name = func.__name__
title, desc = command.parse_docstring(func)
if not title:
title = 'Auto command for: %s' % name
if not desc:
# Prevent Command from using docstring of AutoCommand
desc = ' '
return AutoCommand(title=title, desc=desc, name=name, func=func)
|
[
"def",
"autocommand",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"title",
",",
"desc",
"=",
"command",
".",
"parse_docstring",
"(",
"func",
")",
"if",
"not",
"title",
":",
"title",
"=",
"'Auto command for: %s'",
"%",
"name",
"if",
"not",
"desc",
":",
"# Prevent Command from using docstring of AutoCommand",
"desc",
"=",
"' '",
"return",
"AutoCommand",
"(",
"title",
"=",
"title",
",",
"desc",
"=",
"desc",
",",
"name",
"=",
"name",
",",
"func",
"=",
"func",
")"
] |
A simplified decorator for making a single function a Command
instance. In the future this will leverage PEP0484 to do really smart
function parsing and conversion to argparse actions.
|
[
"A",
"simplified",
"decorator",
"for",
"making",
"a",
"single",
"function",
"a",
"Command",
"instance",
".",
"In",
"the",
"future",
"this",
"will",
"leverage",
"PEP0484",
"to",
"do",
"really",
"smart",
"function",
"parsing",
"and",
"conversion",
"to",
"argparse",
"actions",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/autocommand.py#L114-L125
|
242,937
|
mayfield/shellish
|
shellish/command/autocommand.py
|
AutoCommand.run
|
def run(self, args):
""" Convert the unordered args into function arguments. """
args = vars(args)
positionals = []
keywords = {}
for action in self.argparser._actions:
if not hasattr(action, 'label'):
continue
if action.label == 'positional':
positionals.append(args[action.dest])
elif action.label == 'varargs':
positionals.extend(args[action.dest])
elif action.label == 'keyword':
keywords[action.dest] = args[action.dest]
elif action.label == 'varkwargs':
kwpairs = iter(args[action.dest] or [])
for key in kwpairs:
try:
key, value = key.split('=', 1)
except ValueError:
value = next(kwpairs)
key = key.strip('-')
keywords[key] = value
return self.func(*positionals, **keywords)
|
python
|
def run(self, args):
""" Convert the unordered args into function arguments. """
args = vars(args)
positionals = []
keywords = {}
for action in self.argparser._actions:
if not hasattr(action, 'label'):
continue
if action.label == 'positional':
positionals.append(args[action.dest])
elif action.label == 'varargs':
positionals.extend(args[action.dest])
elif action.label == 'keyword':
keywords[action.dest] = args[action.dest]
elif action.label == 'varkwargs':
kwpairs = iter(args[action.dest] or [])
for key in kwpairs:
try:
key, value = key.split('=', 1)
except ValueError:
value = next(kwpairs)
key = key.strip('-')
keywords[key] = value
return self.func(*positionals, **keywords)
|
[
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"args",
"=",
"vars",
"(",
"args",
")",
"positionals",
"=",
"[",
"]",
"keywords",
"=",
"{",
"}",
"for",
"action",
"in",
"self",
".",
"argparser",
".",
"_actions",
":",
"if",
"not",
"hasattr",
"(",
"action",
",",
"'label'",
")",
":",
"continue",
"if",
"action",
".",
"label",
"==",
"'positional'",
":",
"positionals",
".",
"append",
"(",
"args",
"[",
"action",
".",
"dest",
"]",
")",
"elif",
"action",
".",
"label",
"==",
"'varargs'",
":",
"positionals",
".",
"extend",
"(",
"args",
"[",
"action",
".",
"dest",
"]",
")",
"elif",
"action",
".",
"label",
"==",
"'keyword'",
":",
"keywords",
"[",
"action",
".",
"dest",
"]",
"=",
"args",
"[",
"action",
".",
"dest",
"]",
"elif",
"action",
".",
"label",
"==",
"'varkwargs'",
":",
"kwpairs",
"=",
"iter",
"(",
"args",
"[",
"action",
".",
"dest",
"]",
"or",
"[",
"]",
")",
"for",
"key",
"in",
"kwpairs",
":",
"try",
":",
"key",
",",
"value",
"=",
"key",
".",
"split",
"(",
"'='",
",",
"1",
")",
"except",
"ValueError",
":",
"value",
"=",
"next",
"(",
"kwpairs",
")",
"key",
"=",
"key",
".",
"strip",
"(",
"'-'",
")",
"keywords",
"[",
"key",
"]",
"=",
"value",
"return",
"self",
".",
"func",
"(",
"*",
"positionals",
",",
"*",
"*",
"keywords",
")"
] |
Convert the unordered args into function arguments.
|
[
"Convert",
"the",
"unordered",
"args",
"into",
"function",
"arguments",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/autocommand.py#L29-L52
|
242,938
|
jpscaletti/moar
|
moar/engines/wand_engine.py
|
WandEngine._save_to
|
def _save_to(self, im, path, format=None):
"""Save the image for testing.
"""
format = format or im.format
if not format:
_, format = splitext(path)
format = format[1:]
im.format = format.lower()
im.save(filename=path)
|
python
|
def _save_to(self, im, path, format=None):
"""Save the image for testing.
"""
format = format or im.format
if not format:
_, format = splitext(path)
format = format[1:]
im.format = format.lower()
im.save(filename=path)
|
[
"def",
"_save_to",
"(",
"self",
",",
"im",
",",
"path",
",",
"format",
"=",
"None",
")",
":",
"format",
"=",
"format",
"or",
"im",
".",
"format",
"if",
"not",
"format",
":",
"_",
",",
"format",
"=",
"splitext",
"(",
"path",
")",
"format",
"=",
"format",
"[",
"1",
":",
"]",
"im",
".",
"format",
"=",
"format",
".",
"lower",
"(",
")",
"im",
".",
"save",
"(",
"filename",
"=",
"path",
")"
] |
Save the image for testing.
|
[
"Save",
"the",
"image",
"for",
"testing",
"."
] |
22694e5671b6adaccc4c9c87db7bdd701d20e734
|
https://github.com/jpscaletti/moar/blob/22694e5671b6adaccc4c9c87db7bdd701d20e734/moar/engines/wand_engine.py#L33-L41
|
242,939
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger._log
|
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
|
python
|
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
|
[
"def",
"_log",
"(",
"self",
",",
"priority",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arg",
"in",
"args",
":",
"message",
"=",
"message",
"+",
"\"\\n\"",
"+",
"self",
".",
"pretty_printer",
".",
"pformat",
"(",
"arg",
")",
"self",
".",
"logger",
".",
"log",
"(",
"priority",
",",
"message",
")"
] |
Generic log functions
|
[
"Generic",
"log",
"functions"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L70-L76
|
242,940
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.debug
|
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
|
python
|
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
|
[
"def",
"debug",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"DEBUG",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Debug level to use and abuse when coding
|
[
"Debug",
"level",
"to",
"use",
"and",
"abuse",
"when",
"coding"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L78-L81
|
242,941
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.warn
|
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
|
python
|
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
|
[
"def",
"warn",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"WARNING",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Send email and syslog by default ...
|
[
"Send",
"email",
"and",
"syslog",
"by",
"default",
"..."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L88-L91
|
242,942
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.warning
|
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
|
python
|
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
|
[
"def",
"warning",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"WARNING",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Alias to warn
|
[
"Alias",
"to",
"warn"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L93-L96
|
242,943
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.error
|
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
|
python
|
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
|
[
"def",
"error",
"(",
"self",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"logging",
".",
"ERROR",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Should not happen ...
|
[
"Should",
"not",
"happen",
"..."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L98-L101
|
242,944
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.init_logger
|
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
|
python
|
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
|
[
"def",
"init_logger",
"(",
"self",
")",
":",
"# All logs are comming to this logger",
"self",
".",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"self",
".",
"logger",
".",
"propagate",
"=",
"False",
"# Logging to console",
"if",
"self",
".",
"min_log_level_to_print",
":",
"level",
"=",
"self",
".",
"min_log_level_to_print",
"handler_class",
"=",
"logging",
".",
"StreamHandler",
"self",
".",
"_create_handler",
"(",
"handler_class",
",",
"level",
")",
"# Logging to file",
"if",
"self",
".",
"min_log_level_to_save",
":",
"level",
"=",
"self",
".",
"min_log_level_to_save",
"handler_class",
"=",
"logging",
".",
"handlers",
".",
"TimedRotatingFileHandler",
"self",
".",
"_create_handler",
"(",
"handler_class",
",",
"level",
")",
"# Logging to syslog",
"if",
"self",
".",
"min_log_level_to_syslog",
":",
"level",
"=",
"self",
".",
"min_log_level_to_syslog",
"handler_class",
"=",
"logging",
".",
"handlers",
".",
"SysLogHandler",
"self",
".",
"_create_handler",
"(",
"handler_class",
",",
"level",
")",
"# Logging to email",
"if",
"self",
".",
"min_log_level_to_mail",
":",
"level",
"=",
"self",
".",
"min_log_level_to_mail",
"handler_class",
"=",
"AlkiviEmailHandler",
"self",
".",
"_create_handler",
"(",
"handler_class",
",",
"level",
")",
"return"
] |
Create configuration for the root logger.
|
[
"Create",
"configuration",
"for",
"the",
"root",
"logger",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L113-L143
|
242,945
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.new_iteration
|
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
|
python
|
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
|
[
"def",
"new_iteration",
"(",
"self",
",",
"prefix",
")",
":",
"# Flush data for the current iteration",
"self",
".",
"flush",
"(",
")",
"# Fix prefix",
"self",
".",
"prefix",
"[",
"-",
"1",
"]",
"=",
"prefix",
"self",
".",
"reset_formatter",
"(",
")"
] |
When inside a loop logger, created a new iteration
|
[
"When",
"inside",
"a",
"loop",
"logger",
"created",
"a",
"new",
"iteration"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L168-L176
|
242,946
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.reset_formatter
|
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
|
python
|
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
|
[
"def",
"reset_formatter",
"(",
"self",
")",
":",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"formatter",
"=",
"self",
".",
"get_formatter",
"(",
"handler",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")"
] |
Rebuild formatter for all handlers.
|
[
"Rebuild",
"formatter",
"for",
"all",
"handlers",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L178-L182
|
242,947
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger._set_min_level
|
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
|
python
|
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
|
[
"def",
"_set_min_level",
"(",
"self",
",",
"handler_class",
",",
"level",
")",
":",
"if",
"self",
".",
"_exist_handler",
"(",
"handler_class",
")",
":",
"if",
"not",
"level",
":",
"self",
".",
"_delete_handler",
"(",
"handler_class",
")",
"else",
":",
"self",
".",
"_update_handler",
"(",
"handler_class",
",",
"level",
"=",
"level",
")",
"elif",
"level",
":",
"self",
".",
"_create_handler",
"(",
"handler_class",
",",
"level",
")"
] |
Generic method to setLevel for handlers.
|
[
"Generic",
"method",
"to",
"setLevel",
"for",
"handlers",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L189-L197
|
242,948
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.set_min_level_to_print
|
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
|
python
|
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
|
[
"def",
"set_min_level_to_print",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"min_log_level_to_print",
"=",
"level",
"handler_class",
"=",
"logging",
".",
"StreamHandler",
"self",
".",
"_set_min_level",
"(",
"handler_class",
",",
"level",
")"
] |
Allow to change print level after creation
|
[
"Allow",
"to",
"change",
"print",
"level",
"after",
"creation"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L199-L204
|
242,949
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.set_min_level_to_save
|
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
|
python
|
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
|
[
"def",
"set_min_level_to_save",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"min_log_level_to_save",
"=",
"level",
"handler_class",
"=",
"logging",
".",
"handlers",
".",
"TimedRotatingFileHandler",
"self",
".",
"_set_min_level",
"(",
"handler_class",
",",
"level",
")"
] |
Allow to change save level after creation
|
[
"Allow",
"to",
"change",
"save",
"level",
"after",
"creation"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L206-L211
|
242,950
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.set_min_level_to_mail
|
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
|
python
|
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
|
[
"def",
"set_min_level_to_mail",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"min_log_level_to_mail",
"=",
"level",
"handler_class",
"=",
"AlkiviEmailHandler",
"self",
".",
"_set_min_level",
"(",
"handler_class",
",",
"level",
")"
] |
Allow to change mail level after creation
|
[
"Allow",
"to",
"change",
"mail",
"level",
"after",
"creation"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L213-L218
|
242,951
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.set_min_level_to_syslog
|
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
|
python
|
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
|
[
"def",
"set_min_level_to_syslog",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"min_log_level_to_syslog",
"=",
"level",
"handler_class",
"=",
"logging",
".",
"handlers",
".",
"SysLogHandler",
"self",
".",
"_set_min_level",
"(",
"handler_class",
",",
"level",
")"
] |
Allow to change syslog level after creation
|
[
"Allow",
"to",
"change",
"syslog",
"level",
"after",
"creation"
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L220-L225
|
242,952
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger._get_handler
|
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
|
python
|
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
|
[
"def",
"_get_handler",
"(",
"self",
",",
"handler_class",
")",
":",
"element",
"=",
"None",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"if",
"isinstance",
"(",
"handler",
",",
"handler_class",
")",
":",
"element",
"=",
"handler",
"break",
"return",
"element"
] |
Return an existing class of handler.
|
[
"Return",
"an",
"existing",
"class",
"of",
"handler",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L227-L234
|
242,953
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger._delete_handler
|
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
|
python
|
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
|
[
"def",
"_delete_handler",
"(",
"self",
",",
"handler_class",
")",
":",
"to_remove",
"=",
"self",
".",
"_get_handler",
"(",
"handler_class",
")",
"if",
"not",
"to_remove",
":",
"logging",
".",
"warning",
"(",
"'Error we should have an element to remove'",
")",
"else",
":",
"self",
".",
"handlers",
".",
"remove",
"(",
"to_remove",
")",
"self",
".",
"logger",
".",
"removeHandler",
"(",
"to_remove",
")"
] |
Delete a specific handler from our logger.
|
[
"Delete",
"a",
"specific",
"handler",
"from",
"our",
"logger",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L240-L247
|
242,954
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger._update_handler
|
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
|
python
|
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
|
[
"def",
"_update_handler",
"(",
"self",
",",
"handler_class",
",",
"level",
")",
":",
"handler",
"=",
"self",
".",
"_get_handler",
"(",
"handler_class",
")",
"handler",
".",
"setLevel",
"(",
"level",
")"
] |
Update the level of an handler.
|
[
"Update",
"the",
"level",
"of",
"an",
"handler",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L249-L252
|
242,955
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger._create_handler
|
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
|
python
|
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
|
[
"def",
"_create_handler",
"(",
"self",
",",
"handler_class",
",",
"level",
")",
":",
"if",
"handler_class",
"==",
"logging",
".",
"StreamHandler",
":",
"handler",
"=",
"handler_class",
"(",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"elif",
"handler_class",
"==",
"logging",
".",
"handlers",
".",
"SysLogHandler",
":",
"handler",
"=",
"handler_class",
"(",
"address",
"=",
"'/dev/log'",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"elif",
"handler_class",
"==",
"logging",
".",
"handlers",
".",
"TimedRotatingFileHandler",
":",
"handler",
"=",
"handler_class",
"(",
"self",
".",
"filename",
",",
"when",
"=",
"'midnight'",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"elif",
"handler_class",
"==",
"AlkiviEmailHandler",
":",
"handler",
"=",
"handler_class",
"(",
"mailhost",
"=",
"'127.0.0.1'",
",",
"fromaddr",
"=",
"\"%s@%s\"",
"%",
"(",
"USER",
",",
"HOST",
")",
",",
"toaddrs",
"=",
"self",
".",
"emails",
",",
"level",
"=",
"self",
".",
"min_log_level_to_mail",
")",
"# Needed, we want all logs to go there",
"handler",
".",
"setLevel",
"(",
"0",
")",
"formatter",
"=",
"self",
".",
"get_formatter",
"(",
"handler",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"self",
".",
"handlers",
".",
"append",
"(",
"handler",
")",
"self",
".",
"logger",
".",
"addHandler",
"(",
"handler",
")"
] |
Create an handler for at specific level.
|
[
"Create",
"an",
"handler",
"for",
"at",
"specific",
"level",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L254-L276
|
242,956
|
alkivi-sas/python-alkivi-logger
|
alkivi/logger/logger.py
|
Logger.get_formatter
|
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
python
|
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
[
"def",
"get_formatter",
"(",
"self",
",",
"handler",
")",
":",
"if",
"isinstance",
"(",
"handler",
",",
"logging",
".",
"handlers",
".",
"SysLogHandler",
")",
":",
"formatter",
"=",
"'[%(levelname)-9s]'",
"else",
":",
"formatter",
"=",
"'[%(asctime)s] [%(levelname)-9s]'",
"for",
"p",
"in",
"self",
".",
"prefix",
":",
"formatter",
"+=",
"' [%s]'",
"%",
"(",
"p",
")",
"formatter",
"=",
"formatter",
"+",
"' %(message)s'",
"return",
"logging",
".",
"Formatter",
"(",
"formatter",
")"
] |
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
|
[
"Return",
"formatters",
"according",
"to",
"handler",
"."
] |
e96d5a987a5c8789c51d4fa7541709e05b1f51e1
|
https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L278-L293
|
242,957
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
version_control
|
def version_control():
"""Return an object that provides the version control interface based
on the detected version control system."""
curdir_contents = os.listdir('.')
if '.hg' in curdir_contents:
return hg.Hg()
elif '.git' in curdir_contents:
return git.Git()
else:
logger.critical('No version control system detected.')
sys.exit(1)
|
python
|
def version_control():
"""Return an object that provides the version control interface based
on the detected version control system."""
curdir_contents = os.listdir('.')
if '.hg' in curdir_contents:
return hg.Hg()
elif '.git' in curdir_contents:
return git.Git()
else:
logger.critical('No version control system detected.')
sys.exit(1)
|
[
"def",
"version_control",
"(",
")",
":",
"curdir_contents",
"=",
"os",
".",
"listdir",
"(",
"'.'",
")",
"if",
"'.hg'",
"in",
"curdir_contents",
":",
"return",
"hg",
".",
"Hg",
"(",
")",
"elif",
"'.git'",
"in",
"curdir_contents",
":",
"return",
"git",
".",
"Git",
"(",
")",
"else",
":",
"logger",
".",
"critical",
"(",
"'No version control system detected.'",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] |
Return an object that provides the version control interface based
on the detected version control system.
|
[
"Return",
"an",
"object",
"that",
"provides",
"the",
"version",
"control",
"interface",
"based",
"on",
"the",
"detected",
"version",
"control",
"system",
"."
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L24-L34
|
242,958
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
package_in_pypi
|
def package_in_pypi(package):
"""Check whether the package is registered on pypi"""
url = 'http://pypi.python.org/simple/%s' % package
try:
urllib.request.urlopen(url)
return True
except urllib.error.HTTPError as e:
logger.debug("Package not found on pypi: %s", e)
return False
|
python
|
def package_in_pypi(package):
"""Check whether the package is registered on pypi"""
url = 'http://pypi.python.org/simple/%s' % package
try:
urllib.request.urlopen(url)
return True
except urllib.error.HTTPError as e:
logger.debug("Package not found on pypi: %s", e)
return False
|
[
"def",
"package_in_pypi",
"(",
"package",
")",
":",
"url",
"=",
"'http://pypi.python.org/simple/%s'",
"%",
"package",
"try",
":",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
"return",
"True",
"except",
"urllib",
".",
"error",
".",
"HTTPError",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"Package not found on pypi: %s\"",
",",
"e",
")",
"return",
"False"
] |
Check whether the package is registered on pypi
|
[
"Check",
"whether",
"the",
"package",
"is",
"registered",
"on",
"pypi"
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L37-L45
|
242,959
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._grab_version
|
def _grab_version(self):
"""Set the version to a non-development version."""
original_version = self.vcs.version
logger.debug("Extracted version: %s", original_version)
if original_version is None:
logger.critical('No version found.')
sys.exit(1)
suggestion = utils.cleanup_version(original_version)
new_version = utils.ask_version("Enter version", default=suggestion)
if not new_version:
new_version = suggestion
self.data['original_version'] = original_version
self.data['new_version'] = new_version
|
python
|
def _grab_version(self):
"""Set the version to a non-development version."""
original_version = self.vcs.version
logger.debug("Extracted version: %s", original_version)
if original_version is None:
logger.critical('No version found.')
sys.exit(1)
suggestion = utils.cleanup_version(original_version)
new_version = utils.ask_version("Enter version", default=suggestion)
if not new_version:
new_version = suggestion
self.data['original_version'] = original_version
self.data['new_version'] = new_version
|
[
"def",
"_grab_version",
"(",
"self",
")",
":",
"original_version",
"=",
"self",
".",
"vcs",
".",
"version",
"logger",
".",
"debug",
"(",
"\"Extracted version: %s\"",
",",
"original_version",
")",
"if",
"original_version",
"is",
"None",
":",
"logger",
".",
"critical",
"(",
"'No version found.'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"suggestion",
"=",
"utils",
".",
"cleanup_version",
"(",
"original_version",
")",
"new_version",
"=",
"utils",
".",
"ask_version",
"(",
"\"Enter version\"",
",",
"default",
"=",
"suggestion",
")",
"if",
"not",
"new_version",
":",
"new_version",
"=",
"suggestion",
"self",
".",
"data",
"[",
"'original_version'",
"]",
"=",
"original_version",
"self",
".",
"data",
"[",
"'new_version'",
"]",
"=",
"new_version"
] |
Set the version to a non-development version.
|
[
"Set",
"the",
"version",
"to",
"a",
"non",
"-",
"development",
"version",
"."
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L65-L77
|
242,960
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._write_history
|
def _write_history(self):
"""Write previously-calculated history lines back to the file"""
if self.data['history_file'] is None:
return
contents = '\n'.join(self.data['history_lines'])
history = self.data['history_file']
open(history, 'w').write(contents)
logger.info("History file %s updated.", history)
|
python
|
def _write_history(self):
"""Write previously-calculated history lines back to the file"""
if self.data['history_file'] is None:
return
contents = '\n'.join(self.data['history_lines'])
history = self.data['history_file']
open(history, 'w').write(contents)
logger.info("History file %s updated.", history)
|
[
"def",
"_write_history",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
"[",
"'history_file'",
"]",
"is",
"None",
":",
"return",
"contents",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"data",
"[",
"'history_lines'",
"]",
")",
"history",
"=",
"self",
".",
"data",
"[",
"'history_file'",
"]",
"open",
"(",
"history",
",",
"'w'",
")",
".",
"write",
"(",
"contents",
")",
"logger",
".",
"info",
"(",
"\"History file %s updated.\"",
",",
"history",
")"
] |
Write previously-calculated history lines back to the file
|
[
"Write",
"previously",
"-",
"calculated",
"history",
"lines",
"back",
"to",
"the",
"file"
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L128-L135
|
242,961
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._check_if_tag_already_exists
|
def _check_if_tag_already_exists(self):
"""Check if tag already exists and show the difference if so"""
version = self.data['new_version']
if self.vcs.tag_exists(version):
return True
else:
return False
|
python
|
def _check_if_tag_already_exists(self):
"""Check if tag already exists and show the difference if so"""
version = self.data['new_version']
if self.vcs.tag_exists(version):
return True
else:
return False
|
[
"def",
"_check_if_tag_already_exists",
"(",
"self",
")",
":",
"version",
"=",
"self",
".",
"data",
"[",
"'new_version'",
"]",
"if",
"self",
".",
"vcs",
".",
"tag_exists",
"(",
"version",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] |
Check if tag already exists and show the difference if so
|
[
"Check",
"if",
"tag",
"already",
"exists",
"and",
"show",
"the",
"difference",
"if",
"so"
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L147-L153
|
242,962
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._release
|
def _release(self):
"""Upload the release, when desired"""
pypiconfig = pypi.PypiConfig()
# Does the user normally want a real release? We are
# interested in getting a sane default answer here, so you can
# override it in the exceptional case but just hit Enter in
# the usual case.
main_files = os.listdir(self.data['workingdir'])
if 'setup.py' not in main_files and 'setup.cfg' not in main_files:
# Neither setup.py nor setup.cfg, so this is no python
# package, so at least a pypi release is not useful.
# Expected case: this is a buildout directory.
default_answer = False
else:
default_answer = pypiconfig.want_release()
if not utils.ask("Check out the tag (for tweaks or pypi/distutils "
"server upload)", default=default_answer):
return
package = self.vcs.name
version = self.data['new_version']
logger.info("Doing a checkout...")
self.vcs.checkout_from_tag(version)
self.data['tagdir'] = os.path.realpath(os.getcwd())
logger.info("Tag checkout placed in %s", self.data['tagdir'])
# Possibly fix setup.cfg.
if self.setup_cfg.has_bad_commands():
logger.info("This is not advisable for a release.")
if utils.ask("Fix %s (and commit to tag if possible)" %
self.setup_cfg.config_filename, default=True):
# Fix the setup.cfg in the current working directory
# so the current release works well.
self.setup_cfg.fix_config()
sdist_options = self._sdist_options()
if 'setup.py' in os.listdir(self.data['tagdir']):
self._upload_distributions(package, sdist_options, pypiconfig)
# Make sure we are in the expected directory again.
os.chdir(self.vcs.workingdir)
|
python
|
def _release(self):
"""Upload the release, when desired"""
pypiconfig = pypi.PypiConfig()
# Does the user normally want a real release? We are
# interested in getting a sane default answer here, so you can
# override it in the exceptional case but just hit Enter in
# the usual case.
main_files = os.listdir(self.data['workingdir'])
if 'setup.py' not in main_files and 'setup.cfg' not in main_files:
# Neither setup.py nor setup.cfg, so this is no python
# package, so at least a pypi release is not useful.
# Expected case: this is a buildout directory.
default_answer = False
else:
default_answer = pypiconfig.want_release()
if not utils.ask("Check out the tag (for tweaks or pypi/distutils "
"server upload)", default=default_answer):
return
package = self.vcs.name
version = self.data['new_version']
logger.info("Doing a checkout...")
self.vcs.checkout_from_tag(version)
self.data['tagdir'] = os.path.realpath(os.getcwd())
logger.info("Tag checkout placed in %s", self.data['tagdir'])
# Possibly fix setup.cfg.
if self.setup_cfg.has_bad_commands():
logger.info("This is not advisable for a release.")
if utils.ask("Fix %s (and commit to tag if possible)" %
self.setup_cfg.config_filename, default=True):
# Fix the setup.cfg in the current working directory
# so the current release works well.
self.setup_cfg.fix_config()
sdist_options = self._sdist_options()
if 'setup.py' in os.listdir(self.data['tagdir']):
self._upload_distributions(package, sdist_options, pypiconfig)
# Make sure we are in the expected directory again.
os.chdir(self.vcs.workingdir)
|
[
"def",
"_release",
"(",
"self",
")",
":",
"pypiconfig",
"=",
"pypi",
".",
"PypiConfig",
"(",
")",
"# Does the user normally want a real release? We are",
"# interested in getting a sane default answer here, so you can",
"# override it in the exceptional case but just hit Enter in",
"# the usual case.",
"main_files",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"data",
"[",
"'workingdir'",
"]",
")",
"if",
"'setup.py'",
"not",
"in",
"main_files",
"and",
"'setup.cfg'",
"not",
"in",
"main_files",
":",
"# Neither setup.py nor setup.cfg, so this is no python",
"# package, so at least a pypi release is not useful.",
"# Expected case: this is a buildout directory.",
"default_answer",
"=",
"False",
"else",
":",
"default_answer",
"=",
"pypiconfig",
".",
"want_release",
"(",
")",
"if",
"not",
"utils",
".",
"ask",
"(",
"\"Check out the tag (for tweaks or pypi/distutils \"",
"\"server upload)\"",
",",
"default",
"=",
"default_answer",
")",
":",
"return",
"package",
"=",
"self",
".",
"vcs",
".",
"name",
"version",
"=",
"self",
".",
"data",
"[",
"'new_version'",
"]",
"logger",
".",
"info",
"(",
"\"Doing a checkout...\"",
")",
"self",
".",
"vcs",
".",
"checkout_from_tag",
"(",
"version",
")",
"self",
".",
"data",
"[",
"'tagdir'",
"]",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"logger",
".",
"info",
"(",
"\"Tag checkout placed in %s\"",
",",
"self",
".",
"data",
"[",
"'tagdir'",
"]",
")",
"# Possibly fix setup.cfg.",
"if",
"self",
".",
"setup_cfg",
".",
"has_bad_commands",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"This is not advisable for a release.\"",
")",
"if",
"utils",
".",
"ask",
"(",
"\"Fix %s (and commit to tag if possible)\"",
"%",
"self",
".",
"setup_cfg",
".",
"config_filename",
",",
"default",
"=",
"True",
")",
":",
"# Fix the setup.cfg in the current working directory",
"# so the current release works well.",
"self",
".",
"setup_cfg",
".",
"fix_config",
"(",
")",
"sdist_options",
"=",
"self",
".",
"_sdist_options",
"(",
")",
"if",
"'setup.py'",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"data",
"[",
"'tagdir'",
"]",
")",
":",
"self",
".",
"_upload_distributions",
"(",
"package",
",",
"sdist_options",
",",
"pypiconfig",
")",
"# Make sure we are in the expected directory again.",
"os",
".",
"chdir",
"(",
"self",
".",
"vcs",
".",
"workingdir",
")"
] |
Upload the release, when desired
|
[
"Upload",
"the",
"release",
"when",
"desired"
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L250-L294
|
242,963
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._update_version
|
def _update_version(self):
"""Ask for and store a new dev version string."""
#current = self.vcs.version
current = self.data['new_version']
# Clean it up to a non-development version.
current = utils.cleanup_version(current)
# Try to make sure that the suggestion for next version after
# 1.1.19 is not 1.1.110, but 1.1.20.
current_split = current.split('.')
major = '.'.join(current_split[:-1])
minor = current_split[-1]
try:
minor = int(minor) + 1
suggestion = '.'.join([major, str(minor)])
except ValueError:
# Fall back on simply updating the last character when it is
# an integer.
try:
last = int(current[-1]) + 1
suggestion = current[:-1] + str(last)
except ValueError:
logger.warn("Version does not end with a number, so we can't "
"calculate a suggestion for a next version.")
suggestion = None
print("Current version is %r" % current)
q = "Enter new development version ('.dev0' will be appended)"
version = utils.ask_version(q, default=suggestion)
if not version:
version = suggestion
if not version:
logger.error("No version entered.")
sys.exit()
self.data['new_version'] = version
dev_version = self.data['dev_version_template'] % self.data
self.data['dev_version'] = dev_version
logger.info("New version string is %r",
dev_version)
self.vcs.version = self.data['dev_version']
|
python
|
def _update_version(self):
"""Ask for and store a new dev version string."""
#current = self.vcs.version
current = self.data['new_version']
# Clean it up to a non-development version.
current = utils.cleanup_version(current)
# Try to make sure that the suggestion for next version after
# 1.1.19 is not 1.1.110, but 1.1.20.
current_split = current.split('.')
major = '.'.join(current_split[:-1])
minor = current_split[-1]
try:
minor = int(minor) + 1
suggestion = '.'.join([major, str(minor)])
except ValueError:
# Fall back on simply updating the last character when it is
# an integer.
try:
last = int(current[-1]) + 1
suggestion = current[:-1] + str(last)
except ValueError:
logger.warn("Version does not end with a number, so we can't "
"calculate a suggestion for a next version.")
suggestion = None
print("Current version is %r" % current)
q = "Enter new development version ('.dev0' will be appended)"
version = utils.ask_version(q, default=suggestion)
if not version:
version = suggestion
if not version:
logger.error("No version entered.")
sys.exit()
self.data['new_version'] = version
dev_version = self.data['dev_version_template'] % self.data
self.data['dev_version'] = dev_version
logger.info("New version string is %r",
dev_version)
self.vcs.version = self.data['dev_version']
|
[
"def",
"_update_version",
"(",
"self",
")",
":",
"#current = self.vcs.version",
"current",
"=",
"self",
".",
"data",
"[",
"'new_version'",
"]",
"# Clean it up to a non-development version.",
"current",
"=",
"utils",
".",
"cleanup_version",
"(",
"current",
")",
"# Try to make sure that the suggestion for next version after",
"# 1.1.19 is not 1.1.110, but 1.1.20.",
"current_split",
"=",
"current",
".",
"split",
"(",
"'.'",
")",
"major",
"=",
"'.'",
".",
"join",
"(",
"current_split",
"[",
":",
"-",
"1",
"]",
")",
"minor",
"=",
"current_split",
"[",
"-",
"1",
"]",
"try",
":",
"minor",
"=",
"int",
"(",
"minor",
")",
"+",
"1",
"suggestion",
"=",
"'.'",
".",
"join",
"(",
"[",
"major",
",",
"str",
"(",
"minor",
")",
"]",
")",
"except",
"ValueError",
":",
"# Fall back on simply updating the last character when it is",
"# an integer.",
"try",
":",
"last",
"=",
"int",
"(",
"current",
"[",
"-",
"1",
"]",
")",
"+",
"1",
"suggestion",
"=",
"current",
"[",
":",
"-",
"1",
"]",
"+",
"str",
"(",
"last",
")",
"except",
"ValueError",
":",
"logger",
".",
"warn",
"(",
"\"Version does not end with a number, so we can't \"",
"\"calculate a suggestion for a next version.\"",
")",
"suggestion",
"=",
"None",
"print",
"(",
"\"Current version is %r\"",
"%",
"current",
")",
"q",
"=",
"\"Enter new development version ('.dev0' will be appended)\"",
"version",
"=",
"utils",
".",
"ask_version",
"(",
"q",
",",
"default",
"=",
"suggestion",
")",
"if",
"not",
"version",
":",
"version",
"=",
"suggestion",
"if",
"not",
"version",
":",
"logger",
".",
"error",
"(",
"\"No version entered.\"",
")",
"sys",
".",
"exit",
"(",
")",
"self",
".",
"data",
"[",
"'new_version'",
"]",
"=",
"version",
"dev_version",
"=",
"self",
".",
"data",
"[",
"'dev_version_template'",
"]",
"%",
"self",
".",
"data",
"self",
".",
"data",
"[",
"'dev_version'",
"]",
"=",
"dev_version",
"logger",
".",
"info",
"(",
"\"New version string is %r\"",
",",
"dev_version",
")",
"self",
".",
"vcs",
".",
"version",
"=",
"self",
".",
"data",
"[",
"'dev_version'",
"]"
] |
Ask for and store a new dev version string.
|
[
"Ask",
"for",
"and",
"store",
"a",
"new",
"dev",
"version",
"string",
"."
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L296-L336
|
242,964
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._update_history
|
def _update_history(self):
"""Update the history file"""
version = self.data['new_version']
history = self.vcs.history_file()
if not history:
logger.warn("No history file found")
return
history_lines = open(history).read().split('\n')
headings = utils.extract_headings_from_history(history_lines)
if not len(headings):
logger.warn("No detectable existing version headings in the "
"history file.")
inject_location = 0
underline_char = '-'
else:
first = headings[0]
inject_location = first['line']
underline_line = first['line'] + 1
try:
underline_char = history_lines[underline_line][0]
except IndexError:
logger.debug("No character on line below header.")
underline_char = '-'
header = '%s (unreleased)' % version
inject = [header,
underline_char * len(header),
'',
self.data['nothing_changed_yet'],
'',
'']
history_lines[inject_location:inject_location] = inject
contents = '\n'.join(history_lines)
open(history, 'w').write(contents)
logger.info("Injected new section into the history: %r", header)
|
python
|
def _update_history(self):
"""Update the history file"""
version = self.data['new_version']
history = self.vcs.history_file()
if not history:
logger.warn("No history file found")
return
history_lines = open(history).read().split('\n')
headings = utils.extract_headings_from_history(history_lines)
if not len(headings):
logger.warn("No detectable existing version headings in the "
"history file.")
inject_location = 0
underline_char = '-'
else:
first = headings[0]
inject_location = first['line']
underline_line = first['line'] + 1
try:
underline_char = history_lines[underline_line][0]
except IndexError:
logger.debug("No character on line below header.")
underline_char = '-'
header = '%s (unreleased)' % version
inject = [header,
underline_char * len(header),
'',
self.data['nothing_changed_yet'],
'',
'']
history_lines[inject_location:inject_location] = inject
contents = '\n'.join(history_lines)
open(history, 'w').write(contents)
logger.info("Injected new section into the history: %r", header)
|
[
"def",
"_update_history",
"(",
"self",
")",
":",
"version",
"=",
"self",
".",
"data",
"[",
"'new_version'",
"]",
"history",
"=",
"self",
".",
"vcs",
".",
"history_file",
"(",
")",
"if",
"not",
"history",
":",
"logger",
".",
"warn",
"(",
"\"No history file found\"",
")",
"return",
"history_lines",
"=",
"open",
"(",
"history",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"headings",
"=",
"utils",
".",
"extract_headings_from_history",
"(",
"history_lines",
")",
"if",
"not",
"len",
"(",
"headings",
")",
":",
"logger",
".",
"warn",
"(",
"\"No detectable existing version headings in the \"",
"\"history file.\"",
")",
"inject_location",
"=",
"0",
"underline_char",
"=",
"'-'",
"else",
":",
"first",
"=",
"headings",
"[",
"0",
"]",
"inject_location",
"=",
"first",
"[",
"'line'",
"]",
"underline_line",
"=",
"first",
"[",
"'line'",
"]",
"+",
"1",
"try",
":",
"underline_char",
"=",
"history_lines",
"[",
"underline_line",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"logger",
".",
"debug",
"(",
"\"No character on line below header.\"",
")",
"underline_char",
"=",
"'-'",
"header",
"=",
"'%s (unreleased)'",
"%",
"version",
"inject",
"=",
"[",
"header",
",",
"underline_char",
"*",
"len",
"(",
"header",
")",
",",
"''",
",",
"self",
".",
"data",
"[",
"'nothing_changed_yet'",
"]",
",",
"''",
",",
"''",
"]",
"history_lines",
"[",
"inject_location",
":",
"inject_location",
"]",
"=",
"inject",
"contents",
"=",
"'\\n'",
".",
"join",
"(",
"history_lines",
")",
"open",
"(",
"history",
",",
"'w'",
")",
".",
"write",
"(",
"contents",
")",
"logger",
".",
"info",
"(",
"\"Injected new section into the history: %r\"",
",",
"header",
")"
] |
Update the history file
|
[
"Update",
"the",
"history",
"file"
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L338-L371
|
242,965
|
jlesquembre/jlle
|
jlle/releaser/release.py
|
Releaser._push
|
def _push(self):
"""Offer to push changes, if needed."""
push_cmds = self.vcs.push_commands()
if not push_cmds:
return
if utils.ask("OK to push commits to the server?"):
for push_cmd in push_cmds:
output = utils.system(push_cmd)
logger.info(output)
|
python
|
def _push(self):
"""Offer to push changes, if needed."""
push_cmds = self.vcs.push_commands()
if not push_cmds:
return
if utils.ask("OK to push commits to the server?"):
for push_cmd in push_cmds:
output = utils.system(push_cmd)
logger.info(output)
|
[
"def",
"_push",
"(",
"self",
")",
":",
"push_cmds",
"=",
"self",
".",
"vcs",
".",
"push_commands",
"(",
")",
"if",
"not",
"push_cmds",
":",
"return",
"if",
"utils",
".",
"ask",
"(",
"\"OK to push commits to the server?\"",
")",
":",
"for",
"push_cmd",
"in",
"push_cmds",
":",
"output",
"=",
"utils",
".",
"system",
"(",
"push_cmd",
")",
"logger",
".",
"info",
"(",
"output",
")"
] |
Offer to push changes, if needed.
|
[
"Offer",
"to",
"push",
"changes",
"if",
"needed",
"."
] |
3645d8f203708355853ef911f4b887ae4d794826
|
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/release.py#L373-L382
|
242,966
|
Apitax/Apitax
|
apitax/api/controllers/apitax_controller.py
|
get_user
|
def get_user(user, driver): # noqa: E501
"""Retrieve a user
Retrieve a user # noqa: E501
:param user: Get user with this name
:type user: str
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response
"""
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
user: User = driver.getApitaxUser(User(username=user))
response.body.add({'user': {'username': user.username, 'role': user.role}})
return Response(status=200, body=response.getResponseBody())
|
python
|
def get_user(user, driver): # noqa: E501
"""Retrieve a user
Retrieve a user # noqa: E501
:param user: Get user with this name
:type user: str
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response
"""
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
user: User = driver.getApitaxUser(User(username=user))
response.body.add({'user': {'username': user.username, 'role': user.role}})
return Response(status=200, body=response.getResponseBody())
|
[
"def",
"get_user",
"(",
"user",
",",
"driver",
")",
":",
"# noqa: E501",
"response",
"=",
"ApitaxResponse",
"(",
")",
"driver",
":",
"Driver",
"=",
"LoadedDrivers",
".",
"getDriver",
"(",
"driver",
")",
"user",
":",
"User",
"=",
"driver",
".",
"getApitaxUser",
"(",
"User",
"(",
"username",
"=",
"user",
")",
")",
"response",
".",
"body",
".",
"add",
"(",
"{",
"'user'",
":",
"{",
"'username'",
":",
"user",
".",
"username",
",",
"'role'",
":",
"user",
".",
"role",
"}",
"}",
")",
"return",
"Response",
"(",
"status",
"=",
"200",
",",
"body",
"=",
"response",
".",
"getResponseBody",
"(",
")",
")"
] |
Retrieve a user
Retrieve a user # noqa: E501
:param user: Get user with this name
:type user: str
:param driver: The driver to use for the request. ie. github
:type driver: str
:rtype: Response
|
[
"Retrieve",
"a",
"user"
] |
3883e45f17e01eba4edac9d1bba42f0e7a748682
|
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/apitax_controller.py#L146-L165
|
242,967
|
joaopcanario/imports
|
imports/cli.py
|
main
|
def main(path_dir, requirements_name):
"""Console script for imports."""
click.echo("\nWARNING: Uninstall libs it's at your own risk!")
click.echo('\nREMINDER: After uninstall libs, update your requirements '
'file.\nUse the `pip freeze > requirements.txt` command.')
click.echo('\n\nList of installed libs and your dependencies added on '
'project\nrequirements that are not being used:\n')
check(path_dir, requirements_name)
|
python
|
def main(path_dir, requirements_name):
"""Console script for imports."""
click.echo("\nWARNING: Uninstall libs it's at your own risk!")
click.echo('\nREMINDER: After uninstall libs, update your requirements '
'file.\nUse the `pip freeze > requirements.txt` command.')
click.echo('\n\nList of installed libs and your dependencies added on '
'project\nrequirements that are not being used:\n')
check(path_dir, requirements_name)
|
[
"def",
"main",
"(",
"path_dir",
",",
"requirements_name",
")",
":",
"click",
".",
"echo",
"(",
"\"\\nWARNING: Uninstall libs it's at your own risk!\"",
")",
"click",
".",
"echo",
"(",
"'\\nREMINDER: After uninstall libs, update your requirements '",
"'file.\\nUse the `pip freeze > requirements.txt` command.'",
")",
"click",
".",
"echo",
"(",
"'\\n\\nList of installed libs and your dependencies added on '",
"'project\\nrequirements that are not being used:\\n'",
")",
"check",
"(",
"path_dir",
",",
"requirements_name",
")"
] |
Console script for imports.
|
[
"Console",
"script",
"for",
"imports",
"."
] |
46db0d3d2aa55427027bf0e91d61a24d52730337
|
https://github.com/joaopcanario/imports/blob/46db0d3d2aa55427027bf0e91d61a24d52730337/imports/cli.py#L13-L22
|
242,968
|
smartmob-project/strawboss
|
strawboss/__init__.py
|
now
|
def now(utc=False):
"""Returns the current time.
:param utc: If ``True``, returns a timezone-aware ``datetime`` object in
UTC. When ``False`` (the default), returns a naive ``datetime`` object
in local time.
:return: A ``datetime`` object representing the current time at the time of
the call.
"""
if utc:
return datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
else:
return datetime.datetime.now()
|
python
|
def now(utc=False):
"""Returns the current time.
:param utc: If ``True``, returns a timezone-aware ``datetime`` object in
UTC. When ``False`` (the default), returns a naive ``datetime`` object
in local time.
:return: A ``datetime`` object representing the current time at the time of
the call.
"""
if utc:
return datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
else:
return datetime.datetime.now()
|
[
"def",
"now",
"(",
"utc",
"=",
"False",
")",
":",
"if",
"utc",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"dateutil",
".",
"tz",
".",
"tzutc",
"(",
")",
")",
"else",
":",
"return",
"datetime",
".",
"datetime",
".",
"now",
"(",
")"
] |
Returns the current time.
:param utc: If ``True``, returns a timezone-aware ``datetime`` object in
UTC. When ``False`` (the default), returns a naive ``datetime`` object
in local time.
:return: A ``datetime`` object representing the current time at the time of
the call.
|
[
"Returns",
"the",
"current",
"time",
"."
] |
b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc
|
https://github.com/smartmob-project/strawboss/blob/b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc/strawboss/__init__.py#L22-L34
|
242,969
|
smartmob-project/strawboss
|
strawboss/__init__.py
|
merge_envs
|
def merge_envs(*args):
"""Union of one or more dictionaries.
In case of duplicate keys, the values in the right-most arguments will
squash (overwrite) the value provided by any dict preceding it.
:param args: Sequence of ``dict`` objects that should be merged.
:return: A ``dict`` containing the union of keys in all input dicts.
"""
env = {}
for arg in args:
if not arg:
continue
env.update(arg)
return env
|
python
|
def merge_envs(*args):
"""Union of one or more dictionaries.
In case of duplicate keys, the values in the right-most arguments will
squash (overwrite) the value provided by any dict preceding it.
:param args: Sequence of ``dict`` objects that should be merged.
:return: A ``dict`` containing the union of keys in all input dicts.
"""
env = {}
for arg in args:
if not arg:
continue
env.update(arg)
return env
|
[
"def",
"merge_envs",
"(",
"*",
"args",
")",
":",
"env",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"arg",
":",
"continue",
"env",
".",
"update",
"(",
"arg",
")",
"return",
"env"
] |
Union of one or more dictionaries.
In case of duplicate keys, the values in the right-most arguments will
squash (overwrite) the value provided by any dict preceding it.
:param args: Sequence of ``dict`` objects that should be merged.
:return: A ``dict`` containing the union of keys in all input dicts.
|
[
"Union",
"of",
"one",
"or",
"more",
"dictionaries",
"."
] |
b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc
|
https://github.com/smartmob-project/strawboss/blob/b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc/strawboss/__init__.py#L66-L81
|
242,970
|
smartmob-project/strawboss
|
strawboss/__init__.py
|
run_once
|
def run_once(name, cmd, env, shutdown, loop=None, utc=False):
"""Starts a child process and waits for its completion.
.. note:: This function is a coroutine.
Standard output and error streams are captured and forwarded to the parent
process' standard output. Each line is prefixed with the current time (as
measured by the parent process) and the child process ``name``.
:param name: Label for the child process. Will be used as a prefix to all
lines captured by this child process.
:param cmd: Command-line that will be used to invoke the child process.
Can be a string or sequence of strings. When a string is passed,
``shlex.split()`` will be used to break it into a sequence of strings
with smart quoting analysis. If this does not give the intended
results, break it down as you see fit and pass a sequence of strings.
:param env: Environment variables that should be injected in the child
process. If ``None``, the parent's environment will be inherited as it.
If a ``dict`` is provided, this will overwrite the entire environment;
it is the caller's responsibility to merge this with the parent's
environment if they see fit.
:param shutdown: Future that the caller will fulfill to indicate that the
process should be killed early. When this is set, the process is sent
SIGINT and then is let complete naturally.
:param loop: Event loop to use. When ``None``, the default event loop is
used.
:param utc: When ``True``, the timestamps are logged using the current time
in UTC.
:return: A future that will be completed when the process has completed.
Upon completion, the future's result will contain the process' exit
status.
"""
# Get the default event loop if necessary.
loop = loop or asyncio.get_event_loop()
# Launch the command into a child process.
if isinstance(cmd, str):
cmd = shlex.split(cmd)
process = yield from asyncio.create_subprocess_exec(
*cmd,
env=env,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
print('%s [strawboss] %s(%d) spawned.' % (
now(utc).isoformat(), name, process.pid
))
# Exhaust the child's standard output stream.
#
# TODO: close stdin for new process.
# TODO: terminate the process after the grace period.
ready = asyncio.ensure_future(process.wait())
pending = {
shutdown,
ready,
asyncio.ensure_future(process.stdout.readline()),
}
while not ready.done():
done, pending = yield from asyncio.wait(
pending,
return_when=asyncio.FIRST_COMPLETED,
)
for future in done:
# React to a request to shutdown the process.
#
# NOTE: shutdown is asynchronous unless the process completion
# notification is "in flight". We forward the request to
# shutdown and then wait until the child process completes.
if future is shutdown:
try:
process.kill()
except ProcessLookupError:
pass
else:
print('%s [strawboss] %s(%d) killed.' % (
now(utc).isoformat(), name, process.pid
))
continue
# React to process death (natural, killed or terminated).
if future is ready:
exit_code = yield from future
print('%s [strawboss] %s(%d) completed with exit status %d.' % (
now(utc).isoformat(), name, process.pid, exit_code
))
continue
# React to stdout having a full line of text.
data = yield from future
if not data:
print('%s [strawboss] EOF from %s(%d).' % (
now(utc).isoformat(), name, process.pid,
))
continue
data = data.decode('utf-8').strip()
print('%s [%s] %s' % (
now(utc).isoformat(), name, data
))
pending.add(asyncio.ensure_future(process.stdout.readline()))
# Cancel any remaining tasks (e.g. readline).
for future in pending:
if future is shutdown:
continue
future.cancel()
# Pass the exit code back to the caller.
return exit_code
|
python
|
def run_once(name, cmd, env, shutdown, loop=None, utc=False):
"""Starts a child process and waits for its completion.
.. note:: This function is a coroutine.
Standard output and error streams are captured and forwarded to the parent
process' standard output. Each line is prefixed with the current time (as
measured by the parent process) and the child process ``name``.
:param name: Label for the child process. Will be used as a prefix to all
lines captured by this child process.
:param cmd: Command-line that will be used to invoke the child process.
Can be a string or sequence of strings. When a string is passed,
``shlex.split()`` will be used to break it into a sequence of strings
with smart quoting analysis. If this does not give the intended
results, break it down as you see fit and pass a sequence of strings.
:param env: Environment variables that should be injected in the child
process. If ``None``, the parent's environment will be inherited as it.
If a ``dict`` is provided, this will overwrite the entire environment;
it is the caller's responsibility to merge this with the parent's
environment if they see fit.
:param shutdown: Future that the caller will fulfill to indicate that the
process should be killed early. When this is set, the process is sent
SIGINT and then is let complete naturally.
:param loop: Event loop to use. When ``None``, the default event loop is
used.
:param utc: When ``True``, the timestamps are logged using the current time
in UTC.
:return: A future that will be completed when the process has completed.
Upon completion, the future's result will contain the process' exit
status.
"""
# Get the default event loop if necessary.
loop = loop or asyncio.get_event_loop()
# Launch the command into a child process.
if isinstance(cmd, str):
cmd = shlex.split(cmd)
process = yield from asyncio.create_subprocess_exec(
*cmd,
env=env,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
print('%s [strawboss] %s(%d) spawned.' % (
now(utc).isoformat(), name, process.pid
))
# Exhaust the child's standard output stream.
#
# TODO: close stdin for new process.
# TODO: terminate the process after the grace period.
ready = asyncio.ensure_future(process.wait())
pending = {
shutdown,
ready,
asyncio.ensure_future(process.stdout.readline()),
}
while not ready.done():
done, pending = yield from asyncio.wait(
pending,
return_when=asyncio.FIRST_COMPLETED,
)
for future in done:
# React to a request to shutdown the process.
#
# NOTE: shutdown is asynchronous unless the process completion
# notification is "in flight". We forward the request to
# shutdown and then wait until the child process completes.
if future is shutdown:
try:
process.kill()
except ProcessLookupError:
pass
else:
print('%s [strawboss] %s(%d) killed.' % (
now(utc).isoformat(), name, process.pid
))
continue
# React to process death (natural, killed or terminated).
if future is ready:
exit_code = yield from future
print('%s [strawboss] %s(%d) completed with exit status %d.' % (
now(utc).isoformat(), name, process.pid, exit_code
))
continue
# React to stdout having a full line of text.
data = yield from future
if not data:
print('%s [strawboss] EOF from %s(%d).' % (
now(utc).isoformat(), name, process.pid,
))
continue
data = data.decode('utf-8').strip()
print('%s [%s] %s' % (
now(utc).isoformat(), name, data
))
pending.add(asyncio.ensure_future(process.stdout.readline()))
# Cancel any remaining tasks (e.g. readline).
for future in pending:
if future is shutdown:
continue
future.cancel()
# Pass the exit code back to the caller.
return exit_code
|
[
"def",
"run_once",
"(",
"name",
",",
"cmd",
",",
"env",
",",
"shutdown",
",",
"loop",
"=",
"None",
",",
"utc",
"=",
"False",
")",
":",
"# Get the default event loop if necessary.",
"loop",
"=",
"loop",
"or",
"asyncio",
".",
"get_event_loop",
"(",
")",
"# Launch the command into a child process.",
"if",
"isinstance",
"(",
"cmd",
",",
"str",
")",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"process",
"=",
"yield",
"from",
"asyncio",
".",
"create_subprocess_exec",
"(",
"*",
"cmd",
",",
"env",
"=",
"env",
",",
"stdin",
"=",
"asyncio",
".",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"asyncio",
".",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"asyncio",
".",
"subprocess",
".",
"STDOUT",
",",
")",
"print",
"(",
"'%s [strawboss] %s(%d) spawned.'",
"%",
"(",
"now",
"(",
"utc",
")",
".",
"isoformat",
"(",
")",
",",
"name",
",",
"process",
".",
"pid",
")",
")",
"# Exhaust the child's standard output stream.",
"#",
"# TODO: close stdin for new process.",
"# TODO: terminate the process after the grace period.",
"ready",
"=",
"asyncio",
".",
"ensure_future",
"(",
"process",
".",
"wait",
"(",
")",
")",
"pending",
"=",
"{",
"shutdown",
",",
"ready",
",",
"asyncio",
".",
"ensure_future",
"(",
"process",
".",
"stdout",
".",
"readline",
"(",
")",
")",
",",
"}",
"while",
"not",
"ready",
".",
"done",
"(",
")",
":",
"done",
",",
"pending",
"=",
"yield",
"from",
"asyncio",
".",
"wait",
"(",
"pending",
",",
"return_when",
"=",
"asyncio",
".",
"FIRST_COMPLETED",
",",
")",
"for",
"future",
"in",
"done",
":",
"# React to a request to shutdown the process.",
"#",
"# NOTE: shutdown is asynchronous unless the process completion",
"# notification is \"in flight\". We forward the request to",
"# shutdown and then wait until the child process completes.",
"if",
"future",
"is",
"shutdown",
":",
"try",
":",
"process",
".",
"kill",
"(",
")",
"except",
"ProcessLookupError",
":",
"pass",
"else",
":",
"print",
"(",
"'%s [strawboss] %s(%d) killed.'",
"%",
"(",
"now",
"(",
"utc",
")",
".",
"isoformat",
"(",
")",
",",
"name",
",",
"process",
".",
"pid",
")",
")",
"continue",
"# React to process death (natural, killed or terminated).",
"if",
"future",
"is",
"ready",
":",
"exit_code",
"=",
"yield",
"from",
"future",
"print",
"(",
"'%s [strawboss] %s(%d) completed with exit status %d.'",
"%",
"(",
"now",
"(",
"utc",
")",
".",
"isoformat",
"(",
")",
",",
"name",
",",
"process",
".",
"pid",
",",
"exit_code",
")",
")",
"continue",
"# React to stdout having a full line of text.",
"data",
"=",
"yield",
"from",
"future",
"if",
"not",
"data",
":",
"print",
"(",
"'%s [strawboss] EOF from %s(%d).'",
"%",
"(",
"now",
"(",
"utc",
")",
".",
"isoformat",
"(",
")",
",",
"name",
",",
"process",
".",
"pid",
",",
")",
")",
"continue",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
"print",
"(",
"'%s [%s] %s'",
"%",
"(",
"now",
"(",
"utc",
")",
".",
"isoformat",
"(",
")",
",",
"name",
",",
"data",
")",
")",
"pending",
".",
"add",
"(",
"asyncio",
".",
"ensure_future",
"(",
"process",
".",
"stdout",
".",
"readline",
"(",
")",
")",
")",
"# Cancel any remaining tasks (e.g. readline).",
"for",
"future",
"in",
"pending",
":",
"if",
"future",
"is",
"shutdown",
":",
"continue",
"future",
".",
"cancel",
"(",
")",
"# Pass the exit code back to the caller.",
"return",
"exit_code"
] |
Starts a child process and waits for its completion.
.. note:: This function is a coroutine.
Standard output and error streams are captured and forwarded to the parent
process' standard output. Each line is prefixed with the current time (as
measured by the parent process) and the child process ``name``.
:param name: Label for the child process. Will be used as a prefix to all
lines captured by this child process.
:param cmd: Command-line that will be used to invoke the child process.
Can be a string or sequence of strings. When a string is passed,
``shlex.split()`` will be used to break it into a sequence of strings
with smart quoting analysis. If this does not give the intended
results, break it down as you see fit and pass a sequence of strings.
:param env: Environment variables that should be injected in the child
process. If ``None``, the parent's environment will be inherited as it.
If a ``dict`` is provided, this will overwrite the entire environment;
it is the caller's responsibility to merge this with the parent's
environment if they see fit.
:param shutdown: Future that the caller will fulfill to indicate that the
process should be killed early. When this is set, the process is sent
SIGINT and then is let complete naturally.
:param loop: Event loop to use. When ``None``, the default event loop is
used.
:param utc: When ``True``, the timestamps are logged using the current time
in UTC.
:return: A future that will be completed when the process has completed.
Upon completion, the future's result will contain the process' exit
status.
|
[
"Starts",
"a",
"child",
"process",
"and",
"waits",
"for",
"its",
"completion",
"."
] |
b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc
|
https://github.com/smartmob-project/strawboss/blob/b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc/strawboss/__init__.py#L85-L192
|
242,971
|
smartmob-project/strawboss
|
strawboss/__init__.py
|
run_and_respawn
|
def run_and_respawn(shutdown, loop=None, **kwds):
"""Starts a child process and re-spawns it every time it completes.
.. note:: This function is a coroutine.
:param shutdown: Future that the caller will fulfill to indicate that the
process should not be re-spawned. It is also passed to ``run_once()``
to indicate that the currently running process should be killed early.
:param loop: Event loop to use. Defaults to the
``asyncio.get_event_loop()``.
:param kwds: Arguments to forward to :py:func:`run_once`.
:return: A future that will be completed when the process has stopped
re-spawning and has completed. The future has no result.
"""
# Get the default event loop if necessary.
loop = loop or asyncio.get_event_loop()
while not shutdown.done():
t = loop.create_task(run_once(shutdown=shutdown, loop=loop, **kwds))
yield from t
|
python
|
def run_and_respawn(shutdown, loop=None, **kwds):
"""Starts a child process and re-spawns it every time it completes.
.. note:: This function is a coroutine.
:param shutdown: Future that the caller will fulfill to indicate that the
process should not be re-spawned. It is also passed to ``run_once()``
to indicate that the currently running process should be killed early.
:param loop: Event loop to use. Defaults to the
``asyncio.get_event_loop()``.
:param kwds: Arguments to forward to :py:func:`run_once`.
:return: A future that will be completed when the process has stopped
re-spawning and has completed. The future has no result.
"""
# Get the default event loop if necessary.
loop = loop or asyncio.get_event_loop()
while not shutdown.done():
t = loop.create_task(run_once(shutdown=shutdown, loop=loop, **kwds))
yield from t
|
[
"def",
"run_and_respawn",
"(",
"shutdown",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"# Get the default event loop if necessary.",
"loop",
"=",
"loop",
"or",
"asyncio",
".",
"get_event_loop",
"(",
")",
"while",
"not",
"shutdown",
".",
"done",
"(",
")",
":",
"t",
"=",
"loop",
".",
"create_task",
"(",
"run_once",
"(",
"shutdown",
"=",
"shutdown",
",",
"loop",
"=",
"loop",
",",
"*",
"*",
"kwds",
")",
")",
"yield",
"from",
"t"
] |
Starts a child process and re-spawns it every time it completes.
.. note:: This function is a coroutine.
:param shutdown: Future that the caller will fulfill to indicate that the
process should not be re-spawned. It is also passed to ``run_once()``
to indicate that the currently running process should be killed early.
:param loop: Event loop to use. Defaults to the
``asyncio.get_event_loop()``.
:param kwds: Arguments to forward to :py:func:`run_once`.
:return: A future that will be completed when the process has stopped
re-spawning and has completed. The future has no result.
|
[
"Starts",
"a",
"child",
"process",
"and",
"re",
"-",
"spawns",
"it",
"every",
"time",
"it",
"completes",
"."
] |
b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc
|
https://github.com/smartmob-project/strawboss/blob/b295a7d0e3c1d95c4bb687f7f1bcae9605b3bbdc/strawboss/__init__.py#L196-L217
|
242,972
|
timeyyy/apptools
|
peasoup/uploadlogs.py
|
add_date
|
def add_date(log):
'''Userful for randomizing the name of a log'''
return '{base} - {time}.log'.format(
base=os.path.splitext(log)[0],
time=strftime("%a, %d %b %Y %H-%M-%S", gmtime()))
|
python
|
def add_date(log):
'''Userful for randomizing the name of a log'''
return '{base} - {time}.log'.format(
base=os.path.splitext(log)[0],
time=strftime("%a, %d %b %Y %H-%M-%S", gmtime()))
|
[
"def",
"add_date",
"(",
"log",
")",
":",
"return",
"'{base} - {time}.log'",
".",
"format",
"(",
"base",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"log",
")",
"[",
"0",
"]",
",",
"time",
"=",
"strftime",
"(",
"\"%a, %d %b %Y %H-%M-%S\"",
",",
"gmtime",
"(",
")",
")",
")"
] |
Userful for randomizing the name of a log
|
[
"Userful",
"for",
"randomizing",
"the",
"name",
"of",
"a",
"log"
] |
d3c0f324b0c2689c35f5601348276f4efd6cb240
|
https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/uploadlogs.py#L133-L137
|
242,973
|
timeyyy/apptools
|
peasoup/uploadlogs.py
|
LogUploader.delete_log
|
def delete_log(self, log):
'''check we don't delte anythin unintended'''
if os.path.splitext(log)[-1] != '.log':
raise Exception('File without .log was passed in for deletoin')
with suppress(Exception):
os.remove(log)
|
python
|
def delete_log(self, log):
'''check we don't delte anythin unintended'''
if os.path.splitext(log)[-1] != '.log':
raise Exception('File without .log was passed in for deletoin')
with suppress(Exception):
os.remove(log)
|
[
"def",
"delete_log",
"(",
"self",
",",
"log",
")",
":",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"log",
")",
"[",
"-",
"1",
"]",
"!=",
"'.log'",
":",
"raise",
"Exception",
"(",
"'File without .log was passed in for deletoin'",
")",
"with",
"suppress",
"(",
"Exception",
")",
":",
"os",
".",
"remove",
"(",
"log",
")"
] |
check we don't delte anythin unintended
|
[
"check",
"we",
"don",
"t",
"delte",
"anythin",
"unintended"
] |
d3c0f324b0c2689c35f5601348276f4efd6cb240
|
https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/uploadlogs.py#L72-L77
|
242,974
|
timeyyy/apptools
|
peasoup/uploadlogs.py
|
LogUploader.get_logs
|
def get_logs(self):
'''returns logs from disk, requires .log extenstion'''
folder = os.path.dirname(self.pcfg['log_file'])
for path, dir, files in os.walk(folder):
for file in files:
if os.path.splitext(file)[-1] == '.log':
yield os.path.join(path, file)
|
python
|
def get_logs(self):
'''returns logs from disk, requires .log extenstion'''
folder = os.path.dirname(self.pcfg['log_file'])
for path, dir, files in os.walk(folder):
for file in files:
if os.path.splitext(file)[-1] == '.log':
yield os.path.join(path, file)
|
[
"def",
"get_logs",
"(",
"self",
")",
":",
"folder",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"pcfg",
"[",
"'log_file'",
"]",
")",
"for",
"path",
",",
"dir",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"folder",
")",
":",
"for",
"file",
"in",
"files",
":",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"file",
")",
"[",
"-",
"1",
"]",
"==",
"'.log'",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"file",
")"
] |
returns logs from disk, requires .log extenstion
|
[
"returns",
"logs",
"from",
"disk",
"requires",
".",
"log",
"extenstion"
] |
d3c0f324b0c2689c35f5601348276f4efd6cb240
|
https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/uploadlogs.py#L80-L86
|
242,975
|
timeyyy/apptools
|
peasoup/uploadlogs.py
|
LogUploader._uniquename
|
def _uniquename(self, log):
'''
renames the log to ensure we get no clashes on the server
subclass this to change the path etc'''
return '{hostname} - {time}.log'.format(
hostname=os.getenv('USERNAME'),
time=strftime("%a, %d %b %Y %H-%M-%S", gmtime()))
|
python
|
def _uniquename(self, log):
'''
renames the log to ensure we get no clashes on the server
subclass this to change the path etc'''
return '{hostname} - {time}.log'.format(
hostname=os.getenv('USERNAME'),
time=strftime("%a, %d %b %Y %H-%M-%S", gmtime()))
|
[
"def",
"_uniquename",
"(",
"self",
",",
"log",
")",
":",
"return",
"'{hostname} - {time}.log'",
".",
"format",
"(",
"hostname",
"=",
"os",
".",
"getenv",
"(",
"'USERNAME'",
")",
",",
"time",
"=",
"strftime",
"(",
"\"%a, %d %b %Y %H-%M-%S\"",
",",
"gmtime",
"(",
")",
")",
")"
] |
renames the log to ensure we get no clashes on the server
subclass this to change the path etc
|
[
"renames",
"the",
"log",
"to",
"ensure",
"we",
"get",
"no",
"clashes",
"on",
"the",
"server",
"subclass",
"this",
"to",
"change",
"the",
"path",
"etc"
] |
d3c0f324b0c2689c35f5601348276f4efd6cb240
|
https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/uploadlogs.py#L89-L95
|
242,976
|
jalanb/pysyte
|
pysyte/args.py
|
arg_strings
|
def arg_strings(parsed_args, name=None):
"""A list of all strings for the named arg"""
name = name or 'arg_strings'
value = getattr(parsed_args, name, [])
if isinstance(value, str):
return [value]
try:
return [v for v in value if isinstance(v, str)]
except TypeError:
return []
|
python
|
def arg_strings(parsed_args, name=None):
"""A list of all strings for the named arg"""
name = name or 'arg_strings'
value = getattr(parsed_args, name, [])
if isinstance(value, str):
return [value]
try:
return [v for v in value if isinstance(v, str)]
except TypeError:
return []
|
[
"def",
"arg_strings",
"(",
"parsed_args",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"'arg_strings'",
"value",
"=",
"getattr",
"(",
"parsed_args",
",",
"name",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"[",
"value",
"]",
"try",
":",
"return",
"[",
"v",
"for",
"v",
"in",
"value",
"if",
"isinstance",
"(",
"v",
",",
"str",
")",
"]",
"except",
"TypeError",
":",
"return",
"[",
"]"
] |
A list of all strings for the named arg
|
[
"A",
"list",
"of",
"all",
"strings",
"for",
"the",
"named",
"arg"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/args.py#L87-L96
|
242,977
|
brycepg/mand
|
mand/util.py
|
create_module_file
|
def create_module_file(txt, directory):
"""Create a file in the given directory with
a valid module name populated with the given txt.
Returns:
A path to the file"""
name = nonpresent_module_filename()
path = os.path.join(directory, name)
with open(path, 'w') as fh:
fh.write(txt)
return path
|
python
|
def create_module_file(txt, directory):
"""Create a file in the given directory with
a valid module name populated with the given txt.
Returns:
A path to the file"""
name = nonpresent_module_filename()
path = os.path.join(directory, name)
with open(path, 'w') as fh:
fh.write(txt)
return path
|
[
"def",
"create_module_file",
"(",
"txt",
",",
"directory",
")",
":",
"name",
"=",
"nonpresent_module_filename",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"name",
")",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"txt",
")",
"return",
"path"
] |
Create a file in the given directory with
a valid module name populated with the given txt.
Returns:
A path to the file
|
[
"Create",
"a",
"file",
"in",
"the",
"given",
"directory",
"with",
"a",
"valid",
"module",
"name",
"populated",
"with",
"the",
"given",
"txt",
"."
] |
3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c
|
https://github.com/brycepg/mand/blob/3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c/mand/util.py#L14-L24
|
242,978
|
brycepg/mand
|
mand/util.py
|
nonpresent_module_filename
|
def nonpresent_module_filename():
"""Return module name that doesn't already exist"""
while True:
module_name = get_random_name()
loader = pkgutil.find_loader(module_name)
if loader is not None:
continue
importlib.invalidate_caches()
return "{}.py".format(module_name)
|
python
|
def nonpresent_module_filename():
"""Return module name that doesn't already exist"""
while True:
module_name = get_random_name()
loader = pkgutil.find_loader(module_name)
if loader is not None:
continue
importlib.invalidate_caches()
return "{}.py".format(module_name)
|
[
"def",
"nonpresent_module_filename",
"(",
")",
":",
"while",
"True",
":",
"module_name",
"=",
"get_random_name",
"(",
")",
"loader",
"=",
"pkgutil",
".",
"find_loader",
"(",
"module_name",
")",
"if",
"loader",
"is",
"not",
"None",
":",
"continue",
"importlib",
".",
"invalidate_caches",
"(",
")",
"return",
"\"{}.py\"",
".",
"format",
"(",
"module_name",
")"
] |
Return module name that doesn't already exist
|
[
"Return",
"module",
"name",
"that",
"doesn",
"t",
"already",
"exist"
] |
3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c
|
https://github.com/brycepg/mand/blob/3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c/mand/util.py#L42-L50
|
242,979
|
brycepg/mand
|
mand/util.py
|
get_random_name
|
def get_random_name():
"""Return random lowercase name"""
char_seq = []
name_source = random.randint(1, 2**8-1)
current_value = name_source
while current_value > 0:
char_offset = current_value % 26
current_value = current_value - random.randint(1, 26)
char_seq.append(chr(char_offset + ord('a')))
name = ''.join(char_seq)
assert re.match(VALID_PACKAGE_RE, name)
return name
|
python
|
def get_random_name():
"""Return random lowercase name"""
char_seq = []
name_source = random.randint(1, 2**8-1)
current_value = name_source
while current_value > 0:
char_offset = current_value % 26
current_value = current_value - random.randint(1, 26)
char_seq.append(chr(char_offset + ord('a')))
name = ''.join(char_seq)
assert re.match(VALID_PACKAGE_RE, name)
return name
|
[
"def",
"get_random_name",
"(",
")",
":",
"char_seq",
"=",
"[",
"]",
"name_source",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"2",
"**",
"8",
"-",
"1",
")",
"current_value",
"=",
"name_source",
"while",
"current_value",
">",
"0",
":",
"char_offset",
"=",
"current_value",
"%",
"26",
"current_value",
"=",
"current_value",
"-",
"random",
".",
"randint",
"(",
"1",
",",
"26",
")",
"char_seq",
".",
"append",
"(",
"chr",
"(",
"char_offset",
"+",
"ord",
"(",
"'a'",
")",
")",
")",
"name",
"=",
"''",
".",
"join",
"(",
"char_seq",
")",
"assert",
"re",
".",
"match",
"(",
"VALID_PACKAGE_RE",
",",
"name",
")",
"return",
"name"
] |
Return random lowercase name
|
[
"Return",
"random",
"lowercase",
"name"
] |
3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c
|
https://github.com/brycepg/mand/blob/3a8f9c1cc1bbe217aaca8c805113285ab02ecb7c/mand/util.py#L53-L64
|
242,980
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
get_header_dict
|
def get_header_dict(response, header):
""" returns a dictionary of the cache control headers
the same as is used by django.utils.cache.patch_cache_control
if there are no Cache-Control headers returns and empty dict
"""
def dictitem(s):
t = s.split('=', 1)
if len(t) > 1:
return (t[0].lower(), t[1])
else:
return (t[0].lower(), True)
if response.has_header(header):
hd = dict([dictitem(el) for el in cc_delim_re.split(response[header])])
else:
hd= {}
return hd
|
python
|
def get_header_dict(response, header):
""" returns a dictionary of the cache control headers
the same as is used by django.utils.cache.patch_cache_control
if there are no Cache-Control headers returns and empty dict
"""
def dictitem(s):
t = s.split('=', 1)
if len(t) > 1:
return (t[0].lower(), t[1])
else:
return (t[0].lower(), True)
if response.has_header(header):
hd = dict([dictitem(el) for el in cc_delim_re.split(response[header])])
else:
hd= {}
return hd
|
[
"def",
"get_header_dict",
"(",
"response",
",",
"header",
")",
":",
"def",
"dictitem",
"(",
"s",
")",
":",
"t",
"=",
"s",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"t",
")",
">",
"1",
":",
"return",
"(",
"t",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"t",
"[",
"1",
"]",
")",
"else",
":",
"return",
"(",
"t",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"True",
")",
"if",
"response",
".",
"has_header",
"(",
"header",
")",
":",
"hd",
"=",
"dict",
"(",
"[",
"dictitem",
"(",
"el",
")",
"for",
"el",
"in",
"cc_delim_re",
".",
"split",
"(",
"response",
"[",
"header",
"]",
")",
"]",
")",
"else",
":",
"hd",
"=",
"{",
"}",
"return",
"hd"
] |
returns a dictionary of the cache control headers
the same as is used by django.utils.cache.patch_cache_control
if there are no Cache-Control headers returns and empty dict
|
[
"returns",
"a",
"dictionary",
"of",
"the",
"cache",
"control",
"headers",
"the",
"same",
"as",
"is",
"used",
"by",
"django",
".",
"utils",
".",
"cache",
".",
"patch_cache_control",
"if",
"there",
"are",
"no",
"Cache",
"-",
"Control",
"headers",
"returns",
"and",
"empty",
"dict"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L161-L177
|
242,981
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
set_header_dict
|
def set_header_dict(response, header, header_dict):
"""Formats and sets a header dict in a response, inververs of get_header_dict."""
def dictvalue(t):
if t[1] is True:
return t[0]
return t[0] + '=' + smart_str(t[1])
response[header] = ', '.join([dictvalue(el) for el in header_dict.items()])
|
python
|
def set_header_dict(response, header, header_dict):
"""Formats and sets a header dict in a response, inververs of get_header_dict."""
def dictvalue(t):
if t[1] is True:
return t[0]
return t[0] + '=' + smart_str(t[1])
response[header] = ', '.join([dictvalue(el) for el in header_dict.items()])
|
[
"def",
"set_header_dict",
"(",
"response",
",",
"header",
",",
"header_dict",
")",
":",
"def",
"dictvalue",
"(",
"t",
")",
":",
"if",
"t",
"[",
"1",
"]",
"is",
"True",
":",
"return",
"t",
"[",
"0",
"]",
"return",
"t",
"[",
"0",
"]",
"+",
"'='",
"+",
"smart_str",
"(",
"t",
"[",
"1",
"]",
")",
"response",
"[",
"header",
"]",
"=",
"', '",
".",
"join",
"(",
"[",
"dictvalue",
"(",
"el",
")",
"for",
"el",
"in",
"header_dict",
".",
"items",
"(",
")",
"]",
")"
] |
Formats and sets a header dict in a response, inververs of get_header_dict.
|
[
"Formats",
"and",
"sets",
"a",
"header",
"dict",
"in",
"a",
"response",
"inververs",
"of",
"get_header_dict",
"."
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L179-L186
|
242,982
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
smart_import
|
def smart_import(mpath):
"""Given a path smart_import will import the module and return the attr reffered to."""
try:
rest = __import__(mpath)
except ImportError:
split = mpath.split('.')
rest = smart_import('.'.join(split[:-1]))
rest = getattr(rest, split[-1])
return rest
|
python
|
def smart_import(mpath):
"""Given a path smart_import will import the module and return the attr reffered to."""
try:
rest = __import__(mpath)
except ImportError:
split = mpath.split('.')
rest = smart_import('.'.join(split[:-1]))
rest = getattr(rest, split[-1])
return rest
|
[
"def",
"smart_import",
"(",
"mpath",
")",
":",
"try",
":",
"rest",
"=",
"__import__",
"(",
"mpath",
")",
"except",
"ImportError",
":",
"split",
"=",
"mpath",
".",
"split",
"(",
"'.'",
")",
"rest",
"=",
"smart_import",
"(",
"'.'",
".",
"join",
"(",
"split",
"[",
":",
"-",
"1",
"]",
")",
")",
"rest",
"=",
"getattr",
"(",
"rest",
",",
"split",
"[",
"-",
"1",
"]",
")",
"return",
"rest"
] |
Given a path smart_import will import the module and return the attr reffered to.
|
[
"Given",
"a",
"path",
"smart_import",
"will",
"import",
"the",
"module",
"and",
"return",
"the",
"attr",
"reffered",
"to",
"."
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L188-L196
|
242,983
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
strip_wsgi
|
def strip_wsgi(request):
"""Strip WSGI data out of the request META data."""
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = None
return meta
|
python
|
def strip_wsgi(request):
"""Strip WSGI data out of the request META data."""
meta = copy(request.META)
for key in meta:
if key[:4] == 'wsgi':
meta[key] = None
return meta
|
[
"def",
"strip_wsgi",
"(",
"request",
")",
":",
"meta",
"=",
"copy",
"(",
"request",
".",
"META",
")",
"for",
"key",
"in",
"meta",
":",
"if",
"key",
"[",
":",
"4",
"]",
"==",
"'wsgi'",
":",
"meta",
"[",
"key",
"]",
"=",
"None",
"return",
"meta"
] |
Strip WSGI data out of the request META data.
|
[
"Strip",
"WSGI",
"data",
"out",
"of",
"the",
"request",
"META",
"data",
"."
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L198-L205
|
242,984
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.patch_headers
|
def patch_headers(self, response):
"""Set the headers we want for caching."""
# Remove Vary:Cookie if we want to cache non-anonymous
if not getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False):
vdict = get_header_dict(response, 'Vary')
try:
vdict.pop('cookie')
except KeyError:
pass
else:
set_header_dict(response, 'Vary', vdict)
# Set max-age, post-check and pre-check
cc_headers = get_header_dict(response, 'Cache-Control')
try:
timeout = cc_headers['max-age']
except KeyError:
timeout = settings.BETTERCACHE_CACHE_MAXAGE
cc_headers['max-age'] = timeout
# This should never happen but let's be safe
if timeout is 0:
return response
if not 'pre-check' in cc_headers:
cc_headers['pre-check'] = timeout
if not 'post-check' in cc_headers:
cc_headers['post-check'] = int(timeout * settings.BETTERCACHE_EDGE_POSTCHECK_RATIO)
set_header_dict(response, 'Cache-Control', cc_headers)
# this should be the main/first place we're setting edge control so we can just set what we want
ec_dict = {'cache-maxage' : settings.BETTERCACHE_EDGE_MAXAGE}
set_header_dict(response, 'Edge-Control', ec_dict)
response['Last-Modified'] = http_date()
return response
|
python
|
def patch_headers(self, response):
"""Set the headers we want for caching."""
# Remove Vary:Cookie if we want to cache non-anonymous
if not getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False):
vdict = get_header_dict(response, 'Vary')
try:
vdict.pop('cookie')
except KeyError:
pass
else:
set_header_dict(response, 'Vary', vdict)
# Set max-age, post-check and pre-check
cc_headers = get_header_dict(response, 'Cache-Control')
try:
timeout = cc_headers['max-age']
except KeyError:
timeout = settings.BETTERCACHE_CACHE_MAXAGE
cc_headers['max-age'] = timeout
# This should never happen but let's be safe
if timeout is 0:
return response
if not 'pre-check' in cc_headers:
cc_headers['pre-check'] = timeout
if not 'post-check' in cc_headers:
cc_headers['post-check'] = int(timeout * settings.BETTERCACHE_EDGE_POSTCHECK_RATIO)
set_header_dict(response, 'Cache-Control', cc_headers)
# this should be the main/first place we're setting edge control so we can just set what we want
ec_dict = {'cache-maxage' : settings.BETTERCACHE_EDGE_MAXAGE}
set_header_dict(response, 'Edge-Control', ec_dict)
response['Last-Modified'] = http_date()
return response
|
[
"def",
"patch_headers",
"(",
"self",
",",
"response",
")",
":",
"# Remove Vary:Cookie if we want to cache non-anonymous",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'BETTERCACHE_ANONYMOUS_ONLY'",
",",
"False",
")",
":",
"vdict",
"=",
"get_header_dict",
"(",
"response",
",",
"'Vary'",
")",
"try",
":",
"vdict",
".",
"pop",
"(",
"'cookie'",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"set_header_dict",
"(",
"response",
",",
"'Vary'",
",",
"vdict",
")",
"# Set max-age, post-check and pre-check",
"cc_headers",
"=",
"get_header_dict",
"(",
"response",
",",
"'Cache-Control'",
")",
"try",
":",
"timeout",
"=",
"cc_headers",
"[",
"'max-age'",
"]",
"except",
"KeyError",
":",
"timeout",
"=",
"settings",
".",
"BETTERCACHE_CACHE_MAXAGE",
"cc_headers",
"[",
"'max-age'",
"]",
"=",
"timeout",
"# This should never happen but let's be safe",
"if",
"timeout",
"is",
"0",
":",
"return",
"response",
"if",
"not",
"'pre-check'",
"in",
"cc_headers",
":",
"cc_headers",
"[",
"'pre-check'",
"]",
"=",
"timeout",
"if",
"not",
"'post-check'",
"in",
"cc_headers",
":",
"cc_headers",
"[",
"'post-check'",
"]",
"=",
"int",
"(",
"timeout",
"*",
"settings",
".",
"BETTERCACHE_EDGE_POSTCHECK_RATIO",
")",
"set_header_dict",
"(",
"response",
",",
"'Cache-Control'",
",",
"cc_headers",
")",
"# this should be the main/first place we're setting edge control so we can just set what we want",
"ec_dict",
"=",
"{",
"'cache-maxage'",
":",
"settings",
".",
"BETTERCACHE_EDGE_MAXAGE",
"}",
"set_header_dict",
"(",
"response",
",",
"'Edge-Control'",
",",
"ec_dict",
")",
"response",
"[",
"'Last-Modified'",
"]",
"=",
"http_date",
"(",
")",
"return",
"response"
] |
Set the headers we want for caching.
|
[
"Set",
"the",
"headers",
"we",
"want",
"for",
"caching",
"."
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L18-L50
|
242,985
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.should_cache
|
def should_cache(self, request, response):
""" Given the request and response should it be cached """
if not getattr(request, '_cache_update_cache', False):
return False
if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS):
return False
if getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False) and self.session_accessed and request.user.is_authenticated:
return False
if self.has_uncacheable_headers(response):
return False
return True
|
python
|
def should_cache(self, request, response):
""" Given the request and response should it be cached """
if not getattr(request, '_cache_update_cache', False):
return False
if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS):
return False
if getattr(settings, 'BETTERCACHE_ANONYMOUS_ONLY', False) and self.session_accessed and request.user.is_authenticated:
return False
if self.has_uncacheable_headers(response):
return False
return True
|
[
"def",
"should_cache",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"not",
"getattr",
"(",
"request",
",",
"'_cache_update_cache'",
",",
"False",
")",
":",
"return",
"False",
"if",
"not",
"response",
".",
"status_code",
"in",
"getattr",
"(",
"settings",
",",
"'BETTERCACHE_CACHEABLE_STATUS'",
",",
"CACHEABLE_STATUS",
")",
":",
"return",
"False",
"if",
"getattr",
"(",
"settings",
",",
"'BETTERCACHE_ANONYMOUS_ONLY'",
",",
"False",
")",
"and",
"self",
".",
"session_accessed",
"and",
"request",
".",
"user",
".",
"is_authenticated",
":",
"return",
"False",
"if",
"self",
".",
"has_uncacheable_headers",
"(",
"response",
")",
":",
"return",
"False",
"return",
"True"
] |
Given the request and response should it be cached
|
[
"Given",
"the",
"request",
"and",
"response",
"should",
"it",
"be",
"cached"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L61-L72
|
242,986
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.should_regenerate
|
def should_regenerate(self, response):
""" Check if this page was originally generated less than LOCAL_POSTCHECK seconds ago """
if response.has_header('Last-Modified'):
last_modified = parse_http_date(response['Last-Modified'])
next_regen = last_modified + settings.BETTERCACHE_LOCAL_POSTCHECK
return time.time() > next_regen
|
python
|
def should_regenerate(self, response):
""" Check if this page was originally generated less than LOCAL_POSTCHECK seconds ago """
if response.has_header('Last-Modified'):
last_modified = parse_http_date(response['Last-Modified'])
next_regen = last_modified + settings.BETTERCACHE_LOCAL_POSTCHECK
return time.time() > next_regen
|
[
"def",
"should_regenerate",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"has_header",
"(",
"'Last-Modified'",
")",
":",
"last_modified",
"=",
"parse_http_date",
"(",
"response",
"[",
"'Last-Modified'",
"]",
")",
"next_regen",
"=",
"last_modified",
"+",
"settings",
".",
"BETTERCACHE_LOCAL_POSTCHECK",
"return",
"time",
".",
"time",
"(",
")",
">",
"next_regen"
] |
Check if this page was originally generated less than LOCAL_POSTCHECK seconds ago
|
[
"Check",
"if",
"this",
"page",
"was",
"originally",
"generated",
"less",
"than",
"LOCAL_POSTCHECK",
"seconds",
"ago"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L85-L91
|
242,987
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.has_uncacheable_headers
|
def has_uncacheable_headers(self, response):
""" Should this response be cached based on it's headers
broken out from should_cache for flexibility
"""
cc_dict = get_header_dict(response, 'Cache-Control')
if cc_dict:
if 'max-age' in cc_dict and cc_dict['max-age'] == '0':
return True
if 'no-cache' in cc_dict:
return True
if 'private' in cc_dict:
return True
if response.has_header('Expires'):
if parse_http_date(response['Expires']) < time.time():
return True
return False
|
python
|
def has_uncacheable_headers(self, response):
""" Should this response be cached based on it's headers
broken out from should_cache for flexibility
"""
cc_dict = get_header_dict(response, 'Cache-Control')
if cc_dict:
if 'max-age' in cc_dict and cc_dict['max-age'] == '0':
return True
if 'no-cache' in cc_dict:
return True
if 'private' in cc_dict:
return True
if response.has_header('Expires'):
if parse_http_date(response['Expires']) < time.time():
return True
return False
|
[
"def",
"has_uncacheable_headers",
"(",
"self",
",",
"response",
")",
":",
"cc_dict",
"=",
"get_header_dict",
"(",
"response",
",",
"'Cache-Control'",
")",
"if",
"cc_dict",
":",
"if",
"'max-age'",
"in",
"cc_dict",
"and",
"cc_dict",
"[",
"'max-age'",
"]",
"==",
"'0'",
":",
"return",
"True",
"if",
"'no-cache'",
"in",
"cc_dict",
":",
"return",
"True",
"if",
"'private'",
"in",
"cc_dict",
":",
"return",
"True",
"if",
"response",
".",
"has_header",
"(",
"'Expires'",
")",
":",
"if",
"parse_http_date",
"(",
"response",
"[",
"'Expires'",
"]",
")",
"<",
"time",
".",
"time",
"(",
")",
":",
"return",
"True",
"return",
"False"
] |
Should this response be cached based on it's headers
broken out from should_cache for flexibility
|
[
"Should",
"this",
"response",
"be",
"cached",
"based",
"on",
"it",
"s",
"headers",
"broken",
"out",
"from",
"should_cache",
"for",
"flexibility"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L93-L109
|
242,988
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.set_cache
|
def set_cache(self, request, response):
""" caches the response supresses and logs exceptions"""
try:
cache_key = self.cache_key(request)
#presumably this is to deal with requests with attr functions that won't pickle
if hasattr(response, 'render') and callable(response.render):
response.add_post_render_callback(lambda r: cache.set(cache_key, (r, time.time(),), settings.BETTERCACHE_LOCAL_MAXAGE))
else:
cache.set(cache_key, (response, time.time(),) , settings.BETTERCACHE_LOCAL_MAXAGE)
except:
logger.error("failed to cache to %s" %cache_key)
|
python
|
def set_cache(self, request, response):
""" caches the response supresses and logs exceptions"""
try:
cache_key = self.cache_key(request)
#presumably this is to deal with requests with attr functions that won't pickle
if hasattr(response, 'render') and callable(response.render):
response.add_post_render_callback(lambda r: cache.set(cache_key, (r, time.time(),), settings.BETTERCACHE_LOCAL_MAXAGE))
else:
cache.set(cache_key, (response, time.time(),) , settings.BETTERCACHE_LOCAL_MAXAGE)
except:
logger.error("failed to cache to %s" %cache_key)
|
[
"def",
"set_cache",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"try",
":",
"cache_key",
"=",
"self",
".",
"cache_key",
"(",
"request",
")",
"#presumably this is to deal with requests with attr functions that won't pickle",
"if",
"hasattr",
"(",
"response",
",",
"'render'",
")",
"and",
"callable",
"(",
"response",
".",
"render",
")",
":",
"response",
".",
"add_post_render_callback",
"(",
"lambda",
"r",
":",
"cache",
".",
"set",
"(",
"cache_key",
",",
"(",
"r",
",",
"time",
".",
"time",
"(",
")",
",",
")",
",",
"settings",
".",
"BETTERCACHE_LOCAL_MAXAGE",
")",
")",
"else",
":",
"cache",
".",
"set",
"(",
"cache_key",
",",
"(",
"response",
",",
"time",
".",
"time",
"(",
")",
",",
")",
",",
"settings",
".",
"BETTERCACHE_LOCAL_MAXAGE",
")",
"except",
":",
"logger",
".",
"error",
"(",
"\"failed to cache to %s\"",
"%",
"cache_key",
")"
] |
caches the response supresses and logs exceptions
|
[
"caches",
"the",
"response",
"supresses",
"and",
"logs",
"exceptions"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L111-L122
|
242,989
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.cache_key
|
def cache_key(self, request, method=None):
""" the cache key is the absolute uri and the request method """
if method is None:
method = request.method
return "bettercache_page:%s:%s" %(request.build_absolute_uri(), method)
|
python
|
def cache_key(self, request, method=None):
""" the cache key is the absolute uri and the request method """
if method is None:
method = request.method
return "bettercache_page:%s:%s" %(request.build_absolute_uri(), method)
|
[
"def",
"cache_key",
"(",
"self",
",",
"request",
",",
"method",
"=",
"None",
")",
":",
"if",
"method",
"is",
"None",
":",
"method",
"=",
"request",
".",
"method",
"return",
"\"bettercache_page:%s:%s\"",
"%",
"(",
"request",
".",
"build_absolute_uri",
"(",
")",
",",
"method",
")"
] |
the cache key is the absolute uri and the request method
|
[
"the",
"cache",
"key",
"is",
"the",
"absolute",
"uri",
"and",
"the",
"request",
"method"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L142-L147
|
242,990
|
ironfroggy/django-better-cache
|
bettercache/utils.py
|
CachingMixin.send_task
|
def send_task(self, request, response):
"""send off a celery task for the current page and recache"""
# TODO is this too messy?
from bettercache.tasks import GeneratePage
try:
GeneratePage.apply_async((strip_wsgi(request),))
except:
logger.error("failed to send celery task")
self.set_cache(request, response)
|
python
|
def send_task(self, request, response):
"""send off a celery task for the current page and recache"""
# TODO is this too messy?
from bettercache.tasks import GeneratePage
try:
GeneratePage.apply_async((strip_wsgi(request),))
except:
logger.error("failed to send celery task")
self.set_cache(request, response)
|
[
"def",
"send_task",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# TODO is this too messy?",
"from",
"bettercache",
".",
"tasks",
"import",
"GeneratePage",
"try",
":",
"GeneratePage",
".",
"apply_async",
"(",
"(",
"strip_wsgi",
"(",
"request",
")",
",",
")",
")",
"except",
":",
"logger",
".",
"error",
"(",
"\"failed to send celery task\"",
")",
"self",
".",
"set_cache",
"(",
"request",
",",
"response",
")"
] |
send off a celery task for the current page and recache
|
[
"send",
"off",
"a",
"celery",
"task",
"for",
"the",
"current",
"page",
"and",
"recache"
] |
5350e8c646cef1c1ca74eab176f856ddd9eaf5c3
|
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L149-L158
|
242,991
|
elifesciences/elife-article
|
elifearticle/utils.py
|
entity_to_unicode
|
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
|
python
|
def entity_to_unicode(string):
"""
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
"""
# Selected character replacements that have been seen
replacements = []
replacements.append((r"α", u"\u03b1"))
replacements.append((r"β", u"\u03b2"))
replacements.append((r"γ", u"\u03b3"))
replacements.append((r"δ", u"\u03b4"))
replacements.append((r"ε", u"\u03b5"))
replacements.append((r"º", u"\u00ba"))
replacements.append((r"ï", u"\u00cf"))
replacements.append((r"“", '"'))
replacements.append((r"”", '"'))
# First, replace numeric entities with unicode
string = re.sub(r"&#x(....);", repl, string)
# Second, replace some specific entities specified in the list
for entity, replacement in replacements:
string = re.sub(entity, replacement, string)
return string
|
[
"def",
"entity_to_unicode",
"(",
"string",
")",
":",
"# Selected character replacements that have been seen",
"replacements",
"=",
"[",
"]",
"replacements",
".",
"append",
"(",
"(",
"r\"α\"",
",",
"u\"\\u03b1\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"β\"",
",",
"u\"\\u03b2\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"γ\"",
",",
"u\"\\u03b3\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"δ\"",
",",
"u\"\\u03b4\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"ε\"",
",",
"u\"\\u03b5\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"º\"",
",",
"u\"\\u00ba\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"ï\"",
",",
"u\"\\u00cf\"",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"“\"",
",",
"'\"'",
")",
")",
"replacements",
".",
"append",
"(",
"(",
"r\"”\"",
",",
"'\"'",
")",
")",
"# First, replace numeric entities with unicode",
"string",
"=",
"re",
".",
"sub",
"(",
"r\"&#x(....);\"",
",",
"repl",
",",
"string",
")",
"# Second, replace some specific entities specified in the list",
"for",
"entity",
",",
"replacement",
"in",
"replacements",
":",
"string",
"=",
"re",
".",
"sub",
"(",
"entity",
",",
"replacement",
",",
"string",
")",
"return",
"string"
] |
Quick convert unicode HTML entities to unicode characters
using a regular expression replacement
|
[
"Quick",
"convert",
"unicode",
"HTML",
"entities",
"to",
"unicode",
"characters",
"using",
"a",
"regular",
"expression",
"replacement"
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L37-L59
|
242,992
|
elifesciences/elife-article
|
elifearticle/utils.py
|
remove_tag
|
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
|
python
|
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string
|
[
"def",
"remove_tag",
"(",
"tag_name",
",",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"string",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'</?'",
"+",
"tag_name",
"+",
"'.*?>'",
")",
"string",
"=",
"pattern",
".",
"sub",
"(",
"''",
",",
"string",
")",
"return",
"string"
] |
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
|
[
"Remove",
"open",
"and",
"close",
"tags",
"-",
"the",
"tags",
"themselves",
"only",
"-",
"using",
"a",
"non",
"-",
"greedy",
"angle",
"bracket",
"pattern",
"match"
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L61-L70
|
242,993
|
elifesciences/elife-article
|
elifearticle/utils.py
|
version_from_xml_filename
|
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
|
python
|
def version_from_xml_filename(filename):
"extract the numeric version from the xml filename"
try:
filename_parts = filename.split(os.sep)[-1].split('-')
except AttributeError:
return None
if len(filename_parts) == 3:
try:
return int(filename_parts[-1].lstrip('v').rstrip('.xml'))
except ValueError:
return None
else:
return None
|
[
"def",
"version_from_xml_filename",
"(",
"filename",
")",
":",
"try",
":",
"filename_parts",
"=",
"filename",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"'-'",
")",
"except",
"AttributeError",
":",
"return",
"None",
"if",
"len",
"(",
"filename_parts",
")",
"==",
"3",
":",
"try",
":",
"return",
"int",
"(",
"filename_parts",
"[",
"-",
"1",
"]",
".",
"lstrip",
"(",
"'v'",
")",
".",
"rstrip",
"(",
"'.xml'",
")",
")",
"except",
"ValueError",
":",
"return",
"None",
"else",
":",
"return",
"None"
] |
extract the numeric version from the xml filename
|
[
"extract",
"the",
"numeric",
"version",
"from",
"the",
"xml",
"filename"
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L93-L105
|
242,994
|
elifesciences/elife-article
|
elifearticle/utils.py
|
get_last_commit_to_master
|
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
|
python
|
def get_last_commit_to_master(repo_path="."):
"""
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
"""
last_commit = None
repo = None
try:
repo = Repo(repo_path)
except (InvalidGitRepositoryError, NoSuchPathError):
repo = None
if repo:
try:
last_commit = repo.commits()[0]
except AttributeError:
# Optimised for version 0.3.2.RC1
last_commit = repo.head.commit
return str(last_commit)
|
[
"def",
"get_last_commit_to_master",
"(",
"repo_path",
"=",
"\".\"",
")",
":",
"last_commit",
"=",
"None",
"repo",
"=",
"None",
"try",
":",
"repo",
"=",
"Repo",
"(",
"repo_path",
")",
"except",
"(",
"InvalidGitRepositoryError",
",",
"NoSuchPathError",
")",
":",
"repo",
"=",
"None",
"if",
"repo",
":",
"try",
":",
"last_commit",
"=",
"repo",
".",
"commits",
"(",
")",
"[",
"0",
"]",
"except",
"AttributeError",
":",
"# Optimised for version 0.3.2.RC1",
"last_commit",
"=",
"repo",
".",
"head",
".",
"commit",
"return",
"str",
"(",
"last_commit",
")"
] |
returns the last commit on the master branch. It would be more ideal to get the commit
from the branch we are currently on, but as this is a check mostly to help
with production issues, returning the commit from master will be sufficient.
|
[
"returns",
"the",
"last",
"commit",
"on",
"the",
"master",
"branch",
".",
"It",
"would",
"be",
"more",
"ideal",
"to",
"get",
"the",
"commit",
"from",
"the",
"branch",
"we",
"are",
"currently",
"on",
"but",
"as",
"this",
"is",
"a",
"check",
"mostly",
"to",
"help",
"with",
"production",
"issues",
"returning",
"the",
"commit",
"from",
"master",
"will",
"be",
"sufficient",
"."
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L107-L125
|
242,995
|
elifesciences/elife-article
|
elifearticle/utils.py
|
calculate_journal_volume
|
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
|
python
|
def calculate_journal_volume(pub_date, year):
"""
volume value is based on the pub date year
pub_date is a python time object
"""
try:
volume = str(pub_date.tm_year - year + 1)
except TypeError:
volume = None
except AttributeError:
volume = None
return volume
|
[
"def",
"calculate_journal_volume",
"(",
"pub_date",
",",
"year",
")",
":",
"try",
":",
"volume",
"=",
"str",
"(",
"pub_date",
".",
"tm_year",
"-",
"year",
"+",
"1",
")",
"except",
"TypeError",
":",
"volume",
"=",
"None",
"except",
"AttributeError",
":",
"volume",
"=",
"None",
"return",
"volume"
] |
volume value is based on the pub date year
pub_date is a python time object
|
[
"volume",
"value",
"is",
"based",
"on",
"the",
"pub",
"date",
"year",
"pub_date",
"is",
"a",
"python",
"time",
"object"
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L127-L138
|
242,996
|
elifesciences/elife-article
|
elifearticle/utils.py
|
author_name_from_json
|
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
|
python
|
def author_name_from_json(author_json):
"concatenate an author name from json data"
author_name = None
if author_json.get('type'):
if author_json.get('type') == 'group' and author_json.get('name'):
author_name = author_json.get('name')
elif author_json.get('type') == 'person' and author_json.get('name'):
if author_json.get('name').get('preferred'):
author_name = author_json.get('name').get('preferred')
return author_name
|
[
"def",
"author_name_from_json",
"(",
"author_json",
")",
":",
"author_name",
"=",
"None",
"if",
"author_json",
".",
"get",
"(",
"'type'",
")",
":",
"if",
"author_json",
".",
"get",
"(",
"'type'",
")",
"==",
"'group'",
"and",
"author_json",
".",
"get",
"(",
"'name'",
")",
":",
"author_name",
"=",
"author_json",
".",
"get",
"(",
"'name'",
")",
"elif",
"author_json",
".",
"get",
"(",
"'type'",
")",
"==",
"'person'",
"and",
"author_json",
".",
"get",
"(",
"'name'",
")",
":",
"if",
"author_json",
".",
"get",
"(",
"'name'",
")",
".",
"get",
"(",
"'preferred'",
")",
":",
"author_name",
"=",
"author_json",
".",
"get",
"(",
"'name'",
")",
".",
"get",
"(",
"'preferred'",
")",
"return",
"author_name"
] |
concatenate an author name from json data
|
[
"concatenate",
"an",
"author",
"name",
"from",
"json",
"data"
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L140-L149
|
242,997
|
elifesciences/elife-article
|
elifearticle/utils.py
|
text_from_affiliation_elements
|
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
python
|
def text_from_affiliation_elements(department, institution, city, country):
"format an author affiliation from details"
return ', '.join(element for element in [department, institution, city, country] if element)
|
[
"def",
"text_from_affiliation_elements",
"(",
"department",
",",
"institution",
",",
"city",
",",
"country",
")",
":",
"return",
"', '",
".",
"join",
"(",
"element",
"for",
"element",
"in",
"[",
"department",
",",
"institution",
",",
"city",
",",
"country",
"]",
"if",
"element",
")"
] |
format an author affiliation from details
|
[
"format",
"an",
"author",
"affiliation",
"from",
"details"
] |
99710c213cd81fe6fd1e5c150d6e20efe2d1e33b
|
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L151-L153
|
242,998
|
cdeboever3/cdpybio
|
cdpybio/mutect.py
|
read_variants
|
def read_variants(fns, remove=['DBSNP'], keep_only=True,
min_tumor_f=0.1, min_tumor_cov=14,
min_normal_cov=8):
"""Read muTect results from the list of files fns
Parameters
----------
fns : list
List of MuTect output files.
Returns
-------
variants : pandas.DataFrame
Pandas DataFrame summarizing variant calling results.
remove : list
List of site types for column "dbsnp_site" to remove.
keep_only : boolean
If True, only keep variants with 'KEEP' in "judgement" column.
Otherwise, keep all variants.
min_tumor_f : float between 0 and 1
Minimum tumor allelic fraction.
min_tumor_cov : int > 0
Minimum coverage of the variant in the tumor.
min_normal_cov : int > 0
Minimum coverage of the variant in the normal.
"""
variants = []
for i, f in enumerate(fns):
# If keep_only, use awk to only grab those lines for big speedup.
if keep_only:
from numpy import dtype
import subprocess
res = subprocess.check_output(
'awk \'$35 == "KEEP"\' {}'.format(f), shell=True)
if res.strip() != '':
columns = [u'contig', u'position', u'context', u'ref_allele',
u'alt_allele', u'tumor_name', u'normal_name',
u'score', u'dbsnp_site', u'covered', u'power',
u'tumor_power', u'normal_power', u'total_pairs',
u'improper_pairs', u'map_Q0_reads', u't_lod_fstar',
u'tumor_f', u'contaminant_fraction',
u'contaminant_lod', u't_ref_count', u't_alt_count',
u't_ref_sum', u't_alt_sum', u't_ref_max_mapq',
u't_alt_max_mapq', u't_ins_count', u't_del_count',
u'normal_best_gt', u'init_n_lod', u'n_ref_count',
u'n_alt_count', u'n_ref_sum', u'n_alt_sum',
u'judgement']
tdf = pd.DataFrame(
[x.split('\t') for x in res.strip().split('\n')],
columns=columns)
tdf = tdf.convert_objects(convert_numeric=True)
else:
tdf = pd.DataFrame(columns=columns)
tdf['contig'] = tdf.contig.astype(object)
else:
tdf = pd.read_table(f, index_col=None, header=0, skiprows=1,
low_memory=False,
dtype={'contig':object})
for t in remove:
tdf = tdf[tdf.dbsnp_site != t]
tdf = tdf[tdf.tumor_f > min_tumor_f]
tdf = tdf[tdf.t_ref_count + tdf.t_alt_count > min_tumor_cov]
tdf = tdf[tdf.n_ref_count + tdf.n_alt_count > min_normal_cov]
variants.append(tdf)
variants = pd.concat(variants)
variants.index = range(variants.shape[0])
return variants
|
python
|
def read_variants(fns, remove=['DBSNP'], keep_only=True,
min_tumor_f=0.1, min_tumor_cov=14,
min_normal_cov=8):
"""Read muTect results from the list of files fns
Parameters
----------
fns : list
List of MuTect output files.
Returns
-------
variants : pandas.DataFrame
Pandas DataFrame summarizing variant calling results.
remove : list
List of site types for column "dbsnp_site" to remove.
keep_only : boolean
If True, only keep variants with 'KEEP' in "judgement" column.
Otherwise, keep all variants.
min_tumor_f : float between 0 and 1
Minimum tumor allelic fraction.
min_tumor_cov : int > 0
Minimum coverage of the variant in the tumor.
min_normal_cov : int > 0
Minimum coverage of the variant in the normal.
"""
variants = []
for i, f in enumerate(fns):
# If keep_only, use awk to only grab those lines for big speedup.
if keep_only:
from numpy import dtype
import subprocess
res = subprocess.check_output(
'awk \'$35 == "KEEP"\' {}'.format(f), shell=True)
if res.strip() != '':
columns = [u'contig', u'position', u'context', u'ref_allele',
u'alt_allele', u'tumor_name', u'normal_name',
u'score', u'dbsnp_site', u'covered', u'power',
u'tumor_power', u'normal_power', u'total_pairs',
u'improper_pairs', u'map_Q0_reads', u't_lod_fstar',
u'tumor_f', u'contaminant_fraction',
u'contaminant_lod', u't_ref_count', u't_alt_count',
u't_ref_sum', u't_alt_sum', u't_ref_max_mapq',
u't_alt_max_mapq', u't_ins_count', u't_del_count',
u'normal_best_gt', u'init_n_lod', u'n_ref_count',
u'n_alt_count', u'n_ref_sum', u'n_alt_sum',
u'judgement']
tdf = pd.DataFrame(
[x.split('\t') for x in res.strip().split('\n')],
columns=columns)
tdf = tdf.convert_objects(convert_numeric=True)
else:
tdf = pd.DataFrame(columns=columns)
tdf['contig'] = tdf.contig.astype(object)
else:
tdf = pd.read_table(f, index_col=None, header=0, skiprows=1,
low_memory=False,
dtype={'contig':object})
for t in remove:
tdf = tdf[tdf.dbsnp_site != t]
tdf = tdf[tdf.tumor_f > min_tumor_f]
tdf = tdf[tdf.t_ref_count + tdf.t_alt_count > min_tumor_cov]
tdf = tdf[tdf.n_ref_count + tdf.n_alt_count > min_normal_cov]
variants.append(tdf)
variants = pd.concat(variants)
variants.index = range(variants.shape[0])
return variants
|
[
"def",
"read_variants",
"(",
"fns",
",",
"remove",
"=",
"[",
"'DBSNP'",
"]",
",",
"keep_only",
"=",
"True",
",",
"min_tumor_f",
"=",
"0.1",
",",
"min_tumor_cov",
"=",
"14",
",",
"min_normal_cov",
"=",
"8",
")",
":",
"variants",
"=",
"[",
"]",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"fns",
")",
":",
"# If keep_only, use awk to only grab those lines for big speedup.",
"if",
"keep_only",
":",
"from",
"numpy",
"import",
"dtype",
"import",
"subprocess",
"res",
"=",
"subprocess",
".",
"check_output",
"(",
"'awk \\'$35 == \"KEEP\"\\' {}'",
".",
"format",
"(",
"f",
")",
",",
"shell",
"=",
"True",
")",
"if",
"res",
".",
"strip",
"(",
")",
"!=",
"''",
":",
"columns",
"=",
"[",
"u'contig'",
",",
"u'position'",
",",
"u'context'",
",",
"u'ref_allele'",
",",
"u'alt_allele'",
",",
"u'tumor_name'",
",",
"u'normal_name'",
",",
"u'score'",
",",
"u'dbsnp_site'",
",",
"u'covered'",
",",
"u'power'",
",",
"u'tumor_power'",
",",
"u'normal_power'",
",",
"u'total_pairs'",
",",
"u'improper_pairs'",
",",
"u'map_Q0_reads'",
",",
"u't_lod_fstar'",
",",
"u'tumor_f'",
",",
"u'contaminant_fraction'",
",",
"u'contaminant_lod'",
",",
"u't_ref_count'",
",",
"u't_alt_count'",
",",
"u't_ref_sum'",
",",
"u't_alt_sum'",
",",
"u't_ref_max_mapq'",
",",
"u't_alt_max_mapq'",
",",
"u't_ins_count'",
",",
"u't_del_count'",
",",
"u'normal_best_gt'",
",",
"u'init_n_lod'",
",",
"u'n_ref_count'",
",",
"u'n_alt_count'",
",",
"u'n_ref_sum'",
",",
"u'n_alt_sum'",
",",
"u'judgement'",
"]",
"tdf",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"x",
".",
"split",
"(",
"'\\t'",
")",
"for",
"x",
"in",
"res",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"]",
",",
"columns",
"=",
"columns",
")",
"tdf",
"=",
"tdf",
".",
"convert_objects",
"(",
"convert_numeric",
"=",
"True",
")",
"else",
":",
"tdf",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"columns",
")",
"tdf",
"[",
"'contig'",
"]",
"=",
"tdf",
".",
"contig",
".",
"astype",
"(",
"object",
")",
"else",
":",
"tdf",
"=",
"pd",
".",
"read_table",
"(",
"f",
",",
"index_col",
"=",
"None",
",",
"header",
"=",
"0",
",",
"skiprows",
"=",
"1",
",",
"low_memory",
"=",
"False",
",",
"dtype",
"=",
"{",
"'contig'",
":",
"object",
"}",
")",
"for",
"t",
"in",
"remove",
":",
"tdf",
"=",
"tdf",
"[",
"tdf",
".",
"dbsnp_site",
"!=",
"t",
"]",
"tdf",
"=",
"tdf",
"[",
"tdf",
".",
"tumor_f",
">",
"min_tumor_f",
"]",
"tdf",
"=",
"tdf",
"[",
"tdf",
".",
"t_ref_count",
"+",
"tdf",
".",
"t_alt_count",
">",
"min_tumor_cov",
"]",
"tdf",
"=",
"tdf",
"[",
"tdf",
".",
"n_ref_count",
"+",
"tdf",
".",
"n_alt_count",
">",
"min_normal_cov",
"]",
"variants",
".",
"append",
"(",
"tdf",
")",
"variants",
"=",
"pd",
".",
"concat",
"(",
"variants",
")",
"variants",
".",
"index",
"=",
"range",
"(",
"variants",
".",
"shape",
"[",
"0",
"]",
")",
"return",
"variants"
] |
Read muTect results from the list of files fns
Parameters
----------
fns : list
List of MuTect output files.
Returns
-------
variants : pandas.DataFrame
Pandas DataFrame summarizing variant calling results.
remove : list
List of site types for column "dbsnp_site" to remove.
keep_only : boolean
If True, only keep variants with 'KEEP' in "judgement" column.
Otherwise, keep all variants.
min_tumor_f : float between 0 and 1
Minimum tumor allelic fraction.
min_tumor_cov : int > 0
Minimum coverage of the variant in the tumor.
min_normal_cov : int > 0
Minimum coverage of the variant in the normal.
|
[
"Read",
"muTect",
"results",
"from",
"the",
"list",
"of",
"files",
"fns"
] |
38efdf0e11d01bc00a135921cb91a19c03db5d5c
|
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/mutect.py#L4-L77
|
242,999
|
honzamach/pynspect
|
pynspect/compilers.py
|
ConversionRule.traverse
|
def traverse(self, traverser, **kwargs):
"""
Implementation of mandatory interface for traversing the whole rule tree.
This method will call the ``traverse`` method of child rule tree and
then perform arbitrary conversion of the result before returning it back.
The optional ``kwargs`` are passed down to traverser callback as additional
arguments and can be used to provide additional data or context.
:param pynspect.rules.RuleTreeTraverser traverser: Traverser object providing appropriate interface.
:param dict kwargs: Additional optional keyword arguments to be passed down to traverser callback.
"""
result = self.rule.traverse(traverser, **kwargs)
return self.conversion(result)
|
python
|
def traverse(self, traverser, **kwargs):
"""
Implementation of mandatory interface for traversing the whole rule tree.
This method will call the ``traverse`` method of child rule tree and
then perform arbitrary conversion of the result before returning it back.
The optional ``kwargs`` are passed down to traverser callback as additional
arguments and can be used to provide additional data or context.
:param pynspect.rules.RuleTreeTraverser traverser: Traverser object providing appropriate interface.
:param dict kwargs: Additional optional keyword arguments to be passed down to traverser callback.
"""
result = self.rule.traverse(traverser, **kwargs)
return self.conversion(result)
|
[
"def",
"traverse",
"(",
"self",
",",
"traverser",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"rule",
".",
"traverse",
"(",
"traverser",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"conversion",
"(",
"result",
")"
] |
Implementation of mandatory interface for traversing the whole rule tree.
This method will call the ``traverse`` method of child rule tree and
then perform arbitrary conversion of the result before returning it back.
The optional ``kwargs`` are passed down to traverser callback as additional
arguments and can be used to provide additional data or context.
:param pynspect.rules.RuleTreeTraverser traverser: Traverser object providing appropriate interface.
:param dict kwargs: Additional optional keyword arguments to be passed down to traverser callback.
|
[
"Implementation",
"of",
"mandatory",
"interface",
"for",
"traversing",
"the",
"whole",
"rule",
"tree",
".",
"This",
"method",
"will",
"call",
"the",
"traverse",
"method",
"of",
"child",
"rule",
"tree",
"and",
"then",
"perform",
"arbitrary",
"conversion",
"of",
"the",
"result",
"before",
"returning",
"it",
"back",
".",
"The",
"optional",
"kwargs",
"are",
"passed",
"down",
"to",
"traverser",
"callback",
"as",
"additional",
"arguments",
"and",
"can",
"be",
"used",
"to",
"provide",
"additional",
"data",
"or",
"context",
"."
] |
0582dcc1f7aafe50e25a21c792ea1b3367ea5881
|
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L186-L198
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.