repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | publish_page | def publish_page(page, languages):
"""
Publish a CMS page in all given languages.
"""
for language_code, lang_name in iter_languages(languages):
url = page.get_absolute_url()
if page.publisher_is_draft:
page.publish(language_code)
log.info('page "%s" published in %s: %s', page, lang_name, url)
else:
log.info('published page "%s" already exists in %s: %s', page,
lang_name, url)
return page.reload() | python | def publish_page(page, languages):
"""
Publish a CMS page in all given languages.
"""
for language_code, lang_name in iter_languages(languages):
url = page.get_absolute_url()
if page.publisher_is_draft:
page.publish(language_code)
log.info('page "%s" published in %s: %s', page, lang_name, url)
else:
log.info('published page "%s" already exists in %s: %s', page,
lang_name, url)
return page.reload() | [
"def",
"publish_page",
"(",
"page",
",",
"languages",
")",
":",
"for",
"language_code",
",",
"lang_name",
"in",
"iter_languages",
"(",
"languages",
")",
":",
"url",
"=",
"page",
".",
"get_absolute_url",
"(",
")",
"if",
"page",
".",
"publisher_is_draft",
":",... | Publish a CMS page in all given languages. | [
"Publish",
"a",
"CMS",
"page",
"in",
"all",
"given",
"languages",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L47-L60 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | create_cms_index_pages | def create_cms_index_pages(placeholder_slot="content"):
"""
create cms home page and fill >content< placeholder with TextPlugin
"""
try:
index_page = Page.objects.get(is_home=True, publisher_is_draft=False)
except Page.DoesNotExist:
log.debug('Create index page in "en" and...')
index_page = create_page(
title="index in English",
template=TEMPLATE_INHERITANCE_MAGIC,
language=settings.LANGUAGE_CODE,
published=False,
in_navigation=True)
placeholder, created = index_page.placeholders.get_or_create(
slot=placeholder_slot)
for language_code, lang_name in settings.LANGUAGES:
with translation.override(language_code):
title = 'index in %s' % lang_name
log.info('create %r', title)
if language_code != settings.LANGUAGE_CODE:
create_title(language_code, title, index_page)
add_plugin(
placeholder=placeholder,
plugin_type='TextPlugin', # djangocms_text_ckeditor
language=language_code,
body='index page in %s' % lang_name)
index_page.publish(language_code)
created = True
else:
created = False
log.debug('Index page already exists.')
return index_page, created | python | def create_cms_index_pages(placeholder_slot="content"):
"""
create cms home page and fill >content< placeholder with TextPlugin
"""
try:
index_page = Page.objects.get(is_home=True, publisher_is_draft=False)
except Page.DoesNotExist:
log.debug('Create index page in "en" and...')
index_page = create_page(
title="index in English",
template=TEMPLATE_INHERITANCE_MAGIC,
language=settings.LANGUAGE_CODE,
published=False,
in_navigation=True)
placeholder, created = index_page.placeholders.get_or_create(
slot=placeholder_slot)
for language_code, lang_name in settings.LANGUAGES:
with translation.override(language_code):
title = 'index in %s' % lang_name
log.info('create %r', title)
if language_code != settings.LANGUAGE_CODE:
create_title(language_code, title, index_page)
add_plugin(
placeholder=placeholder,
plugin_type='TextPlugin', # djangocms_text_ckeditor
language=language_code,
body='index page in %s' % lang_name)
index_page.publish(language_code)
created = True
else:
created = False
log.debug('Index page already exists.')
return index_page, created | [
"def",
"create_cms_index_pages",
"(",
"placeholder_slot",
"=",
"\"content\"",
")",
":",
"try",
":",
"index_page",
"=",
"Page",
".",
"objects",
".",
"get",
"(",
"is_home",
"=",
"True",
",",
"publisher_is_draft",
"=",
"False",
")",
"except",
"Page",
".",
"Does... | create cms home page and fill >content< placeholder with TextPlugin | [
"create",
"cms",
"home",
"page",
"and",
"fill",
">",
"content<",
"placeholder",
"with",
"TextPlugin"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L372-L406 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | create_cms_plugin_page | def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None):
"""
Create cms plugin page in all existing languages.
Add a link to the index page.
:param apphook: e.g...........: 'FooBarApp'
:param apphook_namespace: e.g.: 'foobar'
:return:
"""
creator = CmsPluginPageCreator(
apphook=apphook,
apphook_namespace=apphook_namespace,
)
creator.placeholder_slot = placeholder_slot
plugin_page = creator.create()
return plugin_page | python | def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None):
"""
Create cms plugin page in all existing languages.
Add a link to the index page.
:param apphook: e.g...........: 'FooBarApp'
:param apphook_namespace: e.g.: 'foobar'
:return:
"""
creator = CmsPluginPageCreator(
apphook=apphook,
apphook_namespace=apphook_namespace,
)
creator.placeholder_slot = placeholder_slot
plugin_page = creator.create()
return plugin_page | [
"def",
"create_cms_plugin_page",
"(",
"apphook",
",",
"apphook_namespace",
",",
"placeholder_slot",
"=",
"None",
")",
":",
"creator",
"=",
"CmsPluginPageCreator",
"(",
"apphook",
"=",
"apphook",
",",
"apphook_namespace",
"=",
"apphook_namespace",
",",
")",
"creator"... | Create cms plugin page in all existing languages.
Add a link to the index page.
:param apphook: e.g...........: 'FooBarApp'
:param apphook_namespace: e.g.: 'foobar'
:return: | [
"Create",
"cms",
"plugin",
"page",
"in",
"all",
"existing",
"languages",
".",
"Add",
"a",
"link",
"to",
"the",
"index",
"page",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L458-L473 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.get_slug | def get_slug(self, language_code, lang_name):
"""
Notes:
- slug must be unique!
- slug is used to check if page already exists!
:return: 'slug' string for cms.api.create_page()
"""
title = self.get_title(language_code, lang_name)
assert title != ""
title = str(title) # e.g.: evaluate a lazy translation
slug = slugify(title)
assert slug != "", "Title %r results in empty slug!" % title
return slug | python | def get_slug(self, language_code, lang_name):
"""
Notes:
- slug must be unique!
- slug is used to check if page already exists!
:return: 'slug' string for cms.api.create_page()
"""
title = self.get_title(language_code, lang_name)
assert title != ""
title = str(title) # e.g.: evaluate a lazy translation
slug = slugify(title)
assert slug != "", "Title %r results in empty slug!" % title
return slug | [
"def",
"get_slug",
"(",
"self",
",",
"language_code",
",",
"lang_name",
")",
":",
"title",
"=",
"self",
".",
"get_title",
"(",
"language_code",
",",
"lang_name",
")",
"assert",
"title",
"!=",
"\"\"",
"title",
"=",
"str",
"(",
"title",
")",
"# e.g.: evaluat... | Notes:
- slug must be unique!
- slug is used to check if page already exists!
:return: 'slug' string for cms.api.create_page() | [
"Notes",
":",
"-",
"slug",
"must",
"be",
"unique!",
"-",
"slug",
"is",
"used",
"to",
"check",
"if",
"page",
"already",
"exists!",
":",
"return",
":",
"slug",
"string",
"for",
"cms",
".",
"api",
".",
"create_page",
"()"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L107-L121 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.get_home_page | def get_home_page(self):
"""
Return the published home page.
Used for 'parent' in cms.api.create_page()
"""
try:
home_page_draft = Page.objects.get(
is_home=True, publisher_is_draft=True)
except Page.DoesNotExist:
log.error('ERROR: "home page" doesn\'t exists!')
raise RuntimeError('no home page')
return home_page_draft | python | def get_home_page(self):
"""
Return the published home page.
Used for 'parent' in cms.api.create_page()
"""
try:
home_page_draft = Page.objects.get(
is_home=True, publisher_is_draft=True)
except Page.DoesNotExist:
log.error('ERROR: "home page" doesn\'t exists!')
raise RuntimeError('no home page')
return home_page_draft | [
"def",
"get_home_page",
"(",
"self",
")",
":",
"try",
":",
"home_page_draft",
"=",
"Page",
".",
"objects",
".",
"get",
"(",
"is_home",
"=",
"True",
",",
"publisher_is_draft",
"=",
"True",
")",
"except",
"Page",
".",
"DoesNotExist",
":",
"log",
".",
"erro... | Return the published home page.
Used for 'parent' in cms.api.create_page() | [
"Return",
"the",
"published",
"home",
"page",
".",
"Used",
"for",
"parent",
"in",
"cms",
".",
"api",
".",
"create_page",
"()"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L129-L140 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.publish | def publish(self, page):
"""
Publish the page in all languages.
"""
assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page
publish_page(page, languages=self.languages) | python | def publish(self, page):
"""
Publish the page in all languages.
"""
assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page
publish_page(page, languages=self.languages) | [
"def",
"publish",
"(",
"self",
",",
"page",
")",
":",
"assert",
"page",
".",
"publisher_is_draft",
"==",
"True",
",",
"\"Page '%s' must be a draft!\"",
"%",
"page",
"publish_page",
"(",
"page",
",",
"languages",
"=",
"self",
".",
"languages",
")"
] | Publish the page in all languages. | [
"Publish",
"the",
"page",
"in",
"all",
"languages",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L148-L153 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.create_page | def create_page(self, **extra_kwargs):
"""
Create page (and page title) in default language
extra_kwargs will be pass to cms.api.create_page()
e.g.:
extra_kwargs={
"soft_root": True,
"reverse_id": my_reverse_id,
}
"""
with translation.override(self.default_language_code):
# for evaluate the language name lazy translation
# e.g.: settings.LANGUAGE_CODE is not "en"
self.default_lang_name = dict(
self.languages)[self.default_language_code]
self.slug = self.get_slug(self.default_language_code,
self.default_lang_name)
assert self.slug != ""
page = None
parent = self.get_parent_page()
if parent is not None:
assert parent.publisher_is_draft == True, "Parent page '%s' must be a draft!" % parent
if self.delete_first:
if self.apphook_namespace is not None:
pages = Page.objects.filter(
application_namespace=self.apphook_namespace,
parent=parent,
)
else:
pages = Page.objects.filter(
title_set__slug=self.slug,
parent=parent,
)
log.debug("Delete %i pages...", pages.count())
pages.delete()
else:
if self.apphook_namespace is not None:
# Create a plugin page
queryset = Page.objects.drafts()
queryset = queryset.filter(parent=parent)
try:
page = queryset.get(
application_namespace=self.apphook_namespace)
except Page.DoesNotExist:
pass # Create page
else:
log.debug("Use existing page: %s", page)
created = False
return page, created
else:
# Not a plugin page
queryset = Title.objects.filter(
language=self.default_language_code)
queryset = queryset.filter(page__parent=parent)
try:
title = queryset.filter(slug=self.slug).first()
except Title.DoesNotExist:
pass # Create page
else:
if title is not None:
log.debug("Use page from title with slug %r",
self.slug)
page = title.page
created = False
if page is None:
with translation.override(self.default_language_code):
# set right translation language
# for evaluate language name lazy translation
# e.g.: settings.LANGUAGE_CODE is not "en"
page = create_page(
title=self.get_title(self.default_language_code,
self.default_lang_name),
menu_title=self.get_menu_title(self.default_language_code,
self.default_lang_name),
template=self.get_template(self.default_language_code,
self.default_lang_name),
language=self.default_language_code,
slug=self.slug,
published=False,
parent=parent,
in_navigation=self.in_navigation,
apphook=self.apphook,
apphook_namespace=self.apphook_namespace,
**extra_kwargs)
created = True
log.debug("Page created in %s: %s", self.default_lang_name,
page)
assert page.publisher_is_draft == True
return page, created | python | def create_page(self, **extra_kwargs):
"""
Create page (and page title) in default language
extra_kwargs will be pass to cms.api.create_page()
e.g.:
extra_kwargs={
"soft_root": True,
"reverse_id": my_reverse_id,
}
"""
with translation.override(self.default_language_code):
# for evaluate the language name lazy translation
# e.g.: settings.LANGUAGE_CODE is not "en"
self.default_lang_name = dict(
self.languages)[self.default_language_code]
self.slug = self.get_slug(self.default_language_code,
self.default_lang_name)
assert self.slug != ""
page = None
parent = self.get_parent_page()
if parent is not None:
assert parent.publisher_is_draft == True, "Parent page '%s' must be a draft!" % parent
if self.delete_first:
if self.apphook_namespace is not None:
pages = Page.objects.filter(
application_namespace=self.apphook_namespace,
parent=parent,
)
else:
pages = Page.objects.filter(
title_set__slug=self.slug,
parent=parent,
)
log.debug("Delete %i pages...", pages.count())
pages.delete()
else:
if self.apphook_namespace is not None:
# Create a plugin page
queryset = Page.objects.drafts()
queryset = queryset.filter(parent=parent)
try:
page = queryset.get(
application_namespace=self.apphook_namespace)
except Page.DoesNotExist:
pass # Create page
else:
log.debug("Use existing page: %s", page)
created = False
return page, created
else:
# Not a plugin page
queryset = Title.objects.filter(
language=self.default_language_code)
queryset = queryset.filter(page__parent=parent)
try:
title = queryset.filter(slug=self.slug).first()
except Title.DoesNotExist:
pass # Create page
else:
if title is not None:
log.debug("Use page from title with slug %r",
self.slug)
page = title.page
created = False
if page is None:
with translation.override(self.default_language_code):
# set right translation language
# for evaluate language name lazy translation
# e.g.: settings.LANGUAGE_CODE is not "en"
page = create_page(
title=self.get_title(self.default_language_code,
self.default_lang_name),
menu_title=self.get_menu_title(self.default_language_code,
self.default_lang_name),
template=self.get_template(self.default_language_code,
self.default_lang_name),
language=self.default_language_code,
slug=self.slug,
published=False,
parent=parent,
in_navigation=self.in_navigation,
apphook=self.apphook,
apphook_namespace=self.apphook_namespace,
**extra_kwargs)
created = True
log.debug("Page created in %s: %s", self.default_lang_name,
page)
assert page.publisher_is_draft == True
return page, created | [
"def",
"create_page",
"(",
"self",
",",
"*",
"*",
"extra_kwargs",
")",
":",
"with",
"translation",
".",
"override",
"(",
"self",
".",
"default_language_code",
")",
":",
"# for evaluate the language name lazy translation",
"# e.g.: settings.LANGUAGE_CODE is not \"en\"",
"s... | Create page (and page title) in default language
extra_kwargs will be pass to cms.api.create_page()
e.g.:
extra_kwargs={
"soft_root": True,
"reverse_id": my_reverse_id,
} | [
"Create",
"page",
"(",
"and",
"page",
"title",
")",
"in",
"default",
"language"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L155-L250 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.create_title | def create_title(self, page):
"""
Create page title in all other languages with cms.api.create_title()
"""
for language_code, lang_name in iter_languages(self.languages):
try:
title = Title.objects.get(page=page, language=language_code)
except Title.DoesNotExist:
slug = self.get_slug(language_code, lang_name)
assert slug != "", "No slug for %r" % language_code
title = create_title(
language=language_code,
title=self.get_title(language_code, lang_name),
page=page,
slug=slug,
)
log.debug("Title created: %s", title)
else:
log.debug("Page title exist: %s", title) | python | def create_title(self, page):
"""
Create page title in all other languages with cms.api.create_title()
"""
for language_code, lang_name in iter_languages(self.languages):
try:
title = Title.objects.get(page=page, language=language_code)
except Title.DoesNotExist:
slug = self.get_slug(language_code, lang_name)
assert slug != "", "No slug for %r" % language_code
title = create_title(
language=language_code,
title=self.get_title(language_code, lang_name),
page=page,
slug=slug,
)
log.debug("Title created: %s", title)
else:
log.debug("Page title exist: %s", title) | [
"def",
"create_title",
"(",
"self",
",",
"page",
")",
":",
"for",
"language_code",
",",
"lang_name",
"in",
"iter_languages",
"(",
"self",
".",
"languages",
")",
":",
"try",
":",
"title",
"=",
"Title",
".",
"objects",
".",
"get",
"(",
"page",
"=",
"page... | Create page title in all other languages with cms.api.create_title() | [
"Create",
"page",
"title",
"in",
"all",
"other",
"languages",
"with",
"cms",
".",
"api",
".",
"create_title",
"()"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L252-L270 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.get_add_plugin_kwargs | def get_add_plugin_kwargs(self, page, no, placeholder, language_code,
lang_name):
"""
Return "content" for create the plugin.
Called from self.add_plugins()
"""
return {
"plugin_type":
'TextPlugin', # djangocms_text_ckeditor
"body":
self.get_dummy_text(page, no, placeholder, language_code,
lang_name)
} | python | def get_add_plugin_kwargs(self, page, no, placeholder, language_code,
lang_name):
"""
Return "content" for create the plugin.
Called from self.add_plugins()
"""
return {
"plugin_type":
'TextPlugin', # djangocms_text_ckeditor
"body":
self.get_dummy_text(page, no, placeholder, language_code,
lang_name)
} | [
"def",
"get_add_plugin_kwargs",
"(",
"self",
",",
"page",
",",
"no",
",",
"placeholder",
",",
"language_code",
",",
"lang_name",
")",
":",
"return",
"{",
"\"plugin_type\"",
":",
"'TextPlugin'",
",",
"# djangocms_text_ckeditor",
"\"body\"",
":",
"self",
".",
"get... | Return "content" for create the plugin.
Called from self.add_plugins() | [
"Return",
"content",
"for",
"create",
"the",
"plugin",
".",
"Called",
"from",
"self",
".",
"add_plugins",
"()"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L289-L301 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.add_plugins | def add_plugins(self, page, placeholder):
"""
Add a "TextPlugin" in all languages.
"""
for language_code, lang_name in iter_languages(self.languages):
for no in range(1, self.dummy_text_count + 1):
add_plugin_kwargs = self.get_add_plugin_kwargs(
page, no, placeholder, language_code, lang_name)
log.info(
'add plugin to placeholder "%s" (pk:%i) in: %s - no: %i',
placeholder, placeholder.pk, lang_name, no)
plugin = add_plugin(
placeholder=placeholder,
language=language_code,
**add_plugin_kwargs)
log.info('Plugin "%s" (pk:%r) added.', str(plugin), plugin.pk)
placeholder.save() | python | def add_plugins(self, page, placeholder):
"""
Add a "TextPlugin" in all languages.
"""
for language_code, lang_name in iter_languages(self.languages):
for no in range(1, self.dummy_text_count + 1):
add_plugin_kwargs = self.get_add_plugin_kwargs(
page, no, placeholder, language_code, lang_name)
log.info(
'add plugin to placeholder "%s" (pk:%i) in: %s - no: %i',
placeholder, placeholder.pk, lang_name, no)
plugin = add_plugin(
placeholder=placeholder,
language=language_code,
**add_plugin_kwargs)
log.info('Plugin "%s" (pk:%r) added.', str(plugin), plugin.pk)
placeholder.save() | [
"def",
"add_plugins",
"(",
"self",
",",
"page",
",",
"placeholder",
")",
":",
"for",
"language_code",
",",
"lang_name",
"in",
"iter_languages",
"(",
"self",
".",
"languages",
")",
":",
"for",
"no",
"in",
"range",
"(",
"1",
",",
"self",
".",
"dummy_text_c... | Add a "TextPlugin" in all languages. | [
"Add",
"a",
"TextPlugin",
"in",
"all",
"languages",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L303-L320 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.get_or_create_placeholder | def get_or_create_placeholder(self, page, placeholder_slot):
"""
Add a placeholder if not exists.
"""
placeholder, created = get_or_create_placeholder(
page, placeholder_slot, delete_existing=self.delete_first)
return placeholder, created | python | def get_or_create_placeholder(self, page, placeholder_slot):
"""
Add a placeholder if not exists.
"""
placeholder, created = get_or_create_placeholder(
page, placeholder_slot, delete_existing=self.delete_first)
return placeholder, created | [
"def",
"get_or_create_placeholder",
"(",
"self",
",",
"page",
",",
"placeholder_slot",
")",
":",
"placeholder",
",",
"created",
"=",
"get_or_create_placeholder",
"(",
"page",
",",
"placeholder_slot",
",",
"delete_existing",
"=",
"self",
".",
"delete_first",
")",
"... | Add a placeholder if not exists. | [
"Add",
"a",
"placeholder",
"if",
"not",
"exists",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L322-L328 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPageCreator.fill_content | def fill_content(self, page, placeholder_slot):
"""
Add a placeholder to the page.
Here we add a "TextPlugin" in all languages.
"""
if len(placeholder_slot) == 1:
raise RuntimeError(placeholder_slot)
placeholder, created = self.get_or_create_placeholder(
page, placeholder_slot)
self.add_plugins(page, placeholder) | python | def fill_content(self, page, placeholder_slot):
"""
Add a placeholder to the page.
Here we add a "TextPlugin" in all languages.
"""
if len(placeholder_slot) == 1:
raise RuntimeError(placeholder_slot)
placeholder, created = self.get_or_create_placeholder(
page, placeholder_slot)
self.add_plugins(page, placeholder) | [
"def",
"fill_content",
"(",
"self",
",",
"page",
",",
"placeholder_slot",
")",
":",
"if",
"len",
"(",
"placeholder_slot",
")",
"==",
"1",
":",
"raise",
"RuntimeError",
"(",
"placeholder_slot",
")",
"placeholder",
",",
"created",
"=",
"self",
".",
"get_or_cre... | Add a placeholder to the page.
Here we add a "TextPlugin" in all languages. | [
"Add",
"a",
"placeholder",
"to",
"the",
"page",
".",
"Here",
"we",
"add",
"a",
"TextPlugin",
"in",
"all",
"languages",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L330-L339 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | CmsPluginPageCreator.create | def create(self):
"""
Create the plugin page in all languages and fill dummy content.
"""
plugin = CMSPlugin.objects.filter(plugin_type=self.apphook)
if plugin.exists():
log.debug('Plugin page for "%s" plugin already exist, ok.',
self.apphook)
raise plugin
page, created = super(CmsPluginPageCreator, self).create()
if created:
# Add a plugin with content in all languages to the created page.
# But only on new created page
for placeholder_slot in self.placeholder_slots:
self.fill_content(page, placeholder_slot)
return page, created | python | def create(self):
"""
Create the plugin page in all languages and fill dummy content.
"""
plugin = CMSPlugin.objects.filter(plugin_type=self.apphook)
if plugin.exists():
log.debug('Plugin page for "%s" plugin already exist, ok.',
self.apphook)
raise plugin
page, created = super(CmsPluginPageCreator, self).create()
if created:
# Add a plugin with content in all languages to the created page.
# But only on new created page
for placeholder_slot in self.placeholder_slots:
self.fill_content(page, placeholder_slot)
return page, created | [
"def",
"create",
"(",
"self",
")",
":",
"plugin",
"=",
"CMSPlugin",
".",
"objects",
".",
"filter",
"(",
"plugin_type",
"=",
"self",
".",
"apphook",
")",
"if",
"plugin",
".",
"exists",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Plugin page for \"%s\" plug... | Create the plugin page in all languages and fill dummy content. | [
"Create",
"the",
"plugin",
"page",
"in",
"all",
"languages",
"and",
"fill",
"dummy",
"content",
"."
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L437-L455 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | DummyPageGenerator.get_title | def get_title(self, language_code, lang_name):
"""
:return: 'title' string for cms.api.create_page()
"""
title = "%s %i-%i in %s" % (self.title_prefix, self.current_count,
self.current_level, language_code)
log.info(title)
return title | python | def get_title(self, language_code, lang_name):
"""
:return: 'title' string for cms.api.create_page()
"""
title = "%s %i-%i in %s" % (self.title_prefix, self.current_count,
self.current_level, language_code)
log.info(title)
return title | [
"def",
"get_title",
"(",
"self",
",",
"language_code",
",",
"lang_name",
")",
":",
"title",
"=",
"\"%s %i-%i in %s\"",
"%",
"(",
"self",
".",
"title_prefix",
",",
"self",
".",
"current_count",
",",
"self",
".",
"current_level",
",",
"language_code",
")",
"lo... | :return: 'title' string for cms.api.create_page() | [
":",
"return",
":",
"title",
"string",
"for",
"cms",
".",
"api",
".",
"create_page",
"()"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L494-L501 |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | DummyPageGenerator.get_parent_page | def get_parent_page(self):
"""
For 'parent' in cms.api.create_page()
"""
if self.current_level == 1:
# 'root' page
return None
else:
return self.page_data[(self.current_level - 1, self.current_count)] | python | def get_parent_page(self):
"""
For 'parent' in cms.api.create_page()
"""
if self.current_level == 1:
# 'root' page
return None
else:
return self.page_data[(self.current_level - 1, self.current_count)] | [
"def",
"get_parent_page",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_level",
"==",
"1",
":",
"# 'root' page",
"return",
"None",
"else",
":",
"return",
"self",
".",
"page_data",
"[",
"(",
"self",
".",
"current_level",
"-",
"1",
",",
"self",
".",
... | For 'parent' in cms.api.create_page() | [
"For",
"parent",
"in",
"cms",
".",
"api",
".",
"create_page",
"()"
] | train | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L503-L511 |
SmartTeleMax/iktomi | iktomi/web/filters.py | static_files.translate_path | def translate_path(self, pth):
"""Translate a /-separated PATH to the local filename syntax."""
# initially copied from SimpleHTTPServer
words = pth.split('/')
words = filter(None, words)
pth = self.location
for word in words:
# Do not allow path separators other than /,
# drive names and . ..
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if drive or head or word in (os.curdir, os.pardir):
return None
pth = os.path.join(pth, word)
assert pth.startswith(self.location + '/')
assert pth == path.normpath(pth)
return pth | python | def translate_path(self, pth):
"""Translate a /-separated PATH to the local filename syntax."""
# initially copied from SimpleHTTPServer
words = pth.split('/')
words = filter(None, words)
pth = self.location
for word in words:
# Do not allow path separators other than /,
# drive names and . ..
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if drive or head or word in (os.curdir, os.pardir):
return None
pth = os.path.join(pth, word)
assert pth.startswith(self.location + '/')
assert pth == path.normpath(pth)
return pth | [
"def",
"translate_path",
"(",
"self",
",",
"pth",
")",
":",
"# initially copied from SimpleHTTPServer",
"words",
"=",
"pth",
".",
"split",
"(",
"'/'",
")",
"words",
"=",
"filter",
"(",
"None",
",",
"words",
")",
"pth",
"=",
"self",
".",
"location",
"for",
... | Translate a /-separated PATH to the local filename syntax. | [
"Translate",
"a",
"/",
"-",
"separated",
"PATH",
"to",
"the",
"local",
"filename",
"syntax",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/filters.py#L330-L347 |
CivicSpleen/ambry | ambry/orm/source_table.py | SourceColumn.dict | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
from collections import OrderedDict
SKIP_KEYS = ()
return OrderedDict(
(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in SKIP_KEYS) | python | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
from collections import OrderedDict
SKIP_KEYS = ()
return OrderedDict(
(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in SKIP_KEYS) | [
"def",
"dict",
"(",
"self",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"SKIP_KEYS",
"=",
"(",
")",
"return",
"OrderedDict",
"(",
"(",
"p",
".",
"key",
",",
"getattr",
"(",
"self",
",",
"p",
".",
"key",
")",
")",
"for",
"p",
"in",
"se... | A dict that holds key/values for all of the properties in the
object.
:return: | [
"A",
"dict",
"that",
"holds",
"key",
"/",
"values",
"for",
"all",
"of",
"the",
"properties",
"in",
"the",
"object",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source_table.py#L143-L153 |
CivicSpleen/ambry | ambry/orm/source_table.py | SourceTable.column | def column(self, source_header_or_pos):
"""
Return a column by name or position
:param source_header_or_pos: If a string, a source header name. If an integer, column position
:return:
"""
for c in self.columns:
if c.source_header == source_header_or_pos:
assert c.st_vid == self.vid
return c
elif c.position == source_header_or_pos:
assert c.st_vid == self.vid
return c
else:
return None | python | def column(self, source_header_or_pos):
"""
Return a column by name or position
:param source_header_or_pos: If a string, a source header name. If an integer, column position
:return:
"""
for c in self.columns:
if c.source_header == source_header_or_pos:
assert c.st_vid == self.vid
return c
elif c.position == source_header_or_pos:
assert c.st_vid == self.vid
return c
else:
return None | [
"def",
"column",
"(",
"self",
",",
"source_header_or_pos",
")",
":",
"for",
"c",
"in",
"self",
".",
"columns",
":",
"if",
"c",
".",
"source_header",
"==",
"source_header_or_pos",
":",
"assert",
"c",
".",
"st_vid",
"==",
"self",
".",
"vid",
"return",
"c",... | Return a column by name or position
:param source_header_or_pos: If a string, a source header name. If an integer, column position
:return: | [
"Return",
"a",
"column",
"by",
"name",
"or",
"position"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source_table.py#L186-L202 |
CivicSpleen/ambry | ambry/orm/source_table.py | SourceTable.add_column | def add_column(self, position, source_header, datatype, **kwargs):
"""
Add a column to the source table.
:param position: Integer position of the column started from 1.
:param source_header: Name of the column, as it exists in the source file
:param datatype: Python datatype ( str, int, float, None ) for the column
:param kwargs: Other source record args.
:return:
"""
from ..identity import GeneralNumber2
c = self.column(source_header)
c_by_pos = self.column(position)
datatype = 'str' if datatype == 'unicode' else datatype
assert not c or not c_by_pos or c.vid == c_by_pos.vid
# Convert almost anything to True / False
if 'has_codes' in kwargs:
FALSE_VALUES = ['False', 'false', 'F', 'f', '', None, 0, '0']
kwargs['has_codes'] = False if kwargs['has_codes'] in FALSE_VALUES else True
if c:
# Changing the position can result in conflicts
assert not c_by_pos or c_by_pos.vid == c.vid
c.update(
position=position,
datatype=datatype.__name__ if isinstance(datatype, type) else datatype,
**kwargs)
elif c_by_pos:
# FIXME This feels wrong; there probably should not be any changes to the both
# of the table, since then it won't represent the previouls source. Maybe all of the sources
# should get their own tables initially, then affterward the duplicates can be removed.
assert not c or c_by_pos.vid == c.vid
c_by_pos.update(
source_header=source_header,
datatype=datatype.__name__ if isinstance(datatype, type) else datatype,
**kwargs)
else:
assert not c and not c_by_pos
# Hacking an id number, since I don't want to create a new Identity ObjectNUmber type
c = SourceColumn(
vid=str(GeneralNumber2('C', self.d_vid, self.sequence_id, int(position))),
position=position,
st_vid=self.vid,
d_vid=self.d_vid,
datatype=datatype.__name__ if isinstance(datatype, type) else datatype,
source_header=source_header,
**kwargs)
self.columns.append(c)
return c | python | def add_column(self, position, source_header, datatype, **kwargs):
"""
Add a column to the source table.
:param position: Integer position of the column started from 1.
:param source_header: Name of the column, as it exists in the source file
:param datatype: Python datatype ( str, int, float, None ) for the column
:param kwargs: Other source record args.
:return:
"""
from ..identity import GeneralNumber2
c = self.column(source_header)
c_by_pos = self.column(position)
datatype = 'str' if datatype == 'unicode' else datatype
assert not c or not c_by_pos or c.vid == c_by_pos.vid
# Convert almost anything to True / False
if 'has_codes' in kwargs:
FALSE_VALUES = ['False', 'false', 'F', 'f', '', None, 0, '0']
kwargs['has_codes'] = False if kwargs['has_codes'] in FALSE_VALUES else True
if c:
# Changing the position can result in conflicts
assert not c_by_pos or c_by_pos.vid == c.vid
c.update(
position=position,
datatype=datatype.__name__ if isinstance(datatype, type) else datatype,
**kwargs)
elif c_by_pos:
# FIXME This feels wrong; there probably should not be any changes to the both
# of the table, since then it won't represent the previouls source. Maybe all of the sources
# should get their own tables initially, then affterward the duplicates can be removed.
assert not c or c_by_pos.vid == c.vid
c_by_pos.update(
source_header=source_header,
datatype=datatype.__name__ if isinstance(datatype, type) else datatype,
**kwargs)
else:
assert not c and not c_by_pos
# Hacking an id number, since I don't want to create a new Identity ObjectNUmber type
c = SourceColumn(
vid=str(GeneralNumber2('C', self.d_vid, self.sequence_id, int(position))),
position=position,
st_vid=self.vid,
d_vid=self.d_vid,
datatype=datatype.__name__ if isinstance(datatype, type) else datatype,
source_header=source_header,
**kwargs)
self.columns.append(c)
return c | [
"def",
"add_column",
"(",
"self",
",",
"position",
",",
"source_header",
",",
"datatype",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"identity",
"import",
"GeneralNumber2",
"c",
"=",
"self",
".",
"column",
"(",
"source_header",
")",
"c_by_pos",
... | Add a column to the source table.
:param position: Integer position of the column started from 1.
:param source_header: Name of the column, as it exists in the source file
:param datatype: Python datatype ( str, int, float, None ) for the column
:param kwargs: Other source record args.
:return: | [
"Add",
"a",
"column",
"to",
"the",
"source",
"table",
".",
":",
"param",
"position",
":",
"Integer",
"position",
"of",
"the",
"column",
"started",
"from",
"1",
".",
":",
"param",
"source_header",
":",
"Name",
"of",
"the",
"column",
"as",
"it",
"exists",
... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source_table.py#L204-L266 |
CivicSpleen/ambry | ambry/orm/source_table.py | SourceTable.update_id | def update_id(self, sequence_id=None):
"""Alter the sequence id, and all of the names and ids derived from it. This
often needs to be don after an IntegrityError in a multiprocessing run"""
from ..identity import GeneralNumber1
if sequence_id:
self.sequence_id = sequence_id
self.vid = str(GeneralNumber1('T', self.d_vid, self.sequence_id)) | python | def update_id(self, sequence_id=None):
"""Alter the sequence id, and all of the names and ids derived from it. This
often needs to be don after an IntegrityError in a multiprocessing run"""
from ..identity import GeneralNumber1
if sequence_id:
self.sequence_id = sequence_id
self.vid = str(GeneralNumber1('T', self.d_vid, self.sequence_id)) | [
"def",
"update_id",
"(",
"self",
",",
"sequence_id",
"=",
"None",
")",
":",
"from",
".",
".",
"identity",
"import",
"GeneralNumber1",
"if",
"sequence_id",
":",
"self",
".",
"sequence_id",
"=",
"sequence_id",
"self",
".",
"vid",
"=",
"str",
"(",
"GeneralNum... | Alter the sequence id, and all of the names and ids derived from it. This
often needs to be don after an IntegrityError in a multiprocessing run | [
"Alter",
"the",
"sequence",
"id",
"and",
"all",
"of",
"the",
"names",
"and",
"ids",
"derived",
"from",
"it",
".",
"This",
"often",
"needs",
"to",
"be",
"don",
"after",
"an",
"IntegrityError",
"in",
"a",
"multiprocessing",
"run"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source_table.py#L292-L300 |
CivicSpleen/ambry | ambry/orm/__init__.py | table_convert_geometry | def table_convert_geometry(metadata, table_name):
"""Get table metadata from the database."""
from sqlalchemy import Table
from ..orm import Geometry
table = Table(table_name, metadata, autoload=True)
for c in table.columns:
# HACK! Sqlalchemy sees spatialte GEOMETRY types
# as NUMERIC
if c.name == 'geometry':
c.type = Geometry # What about variants?
return table | python | def table_convert_geometry(metadata, table_name):
"""Get table metadata from the database."""
from sqlalchemy import Table
from ..orm import Geometry
table = Table(table_name, metadata, autoload=True)
for c in table.columns:
# HACK! Sqlalchemy sees spatialte GEOMETRY types
# as NUMERIC
if c.name == 'geometry':
c.type = Geometry # What about variants?
return table | [
"def",
"table_convert_geometry",
"(",
"metadata",
",",
"table_name",
")",
":",
"from",
"sqlalchemy",
"import",
"Table",
"from",
".",
".",
"orm",
"import",
"Geometry",
"table",
"=",
"Table",
"(",
"table_name",
",",
"metadata",
",",
"autoload",
"=",
"True",
")... | Get table metadata from the database. | [
"Get",
"table",
"metadata",
"from",
"the",
"database",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/__init__.py#L74-L89 |
CivicSpleen/ambry | ambry/orm/__init__.py | next_sequence_id | def next_sequence_id(session, sequence_ids, parent_vid, table_class, force_query = False):
"""
Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix
for the child object. On the first call, will load the max sequence number
from the database, but subsequence calls will run in process, so this isn't suitable for
multi-process operation -- all of the tables in a dataset should be created by one process
The child table must have a sequence_id value.
:param session: Database session or connection ( must have an execute() method )
:param sequence_ids: A dict for caching sequence ids
:param parent_vid: The VID of the parent object, which sets the namespace for the sequence
:param table_class: Table class of the child object, the one getting a number
:return:
"""
from sqlalchemy import text
seq_col = table_class.sequence_id.property.columns[0].name
try:
parent_col = table_class._parent_col
except AttributeError:
parent_col = table_class.d_vid.property.columns[0].name
assert bool(parent_vid)
key = (parent_vid, table_class.__name__)
number = sequence_ids.get(key, None)
if (not number and session) or force_query:
sql = text("SELECT max({seq_col})+1 FROM {table} WHERE {parent_col} = '{vid}'"
.format(table=table_class.__tablename__, parent_col=parent_col,
seq_col=seq_col, vid=parent_vid))
max_id, = session.execute(sql).fetchone()
if not max_id:
max_id = 1
sequence_ids[key] = int(max_id)
elif not session:
# There was no session set. This should only happen when the parent object is new, and therefore,
# there are no child number, so the appropriate starting number is 1. If the object is not new,
# there will be conflicts.
sequence_ids[key] = 1
else:
# There were no previous numbers, so start with 1
sequence_ids[key] += 1
return sequence_ids[key] | python | def next_sequence_id(session, sequence_ids, parent_vid, table_class, force_query = False):
"""
Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix
for the child object. On the first call, will load the max sequence number
from the database, but subsequence calls will run in process, so this isn't suitable for
multi-process operation -- all of the tables in a dataset should be created by one process
The child table must have a sequence_id value.
:param session: Database session or connection ( must have an execute() method )
:param sequence_ids: A dict for caching sequence ids
:param parent_vid: The VID of the parent object, which sets the namespace for the sequence
:param table_class: Table class of the child object, the one getting a number
:return:
"""
from sqlalchemy import text
seq_col = table_class.sequence_id.property.columns[0].name
try:
parent_col = table_class._parent_col
except AttributeError:
parent_col = table_class.d_vid.property.columns[0].name
assert bool(parent_vid)
key = (parent_vid, table_class.__name__)
number = sequence_ids.get(key, None)
if (not number and session) or force_query:
sql = text("SELECT max({seq_col})+1 FROM {table} WHERE {parent_col} = '{vid}'"
.format(table=table_class.__tablename__, parent_col=parent_col,
seq_col=seq_col, vid=parent_vid))
max_id, = session.execute(sql).fetchone()
if not max_id:
max_id = 1
sequence_ids[key] = int(max_id)
elif not session:
# There was no session set. This should only happen when the parent object is new, and therefore,
# there are no child number, so the appropriate starting number is 1. If the object is not new,
# there will be conflicts.
sequence_ids[key] = 1
else:
# There were no previous numbers, so start with 1
sequence_ids[key] += 1
return sequence_ids[key] | [
"def",
"next_sequence_id",
"(",
"session",
",",
"sequence_ids",
",",
"parent_vid",
",",
"table_class",
",",
"force_query",
"=",
"False",
")",
":",
"from",
"sqlalchemy",
"import",
"text",
"seq_col",
"=",
"table_class",
".",
"sequence_id",
".",
"property",
".",
... | Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix
for the child object. On the first call, will load the max sequence number
from the database, but subsequence calls will run in process, so this isn't suitable for
multi-process operation -- all of the tables in a dataset should be created by one process
The child table must have a sequence_id value.
:param session: Database session or connection ( must have an execute() method )
:param sequence_ids: A dict for caching sequence ids
:param parent_vid: The VID of the parent object, which sets the namespace for the sequence
:param table_class: Table class of the child object, the one getting a number
:return: | [
"Return",
"the",
"next",
"sequence",
"id",
"for",
"a",
"object",
"identified",
"by",
"the",
"vid",
"of",
"the",
"parent",
"object",
"and",
"the",
"database",
"prefix",
"for",
"the",
"child",
"object",
".",
"On",
"the",
"first",
"call",
"will",
"load",
"t... | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/__init__.py#L351-L405 |
CivicSpleen/ambry | ambry/orm/__init__.py | incver | def incver(o, prop_names):
"""Increment the version numbers of a set of properties and return a new object"""
from ambry.identity import ObjectNumber
d = {}
for p in o.__mapper__.attrs:
v = getattr(o, p.key)
if v is None:
d[p.key] = None
elif p.key in prop_names:
d[p.key] = str(ObjectNumber.increment(v))
else:
if not hasattr(v, '__mapper__'): # Only copy values, never objects
d[p.key] = v
return o.__class__(**d) | python | def incver(o, prop_names):
"""Increment the version numbers of a set of properties and return a new object"""
from ambry.identity import ObjectNumber
d = {}
for p in o.__mapper__.attrs:
v = getattr(o, p.key)
if v is None:
d[p.key] = None
elif p.key in prop_names:
d[p.key] = str(ObjectNumber.increment(v))
else:
if not hasattr(v, '__mapper__'): # Only copy values, never objects
d[p.key] = v
return o.__class__(**d) | [
"def",
"incver",
"(",
"o",
",",
"prop_names",
")",
":",
"from",
"ambry",
".",
"identity",
"import",
"ObjectNumber",
"d",
"=",
"{",
"}",
"for",
"p",
"in",
"o",
".",
"__mapper__",
".",
"attrs",
":",
"v",
"=",
"getattr",
"(",
"o",
",",
"p",
".",
"ke... | Increment the version numbers of a set of properties and return a new object | [
"Increment",
"the",
"version",
"numbers",
"of",
"a",
"set",
"of",
"properties",
"and",
"return",
"a",
"new",
"object"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/__init__.py#L408-L424 |
CivicSpleen/ambry | ambry/orm/__init__.py | MutationList.coerce | def coerce(cls, key, value):
"""Convert plain list to MutationList."""
if isinstance(value, string_types):
value = value.strip()
if value[0] == '[': # It's json encoded, probably
try:
value = json.loads(value)
except ValueError:
raise ValueError("Failed to parse JSON: '{}' ".format(value))
else:
value = value.split(',')
if not value:
value = []
self = MutationList((MutationObj.coerce(key, v) for v in value))
self._key = key
return self | python | def coerce(cls, key, value):
"""Convert plain list to MutationList."""
if isinstance(value, string_types):
value = value.strip()
if value[0] == '[': # It's json encoded, probably
try:
value = json.loads(value)
except ValueError:
raise ValueError("Failed to parse JSON: '{}' ".format(value))
else:
value = value.split(',')
if not value:
value = []
self = MutationList((MutationObj.coerce(key, v) for v in value))
self._key = key
return self | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"value",
"[",
"0",
"]",
"==",
"'['",
":",
"# It's json encoded, pro... | Convert plain list to MutationList. | [
"Convert",
"plain",
"list",
"to",
"MutationList",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/__init__.py#L214-L232 |
CivicSpleen/ambry | ambry/bundle/asql_parser.py | parse_view | def parse_view(query):
""" Parses asql query to view object.
Args:
query (str): asql query
Returns:
View instance: parsed view.
"""
try:
idx = query.lower().index('where')
query = query[:idx]
except ValueError:
pass
if not query.endswith(';'):
query = query.strip()
query += ';'
result = _view_stmt.parseString(query)
return View(result) | python | def parse_view(query):
""" Parses asql query to view object.
Args:
query (str): asql query
Returns:
View instance: parsed view.
"""
try:
idx = query.lower().index('where')
query = query[:idx]
except ValueError:
pass
if not query.endswith(';'):
query = query.strip()
query += ';'
result = _view_stmt.parseString(query)
return View(result) | [
"def",
"parse_view",
"(",
"query",
")",
":",
"try",
":",
"idx",
"=",
"query",
".",
"lower",
"(",
")",
".",
"index",
"(",
"'where'",
")",
"query",
"=",
"query",
"[",
":",
"idx",
"]",
"except",
"ValueError",
":",
"pass",
"if",
"not",
"query",
".",
... | Parses asql query to view object.
Args:
query (str): asql query
Returns:
View instance: parsed view. | [
"Parses",
"asql",
"query",
"to",
"view",
"object",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/asql_parser.py#L36-L58 |
CivicSpleen/ambry | ambry/bundle/asql_parser.py | _flat_alias | def _flat_alias(t):
""" Populates token (column or table) fields from parse result. """
t.name = t.parsed_name
t.alias = t.parsed_alias[0] if t.parsed_alias else ''
return t | python | def _flat_alias(t):
""" Populates token (column or table) fields from parse result. """
t.name = t.parsed_name
t.alias = t.parsed_alias[0] if t.parsed_alias else ''
return t | [
"def",
"_flat_alias",
"(",
"t",
")",
":",
"t",
".",
"name",
"=",
"t",
".",
"parsed_name",
"t",
".",
"alias",
"=",
"t",
".",
"parsed_alias",
"[",
"0",
"]",
"if",
"t",
".",
"parsed_alias",
"else",
"''",
"return",
"t"
] | Populates token (column or table) fields from parse result. | [
"Populates",
"token",
"(",
"column",
"or",
"table",
")",
"fields",
"from",
"parse",
"result",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/asql_parser.py#L170-L174 |
CivicSpleen/ambry | ambry/bundle/asql_parser.py | _build_join | def _build_join(t):
""" Populates join token fields. """
t.source.name = t.source.parsed_name
t.source.alias = t.source.parsed_alias[0] if t.source.parsed_alias else ''
return t | python | def _build_join(t):
""" Populates join token fields. """
t.source.name = t.source.parsed_name
t.source.alias = t.source.parsed_alias[0] if t.source.parsed_alias else ''
return t | [
"def",
"_build_join",
"(",
"t",
")",
":",
"t",
".",
"source",
".",
"name",
"=",
"t",
".",
"source",
".",
"parsed_name",
"t",
".",
"source",
".",
"alias",
"=",
"t",
".",
"source",
".",
"parsed_alias",
"[",
"0",
"]",
"if",
"t",
".",
"source",
".",
... | Populates join token fields. | [
"Populates",
"join",
"token",
"fields",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/asql_parser.py#L177-L182 |
CivicSpleen/ambry | ambry/bundle/asql_parser.py | substitute_vids | def substitute_vids(library, statement):
""" Replace all of the references to tables and partitions with their vids.
This is a bit of a hack -- it ought to work with the parser, but instead it just looks for
common SQL tokens that indicate an identifier.
:param statement: an sqlstatement. String.
:return: tuple: new_statement, set of table vids, set of partition vids.
"""
from ambry.identity import ObjectNumber, TableNumber, NotObjectNumberError
from ambry.orm.exc import NotFoundError
try:
stmt_str = statement.to_unicode()
except AttributeError:
stmt_str = statement
parts = stmt_str.strip(';').split()
new_parts = []
tables = set()
partitions = set()
while parts:
token = parts.pop(0).strip()
if token.lower() in ('from', 'join', 'materialize', 'install'):
ident = parts.pop(0).strip(';')
new_parts.append(token)
try:
obj_number = ObjectNumber.parse(token)
if isinstance(obj_number, TableNumber):
table = library.table(ident)
tables.add(table.vid)
new_parts.append(table.vid)
else:
# Do not care about other object numbers. Assume partition.
raise NotObjectNumberError
except NotObjectNumberError:
# assume partition
try:
partition = library.partition(ident)
partitions.add(partition.vid)
new_parts.append(partition.vid)
except NotFoundError:
# Ok, maybe it is just a normal identifier...
new_parts.append(ident)
else:
new_parts.append(token)
return ' '.join(new_parts).strip(), tables, partitions | python | def substitute_vids(library, statement):
""" Replace all of the references to tables and partitions with their vids.
This is a bit of a hack -- it ought to work with the parser, but instead it just looks for
common SQL tokens that indicate an identifier.
:param statement: an sqlstatement. String.
:return: tuple: new_statement, set of table vids, set of partition vids.
"""
from ambry.identity import ObjectNumber, TableNumber, NotObjectNumberError
from ambry.orm.exc import NotFoundError
try:
stmt_str = statement.to_unicode()
except AttributeError:
stmt_str = statement
parts = stmt_str.strip(';').split()
new_parts = []
tables = set()
partitions = set()
while parts:
token = parts.pop(0).strip()
if token.lower() in ('from', 'join', 'materialize', 'install'):
ident = parts.pop(0).strip(';')
new_parts.append(token)
try:
obj_number = ObjectNumber.parse(token)
if isinstance(obj_number, TableNumber):
table = library.table(ident)
tables.add(table.vid)
new_parts.append(table.vid)
else:
# Do not care about other object numbers. Assume partition.
raise NotObjectNumberError
except NotObjectNumberError:
# assume partition
try:
partition = library.partition(ident)
partitions.add(partition.vid)
new_parts.append(partition.vid)
except NotFoundError:
# Ok, maybe it is just a normal identifier...
new_parts.append(ident)
else:
new_parts.append(token)
return ' '.join(new_parts).strip(), tables, partitions | [
"def",
"substitute_vids",
"(",
"library",
",",
"statement",
")",
":",
"from",
"ambry",
".",
"identity",
"import",
"ObjectNumber",
",",
"TableNumber",
",",
"NotObjectNumberError",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"try",
":",
"... | Replace all of the references to tables and partitions with their vids.
This is a bit of a hack -- it ought to work with the parser, but instead it just looks for
common SQL tokens that indicate an identifier.
:param statement: an sqlstatement. String.
:return: tuple: new_statement, set of table vids, set of partition vids. | [
"Replace",
"all",
"of",
"the",
"references",
"to",
"tables",
"and",
"partitions",
"with",
"their",
"vids",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/asql_parser.py#L361-L413 |
CivicSpleen/ambry | ambry/bundle/asql_parser.py | find_indexable_materializable | def find_indexable_materializable(sql, library):
"""
Parse a statement, then call functions to install, materialize or create indexes for partitions
referenced in the statement.
:param sql:
:param materialize_f:
:param install_f:
:param index_f:
:return:
"""
derefed, tables, partitions = substitute_vids(library, sql)
if derefed.lower().startswith('create index') or derefed.lower().startswith('index'):
parsed = parse_index(derefed)
return FIMRecord(statement=derefed, indexes=[(parsed.source, tuple(parsed.columns))])
elif derefed.lower().startswith('materialize'):
_, vid = derefed.split()
return FIMRecord(statement=derefed, materialize=set([vid]))
elif derefed.lower().startswith('install'):
_, vid = derefed.split()
return FIMRecord(statement=derefed, install=set([vid]))
elif derefed.lower().startswith('select'):
rec = FIMRecord(statement=derefed)
parsed = parse_select(derefed)
elif derefed.lower().startswith('drop'):
return FIMRecord(statement=derefed, drop=derefed)
elif derefed.lower().startswith('create table'):
parsed = parse_view(derefed)
rec = FIMRecord(statement=derefed, drop='DROP TABLE IF EXISTS {};'.format(parsed.name), views=1)
elif derefed.lower().startswith('create view'):
parsed = parse_view(derefed)
rec = FIMRecord(statement=derefed, drop='DROP VIEW IF EXISTS {};'.format(parsed.name), views=1)
else:
return FIMRecord(statement=derefed, tables=set(tables), install=set(partitions))
def partition_aliases(parsed):
d = {}
for source in parsed.sources:
if source.alias:
d[source.alias] = source.name
for j in parsed.joins:
if j.source.alias:
d[j.source.alias] = j.source.name
return d
def indexable_columns(aliases, parsed):
indexes = []
for j in parsed.joins:
if j and j.join_cols:
for col in j.join_cols:
if '.' in col:
try:
alias, col = col.split('.')
if alias:
indexes.append((aliases[alias], (col,)))
except KeyError:
pass
return indexes
aliases = partition_aliases(parsed)
indexes = indexable_columns(aliases, parsed)
rec.joins = len(parsed.joins)
install = set(partitions)
rec.update(tables=tables, install=install, indexes=indexes)
return rec | python | def find_indexable_materializable(sql, library):
"""
Parse a statement, then call functions to install, materialize or create indexes for partitions
referenced in the statement.
:param sql:
:param materialize_f:
:param install_f:
:param index_f:
:return:
"""
derefed, tables, partitions = substitute_vids(library, sql)
if derefed.lower().startswith('create index') or derefed.lower().startswith('index'):
parsed = parse_index(derefed)
return FIMRecord(statement=derefed, indexes=[(parsed.source, tuple(parsed.columns))])
elif derefed.lower().startswith('materialize'):
_, vid = derefed.split()
return FIMRecord(statement=derefed, materialize=set([vid]))
elif derefed.lower().startswith('install'):
_, vid = derefed.split()
return FIMRecord(statement=derefed, install=set([vid]))
elif derefed.lower().startswith('select'):
rec = FIMRecord(statement=derefed)
parsed = parse_select(derefed)
elif derefed.lower().startswith('drop'):
return FIMRecord(statement=derefed, drop=derefed)
elif derefed.lower().startswith('create table'):
parsed = parse_view(derefed)
rec = FIMRecord(statement=derefed, drop='DROP TABLE IF EXISTS {};'.format(parsed.name), views=1)
elif derefed.lower().startswith('create view'):
parsed = parse_view(derefed)
rec = FIMRecord(statement=derefed, drop='DROP VIEW IF EXISTS {};'.format(parsed.name), views=1)
else:
return FIMRecord(statement=derefed, tables=set(tables), install=set(partitions))
def partition_aliases(parsed):
d = {}
for source in parsed.sources:
if source.alias:
d[source.alias] = source.name
for j in parsed.joins:
if j.source.alias:
d[j.source.alias] = j.source.name
return d
def indexable_columns(aliases, parsed):
indexes = []
for j in parsed.joins:
if j and j.join_cols:
for col in j.join_cols:
if '.' in col:
try:
alias, col = col.split('.')
if alias:
indexes.append((aliases[alias], (col,)))
except KeyError:
pass
return indexes
aliases = partition_aliases(parsed)
indexes = indexable_columns(aliases, parsed)
rec.joins = len(parsed.joins)
install = set(partitions)
rec.update(tables=tables, install=install, indexes=indexes)
return rec | [
"def",
"find_indexable_materializable",
"(",
"sql",
",",
"library",
")",
":",
"derefed",
",",
"tables",
",",
"partitions",
"=",
"substitute_vids",
"(",
"library",
",",
"sql",
")",
"if",
"derefed",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'create inde... | Parse a statement, then call functions to install, materialize or create indexes for partitions
referenced in the statement.
:param sql:
:param materialize_f:
:param install_f:
:param index_f:
:return: | [
"Parse",
"a",
"statement",
"then",
"call",
"functions",
"to",
"install",
"materialize",
"or",
"create",
"indexes",
"for",
"partitions",
"referenced",
"in",
"the",
"statement",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/asql_parser.py#L491-L574 |
CivicSpleen/ambry | ambry/bundle/asql_parser.py | FIMRecord.update | def update(self, rec=None, drop=None, tables=None, install=None, materialize=None,
indexes=None, joins=0, views=0):
""" Updates current record.
Args:
rec (FIMRecord):
"""
if not drop:
drop = []
if not tables:
tables = set()
if not install:
install = set()
if not materialize:
materialize = set()
if not indexes:
indexes = set()
if rec:
self.update(
drop=rec.drop, tables=rec.tables, install=rec.install, materialize=rec.materialize,
indexes=rec.indexes, joins=rec.joins
)
self.drop += drop
self.tables |= set(tables)
self.install |= set(install)
self.materialize |= set(materialize)
self.indexes |= set(indexes)
self.joins += joins
self.views += views
# Joins or views promote installed partitions to materialized partitions
if self.joins > 0 or self.views > 0:
self.materialize |= self.install
self.install = set() | python | def update(self, rec=None, drop=None, tables=None, install=None, materialize=None,
indexes=None, joins=0, views=0):
""" Updates current record.
Args:
rec (FIMRecord):
"""
if not drop:
drop = []
if not tables:
tables = set()
if not install:
install = set()
if not materialize:
materialize = set()
if not indexes:
indexes = set()
if rec:
self.update(
drop=rec.drop, tables=rec.tables, install=rec.install, materialize=rec.materialize,
indexes=rec.indexes, joins=rec.joins
)
self.drop += drop
self.tables |= set(tables)
self.install |= set(install)
self.materialize |= set(materialize)
self.indexes |= set(indexes)
self.joins += joins
self.views += views
# Joins or views promote installed partitions to materialized partitions
if self.joins > 0 or self.views > 0:
self.materialize |= self.install
self.install = set() | [
"def",
"update",
"(",
"self",
",",
"rec",
"=",
"None",
",",
"drop",
"=",
"None",
",",
"tables",
"=",
"None",
",",
"install",
"=",
"None",
",",
"materialize",
"=",
"None",
",",
"indexes",
"=",
"None",
",",
"joins",
"=",
"0",
",",
"views",
"=",
"0"... | Updates current record.
Args:
rec (FIMRecord): | [
"Updates",
"current",
"record",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/asql_parser.py#L448-L488 |
project-ncl/pnc-cli | pnc_cli/swagger_client/models/product_release_rest.py | ProductReleaseRest.support_level | def support_level(self, support_level):
"""
Sets the support_level of this ProductReleaseRest.
:param support_level: The support_level of this ProductReleaseRest.
:type: str
"""
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
if support_level not in allowed_values:
raise ValueError(
"Invalid value for `support_level` ({0}), must be one of {1}"
.format(support_level, allowed_values)
)
self._support_level = support_level | python | def support_level(self, support_level):
"""
Sets the support_level of this ProductReleaseRest.
:param support_level: The support_level of this ProductReleaseRest.
:type: str
"""
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
if support_level not in allowed_values:
raise ValueError(
"Invalid value for `support_level` ({0}), must be one of {1}"
.format(support_level, allowed_values)
)
self._support_level = support_level | [
"def",
"support_level",
"(",
"self",
",",
"support_level",
")",
":",
"allowed_values",
"=",
"[",
"\"UNRELEASED\"",
",",
"\"EARLYACCESS\"",
",",
"\"SUPPORTED\"",
",",
"\"EXTENDED_SUPPORT\"",
",",
"\"EOL\"",
"]",
"if",
"support_level",
"not",
"in",
"allowed_values",
... | Sets the support_level of this ProductReleaseRest.
:param support_level: The support_level of this ProductReleaseRest.
:type: str | [
"Sets",
"the",
"support_level",
"of",
"this",
"ProductReleaseRest",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/product_release_rest.py#L244-L258 |
twisted/epsilon | epsilon/hotfixes/internet_task_clock.py | callLater | def callLater(self, when, what, *a, **kw):
"""
Copied from twisted.internet.task.Clock, r20480. Fixes the bug
where the wrong DelayedCall would sometimes be returned.
"""
dc = base.DelayedCall(self.seconds() + when,
what, a, kw,
self.calls.remove,
lambda c: None,
self.seconds)
self.calls.append(dc)
self.calls.sort(lambda a, b: cmp(a.getTime(), b.getTime()))
return dc | python | def callLater(self, when, what, *a, **kw):
"""
Copied from twisted.internet.task.Clock, r20480. Fixes the bug
where the wrong DelayedCall would sometimes be returned.
"""
dc = base.DelayedCall(self.seconds() + when,
what, a, kw,
self.calls.remove,
lambda c: None,
self.seconds)
self.calls.append(dc)
self.calls.sort(lambda a, b: cmp(a.getTime(), b.getTime()))
return dc | [
"def",
"callLater",
"(",
"self",
",",
"when",
",",
"what",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"dc",
"=",
"base",
".",
"DelayedCall",
"(",
"self",
".",
"seconds",
"(",
")",
"+",
"when",
",",
"what",
",",
"a",
",",
"kw",
",",
"self",... | Copied from twisted.internet.task.Clock, r20480. Fixes the bug
where the wrong DelayedCall would sometimes be returned. | [
"Copied",
"from",
"twisted",
".",
"internet",
".",
"task",
".",
"Clock",
"r20480",
".",
"Fixes",
"the",
"bug",
"where",
"the",
"wrong",
"DelayedCall",
"would",
"sometimes",
"be",
"returned",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/internet_task_clock.py#L7-L19 |
twisted/epsilon | epsilon/hotfixes/internet_task_clock.py | clockIsBroken | def clockIsBroken():
"""
Returns whether twisted.internet.task.Clock has the bug that
returns the wrong DelayedCall or not.
"""
clock = Clock()
dc1 = clock.callLater(10, lambda: None)
dc2 = clock.callLater(1, lambda: None)
if dc1 is dc2:
return True
else:
return False | python | def clockIsBroken():
"""
Returns whether twisted.internet.task.Clock has the bug that
returns the wrong DelayedCall or not.
"""
clock = Clock()
dc1 = clock.callLater(10, lambda: None)
dc2 = clock.callLater(1, lambda: None)
if dc1 is dc2:
return True
else:
return False | [
"def",
"clockIsBroken",
"(",
")",
":",
"clock",
"=",
"Clock",
"(",
")",
"dc1",
"=",
"clock",
".",
"callLater",
"(",
"10",
",",
"lambda",
":",
"None",
")",
"dc2",
"=",
"clock",
".",
"callLater",
"(",
"1",
",",
"lambda",
":",
"None",
")",
"if",
"dc... | Returns whether twisted.internet.task.Clock has the bug that
returns the wrong DelayedCall or not. | [
"Returns",
"whether",
"twisted",
".",
"internet",
".",
"task",
".",
"Clock",
"has",
"the",
"bug",
"that",
"returns",
"the",
"wrong",
"DelayedCall",
"or",
"not",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/internet_task_clock.py#L21-L32 |
project-ncl/pnc-cli | pnc_cli/tools/scm_utils.py | get_scm_status | def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None):
"""
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module structure.
:param config: artifact config (ArtifactConfig instance)
:param read_modules: if True all modules are read, otherwise only top-level artifact
:param repo_url: the URL of the repository to use
:param mvn_repo_local: local repository path
:param additional_params: additional params to add on command-line when running maven
"""
global scm_status_cache
if config.artifact in scm_status_cache.keys():
result = scm_status_cache[config.artifact]
elif not read_modules and (("%s|False" % config.artifact) in scm_status_cache.keys()):
result = scm_status_cache["%s|False" % config.artifact]
else:
result = _get_scm_status(config, read_modules, repo_url, mvn_repo_local, additional_params)
if read_modules:
scm_status_cache[config.artifact] = result
if ("%s|False" % config.artifact) in scm_status_cache.keys():
del(scm_status_cache["%s|False" % config.artifact])
else:
scm_status_cache["%s|False" % config.artifact] = result
return result | python | def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None):
"""
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module structure.
:param config: artifact config (ArtifactConfig instance)
:param read_modules: if True all modules are read, otherwise only top-level artifact
:param repo_url: the URL of the repository to use
:param mvn_repo_local: local repository path
:param additional_params: additional params to add on command-line when running maven
"""
global scm_status_cache
if config.artifact in scm_status_cache.keys():
result = scm_status_cache[config.artifact]
elif not read_modules and (("%s|False" % config.artifact) in scm_status_cache.keys()):
result = scm_status_cache["%s|False" % config.artifact]
else:
result = _get_scm_status(config, read_modules, repo_url, mvn_repo_local, additional_params)
if read_modules:
scm_status_cache[config.artifact] = result
if ("%s|False" % config.artifact) in scm_status_cache.keys():
del(scm_status_cache["%s|False" % config.artifact])
else:
scm_status_cache["%s|False" % config.artifact] = result
return result | [
"def",
"get_scm_status",
"(",
"config",
",",
"read_modules",
"=",
"False",
",",
"repo_url",
"=",
"None",
",",
"mvn_repo_local",
"=",
"None",
",",
"additional_params",
"=",
"None",
")",
":",
"global",
"scm_status_cache",
"if",
"config",
".",
"artifact",
"in",
... | Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module structure.
:param config: artifact config (ArtifactConfig instance)
:param read_modules: if True all modules are read, otherwise only top-level artifact
:param repo_url: the URL of the repository to use
:param mvn_repo_local: local repository path
:param additional_params: additional params to add on command-line when running maven | [
"Gets",
"the",
"artifact",
"status",
"(",
"MavenArtifact",
"instance",
")",
"from",
"SCM",
"defined",
"by",
"config",
".",
"Only",
"the",
"top",
"-",
"level",
"artifact",
"is",
"read",
"by",
"default",
"although",
"it",
"can",
"be",
"requested",
"to",
"rea... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/scm_utils.py#L23-L47 |
project-ncl/pnc-cli | pnc_cli/tools/scm_utils.py | shrink_patch | def shrink_patch(patch_path, target_file):
"""
Shrinks a patch on patch_path to contain only changes for target_file.
:param patch_path: path to the shrinked patch file
:param target_file: filename of a file of which changes should be kept
:return: True if the is a section containing changes for target_file, Flase otherwise
"""
logging.debug("Shrinking patch file %s to keep only %s changes.", patch_path, target_file)
shrinked_lines = []
patch_file = None
try:
patch_file = open(patch_path)
adding = False
search_line = "diff --git a/%s b/%s" % (target_file, target_file)
for line in patch_file.read().split("\n"):
if adding and line.startswith("diff --git a/") and line != search_line:
adding = False
elif line == search_line:
adding = True
if adding:
shrinked_lines.append(line)
finally:
if patch_file:
patch_file.close()
if len(shrinked_lines):
patch_file = None
try:
patch_file = open(patch_path, "w")
content = "\n".join(shrinked_lines)
if not content.endswith("\n"):
content = content + "\n"
patch_file.write(content)
finally:
if patch_file:
patch_file.close()
return True
else:
return False | python | def shrink_patch(patch_path, target_file):
"""
Shrinks a patch on patch_path to contain only changes for target_file.
:param patch_path: path to the shrinked patch file
:param target_file: filename of a file of which changes should be kept
:return: True if the is a section containing changes for target_file, Flase otherwise
"""
logging.debug("Shrinking patch file %s to keep only %s changes.", patch_path, target_file)
shrinked_lines = []
patch_file = None
try:
patch_file = open(patch_path)
adding = False
search_line = "diff --git a/%s b/%s" % (target_file, target_file)
for line in patch_file.read().split("\n"):
if adding and line.startswith("diff --git a/") and line != search_line:
adding = False
elif line == search_line:
adding = True
if adding:
shrinked_lines.append(line)
finally:
if patch_file:
patch_file.close()
if len(shrinked_lines):
patch_file = None
try:
patch_file = open(patch_path, "w")
content = "\n".join(shrinked_lines)
if not content.endswith("\n"):
content = content + "\n"
patch_file.write(content)
finally:
if patch_file:
patch_file.close()
return True
else:
return False | [
"def",
"shrink_patch",
"(",
"patch_path",
",",
"target_file",
")",
":",
"logging",
".",
"debug",
"(",
"\"Shrinking patch file %s to keep only %s changes.\"",
",",
"patch_path",
",",
"target_file",
")",
"shrinked_lines",
"=",
"[",
"]",
"patch_file",
"=",
"None",
"try... | Shrinks a patch on patch_path to contain only changes for target_file.
:param patch_path: path to the shrinked patch file
:param target_file: filename of a file of which changes should be kept
:return: True if the is a section containing changes for target_file, Flase otherwise | [
"Shrinks",
"a",
"patch",
"on",
"patch_path",
"to",
"contain",
"only",
"changes",
"for",
"target_file",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/scm_utils.py#L274-L313 |
project-ncl/pnc-cli | pnc_cli/tools/scm_utils.py | get_scm_info | def get_scm_info(directory, branch_id=False, read_only=False, filePath=None):
"""
Reads SCM info from the given directory. It can fill real commit ID into commit_id field or branch name.
@param directory: directory name
@param branch_id: reads commit ID if False (default) or branch name if True
@param read_only: if True it replaces the actual scheme to the read-only for known hosts, e.g. git+ssh to git for
git.app.eng.bos.redhat.com, otherwise it just reads it (default)
@return: an ScmInfo instance
"""
#TODO use a commit id instead of branch if in detached state
if (directory, branch_id, read_only, filePath) in scm_info_path_cache:
return copy.copy(scm_info_path_cache[(directory, branch_id, read_only, filePath)])
if os.path.exists(os.path.join(directory, ".git")):
logging.debug("Getting git info for %s", directory)
if filePath != None:
args = ["git", "--git-dir", directory + "/.git", "log", "-z", "-n", "2", "--pretty=format:* dummy-branch %H %s%n", "--", filePath]
else:
args = ["git", "--git-dir", directory + "/.git", "branch", "-v", "--no-abbrev"]
command = Popen(args, stdout=PIPE, stderr=STDOUT)
stdout = command.communicate()[0]
if command.returncode:
raise ScmException("Reading Git branch name and commit ID from %s failed. Output: %s" % (directory, stdout))
branch_name = None
commit_id = None
for line in stdout.split("\n"):
if line.startswith("* "):
pattern = "\* +(.*) +([a-f0-9]{40}) .*"
m = re.match(pattern, line)
if m:
branch_name = m.group(1).strip()
commit_id = m.group(2).strip()
break
else:
raise ScmException("Cannot parse commit ID and branch name from result line:\n%s" % line)
logging.info ("Retrieved branch_name %s and commit_id %s", branch_name, commit_id)
args = ["git", "--git-dir", directory + "/.git", "remote", "-v"]
command = Popen(args, stdout=PIPE, stderr=STDOUT)
stdout = command.communicate()[0]
if command.returncode:
raise ScmException("Reading Git remote from %s failed. Output: %s" % (directory, stdout))
origin_url = None
for line in stdout.split("\n"):
if line.startswith("origin" + chr(9)) and line.endswith(" (fetch)"):
parts = re.split("[\s]+", line, 3)
origin_url = parts[1]
break
if branch_id:
scminfo = ScmInfo("%s#%s" % (origin_url, branch_name))
else:
scminfo = ScmInfo("%s#%s" % (origin_url, commit_id))
if read_only:
if scminfo.get_scm_url().startswith("git+ssh://git.app.eng.bos.redhat.com/srv/git/"):
scminfo.scheme = "git"
scminfo.path = scminfo.path.replace("/srv/git/", "/")
elif scminfo.get_scm_url().startswith("git+ssh://code.engineering.redhat.com/"):
scminfo.scheme = "git+https"
scminfo.path = ("%s%s" % ("/gerrit/", scminfo.path)).replace("gerrit//", "gerrit/")
scm_info_path_cache[(directory, branch_id, read_only, filePath)] = scminfo
return scminfo
elif os.path.exists(directory):
#Special case for the integration-platform-tests which test tooling
#inplace and use the file:// in the test.cfg
scminfo = ScmInfo("file://%s#%s" % (directory, "xx"))
scm_info_path_cache[(directory, branch_id, read_only, filePath)] = scminfo
return scminfo
else:
raise ScmException("Unknown SCM type while reading SCM info from %s" % directory) | python | def get_scm_info(directory, branch_id=False, read_only=False, filePath=None):
"""
Reads SCM info from the given directory. It can fill real commit ID into commit_id field or branch name.
@param directory: directory name
@param branch_id: reads commit ID if False (default) or branch name if True
@param read_only: if True it replaces the actual scheme to the read-only for known hosts, e.g. git+ssh to git for
git.app.eng.bos.redhat.com, otherwise it just reads it (default)
@return: an ScmInfo instance
"""
#TODO use a commit id instead of branch if in detached state
if (directory, branch_id, read_only, filePath) in scm_info_path_cache:
return copy.copy(scm_info_path_cache[(directory, branch_id, read_only, filePath)])
if os.path.exists(os.path.join(directory, ".git")):
logging.debug("Getting git info for %s", directory)
if filePath != None:
args = ["git", "--git-dir", directory + "/.git", "log", "-z", "-n", "2", "--pretty=format:* dummy-branch %H %s%n", "--", filePath]
else:
args = ["git", "--git-dir", directory + "/.git", "branch", "-v", "--no-abbrev"]
command = Popen(args, stdout=PIPE, stderr=STDOUT)
stdout = command.communicate()[0]
if command.returncode:
raise ScmException("Reading Git branch name and commit ID from %s failed. Output: %s" % (directory, stdout))
branch_name = None
commit_id = None
for line in stdout.split("\n"):
if line.startswith("* "):
pattern = "\* +(.*) +([a-f0-9]{40}) .*"
m = re.match(pattern, line)
if m:
branch_name = m.group(1).strip()
commit_id = m.group(2).strip()
break
else:
raise ScmException("Cannot parse commit ID and branch name from result line:\n%s" % line)
logging.info ("Retrieved branch_name %s and commit_id %s", branch_name, commit_id)
args = ["git", "--git-dir", directory + "/.git", "remote", "-v"]
command = Popen(args, stdout=PIPE, stderr=STDOUT)
stdout = command.communicate()[0]
if command.returncode:
raise ScmException("Reading Git remote from %s failed. Output: %s" % (directory, stdout))
origin_url = None
for line in stdout.split("\n"):
if line.startswith("origin" + chr(9)) and line.endswith(" (fetch)"):
parts = re.split("[\s]+", line, 3)
origin_url = parts[1]
break
if branch_id:
scminfo = ScmInfo("%s#%s" % (origin_url, branch_name))
else:
scminfo = ScmInfo("%s#%s" % (origin_url, commit_id))
if read_only:
if scminfo.get_scm_url().startswith("git+ssh://git.app.eng.bos.redhat.com/srv/git/"):
scminfo.scheme = "git"
scminfo.path = scminfo.path.replace("/srv/git/", "/")
elif scminfo.get_scm_url().startswith("git+ssh://code.engineering.redhat.com/"):
scminfo.scheme = "git+https"
scminfo.path = ("%s%s" % ("/gerrit/", scminfo.path)).replace("gerrit//", "gerrit/")
scm_info_path_cache[(directory, branch_id, read_only, filePath)] = scminfo
return scminfo
elif os.path.exists(directory):
#Special case for the integration-platform-tests which test tooling
#inplace and use the file:// in the test.cfg
scminfo = ScmInfo("file://%s#%s" % (directory, "xx"))
scm_info_path_cache[(directory, branch_id, read_only, filePath)] = scminfo
return scminfo
else:
raise ScmException("Unknown SCM type while reading SCM info from %s" % directory) | [
"def",
"get_scm_info",
"(",
"directory",
",",
"branch_id",
"=",
"False",
",",
"read_only",
"=",
"False",
",",
"filePath",
"=",
"None",
")",
":",
"#TODO use a commit id instead of branch if in detached state",
"if",
"(",
"directory",
",",
"branch_id",
",",
"read_only... | Reads SCM info from the given directory. It can fill real commit ID into commit_id field or branch name.
@param directory: directory name
@param branch_id: reads commit ID if False (default) or branch name if True
@param read_only: if True it replaces the actual scheme to the read-only for known hosts, e.g. git+ssh to git for
git.app.eng.bos.redhat.com, otherwise it just reads it (default)
@return: an ScmInfo instance | [
"Reads",
"SCM",
"info",
"from",
"the",
"given",
"directory",
".",
"It",
"can",
"fill",
"real",
"commit",
"ID",
"into",
"commit_id",
"field",
"or",
"branch",
"name",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/scm_utils.py#L321-L399 |
project-ncl/pnc-cli | pnc_cli/swagger_client/models/build_set_status_changed_event.py | BuildSetStatusChangedEvent.new_status | def new_status(self, new_status):
"""
Sets the new_status of this BuildSetStatusChangedEvent.
:param new_status: The new_status of this BuildSetStatusChangedEvent.
:type: str
"""
allowed_values = ["NEW", "DONE", "REJECTED"]
if new_status not in allowed_values:
raise ValueError(
"Invalid value for `new_status` ({0}), must be one of {1}"
.format(new_status, allowed_values)
)
self._new_status = new_status | python | def new_status(self, new_status):
"""
Sets the new_status of this BuildSetStatusChangedEvent.
:param new_status: The new_status of this BuildSetStatusChangedEvent.
:type: str
"""
allowed_values = ["NEW", "DONE", "REJECTED"]
if new_status not in allowed_values:
raise ValueError(
"Invalid value for `new_status` ({0}), must be one of {1}"
.format(new_status, allowed_values)
)
self._new_status = new_status | [
"def",
"new_status",
"(",
"self",
",",
"new_status",
")",
":",
"allowed_values",
"=",
"[",
"\"NEW\"",
",",
"\"DONE\"",
",",
"\"REJECTED\"",
"]",
"if",
"new_status",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `new_status` (... | Sets the new_status of this BuildSetStatusChangedEvent.
:param new_status: The new_status of this BuildSetStatusChangedEvent.
:type: str | [
"Sets",
"the",
"new_status",
"of",
"this",
"BuildSetStatusChangedEvent",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/build_set_status_changed_event.py#L139-L153 |
project-ncl/pnc-cli | pnc_cli/swagger_client/models/build_set_status_changed_event.py | BuildSetStatusChangedEvent.old_status | def old_status(self, old_status):
"""
Sets the old_status of this BuildSetStatusChangedEvent.
:param old_status: The old_status of this BuildSetStatusChangedEvent.
:type: str
"""
allowed_values = ["NEW", "DONE", "REJECTED"]
if old_status not in allowed_values:
raise ValueError(
"Invalid value for `old_status` ({0}), must be one of {1}"
.format(old_status, allowed_values)
)
self._old_status = old_status | python | def old_status(self, old_status):
"""
Sets the old_status of this BuildSetStatusChangedEvent.
:param old_status: The old_status of this BuildSetStatusChangedEvent.
:type: str
"""
allowed_values = ["NEW", "DONE", "REJECTED"]
if old_status not in allowed_values:
raise ValueError(
"Invalid value for `old_status` ({0}), must be one of {1}"
.format(old_status, allowed_values)
)
self._old_status = old_status | [
"def",
"old_status",
"(",
"self",
",",
"old_status",
")",
":",
"allowed_values",
"=",
"[",
"\"NEW\"",
",",
"\"DONE\"",
",",
"\"REJECTED\"",
"]",
"if",
"old_status",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `old_status` (... | Sets the old_status of this BuildSetStatusChangedEvent.
:param old_status: The old_status of this BuildSetStatusChangedEvent.
:type: str | [
"Sets",
"the",
"old_status",
"of",
"this",
"BuildSetStatusChangedEvent",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/build_set_status_changed_event.py#L250-L264 |
SmartTeleMax/iktomi | iktomi/cli/app.py | App.command_serve | def command_serve(self, host='', port='8000', level='debug'):
'''
Run development server with automated reload on code change::
./manage.py app:serve [host] [port] [level]
'''
logging.basicConfig(level=getattr(logging, level.upper()), format=self.format)
if self.bootstrap:
logger.info('Bootstraping...')
self.bootstrap()
try:
server_thread = DevServerThread(host, port, self.app)
server_thread.start()
wait_for_code_change(extra_files=self.extra_files)
server_thread.running = False
server_thread.join()
logger.info('Reloading...')
flush_fds()
pid = os.fork()
# We need to fork before `execvp` to perform code reload
# correctly, because we need to complete python destructors and
# `atexit`.
# This will save us from problems of incorrect exit, such as:
# - unsaved data in data storage, which does not write data
# on hard drive immediatly
# - code, that can't be measured with coverage tool, because it uses
# `atexit` handler to save coverage data
# NOTE: we using untipical fork-exec scheme with replacing
# the parent process(not the child) to preserve PID of proccess
# we use `pragma: no cover` here, because parent process cannot be
# measured with coverage since it is ends with `execvp`
if pid: # pragma: no cover
os.closerange(3, MAXFD)
os.waitpid(pid, 0)
# reloading the code in parent process
os.execvp(sys.executable, [sys.executable] + sys.argv)
else:
# we closing our recources, including file descriptors
# and performing `atexit`.
sys.exit()
except KeyboardInterrupt:
logger.info('Stoping dev-server...')
server_thread.running = False
server_thread.join()
sys.exit() | python | def command_serve(self, host='', port='8000', level='debug'):
'''
Run development server with automated reload on code change::
./manage.py app:serve [host] [port] [level]
'''
logging.basicConfig(level=getattr(logging, level.upper()), format=self.format)
if self.bootstrap:
logger.info('Bootstraping...')
self.bootstrap()
try:
server_thread = DevServerThread(host, port, self.app)
server_thread.start()
wait_for_code_change(extra_files=self.extra_files)
server_thread.running = False
server_thread.join()
logger.info('Reloading...')
flush_fds()
pid = os.fork()
# We need to fork before `execvp` to perform code reload
# correctly, because we need to complete python destructors and
# `atexit`.
# This will save us from problems of incorrect exit, such as:
# - unsaved data in data storage, which does not write data
# on hard drive immediatly
# - code, that can't be measured with coverage tool, because it uses
# `atexit` handler to save coverage data
# NOTE: we using untipical fork-exec scheme with replacing
# the parent process(not the child) to preserve PID of proccess
# we use `pragma: no cover` here, because parent process cannot be
# measured with coverage since it is ends with `execvp`
if pid: # pragma: no cover
os.closerange(3, MAXFD)
os.waitpid(pid, 0)
# reloading the code in parent process
os.execvp(sys.executable, [sys.executable] + sys.argv)
else:
# we closing our recources, including file descriptors
# and performing `atexit`.
sys.exit()
except KeyboardInterrupt:
logger.info('Stoping dev-server...')
server_thread.running = False
server_thread.join()
sys.exit() | [
"def",
"command_serve",
"(",
"self",
",",
"host",
"=",
"''",
",",
"port",
"=",
"'8000'",
",",
"level",
"=",
"'debug'",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"level",
".",
"upper",
"(",
")",
")",
... | Run development server with automated reload on code change::
./manage.py app:serve [host] [port] [level] | [
"Run",
"development",
"server",
"with",
"automated",
"reload",
"on",
"code",
"change",
"::"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/app.py#L49-L94 |
SmartTeleMax/iktomi | iktomi/cli/app.py | App.command_shell | def command_shell(self):
'''
Shell command::
./manage.py app:shell
Executed with `self.shell_namespace` as local variables namespace.
'''
from code import interact
interact('Namespace {!r}'.format(self.shell_namespace),
local=self.shell_namespace) | python | def command_shell(self):
'''
Shell command::
./manage.py app:shell
Executed with `self.shell_namespace` as local variables namespace.
'''
from code import interact
interact('Namespace {!r}'.format(self.shell_namespace),
local=self.shell_namespace) | [
"def",
"command_shell",
"(",
"self",
")",
":",
"from",
"code",
"import",
"interact",
"interact",
"(",
"'Namespace {!r}'",
".",
"format",
"(",
"self",
".",
"shell_namespace",
")",
",",
"local",
"=",
"self",
".",
"shell_namespace",
")"
] | Shell command::
./manage.py app:shell
Executed with `self.shell_namespace` as local variables namespace. | [
"Shell",
"command",
"::"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/app.py#L96-L106 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/mixin.py | declared_mixin | def declared_mixin(*bases):
'''Create mix-in class with all assignments turned into methods decorated
with declared_attr. Usage:
@declared_mixin
def FactoryFunction():
or with base mix-in class[es]:
@declared_mixin(BaseMixIn1, BaseMixIn2)
def FactoryFunction():
For example:
@declared_mixin
def WithParent():
parent_id = Column(ForeignKey(Parent.id))
parent = relationship(Parent)
is equivalent to
class WithParent(object):
@declared_attr
def parent_id(cls):
return Column(ForeignKey(Parent.id))
@declared_attr
def parent(cls):
return relationship(Parent)
'''
def wrapper(func):
attrs = weakref.WeakKeyDictionary()
def create_descriptor(name):
def get_attr(cls):
if cls not in attrs:
# Call func only once per class
attrs[cls] = return_locals(func)()
return attrs[cls][name]
get_attr.__name__ = name
return declared_attr(get_attr)
dict_ = {name: create_descriptor(name)
for name in six.get_function_code(func).co_varnames}
dict_['__doc__'] = func.__doc__
return type(func.__name__, bases, dict_)
if len(bases)==1 and not isinstance(bases[0], type):
# Short form (without bases) is used
func = bases[0]
bases = ()
return wrapper(func)
else:
return wrapper | python | def declared_mixin(*bases):
'''Create mix-in class with all assignments turned into methods decorated
with declared_attr. Usage:
@declared_mixin
def FactoryFunction():
or with base mix-in class[es]:
@declared_mixin(BaseMixIn1, BaseMixIn2)
def FactoryFunction():
For example:
@declared_mixin
def WithParent():
parent_id = Column(ForeignKey(Parent.id))
parent = relationship(Parent)
is equivalent to
class WithParent(object):
@declared_attr
def parent_id(cls):
return Column(ForeignKey(Parent.id))
@declared_attr
def parent(cls):
return relationship(Parent)
'''
def wrapper(func):
attrs = weakref.WeakKeyDictionary()
def create_descriptor(name):
def get_attr(cls):
if cls not in attrs:
# Call func only once per class
attrs[cls] = return_locals(func)()
return attrs[cls][name]
get_attr.__name__ = name
return declared_attr(get_attr)
dict_ = {name: create_descriptor(name)
for name in six.get_function_code(func).co_varnames}
dict_['__doc__'] = func.__doc__
return type(func.__name__, bases, dict_)
if len(bases)==1 and not isinstance(bases[0], type):
# Short form (without bases) is used
func = bases[0]
bases = ()
return wrapper(func)
else:
return wrapper | [
"def",
"declared_mixin",
"(",
"*",
"bases",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"attrs",
"=",
"weakref",
".",
"WeakKeyDictionary",
"(",
")",
"def",
"create_descriptor",
"(",
"name",
")",
":",
"def",
"get_attr",
"(",
"cls",
")",
":",
"if"... | Create mix-in class with all assignments turned into methods decorated
with declared_attr. Usage:
@declared_mixin
def FactoryFunction():
or with base mix-in class[es]:
@declared_mixin(BaseMixIn1, BaseMixIn2)
def FactoryFunction():
For example:
@declared_mixin
def WithParent():
parent_id = Column(ForeignKey(Parent.id))
parent = relationship(Parent)
is equivalent to
class WithParent(object):
@declared_attr
def parent_id(cls):
return Column(ForeignKey(Parent.id))
@declared_attr
def parent(cls):
return relationship(Parent) | [
"Create",
"mix",
"-",
"in",
"class",
"with",
"all",
"assignments",
"turned",
"into",
"methods",
"decorated",
"with",
"declared_attr",
".",
"Usage",
":"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/mixin.py#L7-L58 |
cosven/feeluown-core | fuocore/utils.py | elfhash | def elfhash(s):
"""
:param string: bytes
>>> import base64
>>> s = base64.b64encode(b'hello world')
>>> elfhash(s)
224648685
"""
hash = 0
x = 0
for c in s:
hash = (hash << 4) + c
x = hash & 0xF0000000
if x:
hash ^= (x >> 24)
hash &= ~x
return (hash & 0x7FFFFFFF) | python | def elfhash(s):
"""
:param string: bytes
>>> import base64
>>> s = base64.b64encode(b'hello world')
>>> elfhash(s)
224648685
"""
hash = 0
x = 0
for c in s:
hash = (hash << 4) + c
x = hash & 0xF0000000
if x:
hash ^= (x >> 24)
hash &= ~x
return (hash & 0x7FFFFFFF) | [
"def",
"elfhash",
"(",
"s",
")",
":",
"hash",
"=",
"0",
"x",
"=",
"0",
"for",
"c",
"in",
"s",
":",
"hash",
"=",
"(",
"hash",
"<<",
"4",
")",
"+",
"c",
"x",
"=",
"hash",
"&",
"0xF0000000",
"if",
"x",
":",
"hash",
"^=",
"(",
"x",
">>",
"24"... | :param string: bytes
>>> import base64
>>> s = base64.b64encode(b'hello world')
>>> elfhash(s)
224648685 | [
":",
"param",
"string",
":",
"bytes"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/utils.py#L23-L40 |
cosven/feeluown-core | fuocore/utils.py | find_previous | def find_previous(element, l):
"""
find previous element in a sorted list
>>> find_previous(0, [0])
0
>>> find_previous(2, [1, 1, 3])
1
>>> find_previous(0, [1, 2])
>>> find_previous(1.5, [1, 2])
1
>>> find_previous(3, [1, 2])
2
"""
length = len(l)
for index, current in enumerate(l):
# current is the last element
if length - 1 == index:
return current
# current is the first element
if index == 0:
if element < current:
return None
if current <= element < l[index+1]:
return current | python | def find_previous(element, l):
"""
find previous element in a sorted list
>>> find_previous(0, [0])
0
>>> find_previous(2, [1, 1, 3])
1
>>> find_previous(0, [1, 2])
>>> find_previous(1.5, [1, 2])
1
>>> find_previous(3, [1, 2])
2
"""
length = len(l)
for index, current in enumerate(l):
# current is the last element
if length - 1 == index:
return current
# current is the first element
if index == 0:
if element < current:
return None
if current <= element < l[index+1]:
return current | [
"def",
"find_previous",
"(",
"element",
",",
"l",
")",
":",
"length",
"=",
"len",
"(",
"l",
")",
"for",
"index",
",",
"current",
"in",
"enumerate",
"(",
"l",
")",
":",
"# current is the last element",
"if",
"length",
"-",
"1",
"==",
"index",
":",
"retu... | find previous element in a sorted list
>>> find_previous(0, [0])
0
>>> find_previous(2, [1, 1, 3])
1
>>> find_previous(0, [1, 2])
>>> find_previous(1.5, [1, 2])
1
>>> find_previous(3, [1, 2])
2 | [
"find",
"previous",
"element",
"in",
"a",
"sorted",
"list"
] | train | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/utils.py#L43-L69 |
CivicSpleen/ambry | ambry/orm/remote.py | patch_match_hostname | def patch_match_hostname():
"""Fixes https://github.com/boto/boto/issues/2836"""
_old_match_hostname = ssl.match_hostname
def _new_match_hostname(cert, hostname):
if hostname.endswith('.s3.amazonaws.com'):
pos = hostname.find('.s3.amazonaws.com')
hostname = hostname[:pos].replace('.', '') + hostname[pos:]
return _old_match_hostname(cert, hostname)
ssl.match_hostname = _new_match_hostname | python | def patch_match_hostname():
"""Fixes https://github.com/boto/boto/issues/2836"""
_old_match_hostname = ssl.match_hostname
def _new_match_hostname(cert, hostname):
if hostname.endswith('.s3.amazonaws.com'):
pos = hostname.find('.s3.amazonaws.com')
hostname = hostname[:pos].replace('.', '') + hostname[pos:]
return _old_match_hostname(cert, hostname)
ssl.match_hostname = _new_match_hostname | [
"def",
"patch_match_hostname",
"(",
")",
":",
"_old_match_hostname",
"=",
"ssl",
".",
"match_hostname",
"def",
"_new_match_hostname",
"(",
"cert",
",",
"hostname",
")",
":",
"if",
"hostname",
".",
"endswith",
"(",
"'.s3.amazonaws.com'",
")",
":",
"pos",
"=",
"... | Fixes https://github.com/boto/boto/issues/2836 | [
"Fixes",
"https",
":",
"//",
"github",
".",
"com",
"/",
"boto",
"/",
"boto",
"/",
"issues",
"/",
"2836"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L41-L53 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.dict | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
from collections import OrderedDict
d = OrderedDict(
[(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in ('data',)])
if 'list' in self.data:
d['bundle_count'] = len(self.data['list'])
else:
d['bundle_count'] = None
if self.data:
for k, v in self.data.items():
d[k] = v
return d | python | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
from collections import OrderedDict
d = OrderedDict(
[(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in ('data',)])
if 'list' in self.data:
d['bundle_count'] = len(self.data['list'])
else:
d['bundle_count'] = None
if self.data:
for k, v in self.data.items():
d[k] = v
return d | [
"def",
"dict",
"(",
"self",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"d",
"=",
"OrderedDict",
"(",
"[",
"(",
"p",
".",
"key",
",",
"getattr",
"(",
"self",
",",
"p",
".",
"key",
")",
")",
"for",
"p",
"in",
"self",
".",
"__mapper__",... | A dict that holds key/values for all of the properties in the
object.
:return: | [
"A",
"dict",
"that",
"holds",
"key",
"/",
"values",
"for",
"all",
"of",
"the",
"properties",
"in",
"the",
"object",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L115-L136 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.update | def update(self):
"""Cache the list into the data section of the record"""
from ambry.orm.exc import NotFoundError
from requests.exceptions import ConnectionError, HTTPError
from boto.exception import S3ResponseError
d = {}
try:
for k, v in self.list(full=True):
if not v:
continue
d[v['vid']] = {
'vid': v['vid'],
'vname': v.get('vname'),
'id': v.get('id'),
'name': v.get('name')
}
self.data['list'] = d
except (NotFoundError, ConnectionError, S3ResponseError, HTTPError) as e:
raise RemoteAccessError("Failed to update {}: {}".format(self.short_name, e)) | python | def update(self):
"""Cache the list into the data section of the record"""
from ambry.orm.exc import NotFoundError
from requests.exceptions import ConnectionError, HTTPError
from boto.exception import S3ResponseError
d = {}
try:
for k, v in self.list(full=True):
if not v:
continue
d[v['vid']] = {
'vid': v['vid'],
'vname': v.get('vname'),
'id': v.get('id'),
'name': v.get('name')
}
self.data['list'] = d
except (NotFoundError, ConnectionError, S3ResponseError, HTTPError) as e:
raise RemoteAccessError("Failed to update {}: {}".format(self.short_name, e)) | [
"def",
"update",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"from",
"requests",
".",
"exceptions",
"import",
"ConnectionError",
",",
"HTTPError",
"from",
"boto",
".",
"exception",
"import",
"S3ResponseError",
"d"... | Cache the list into the data section of the record | [
"Cache",
"the",
"list",
"into",
"the",
"data",
"section",
"of",
"the",
"record"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L177-L200 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.list | def list(self, full=False):
"""List all of the bundles in the remote"""
if self.is_api:
return self._list_api(full=full)
else:
return self._list_fs(full=full) | python | def list(self, full=False):
"""List all of the bundles in the remote"""
if self.is_api:
return self._list_api(full=full)
else:
return self._list_fs(full=full) | [
"def",
"list",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_api",
":",
"return",
"self",
".",
"_list_api",
"(",
"full",
"=",
"full",
")",
"else",
":",
"return",
"self",
".",
"_list_fs",
"(",
"full",
"=",
"full",
")"
] | List all of the bundles in the remote | [
"List",
"all",
"of",
"the",
"bundles",
"in",
"the",
"remote"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L202-L208 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote._update_fs_list | def _update_fs_list(self):
"""Cache the full list for http access. This creates a meta file that can be read all at once,
rather than requiring a list operation like S3 access does"""
from json import dumps
full_list = [ e[1] for e in self._list_fs(full=True) ]
remote = self._fs_remote(self.url)
remote.setcontents(os.path.join('_meta', 'list.json'), dumps(full_list, indent = 4)) | python | def _update_fs_list(self):
"""Cache the full list for http access. This creates a meta file that can be read all at once,
rather than requiring a list operation like S3 access does"""
from json import dumps
full_list = [ e[1] for e in self._list_fs(full=True) ]
remote = self._fs_remote(self.url)
remote.setcontents(os.path.join('_meta', 'list.json'), dumps(full_list, indent = 4)) | [
"def",
"_update_fs_list",
"(",
"self",
")",
":",
"from",
"json",
"import",
"dumps",
"full_list",
"=",
"[",
"e",
"[",
"1",
"]",
"for",
"e",
"in",
"self",
".",
"_list_fs",
"(",
"full",
"=",
"True",
")",
"]",
"remote",
"=",
"self",
".",
"_fs_remote",
... | Cache the full list for http access. This creates a meta file that can be read all at once,
rather than requiring a list operation like S3 access does | [
"Cache",
"the",
"full",
"list",
"for",
"http",
"access",
".",
"This",
"creates",
"a",
"meta",
"file",
"that",
"can",
"be",
"read",
"all",
"at",
"once",
"rather",
"than",
"requiring",
"a",
"list",
"operation",
"like",
"S3",
"access",
"does"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L253-L262 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.checkin | def checkin(self, package, no_partitions=False, force=False, cb=None):
"""
Check in a bundle package to the remote.
:param package: A Database, referencing a sqlite database holding the bundle
:param cb: a two argument progress callback: cb(message, num_records)
:return:
"""
from ambry.orm.exc import NotFoundError
if not os.path.exists(package.path):
raise NotFoundError("Package path does not exist: '{}' ".format(package.path))
if self.is_api:
return self._checkin_api(package, no_partitions=no_partitions, force=force, cb=cb)
else:
return self._checkin_fs(package, no_partitions=no_partitions, force=force, cb=cb) | python | def checkin(self, package, no_partitions=False, force=False, cb=None):
"""
Check in a bundle package to the remote.
:param package: A Database, referencing a sqlite database holding the bundle
:param cb: a two argument progress callback: cb(message, num_records)
:return:
"""
from ambry.orm.exc import NotFoundError
if not os.path.exists(package.path):
raise NotFoundError("Package path does not exist: '{}' ".format(package.path))
if self.is_api:
return self._checkin_api(package, no_partitions=no_partitions, force=force, cb=cb)
else:
return self._checkin_fs(package, no_partitions=no_partitions, force=force, cb=cb) | [
"def",
"checkin",
"(",
"self",
",",
"package",
",",
"no_partitions",
"=",
"False",
",",
"force",
"=",
"False",
",",
"cb",
"=",
"None",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"if",
"not",
"os",
".",
"path",
".",
... | Check in a bundle package to the remote.
:param package: A Database, referencing a sqlite database holding the bundle
:param cb: a two argument progress callback: cb(message, num_records)
:return: | [
"Check",
"in",
"a",
"bundle",
"package",
"to",
"the",
"remote",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L307-L323 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote._put_metadata | def _put_metadata(self, fs_remote, ds):
"""Store metadata on a pyfs remote"""
from six import text_type
from fs.errors import ResourceNotFoundError
identity = ds.identity
d = identity.dict
d['summary'] = ds.config.metadata.about.summary
d['title'] = ds.config.metadata.about.title
meta_stack = self._meta_infos(ds)
def do_metadata():
for path, ident in meta_stack:
fs_remote.setcontents(path, ident)
try:
# Assume the directories already exist
do_metadata()
except ResourceNotFoundError:
# Nope, make them and try again.
parts = ['vid', 'id', 'vname', 'name']
for p in parts:
dirname = os.path.join('_meta', p)
fs_remote.makedir(dirname, allow_recreate=True, recursive=True)
do_metadata() | python | def _put_metadata(self, fs_remote, ds):
"""Store metadata on a pyfs remote"""
from six import text_type
from fs.errors import ResourceNotFoundError
identity = ds.identity
d = identity.dict
d['summary'] = ds.config.metadata.about.summary
d['title'] = ds.config.metadata.about.title
meta_stack = self._meta_infos(ds)
def do_metadata():
for path, ident in meta_stack:
fs_remote.setcontents(path, ident)
try:
# Assume the directories already exist
do_metadata()
except ResourceNotFoundError:
# Nope, make them and try again.
parts = ['vid', 'id', 'vname', 'name']
for p in parts:
dirname = os.path.join('_meta', p)
fs_remote.makedir(dirname, allow_recreate=True, recursive=True)
do_metadata() | [
"def",
"_put_metadata",
"(",
"self",
",",
"fs_remote",
",",
"ds",
")",
":",
"from",
"six",
"import",
"text_type",
"from",
"fs",
".",
"errors",
"import",
"ResourceNotFoundError",
"identity",
"=",
"ds",
".",
"identity",
"d",
"=",
"identity",
".",
"dict",
"d"... | Store metadata on a pyfs remote | [
"Store",
"metadata",
"on",
"a",
"pyfs",
"remote"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L398-L428 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.checkout | def checkout(self, ref, cb=None):
"""Checkout a bundle from the remote. Returns a file-like object"""
if self.is_api:
return self._checkout_api(ref, cb=cb)
else:
return self._checkout_fs(ref, cb=cb) | python | def checkout(self, ref, cb=None):
"""Checkout a bundle from the remote. Returns a file-like object"""
if self.is_api:
return self._checkout_api(ref, cb=cb)
else:
return self._checkout_fs(ref, cb=cb) | [
"def",
"checkout",
"(",
"self",
",",
"ref",
",",
"cb",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_api",
":",
"return",
"self",
".",
"_checkout_api",
"(",
"ref",
",",
"cb",
"=",
"cb",
")",
"else",
":",
"return",
"self",
".",
"_checkout_fs",
"(",
... | Checkout a bundle from the remote. Returns a file-like object | [
"Checkout",
"a",
"bundle",
"from",
"the",
"remote",
".",
"Returns",
"a",
"file",
"-",
"like",
"object"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L463-L468 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.remove | def remove(self, ref, cb=None):
"""Check in a bundle to the remote"""
if self.is_api:
return self._remove_api(ref, cb)
else:
return self._remove_fs(ref, cb) | python | def remove(self, ref, cb=None):
"""Check in a bundle to the remote"""
if self.is_api:
return self._remove_api(ref, cb)
else:
return self._remove_fs(ref, cb) | [
"def",
"remove",
"(",
"self",
",",
"ref",
",",
"cb",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_api",
":",
"return",
"self",
".",
"_remove_api",
"(",
"ref",
",",
"cb",
")",
"else",
":",
"return",
"self",
".",
"_remove_fs",
"(",
"ref",
",",
"cb... | Check in a bundle to the remote | [
"Check",
"in",
"a",
"bundle",
"to",
"the",
"remote"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L484-L490 |
CivicSpleen/ambry | ambry/orm/remote.py | Remote.s3 | def s3(self, url, account_acessor=None, access=None, secret=None):
"""Setup an S3 pyfs, with account credentials, fixing an ssl matching problem"""
from ambry.util.ambrys3 import AmbryS3FS
from ambry.util import parse_url_to_dict
import ssl
pd = parse_url_to_dict(url)
if account_acessor:
account = account_acessor(pd['hostname'])
assert account['account_id'] == pd['hostname']
aws_access_key = account['access_key'],
aws_secret_key = account['secret']
else:
aws_access_key = access
aws_secret_key = secret
assert access, url
assert secret, url
s3 = AmbryS3FS(
bucket=pd['netloc'],
prefix=pd['path'].strip('/')+'/',
aws_access_key=aws_access_key,
aws_secret_key=aws_secret_key,
)
return s3 | python | def s3(self, url, account_acessor=None, access=None, secret=None):
"""Setup an S3 pyfs, with account credentials, fixing an ssl matching problem"""
from ambry.util.ambrys3 import AmbryS3FS
from ambry.util import parse_url_to_dict
import ssl
pd = parse_url_to_dict(url)
if account_acessor:
account = account_acessor(pd['hostname'])
assert account['account_id'] == pd['hostname']
aws_access_key = account['access_key'],
aws_secret_key = account['secret']
else:
aws_access_key = access
aws_secret_key = secret
assert access, url
assert secret, url
s3 = AmbryS3FS(
bucket=pd['netloc'],
prefix=pd['path'].strip('/')+'/',
aws_access_key=aws_access_key,
aws_secret_key=aws_secret_key,
)
return s3 | [
"def",
"s3",
"(",
"self",
",",
"url",
",",
"account_acessor",
"=",
"None",
",",
"access",
"=",
"None",
",",
"secret",
"=",
"None",
")",
":",
"from",
"ambry",
".",
"util",
".",
"ambrys3",
"import",
"AmbryS3FS",
"from",
"ambry",
".",
"util",
"import",
... | Setup an S3 pyfs, with account credentials, fixing an ssl matching problem | [
"Setup",
"an",
"S3",
"pyfs",
"with",
"account",
"credentials",
"fixing",
"an",
"ssl",
"matching",
"problem"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/remote.py#L555-L584 |
edoburu/django-any-urlfield | any_urlfield/templatetags/any_urlfield_tags.py | withdict | def withdict(parser, token):
"""
Take a complete context dict as extra layer.
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("{% withdict %} expects one argument")
nodelist = parser.parse(('endwithdict',))
parser.delete_first_token()
return WithDictNode(
nodelist=nodelist,
context_expr=parser.compile_filter(bits[1])
) | python | def withdict(parser, token):
"""
Take a complete context dict as extra layer.
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("{% withdict %} expects one argument")
nodelist = parser.parse(('endwithdict',))
parser.delete_first_token()
return WithDictNode(
nodelist=nodelist,
context_expr=parser.compile_filter(bits[1])
) | [
"def",
"withdict",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"{% withdict %} expects one argument\"",
")",
"nodelist",
"... | Take a complete context dict as extra layer. | [
"Take",
"a",
"complete",
"context",
"dict",
"as",
"extra",
"layer",
"."
] | train | https://github.com/edoburu/django-any-urlfield/blob/8d7d36c8a1fc251930f6dbdcc8b5b5151d20e3ab/any_urlfield/templatetags/any_urlfield_tags.py#L31-L45 |
edoburu/django-any-urlfield | any_urlfield/templatetags/any_urlfield_tags.py | WithDictNode.render | def render(self, context):
"""
Render the tag, with extra context layer.
"""
extra_context = self.context_expr.resolve(context)
if not isinstance(extra_context, dict):
raise TemplateSyntaxError("{% withdict %} expects the argument to be a dictionary.")
with context.push(**extra_context):
return self.nodelist.render(context) | python | def render(self, context):
"""
Render the tag, with extra context layer.
"""
extra_context = self.context_expr.resolve(context)
if not isinstance(extra_context, dict):
raise TemplateSyntaxError("{% withdict %} expects the argument to be a dictionary.")
with context.push(**extra_context):
return self.nodelist.render(context) | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"extra_context",
"=",
"self",
".",
"context_expr",
".",
"resolve",
"(",
"context",
")",
"if",
"not",
"isinstance",
"(",
"extra_context",
",",
"dict",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"... | Render the tag, with extra context layer. | [
"Render",
"the",
"tag",
"with",
"extra",
"context",
"layer",
"."
] | train | https://github.com/edoburu/django-any-urlfield/blob/8d7d36c8a1fc251930f6dbdcc8b5b5151d20e3ab/any_urlfield/templatetags/any_urlfield_tags.py#L18-L27 |
SmartTeleMax/iktomi | iktomi/db/sqla/files.py | filesessionmaker | def filesessionmaker(sessionmaker, file_manager, file_managers=None):
u'''Wrapper of session maker adding link to a FileManager instance
to session.::
file_manager = FileManager(cfg.TRANSIENT_ROOT,
cfg.PERSISTENT_ROOT)
filesessionmaker(sessionmaker(...), file_manager)
'''
registry = WeakKeyDictionary()
if file_managers:
for k, v in six.iteritems(file_managers):
if isinstance(k, FileAttribute):
raise NotImplementedError()
registry[k] = v
def find_file_manager(self, target):
if isinstance(target, FileAttribute):
assert hasattr(target, 'class_')
target = target.class_
else:
if not inspect.isclass(target):
target = type(target)
assert hasattr(target, 'metadata')
assert class_mapper(target) is not None
if target in registry:
return registry[target]
if target.metadata in registry:
return registry[target.metadata]
return file_manager
def session_maker(*args, **kwargs):
session = sessionmaker(*args, **kwargs)
# XXX in case we want to use session manager somehow bound
# to request environment. For example, to generate user-specific
# URLs.
#session.file_manager = \
# kwargs.get('file_manager', file_manager)
session.file_manager = file_manager
session.find_file_manager = six.create_bound_method(
find_file_manager,
session)
return session
return session_maker | python | def filesessionmaker(sessionmaker, file_manager, file_managers=None):
u'''Wrapper of session maker adding link to a FileManager instance
to session.::
file_manager = FileManager(cfg.TRANSIENT_ROOT,
cfg.PERSISTENT_ROOT)
filesessionmaker(sessionmaker(...), file_manager)
'''
registry = WeakKeyDictionary()
if file_managers:
for k, v in six.iteritems(file_managers):
if isinstance(k, FileAttribute):
raise NotImplementedError()
registry[k] = v
def find_file_manager(self, target):
if isinstance(target, FileAttribute):
assert hasattr(target, 'class_')
target = target.class_
else:
if not inspect.isclass(target):
target = type(target)
assert hasattr(target, 'metadata')
assert class_mapper(target) is not None
if target in registry:
return registry[target]
if target.metadata in registry:
return registry[target.metadata]
return file_manager
def session_maker(*args, **kwargs):
session = sessionmaker(*args, **kwargs)
# XXX in case we want to use session manager somehow bound
# to request environment. For example, to generate user-specific
# URLs.
#session.file_manager = \
# kwargs.get('file_manager', file_manager)
session.file_manager = file_manager
session.find_file_manager = six.create_bound_method(
find_file_manager,
session)
return session
return session_maker | [
"def",
"filesessionmaker",
"(",
"sessionmaker",
",",
"file_manager",
",",
"file_managers",
"=",
"None",
")",
":",
"registry",
"=",
"WeakKeyDictionary",
"(",
")",
"if",
"file_managers",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"file_mana... | u'''Wrapper of session maker adding link to a FileManager instance
to session.::
file_manager = FileManager(cfg.TRANSIENT_ROOT,
cfg.PERSISTENT_ROOT)
filesessionmaker(sessionmaker(...), file_manager) | [
"u",
"Wrapper",
"of",
"session",
"maker",
"adding",
"link",
"to",
"a",
"FileManager",
"instance",
"to",
"session",
".",
"::"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/db/sqla/files.py#L210-L256 |
sailthru/relay | relay/plugins/__init__.py | oscillating_setpoint | def oscillating_setpoint(_square_wave=False, shift=0):
"""A basic example of a target that you may want to approximate.
If you have a thermostat, this is a temperature setting.
This target can't change too often
"""
import math
c = 0
while 1:
if _square_wave:
yield ((c % 300) < 150) * 30 + 20
c += 1
else:
yield 10 * math.sin(2 * 3.1415926 * c + shift) \
+ 20 + 5 * math.sin(2 * 3.1415926 * c * 3 + shift)
c += .001 | python | def oscillating_setpoint(_square_wave=False, shift=0):
"""A basic example of a target that you may want to approximate.
If you have a thermostat, this is a temperature setting.
This target can't change too often
"""
import math
c = 0
while 1:
if _square_wave:
yield ((c % 300) < 150) * 30 + 20
c += 1
else:
yield 10 * math.sin(2 * 3.1415926 * c + shift) \
+ 20 + 5 * math.sin(2 * 3.1415926 * c * 3 + shift)
c += .001 | [
"def",
"oscillating_setpoint",
"(",
"_square_wave",
"=",
"False",
",",
"shift",
"=",
"0",
")",
":",
"import",
"math",
"c",
"=",
"0",
"while",
"1",
":",
"if",
"_square_wave",
":",
"yield",
"(",
"(",
"c",
"%",
"300",
")",
"<",
"150",
")",
"*",
"30",
... | A basic example of a target that you may want to approximate.
If you have a thermostat, this is a temperature setting.
This target can't change too often | [
"A",
"basic",
"example",
"of",
"a",
"target",
"that",
"you",
"may",
"want",
"to",
"approximate",
"."
] | train | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/plugins/__init__.py#L71-L86 |
sailthru/relay | relay/plugins/__init__.py | bash_echo_metric | def bash_echo_metric():
"""A very basic example that monitors
a number of currently running processes"""
import subprocess
# import random
# more predictable version of the metric
cmd = (
'set -o pipefail '
' ; pgrep -f "^bash.*sleep .*from bash: started relay launcher"'
' | wc -l '
)
# less predictable version of the metric
# cmd = 'ps aux|wc -l'
while True:
yield (
int(subprocess.check_output(cmd, shell=True, executable='bash'))
# + random.choice([-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
) | python | def bash_echo_metric():
"""A very basic example that monitors
a number of currently running processes"""
import subprocess
# import random
# more predictable version of the metric
cmd = (
'set -o pipefail '
' ; pgrep -f "^bash.*sleep .*from bash: started relay launcher"'
' | wc -l '
)
# less predictable version of the metric
# cmd = 'ps aux|wc -l'
while True:
yield (
int(subprocess.check_output(cmd, shell=True, executable='bash'))
# + random.choice([-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
) | [
"def",
"bash_echo_metric",
"(",
")",
":",
"import",
"subprocess",
"# import random",
"# more predictable version of the metric",
"cmd",
"=",
"(",
"'set -o pipefail '",
"' ; pgrep -f \"^bash.*sleep .*from bash: started relay launcher\"'",
"' | wc -l '",
")",
"# less predictable versio... | A very basic example that monitors
a number of currently running processes | [
"A",
"very",
"basic",
"example",
"that",
"monitors",
"a",
"number",
"of",
"currently",
"running",
"processes"
] | train | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/plugins/__init__.py#L101-L121 |
sailthru/relay | relay/plugins/__init__.py | bash_echo_warmer | def bash_echo_warmer(n):
"""A very basic example of how to create n additional tasks.
This is a warmer function with randomly delayed effects on the
bash_echo_metric and random task lengths to make the metric less
predictable
"""
import subprocess
import random
cmd = (
'set -o pipefail '
" ; sleep %s "
" ; sh -c 'echo from bash: started relay launcher task && sleep %s'"
)
for i in range(n):
subprocess.Popen(
cmd % ((1 + random.random()) * 1, (1 + random.random()) * 4),
shell=True, stdout=subprocess.PIPE, executable='bash') | python | def bash_echo_warmer(n):
"""A very basic example of how to create n additional tasks.
This is a warmer function with randomly delayed effects on the
bash_echo_metric and random task lengths to make the metric less
predictable
"""
import subprocess
import random
cmd = (
'set -o pipefail '
" ; sleep %s "
" ; sh -c 'echo from bash: started relay launcher task && sleep %s'"
)
for i in range(n):
subprocess.Popen(
cmd % ((1 + random.random()) * 1, (1 + random.random()) * 4),
shell=True, stdout=subprocess.PIPE, executable='bash') | [
"def",
"bash_echo_warmer",
"(",
"n",
")",
":",
"import",
"subprocess",
"import",
"random",
"cmd",
"=",
"(",
"'set -o pipefail '",
"\" ; sleep %s \"",
"\" ; sh -c 'echo from bash: started relay launcher task && sleep %s'\"",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",... | A very basic example of how to create n additional tasks.
This is a warmer function with randomly delayed effects on the
bash_echo_metric and random task lengths to make the metric less
predictable | [
"A",
"very",
"basic",
"example",
"of",
"how",
"to",
"create",
"n",
"additional",
"tasks",
".",
"This",
"is",
"a",
"warmer",
"function",
"with",
"randomly",
"delayed",
"effects",
"on",
"the",
"bash_echo_metric",
"and",
"random",
"task",
"lengths",
"to",
"make... | train | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/plugins/__init__.py#L124-L140 |
sailthru/relay | relay/plugins/__init__.py | bash_echo_cooler | def bash_echo_cooler(n):
"""A very basic example of how to destroy n running tasks
This is a cooler function
"""
import subprocess
cmd = (
'set -o pipefile '
' ; kill `pgrep -f "from bash: started relay launcher task"'
' | tail -n %s` 2>/dev/null' % n)
subprocess.Popen(cmd, shell=True, executable='bash').wait() | python | def bash_echo_cooler(n):
"""A very basic example of how to destroy n running tasks
This is a cooler function
"""
import subprocess
cmd = (
'set -o pipefile '
' ; kill `pgrep -f "from bash: started relay launcher task"'
' | tail -n %s` 2>/dev/null' % n)
subprocess.Popen(cmd, shell=True, executable='bash').wait() | [
"def",
"bash_echo_cooler",
"(",
"n",
")",
":",
"import",
"subprocess",
"cmd",
"=",
"(",
"'set -o pipefile '",
"' ; kill `pgrep -f \"from bash: started relay launcher task\"'",
"' | tail -n %s` 2>/dev/null'",
"%",
"n",
")",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"s... | A very basic example of how to destroy n running tasks
This is a cooler function | [
"A",
"very",
"basic",
"example",
"of",
"how",
"to",
"destroy",
"n",
"running",
"tasks",
"This",
"is",
"a",
"cooler",
"function"
] | train | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/plugins/__init__.py#L143-L152 |
sailthru/relay | relay/plugins/__init__.py | stop_if_mostly_diverging | def stop_if_mostly_diverging(errdata):
"""This is an example stop condition that asks Relay to quit if
the error difference between consecutive samples is increasing more than
half of the time.
It's quite sensitive and designed for the demo, so you probably shouldn't
use this is a production setting
"""
n_increases = sum([
abs(y) - abs(x) > 0 for x, y in zip(errdata, errdata[1:])])
if len(errdata) * 0.5 < n_increases:
# most of the time, the next sample is worse than the previous sample
# relay is not healthy
return 0
else:
# most of the time, the next sample is better than the previous sample
# realy is in a healthy state
return -1 | python | def stop_if_mostly_diverging(errdata):
"""This is an example stop condition that asks Relay to quit if
the error difference between consecutive samples is increasing more than
half of the time.
It's quite sensitive and designed for the demo, so you probably shouldn't
use this is a production setting
"""
n_increases = sum([
abs(y) - abs(x) > 0 for x, y in zip(errdata, errdata[1:])])
if len(errdata) * 0.5 < n_increases:
# most of the time, the next sample is worse than the previous sample
# relay is not healthy
return 0
else:
# most of the time, the next sample is better than the previous sample
# realy is in a healthy state
return -1 | [
"def",
"stop_if_mostly_diverging",
"(",
"errdata",
")",
":",
"n_increases",
"=",
"sum",
"(",
"[",
"abs",
"(",
"y",
")",
"-",
"abs",
"(",
"x",
")",
">",
"0",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"errdata",
",",
"errdata",
"[",
"1",
":",
"]",
... | This is an example stop condition that asks Relay to quit if
the error difference between consecutive samples is increasing more than
half of the time.
It's quite sensitive and designed for the demo, so you probably shouldn't
use this is a production setting | [
"This",
"is",
"an",
"example",
"stop",
"condition",
"that",
"asks",
"Relay",
"to",
"quit",
"if",
"the",
"error",
"difference",
"between",
"consecutive",
"samples",
"is",
"increasing",
"more",
"than",
"half",
"of",
"the",
"time",
"."
] | train | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/plugins/__init__.py#L155-L172 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Task.has_resolved_dependencies | def has_resolved_dependencies(self):
"""Return True if all dependencies are in State.DONE"""
for dependency in self.dependencies:
if dependency.state != Task.State.DONE:
return False
return True | python | def has_resolved_dependencies(self):
"""Return True if all dependencies are in State.DONE"""
for dependency in self.dependencies:
if dependency.state != Task.State.DONE:
return False
return True | [
"def",
"has_resolved_dependencies",
"(",
"self",
")",
":",
"for",
"dependency",
"in",
"self",
".",
"dependencies",
":",
"if",
"dependency",
".",
"state",
"!=",
"Task",
".",
"State",
".",
"DONE",
":",
"return",
"False",
"return",
"True"
] | Return True if all dependencies are in State.DONE | [
"Return",
"True",
"if",
"all",
"dependencies",
"are",
"in",
"State",
".",
"DONE"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L46-L52 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Task.dependencies_as_list | def dependencies_as_list(self):
"""Returns a list of dependency names."""
dependencies = []
for dependency in self.dependencies:
dependencies.append(dependency.name)
return dependencies | python | def dependencies_as_list(self):
"""Returns a list of dependency names."""
dependencies = []
for dependency in self.dependencies:
dependencies.append(dependency.name)
return dependencies | [
"def",
"dependencies_as_list",
"(",
"self",
")",
":",
"dependencies",
"=",
"[",
"]",
"for",
"dependency",
"in",
"self",
".",
"dependencies",
":",
"dependencies",
".",
"append",
"(",
"dependency",
".",
"name",
")",
"return",
"dependencies"
] | Returns a list of dependency names. | [
"Returns",
"a",
"list",
"of",
"dependency",
"names",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L57-L62 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Tasks.get_task | def get_task(self, name):
"""Get task by name or create it if it does not exists."""
if name in self.tasks.keys():
task = self.tasks[name]
else:
task = Task(name)
self.tasks[name] = task
return task | python | def get_task(self, name):
"""Get task by name or create it if it does not exists."""
if name in self.tasks.keys():
task = self.tasks[name]
else:
task = Task(name)
self.tasks[name] = task
return task | [
"def",
"get_task",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"tasks",
".",
"keys",
"(",
")",
":",
"task",
"=",
"self",
".",
"tasks",
"[",
"name",
"]",
"else",
":",
"task",
"=",
"Task",
"(",
"name",
")",
"self",
".",
... | Get task by name or create it if it does not exists. | [
"Get",
"task",
"by",
"name",
"or",
"create",
"it",
"if",
"it",
"does",
"not",
"exists",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L97-L104 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Tasks.get_next | def get_next(self):
"""Return next task from the stack that has all dependencies resolved.
Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack.
Use `count` to check is there are still some task left on the stack.
raise ValueError if total ordering is not possible."""
self.update_tasks_status()
if self.dirty:
self.tsort()
self.dirty = False
for key, task in self.tasks.iteritems():
if task.is_new() and task.has_resolved_dependencies():
return task
return None | python | def get_next(self):
"""Return next task from the stack that has all dependencies resolved.
Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack.
Use `count` to check is there are still some task left on the stack.
raise ValueError if total ordering is not possible."""
self.update_tasks_status()
if self.dirty:
self.tsort()
self.dirty = False
for key, task in self.tasks.iteritems():
if task.is_new() and task.has_resolved_dependencies():
return task
return None | [
"def",
"get_next",
"(",
"self",
")",
":",
"self",
".",
"update_tasks_status",
"(",
")",
"if",
"self",
".",
"dirty",
":",
"self",
".",
"tsort",
"(",
")",
"self",
".",
"dirty",
"=",
"False",
"for",
"key",
",",
"task",
"in",
"self",
".",
"tasks",
".",... | Return next task from the stack that has all dependencies resolved.
Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack.
Use `count` to check is there are still some task left on the stack.
raise ValueError if total ordering is not possible. | [
"Return",
"next",
"task",
"from",
"the",
"stack",
"that",
"has",
"all",
"dependencies",
"resolved",
".",
"Return",
"None",
"if",
"there",
"are",
"no",
"tasks",
"with",
"resolved",
"dependencies",
"or",
"is",
"there",
"are",
"no",
"more",
"tasks",
"on",
"st... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L114-L131 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Tasks.count_buildable_tasks | def count_buildable_tasks(self):
"""Count tasks that are new and have dependencies in non FAILED state."""
self.update_tasks_status()
buildable_tasks_count = 0
for key, task in self.tasks.iteritems():
if task.state is Task.State.NEW:
if self.are_dependencies_buildable(task):
buildable_tasks_count += 1
logging.debug("Buildable task: %s" % task.name )
else:
logging.debug("Task %s has broken dependencies." % task.name )
return buildable_tasks_count | python | def count_buildable_tasks(self):
"""Count tasks that are new and have dependencies in non FAILED state."""
self.update_tasks_status()
buildable_tasks_count = 0
for key, task in self.tasks.iteritems():
if task.state is Task.State.NEW:
if self.are_dependencies_buildable(task):
buildable_tasks_count += 1
logging.debug("Buildable task: %s" % task.name )
else:
logging.debug("Task %s has broken dependencies." % task.name )
return buildable_tasks_count | [
"def",
"count_buildable_tasks",
"(",
"self",
")",
":",
"self",
".",
"update_tasks_status",
"(",
")",
"buildable_tasks_count",
"=",
"0",
"for",
"key",
",",
"task",
"in",
"self",
".",
"tasks",
".",
"iteritems",
"(",
")",
":",
"if",
"task",
".",
"state",
"i... | Count tasks that are new and have dependencies in non FAILED state. | [
"Count",
"tasks",
"that",
"are",
"new",
"and",
"have",
"dependencies",
"in",
"non",
"FAILED",
"state",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L165-L177 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Tasks.filter_tasks | def filter_tasks(self, task_names, keep_dependencies=False):
"""If filter is applied only tasks with given name and its dependencies (if keep_keep_dependencies=True) are kept in the list of tasks."""
new_tasks = {}
for task_name in task_names:
task = self.get_task(task_name)
if task not in new_tasks:
new_tasks[task.name] = task
if keep_dependencies:
for dependency in task.ordered_dependencies():
if dependency not in new_tasks:
new_tasks[dependency.name] = dependency
else:
#strip dependencies
task.dependencies = set()
self.tasks = new_tasks | python | def filter_tasks(self, task_names, keep_dependencies=False):
"""If filter is applied only tasks with given name and its dependencies (if keep_keep_dependencies=True) are kept in the list of tasks."""
new_tasks = {}
for task_name in task_names:
task = self.get_task(task_name)
if task not in new_tasks:
new_tasks[task.name] = task
if keep_dependencies:
for dependency in task.ordered_dependencies():
if dependency not in new_tasks:
new_tasks[dependency.name] = dependency
else:
#strip dependencies
task.dependencies = set()
self.tasks = new_tasks | [
"def",
"filter_tasks",
"(",
"self",
",",
"task_names",
",",
"keep_dependencies",
"=",
"False",
")",
":",
"new_tasks",
"=",
"{",
"}",
"for",
"task_name",
"in",
"task_names",
":",
"task",
"=",
"self",
".",
"get_task",
"(",
"task_name",
")",
"if",
"task",
"... | If filter is applied only tasks with given name and its dependencies (if keep_keep_dependencies=True) are kept in the list of tasks. | [
"If",
"filter",
"is",
"applied",
"only",
"tasks",
"with",
"given",
"name",
"and",
"its",
"dependencies",
"(",
"if",
"keep_keep_dependencies",
"=",
"True",
")",
"are",
"kept",
"in",
"the",
"list",
"of",
"tasks",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L179-L194 |
project-ncl/pnc-cli | pnc_cli/tools/tasks.py | Tasks.tsort | def tsort(self):
"""Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
raise ValueError if ordering is not possible (check for circular or missing dependencies)"""
task_dict = {}
for key, task in self.tasks.iteritems():
task_dict[task] = task.dependencies
# parts = parts.copy()
parts = task_dict.copy()
result = []
while True:
level = set([name for name, deps in parts.iteritems() if not deps])
if not level:
break
result.append(level)
parts = dict([(name, deps - level) for name, deps in parts.iteritems() if name not in level])
if parts:
raise ValueError('total ordering not possible (check for circular or missing dependencies)')
return result | python | def tsort(self):
"""Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
raise ValueError if ordering is not possible (check for circular or missing dependencies)"""
task_dict = {}
for key, task in self.tasks.iteritems():
task_dict[task] = task.dependencies
# parts = parts.copy()
parts = task_dict.copy()
result = []
while True:
level = set([name for name, deps in parts.iteritems() if not deps])
if not level:
break
result.append(level)
parts = dict([(name, deps - level) for name, deps in parts.iteritems() if name not in level])
if parts:
raise ValueError('total ordering not possible (check for circular or missing dependencies)')
return result | [
"def",
"tsort",
"(",
"self",
")",
":",
"task_dict",
"=",
"{",
"}",
"for",
"key",
",",
"task",
"in",
"self",
".",
"tasks",
".",
"iteritems",
"(",
")",
":",
"task_dict",
"[",
"task",
"]",
"=",
"task",
".",
"dependencies",
"# parts = parts.copy()",
"parts... | Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
raise ValueError if ordering is not possible (check for circular or missing dependencies) | [
"Given",
"a",
"partial",
"ordering",
"return",
"a",
"totally",
"ordered",
"list",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L197-L223 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildtasks_api.py | BuildtasksApi.build | def build(self, build_execution_configuration, **kwargs):
"""
Triggers the build execution for a given configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build(build_execution_configuration, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str build_execution_configuration: Build Execution Configuration. See org.jboss.pnc.spi.executor.BuildExecutionConfiguration. (required)
:param str username_triggered: Username who triggered the build. If empty current user is used.
:param str callback_url: Optional Callback URL
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_with_http_info(build_execution_configuration, **kwargs)
else:
(data) = self.build_with_http_info(build_execution_configuration, **kwargs)
return data | python | def build(self, build_execution_configuration, **kwargs):
"""
Triggers the build execution for a given configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build(build_execution_configuration, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str build_execution_configuration: Build Execution Configuration. See org.jboss.pnc.spi.executor.BuildExecutionConfiguration. (required)
:param str username_triggered: Username who triggered the build. If empty current user is used.
:param str callback_url: Optional Callback URL
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_with_http_info(build_execution_configuration, **kwargs)
else:
(data) = self.build_with_http_info(build_execution_configuration, **kwargs)
return data | [
"def",
"build",
"(",
"self",
",",
"build_execution_configuration",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"build_with_htt... | Triggers the build execution for a given configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build(build_execution_configuration, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str build_execution_configuration: Build Execution Configuration. See org.jboss.pnc.spi.executor.BuildExecutionConfiguration. (required)
:param str username_triggered: Username who triggered the build. If empty current user is used.
:param str callback_url: Optional Callback URL
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Triggers",
"the",
"build",
"execution",
"for",
"a",
"given",
"configuration",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callbac... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildtasks_api.py#L42-L68 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildtasks_api.py | BuildtasksApi.build_task_completed | def build_task_completed(self, task_id, build_result, **kwargs):
"""
Notifies the completion of externally managed build task process.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build_task_completed(task_id, build_result, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: Build task id (required)
:param str build_result: Build result (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_task_completed_with_http_info(task_id, build_result, **kwargs)
else:
(data) = self.build_task_completed_with_http_info(task_id, build_result, **kwargs)
return data | python | def build_task_completed(self, task_id, build_result, **kwargs):
"""
Notifies the completion of externally managed build task process.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build_task_completed(task_id, build_result, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: Build task id (required)
:param str build_result: Build result (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.build_task_completed_with_http_info(task_id, build_result, **kwargs)
else:
(data) = self.build_task_completed_with_http_info(task_id, build_result, **kwargs)
return data | [
"def",
"build_task_completed",
"(",
"self",
",",
"task_id",
",",
"build_result",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",... | Notifies the completion of externally managed build task process.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.build_task_completed(task_id, build_result, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: Build task id (required)
:param str build_result: Build result (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Notifies",
"the",
"completion",
"of",
"externally",
"managed",
"build",
"task",
"process",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildtasks_api.py#L156-L181 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/buildtasks_api.py | BuildtasksApi.cancel_bbuild | def cancel_bbuild(self, build_execution_configuration_id, **kwargs):
"""
Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_bbuild(build_execution_configuration_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_execution_configuration_id: Build Execution Configuration ID. See org.jboss.pnc.spi.executor.BuildExecutionConfiguration. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs)
else:
(data) = self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs)
return data | python | def cancel_bbuild(self, build_execution_configuration_id, **kwargs):
"""
Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_bbuild(build_execution_configuration_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_execution_configuration_id: Build Execution Configuration ID. See org.jboss.pnc.spi.executor.BuildExecutionConfiguration. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs)
else:
(data) = self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs)
return data | [
"def",
"cancel_bbuild",
"(",
"self",
",",
"build_execution_configuration_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"can... | Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.cancel_bbuild(build_execution_configuration_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int build_execution_configuration_id: Build Execution Configuration ID. See org.jboss.pnc.spi.executor.BuildExecutionConfiguration. (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Cancel",
"the",
"build",
"execution",
"defined",
"with",
"given",
"executionConfigurationId",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildtasks_api.py#L269-L293 |
PythonRails/rails | rails/config.py | Config._load_config | def _load_config(self):
"""
Load project's config and return dict.
TODO: Convert the original dotted representation to hierarchical.
"""
config = import_module('config')
variables = [var for var in dir(config) if not var.startswith('_')]
return {var: getattr(config, var) for var in variables} | python | def _load_config(self):
"""
Load project's config and return dict.
TODO: Convert the original dotted representation to hierarchical.
"""
config = import_module('config')
variables = [var for var in dir(config) if not var.startswith('_')]
return {var: getattr(config, var) for var in variables} | [
"def",
"_load_config",
"(",
"self",
")",
":",
"config",
"=",
"import_module",
"(",
"'config'",
")",
"variables",
"=",
"[",
"var",
"for",
"var",
"in",
"dir",
"(",
"config",
")",
"if",
"not",
"var",
".",
"startswith",
"(",
"'_'",
")",
"]",
"return",
"{... | Load project's config and return dict.
TODO: Convert the original dotted representation to hierarchical. | [
"Load",
"project",
"s",
"config",
"and",
"return",
"dict",
"."
] | train | https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/config.py#L18-L26 |
PythonRails/rails | rails/config.py | Config.get | def get(name, default=None):
"""
Return variable by name from the project's config.
Name can be a dotted path, like: 'rails.db.type'.
"""
if '.' not in name:
raise Exception("Config path should be divided by at least one dot")
section_name, var_path = name.split('.', 1)
section = Config._data.get(section_name)
return section.get(var_path) | python | def get(name, default=None):
"""
Return variable by name from the project's config.
Name can be a dotted path, like: 'rails.db.type'.
"""
if '.' not in name:
raise Exception("Config path should be divided by at least one dot")
section_name, var_path = name.split('.', 1)
section = Config._data.get(section_name)
return section.get(var_path) | [
"def",
"get",
"(",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"'.'",
"not",
"in",
"name",
":",
"raise",
"Exception",
"(",
"\"Config path should be divided by at least one dot\"",
")",
"section_name",
",",
"var_path",
"=",
"name",
".",
"split",
"(",
... | Return variable by name from the project's config.
Name can be a dotted path, like: 'rails.db.type'. | [
"Return",
"variable",
"by",
"name",
"from",
"the",
"project",
"s",
"config",
"."
] | train | https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/config.py#L29-L39 |
CivicSpleen/ambry | ambry/util/sortedcollection.py | SortedCollection.find_le | def find_le(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
return self._items[i - 1]
raise ValueError('No item found with key at or below: %r' % (k,)) | python | def find_le(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
return self._items[i - 1]
raise ValueError('No item found with key at or below: %r' % (k,)) | [
"def",
"find_le",
"(",
"self",
",",
"k",
")",
":",
"i",
"=",
"bisect_right",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"if",
"i",
":",
"return",
"self",
".",
"_items",
"[",
"i",
"-",
"1",
"]",
"raise",
"ValueError",
"(",
"'No item found with key at o... | Return last item with a key <= k. Raise ValueError if not found. | [
"Return",
"last",
"item",
"with",
"a",
"key",
"<",
"=",
"k",
".",
"Raise",
"ValueError",
"if",
"not",
"found",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/sortedcollection.py#L186-L191 |
CivicSpleen/ambry | ambry/util/sortedcollection.py | SortedCollection.find_le_index | def find_le_index(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
return i - 1
raise ValueError('No item found with key at or below: %r' % (k,)) | python | def find_le_index(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
return i - 1
raise ValueError('No item found with key at or below: %r' % (k,)) | [
"def",
"find_le_index",
"(",
"self",
",",
"k",
")",
":",
"i",
"=",
"bisect_right",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"if",
"i",
":",
"return",
"i",
"-",
"1",
"raise",
"ValueError",
"(",
"'No item found with key at or below: %r'",
"%",
"(",
"k",
... | Return last item with a key <= k. Raise ValueError if not found. | [
"Return",
"last",
"item",
"with",
"a",
"key",
"<",
"=",
"k",
".",
"Raise",
"ValueError",
"if",
"not",
"found",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/sortedcollection.py#L193-L198 |
CivicSpleen/ambry | ambry/util/sortedcollection.py | SortedCollection.find_lt | def find_lt(self, k):
"""Return last item with a key < k.
Raise ValueError if not found.
"""
i = bisect_left(self._keys, k)
if i:
return self._items[i - 1]
raise ValueError('No item found with key below: %r' % (k,)) | python | def find_lt(self, k):
"""Return last item with a key < k.
Raise ValueError if not found.
"""
i = bisect_left(self._keys, k)
if i:
return self._items[i - 1]
raise ValueError('No item found with key below: %r' % (k,)) | [
"def",
"find_lt",
"(",
"self",
",",
"k",
")",
":",
"i",
"=",
"bisect_left",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"if",
"i",
":",
"return",
"self",
".",
"_items",
"[",
"i",
"-",
"1",
"]",
"raise",
"ValueError",
"(",
"'No item found with key below... | Return last item with a key < k.
Raise ValueError if not found. | [
"Return",
"last",
"item",
"with",
"a",
"key",
"<",
"k",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/sortedcollection.py#L200-L209 |
CivicSpleen/ambry | ambry/util/sortedcollection.py | SortedCollection.find_ge_index | def find_ge_index(self, k):
'Return first item with a key >= equal to k. Raise ValueError if not found'
i = bisect_left(self._keys, k)
if i != len(self):
return i
raise ValueError('No item found with key at or above: %r' % (k,)) | python | def find_ge_index(self, k):
'Return first item with a key >= equal to k. Raise ValueError if not found'
i = bisect_left(self._keys, k)
if i != len(self):
return i
raise ValueError('No item found with key at or above: %r' % (k,)) | [
"def",
"find_ge_index",
"(",
"self",
",",
"k",
")",
":",
"i",
"=",
"bisect_left",
"(",
"self",
".",
"_keys",
",",
"k",
")",
"if",
"i",
"!=",
"len",
"(",
"self",
")",
":",
"return",
"i",
"raise",
"ValueError",
"(",
"'No item found with key at or above: %r... | Return first item with a key >= equal to k. Raise ValueError if not found | [
"Return",
"first",
"item",
"with",
"a",
"key",
">",
"=",
"equal",
"to",
"k",
".",
"Raise",
"ValueError",
"if",
"not",
"found"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/sortedcollection.py#L218-L223 |
andreafioraldi/angrdbg | angrdbg/brk.py | get_dbg_brk_linux64 | def get_dbg_brk_linux64():
'''
Return the current brk value in the debugged process (only x86_64 Linux)
'''
# TODO this method is so weird, find a unused address to inject code not
# the base address
debugger = get_debugger()
code = b'\x0f\x05' # syscall
rax = debugger.get_reg("rax")
rdi = debugger.get_reg("rdi")
rip = debugger.get_reg("rip")
efl = debugger.get_reg("efl")
debugger.set_reg("rax", 12) # sys_brk
debugger.set_reg("rdi", 0)
base = debugger.image_base()
inj = base
save = debugger.get_bytes(inj, len(code))
debugger.put_bytes(inj, code)
debugger.set_reg("rip", inj)
debugger.step_into()
debugger.wait_ready()
brk_res = debugger.get_reg("rax")
debugger.set_reg("rax", rax)
debugger.set_reg("rdi", rdi)
debugger.set_reg("rip", rip)
debugger.set_reg("efl", efl)
debugger.put_bytes(inj, save)
return brk_res | python | def get_dbg_brk_linux64():
'''
Return the current brk value in the debugged process (only x86_64 Linux)
'''
# TODO this method is so weird, find a unused address to inject code not
# the base address
debugger = get_debugger()
code = b'\x0f\x05' # syscall
rax = debugger.get_reg("rax")
rdi = debugger.get_reg("rdi")
rip = debugger.get_reg("rip")
efl = debugger.get_reg("efl")
debugger.set_reg("rax", 12) # sys_brk
debugger.set_reg("rdi", 0)
base = debugger.image_base()
inj = base
save = debugger.get_bytes(inj, len(code))
debugger.put_bytes(inj, code)
debugger.set_reg("rip", inj)
debugger.step_into()
debugger.wait_ready()
brk_res = debugger.get_reg("rax")
debugger.set_reg("rax", rax)
debugger.set_reg("rdi", rdi)
debugger.set_reg("rip", rip)
debugger.set_reg("efl", efl)
debugger.put_bytes(inj, save)
return brk_res | [
"def",
"get_dbg_brk_linux64",
"(",
")",
":",
"# TODO this method is so weird, find a unused address to inject code not",
"# the base address",
"debugger",
"=",
"get_debugger",
"(",
")",
"code",
"=",
"b'\\x0f\\x05'",
"# syscall",
"rax",
"=",
"debugger",
".",
"get_reg",
"(",
... | Return the current brk value in the debugged process (only x86_64 Linux) | [
"Return",
"the",
"current",
"brk",
"value",
"in",
"the",
"debugged",
"process",
"(",
"only",
"x86_64",
"Linux",
")"
] | train | https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/brk.py#L11-L52 |
andreafioraldi/angrdbg | angrdbg/brk.py | get_dbg_brk_linux32 | def get_dbg_brk_linux32():
'''
Return the current brk value in the debugged process (only x86 Linux)
'''
# TODO this method is so weird, find a unused address to inject code not
# the base address
debugger = get_debugger()
code = b'\xcd\x80' # int 0x80
eax = debugger.get_reg("eax")
ebx = debugger.get_reg("ebx")
eip = debugger.get_reg("eip")
efl = debugger.get_reg("efl")
debugger.set_reg("eax", 45) # sys_brk
debugger.set_reg("ebx", 0)
base = debugger.image_base()
inj = base
save = debugger.get_bytes(inj, len(code))
debugger.put_bytes(inj, code)
debugger.set_reg("eip", inj)
debugger.step_into()
debugger.wait_ready()
brk_res = debugger.get_reg("eax")
debugger.set_reg("eax", eax)
debugger.set_reg("ebx", ebx)
debugger.set_reg("eip", eip)
debugger.set_reg("efl", efl)
debugger.put_bytes(inj, save)
return brk_res | python | def get_dbg_brk_linux32():
'''
Return the current brk value in the debugged process (only x86 Linux)
'''
# TODO this method is so weird, find a unused address to inject code not
# the base address
debugger = get_debugger()
code = b'\xcd\x80' # int 0x80
eax = debugger.get_reg("eax")
ebx = debugger.get_reg("ebx")
eip = debugger.get_reg("eip")
efl = debugger.get_reg("efl")
debugger.set_reg("eax", 45) # sys_brk
debugger.set_reg("ebx", 0)
base = debugger.image_base()
inj = base
save = debugger.get_bytes(inj, len(code))
debugger.put_bytes(inj, code)
debugger.set_reg("eip", inj)
debugger.step_into()
debugger.wait_ready()
brk_res = debugger.get_reg("eax")
debugger.set_reg("eax", eax)
debugger.set_reg("ebx", ebx)
debugger.set_reg("eip", eip)
debugger.set_reg("efl", efl)
debugger.put_bytes(inj, save)
return brk_res | [
"def",
"get_dbg_brk_linux32",
"(",
")",
":",
"# TODO this method is so weird, find a unused address to inject code not",
"# the base address",
"debugger",
"=",
"get_debugger",
"(",
")",
"code",
"=",
"b'\\xcd\\x80'",
"# int 0x80",
"eax",
"=",
"debugger",
".",
"get_reg",
"(",... | Return the current brk value in the debugged process (only x86 Linux) | [
"Return",
"the",
"current",
"brk",
"value",
"in",
"the",
"debugged",
"process",
"(",
"only",
"x86",
"Linux",
")"
] | train | https://github.com/andreafioraldi/angrdbg/blob/939b20fb9b341aee695d2db12142b1eddc5b555a/angrdbg/brk.py#L55-L96 |
and800/aioreloader | aioreloader/_contents.py | start | def start(
loop: abstract_loop = None,
interval: float = 0.5,
hook: hook_type = None) -> asyncio.Task:
"""
Start the reloader.
Create the task which is watching loaded modules
and manually added files via ``watch()``
and reloading the process in case of modification.
Attach this task to the loop.
If ``hook`` is provided, it will be called right before
the application goes to the reload stage.
"""
if loop is None:
loop = asyncio.get_event_loop()
global reload_hook
if hook is not None:
reload_hook = hook
global task
if not task:
modify_times = {}
executor = ThreadPoolExecutor(1)
task = call_periodically(
loop,
interval,
check_and_reload,
modify_times,
executor,
)
return task | python | def start(
loop: abstract_loop = None,
interval: float = 0.5,
hook: hook_type = None) -> asyncio.Task:
"""
Start the reloader.
Create the task which is watching loaded modules
and manually added files via ``watch()``
and reloading the process in case of modification.
Attach this task to the loop.
If ``hook`` is provided, it will be called right before
the application goes to the reload stage.
"""
if loop is None:
loop = asyncio.get_event_loop()
global reload_hook
if hook is not None:
reload_hook = hook
global task
if not task:
modify_times = {}
executor = ThreadPoolExecutor(1)
task = call_periodically(
loop,
interval,
check_and_reload,
modify_times,
executor,
)
return task | [
"def",
"start",
"(",
"loop",
":",
"abstract_loop",
"=",
"None",
",",
"interval",
":",
"float",
"=",
"0.5",
",",
"hook",
":",
"hook_type",
"=",
"None",
")",
"->",
"asyncio",
".",
"Task",
":",
"if",
"loop",
"is",
"None",
":",
"loop",
"=",
"asyncio",
... | Start the reloader.
Create the task which is watching loaded modules
and manually added files via ``watch()``
and reloading the process in case of modification.
Attach this task to the loop.
If ``hook`` is provided, it will be called right before
the application goes to the reload stage. | [
"Start",
"the",
"reloader",
"."
] | train | https://github.com/and800/aioreloader/blob/9f44b537b69185be4f19d31d9427afdc195a8abd/aioreloader/_contents.py#L29-L62 |
SmartTeleMax/iktomi | iktomi/utils/dt.py | strftime | def strftime(dt, fmt):
'''
`strftime` implementation working before 1900
'''
if _illegal_s.search(fmt):
raise TypeError("This strftime implementation does not handle %s")
if dt.year > 1900:
return dt.strftime(fmt)
fmt = fmt.replace('%c', '%a %b %d %H:%M:%S %Y')\
.replace('%Y', str(dt.year))\
.replace('%y', '{:04}'.format(dt.year)[-2:])
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6*(delta // 100 + delta // 400)
year = year + off
# Move to around the year 2000
year = year + ((2000 - year)//28)*28
timetuple = dt.timetuple()
return time.strftime(fmt, (year,) + timetuple[1:]) | python | def strftime(dt, fmt):
'''
`strftime` implementation working before 1900
'''
if _illegal_s.search(fmt):
raise TypeError("This strftime implementation does not handle %s")
if dt.year > 1900:
return dt.strftime(fmt)
fmt = fmt.replace('%c', '%a %b %d %H:%M:%S %Y')\
.replace('%Y', str(dt.year))\
.replace('%y', '{:04}'.format(dt.year)[-2:])
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6*(delta // 100 + delta // 400)
year = year + off
# Move to around the year 2000
year = year + ((2000 - year)//28)*28
timetuple = dt.timetuple()
return time.strftime(fmt, (year,) + timetuple[1:]) | [
"def",
"strftime",
"(",
"dt",
",",
"fmt",
")",
":",
"if",
"_illegal_s",
".",
"search",
"(",
"fmt",
")",
":",
"raise",
"TypeError",
"(",
"\"This strftime implementation does not handle %s\"",
")",
"if",
"dt",
".",
"year",
">",
"1900",
":",
"return",
"dt",
"... | `strftime` implementation working before 1900 | [
"strftime",
"implementation",
"working",
"before",
"1900"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/utils/dt.py#L19-L42 |
CivicSpleen/ambry | ambry/cli/library.py | library_pg | def library_pg(args, l, config):
"""Report on the operation of a Postgres Library database"""
import tabulate
import terminaltables
from textwrap import fill
from ambry.util.text import getTerminalSize
import sys
if args.connect:
try:
l.database.connection.execute('SELECT * FROM pg_stat_activity;')
sys.exit(0)
except Exception as e:
prt(str(e))
sys.exit(1)
db = l.database
(x, y) = getTerminalSize()
if args.processes:
headers = None
rows = []
for row in db.connection.execute('SELECT pid, client_addr, application_name ass, query FROM pg_stat_activity '):
if not headers:
headers = row.keys()
row = list(str(e) for e in row)
row[3] = fill(row[3],x-50)
rows.append(row)
#print tabulate.tabulate(rows, headers)
table = terminaltables.UnixTable([headers]+rows)
print table.table
if args.blocks:
headers = None
rows = []
q1 = """
SELECT pid, database, mode, locktype, mode, relation, tuple, virtualxid FROM pg_locks order by pid;
"""
q2 = """
SELECT blocked_locks.pid AS blocked_pid,
-- blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
-- blocking_activity.usename AS blocking_user,
blocked_activity.query AS blocked_statement,
blocking_activity.query AS current_statement_in_blocking_process
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks
ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks.DATABASE IS NOT DISTINCT FROM blocked_locks.DATABASE
AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.GRANTED;
"""
for row in db.connection.execute(q2):
if not headers:
headers = row.keys()
row = list(str(e) for e in row)
row[2] = fill(row[2],(x-50)/2)
row[3] = fill(row[3], (x-50)/2)
rows.append(row)
if rows:
table = terminaltables.UnixTable([headers] + rows)
print table.table
if args.locks:
headers = None
rows = []
q = """
SELECT pid, database, mode, locktype, mode, relation::regclass, tuple, virtualxid
FROM pg_locks
ORDER BY pid
;
"""
for row in db.connection.execute(q):
if not headers:
headers = row.keys()
row = list(str(e) for e in row)
row[2] = fill(row[2], (x - 50) / 2)
row[3] = fill(row[3], (x - 50) / 2)
rows.append(row)
if rows:
table = terminaltables.UnixTable([headers] + rows)
print table.table | python | def library_pg(args, l, config):
"""Report on the operation of a Postgres Library database"""
import tabulate
import terminaltables
from textwrap import fill
from ambry.util.text import getTerminalSize
import sys
if args.connect:
try:
l.database.connection.execute('SELECT * FROM pg_stat_activity;')
sys.exit(0)
except Exception as e:
prt(str(e))
sys.exit(1)
db = l.database
(x, y) = getTerminalSize()
if args.processes:
headers = None
rows = []
for row in db.connection.execute('SELECT pid, client_addr, application_name ass, query FROM pg_stat_activity '):
if not headers:
headers = row.keys()
row = list(str(e) for e in row)
row[3] = fill(row[3],x-50)
rows.append(row)
#print tabulate.tabulate(rows, headers)
table = terminaltables.UnixTable([headers]+rows)
print table.table
if args.blocks:
headers = None
rows = []
q1 = """
SELECT pid, database, mode, locktype, mode, relation, tuple, virtualxid FROM pg_locks order by pid;
"""
q2 = """
SELECT blocked_locks.pid AS blocked_pid,
-- blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
-- blocking_activity.usename AS blocking_user,
blocked_activity.query AS blocked_statement,
blocking_activity.query AS current_statement_in_blocking_process
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks
ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks.DATABASE IS NOT DISTINCT FROM blocked_locks.DATABASE
AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.GRANTED;
"""
for row in db.connection.execute(q2):
if not headers:
headers = row.keys()
row = list(str(e) for e in row)
row[2] = fill(row[2],(x-50)/2)
row[3] = fill(row[3], (x-50)/2)
rows.append(row)
if rows:
table = terminaltables.UnixTable([headers] + rows)
print table.table
if args.locks:
headers = None
rows = []
q = """
SELECT pid, database, mode, locktype, mode, relation::regclass, tuple, virtualxid
FROM pg_locks
ORDER BY pid
;
"""
for row in db.connection.execute(q):
if not headers:
headers = row.keys()
row = list(str(e) for e in row)
row[2] = fill(row[2], (x - 50) / 2)
row[3] = fill(row[3], (x - 50) / 2)
rows.append(row)
if rows:
table = terminaltables.UnixTable([headers] + rows)
print table.table | [
"def",
"library_pg",
"(",
"args",
",",
"l",
",",
"config",
")",
":",
"import",
"tabulate",
"import",
"terminaltables",
"from",
"textwrap",
"import",
"fill",
"from",
"ambry",
".",
"util",
".",
"text",
"import",
"getTerminalSize",
"import",
"sys",
"if",
"args"... | Report on the operation of a Postgres Library database | [
"Report",
"on",
"the",
"operation",
"of",
"a",
"Postgres",
"Library",
"database"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/cli/library.py#L117-L228 |
mithro/python-datetime-tz | datetime_tz/detect_windows.py | _detect_timezone_windows | def _detect_timezone_windows():
"""Detect timezone on the windows platform."""
# pylint: disable=global-statement
global win32timezone_to_en
# Try and fetch the key_name for the timezone using
# Get(Dynamic)TimeZoneInformation
tzi = DTZI_c()
kernel32 = ctypes.windll.kernel32
getter = kernel32.GetTimeZoneInformation
getter = getattr(kernel32, "GetDynamicTimeZoneInformation", getter)
# code is for daylight savings: 0 means disabled/not defined, 1 means enabled
# but inactive, 2 means enabled and active
_ = getter(ctypes.byref(tzi))
win32tz_key_name = tzi.key_name
if not win32tz_key_name:
if win32timezone is None:
return None
# We're on Windows before Vista/Server 2008 - need to look up the
# standard_name in the registry.
# This will not work in some multilingual setups if running in a language
# other than the operating system default
win32tz_name = tzi.standard_name
if not win32timezone_to_en:
win32timezone_to_en = dict(
win32timezone.TimeZoneInfo._get_indexed_time_zone_keys("Std"))
win32tz_key_name = win32timezone_to_en.get(win32tz_name, win32tz_name)
territory = locale.getdefaultlocale()[0].split("_", 1)[1]
olson_name = win32tz_map.win32timezones.get((win32tz_key_name, territory), win32tz_map.win32timezones.get(win32tz_key_name, None))
if not olson_name:
return None
if not isinstance(olson_name, str):
olson_name = olson_name.encode("ascii")
return pytz.timezone(olson_name) | python | def _detect_timezone_windows():
"""Detect timezone on the windows platform."""
# pylint: disable=global-statement
global win32timezone_to_en
# Try and fetch the key_name for the timezone using
# Get(Dynamic)TimeZoneInformation
tzi = DTZI_c()
kernel32 = ctypes.windll.kernel32
getter = kernel32.GetTimeZoneInformation
getter = getattr(kernel32, "GetDynamicTimeZoneInformation", getter)
# code is for daylight savings: 0 means disabled/not defined, 1 means enabled
# but inactive, 2 means enabled and active
_ = getter(ctypes.byref(tzi))
win32tz_key_name = tzi.key_name
if not win32tz_key_name:
if win32timezone is None:
return None
# We're on Windows before Vista/Server 2008 - need to look up the
# standard_name in the registry.
# This will not work in some multilingual setups if running in a language
# other than the operating system default
win32tz_name = tzi.standard_name
if not win32timezone_to_en:
win32timezone_to_en = dict(
win32timezone.TimeZoneInfo._get_indexed_time_zone_keys("Std"))
win32tz_key_name = win32timezone_to_en.get(win32tz_name, win32tz_name)
territory = locale.getdefaultlocale()[0].split("_", 1)[1]
olson_name = win32tz_map.win32timezones.get((win32tz_key_name, territory), win32tz_map.win32timezones.get(win32tz_key_name, None))
if not olson_name:
return None
if not isinstance(olson_name, str):
olson_name = olson_name.encode("ascii")
return pytz.timezone(olson_name) | [
"def",
"_detect_timezone_windows",
"(",
")",
":",
"# pylint: disable=global-statement",
"global",
"win32timezone_to_en",
"# Try and fetch the key_name for the timezone using",
"# Get(Dynamic)TimeZoneInformation",
"tzi",
"=",
"DTZI_c",
"(",
")",
"kernel32",
"=",
"ctypes",
".",
"... | Detect timezone on the windows platform. | [
"Detect",
"timezone",
"on",
"the",
"windows",
"platform",
"."
] | train | https://github.com/mithro/python-datetime-tz/blob/3c682d003f8b28e39f0c096773e471aeb68e6bbb/datetime_tz/detect_windows.py#L89-L126 |
SmartTeleMax/iktomi | iktomi/auth.py | encrypt_password | def encrypt_password(raw_password, algorithm='sha1', salt=None):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or other supported by hashlib).
"""
if salt is None:
salt = binascii.hexlify(os.urandom(3))[:5]
else:
salt = salt.encode('utf-8')
raw_password = raw_password.encode('utf-8')
hash = hashlib.new(algorithm, salt+raw_password).hexdigest()
return '{}${}${}'.format(algorithm, salt.decode('utf-8'), hash) | python | def encrypt_password(raw_password, algorithm='sha1', salt=None):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or other supported by hashlib).
"""
if salt is None:
salt = binascii.hexlify(os.urandom(3))[:5]
else:
salt = salt.encode('utf-8')
raw_password = raw_password.encode('utf-8')
hash = hashlib.new(algorithm, salt+raw_password).hexdigest()
return '{}${}${}'.format(algorithm, salt.decode('utf-8'), hash) | [
"def",
"encrypt_password",
"(",
"raw_password",
",",
"algorithm",
"=",
"'sha1'",
",",
"salt",
"=",
"None",
")",
":",
"if",
"salt",
"is",
"None",
":",
"salt",
"=",
"binascii",
".",
"hexlify",
"(",
"os",
".",
"urandom",
"(",
"3",
")",
")",
"[",
":",
... | Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or other supported by hashlib). | [
"Returns",
"a",
"string",
"of",
"the",
"hexdigest",
"of",
"the",
"given",
"plaintext",
"password",
"and",
"salt",
"using",
"the",
"given",
"algorithm",
"(",
"md5",
"sha1",
"or",
"other",
"supported",
"by",
"hashlib",
")",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/auth.py#L18-L30 |
SmartTeleMax/iktomi | iktomi/auth.py | check_password | def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return enc_password == encrypt_password(raw_password, algorithm=algo,
salt=salt) | python | def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return enc_password == encrypt_password(raw_password, algorithm=algo,
salt=salt) | [
"def",
"check_password",
"(",
"raw_password",
",",
"enc_password",
")",
":",
"algo",
",",
"salt",
",",
"hsh",
"=",
"enc_password",
".",
"split",
"(",
"'$'",
")",
"return",
"enc_password",
"==",
"encrypt_password",
"(",
"raw_password",
",",
"algorithm",
"=",
... | Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes. | [
"Returns",
"a",
"boolean",
"of",
"whether",
"the",
"raw_password",
"was",
"correct",
".",
"Handles",
"encryption",
"formats",
"behind",
"the",
"scenes",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/auth.py#L33-L40 |
SmartTeleMax/iktomi | iktomi/auth.py | CookieAuth.login | def login(self, template='login'):
'''
This property will return component which will handle login requests.
auth.login(template='login.html')
'''
def _login(env, data):
form = self._login_form(env)
next = env.request.GET.get('next', '/')
login_failed = False
if env.request.method == 'POST':
if form.accept(env.request.POST):
user_identity = self.get_user_identity(
env, **form.python_data)
if user_identity is not None:
response = HTTPSeeOther(location=next)
return self.login_identity(user_identity, response)
login_failed = True
data.form = form
data.login_failed = login_failed
data.login_url = env.root.login.as_url.qs_set(next=next)
return env.template.render_to_response(template, data.as_dict())
return web.match('/login', 'login') | _login | python | def login(self, template='login'):
'''
This property will return component which will handle login requests.
auth.login(template='login.html')
'''
def _login(env, data):
form = self._login_form(env)
next = env.request.GET.get('next', '/')
login_failed = False
if env.request.method == 'POST':
if form.accept(env.request.POST):
user_identity = self.get_user_identity(
env, **form.python_data)
if user_identity is not None:
response = HTTPSeeOther(location=next)
return self.login_identity(user_identity, response)
login_failed = True
data.form = form
data.login_failed = login_failed
data.login_url = env.root.login.as_url.qs_set(next=next)
return env.template.render_to_response(template, data.as_dict())
return web.match('/login', 'login') | _login | [
"def",
"login",
"(",
"self",
",",
"template",
"=",
"'login'",
")",
":",
"def",
"_login",
"(",
"env",
",",
"data",
")",
":",
"form",
"=",
"self",
".",
"_login_form",
"(",
"env",
")",
"next",
"=",
"env",
".",
"request",
".",
"GET",
".",
"get",
"(",... | This property will return component which will handle login requests.
auth.login(template='login.html') | [
"This",
"property",
"will",
"return",
"component",
"which",
"will",
"handle",
"login",
"requests",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/auth.py#L104-L126 |
SmartTeleMax/iktomi | iktomi/auth.py | CookieAuth.logout | def logout(self, redirect_to='/'):
'''
This property will return component which will handle logout requests.
It only handles POST requests and do not display any rendered content.
This handler deletes session id from `storage`. If there is no
session id provided or id is incorrect handler silently redirects to
login url and does not throw any exception.
'''
def _logout(env, data):
location = redirect_to
if location is None and env.request.referer:
location = env.request.referer
elif location is None:
location = '/'
response = HTTPSeeOther(location=str(location))
self.logout_user(env.request, response)
return response
return web.match('/logout', 'logout') | web.method('post') | _logout | python | def logout(self, redirect_to='/'):
'''
This property will return component which will handle logout requests.
It only handles POST requests and do not display any rendered content.
This handler deletes session id from `storage`. If there is no
session id provided or id is incorrect handler silently redirects to
login url and does not throw any exception.
'''
def _logout(env, data):
location = redirect_to
if location is None and env.request.referer:
location = env.request.referer
elif location is None:
location = '/'
response = HTTPSeeOther(location=str(location))
self.logout_user(env.request, response)
return response
return web.match('/logout', 'logout') | web.method('post') | _logout | [
"def",
"logout",
"(",
"self",
",",
"redirect_to",
"=",
"'/'",
")",
":",
"def",
"_logout",
"(",
"env",
",",
"data",
")",
":",
"location",
"=",
"redirect_to",
"if",
"location",
"is",
"None",
"and",
"env",
".",
"request",
".",
"referer",
":",
"location",
... | This property will return component which will handle logout requests.
It only handles POST requests and do not display any rendered content.
This handler deletes session id from `storage`. If there is no
session id provided or id is incorrect handler silently redirects to
login url and does not throw any exception. | [
"This",
"property",
"will",
"return",
"component",
"which",
"will",
"handle",
"logout",
"requests",
".",
"It",
"only",
"handles",
"POST",
"requests",
"and",
"do",
"not",
"display",
"any",
"rendered",
"content",
".",
"This",
"handler",
"deletes",
"session",
"id... | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/auth.py#L128-L145 |
project-ncl/pnc-cli | pnc_cli/swagger_client/models/support_level_page.py | SupportLevelPage.content | def content(self, content):
"""
Sets the content of this SupportLevelPage.
:param content: The content of this SupportLevelPage.
:type: list[str]
"""
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
if not set(content).issubset(set(allowed_values)):
raise ValueError(
"Invalid values for `content` [{0}], must be a subset of [{1}]"
.format(", ".join(map(str, set(content)-set(allowed_values))),
", ".join(map(str, allowed_values)))
)
self._content = content | python | def content(self, content):
"""
Sets the content of this SupportLevelPage.
:param content: The content of this SupportLevelPage.
:type: list[str]
"""
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
if not set(content).issubset(set(allowed_values)):
raise ValueError(
"Invalid values for `content` [{0}], must be a subset of [{1}]"
.format(", ".join(map(str, set(content)-set(allowed_values))),
", ".join(map(str, allowed_values)))
)
self._content = content | [
"def",
"content",
"(",
"self",
",",
"content",
")",
":",
"allowed_values",
"=",
"[",
"\"UNRELEASED\"",
",",
"\"EARLYACCESS\"",
",",
"\"SUPPORTED\"",
",",
"\"EXTENDED_SUPPORT\"",
",",
"\"EOL\"",
"]",
"if",
"not",
"set",
"(",
"content",
")",
".",
"issubset",
"... | Sets the content of this SupportLevelPage.
:param content: The content of this SupportLevelPage.
:type: list[str] | [
"Sets",
"the",
"content",
"of",
"this",
"SupportLevelPage",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/support_level_page.py#L140-L155 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/bpm_api.py | BpmApi.get_bpm_task_by_id | def get_bpm_task_by_id(self, task_id, **kwargs):
"""
Get single (recently) active BPM task.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_bpm_task_by_id(task_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: BPM task ID (required)
:return: BpmTaskRestSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_bpm_task_by_id_with_http_info(task_id, **kwargs)
else:
(data) = self.get_bpm_task_by_id_with_http_info(task_id, **kwargs)
return data | python | def get_bpm_task_by_id(self, task_id, **kwargs):
"""
Get single (recently) active BPM task.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_bpm_task_by_id(task_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: BPM task ID (required)
:return: BpmTaskRestSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_bpm_task_by_id_with_http_info(task_id, **kwargs)
else:
(data) = self.get_bpm_task_by_id_with_http_info(task_id, **kwargs)
return data | [
"def",
"get_bpm_task_by_id",
"(",
"self",
",",
"task_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_bpm_task_by_id_with... | Get single (recently) active BPM task.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_bpm_task_by_id(task_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: BPM task ID (required)
:return: BpmTaskRestSingleton
If the method is called asynchronously,
returns the request thread. | [
"Get",
"single",
"(",
"recently",
")",
"active",
"BPM",
"task",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/bpm_api.py#L42-L66 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/bpm_api.py | BpmApi.get_bpm_tasks | def get_bpm_tasks(self, **kwargs):
"""
List of (recently) active BPM tasks.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_bpm_tasks(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int page_index: Page Index
:param int page_size: Pagination size
:return: BpmTaskRestPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_bpm_tasks_with_http_info(**kwargs)
else:
(data) = self.get_bpm_tasks_with_http_info(**kwargs)
return data | python | def get_bpm_tasks(self, **kwargs):
"""
List of (recently) active BPM tasks.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_bpm_tasks(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int page_index: Page Index
:param int page_size: Pagination size
:return: BpmTaskRestPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_bpm_tasks_with_http_info(**kwargs)
else:
(data) = self.get_bpm_tasks_with_http_info(**kwargs)
return data | [
"def",
"get_bpm_tasks",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_bpm_tasks_with_http_info",
"(",
"*",
"... | List of (recently) active BPM tasks.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_bpm_tasks(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int page_index: Page Index
:param int page_size: Pagination size
:return: BpmTaskRestPage
If the method is called asynchronously,
returns the request thread. | [
"List",
"of",
"(",
"recently",
")",
"active",
"BPM",
"tasks",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/bpm_api.py#L148-L173 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/bpm_api.py | BpmApi.notify_task | def notify_task(self, task_id, **kwargs):
"""
Notify PNC about a BPM task event. Accepts polymorphic JSON {\"eventType\": \"string\"} based on \"eventType\" field.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.notify_task(task_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: BPM task ID (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.notify_task_with_http_info(task_id, **kwargs)
else:
(data) = self.notify_task_with_http_info(task_id, **kwargs)
return data | python | def notify_task(self, task_id, **kwargs):
"""
Notify PNC about a BPM task event. Accepts polymorphic JSON {\"eventType\": \"string\"} based on \"eventType\" field.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.notify_task(task_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: BPM task ID (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.notify_task_with_http_info(task_id, **kwargs)
else:
(data) = self.notify_task_with_http_info(task_id, **kwargs)
return data | [
"def",
"notify_task",
"(",
"self",
",",
"task_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"notify_task_with_http_info",
... | Notify PNC about a BPM task event. Accepts polymorphic JSON {\"eventType\": \"string\"} based on \"eventType\" field.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.notify_task(task_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int task_id: BPM task ID (required)
:return: None
If the method is called asynchronously,
returns the request thread. | [
"Notify",
"PNC",
"about",
"a",
"BPM",
"task",
"event",
".",
"Accepts",
"polymorphic",
"JSON",
"{",
"\\",
"eventType",
"\\",
":",
"\\",
"string",
"\\",
"}",
"based",
"on",
"\\",
"eventType",
"\\",
"field",
".",
"This",
"method",
"makes",
"a",
"synchronous... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/bpm_api.py#L255-L279 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/bpm_api.py | BpmApi.start_r_creation_task_with_single_url | def start_r_creation_task_with_single_url(self, body, **kwargs):
"""
Start Repository Creation task with url autodetect (internal vs. external).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.start_r_creation_task_with_single_url(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RepositoryCreationUrlAutoRest body: Task parameters. (required)
:return: int
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.start_r_creation_task_with_single_url_with_http_info(body, **kwargs)
else:
(data) = self.start_r_creation_task_with_single_url_with_http_info(body, **kwargs)
return data | python | def start_r_creation_task_with_single_url(self, body, **kwargs):
"""
Start Repository Creation task with url autodetect (internal vs. external).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.start_r_creation_task_with_single_url(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RepositoryCreationUrlAutoRest body: Task parameters. (required)
:return: int
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.start_r_creation_task_with_single_url_with_http_info(body, **kwargs)
else:
(data) = self.start_r_creation_task_with_single_url_with_http_info(body, **kwargs)
return data | [
"def",
"start_r_creation_task_with_single_url",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"start_r... | Start Repository Creation task with url autodetect (internal vs. external).
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.start_r_creation_task_with_single_url(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RepositoryCreationUrlAutoRest body: Task parameters. (required)
:return: int
If the method is called asynchronously,
returns the request thread. | [
"Start",
"Repository",
"Creation",
"task",
"with",
"url",
"autodetect",
"(",
"internal",
"vs",
".",
"external",
")",
".",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"req... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/bpm_api.py#L361-L385 |
CivicSpleen/ambry | ambry/util/flo.py | copy_file_or_flo | def copy_file_or_flo(input_, output, buffer_size=64 * 1024, cb=None):
""" Copy a file name or file-like-object to another
file name or file-like object"""
assert bool(input_)
assert bool(output)
input_opened = False
output_opened = False
try:
if isinstance(input_, string_types):
if not os.path.isdir(os.path.dirname(input_)):
os.makedirs(os.path.dirname(input_))
input_ = open(input_, 'r')
input_opened = True
if isinstance(output, string_types):
if not os.path.isdir(os.path.dirname(output)):
os.makedirs(os.path.dirname(output))
output = open(output, 'wb')
output_opened = True
# shutil.copyfileobj(input_, output, buffer_size)
def copyfileobj(fsrc, fdst, length=buffer_size):
cumulative = 0
while True:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
if cb:
cumulative += len(buf)
cb(len(buf), cumulative)
copyfileobj(input_, output)
finally:
if input_opened:
input_.close()
if output_opened:
output.close() | python | def copy_file_or_flo(input_, output, buffer_size=64 * 1024, cb=None):
""" Copy a file name or file-like-object to another
file name or file-like object"""
assert bool(input_)
assert bool(output)
input_opened = False
output_opened = False
try:
if isinstance(input_, string_types):
if not os.path.isdir(os.path.dirname(input_)):
os.makedirs(os.path.dirname(input_))
input_ = open(input_, 'r')
input_opened = True
if isinstance(output, string_types):
if not os.path.isdir(os.path.dirname(output)):
os.makedirs(os.path.dirname(output))
output = open(output, 'wb')
output_opened = True
# shutil.copyfileobj(input_, output, buffer_size)
def copyfileobj(fsrc, fdst, length=buffer_size):
cumulative = 0
while True:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
if cb:
cumulative += len(buf)
cb(len(buf), cumulative)
copyfileobj(input_, output)
finally:
if input_opened:
input_.close()
if output_opened:
output.close() | [
"def",
"copy_file_or_flo",
"(",
"input_",
",",
"output",
",",
"buffer_size",
"=",
"64",
"*",
"1024",
",",
"cb",
"=",
"None",
")",
":",
"assert",
"bool",
"(",
"input_",
")",
"assert",
"bool",
"(",
"output",
")",
"input_opened",
"=",
"False",
"output_opene... | Copy a file name or file-like-object to another
file name or file-like object | [
"Copy",
"a",
"file",
"name",
"or",
"file",
"-",
"like",
"-",
"object",
"to",
"another",
"file",
"name",
"or",
"file",
"-",
"like",
"object"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/flo.py#L38-L85 |
caktus/rapidsms-tropo | rtropo/outgoing.py | TropoBackend.configure | def configure(self, config=None, **kwargs):
"""
We expect all of our config (apart from the ENGINE) to be
in a dictionary called 'config' in our INSTALLED_BACKENDS entry
"""
self.config = config or {}
for key in ['messaging_token', 'number']:
if key not in self.config:
msg = "Tropo backend config must set '%s'; config is %r" %\
(key, config)
raise ImproperlyConfigured(msg)
if kwargs:
msg = "All tropo backend config should be within the `config`"\
"entry of the backend dictionary"
raise ImproperlyConfigured(msg) | python | def configure(self, config=None, **kwargs):
"""
We expect all of our config (apart from the ENGINE) to be
in a dictionary called 'config' in our INSTALLED_BACKENDS entry
"""
self.config = config or {}
for key in ['messaging_token', 'number']:
if key not in self.config:
msg = "Tropo backend config must set '%s'; config is %r" %\
(key, config)
raise ImproperlyConfigured(msg)
if kwargs:
msg = "All tropo backend config should be within the `config`"\
"entry of the backend dictionary"
raise ImproperlyConfigured(msg) | [
"def",
"configure",
"(",
"self",
",",
"config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"config",
"=",
"config",
"or",
"{",
"}",
"for",
"key",
"in",
"[",
"'messaging_token'",
",",
"'number'",
"]",
":",
"if",
"key",
"not",
"in",... | We expect all of our config (apart from the ENGINE) to be
in a dictionary called 'config' in our INSTALLED_BACKENDS entry | [
"We",
"expect",
"all",
"of",
"our",
"config",
"(",
"apart",
"from",
"the",
"ENGINE",
")",
"to",
"be",
"in",
"a",
"dictionary",
"called",
"config",
"in",
"our",
"INSTALLED_BACKENDS",
"entry"
] | train | https://github.com/caktus/rapidsms-tropo/blob/7680f351053837f210bf90576fa8f947c8f1c5c6/rtropo/outgoing.py#L20-L34 |
caktus/rapidsms-tropo | rtropo/outgoing.py | TropoBackend.execute_tropo_program | def execute_tropo_program(self, program):
"""
Ask Tropo to execute a program for us.
We can't do this directly;
we have to ask Tropo to call us back and then give Tropo the
program in the response body to that request from Tropo.
But we can pass data to Tropo and ask Tropo to pass it back
to us when Tropo calls us back. So, we just bundle up the program
and pass it to Tropo, then when Tropo calls us back, we
give the program back to Tropo.
We also cryptographically sign our program, so that
we can verify when we're called back with a program, that it's
one that we sent to Tropo and has not gotten mangled.
See https://docs.djangoproject.com/en/1.4/topics/signing/ for more
about the signing API.
See https://www.tropo.com/docs/webapi/passing_in_parameters_text.htm
for the format we're using to call Tropo, pass it data, and ask
them to call us back.
:param program: A Tropo program, i.e. a dictionary with a 'tropo'
key whose value is a list of dictionaries, each representing
a Tropo command.
"""
# The signer will also "pickle" the data structure for us
signed_program = signing.dumps(program)
params = {
'action': 'create', # Required by Tropo
'token': self.config['messaging_token'], # Identify ourselves
'program': signed_program, # Additional data
}
data = json.dumps(params)
# Tell Tropo we'd like our response in JSON format
# and our data is in that format too.
headers = {
'accept': 'application/json',
'content-type': 'application/json',
}
response = requests.post(base_url,
data=data,
headers=headers)
# If the HTTP request failed, raise an appropriate exception - e.g.
# if our network (or Tropo) are down:
response.raise_for_status()
result = json.loads(response.content)
if not result['success']:
raise Exception("Tropo error: %s" % result.get('error', 'unknown')) | python | def execute_tropo_program(self, program):
"""
Ask Tropo to execute a program for us.
We can't do this directly;
we have to ask Tropo to call us back and then give Tropo the
program in the response body to that request from Tropo.
But we can pass data to Tropo and ask Tropo to pass it back
to us when Tropo calls us back. So, we just bundle up the program
and pass it to Tropo, then when Tropo calls us back, we
give the program back to Tropo.
We also cryptographically sign our program, so that
we can verify when we're called back with a program, that it's
one that we sent to Tropo and has not gotten mangled.
See https://docs.djangoproject.com/en/1.4/topics/signing/ for more
about the signing API.
See https://www.tropo.com/docs/webapi/passing_in_parameters_text.htm
for the format we're using to call Tropo, pass it data, and ask
them to call us back.
:param program: A Tropo program, i.e. a dictionary with a 'tropo'
key whose value is a list of dictionaries, each representing
a Tropo command.
"""
# The signer will also "pickle" the data structure for us
signed_program = signing.dumps(program)
params = {
'action': 'create', # Required by Tropo
'token': self.config['messaging_token'], # Identify ourselves
'program': signed_program, # Additional data
}
data = json.dumps(params)
# Tell Tropo we'd like our response in JSON format
# and our data is in that format too.
headers = {
'accept': 'application/json',
'content-type': 'application/json',
}
response = requests.post(base_url,
data=data,
headers=headers)
# If the HTTP request failed, raise an appropriate exception - e.g.
# if our network (or Tropo) are down:
response.raise_for_status()
result = json.loads(response.content)
if not result['success']:
raise Exception("Tropo error: %s" % result.get('error', 'unknown')) | [
"def",
"execute_tropo_program",
"(",
"self",
",",
"program",
")",
":",
"# The signer will also \"pickle\" the data structure for us",
"signed_program",
"=",
"signing",
".",
"dumps",
"(",
"program",
")",
"params",
"=",
"{",
"'action'",
":",
"'create'",
",",
"# Required... | Ask Tropo to execute a program for us.
We can't do this directly;
we have to ask Tropo to call us back and then give Tropo the
program in the response body to that request from Tropo.
But we can pass data to Tropo and ask Tropo to pass it back
to us when Tropo calls us back. So, we just bundle up the program
and pass it to Tropo, then when Tropo calls us back, we
give the program back to Tropo.
We also cryptographically sign our program, so that
we can verify when we're called back with a program, that it's
one that we sent to Tropo and has not gotten mangled.
See https://docs.djangoproject.com/en/1.4/topics/signing/ for more
about the signing API.
See https://www.tropo.com/docs/webapi/passing_in_parameters_text.htm
for the format we're using to call Tropo, pass it data, and ask
them to call us back.
:param program: A Tropo program, i.e. a dictionary with a 'tropo'
key whose value is a list of dictionaries, each representing
a Tropo command. | [
"Ask",
"Tropo",
"to",
"execute",
"a",
"program",
"for",
"us",
"."
] | train | https://github.com/caktus/rapidsms-tropo/blob/7680f351053837f210bf90576fa8f947c8f1c5c6/rtropo/outgoing.py#L40-L96 |
caktus/rapidsms-tropo | rtropo/outgoing.py | TropoBackend.send | def send(self, id_, text, identities, context=None):
"""
Send messages when using RapidSMS 0.14.0 or later.
We can send multiple messages in one Tropo program, so we do
that.
:param id_: Unused, included for compatibility with RapidSMS.
:param string text: The message text to send.
:param identities: A list of identities to send the message to
(a list of strings)
:param context: Unused, included for compatibility with RapidSMS.
"""
# Build our program
from_ = self.config['number'].replace('-', '')
commands = []
for identity in identities:
# We'll include a 'message' command for each recipient.
# The Tropo doc explicitly says that while passing a list
# of destination numbers is not a syntax error, only the
# first number on the list will get sent the message. So
# we have to send each one as a separate `message` command.
commands.append(
{
'message': {
'say': {'value': text},
'to': identity,
'from': from_,
'channel': 'TEXT',
'network': 'SMS'
}
}
)
program = {
'tropo': commands,
}
self.execute_tropo_program(program) | python | def send(self, id_, text, identities, context=None):
"""
Send messages when using RapidSMS 0.14.0 or later.
We can send multiple messages in one Tropo program, so we do
that.
:param id_: Unused, included for compatibility with RapidSMS.
:param string text: The message text to send.
:param identities: A list of identities to send the message to
(a list of strings)
:param context: Unused, included for compatibility with RapidSMS.
"""
# Build our program
from_ = self.config['number'].replace('-', '')
commands = []
for identity in identities:
# We'll include a 'message' command for each recipient.
# The Tropo doc explicitly says that while passing a list
# of destination numbers is not a syntax error, only the
# first number on the list will get sent the message. So
# we have to send each one as a separate `message` command.
commands.append(
{
'message': {
'say': {'value': text},
'to': identity,
'from': from_,
'channel': 'TEXT',
'network': 'SMS'
}
}
)
program = {
'tropo': commands,
}
self.execute_tropo_program(program) | [
"def",
"send",
"(",
"self",
",",
"id_",
",",
"text",
",",
"identities",
",",
"context",
"=",
"None",
")",
":",
"# Build our program",
"from_",
"=",
"self",
".",
"config",
"[",
"'number'",
"]",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"commands",
"... | Send messages when using RapidSMS 0.14.0 or later.
We can send multiple messages in one Tropo program, so we do
that.
:param id_: Unused, included for compatibility with RapidSMS.
:param string text: The message text to send.
:param identities: A list of identities to send the message to
(a list of strings)
:param context: Unused, included for compatibility with RapidSMS. | [
"Send",
"messages",
"when",
"using",
"RapidSMS",
"0",
".",
"14",
".",
"0",
"or",
"later",
"."
] | train | https://github.com/caktus/rapidsms-tropo/blob/7680f351053837f210bf90576fa8f947c8f1c5c6/rtropo/outgoing.py#L98-L135 |
CivicSpleen/ambry | ambry/valuetype/geo.py | CensusTractGeoid.dotted | def dotted(self):
"""Return just the tract number, excluding the state and county, in the dotted format"""
v = str(self.geoid.tract).zfill(6)
return v[0:4] + '.' + v[4:] | python | def dotted(self):
"""Return just the tract number, excluding the state and county, in the dotted format"""
v = str(self.geoid.tract).zfill(6)
return v[0:4] + '.' + v[4:] | [
"def",
"dotted",
"(",
"self",
")",
":",
"v",
"=",
"str",
"(",
"self",
".",
"geoid",
".",
"tract",
")",
".",
"zfill",
"(",
"6",
")",
"return",
"v",
"[",
"0",
":",
"4",
"]",
"+",
"'.'",
"+",
"v",
"[",
"4",
":",
"]"
] | Return just the tract number, excluding the state and county, in the dotted format | [
"Return",
"just",
"the",
"tract",
"number",
"excluding",
"the",
"state",
"and",
"county",
"in",
"the",
"dotted",
"format"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/geo.py#L115-L118 |
CivicSpleen/ambry | ambry/valuetype/geo.py | GeoCensusVT.subclass | def subclass(cls, vt_code, vt_args):
"""Return a dynamic subclass that has the extra parameters built in"""
from geoid import get_class
import geoid.census
parser = get_class(geoid.census, vt_args.strip('/')).parse
cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_code, 'parser': parser})
globals()[cls.__name__] = cls
assert cls.parser
return cls | python | def subclass(cls, vt_code, vt_args):
"""Return a dynamic subclass that has the extra parameters built in"""
from geoid import get_class
import geoid.census
parser = get_class(geoid.census, vt_args.strip('/')).parse
cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_code, 'parser': parser})
globals()[cls.__name__] = cls
assert cls.parser
return cls | [
"def",
"subclass",
"(",
"cls",
",",
"vt_code",
",",
"vt_args",
")",
":",
"from",
"geoid",
"import",
"get_class",
"import",
"geoid",
".",
"census",
"parser",
"=",
"get_class",
"(",
"geoid",
".",
"census",
",",
"vt_args",
".",
"strip",
"(",
"'/'",
")",
"... | Return a dynamic subclass that has the extra parameters built in | [
"Return",
"a",
"dynamic",
"subclass",
"that",
"has",
"the",
"extra",
"parameters",
"built",
"in"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/valuetype/geo.py#L139-L150 |
derpston/python-multitail2 | src/multitail2.py | TailedFile._open | def _open(self, path, skip_to_end = True, offset = None):
"""Open `path`, optionally seeking to the end if `skip_to_end` is True."""
fh = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK))
# If the file is being opened for the first time, jump to the end.
# Otherwise, it is being reopened after a rotation, and we want
# content from the beginning.
if offset is None:
if skip_to_end:
fh.seek(0, 2)
self._offset = fh.tell()
else:
self._offset = 0
else:
fh.seek(offset)
self._offset = fh.tell()
self._fh = fh
self._lastsize = fh.tell()
self._inode = os.stat(self._path).st_ino | python | def _open(self, path, skip_to_end = True, offset = None):
"""Open `path`, optionally seeking to the end if `skip_to_end` is True."""
fh = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK))
# If the file is being opened for the first time, jump to the end.
# Otherwise, it is being reopened after a rotation, and we want
# content from the beginning.
if offset is None:
if skip_to_end:
fh.seek(0, 2)
self._offset = fh.tell()
else:
self._offset = 0
else:
fh.seek(offset)
self._offset = fh.tell()
self._fh = fh
self._lastsize = fh.tell()
self._inode = os.stat(self._path).st_ino | [
"def",
"_open",
"(",
"self",
",",
"path",
",",
"skip_to_end",
"=",
"True",
",",
"offset",
"=",
"None",
")",
":",
"fh",
"=",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_RDONLY",
"|",
"os",
".",
"O_NONBLOCK",
")",
... | Open `path`, optionally seeking to the end if `skip_to_end` is True. | [
"Open",
"path",
"optionally",
"seeking",
"to",
"the",
"end",
"if",
"skip_to_end",
"is",
"True",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L27-L47 |
derpston/python-multitail2 | src/multitail2.py | TailedFile._read | def _read(self, limit = None):
"""Checks the file for new data and refills the buffer if it finds any."""
# The code that used to be here was self._fh.read(limit)
# However, this broke on OSX. os.read, however, works fine, but doesn't
# take the None argument or have any way to specify "read to the end".
# This emulates that behaviour.
while True:
# Check that we haven't closed this file
if not self._fh:
return False
dataread = os.read(self._fh.fileno(), limit or 65535)
if len(dataread) > 0:
self._buf += dataread
if limit is not None:
return True
else:
return False | python | def _read(self, limit = None):
"""Checks the file for new data and refills the buffer if it finds any."""
# The code that used to be here was self._fh.read(limit)
# However, this broke on OSX. os.read, however, works fine, but doesn't
# take the None argument or have any way to specify "read to the end".
# This emulates that behaviour.
while True:
# Check that we haven't closed this file
if not self._fh:
return False
dataread = os.read(self._fh.fileno(), limit or 65535)
if len(dataread) > 0:
self._buf += dataread
if limit is not None:
return True
else:
return False | [
"def",
"_read",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"# The code that used to be here was self._fh.read(limit)",
"# However, this broke on OSX. os.read, however, works fine, but doesn't",
"# take the None argument or have any way to specify \"read to the end\".",
"# This emula... | Checks the file for new data and refills the buffer if it finds any. | [
"Checks",
"the",
"file",
"for",
"new",
"data",
"and",
"refills",
"the",
"buffer",
"if",
"it",
"finds",
"any",
"."
] | train | https://github.com/derpston/python-multitail2/blob/4f05311da3b18f7a8cfe2877e68e35e88c07298d/src/multitail2.py#L49-L65 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.