repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mozilla/treeherder | treeherder/etl/job_loader.py | JobLoader.transform | def transform(self, pulse_job):
"""
Transform a pulse job into a job that can be written to disk. Log
References and artifacts will also be transformed and loaded with the
job.
We can rely on the structure of ``pulse_job`` because it will
already have been validated against the JSON Schema at this point.
"""
job_guid = pulse_job["taskId"]
x = {
"job": {
"job_guid": job_guid,
"name": pulse_job["display"].get("jobName", "unknown"),
"job_symbol": self._get_job_symbol(pulse_job),
"group_name": pulse_job["display"].get("groupName", "unknown"),
"group_symbol": pulse_job["display"].get("groupSymbol"),
"product_name": pulse_job.get("productName", "unknown"),
"state": pulse_job["state"],
"result": self._get_result(pulse_job),
"reason": pulse_job.get("reason", "unknown"),
"who": pulse_job.get("owner", "unknown"),
"build_system_type": pulse_job["buildSystem"],
"tier": pulse_job.get("tier", 1),
"machine": self._get_machine(pulse_job),
"option_collection": self._get_option_collection(pulse_job),
"log_references": self._get_log_references(pulse_job),
"artifacts": self._get_artifacts(pulse_job, job_guid),
},
"superseded": pulse_job.get("coalesced", []),
"revision": pulse_job["origin"]["revision"]
}
# some or all the time fields may not be present in some cases
for k, v in self.TIME_FIELD_MAP.items():
if v in pulse_job:
x["job"][k] = to_timestamp(pulse_job[v])
# if only one platform is given, use it.
default_platform = pulse_job.get(
"buildMachine",
pulse_job.get("runMachine", {}))
for k, v in self.PLATFORM_FIELD_MAP.items():
platform_src = pulse_job[v] if v in pulse_job else default_platform
x["job"][k] = self._get_platform(platform_src)
# add some taskcluster metadata if it's available
# currently taskcluster doesn't pass the taskId directly, so we'll
# derive it from the guid, where it is stored in uncompressed
# guid form of a slug (see: https://github.com/taskcluster/slugid)
# FIXME: add support for processing the taskcluster information
# properly, when it's available:
# https://bugzilla.mozilla.org/show_bug.cgi?id=1323110#c7
try:
(decoded_task_id, retry_id) = job_guid.split('/')
# As of slugid v2, slugid.encode() returns a string not bytestring under Python 3.
real_task_id = slugid.encode(uuid.UUID(decoded_task_id))
x["job"].update({
"taskcluster_task_id": real_task_id,
"taskcluster_retry_id": int(retry_id)
})
# TODO: Figure out what exception types we actually expect here.
except Exception:
pass
return x | python | def transform(self, pulse_job):
"""
Transform a pulse job into a job that can be written to disk. Log
References and artifacts will also be transformed and loaded with the
job.
We can rely on the structure of ``pulse_job`` because it will
already have been validated against the JSON Schema at this point.
"""
job_guid = pulse_job["taskId"]
x = {
"job": {
"job_guid": job_guid,
"name": pulse_job["display"].get("jobName", "unknown"),
"job_symbol": self._get_job_symbol(pulse_job),
"group_name": pulse_job["display"].get("groupName", "unknown"),
"group_symbol": pulse_job["display"].get("groupSymbol"),
"product_name": pulse_job.get("productName", "unknown"),
"state": pulse_job["state"],
"result": self._get_result(pulse_job),
"reason": pulse_job.get("reason", "unknown"),
"who": pulse_job.get("owner", "unknown"),
"build_system_type": pulse_job["buildSystem"],
"tier": pulse_job.get("tier", 1),
"machine": self._get_machine(pulse_job),
"option_collection": self._get_option_collection(pulse_job),
"log_references": self._get_log_references(pulse_job),
"artifacts": self._get_artifacts(pulse_job, job_guid),
},
"superseded": pulse_job.get("coalesced", []),
"revision": pulse_job["origin"]["revision"]
}
# some or all the time fields may not be present in some cases
for k, v in self.TIME_FIELD_MAP.items():
if v in pulse_job:
x["job"][k] = to_timestamp(pulse_job[v])
# if only one platform is given, use it.
default_platform = pulse_job.get(
"buildMachine",
pulse_job.get("runMachine", {}))
for k, v in self.PLATFORM_FIELD_MAP.items():
platform_src = pulse_job[v] if v in pulse_job else default_platform
x["job"][k] = self._get_platform(platform_src)
# add some taskcluster metadata if it's available
# currently taskcluster doesn't pass the taskId directly, so we'll
# derive it from the guid, where it is stored in uncompressed
# guid form of a slug (see: https://github.com/taskcluster/slugid)
# FIXME: add support for processing the taskcluster information
# properly, when it's available:
# https://bugzilla.mozilla.org/show_bug.cgi?id=1323110#c7
try:
(decoded_task_id, retry_id) = job_guid.split('/')
# As of slugid v2, slugid.encode() returns a string not bytestring under Python 3.
real_task_id = slugid.encode(uuid.UUID(decoded_task_id))
x["job"].update({
"taskcluster_task_id": real_task_id,
"taskcluster_retry_id": int(retry_id)
})
# TODO: Figure out what exception types we actually expect here.
except Exception:
pass
return x | [
"def",
"transform",
"(",
"self",
",",
"pulse_job",
")",
":",
"job_guid",
"=",
"pulse_job",
"[",
"\"taskId\"",
"]",
"x",
"=",
"{",
"\"job\"",
":",
"{",
"\"job_guid\"",
":",
"job_guid",
",",
"\"name\"",
":",
"pulse_job",
"[",
"\"display\"",
"]",
".",
"get"... | Transform a pulse job into a job that can be written to disk. Log
References and artifacts will also be transformed and loaded with the
job.
We can rely on the structure of ``pulse_job`` because it will
already have been validated against the JSON Schema at this point. | [
"Transform",
"a",
"pulse",
"job",
"into",
"a",
"job",
"that",
"can",
"be",
"written",
"to",
"disk",
".",
"Log",
"References",
"and",
"artifacts",
"will",
"also",
"be",
"transformed",
"and",
"loaded",
"with",
"the",
"job",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/job_loader.py#L86-L153 | train | 205,600 |
mozilla/treeherder | treeherder/webapp/api/push.py | PushViewSet.retrieve | def retrieve(self, request, project, pk=None):
"""
GET method implementation for detail view of ``push``
"""
try:
push = Push.objects.get(repository__name=project,
id=pk)
serializer = PushSerializer(push)
return Response(serializer.data)
except Push.DoesNotExist:
return Response("No push with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND) | python | def retrieve(self, request, project, pk=None):
"""
GET method implementation for detail view of ``push``
"""
try:
push = Push.objects.get(repository__name=project,
id=pk)
serializer = PushSerializer(push)
return Response(serializer.data)
except Push.DoesNotExist:
return Response("No push with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND) | [
"def",
"retrieve",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"try",
":",
"push",
"=",
"Push",
".",
"objects",
".",
"get",
"(",
"repository__name",
"=",
"project",
",",
"id",
"=",
"pk",
")",
"serializer",
"=",
"P... | GET method implementation for detail view of ``push`` | [
"GET",
"method",
"implementation",
"for",
"detail",
"view",
"of",
"push"
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/push.py#L173-L184 | train | 205,601 |
mozilla/treeherder | treeherder/webapp/api/push.py | PushViewSet.status | def status(self, request, project, pk=None):
"""
Return a count of the jobs belonging to this push
grouped by job status.
"""
try:
push = Push.objects.get(id=pk)
except Push.DoesNotExist:
return Response("No push with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND)
return Response(push.get_status()) | python | def status(self, request, project, pk=None):
"""
Return a count of the jobs belonging to this push
grouped by job status.
"""
try:
push = Push.objects.get(id=pk)
except Push.DoesNotExist:
return Response("No push with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND)
return Response(push.get_status()) | [
"def",
"status",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"try",
":",
"push",
"=",
"Push",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"pk",
")",
"except",
"Push",
".",
"DoesNotExist",
":",
"return",
"Response"... | Return a count of the jobs belonging to this push
grouped by job status. | [
"Return",
"a",
"count",
"of",
"the",
"jobs",
"belonging",
"to",
"this",
"push",
"grouped",
"by",
"job",
"status",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/push.py#L187-L197 | train | 205,602 |
mozilla/treeherder | treeherder/webapp/api/push.py | PushViewSet.health | def health(self, request, project):
"""
Return a calculated assessment of the health of this push.
"""
revision = request.query_params.get('revision')
try:
push = Push.objects.get(revision=revision, repository__name=project)
except Push.DoesNotExist:
return Response("No push with revision: {0}".format(revision),
status=HTTP_404_NOT_FOUND)
push_health_test_failures = get_push_health_test_failures(push, REPO_GROUPS['trunk'])
test_result = 'fail' if len(push_health_test_failures['needInvestigation']) else 'pass'
return Response({
'revision': revision,
'id': push.id,
'result': test_result,
'metrics': [
{
'name': 'Tests',
'result': test_result,
'failures': push_health_test_failures,
},
{
'name': 'Builds (Not yet implemented)',
'result': 'pass',
'details': ['Wow, everything passed!'],
},
{
'name': 'Linting (Not yet implemented)',
'result': 'pass',
'details': ['Gosh, this code is really nicely formatted.'],
},
{
'name': 'Coverage (Not yet implemented)',
'result': 'pass',
'details': [
'Covered 42% of the tests that are needed for feature ``foo``.',
'Covered 100% of the tests that are needed for feature ``bar``.',
'The ratio of people to cake is too many...',
],
},
{
'name': 'Performance (Not yet implemented)',
'result': 'pass',
'details': ['Ludicrous Speed'],
},
],
}) | python | def health(self, request, project):
"""
Return a calculated assessment of the health of this push.
"""
revision = request.query_params.get('revision')
try:
push = Push.objects.get(revision=revision, repository__name=project)
except Push.DoesNotExist:
return Response("No push with revision: {0}".format(revision),
status=HTTP_404_NOT_FOUND)
push_health_test_failures = get_push_health_test_failures(push, REPO_GROUPS['trunk'])
test_result = 'fail' if len(push_health_test_failures['needInvestigation']) else 'pass'
return Response({
'revision': revision,
'id': push.id,
'result': test_result,
'metrics': [
{
'name': 'Tests',
'result': test_result,
'failures': push_health_test_failures,
},
{
'name': 'Builds (Not yet implemented)',
'result': 'pass',
'details': ['Wow, everything passed!'],
},
{
'name': 'Linting (Not yet implemented)',
'result': 'pass',
'details': ['Gosh, this code is really nicely formatted.'],
},
{
'name': 'Coverage (Not yet implemented)',
'result': 'pass',
'details': [
'Covered 42% of the tests that are needed for feature ``foo``.',
'Covered 100% of the tests that are needed for feature ``bar``.',
'The ratio of people to cake is too many...',
],
},
{
'name': 'Performance (Not yet implemented)',
'result': 'pass',
'details': ['Ludicrous Speed'],
},
],
}) | [
"def",
"health",
"(",
"self",
",",
"request",
",",
"project",
")",
":",
"revision",
"=",
"request",
".",
"query_params",
".",
"get",
"(",
"'revision'",
")",
"try",
":",
"push",
"=",
"Push",
".",
"objects",
".",
"get",
"(",
"revision",
"=",
"revision",
... | Return a calculated assessment of the health of this push. | [
"Return",
"a",
"calculated",
"assessment",
"of",
"the",
"health",
"of",
"this",
"push",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/push.py#L200-L249 | train | 205,603 |
mozilla/treeherder | treeherder/webapp/api/push.py | PushViewSet.decisiontask | def decisiontask(self, request, project):
"""
Return the decision task ids for the pushes.
"""
push_ids = request.query_params.getlist('push_ids')
job_type = JobType.objects.get(name='Gecko Decision Task')
decision_jobs = Job.objects.filter(
push_id__in=push_ids,
job_type=job_type
).select_related('taskcluster_metadata')
if decision_jobs:
return Response(
{job.push_id: job.taskcluster_metadata.task_id for job in decision_jobs}
)
else:
return Response("No decision tasks found for pushes: {}".format(push_ids),
status=HTTP_404_NOT_FOUND) | python | def decisiontask(self, request, project):
"""
Return the decision task ids for the pushes.
"""
push_ids = request.query_params.getlist('push_ids')
job_type = JobType.objects.get(name='Gecko Decision Task')
decision_jobs = Job.objects.filter(
push_id__in=push_ids,
job_type=job_type
).select_related('taskcluster_metadata')
if decision_jobs:
return Response(
{job.push_id: job.taskcluster_metadata.task_id for job in decision_jobs}
)
else:
return Response("No decision tasks found for pushes: {}".format(push_ids),
status=HTTP_404_NOT_FOUND) | [
"def",
"decisiontask",
"(",
"self",
",",
"request",
",",
"project",
")",
":",
"push_ids",
"=",
"request",
".",
"query_params",
".",
"getlist",
"(",
"'push_ids'",
")",
"job_type",
"=",
"JobType",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"'Gecko Decisio... | Return the decision task ids for the pushes. | [
"Return",
"the",
"decision",
"task",
"ids",
"for",
"the",
"pushes",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/push.py#L252-L269 | train | 205,604 |
romanvm/django-tinymce4-lite | tinymce/widgets.py | language_file_exists | def language_file_exists(language_code):
"""
Check if TinyMCE has a language file for the specified lang code
:param language_code: language code
:type language_code: str
:return: check result
:rtype: bool
"""
filename = '{0}.js'.format(language_code)
path = os.path.join('tinymce', 'js', 'tinymce', 'langs', filename)
return finders.find(path) is not None | python | def language_file_exists(language_code):
"""
Check if TinyMCE has a language file for the specified lang code
:param language_code: language code
:type language_code: str
:return: check result
:rtype: bool
"""
filename = '{0}.js'.format(language_code)
path = os.path.join('tinymce', 'js', 'tinymce', 'langs', filename)
return finders.find(path) is not None | [
"def",
"language_file_exists",
"(",
"language_code",
")",
":",
"filename",
"=",
"'{0}.js'",
".",
"format",
"(",
"language_code",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'tinymce'",
",",
"'js'",
",",
"'tinymce'",
",",
"'langs'",
",",
"filena... | Check if TinyMCE has a language file for the specified lang code
:param language_code: language code
:type language_code: str
:return: check result
:rtype: bool | [
"Check",
"if",
"TinyMCE",
"has",
"a",
"language",
"file",
"for",
"the",
"specified",
"lang",
"code"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/widgets.py#L49-L60 | train | 205,605 |
romanvm/django-tinymce4-lite | tinymce/widgets.py | get_language_config | def get_language_config():
"""
Creates a language configuration for TinyMCE4 based on Django project settings
:return: language- and locale-related parameters for TinyMCE 4
:rtype: dict
"""
language_code = convert_language_code(get_language() or settings.LANGUAGE_CODE)
if not language_file_exists(language_code):
language_code = language_code[:2]
if not language_file_exists(language_code):
# Fall back to English if Tiny MCE 4 does not have required translation
language_code = 'en'
config = {'language': language_code}
if get_language_bidi():
config['directionality'] = 'rtl'
else:
config['directionality'] = 'ltr'
return config | python | def get_language_config():
"""
Creates a language configuration for TinyMCE4 based on Django project settings
:return: language- and locale-related parameters for TinyMCE 4
:rtype: dict
"""
language_code = convert_language_code(get_language() or settings.LANGUAGE_CODE)
if not language_file_exists(language_code):
language_code = language_code[:2]
if not language_file_exists(language_code):
# Fall back to English if Tiny MCE 4 does not have required translation
language_code = 'en'
config = {'language': language_code}
if get_language_bidi():
config['directionality'] = 'rtl'
else:
config['directionality'] = 'ltr'
return config | [
"def",
"get_language_config",
"(",
")",
":",
"language_code",
"=",
"convert_language_code",
"(",
"get_language",
"(",
")",
"or",
"settings",
".",
"LANGUAGE_CODE",
")",
"if",
"not",
"language_file_exists",
"(",
"language_code",
")",
":",
"language_code",
"=",
"lang... | Creates a language configuration for TinyMCE4 based on Django project settings
:return: language- and locale-related parameters for TinyMCE 4
:rtype: dict | [
"Creates",
"a",
"language",
"configuration",
"for",
"TinyMCE4",
"based",
"on",
"Django",
"project",
"settings"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/widgets.py#L63-L81 | train | 205,606 |
romanvm/django-tinymce4-lite | tinymce/widgets.py | get_spellcheck_config | def get_spellcheck_config():
"""
Create TinyMCE spellchecker config based on Django settings
:return: spellchecker parameters for TinyMCE
:rtype: dict
"""
config = {}
if mce_settings.USE_SPELLCHECKER:
from enchant import list_languages
enchant_languages = list_languages()
if settings.DEBUG:
logger.info('Enchant languages: {0}'.format(enchant_languages))
lang_names = []
for lang, name in settings.LANGUAGES:
lang = convert_language_code(lang)
if lang not in enchant_languages:
lang = lang[:2]
if lang not in enchant_languages:
logger.warning('Missing {0} spellchecker dictionary!'.format(lang))
continue
if config.get('spellchecker_language') is None:
config['spellchecker_language'] = lang
lang_names.append('{0}={1}'.format(name, lang))
config['spellchecker_languages'] = ','.join(lang_names)
return config | python | def get_spellcheck_config():
"""
Create TinyMCE spellchecker config based on Django settings
:return: spellchecker parameters for TinyMCE
:rtype: dict
"""
config = {}
if mce_settings.USE_SPELLCHECKER:
from enchant import list_languages
enchant_languages = list_languages()
if settings.DEBUG:
logger.info('Enchant languages: {0}'.format(enchant_languages))
lang_names = []
for lang, name in settings.LANGUAGES:
lang = convert_language_code(lang)
if lang not in enchant_languages:
lang = lang[:2]
if lang not in enchant_languages:
logger.warning('Missing {0} spellchecker dictionary!'.format(lang))
continue
if config.get('spellchecker_language') is None:
config['spellchecker_language'] = lang
lang_names.append('{0}={1}'.format(name, lang))
config['spellchecker_languages'] = ','.join(lang_names)
return config | [
"def",
"get_spellcheck_config",
"(",
")",
":",
"config",
"=",
"{",
"}",
"if",
"mce_settings",
".",
"USE_SPELLCHECKER",
":",
"from",
"enchant",
"import",
"list_languages",
"enchant_languages",
"=",
"list_languages",
"(",
")",
"if",
"settings",
".",
"DEBUG",
":",
... | Create TinyMCE spellchecker config based on Django settings
:return: spellchecker parameters for TinyMCE
:rtype: dict | [
"Create",
"TinyMCE",
"spellchecker",
"config",
"based",
"on",
"Django",
"settings"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/widgets.py#L84-L109 | train | 205,607 |
romanvm/django-tinymce4-lite | tinymce/widgets.py | convert_language_code | def convert_language_code(django_lang):
"""
Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll"
:param django_lang: Django language code as ll-cc
:type django_lang: str
:return: ISO language code as ll_CC
:rtype: str
"""
lang_and_country = django_lang.split('-')
try:
return '_'.join((lang_and_country[0], lang_and_country[1].upper()))
except IndexError:
return lang_and_country[0] | python | def convert_language_code(django_lang):
"""
Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll"
:param django_lang: Django language code as ll-cc
:type django_lang: str
:return: ISO language code as ll_CC
:rtype: str
"""
lang_and_country = django_lang.split('-')
try:
return '_'.join((lang_and_country[0], lang_and_country[1].upper()))
except IndexError:
return lang_and_country[0] | [
"def",
"convert_language_code",
"(",
"django_lang",
")",
":",
"lang_and_country",
"=",
"django_lang",
".",
"split",
"(",
"'-'",
")",
"try",
":",
"return",
"'_'",
".",
"join",
"(",
"(",
"lang_and_country",
"[",
"0",
"]",
",",
"lang_and_country",
"[",
"1",
"... | Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll"
:param django_lang: Django language code as ll-cc
:type django_lang: str
:return: ISO language code as ll_CC
:rtype: str | [
"Converts",
"Django",
"language",
"codes",
"ll",
"-",
"cc",
"into",
"ISO",
"codes",
"ll_CC",
"or",
"ll"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/widgets.py#L112-L125 | train | 205,608 |
romanvm/django-tinymce4-lite | tinymce/settings.py | is_managed | def is_managed():
"""
Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool
"""
for item in sys.argv:
if re.search(r'manage.py|django-admin|django', item) is not None:
return True
return False | python | def is_managed():
"""
Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool
"""
for item in sys.argv:
if re.search(r'manage.py|django-admin|django', item) is not None:
return True
return False | [
"def",
"is_managed",
"(",
")",
":",
"for",
"item",
"in",
"sys",
".",
"argv",
":",
"if",
"re",
".",
"search",
"(",
"r'manage.py|django-admin|django'",
",",
"item",
")",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"False"
] | Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool | [
"Check",
"if",
"a",
"Django",
"project",
"is",
"being",
"managed",
"with",
"manage",
".",
"py",
"or",
"django",
"-",
"admin",
"scripts"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/settings.py#L12-L23 | train | 205,609 |
romanvm/django-tinymce4-lite | tinymce/views.py | spell_check | def spell_check(request):
"""
Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse
"""
data = json.loads(request.body.decode('utf-8'))
output = {'id': data['id']}
error = None
status = 200
try:
if data['params']['lang'] not in list_languages():
error = 'Missing {0} dictionary!'.format(data['params']['lang'])
raise LookupError(error)
spell_checker = checker.SpellChecker(data['params']['lang'])
spell_checker.set_text(strip_tags(data['params']['text']))
output['result'] = {spell_checker.word: spell_checker.suggest()
for err in spell_checker}
except NameError:
error = 'The pyenchant package is not installed!'
logger.exception(error)
except LookupError:
logger.exception(error)
except Exception:
error = 'Unknown error!'
logger.exception(error)
if error is not None:
output['error'] = error
status = 500
return JsonResponse(output, status=status) | python | def spell_check(request):
"""
Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse
"""
data = json.loads(request.body.decode('utf-8'))
output = {'id': data['id']}
error = None
status = 200
try:
if data['params']['lang'] not in list_languages():
error = 'Missing {0} dictionary!'.format(data['params']['lang'])
raise LookupError(error)
spell_checker = checker.SpellChecker(data['params']['lang'])
spell_checker.set_text(strip_tags(data['params']['text']))
output['result'] = {spell_checker.word: spell_checker.suggest()
for err in spell_checker}
except NameError:
error = 'The pyenchant package is not installed!'
logger.exception(error)
except LookupError:
logger.exception(error)
except Exception:
error = 'Unknown error!'
logger.exception(error)
if error is not None:
output['error'] = error
status = 500
return JsonResponse(output, status=status) | [
"def",
"spell_check",
"(",
"request",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"output",
"=",
"{",
"'id'",
":",
"data",
"[",
"'id'",
"]",
"}",
"error",
"=",
"None",
"status",... | Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse | [
"Implements",
"the",
"TinyMCE",
"4",
"spellchecker",
"protocol"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/views.py#L32-L66 | train | 205,610 |
romanvm/django-tinymce4-lite | tinymce/views.py | css | def css(request):
"""
Custom CSS for TinyMCE 4 widget
By default it fixes widget's position in Django Admin
:param request: Django http request
:type request: django.http.request.HttpRequest
:return: Django http response with CSS file for TinyMCE 4
:rtype: django.http.HttpResponse
"""
if 'grappelli' in settings.INSTALLED_APPS:
margin_left = 0
elif VERSION[:2] <= (1, 8):
margin_left = 110 # For old style admin
else:
margin_left = 170 # For Django >= 1.9 style admin
# For Django >= 2.0 responsive admin
responsive_admin = VERSION[:2] >= (2, 0)
return HttpResponse(render_to_string('tinymce/tinymce4.css',
context={
'margin_left': margin_left,
'responsive_admin': responsive_admin
},
request=request),
content_type='text/css; charset=utf-8') | python | def css(request):
"""
Custom CSS for TinyMCE 4 widget
By default it fixes widget's position in Django Admin
:param request: Django http request
:type request: django.http.request.HttpRequest
:return: Django http response with CSS file for TinyMCE 4
:rtype: django.http.HttpResponse
"""
if 'grappelli' in settings.INSTALLED_APPS:
margin_left = 0
elif VERSION[:2] <= (1, 8):
margin_left = 110 # For old style admin
else:
margin_left = 170 # For Django >= 1.9 style admin
# For Django >= 2.0 responsive admin
responsive_admin = VERSION[:2] >= (2, 0)
return HttpResponse(render_to_string('tinymce/tinymce4.css',
context={
'margin_left': margin_left,
'responsive_admin': responsive_admin
},
request=request),
content_type='text/css; charset=utf-8') | [
"def",
"css",
"(",
"request",
")",
":",
"if",
"'grappelli'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"margin_left",
"=",
"0",
"elif",
"VERSION",
"[",
":",
"2",
"]",
"<=",
"(",
"1",
",",
"8",
")",
":",
"margin_left",
"=",
"110",
"# For old style a... | Custom CSS for TinyMCE 4 widget
By default it fixes widget's position in Django Admin
:param request: Django http request
:type request: django.http.request.HttpRequest
:return: Django http response with CSS file for TinyMCE 4
:rtype: django.http.HttpResponse | [
"Custom",
"CSS",
"for",
"TinyMCE",
"4",
"widget"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/views.py#L86-L111 | train | 205,611 |
romanvm/django-tinymce4-lite | tinymce/views.py | filebrowser | def filebrowser(request):
"""
JavaScript callback function for `django-filebrowser`_
:param request: Django http request
:type request: django.http.request.HttpRequest
:return: Django http response with filebrowser JavaScript code for for TinyMCE 4
:rtype: django.http.HttpResponse
.. _django-filebrowser: https://github.com/sehmaschine/django-filebrowser
"""
try:
fb_url = reverse('fb_browse')
except:
fb_url = reverse('filebrowser:fb_browse')
return HttpResponse(jsmin(render_to_string('tinymce/filebrowser.js',
context={'fb_url': fb_url},
request=request)),
content_type='application/javascript; charset=utf-8') | python | def filebrowser(request):
"""
JavaScript callback function for `django-filebrowser`_
:param request: Django http request
:type request: django.http.request.HttpRequest
:return: Django http response with filebrowser JavaScript code for for TinyMCE 4
:rtype: django.http.HttpResponse
.. _django-filebrowser: https://github.com/sehmaschine/django-filebrowser
"""
try:
fb_url = reverse('fb_browse')
except:
fb_url = reverse('filebrowser:fb_browse')
return HttpResponse(jsmin(render_to_string('tinymce/filebrowser.js',
context={'fb_url': fb_url},
request=request)),
content_type='application/javascript; charset=utf-8') | [
"def",
"filebrowser",
"(",
"request",
")",
":",
"try",
":",
"fb_url",
"=",
"reverse",
"(",
"'fb_browse'",
")",
"except",
":",
"fb_url",
"=",
"reverse",
"(",
"'filebrowser:fb_browse'",
")",
"return",
"HttpResponse",
"(",
"jsmin",
"(",
"render_to_string",
"(",
... | JavaScript callback function for `django-filebrowser`_
:param request: Django http request
:type request: django.http.request.HttpRequest
:return: Django http response with filebrowser JavaScript code for for TinyMCE 4
:rtype: django.http.HttpResponse
.. _django-filebrowser: https://github.com/sehmaschine/django-filebrowser | [
"JavaScript",
"callback",
"function",
"for",
"django",
"-",
"filebrowser",
"_"
] | 3b9221db5f0327e1e08c79b7b8cdbdcb1848a390 | https://github.com/romanvm/django-tinymce4-lite/blob/3b9221db5f0327e1e08c79b7b8cdbdcb1848a390/tinymce/views.py#L115-L133 | train | 205,612 |
amperser/proselint | proselint/checks/lgbtq/offensive_terms.py | check | def check(text):
"""Flag offensive words based on the GLAAD reference guide."""
err = "glaad.offensive_terms"
msg = "Offensive term. Remove it or consider the context."
list = [
"fag",
"faggot",
"dyke",
"sodomite",
"homosexual agenda",
"gay agenda",
"transvestite",
"homosexual lifestyle",
"gay lifestyle"
# homo - may create false positives without additional context
# FIXME use topic detetor to decide whether "homo" is offensive
]
return existence_check(text, list, err, msg, join=True, ignore_case=False) | python | def check(text):
"""Flag offensive words based on the GLAAD reference guide."""
err = "glaad.offensive_terms"
msg = "Offensive term. Remove it or consider the context."
list = [
"fag",
"faggot",
"dyke",
"sodomite",
"homosexual agenda",
"gay agenda",
"transvestite",
"homosexual lifestyle",
"gay lifestyle"
# homo - may create false positives without additional context
# FIXME use topic detetor to decide whether "homo" is offensive
]
return existence_check(text, list, err, msg, join=True, ignore_case=False) | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"glaad.offensive_terms\"",
"msg",
"=",
"\"Offensive term. Remove it or consider the context.\"",
"list",
"=",
"[",
"\"fag\"",
",",
"\"faggot\"",
",",
"\"dyke\"",
",",
"\"sodomite\"",
",",
"\"homosexual agenda\"",
",... | Flag offensive words based on the GLAAD reference guide. | [
"Flag",
"offensive",
"words",
"based",
"on",
"the",
"GLAAD",
"reference",
"guide",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/lgbtq/offensive_terms.py#L22-L41 | train | 205,613 |
amperser/proselint | proselint/score.py | score | def score(check=None):
"""Compute the linter's score on the corpus.
Proselint's score reflects the desire to have a linter that catches many
errors, but which takes false alarms seriously. It is better not to say
something than to say the wrong thing, and the harm from saying the wrong
thing is greater than the benefit of saying the right thing. Thus our score
metric is defined as:
TP * (TP / (FP + TP)) ^ k,
where TP is the number of true positives (hits), FP is the number of
false positives (false alarms), and k > 0 is a temperature parameter that
determines the penalty for imprecision. In general, we should choose a
large value of k, one that strongly discourages the creation of rules that
can't be trusted. Suppose that k = 2. Then if the linter detects 100
errors, of which 10 are false positives, the score is 81.
"""
tp = 0
fp = 0
parent_directory = os.path.dirname(proselint_path)
path_to_corpus = os.path.join(parent_directory, "corpora", "0.1.0")
for root, _, files in os.walk(path_to_corpus):
files = [f for f in files if f.endswith(".md")]
for f in files:
fullpath = os.path.join(root, f)
# Run the linter.
print("Linting {}".format(f))
out = subprocess.check_output(["proselint", fullpath])
# Determine the number of errors.
regex = r".+?:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)"
num_errors = len(tuple(re.finditer(regex, out)))
print("Found {} errors.".format(num_errors))
# Open the document.
subprocess.call(["open", fullpath])
# Ask the scorer how many of the errors were false alarms?
input_val = None
while not isinstance(input_val, int):
try:
input_val = input("# of false alarms? ")
if input_val == "exit":
return
else:
input_val = int(input_val)
fp += input_val
tp += (num_errors - input_val)
except ValueError:
pass
print("Currently {} hits and {} false alarms\n---".format(tp, fp))
if (tp + fp) > 0:
return tp * (1.0 * tp / (tp + fp)) ** 2
else:
return 0 | python | def score(check=None):
"""Compute the linter's score on the corpus.
Proselint's score reflects the desire to have a linter that catches many
errors, but which takes false alarms seriously. It is better not to say
something than to say the wrong thing, and the harm from saying the wrong
thing is greater than the benefit of saying the right thing. Thus our score
metric is defined as:
TP * (TP / (FP + TP)) ^ k,
where TP is the number of true positives (hits), FP is the number of
false positives (false alarms), and k > 0 is a temperature parameter that
determines the penalty for imprecision. In general, we should choose a
large value of k, one that strongly discourages the creation of rules that
can't be trusted. Suppose that k = 2. Then if the linter detects 100
errors, of which 10 are false positives, the score is 81.
"""
tp = 0
fp = 0
parent_directory = os.path.dirname(proselint_path)
path_to_corpus = os.path.join(parent_directory, "corpora", "0.1.0")
for root, _, files in os.walk(path_to_corpus):
files = [f for f in files if f.endswith(".md")]
for f in files:
fullpath = os.path.join(root, f)
# Run the linter.
print("Linting {}".format(f))
out = subprocess.check_output(["proselint", fullpath])
# Determine the number of errors.
regex = r".+?:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)"
num_errors = len(tuple(re.finditer(regex, out)))
print("Found {} errors.".format(num_errors))
# Open the document.
subprocess.call(["open", fullpath])
# Ask the scorer how many of the errors were false alarms?
input_val = None
while not isinstance(input_val, int):
try:
input_val = input("# of false alarms? ")
if input_val == "exit":
return
else:
input_val = int(input_val)
fp += input_val
tp += (num_errors - input_val)
except ValueError:
pass
print("Currently {} hits and {} false alarms\n---".format(tp, fp))
if (tp + fp) > 0:
return tp * (1.0 * tp / (tp + fp)) ** 2
else:
return 0 | [
"def",
"score",
"(",
"check",
"=",
"None",
")",
":",
"tp",
"=",
"0",
"fp",
"=",
"0",
"parent_directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"proselint_path",
")",
"path_to_corpus",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_directory",... | Compute the linter's score on the corpus.
Proselint's score reflects the desire to have a linter that catches many
errors, but which takes false alarms seriously. It is better not to say
something than to say the wrong thing, and the harm from saying the wrong
thing is greater than the benefit of saying the right thing. Thus our score
metric is defined as:
TP * (TP / (FP + TP)) ^ k,
where TP is the number of true positives (hits), FP is the number of
false positives (false alarms), and k > 0 is a temperature parameter that
determines the penalty for imprecision. In general, we should choose a
large value of k, one that strongly discourages the creation of rules that
can't be trusted. Suppose that k = 2. Then if the linter detects 100
errors, of which 10 are false positives, the score is 81. | [
"Compute",
"the",
"linter",
"s",
"score",
"on",
"the",
"corpus",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/score.py#L16-L75 | train | 205,614 |
amperser/proselint | proselint/checks/links/broken.py | is_broken_link | def is_broken_link(url):
"""Determine whether the link returns a 404 error."""
try:
request = urllib_request.Request(
url, headers={'User-Agent': 'Mozilla/5.0'})
urllib_request.urlopen(request).read()
return False
except urllib_request.URLError:
return True
except SocketError:
return True | python | def is_broken_link(url):
"""Determine whether the link returns a 404 error."""
try:
request = urllib_request.Request(
url, headers={'User-Agent': 'Mozilla/5.0'})
urllib_request.urlopen(request).read()
return False
except urllib_request.URLError:
return True
except SocketError:
return True | [
"def",
"is_broken_link",
"(",
"url",
")",
":",
"try",
":",
"request",
"=",
"urllib_request",
".",
"Request",
"(",
"url",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'Mozilla/5.0'",
"}",
")",
"urllib_request",
".",
"urlopen",
"(",
"request",
")",
".",
... | Determine whether the link returns a 404 error. | [
"Determine",
"whether",
"the",
"link",
"returns",
"a",
"404",
"error",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/links/broken.py#L54-L64 | train | 205,615 |
amperser/proselint | proselint/checks/misc/suddenly.py | check | def check(text):
"""Advice on sudden vs suddenly."""
err = "misc.suddenly"
msg = u"Suddenly is nondescript, slows the action, and warns your reader."
regex = "Suddenly,"
return existence_check(text, [regex], err, msg, max_errors=3,
require_padding=False, offset=-1, ignore_case=False) | python | def check(text):
"""Advice on sudden vs suddenly."""
err = "misc.suddenly"
msg = u"Suddenly is nondescript, slows the action, and warns your reader."
regex = "Suddenly,"
return existence_check(text, [regex], err, msg, max_errors=3,
require_padding=False, offset=-1, ignore_case=False) | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"misc.suddenly\"",
"msg",
"=",
"u\"Suddenly is nondescript, slows the action, and warns your reader.\"",
"regex",
"=",
"\"Suddenly,\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",
"]",
",",
"err",
... | Advice on sudden vs suddenly. | [
"Advice",
"on",
"sudden",
"vs",
"suddenly",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/misc/suddenly.py#L32-L39 | train | 205,616 |
amperser/proselint | proselint/checks/weasel_words/very.py | check | def check(text):
"""Avoid 'very'."""
err = "weasel_words.very"
msg = ("Substitute 'damn' every time you're "
"inclined to write 'very'; your editor will delete it "
"and the writing will be just as it should be.")
regex = "very"
return existence_check(text, [regex], err, msg, max_errors=1) | python | def check(text):
"""Avoid 'very'."""
err = "weasel_words.very"
msg = ("Substitute 'damn' every time you're "
"inclined to write 'very'; your editor will delete it "
"and the writing will be just as it should be.")
regex = "very"
return existence_check(text, [regex], err, msg, max_errors=1) | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"weasel_words.very\"",
"msg",
"=",
"(",
"\"Substitute 'damn' every time you're \"",
"\"inclined to write 'very'; your editor will delete it \"",
"\"and the writing will be just as it should be.\"",
")",
"regex",
"=",
"\"very\""... | Avoid 'very'. | [
"Avoid",
"very",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/weasel_words/very.py#L21-L29 | train | 205,617 |
amperser/proselint | proselint/checks/psychology/misc.py | check_p_equals_zero | def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "psychology.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True) | python | def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "psychology.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True) | [
"def",
"check_p_equals_zero",
"(",
"text",
")",
":",
"err",
"=",
"\"psychology.p_equals_zero\"",
"msg",
"=",
"\"Unless p really equals zero, you should use more decimal places.\"",
"list",
"=",
"[",
"\"p = 0.00\"",
",",
"\"p = 0.000\"",
",",
"\"p = 0.0000\"",
",",
"]",
"r... | Check for p = 0.000. | [
"Check",
"for",
"p",
"=",
"0",
".",
"000",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/psychology/misc.py#L34-L45 | train | 205,618 |
amperser/proselint | app.py | rate | def rate():
"""Set rate limits for authenticated and nonauthenticated users."""
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return "60/minute"
else:
return "600/minute" | python | def rate():
"""Set rate limits for authenticated and nonauthenticated users."""
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return "60/minute"
else:
return "600/minute" | [
"def",
"rate",
"(",
")",
":",
"auth",
"=",
"request",
".",
"authorization",
"if",
"not",
"auth",
"or",
"not",
"check_auth",
"(",
"auth",
".",
"username",
",",
"auth",
".",
"password",
")",
":",
"return",
"\"60/minute\"",
"else",
":",
"return",
"\"600/min... | Set rate limits for authenticated and nonauthenticated users. | [
"Set",
"rate",
"limits",
"for",
"authenticated",
"and",
"nonauthenticated",
"users",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/app.py#L80-L87 | train | 205,619 |
amperser/proselint | app.py | lint | def lint():
"""Run linter on the provided text and return the results."""
if 'text' in request.values:
text = unquote(request.values['text'])
job = q.enqueue(worker_function, text)
return jsonify(job_id=job.id), 202
elif 'job_id' in request.values:
job = q.fetch_job(request.values['job_id'])
if not job:
return jsonify(
status="error",
message="No job with requested job_id."), 404
elif job.result is None:
return jsonify(
status="error",
message="Job is not yet ready."), 202
else:
errors = []
for i, e in enumerate(job.result):
app.logger.debug(e)
errors.append({
"check": e[0],
"message": e[1],
"line": e[2],
"column": e[3],
"start": e[4],
"end": e[5],
"extent": e[5] - e[4],
"severity": e[7],
"replacements": e[8],
"source_name": "",
"source_url": "",
})
return jsonify(
status="success",
data={"errors": errors}) | python | def lint():
"""Run linter on the provided text and return the results."""
if 'text' in request.values:
text = unquote(request.values['text'])
job = q.enqueue(worker_function, text)
return jsonify(job_id=job.id), 202
elif 'job_id' in request.values:
job = q.fetch_job(request.values['job_id'])
if not job:
return jsonify(
status="error",
message="No job with requested job_id."), 404
elif job.result is None:
return jsonify(
status="error",
message="Job is not yet ready."), 202
else:
errors = []
for i, e in enumerate(job.result):
app.logger.debug(e)
errors.append({
"check": e[0],
"message": e[1],
"line": e[2],
"column": e[3],
"start": e[4],
"end": e[5],
"extent": e[5] - e[4],
"severity": e[7],
"replacements": e[8],
"source_name": "",
"source_url": "",
})
return jsonify(
status="success",
data={"errors": errors}) | [
"def",
"lint",
"(",
")",
":",
"if",
"'text'",
"in",
"request",
".",
"values",
":",
"text",
"=",
"unquote",
"(",
"request",
".",
"values",
"[",
"'text'",
"]",
")",
"job",
"=",
"q",
".",
"enqueue",
"(",
"worker_function",
",",
"text",
")",
"return",
... | Run linter on the provided text and return the results. | [
"Run",
"linter",
"on",
"the",
"provided",
"text",
"and",
"return",
"the",
"results",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/app.py#L93-L133 | train | 205,620 |
amperser/proselint | proselint/checks/misc/illogic.py | check_without_your_collusion | def check_without_your_collusion(text):
"""Check the textself."""
err = "misc.illogic.collusion"
msg = "It's impossible to defraud yourself. Try 'aquiescence'."
regex = "without your collusion"
return existence_check(
text, [regex], err, msg, require_padding=False, offset=-1) | python | def check_without_your_collusion(text):
"""Check the textself."""
err = "misc.illogic.collusion"
msg = "It's impossible to defraud yourself. Try 'aquiescence'."
regex = "without your collusion"
return existence_check(
text, [regex], err, msg, require_padding=False, offset=-1) | [
"def",
"check_without_your_collusion",
"(",
"text",
")",
":",
"err",
"=",
"\"misc.illogic.collusion\"",
"msg",
"=",
"\"It's impossible to defraud yourself. Try 'aquiescence'.\"",
"regex",
"=",
"\"without your collusion\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
... | Check the textself. | [
"Check",
"the",
"textself",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/misc/illogic.py#L52-L60 | train | 205,621 |
amperser/proselint | proselint/checks/typography/exclamation.py | check_exclamations_ppm | def check_exclamations_ppm(text):
"""Make sure that the exclamation ppm is under 30."""
err = "leonard.exclamation.30ppm"
msg = u"More than 30 ppm of exclamations. Keep them under control."
regex = r"\w!"
count = len(re.findall(regex, text))
num_words = len(text.split(" "))
ppm = (count*1.0 / num_words) * 1e6
if ppm > 30 and count > 1:
loc = re.search(regex, text).start() + 1
return [(loc, loc+1, err, msg, ".")]
else:
return [] | python | def check_exclamations_ppm(text):
"""Make sure that the exclamation ppm is under 30."""
err = "leonard.exclamation.30ppm"
msg = u"More than 30 ppm of exclamations. Keep them under control."
regex = r"\w!"
count = len(re.findall(regex, text))
num_words = len(text.split(" "))
ppm = (count*1.0 / num_words) * 1e6
if ppm > 30 and count > 1:
loc = re.search(regex, text).start() + 1
return [(loc, loc+1, err, msg, ".")]
else:
return [] | [
"def",
"check_exclamations_ppm",
"(",
"text",
")",
":",
"err",
"=",
"\"leonard.exclamation.30ppm\"",
"msg",
"=",
"u\"More than 30 ppm of exclamations. Keep them under control.\"",
"regex",
"=",
"r\"\\w!\"",
"count",
"=",
"len",
"(",
"re",
".",
"findall",
"(",
"regex",
... | Make sure that the exclamation ppm is under 30. | [
"Make",
"sure",
"that",
"the",
"exclamation",
"ppm",
"is",
"under",
"30",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/typography/exclamation.py#L35-L51 | train | 205,622 |
amperser/proselint | proselint/checks/lgbtq/terms.py | check | def check(text):
"""Suggest preferred forms given the reference document."""
err = "glaad.terms"
msg = "Possibly offensive term. Consider using '{}' instead of '{}'."
list = [
["gay man", ["homosexual man"]],
["gay men", ["homosexual men"]],
["lesbian", ["homosexual woman"]],
["lesbians", ["homosexual women"]],
["gay people", ["homosexual people"]],
["gay couple", ["homosexual couple"]],
["sexual orientation", ["sexual preference"]],
["openly gay", ["admitted homosexual", "avowed homosexual"]],
["equal rights", ["special rights"]]
]
return preferred_forms_check(text, list, err, msg, ignore_case=False) | python | def check(text):
"""Suggest preferred forms given the reference document."""
err = "glaad.terms"
msg = "Possibly offensive term. Consider using '{}' instead of '{}'."
list = [
["gay man", ["homosexual man"]],
["gay men", ["homosexual men"]],
["lesbian", ["homosexual woman"]],
["lesbians", ["homosexual women"]],
["gay people", ["homosexual people"]],
["gay couple", ["homosexual couple"]],
["sexual orientation", ["sexual preference"]],
["openly gay", ["admitted homosexual", "avowed homosexual"]],
["equal rights", ["special rights"]]
]
return preferred_forms_check(text, list, err, msg, ignore_case=False) | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"glaad.terms\"",
"msg",
"=",
"\"Possibly offensive term. Consider using '{}' instead of '{}'.\"",
"list",
"=",
"[",
"[",
"\"gay man\"",
",",
"[",
"\"homosexual man\"",
"]",
"]",
",",
"[",
"\"gay men\"",
",",
"["... | Suggest preferred forms given the reference document. | [
"Suggest",
"preferred",
"forms",
"given",
"the",
"reference",
"document",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/lgbtq/terms.py#L22-L39 | train | 205,623 |
amperser/proselint | proselint/command_line.py | _delete_compiled_python_files | def _delete_compiled_python_files():
"""Remove files with a 'pyc' extension."""
for path, _, files in os.walk(os.getcwd()):
for fname in [f for f in files if os.path.splitext(f)[1] == ".pyc"]:
try:
os.remove(os.path.join(path, fname))
except OSError:
pass | python | def _delete_compiled_python_files():
"""Remove files with a 'pyc' extension."""
for path, _, files in os.walk(os.getcwd()):
for fname in [f for f in files if os.path.splitext(f)[1] == ".pyc"]:
try:
os.remove(os.path.join(path, fname))
except OSError:
pass | [
"def",
"_delete_compiled_python_files",
"(",
")",
":",
"for",
"path",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"for",
"fname",
"in",
"[",
"f",
"for",
"f",
"in",
"files",
"if",
"os",
".",
"path... | Remove files with a 'pyc' extension. | [
"Remove",
"files",
"with",
"a",
"pyc",
"extension",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/command_line.py#L54-L61 | train | 205,624 |
amperser/proselint | proselint/command_line.py | print_errors | def print_errors(filename, errors, output_json=False, compact=False):
"""Print the errors, resulting from lint, for filename."""
if output_json:
click.echo(errors_to_json(errors))
else:
for error in errors:
(check, message, line, column, start, end,
extent, severity, replacements) = error
if compact:
filename = "-"
click.echo(
filename + ":" +
str(1 + line) + ":" +
str(1 + column) + ": " +
check + " " +
message) | python | def print_errors(filename, errors, output_json=False, compact=False):
"""Print the errors, resulting from lint, for filename."""
if output_json:
click.echo(errors_to_json(errors))
else:
for error in errors:
(check, message, line, column, start, end,
extent, severity, replacements) = error
if compact:
filename = "-"
click.echo(
filename + ":" +
str(1 + line) + ":" +
str(1 + column) + ": " +
check + " " +
message) | [
"def",
"print_errors",
"(",
"filename",
",",
"errors",
",",
"output_json",
"=",
"False",
",",
"compact",
"=",
"False",
")",
":",
"if",
"output_json",
":",
"click",
".",
"echo",
"(",
"errors_to_json",
"(",
"errors",
")",
")",
"else",
":",
"for",
"error",
... | Print the errors, resulting from lint, for filename. | [
"Print",
"the",
"errors",
"resulting",
"from",
"lint",
"for",
"filename",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/command_line.py#L73-L92 | train | 205,625 |
amperser/proselint | proselint/command_line.py | proselint | def proselint(paths=None, version=None, clean=None, debug=None,
output_json=None, time=None, demo=None, compact=None):
"""A CLI for proselint, a linter for prose."""
if time:
click.echo(timing_test())
return
# In debug or clean mode, delete cache & *.pyc files before running.
if debug or clean:
clear_cache()
# Use the demo file by default.
if demo:
paths = [demo_file]
# Expand the list of directories and files.
filepaths = extract_files(list(paths))
# Lint the files
num_errors = 0
# Use stdin if no paths were specified
if len(paths) == 0:
filepaths.append('-')
for fp in filepaths:
try:
if fp == '-':
fp = '<stdin>'
f = sys.stdin
else:
f = click.open_file(
fp, 'r', encoding="utf-8", errors="replace")
errors = lint(f, debug=debug)
num_errors += len(errors)
print_errors(fp, errors, output_json, compact=compact)
except Exception:
traceback.print_exc()
# Return an exit code
close_cache_shelves()
if num_errors > 0:
sys.exit(1)
else:
sys.exit(0) | python | def proselint(paths=None, version=None, clean=None, debug=None,
output_json=None, time=None, demo=None, compact=None):
"""A CLI for proselint, a linter for prose."""
if time:
click.echo(timing_test())
return
# In debug or clean mode, delete cache & *.pyc files before running.
if debug or clean:
clear_cache()
# Use the demo file by default.
if demo:
paths = [demo_file]
# Expand the list of directories and files.
filepaths = extract_files(list(paths))
# Lint the files
num_errors = 0
# Use stdin if no paths were specified
if len(paths) == 0:
filepaths.append('-')
for fp in filepaths:
try:
if fp == '-':
fp = '<stdin>'
f = sys.stdin
else:
f = click.open_file(
fp, 'r', encoding="utf-8", errors="replace")
errors = lint(f, debug=debug)
num_errors += len(errors)
print_errors(fp, errors, output_json, compact=compact)
except Exception:
traceback.print_exc()
# Return an exit code
close_cache_shelves()
if num_errors > 0:
sys.exit(1)
else:
sys.exit(0) | [
"def",
"proselint",
"(",
"paths",
"=",
"None",
",",
"version",
"=",
"None",
",",
"clean",
"=",
"None",
",",
"debug",
"=",
"None",
",",
"output_json",
"=",
"None",
",",
"time",
"=",
"None",
",",
"demo",
"=",
"None",
",",
"compact",
"=",
"None",
")",... | A CLI for proselint, a linter for prose. | [
"A",
"CLI",
"for",
"proselint",
"a",
"linter",
"for",
"prose",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/command_line.py#L106-L150 | train | 205,626 |
amperser/proselint | proselint/command_line.py | extract_files | def extract_files(files):
"""Expand list of paths to include all text files matching the pattern."""
expanded_files = []
legal_extensions = [".md", ".txt", ".rtf", ".html", ".tex", ".markdown"]
for f in files:
# If it's a directory, recursively walk through it and find the files.
if os.path.isdir(f):
for dir_, _, filenames in os.walk(f):
for filename in filenames:
fn, file_extension = os.path.splitext(filename)
if file_extension in legal_extensions:
joined_file = os.path.join(dir_, filename)
expanded_files.append(joined_file)
# Otherwise add the file directly.
else:
expanded_files.append(f)
return expanded_files | python | def extract_files(files):
"""Expand list of paths to include all text files matching the pattern."""
expanded_files = []
legal_extensions = [".md", ".txt", ".rtf", ".html", ".tex", ".markdown"]
for f in files:
# If it's a directory, recursively walk through it and find the files.
if os.path.isdir(f):
for dir_, _, filenames in os.walk(f):
for filename in filenames:
fn, file_extension = os.path.splitext(filename)
if file_extension in legal_extensions:
joined_file = os.path.join(dir_, filename)
expanded_files.append(joined_file)
# Otherwise add the file directly.
else:
expanded_files.append(f)
return expanded_files | [
"def",
"extract_files",
"(",
"files",
")",
":",
"expanded_files",
"=",
"[",
"]",
"legal_extensions",
"=",
"[",
"\".md\"",
",",
"\".txt\"",
",",
"\".rtf\"",
",",
"\".html\"",
",",
"\".tex\"",
",",
"\".markdown\"",
"]",
"for",
"f",
"in",
"files",
":",
"# If ... | Expand list of paths to include all text files matching the pattern. | [
"Expand",
"list",
"of",
"paths",
"to",
"include",
"all",
"text",
"files",
"matching",
"the",
"pattern",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/command_line.py#L153-L172 | train | 205,627 |
amperser/proselint | proselint/checks/misc/institution_name.py | check_vtech | def check_vtech(text):
"""Suggest the correct name.
source: Virginia Tech Division of Student Affairs
source_url: http://bit.ly/2en1zbv
"""
err = "institution.vtech"
msg = "Incorrect name. Use '{}' instead of '{}'."
institution = [
["Virginia Polytechnic Institute and State University",
["Virginia Polytechnic and State University"]],
]
return preferred_forms_check(text, institution, err, msg) | python | def check_vtech(text):
"""Suggest the correct name.
source: Virginia Tech Division of Student Affairs
source_url: http://bit.ly/2en1zbv
"""
err = "institution.vtech"
msg = "Incorrect name. Use '{}' instead of '{}'."
institution = [
["Virginia Polytechnic Institute and State University",
["Virginia Polytechnic and State University"]],
]
return preferred_forms_check(text, institution, err, msg) | [
"def",
"check_vtech",
"(",
"text",
")",
":",
"err",
"=",
"\"institution.vtech\"",
"msg",
"=",
"\"Incorrect name. Use '{}' instead of '{}'.\"",
"institution",
"=",
"[",
"[",
"\"Virginia Polytechnic Institute and State University\"",
",",
"[",
"\"Virginia Polytechnic and State Un... | Suggest the correct name.
source: Virginia Tech Division of Student Affairs
source_url: http://bit.ly/2en1zbv | [
"Suggest",
"the",
"correct",
"name",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/misc/institution_name.py#L20-L33 | train | 205,628 |
amperser/proselint | proselint/checks/dates_times/dates.py | check_decade_apostrophes_short | def check_decade_apostrophes_short(text):
"""Check the text for dates of the form X0's."""
err = "dates_times.dates"
msg = u"Apostrophes aren't needed for decades."
regex = "\d0\'s"
return existence_check(
text, [regex], err, msg, excluded_topics=["50 Cent"]) | python | def check_decade_apostrophes_short(text):
"""Check the text for dates of the form X0's."""
err = "dates_times.dates"
msg = u"Apostrophes aren't needed for decades."
regex = "\d0\'s"
return existence_check(
text, [regex], err, msg, excluded_topics=["50 Cent"]) | [
"def",
"check_decade_apostrophes_short",
"(",
"text",
")",
":",
"err",
"=",
"\"dates_times.dates\"",
"msg",
"=",
"u\"Apostrophes aren't needed for decades.\"",
"regex",
"=",
"\"\\d0\\'s\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",
"]",
",",
"err",
... | Check the text for dates of the form X0's. | [
"Check",
"the",
"text",
"for",
"dates",
"of",
"the",
"form",
"X0",
"s",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/dates_times/dates.py#L21-L29 | train | 205,629 |
amperser/proselint | proselint/checks/dates_times/dates.py | check_decade_apostrophes_long | def check_decade_apostrophes_long(text):
"""Check the text for dates of the form XXX0's."""
err = "dates_times.dates"
msg = u"Apostrophes aren't needed for decades."
regex = "\d\d\d0\'s"
return existence_check(text, [regex], err, msg) | python | def check_decade_apostrophes_long(text):
"""Check the text for dates of the form XXX0's."""
err = "dates_times.dates"
msg = u"Apostrophes aren't needed for decades."
regex = "\d\d\d0\'s"
return existence_check(text, [regex], err, msg) | [
"def",
"check_decade_apostrophes_long",
"(",
"text",
")",
":",
"err",
"=",
"\"dates_times.dates\"",
"msg",
"=",
"u\"Apostrophes aren't needed for decades.\"",
"regex",
"=",
"\"\\d\\d\\d0\\'s\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",
"]",
",",
"e... | Check the text for dates of the form XXX0's. | [
"Check",
"the",
"text",
"for",
"dates",
"of",
"the",
"form",
"XXX0",
"s",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/dates_times/dates.py#L33-L39 | train | 205,630 |
amperser/proselint | proselint/tools.py | close_cache_shelves_after | def close_cache_shelves_after(f):
"""Decorator that ensures cache shelves are closed after the call."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
f(*args, **kwargs)
close_cache_shelves()
return wrapped | python | def close_cache_shelves_after(f):
"""Decorator that ensures cache shelves are closed after the call."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
f(*args, **kwargs)
close_cache_shelves()
return wrapped | [
"def",
"close_cache_shelves_after",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"close_cache_shelves",
... | Decorator that ensures cache shelves are closed after the call. | [
"Decorator",
"that",
"ensures",
"cache",
"shelves",
"are",
"closed",
"after",
"the",
"call",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L41-L47 | train | 205,631 |
amperser/proselint | proselint/tools.py | memoize | def memoize(f):
"""Cache results of computations on disk."""
# Determine the location of the cache.
cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint')
legacy_cache_dirname = os.path.join(os.path.expanduser("~"), ".proselint")
if not os.path.isdir(cache_dirname):
# Migrate the cache from the legacy path to XDG complaint location.
if os.path.isdir(legacy_cache_dirname):
os.rename(legacy_cache_dirname, cache_dirname)
# Create the cache if it does not already exist.
else:
os.makedirs(cache_dirname)
cache_filename = f.__module__ + "." + f.__name__
cachepath = os.path.join(cache_dirname, cache_filename)
@functools.wraps(f)
def wrapped(*args, **kwargs):
# handle instance methods
if hasattr(f, '__self__'):
args = args[1:]
signature = (f.__module__ + '.' + f.__name__).encode("utf-8")
tempargdict = inspect.getcallargs(f, *args, **kwargs)
for item in list(tempargdict.items()):
signature += item[1].encode("utf-8")
key = hashlib.sha256(signature).hexdigest()
try:
cache = _get_cache(cachepath)
return cache[key]
except KeyError:
value = f(*args, **kwargs)
cache[key] = value
cache.sync()
return value
except TypeError:
call_to = f.__module__ + '.' + f.__name__
print('Warning: could not disk cache call to %s;'
'it probably has unhashable args. Error: %s' %
(call_to, traceback.format_exc()))
return f(*args, **kwargs)
return wrapped | python | def memoize(f):
"""Cache results of computations on disk."""
# Determine the location of the cache.
cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint')
legacy_cache_dirname = os.path.join(os.path.expanduser("~"), ".proselint")
if not os.path.isdir(cache_dirname):
# Migrate the cache from the legacy path to XDG complaint location.
if os.path.isdir(legacy_cache_dirname):
os.rename(legacy_cache_dirname, cache_dirname)
# Create the cache if it does not already exist.
else:
os.makedirs(cache_dirname)
cache_filename = f.__module__ + "." + f.__name__
cachepath = os.path.join(cache_dirname, cache_filename)
@functools.wraps(f)
def wrapped(*args, **kwargs):
# handle instance methods
if hasattr(f, '__self__'):
args = args[1:]
signature = (f.__module__ + '.' + f.__name__).encode("utf-8")
tempargdict = inspect.getcallargs(f, *args, **kwargs)
for item in list(tempargdict.items()):
signature += item[1].encode("utf-8")
key = hashlib.sha256(signature).hexdigest()
try:
cache = _get_cache(cachepath)
return cache[key]
except KeyError:
value = f(*args, **kwargs)
cache[key] = value
cache.sync()
return value
except TypeError:
call_to = f.__module__ + '.' + f.__name__
print('Warning: could not disk cache call to %s;'
'it probably has unhashable args. Error: %s' %
(call_to, traceback.format_exc()))
return f(*args, **kwargs)
return wrapped | [
"def",
"memoize",
"(",
"f",
")",
":",
"# Determine the location of the cache.",
"cache_dirname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_get_xdg_cache_home",
"(",
")",
",",
"'proselint'",
")",
"legacy_cache_dirname",
"=",
"os",
".",
"path",
".",
"join",
"(... | Cache results of computations on disk. | [
"Cache",
"results",
"of",
"computations",
"on",
"disk",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L99-L147 | train | 205,632 |
amperser/proselint | proselint/tools.py | get_checks | def get_checks(options):
"""Extract the checks."""
sys.path.append(proselint_path)
checks = []
check_names = [key for (key, val)
in list(options["checks"].items()) if val]
for check_name in check_names:
module = importlib.import_module("checks." + check_name)
for d in dir(module):
if re.match("check", d):
checks.append(getattr(module, d))
return checks | python | def get_checks(options):
"""Extract the checks."""
sys.path.append(proselint_path)
checks = []
check_names = [key for (key, val)
in list(options["checks"].items()) if val]
for check_name in check_names:
module = importlib.import_module("checks." + check_name)
for d in dir(module):
if re.match("check", d):
checks.append(getattr(module, d))
return checks | [
"def",
"get_checks",
"(",
"options",
")",
":",
"sys",
".",
"path",
".",
"append",
"(",
"proselint_path",
")",
"checks",
"=",
"[",
"]",
"check_names",
"=",
"[",
"key",
"for",
"(",
"key",
",",
"val",
")",
"in",
"list",
"(",
"options",
"[",
"\"checks\""... | Extract the checks. | [
"Extract",
"the",
"checks",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L150-L163 | train | 205,633 |
amperser/proselint | proselint/tools.py | load_options | def load_options():
"""Read various proselintrc files, allowing user overrides."""
possible_defaults = (
'/etc/proselintrc',
os.path.join(proselint_path, '.proselintrc'),
)
options = {}
has_overrides = False
for filename in possible_defaults:
try:
options = json.load(open(filename))
break
except IOError:
pass
try:
user_options = json.load(
open(os.path.join(_get_xdg_config_home(), 'proselint', 'config')))
has_overrides = True
except IOError:
pass
# Read user configuration from the legacy path.
if not has_overrides:
try:
user_options = json.load(
open(os.path.join(os.path.expanduser('~'), '.proselintrc')))
has_overrides = True
except IOError:
pass
if has_overrides:
if 'max_errors' in user_options:
options['max_errors'] = user_options['max_errors']
if 'checks' in user_options:
for (key, value) in user_options['checks'].items():
try:
options['checks'][key] = value
except KeyError:
pass
return options | python | def load_options():
"""Read various proselintrc files, allowing user overrides."""
possible_defaults = (
'/etc/proselintrc',
os.path.join(proselint_path, '.proselintrc'),
)
options = {}
has_overrides = False
for filename in possible_defaults:
try:
options = json.load(open(filename))
break
except IOError:
pass
try:
user_options = json.load(
open(os.path.join(_get_xdg_config_home(), 'proselint', 'config')))
has_overrides = True
except IOError:
pass
# Read user configuration from the legacy path.
if not has_overrides:
try:
user_options = json.load(
open(os.path.join(os.path.expanduser('~'), '.proselintrc')))
has_overrides = True
except IOError:
pass
if has_overrides:
if 'max_errors' in user_options:
options['max_errors'] = user_options['max_errors']
if 'checks' in user_options:
for (key, value) in user_options['checks'].items():
try:
options['checks'][key] = value
except KeyError:
pass
return options | [
"def",
"load_options",
"(",
")",
":",
"possible_defaults",
"=",
"(",
"'/etc/proselintrc'",
",",
"os",
".",
"path",
".",
"join",
"(",
"proselint_path",
",",
"'.proselintrc'",
")",
",",
")",
"options",
"=",
"{",
"}",
"has_overrides",
"=",
"False",
"for",
"fi... | Read various proselintrc files, allowing user overrides. | [
"Read",
"various",
"proselintrc",
"files",
"allowing",
"user",
"overrides",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L166-L208 | train | 205,634 |
amperser/proselint | proselint/tools.py | errors_to_json | def errors_to_json(errors):
"""Convert the errors to JSON."""
out = []
for e in errors:
out.append({
"check": e[0],
"message": e[1],
"line": 1 + e[2],
"column": 1 + e[3],
"start": 1 + e[4],
"end": 1 + e[5],
"extent": e[6],
"severity": e[7],
"replacements": e[8],
})
return json.dumps(
dict(status="success", data={"errors": out}), sort_keys=True) | python | def errors_to_json(errors):
"""Convert the errors to JSON."""
out = []
for e in errors:
out.append({
"check": e[0],
"message": e[1],
"line": 1 + e[2],
"column": 1 + e[3],
"start": 1 + e[4],
"end": 1 + e[5],
"extent": e[6],
"severity": e[7],
"replacements": e[8],
})
return json.dumps(
dict(status="success", data={"errors": out}), sort_keys=True) | [
"def",
"errors_to_json",
"(",
"errors",
")",
":",
"out",
"=",
"[",
"]",
"for",
"e",
"in",
"errors",
":",
"out",
".",
"append",
"(",
"{",
"\"check\"",
":",
"e",
"[",
"0",
"]",
",",
"\"message\"",
":",
"e",
"[",
"1",
"]",
",",
"\"line\"",
":",
"1... | Convert the errors to JSON. | [
"Convert",
"the",
"errors",
"to",
"JSON",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L211-L228 | train | 205,635 |
amperser/proselint | proselint/tools.py | line_and_column | def line_and_column(text, position):
"""Return the line number and column of a position in a string."""
position_counter = 0
for idx_line, line in enumerate(text.splitlines(True)):
if (position_counter + len(line.rstrip())) >= position:
return (idx_line, position - position_counter)
else:
position_counter += len(line) | python | def line_and_column(text, position):
"""Return the line number and column of a position in a string."""
position_counter = 0
for idx_line, line in enumerate(text.splitlines(True)):
if (position_counter + len(line.rstrip())) >= position:
return (idx_line, position - position_counter)
else:
position_counter += len(line) | [
"def",
"line_and_column",
"(",
"text",
",",
"position",
")",
":",
"position_counter",
"=",
"0",
"for",
"idx_line",
",",
"line",
"in",
"enumerate",
"(",
"text",
".",
"splitlines",
"(",
"True",
")",
")",
":",
"if",
"(",
"position_counter",
"+",
"len",
"(",... | Return the line number and column of a position in a string. | [
"Return",
"the",
"line",
"number",
"and",
"column",
"of",
"a",
"position",
"in",
"a",
"string",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L231-L238 | train | 205,636 |
amperser/proselint | proselint/tools.py | lint | def lint(input_file, debug=False):
"""Run the linter on the input file."""
options = load_options()
if isinstance(input_file, string_types):
text = input_file
else:
text = input_file.read()
# Get the checks.
checks = get_checks(options)
# Apply all the checks.
errors = []
for check in checks:
result = check(text)
for error in result:
(start, end, check, message, replacements) = error
(line, column) = line_and_column(text, start)
if not is_quoted(start, text):
errors += [(check, message, line, column, start, end,
end - start, "warning", replacements)]
if len(errors) > options["max_errors"]:
break
# Sort the errors by line and column number.
errors = sorted(errors[:options["max_errors"]], key=lambda e: (e[2], e[3]))
return errors | python | def lint(input_file, debug=False):
"""Run the linter on the input file."""
options = load_options()
if isinstance(input_file, string_types):
text = input_file
else:
text = input_file.read()
# Get the checks.
checks = get_checks(options)
# Apply all the checks.
errors = []
for check in checks:
result = check(text)
for error in result:
(start, end, check, message, replacements) = error
(line, column) = line_and_column(text, start)
if not is_quoted(start, text):
errors += [(check, message, line, column, start, end,
end - start, "warning", replacements)]
if len(errors) > options["max_errors"]:
break
# Sort the errors by line and column number.
errors = sorted(errors[:options["max_errors"]], key=lambda e: (e[2], e[3]))
return errors | [
"def",
"lint",
"(",
"input_file",
",",
"debug",
"=",
"False",
")",
":",
"options",
"=",
"load_options",
"(",
")",
"if",
"isinstance",
"(",
"input_file",
",",
"string_types",
")",
":",
"text",
"=",
"input_file",
"else",
":",
"text",
"=",
"input_file",
"."... | Run the linter on the input file. | [
"Run",
"the",
"linter",
"on",
"the",
"input",
"file",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L241-L272 | train | 205,637 |
amperser/proselint | proselint/tools.py | assert_error | def assert_error(text, check, n=1):
"""Assert that text has n errors of type check."""
assert_error.description = "No {} error for '{}'".format(check, text)
assert(check in [error[0] for error in lint(text)]) | python | def assert_error(text, check, n=1):
"""Assert that text has n errors of type check."""
assert_error.description = "No {} error for '{}'".format(check, text)
assert(check in [error[0] for error in lint(text)]) | [
"def",
"assert_error",
"(",
"text",
",",
"check",
",",
"n",
"=",
"1",
")",
":",
"assert_error",
".",
"description",
"=",
"\"No {} error for '{}'\"",
".",
"format",
"(",
"check",
",",
"text",
")",
"assert",
"(",
"check",
"in",
"[",
"error",
"[",
"0",
"]... | Assert that text has n errors of type check. | [
"Assert",
"that",
"text",
"has",
"n",
"errors",
"of",
"type",
"check",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L275-L278 | train | 205,638 |
amperser/proselint | proselint/tools.py | consistency_check | def consistency_check(text, word_pairs, err, msg, offset=0):
"""Build a consistency checker for the given word_pairs."""
errors = []
msg = " ".join(msg.split())
for w in word_pairs:
matches = [
[m for m in re.finditer(w[0], text)],
[m for m in re.finditer(w[1], text)]
]
if len(matches[0]) > 0 and len(matches[1]) > 0:
idx_minority = len(matches[0]) > len(matches[1])
for m in matches[idx_minority]:
errors.append((
m.start() + offset,
m.end() + offset,
err,
msg.format(w[~idx_minority], m.group(0)),
w[~idx_minority]))
return errors | python | def consistency_check(text, word_pairs, err, msg, offset=0):
"""Build a consistency checker for the given word_pairs."""
errors = []
msg = " ".join(msg.split())
for w in word_pairs:
matches = [
[m for m in re.finditer(w[0], text)],
[m for m in re.finditer(w[1], text)]
]
if len(matches[0]) > 0 and len(matches[1]) > 0:
idx_minority = len(matches[0]) > len(matches[1])
for m in matches[idx_minority]:
errors.append((
m.start() + offset,
m.end() + offset,
err,
msg.format(w[~idx_minority], m.group(0)),
w[~idx_minority]))
return errors | [
"def",
"consistency_check",
"(",
"text",
",",
"word_pairs",
",",
"err",
",",
"msg",
",",
"offset",
"=",
"0",
")",
":",
"errors",
"=",
"[",
"]",
"msg",
"=",
"\" \"",
".",
"join",
"(",
"msg",
".",
"split",
"(",
")",
")",
"for",
"w",
"in",
"word_pai... | Build a consistency checker for the given word_pairs. | [
"Build",
"a",
"consistency",
"checker",
"for",
"the",
"given",
"word_pairs",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L281-L305 | train | 205,639 |
amperser/proselint | proselint/tools.py | preferred_forms_check | def preferred_forms_check(text, list, err, msg, ignore_case=True, offset=0,
max_errors=float("inf")):
"""Build a checker that suggests the preferred form."""
if ignore_case:
flags = re.IGNORECASE
else:
flags = 0
msg = " ".join(msg.split())
errors = []
regex = u"[\W^]{}[\W$]"
for p in list:
for r in p[1]:
for m in re.finditer(regex.format(r), text, flags=flags):
txt = m.group(0).strip()
errors.append((
m.start() + 1 + offset,
m.end() + offset,
err,
msg.format(p[0], txt),
p[0]))
errors = truncate_to_max(errors, max_errors)
return errors | python | def preferred_forms_check(text, list, err, msg, ignore_case=True, offset=0,
max_errors=float("inf")):
"""Build a checker that suggests the preferred form."""
if ignore_case:
flags = re.IGNORECASE
else:
flags = 0
msg = " ".join(msg.split())
errors = []
regex = u"[\W^]{}[\W$]"
for p in list:
for r in p[1]:
for m in re.finditer(regex.format(r), text, flags=flags):
txt = m.group(0).strip()
errors.append((
m.start() + 1 + offset,
m.end() + offset,
err,
msg.format(p[0], txt),
p[0]))
errors = truncate_to_max(errors, max_errors)
return errors | [
"def",
"preferred_forms_check",
"(",
"text",
",",
"list",
",",
"err",
",",
"msg",
",",
"ignore_case",
"=",
"True",
",",
"offset",
"=",
"0",
",",
"max_errors",
"=",
"float",
"(",
"\"inf\"",
")",
")",
":",
"if",
"ignore_case",
":",
"flags",
"=",
"re",
... | Build a checker that suggests the preferred form. | [
"Build",
"a",
"checker",
"that",
"suggests",
"the",
"preferred",
"form",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L308-L333 | train | 205,640 |
amperser/proselint | proselint/tools.py | existence_check | def existence_check(text, list, err, msg, ignore_case=True,
str=False, max_errors=float("inf"), offset=0,
require_padding=True, dotall=False,
excluded_topics=None, join=False):
"""Build a checker that blacklists certain words."""
flags = 0
msg = " ".join(msg.split())
if ignore_case:
flags = flags | re.IGNORECASE
if str:
flags = flags | re.UNICODE
if dotall:
flags = flags | re.DOTALL
if require_padding:
regex = u"(?:^|\W){}[\W$]"
else:
regex = u"{}"
errors = []
# If the topic of the text is in the excluded list, return immediately.
if excluded_topics:
tps = topics(text)
if any([t in excluded_topics for t in tps]):
return errors
rx = "|".join(regex.format(w) for w in list)
for m in re.finditer(rx, text, flags=flags):
txt = m.group(0).strip()
errors.append((
m.start() + 1 + offset,
m.end() + offset,
err,
msg.format(txt),
None))
errors = truncate_to_max(errors, max_errors)
return errors | python | def existence_check(text, list, err, msg, ignore_case=True,
str=False, max_errors=float("inf"), offset=0,
require_padding=True, dotall=False,
excluded_topics=None, join=False):
"""Build a checker that blacklists certain words."""
flags = 0
msg = " ".join(msg.split())
if ignore_case:
flags = flags | re.IGNORECASE
if str:
flags = flags | re.UNICODE
if dotall:
flags = flags | re.DOTALL
if require_padding:
regex = u"(?:^|\W){}[\W$]"
else:
regex = u"{}"
errors = []
# If the topic of the text is in the excluded list, return immediately.
if excluded_topics:
tps = topics(text)
if any([t in excluded_topics for t in tps]):
return errors
rx = "|".join(regex.format(w) for w in list)
for m in re.finditer(rx, text, flags=flags):
txt = m.group(0).strip()
errors.append((
m.start() + 1 + offset,
m.end() + offset,
err,
msg.format(txt),
None))
errors = truncate_to_max(errors, max_errors)
return errors | [
"def",
"existence_check",
"(",
"text",
",",
"list",
",",
"err",
",",
"msg",
",",
"ignore_case",
"=",
"True",
",",
"str",
"=",
"False",
",",
"max_errors",
"=",
"float",
"(",
"\"inf\"",
")",
",",
"offset",
"=",
"0",
",",
"require_padding",
"=",
"True",
... | Build a checker that blacklists certain words. | [
"Build",
"a",
"checker",
"that",
"blacklists",
"certain",
"words",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L336-L379 | train | 205,641 |
amperser/proselint | proselint/tools.py | truncate_to_max | def truncate_to_max(errors, max_errors):
"""If max_errors was specified, truncate the list of errors.
Give the total number of times that the error was found elsewhere.
"""
if len(errors) > max_errors:
start1, end1, err1, msg1, replacements = errors[0]
if len(errors) == (max_errors + 1):
msg1 += " Found once elsewhere."
else:
msg1 += " Found {} times elsewhere.".format(len(errors))
errors = errors[1:max_errors]
errors = [(start1, end1, err1, msg1, replacements)] + errors
return errors | python | def truncate_to_max(errors, max_errors):
"""If max_errors was specified, truncate the list of errors.
Give the total number of times that the error was found elsewhere.
"""
if len(errors) > max_errors:
start1, end1, err1, msg1, replacements = errors[0]
if len(errors) == (max_errors + 1):
msg1 += " Found once elsewhere."
else:
msg1 += " Found {} times elsewhere.".format(len(errors))
errors = errors[1:max_errors]
errors = [(start1, end1, err1, msg1, replacements)] + errors
return errors | [
"def",
"truncate_to_max",
"(",
"errors",
",",
"max_errors",
")",
":",
"if",
"len",
"(",
"errors",
")",
">",
"max_errors",
":",
"start1",
",",
"end1",
",",
"err1",
",",
"msg1",
",",
"replacements",
"=",
"errors",
"[",
"0",
"]",
"if",
"len",
"(",
"erro... | If max_errors was specified, truncate the list of errors.
Give the total number of times that the error was found elsewhere. | [
"If",
"max_errors",
"was",
"specified",
"truncate",
"the",
"list",
"of",
"errors",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L382-L398 | train | 205,642 |
amperser/proselint | proselint/tools.py | detector_50_Cent | def detector_50_Cent(text):
"""Determine whether 50 Cent is a topic."""
keywords = [
"50 Cent",
"rap",
"hip hop",
"Curtis James Jackson III",
"Curtis Jackson",
"Eminem",
"Dre",
"Get Rich or Die Tryin'",
"G-Unit",
"Street King Immortal",
"In da Club",
"Interscope",
]
num_keywords = sum(word in text for word in keywords)
return ("50 Cent", float(num_keywords > 2)) | python | def detector_50_Cent(text):
"""Determine whether 50 Cent is a topic."""
keywords = [
"50 Cent",
"rap",
"hip hop",
"Curtis James Jackson III",
"Curtis Jackson",
"Eminem",
"Dre",
"Get Rich or Die Tryin'",
"G-Unit",
"Street King Immortal",
"In da Club",
"Interscope",
]
num_keywords = sum(word in text for word in keywords)
return ("50 Cent", float(num_keywords > 2)) | [
"def",
"detector_50_Cent",
"(",
"text",
")",
":",
"keywords",
"=",
"[",
"\"50 Cent\"",
",",
"\"rap\"",
",",
"\"hip hop\"",
",",
"\"Curtis James Jackson III\"",
",",
"\"Curtis Jackson\"",
",",
"\"Eminem\"",
",",
"\"Dre\"",
",",
"\"Get Rich or Die Tryin'\"",
",",
"\"G... | Determine whether 50 Cent is a topic. | [
"Determine",
"whether",
"50",
"Cent",
"is",
"a",
"topic",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L446-L463 | train | 205,643 |
amperser/proselint | proselint/tools.py | topics | def topics(text):
"""Return a list of topics."""
detectors = [
detector_50_Cent
]
ts = []
for detector in detectors:
ts.append(detector(text))
return [t[0] for t in ts if t[1] > 0.95] | python | def topics(text):
"""Return a list of topics."""
detectors = [
detector_50_Cent
]
ts = []
for detector in detectors:
ts.append(detector(text))
return [t[0] for t in ts if t[1] > 0.95] | [
"def",
"topics",
"(",
"text",
")",
":",
"detectors",
"=",
"[",
"detector_50_Cent",
"]",
"ts",
"=",
"[",
"]",
"for",
"detector",
"in",
"detectors",
":",
"ts",
".",
"append",
"(",
"detector",
"(",
"text",
")",
")",
"return",
"[",
"t",
"[",
"0",
"]",
... | Return a list of topics. | [
"Return",
"a",
"list",
"of",
"topics",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/tools.py#L466-L475 | train | 205,644 |
amperser/proselint | proselint/checks/typography/symbols.py | check_ellipsis | def check_ellipsis(text):
"""Use an ellipsis instead of three dots."""
err = "typography.symbols.ellipsis"
msg = u"'...' is an approximation, use the ellipsis symbol '…'."
regex = "\.\.\."
return existence_check(text, [regex], err, msg, max_errors=3,
require_padding=False, offset=0) | python | def check_ellipsis(text):
"""Use an ellipsis instead of three dots."""
err = "typography.symbols.ellipsis"
msg = u"'...' is an approximation, use the ellipsis symbol '…'."
regex = "\.\.\."
return existence_check(text, [regex], err, msg, max_errors=3,
require_padding=False, offset=0) | [
"def",
"check_ellipsis",
"(",
"text",
")",
":",
"err",
"=",
"\"typography.symbols.ellipsis\"",
"msg",
"=",
"u\"'...' is an approximation, use the ellipsis symbol '…'.\"",
"regex",
"=",
"\"\\.\\.\\.\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",
"]",
",... | Use an ellipsis instead of three dots. | [
"Use",
"an",
"ellipsis",
"instead",
"of",
"three",
"dots",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/typography/symbols.py#L12-L19 | train | 205,645 |
amperser/proselint | proselint/checks/typography/symbols.py | check_sentence_spacing | def check_sentence_spacing(text):
"""Use no more than two spaces after a period."""
err = "typography.symbols.sentence_spacing"
msg = u"More than two spaces after the period; use 1 or 2."
regex = "\. {3}"
return existence_check(
text, [regex], err, msg, max_errors=3, require_padding=False) | python | def check_sentence_spacing(text):
"""Use no more than two spaces after a period."""
err = "typography.symbols.sentence_spacing"
msg = u"More than two spaces after the period; use 1 or 2."
regex = "\. {3}"
return existence_check(
text, [regex], err, msg, max_errors=3, require_padding=False) | [
"def",
"check_sentence_spacing",
"(",
"text",
")",
":",
"err",
"=",
"\"typography.symbols.sentence_spacing\"",
"msg",
"=",
"u\"More than two spaces after the period; use 1 or 2.\"",
"regex",
"=",
"\"\\. {3}\"",
"return",
"existence_check",
"(",
"text",
",",
"[",
"regex",
... | Use no more than two spaces after a period. | [
"Use",
"no",
"more",
"than",
"two",
"spaces",
"after",
"a",
"period",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/typography/symbols.py#L56-L63 | train | 205,646 |
amperser/proselint | clock.py | check_email | def check_email():
"""Check the mail account and lint new mail."""
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(user, password)
g = gmail.login(user, password)
# Check for unread messages.
unread = g.inbox().mail(unread=True)
# Submit a job to lint each email sent to editor@proselint.com. Record the
# resulting job_ids somewhere (in Redis, I suppose), keyed by a hash of the
# email.
for u in unread:
u.fetch()
signature = (u.fr.decode('utf-8') +
u.subject.decode('utf-8') +
u.body.decode('utf-8'))
hash = hashlib.sha256(signature.encode('utf-8')).hexdigest()
if user_to in u.to or user_to in u.headers.get('Cc', []):
job_id = conn.get(hash)
if not job_id:
# If the email hasn't been sent for processing, send it.
r = requests.post(api_url, data={"text": u.body})
conn.set(hash, r.json()["job_id"])
print("Email {} sent for processing.".format(hash))
else:
# Otherwise, check whether the results are ready, and if so,
# reply with them.
r = requests.get(api_url, params={"job_id": job_id})
if r.json()["status"] == "success":
reply = quoted(u.body)
errors = r.json()['data']['errors']
reply += "\r\n\r\n".join([json.dumps(e) for e in errors])
msg = MIMEMultipart()
msg["From"] = "{} <{}>".format(name, user)
msg["To"] = u.fr
msg["Subject"] = "Re: " + u.subject
if u.headers.get('Message-ID'):
msg.add_header("In-Reply-To", u.headers['Message-ID'])
msg.add_header("References", u.headers['Message-ID'])
body = reply + "\r\n\r\n--\r\n" + tagline + "\r\n" + url
msg.attach(MIMEText(body, "plain"))
text = msg.as_string()
server.sendmail(user, u.fr, text)
# Mark the email as read.
u.read()
u.archive()
print("Email {} has been replied to.".format(hash)) | python | def check_email():
"""Check the mail account and lint new mail."""
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(user, password)
g = gmail.login(user, password)
# Check for unread messages.
unread = g.inbox().mail(unread=True)
# Submit a job to lint each email sent to editor@proselint.com. Record the
# resulting job_ids somewhere (in Redis, I suppose), keyed by a hash of the
# email.
for u in unread:
u.fetch()
signature = (u.fr.decode('utf-8') +
u.subject.decode('utf-8') +
u.body.decode('utf-8'))
hash = hashlib.sha256(signature.encode('utf-8')).hexdigest()
if user_to in u.to or user_to in u.headers.get('Cc', []):
job_id = conn.get(hash)
if not job_id:
# If the email hasn't been sent for processing, send it.
r = requests.post(api_url, data={"text": u.body})
conn.set(hash, r.json()["job_id"])
print("Email {} sent for processing.".format(hash))
else:
# Otherwise, check whether the results are ready, and if so,
# reply with them.
r = requests.get(api_url, params={"job_id": job_id})
if r.json()["status"] == "success":
reply = quoted(u.body)
errors = r.json()['data']['errors']
reply += "\r\n\r\n".join([json.dumps(e) for e in errors])
msg = MIMEMultipart()
msg["From"] = "{} <{}>".format(name, user)
msg["To"] = u.fr
msg["Subject"] = "Re: " + u.subject
if u.headers.get('Message-ID'):
msg.add_header("In-Reply-To", u.headers['Message-ID'])
msg.add_header("References", u.headers['Message-ID'])
body = reply + "\r\n\r\n--\r\n" + tagline + "\r\n" + url
msg.attach(MIMEText(body, "plain"))
text = msg.as_string()
server.sendmail(user, u.fr, text)
# Mark the email as read.
u.read()
u.archive()
print("Email {} has been replied to.".format(hash)) | [
"def",
"check_email",
"(",
")",
":",
"server",
"=",
"smtplib",
".",
"SMTP",
"(",
"\"smtp.gmail.com\"",
",",
"587",
")",
"server",
".",
"ehlo",
"(",
")",
"server",
".",
"starttls",
"(",
")",
"server",
".",
"ehlo",
"(",
")",
"server",
".",
"login",
"("... | Check the mail account and lint new mail. | [
"Check",
"the",
"mail",
"account",
"and",
"lint",
"new",
"mail",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/clock.py#L36-L102 | train | 205,647 |
amperser/proselint | proselint/checks/mixed_metaphors/misc.py | check_bottleneck | def check_bottleneck(text):
"""Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61
"""
err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [
"biggest bottleneck",
"big bottleneck",
"large bottleneck",
"largest bottleneck",
"world-wide bottleneck",
"huge bottleneck",
"massive bottleneck",
]
return existence_check(text, list, err, msg, max_errors=1) | python | def check_bottleneck(text):
"""Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61
"""
err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [
"biggest bottleneck",
"big bottleneck",
"large bottleneck",
"largest bottleneck",
"world-wide bottleneck",
"huge bottleneck",
"massive bottleneck",
]
return existence_check(text, list, err, msg, max_errors=1) | [
"def",
"check_bottleneck",
"(",
"text",
")",
":",
"err",
"=",
"\"mixed_metaphors.misc.bottleneck\"",
"msg",
"=",
"u\"Mixed metaphor — bottles with big necks are easy to pass through.\"",
"list",
"=",
"[",
"\"biggest bottleneck\"",
",",
"\"big bottleneck\"",
",",
"\"large bottle... | Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61 | [
"Avoid",
"mixing",
"metaphors",
"about",
"bottles",
"and",
"their",
"necks",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/mixed_metaphors/misc.py#L9-L27 | train | 205,648 |
amperser/proselint | proselint/checks/mixed_metaphors/misc.py | check_misc | def check_misc(text):
"""Avoid mixing metaphors.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = "mixed_metaphors.misc.misc"
msg = u"Mixed metaphor. Try '{}'."
preferences = [
["cream rises to the top", ["cream rises to the crop"]],
["fasten your seatbelts", ["button your seatbelts"]],
["a minute to decompress", ["a minute to decompose"]],
["sharpest tool in the shed", ["sharpest marble in the (shed|box)"]],
["not rocket science", ["not rocket surgery"]],
]
return preferred_forms_check(text, preferences, err, msg) | python | def check_misc(text):
"""Avoid mixing metaphors.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = "mixed_metaphors.misc.misc"
msg = u"Mixed metaphor. Try '{}'."
preferences = [
["cream rises to the top", ["cream rises to the crop"]],
["fasten your seatbelts", ["button your seatbelts"]],
["a minute to decompress", ["a minute to decompose"]],
["sharpest tool in the shed", ["sharpest marble in the (shed|box)"]],
["not rocket science", ["not rocket surgery"]],
]
return preferred_forms_check(text, preferences, err, msg) | [
"def",
"check_misc",
"(",
"text",
")",
":",
"err",
"=",
"\"mixed_metaphors.misc.misc\"",
"msg",
"=",
"u\"Mixed metaphor. Try '{}'.\"",
"preferences",
"=",
"[",
"[",
"\"cream rises to the top\"",
",",
"[",
"\"cream rises to the crop\"",
"]",
"]",
",",
"[",
"\"fasten yo... | Avoid mixing metaphors.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY | [
"Avoid",
"mixing",
"metaphors",
"."
] | cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2 | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/mixed_metaphors/misc.py#L31-L49 | train | 205,649 |
tonybaloney/wily | wily/archivers/git.py | GitArchiver.checkout | def checkout(self, revision, options):
"""
Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict``
"""
rev = revision.key
self.repo.git.checkout(rev) | python | def checkout(self, revision, options):
"""
Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict``
"""
rev = revision.key
self.repo.git.checkout(rev) | [
"def",
"checkout",
"(",
"self",
",",
"revision",
",",
"options",
")",
":",
"rev",
"=",
"revision",
".",
"key",
"self",
".",
"repo",
".",
"git",
".",
"checkout",
"(",
"rev",
")"
] | Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict`` | [
"Checkout",
"a",
"specific",
"revision",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/archivers/git.py#L87-L98 | train | 205,650 |
tonybaloney/wily | wily/config.py | generate_cache_path | def generate_cache_path(path):
"""
Generate a reusable path to cache results.
Will use the --path of the target and hash into
a 9-character directory within the HOME folder.
:return: The cache path
:rtype: ``str``
"""
logger.debug(f"Generating cache for {path}")
sha = hashlib.sha1(str(path).encode()).hexdigest()[:9]
HOME = pathlib.Path.home()
cache_path = str(HOME / ".wily" / sha)
logger.debug(f"Cache path is {cache_path}")
return cache_path | python | def generate_cache_path(path):
"""
Generate a reusable path to cache results.
Will use the --path of the target and hash into
a 9-character directory within the HOME folder.
:return: The cache path
:rtype: ``str``
"""
logger.debug(f"Generating cache for {path}")
sha = hashlib.sha1(str(path).encode()).hexdigest()[:9]
HOME = pathlib.Path.home()
cache_path = str(HOME / ".wily" / sha)
logger.debug(f"Cache path is {cache_path}")
return cache_path | [
"def",
"generate_cache_path",
"(",
"path",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Generating cache for {path}\"",
")",
"sha",
"=",
"hashlib",
".",
"sha1",
"(",
"str",
"(",
"path",
")",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
... | Generate a reusable path to cache results.
Will use the --path of the target and hash into
a 9-character directory within the HOME folder.
:return: The cache path
:rtype: ``str`` | [
"Generate",
"a",
"reusable",
"path",
"to",
"cache",
"results",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/config.py#L23-L38 | train | 205,651 |
tonybaloney/wily | wily/config.py | load | def load(config_path=DEFAULT_CONFIG_PATH):
"""
Load config file and set values to defaults where no present.
:return: The configuration ``WilyConfig``
:rtype: :class:`wily.config.WilyConfig`
"""
if not pathlib.Path(config_path).exists():
logger.debug(f"Could not locate {config_path}, using default config.")
return DEFAULT_CONFIG
config = configparser.ConfigParser(default_section=DEFAULT_CONFIG_SECTION)
config.read(config_path)
operators = config.get(
section=DEFAULT_CONFIG_SECTION, option="operators", fallback=DEFAULT_OPERATORS
)
archiver = config.get(
section=DEFAULT_CONFIG_SECTION, option="archiver", fallback=DEFAULT_ARCHIVER
)
path = config.get(section=DEFAULT_CONFIG_SECTION, option="path", fallback=".")
max_revisions = int(
config.get(
section=DEFAULT_CONFIG_SECTION,
option="max_revisions",
fallback=DEFAULT_MAX_REVISIONS,
)
)
return WilyConfig(
operators=operators, archiver=archiver, path=path, max_revisions=max_revisions
) | python | def load(config_path=DEFAULT_CONFIG_PATH):
"""
Load config file and set values to defaults where no present.
:return: The configuration ``WilyConfig``
:rtype: :class:`wily.config.WilyConfig`
"""
if not pathlib.Path(config_path).exists():
logger.debug(f"Could not locate {config_path}, using default config.")
return DEFAULT_CONFIG
config = configparser.ConfigParser(default_section=DEFAULT_CONFIG_SECTION)
config.read(config_path)
operators = config.get(
section=DEFAULT_CONFIG_SECTION, option="operators", fallback=DEFAULT_OPERATORS
)
archiver = config.get(
section=DEFAULT_CONFIG_SECTION, option="archiver", fallback=DEFAULT_ARCHIVER
)
path = config.get(section=DEFAULT_CONFIG_SECTION, option="path", fallback=".")
max_revisions = int(
config.get(
section=DEFAULT_CONFIG_SECTION,
option="max_revisions",
fallback=DEFAULT_MAX_REVISIONS,
)
)
return WilyConfig(
operators=operators, archiver=archiver, path=path, max_revisions=max_revisions
) | [
"def",
"load",
"(",
"config_path",
"=",
"DEFAULT_CONFIG_PATH",
")",
":",
"if",
"not",
"pathlib",
".",
"Path",
"(",
"config_path",
")",
".",
"exists",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Could not locate {config_path}, using default config.\"",
")",
"... | Load config file and set values to defaults where no present.
:return: The configuration ``WilyConfig``
:rtype: :class:`wily.config.WilyConfig` | [
"Load",
"config",
"file",
"and",
"set",
"values",
"to",
"defaults",
"where",
"no",
"present",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/config.py#L112-L143 | train | 205,652 |
tonybaloney/wily | wily/__main__.py | cli | def cli(ctx, debug, config, path, cache):
"""
\U0001F98A Inspect and search through the complexity of your source code.
To get started, run setup:
$ wily setup
To reindex any changes in your source code:
$ wily build <src>
Then explore basic metrics with:
$ wily report <file>
You can also graph specific metrics in a browser with:
$ wily graph <file> <metric>
"""
ctx.ensure_object(dict)
ctx.obj["DEBUG"] = debug
if debug:
logger.setLevel("DEBUG")
else:
logger.setLevel("INFO")
ctx.obj["CONFIG"] = load_config(config)
if path:
logger.debug(f"Fixing path to {path}")
ctx.obj["CONFIG"].path = path
if cache:
logger.debug(f"Fixing cache to {cache}")
ctx.obj["CONFIG"].cache_path = cache
logger.debug(f"Loaded configuration from {config}") | python | def cli(ctx, debug, config, path, cache):
"""
\U0001F98A Inspect and search through the complexity of your source code.
To get started, run setup:
$ wily setup
To reindex any changes in your source code:
$ wily build <src>
Then explore basic metrics with:
$ wily report <file>
You can also graph specific metrics in a browser with:
$ wily graph <file> <metric>
"""
ctx.ensure_object(dict)
ctx.obj["DEBUG"] = debug
if debug:
logger.setLevel("DEBUG")
else:
logger.setLevel("INFO")
ctx.obj["CONFIG"] = load_config(config)
if path:
logger.debug(f"Fixing path to {path}")
ctx.obj["CONFIG"].path = path
if cache:
logger.debug(f"Fixing cache to {cache}")
ctx.obj["CONFIG"].cache_path = cache
logger.debug(f"Loaded configuration from {config}") | [
"def",
"cli",
"(",
"ctx",
",",
"debug",
",",
"config",
",",
"path",
",",
"cache",
")",
":",
"ctx",
".",
"ensure_object",
"(",
"dict",
")",
"ctx",
".",
"obj",
"[",
"\"DEBUG\"",
"]",
"=",
"debug",
"if",
"debug",
":",
"logger",
".",
"setLevel",
"(",
... | \U0001F98A Inspect and search through the complexity of your source code.
To get started, run setup:
$ wily setup
To reindex any changes in your source code:
$ wily build <src>
Then explore basic metrics with:
$ wily report <file>
You can also graph specific metrics in a browser with:
$ wily graph <file> <metric> | [
"\\",
"U0001F98A",
"Inspect",
"and",
"search",
"through",
"the",
"complexity",
"of",
"your",
"source",
"code",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L47-L81 | train | 205,653 |
tonybaloney/wily | wily/__main__.py | build | def build(ctx, max_revisions, targets, operators, archiver):
"""Build the wily cache."""
config = ctx.obj["CONFIG"]
from wily.commands.build import build
if max_revisions:
logger.debug(f"Fixing revisions to {max_revisions}")
config.max_revisions = max_revisions
if operators:
logger.debug(f"Fixing operators to {operators}")
config.operators = operators.strip().split(",")
if archiver:
logger.debug(f"Fixing archiver to {archiver}")
config.archiver = archiver
if targets:
logger.debug(f"Fixing targets to {targets}")
config.targets = targets
build(
config=config,
archiver=resolve_archiver(config.archiver),
operators=resolve_operators(config.operators),
)
logger.info(
"Completed building wily history, run `wily report <file>` or `wily index` to see more."
) | python | def build(ctx, max_revisions, targets, operators, archiver):
"""Build the wily cache."""
config = ctx.obj["CONFIG"]
from wily.commands.build import build
if max_revisions:
logger.debug(f"Fixing revisions to {max_revisions}")
config.max_revisions = max_revisions
if operators:
logger.debug(f"Fixing operators to {operators}")
config.operators = operators.strip().split(",")
if archiver:
logger.debug(f"Fixing archiver to {archiver}")
config.archiver = archiver
if targets:
logger.debug(f"Fixing targets to {targets}")
config.targets = targets
build(
config=config,
archiver=resolve_archiver(config.archiver),
operators=resolve_operators(config.operators),
)
logger.info(
"Completed building wily history, run `wily report <file>` or `wily index` to see more."
) | [
"def",
"build",
"(",
"ctx",
",",
"max_revisions",
",",
"targets",
",",
"operators",
",",
"archiver",
")",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"\"CONFIG\"",
"]",
"from",
"wily",
".",
"commands",
".",
"build",
"import",
"build",
"if",
"max_revision... | Build the wily cache. | [
"Build",
"the",
"wily",
"cache",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L107-L136 | train | 205,654 |
tonybaloney/wily | wily/__main__.py | report | def report(ctx, file, metrics, number, message, format, console_format, output):
"""Show metrics for a given file."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
if not metrics:
metrics = get_default_metrics(config)
logger.info(f"Using default metrics {metrics}")
new_output = Path().cwd()
if output:
new_output = new_output / Path(output)
else:
new_output = new_output / "wily_report" / "index.html"
from wily.commands.report import report
logger.debug(f"Running report on {file} for metric {metrics}")
logger.debug(f"Output format is {format}")
report(
config=config,
path=file,
metrics=metrics,
n=number,
output=new_output,
include_message=message,
format=ReportFormat[format],
console_format=console_format,
) | python | def report(ctx, file, metrics, number, message, format, console_format, output):
"""Show metrics for a given file."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
if not metrics:
metrics = get_default_metrics(config)
logger.info(f"Using default metrics {metrics}")
new_output = Path().cwd()
if output:
new_output = new_output / Path(output)
else:
new_output = new_output / "wily_report" / "index.html"
from wily.commands.report import report
logger.debug(f"Running report on {file} for metric {metrics}")
logger.debug(f"Output format is {format}")
report(
config=config,
path=file,
metrics=metrics,
n=number,
output=new_output,
include_message=message,
format=ReportFormat[format],
console_format=console_format,
) | [
"def",
"report",
"(",
"ctx",
",",
"file",
",",
"metrics",
",",
"number",
",",
"message",
",",
"format",
",",
"console_format",
",",
"output",
")",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"\"CONFIG\"",
"]",
"if",
"not",
"exists",
"(",
"config",
")... | Show metrics for a given file. | [
"Show",
"metrics",
"for",
"a",
"given",
"file",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L175-L206 | train | 205,655 |
tonybaloney/wily | wily/__main__.py | diff | def diff(ctx, files, metrics, all, detail):
"""Show the differences in metrics for each file."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
if not metrics:
metrics = get_default_metrics(config)
logger.info(f"Using default metrics {metrics}")
else:
metrics = metrics.split(",")
logger.info(f"Using specified metrics {metrics}")
from wily.commands.diff import diff
logger.debug(f"Running diff on {files} for metric {metrics}")
diff(
config=config, files=files, metrics=metrics, changes_only=not all, detail=detail
) | python | def diff(ctx, files, metrics, all, detail):
"""Show the differences in metrics for each file."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
if not metrics:
metrics = get_default_metrics(config)
logger.info(f"Using default metrics {metrics}")
else:
metrics = metrics.split(",")
logger.info(f"Using specified metrics {metrics}")
from wily.commands.diff import diff
logger.debug(f"Running diff on {files} for metric {metrics}")
diff(
config=config, files=files, metrics=metrics, changes_only=not all, detail=detail
) | [
"def",
"diff",
"(",
"ctx",
",",
"files",
",",
"metrics",
",",
"all",
",",
"detail",
")",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"\"CONFIG\"",
"]",
"if",
"not",
"exists",
"(",
"config",
")",
":",
"handle_no_cache",
"(",
"ctx",
")",
"if",
"not",... | Show the differences in metrics for each file. | [
"Show",
"the",
"differences",
"in",
"metrics",
"for",
"each",
"file",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L227-L246 | train | 205,656 |
tonybaloney/wily | wily/__main__.py | graph | def graph(ctx, path, metrics, output, x_axis, changes):
"""
Graph a specific metric for a given file, if a path is given, all files within path will be graphed.
Some common examples:
Graph all .py files within src/ for the raw.loc metric
$ wily graph src/ raw.loc
Graph test.py against raw.loc and cyclomatic.complexity metrics
$ wily graph src/test.py raw.loc cyclomatic.complexity
Graph test.py against raw.loc and raw.sloc on the x-axis
$ wily graph src/test.py raw.loc --x-axis raw.sloc
"""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
from wily.commands.graph import graph
logger.debug(f"Running report on {path} for metrics {metrics}")
graph(
config=config,
path=path,
metrics=metrics,
output=output,
x_axis=x_axis,
changes=changes,
) | python | def graph(ctx, path, metrics, output, x_axis, changes):
"""
Graph a specific metric for a given file, if a path is given, all files within path will be graphed.
Some common examples:
Graph all .py files within src/ for the raw.loc metric
$ wily graph src/ raw.loc
Graph test.py against raw.loc and cyclomatic.complexity metrics
$ wily graph src/test.py raw.loc cyclomatic.complexity
Graph test.py against raw.loc and raw.sloc on the x-axis
$ wily graph src/test.py raw.loc --x-axis raw.sloc
"""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
from wily.commands.graph import graph
logger.debug(f"Running report on {path} for metrics {metrics}")
graph(
config=config,
path=path,
metrics=metrics,
output=output,
x_axis=x_axis,
changes=changes,
) | [
"def",
"graph",
"(",
"ctx",
",",
"path",
",",
"metrics",
",",
"output",
",",
"x_axis",
",",
"changes",
")",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"\"CONFIG\"",
"]",
"if",
"not",
"exists",
"(",
"config",
")",
":",
"handle_no_cache",
"(",
"ctx",
... | Graph a specific metric for a given file, if a path is given, all files within path will be graphed.
Some common examples:
Graph all .py files within src/ for the raw.loc metric
$ wily graph src/ raw.loc
Graph test.py against raw.loc and cyclomatic.complexity metrics
$ wily graph src/test.py raw.loc cyclomatic.complexity
Graph test.py against raw.loc and raw.sloc on the x-axis
$ wily graph src/test.py raw.loc --x-axis raw.sloc | [
"Graph",
"a",
"specific",
"metric",
"for",
"a",
"given",
"file",
"if",
"a",
"path",
"is",
"given",
"all",
"files",
"within",
"path",
"will",
"be",
"graphed",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L260-L293 | train | 205,657 |
tonybaloney/wily | wily/__main__.py | list_metrics | def list_metrics(ctx):
"""List the available metrics."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
from wily.commands.list_metrics import list_metrics
list_metrics() | python | def list_metrics(ctx):
"""List the available metrics."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
from wily.commands.list_metrics import list_metrics
list_metrics() | [
"def",
"list_metrics",
"(",
"ctx",
")",
":",
"config",
"=",
"ctx",
".",
"obj",
"[",
"\"CONFIG\"",
"]",
"if",
"not",
"exists",
"(",
"config",
")",
":",
"handle_no_cache",
"(",
"ctx",
")",
"from",
"wily",
".",
"commands",
".",
"list_metrics",
"import",
"... | List the available metrics. | [
"List",
"the",
"available",
"metrics",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L318-L327 | train | 205,658 |
tonybaloney/wily | wily/__main__.py | handle_no_cache | def handle_no_cache(context):
"""Handle lack-of-cache error, prompt user for index process."""
logger.error(
f"Could not locate wily cache, the cache is required to provide insights."
)
p = input("Do you want to run setup and index your project now? [y/N]")
if p.lower() != "y":
exit(1)
else:
revisions = input("How many previous git revisions do you want to index? : ")
revisions = int(revisions)
path = input("Path to your source files; comma-separated for multiple: ")
paths = path.split(",")
context.invoke(
build,
max_revisions=revisions,
targets=paths,
operators=None,
) | python | def handle_no_cache(context):
"""Handle lack-of-cache error, prompt user for index process."""
logger.error(
f"Could not locate wily cache, the cache is required to provide insights."
)
p = input("Do you want to run setup and index your project now? [y/N]")
if p.lower() != "y":
exit(1)
else:
revisions = input("How many previous git revisions do you want to index? : ")
revisions = int(revisions)
path = input("Path to your source files; comma-separated for multiple: ")
paths = path.split(",")
context.invoke(
build,
max_revisions=revisions,
targets=paths,
operators=None,
) | [
"def",
"handle_no_cache",
"(",
"context",
")",
":",
"logger",
".",
"error",
"(",
"f\"Could not locate wily cache, the cache is required to provide insights.\"",
")",
"p",
"=",
"input",
"(",
"\"Do you want to run setup and index your project now? [y/N]\"",
")",
"if",
"p",
".",... | Handle lack-of-cache error, prompt user for index process. | [
"Handle",
"lack",
"-",
"of",
"-",
"cache",
"error",
"prompt",
"user",
"for",
"index",
"process",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/__main__.py#L337-L355 | train | 205,659 |
tonybaloney/wily | wily/commands/graph.py | metric_parts | def metric_parts(metric):
"""Convert a metric name into the operator and metric names."""
operator, met = resolve_metric_as_tuple(metric)
return operator.name, met.name | python | def metric_parts(metric):
"""Convert a metric name into the operator and metric names."""
operator, met = resolve_metric_as_tuple(metric)
return operator.name, met.name | [
"def",
"metric_parts",
"(",
"metric",
")",
":",
"operator",
",",
"met",
"=",
"resolve_metric_as_tuple",
"(",
"metric",
")",
"return",
"operator",
".",
"name",
",",
"met",
".",
"name"
] | Convert a metric name into the operator and metric names. | [
"Convert",
"a",
"metric",
"name",
"into",
"the",
"operator",
"and",
"metric",
"names",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/graph.py#L16-L19 | train | 205,660 |
tonybaloney/wily | wily/commands/graph.py | graph | def graph(config, path, metrics, output=None, x_axis=None, changes=True, text=False):
"""
Graph information about the cache and runtime.
:param config: The configuration.
:type config: :class:`wily.config.WilyConfig`
:param path: The path to the files.
:type path: ``list``
:param metrics: The Y and Z-axis metrics to report on.
:type metrics: ``tuple``
:param output: Save report to specified path instead of opening browser.
:type output: ``str``
"""
logger.debug("Running report command")
data = []
state = State(config)
abs_path = config.path / pathlib.Path(path)
if x_axis is None:
x_axis = "history"
else:
x_operator, x_key = metric_parts(x_axis)
if abs_path.is_dir():
paths = [
p.relative_to(config.path) for p in pathlib.Path(abs_path).glob("**/*.py")
]
else:
paths = [path]
operator, key = metric_parts(metrics[0])
if len(metrics) == 1: # only y-axis
z_axis = None
else:
z_axis = resolve_metric(metrics[1])
z_operator, z_key = metric_parts(metrics[1])
for path in paths:
x = []
y = []
z = []
labels = []
last_y = None
for rev in state.index[state.default_archiver].revisions:
labels.append(f"{rev.revision.author_name} <br>{rev.revision.message}")
try:
val = rev.get(config, state.default_archiver, operator, str(path), key)
if val != last_y or not changes:
y.append(val)
if z_axis:
z.append(
rev.get(
config,
state.default_archiver,
z_operator,
str(path),
z_key,
)
)
if x_axis == "history":
x.append(format_datetime(rev.revision.date))
else:
x.append(
rev.get(
config,
state.default_archiver,
x_operator,
str(path),
x_key,
)
)
last_y = val
except KeyError:
# missing data
pass
# Create traces
trace = go.Scatter(
x=x,
y=y,
mode="lines+markers+text" if text else "lines+markers",
name=f"{path}",
ids=state.index[state.default_archiver].revision_keys,
text=labels,
marker=dict(
size=0 if z_axis is None else z,
color=list(range(len(y))),
# colorscale='Viridis',
),
xcalendar="gregorian",
hoveron="points+fills",
)
data.append(trace)
if output:
filename = output
auto_open = False
else:
filename = "wily-report.html"
auto_open = True
y_metric = resolve_metric(metrics[0])
title = f"{x_axis.capitalize()} of {y_metric.description} for {path}"
plotly.offline.plot(
{
"data": data,
"layout": go.Layout(
title=title,
xaxis={"title": x_axis},
yaxis={"title": y_metric.description},
),
},
auto_open=auto_open,
filename=filename,
) | python | def graph(config, path, metrics, output=None, x_axis=None, changes=True, text=False):
"""
Graph information about the cache and runtime.
:param config: The configuration.
:type config: :class:`wily.config.WilyConfig`
:param path: The path to the files.
:type path: ``list``
:param metrics: The Y and Z-axis metrics to report on.
:type metrics: ``tuple``
:param output: Save report to specified path instead of opening browser.
:type output: ``str``
"""
logger.debug("Running report command")
data = []
state = State(config)
abs_path = config.path / pathlib.Path(path)
if x_axis is None:
x_axis = "history"
else:
x_operator, x_key = metric_parts(x_axis)
if abs_path.is_dir():
paths = [
p.relative_to(config.path) for p in pathlib.Path(abs_path).glob("**/*.py")
]
else:
paths = [path]
operator, key = metric_parts(metrics[0])
if len(metrics) == 1: # only y-axis
z_axis = None
else:
z_axis = resolve_metric(metrics[1])
z_operator, z_key = metric_parts(metrics[1])
for path in paths:
x = []
y = []
z = []
labels = []
last_y = None
for rev in state.index[state.default_archiver].revisions:
labels.append(f"{rev.revision.author_name} <br>{rev.revision.message}")
try:
val = rev.get(config, state.default_archiver, operator, str(path), key)
if val != last_y or not changes:
y.append(val)
if z_axis:
z.append(
rev.get(
config,
state.default_archiver,
z_operator,
str(path),
z_key,
)
)
if x_axis == "history":
x.append(format_datetime(rev.revision.date))
else:
x.append(
rev.get(
config,
state.default_archiver,
x_operator,
str(path),
x_key,
)
)
last_y = val
except KeyError:
# missing data
pass
# Create traces
trace = go.Scatter(
x=x,
y=y,
mode="lines+markers+text" if text else "lines+markers",
name=f"{path}",
ids=state.index[state.default_archiver].revision_keys,
text=labels,
marker=dict(
size=0 if z_axis is None else z,
color=list(range(len(y))),
# colorscale='Viridis',
),
xcalendar="gregorian",
hoveron="points+fills",
)
data.append(trace)
if output:
filename = output
auto_open = False
else:
filename = "wily-report.html"
auto_open = True
y_metric = resolve_metric(metrics[0])
title = f"{x_axis.capitalize()} of {y_metric.description} for {path}"
plotly.offline.plot(
{
"data": data,
"layout": go.Layout(
title=title,
xaxis={"title": x_axis},
yaxis={"title": y_metric.description},
),
},
auto_open=auto_open,
filename=filename,
) | [
"def",
"graph",
"(",
"config",
",",
"path",
",",
"metrics",
",",
"output",
"=",
"None",
",",
"x_axis",
"=",
"None",
",",
"changes",
"=",
"True",
",",
"text",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Running report command\"",
")",
"data"... | Graph information about the cache and runtime.
:param config: The configuration.
:type config: :class:`wily.config.WilyConfig`
:param path: The path to the files.
:type path: ``list``
:param metrics: The Y and Z-axis metrics to report on.
:type metrics: ``tuple``
:param output: Save report to specified path instead of opening browser.
:type output: ``str`` | [
"Graph",
"information",
"about",
"the",
"cache",
"and",
"runtime",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/graph.py#L22-L137 | train | 205,661 |
tonybaloney/wily | wily/commands/list_metrics.py | list_metrics | def list_metrics():
"""List metrics available."""
for name, operator in ALL_OPERATORS.items():
print(f"{name} operator:")
if len(operator.cls.metrics) > 0:
print(
tabulate.tabulate(
headers=("Name", "Description", "Type"),
tabular_data=operator.cls.metrics,
tablefmt=DEFAULT_GRID_STYLE,
)
) | python | def list_metrics():
"""List metrics available."""
for name, operator in ALL_OPERATORS.items():
print(f"{name} operator:")
if len(operator.cls.metrics) > 0:
print(
tabulate.tabulate(
headers=("Name", "Description", "Type"),
tabular_data=operator.cls.metrics,
tablefmt=DEFAULT_GRID_STYLE,
)
) | [
"def",
"list_metrics",
"(",
")",
":",
"for",
"name",
",",
"operator",
"in",
"ALL_OPERATORS",
".",
"items",
"(",
")",
":",
"print",
"(",
"f\"{name} operator:\"",
")",
"if",
"len",
"(",
"operator",
".",
"cls",
".",
"metrics",
")",
">",
"0",
":",
"print",... | List metrics available. | [
"List",
"metrics",
"available",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/list_metrics.py#L12-L23 | train | 205,662 |
tonybaloney/wily | wily/commands/build.py | run_operator | def run_operator(operator, revision, config):
"""Run an operator for the multiprocessing pool. Not called directly."""
instance = operator.cls(config)
logger.debug(f"Running {operator.name} operator on {revision.key}")
return operator.name, instance.run(revision, config) | python | def run_operator(operator, revision, config):
"""Run an operator for the multiprocessing pool. Not called directly."""
instance = operator.cls(config)
logger.debug(f"Running {operator.name} operator on {revision.key}")
return operator.name, instance.run(revision, config) | [
"def",
"run_operator",
"(",
"operator",
",",
"revision",
",",
"config",
")",
":",
"instance",
"=",
"operator",
".",
"cls",
"(",
"config",
")",
"logger",
".",
"debug",
"(",
"f\"Running {operator.name} operator on {revision.key}\"",
")",
"return",
"operator",
".",
... | Run an operator for the multiprocessing pool. Not called directly. | [
"Run",
"an",
"operator",
"for",
"the",
"multiprocessing",
"pool",
".",
"Not",
"called",
"directly",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/build.py#L20-L24 | train | 205,663 |
tonybaloney/wily | wily/commands/build.py | build | def build(config, archiver, operators):
"""
Build the history given a archiver and collection of operators.
:param config: The wily configuration
:type config: :namedtuple:`wily.config.WilyConfig`
:param archiver: The archiver to use
:type archiver: :namedtuple:`wily.archivers.Archiver`
:param operators: The list of operators to execute
:type operators: `list` of :namedtuple:`wily.operators.Operator`
"""
try:
logger.debug(f"Using {archiver.name} archiver module")
archiver = archiver.cls(config)
revisions = archiver.revisions(config.path, config.max_revisions)
except InvalidGitRepositoryError:
# TODO: This logic shouldn't really be here (SoC)
logger.info(f"Defaulting back to the filesystem archiver, not a valid git repo")
archiver = FilesystemArchiver(config)
revisions = archiver.revisions(config.path, config.max_revisions)
except Exception as e:
if hasattr(e, "message"):
logger.error(f"Failed to setup archiver: '{e.message}'")
else:
logger.error(f"Failed to setup archiver: '{type(e)} - {e}'")
exit(1)
state = State(config, archiver=archiver)
# Check for existence of cache, else provision
state.ensure_exists()
index = state.index[archiver.name]
# remove existing revisions from the list
revisions = [revision for revision in revisions if revision not in index]
logger.info(
f"Found {len(revisions)} revisions from '{archiver.name}' archiver in '{config.path}'."
)
_op_desc = ",".join([operator.name for operator in operators])
logger.info(f"Running operators - {_op_desc}")
bar = Bar("Processing", max=len(revisions) * len(operators))
state.operators = operators
try:
with multiprocessing.Pool(processes=len(operators)) as pool:
for revision in revisions:
# Checkout target revision
archiver.checkout(revision, config.checkout_options)
stats = {"operator_data": {}}
# Run each operator as a seperate process
data = pool.starmap(
run_operator,
[(operator, revision, config) for operator in operators],
)
# Map the data back into a dictionary
for operator_name, result in data:
# aggregate values to directories
roots = []
# find all unique directories in the results
for entry in result.keys():
parent = pathlib.Path(entry).parents[0]
if parent not in roots:
roots.append(parent)
for root in roots:
# find all matching entries recursively
aggregates = [
path
for path in result.keys()
if root in pathlib.Path(path).parents
]
result[str(root)] = {}
# aggregate values
for metric in resolve_operator(operator_name).cls.metrics:
func = metric.aggregate
values = [
result[aggregate][metric.name]
for aggregate in aggregates
if aggregate in result
and metric.name in result[aggregate]
]
if len(values) > 0:
result[str(root)][metric.name] = func(values)
stats["operator_data"][operator_name] = result
bar.next()
ir = index.add(revision, operators=operators)
ir.store(config, archiver, stats)
index.save()
bar.finish()
except Exception as e:
logger.error(f"Failed to build cache: '{e}'")
raise e
finally:
# Reset the archive after every run back to the head of the branch
archiver.finish() | python | def build(config, archiver, operators):
"""
Build the history given a archiver and collection of operators.
:param config: The wily configuration
:type config: :namedtuple:`wily.config.WilyConfig`
:param archiver: The archiver to use
:type archiver: :namedtuple:`wily.archivers.Archiver`
:param operators: The list of operators to execute
:type operators: `list` of :namedtuple:`wily.operators.Operator`
"""
try:
logger.debug(f"Using {archiver.name} archiver module")
archiver = archiver.cls(config)
revisions = archiver.revisions(config.path, config.max_revisions)
except InvalidGitRepositoryError:
# TODO: This logic shouldn't really be here (SoC)
logger.info(f"Defaulting back to the filesystem archiver, not a valid git repo")
archiver = FilesystemArchiver(config)
revisions = archiver.revisions(config.path, config.max_revisions)
except Exception as e:
if hasattr(e, "message"):
logger.error(f"Failed to setup archiver: '{e.message}'")
else:
logger.error(f"Failed to setup archiver: '{type(e)} - {e}'")
exit(1)
state = State(config, archiver=archiver)
# Check for existence of cache, else provision
state.ensure_exists()
index = state.index[archiver.name]
# remove existing revisions from the list
revisions = [revision for revision in revisions if revision not in index]
logger.info(
f"Found {len(revisions)} revisions from '{archiver.name}' archiver in '{config.path}'."
)
_op_desc = ",".join([operator.name for operator in operators])
logger.info(f"Running operators - {_op_desc}")
bar = Bar("Processing", max=len(revisions) * len(operators))
state.operators = operators
try:
with multiprocessing.Pool(processes=len(operators)) as pool:
for revision in revisions:
# Checkout target revision
archiver.checkout(revision, config.checkout_options)
stats = {"operator_data": {}}
# Run each operator as a seperate process
data = pool.starmap(
run_operator,
[(operator, revision, config) for operator in operators],
)
# Map the data back into a dictionary
for operator_name, result in data:
# aggregate values to directories
roots = []
# find all unique directories in the results
for entry in result.keys():
parent = pathlib.Path(entry).parents[0]
if parent not in roots:
roots.append(parent)
for root in roots:
# find all matching entries recursively
aggregates = [
path
for path in result.keys()
if root in pathlib.Path(path).parents
]
result[str(root)] = {}
# aggregate values
for metric in resolve_operator(operator_name).cls.metrics:
func = metric.aggregate
values = [
result[aggregate][metric.name]
for aggregate in aggregates
if aggregate in result
and metric.name in result[aggregate]
]
if len(values) > 0:
result[str(root)][metric.name] = func(values)
stats["operator_data"][operator_name] = result
bar.next()
ir = index.add(revision, operators=operators)
ir.store(config, archiver, stats)
index.save()
bar.finish()
except Exception as e:
logger.error(f"Failed to build cache: '{e}'")
raise e
finally:
# Reset the archive after every run back to the head of the branch
archiver.finish() | [
"def",
"build",
"(",
"config",
",",
"archiver",
",",
"operators",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"f\"Using {archiver.name} archiver module\"",
")",
"archiver",
"=",
"archiver",
".",
"cls",
"(",
"config",
")",
"revisions",
"=",
"archiver",
... | Build the history given a archiver and collection of operators.
:param config: The wily configuration
:type config: :namedtuple:`wily.config.WilyConfig`
:param archiver: The archiver to use
:type archiver: :namedtuple:`wily.archivers.Archiver`
:param operators: The list of operators to execute
:type operators: `list` of :namedtuple:`wily.operators.Operator` | [
"Build",
"the",
"history",
"given",
"a",
"archiver",
"and",
"collection",
"of",
"operators",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/commands/build.py#L27-L130 | train | 205,664 |
tonybaloney/wily | wily/state.py | Index.add | def add(self, revision, operators):
"""
Add a revision to the index.
:param revision: The revision.
:type revision: :class:`Revision` or :class:`LazyRevision`
"""
ir = IndexedRevision(
revision=revision, operators=[operator.name for operator in operators]
)
self._revisions[revision.key] = ir
return ir | python | def add(self, revision, operators):
"""
Add a revision to the index.
:param revision: The revision.
:type revision: :class:`Revision` or :class:`LazyRevision`
"""
ir = IndexedRevision(
revision=revision, operators=[operator.name for operator in operators]
)
self._revisions[revision.key] = ir
return ir | [
"def",
"add",
"(",
"self",
",",
"revision",
",",
"operators",
")",
":",
"ir",
"=",
"IndexedRevision",
"(",
"revision",
"=",
"revision",
",",
"operators",
"=",
"[",
"operator",
".",
"name",
"for",
"operator",
"in",
"operators",
"]",
")",
"self",
".",
"_... | Add a revision to the index.
:param revision: The revision.
:type revision: :class:`Revision` or :class:`LazyRevision` | [
"Add",
"a",
"revision",
"to",
"the",
"index",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/state.py#L155-L166 | train | 205,665 |
tonybaloney/wily | wily/state.py | Index.save | def save(self):
"""Save the index data back to the wily cache."""
data = [i.asdict() for i in self._revisions.values()]
logger.debug("Saving data")
cache.store_archiver_index(self.config, self.archiver, data) | python | def save(self):
"""Save the index data back to the wily cache."""
data = [i.asdict() for i in self._revisions.values()]
logger.debug("Saving data")
cache.store_archiver_index(self.config, self.archiver, data) | [
"def",
"save",
"(",
"self",
")",
":",
"data",
"=",
"[",
"i",
".",
"asdict",
"(",
")",
"for",
"i",
"in",
"self",
".",
"_revisions",
".",
"values",
"(",
")",
"]",
"logger",
".",
"debug",
"(",
"\"Saving data\"",
")",
"cache",
".",
"store_archiver_index"... | Save the index data back to the wily cache. | [
"Save",
"the",
"index",
"data",
"back",
"to",
"the",
"wily",
"cache",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/state.py#L168-L172 | train | 205,666 |
tonybaloney/wily | wily/state.py | State.ensure_exists | def ensure_exists(self):
"""Ensure that cache directory exists."""
if not cache.exists(self.config):
logger.debug("Wily cache not found, creating.")
cache.create(self.config)
logger.debug("Created wily cache")
else:
logger.debug(f"Cache {self.config.cache_path} exists") | python | def ensure_exists(self):
"""Ensure that cache directory exists."""
if not cache.exists(self.config):
logger.debug("Wily cache not found, creating.")
cache.create(self.config)
logger.debug("Created wily cache")
else:
logger.debug(f"Cache {self.config.cache_path} exists") | [
"def",
"ensure_exists",
"(",
"self",
")",
":",
"if",
"not",
"cache",
".",
"exists",
"(",
"self",
".",
"config",
")",
":",
"logger",
".",
"debug",
"(",
"\"Wily cache not found, creating.\"",
")",
"cache",
".",
"create",
"(",
"self",
".",
"config",
")",
"l... | Ensure that cache directory exists. | [
"Ensure",
"that",
"cache",
"directory",
"exists",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/state.py#L203-L210 | train | 205,667 |
tonybaloney/wily | wily/decorators.py | add_version | def add_version(f):
"""
Add the version of wily to the help heading.
:param f: function to decorate
:return: decorated function
"""
doc = f.__doc__
f.__doc__ = "Version: " + __version__ + "\n\n" + doc
return f | python | def add_version(f):
"""
Add the version of wily to the help heading.
:param f: function to decorate
:return: decorated function
"""
doc = f.__doc__
f.__doc__ = "Version: " + __version__ + "\n\n" + doc
return f | [
"def",
"add_version",
"(",
"f",
")",
":",
"doc",
"=",
"f",
".",
"__doc__",
"f",
".",
"__doc__",
"=",
"\"Version: \"",
"+",
"__version__",
"+",
"\"\\n\\n\"",
"+",
"doc",
"return",
"f"
] | Add the version of wily to the help heading.
:param f: function to decorate
:return: decorated function | [
"Add",
"the",
"version",
"of",
"wily",
"to",
"the",
"help",
"heading",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/decorators.py#L11-L20 | train | 205,668 |
tonybaloney/wily | wily/operators/__init__.py | resolve_metric_as_tuple | def resolve_metric_as_tuple(metric):
"""
Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric`
"""
if "." in metric:
_, metric = metric.split(".")
r = [
(operator, match) for operator, match in ALL_METRICS if match[0] == metric
]
if not r or len(r) == 0:
raise ValueError(f"Metric {metric} not recognised.")
else:
return r[0] | python | def resolve_metric_as_tuple(metric):
"""
Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric`
"""
if "." in metric:
_, metric = metric.split(".")
r = [
(operator, match) for operator, match in ALL_METRICS if match[0] == metric
]
if not r or len(r) == 0:
raise ValueError(f"Metric {metric} not recognised.")
else:
return r[0] | [
"def",
"resolve_metric_as_tuple",
"(",
"metric",
")",
":",
"if",
"\".\"",
"in",
"metric",
":",
"_",
",",
"metric",
"=",
"metric",
".",
"split",
"(",
"\".\"",
")",
"r",
"=",
"[",
"(",
"operator",
",",
"match",
")",
"for",
"operator",
",",
"match",
"in... | Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric` | [
"Resolve",
"metric",
"key",
"to",
"a",
"given",
"target",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/operators/__init__.py#L170-L188 | train | 205,669 |
tonybaloney/wily | wily/operators/__init__.py | get_metric | def get_metric(revision, operator, path, key):
"""
Get a metric from the cache.
:param revision: The revision id.
:type revision: ``str``
:param operator: The operator name.
:type operator: ``str``
:param path: The path to the file/function
:type path: ``str``
:param key: The key of the data
:type key: ``str``
:return: Data from the cache
:rtype: ``dict``
"""
if ":" in path:
part, entry = path.split(":")
val = revision[operator][part][entry][key]
else:
val = revision[operator][path][key]
return val | python | def get_metric(revision, operator, path, key):
"""
Get a metric from the cache.
:param revision: The revision id.
:type revision: ``str``
:param operator: The operator name.
:type operator: ``str``
:param path: The path to the file/function
:type path: ``str``
:param key: The key of the data
:type key: ``str``
:return: Data from the cache
:rtype: ``dict``
"""
if ":" in path:
part, entry = path.split(":")
val = revision[operator][part][entry][key]
else:
val = revision[operator][path][key]
return val | [
"def",
"get_metric",
"(",
"revision",
",",
"operator",
",",
"path",
",",
"key",
")",
":",
"if",
"\":\"",
"in",
"path",
":",
"part",
",",
"entry",
"=",
"path",
".",
"split",
"(",
"\":\"",
")",
"val",
"=",
"revision",
"[",
"operator",
"]",
"[",
"part... | Get a metric from the cache.
:param revision: The revision id.
:type revision: ``str``
:param operator: The operator name.
:type operator: ``str``
:param path: The path to the file/function
:type path: ``str``
:param key: The key of the data
:type key: ``str``
:return: Data from the cache
:rtype: ``dict`` | [
"Get",
"a",
"metric",
"from",
"the",
"cache",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/operators/__init__.py#L191-L215 | train | 205,670 |
tonybaloney/wily | wily/cache.py | create_index | def create_index(config):
"""Create the root index."""
filename = pathlib.Path(config.cache_path) / "index.json"
index = {"version": __version__}
with open(filename, "w") as out:
out.write(json.dumps(index, indent=2)) | python | def create_index(config):
"""Create the root index."""
filename = pathlib.Path(config.cache_path) / "index.json"
index = {"version": __version__}
with open(filename, "w") as out:
out.write(json.dumps(index, indent=2)) | [
"def",
"create_index",
"(",
"config",
")",
":",
"filename",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"\"index.json\"",
"index",
"=",
"{",
"\"version\"",
":",
"__version__",
"}",
"with",
"open",
"(",
"filename",
",",
"\"w\"",... | Create the root index. | [
"Create",
"the",
"root",
"index",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L52-L57 | train | 205,671 |
tonybaloney/wily | wily/cache.py | create | def create(config):
"""
Create a wily cache.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: The path to the cache
:rtype: ``str``
"""
if exists(config):
logger.debug("Wily cache exists, skipping")
return config.cache_path
logger.debug(f"Creating wily cache {config.cache_path}")
pathlib.Path(config.cache_path).mkdir(parents=True, exist_ok=True)
create_index(config)
return config.cache_path | python | def create(config):
"""
Create a wily cache.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: The path to the cache
:rtype: ``str``
"""
if exists(config):
logger.debug("Wily cache exists, skipping")
return config.cache_path
logger.debug(f"Creating wily cache {config.cache_path}")
pathlib.Path(config.cache_path).mkdir(parents=True, exist_ok=True)
create_index(config)
return config.cache_path | [
"def",
"create",
"(",
"config",
")",
":",
"if",
"exists",
"(",
"config",
")",
":",
"logger",
".",
"debug",
"(",
"\"Wily cache exists, skipping\"",
")",
"return",
"config",
".",
"cache_path",
"logger",
".",
"debug",
"(",
"f\"Creating wily cache {config.cache_path}\... | Create a wily cache.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: The path to the cache
:rtype: ``str`` | [
"Create",
"a",
"wily",
"cache",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L60-L76 | train | 205,672 |
tonybaloney/wily | wily/cache.py | clean | def clean(config):
"""
Delete a wily cache.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
"""
if not exists(config):
logger.debug("Wily cache does not exist, skipping")
return
shutil.rmtree(config.cache_path)
logger.debug("Deleted wily cache") | python | def clean(config):
"""
Delete a wily cache.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
"""
if not exists(config):
logger.debug("Wily cache does not exist, skipping")
return
shutil.rmtree(config.cache_path)
logger.debug("Deleted wily cache") | [
"def",
"clean",
"(",
"config",
")",
":",
"if",
"not",
"exists",
"(",
"config",
")",
":",
"logger",
".",
"debug",
"(",
"\"Wily cache does not exist, skipping\"",
")",
"return",
"shutil",
".",
"rmtree",
"(",
"config",
".",
"cache_path",
")",
"logger",
".",
"... | Delete a wily cache.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig` | [
"Delete",
"a",
"wily",
"cache",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L79-L91 | train | 205,673 |
tonybaloney/wily | wily/cache.py | store | def store(config, archiver, revision, stats):
"""
Store a revision record within an archiver folder.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:param stats: The collected data
:type stats: ``dict``
:return: The absolute path to the created file
:rtype: ``str``
:rtype: `pathlib.Path`
"""
root = pathlib.Path(config.cache_path) / archiver.name
if not root.exists():
logger.debug("Creating wily cache")
root.mkdir()
# fix absolute path references.
if config.path != ".":
for operator, operator_data in list(stats["operator_data"].items()):
if operator_data:
new_operator_data = operator_data.copy()
for k, v in list(operator_data.items()):
new_key = os.path.relpath(str(k), str(config.path))
del new_operator_data[k]
new_operator_data[new_key] = v
del stats["operator_data"][operator]
stats["operator_data"][operator] = new_operator_data
logger.debug(f"Creating {revision.key} output")
filename = root / (revision.key + ".json")
if filename.exists():
raise RuntimeError(f"File {filename} already exists, index may be corrupt.")
with open(filename, "w") as out:
out.write(json.dumps(stats, indent=2))
return filename | python | def store(config, archiver, revision, stats):
"""
Store a revision record within an archiver folder.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:param stats: The collected data
:type stats: ``dict``
:return: The absolute path to the created file
:rtype: ``str``
:rtype: `pathlib.Path`
"""
root = pathlib.Path(config.cache_path) / archiver.name
if not root.exists():
logger.debug("Creating wily cache")
root.mkdir()
# fix absolute path references.
if config.path != ".":
for operator, operator_data in list(stats["operator_data"].items()):
if operator_data:
new_operator_data = operator_data.copy()
for k, v in list(operator_data.items()):
new_key = os.path.relpath(str(k), str(config.path))
del new_operator_data[k]
new_operator_data[new_key] = v
del stats["operator_data"][operator]
stats["operator_data"][operator] = new_operator_data
logger.debug(f"Creating {revision.key} output")
filename = root / (revision.key + ".json")
if filename.exists():
raise RuntimeError(f"File {filename} already exists, index may be corrupt.")
with open(filename, "w") as out:
out.write(json.dumps(stats, indent=2))
return filename | [
"def",
"store",
"(",
"config",
",",
"archiver",
",",
"revision",
",",
"stats",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
".",
"name",
"if",
"not",
"root",
".",
"exists",
"(",
")",
":",
"l... | Store a revision record within an archiver folder.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:param stats: The collected data
:type stats: ``dict``
:return: The absolute path to the created file
:rtype: ``str``
:rtype: `pathlib.Path` | [
"Store",
"a",
"revision",
"record",
"within",
"an",
"archiver",
"folder",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L94-L139 | train | 205,674 |
tonybaloney/wily | wily/cache.py | store_archiver_index | def store_archiver_index(config, archiver, index):
"""
Store an archiver's index record for faster search.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param index: The archiver index record
:type index: ``dict``
:rtype: `pathlib.Path`
"""
root = pathlib.Path(config.cache_path) / archiver.name
if not root.exists():
root.mkdir()
logger.debug("Created archiver directory")
index = sorted(index, key=lambda k: k["date"], reverse=True)
filename = root / "index.json"
with open(filename, "w") as out:
out.write(json.dumps(index, indent=2))
logger.debug(f"Created index output")
return filename | python | def store_archiver_index(config, archiver, index):
"""
Store an archiver's index record for faster search.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param index: The archiver index record
:type index: ``dict``
:rtype: `pathlib.Path`
"""
root = pathlib.Path(config.cache_path) / archiver.name
if not root.exists():
root.mkdir()
logger.debug("Created archiver directory")
index = sorted(index, key=lambda k: k["date"], reverse=True)
filename = root / "index.json"
with open(filename, "w") as out:
out.write(json.dumps(index, indent=2))
logger.debug(f"Created index output")
return filename | [
"def",
"store_archiver_index",
"(",
"config",
",",
"archiver",
",",
"index",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
".",
"name",
"if",
"not",
"root",
".",
"exists",
"(",
")",
":",
"root",
... | Store an archiver's index record for faster search.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param index: The archiver index record
:type index: ``dict``
:rtype: `pathlib.Path` | [
"Store",
"an",
"archiver",
"s",
"index",
"record",
"for",
"faster",
"search",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L142-L169 | train | 205,675 |
tonybaloney/wily | wily/cache.py | list_archivers | def list_archivers(config):
"""
List the names of archivers with data.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: A list of archiver names
:rtype: ``list`` of ``str``
"""
root = pathlib.Path(config.cache_path)
result = []
for name in ALL_ARCHIVERS.keys():
if (root / name).exists():
result.append(name)
return result | python | def list_archivers(config):
"""
List the names of archivers with data.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: A list of archiver names
:rtype: ``list`` of ``str``
"""
root = pathlib.Path(config.cache_path)
result = []
for name in ALL_ARCHIVERS.keys():
if (root / name).exists():
result.append(name)
return result | [
"def",
"list_archivers",
"(",
"config",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"ALL_ARCHIVERS",
".",
"keys",
"(",
")",
":",
"if",
"(",
"root",
"/",
"name",
... | List the names of archivers with data.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: A list of archiver names
:rtype: ``list`` of ``str`` | [
"List",
"the",
"names",
"of",
"archivers",
"with",
"data",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L172-L187 | train | 205,676 |
tonybaloney/wily | wily/cache.py | get_default_metrics | def get_default_metrics(config):
"""
Get the default metrics for a configuration.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: Return the list of default metrics in this index
:rtype: ``list`` of ``str``
"""
archivers = list_archivers(config)
default_metrics = []
for archiver in archivers:
index = get_archiver_index(config, archiver)
if len(index) == 0:
logger.warning("No records found in the index, no metrics available")
return []
operators = index[0]["operators"]
for operator in operators:
o = resolve_operator(operator)
if o.cls.default_metric_index is not None:
metric = o.cls.metrics[o.cls.default_metric_index]
default_metrics.append("{0}.{1}".format(o.cls.name, metric.name))
return default_metrics | python | def get_default_metrics(config):
"""
Get the default metrics for a configuration.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: Return the list of default metrics in this index
:rtype: ``list`` of ``str``
"""
archivers = list_archivers(config)
default_metrics = []
for archiver in archivers:
index = get_archiver_index(config, archiver)
if len(index) == 0:
logger.warning("No records found in the index, no metrics available")
return []
operators = index[0]["operators"]
for operator in operators:
o = resolve_operator(operator)
if o.cls.default_metric_index is not None:
metric = o.cls.metrics[o.cls.default_metric_index]
default_metrics.append("{0}.{1}".format(o.cls.name, metric.name))
return default_metrics | [
"def",
"get_default_metrics",
"(",
"config",
")",
":",
"archivers",
"=",
"list_archivers",
"(",
"config",
")",
"default_metrics",
"=",
"[",
"]",
"for",
"archiver",
"in",
"archivers",
":",
"index",
"=",
"get_archiver_index",
"(",
"config",
",",
"archiver",
")",... | Get the default metrics for a configuration.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:return: Return the list of default metrics in this index
:rtype: ``list`` of ``str`` | [
"Get",
"the",
"default",
"metrics",
"for",
"a",
"configuration",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L190-L216 | train | 205,677 |
tonybaloney/wily | wily/cache.py | has_archiver_index | def has_archiver_index(config, archiver):
"""
Check if this archiver has an index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: the exist
:rtype: ``bool``
"""
root = pathlib.Path(config.cache_path) / archiver / "index.json"
return root.exists() | python | def has_archiver_index(config, archiver):
"""
Check if this archiver has an index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: the exist
:rtype: ``bool``
"""
root = pathlib.Path(config.cache_path) / archiver / "index.json"
return root.exists() | [
"def",
"has_archiver_index",
"(",
"config",
",",
"archiver",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
"/",
"\"index.json\"",
"return",
"root",
".",
"exists",
"(",
")"
] | Check if this archiver has an index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: the exist
:rtype: ``bool`` | [
"Check",
"if",
"this",
"archiver",
"has",
"an",
"index",
"file",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L219-L233 | train | 205,678 |
tonybaloney/wily | wily/cache.py | get_archiver_index | def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: The index data
:rtype: ``dict``
"""
root = pathlib.Path(config.cache_path) / archiver
with (root / "index.json").open("r") as index_f:
index = json.load(index_f)
return index | python | def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: The index data
:rtype: ``dict``
"""
root = pathlib.Path(config.cache_path) / archiver
with (root / "index.json").open("r") as index_f:
index = json.load(index_f)
return index | [
"def",
"get_archiver_index",
"(",
"config",
",",
"archiver",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
"with",
"(",
"root",
"/",
"\"index.json\"",
")",
".",
"open",
"(",
"\"r\"",
")",
"as",
"... | Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: The index data
:rtype: ``dict`` | [
"Get",
"the",
"contents",
"of",
"the",
"archiver",
"index",
"file",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L236-L252 | train | 205,679 |
tonybaloney/wily | wily/cache.py | get | def get(config, archiver, revision):
"""
Get the data for a given revision.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:return: The data record for that revision
:rtype: ``dict``
"""
root = pathlib.Path(config.cache_path) / archiver
# TODO : string escaping!!!
with (root / f"{revision}.json").open("r") as rev_f:
index = json.load(rev_f)
return index | python | def get(config, archiver, revision):
"""
Get the data for a given revision.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:return: The data record for that revision
:rtype: ``dict``
"""
root = pathlib.Path(config.cache_path) / archiver
# TODO : string escaping!!!
with (root / f"{revision}.json").open("r") as rev_f:
index = json.load(rev_f)
return index | [
"def",
"get",
"(",
"config",
",",
"archiver",
",",
"revision",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
"# TODO : string escaping!!!",
"with",
"(",
"root",
"/",
"f\"{revision}.json\"",
")",
".",
... | Get the data for a given revision.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:return: The data record for that revision
:rtype: ``dict`` | [
"Get",
"the",
"data",
"for",
"a",
"given",
"revision",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L255-L275 | train | 205,680 |
tonybaloney/wily | wily/operators/maintainability.py | mode | def mode(data):
"""
Return the modal value of a iterable with discrete values.
If there is more than 1 modal value, arbritrarily return the first top n.
"""
c = Counter(data)
mode, freq = c.most_common(1)[0]
return mode | python | def mode(data):
"""
Return the modal value of a iterable with discrete values.
If there is more than 1 modal value, arbritrarily return the first top n.
"""
c = Counter(data)
mode, freq = c.most_common(1)[0]
return mode | [
"def",
"mode",
"(",
"data",
")",
":",
"c",
"=",
"Counter",
"(",
"data",
")",
"mode",
",",
"freq",
"=",
"c",
".",
"most_common",
"(",
"1",
")",
"[",
"0",
"]",
"return",
"mode"
] | Return the modal value of a iterable with discrete values.
If there is more than 1 modal value, arbritrarily return the first top n. | [
"Return",
"the",
"modal",
"value",
"of",
"a",
"iterable",
"with",
"discrete",
"values",
".",
"If",
"there",
"is",
"more",
"than",
"1",
"modal",
"value",
"arbritrarily",
"return",
"the",
"first",
"top",
"n",
"."
] | bae259354a91b57d56603f0ca7403186f086a84c | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/operators/maintainability.py#L16-L24 | train | 205,681 |
renatopp/liac-arff | arff.py | load | def load(fp, encode_nominal=False, return_type=DENSE):
'''Load a file-like object containing the ARFF document and convert it into
a Python object.
:param fp: a file-like object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
:return: a dictionary.
'''
decoder = ArffDecoder()
return decoder.decode(fp, encode_nominal=encode_nominal,
return_type=return_type) | python | def load(fp, encode_nominal=False, return_type=DENSE):
'''Load a file-like object containing the ARFF document and convert it into
a Python object.
:param fp: a file-like object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
:return: a dictionary.
'''
decoder = ArffDecoder()
return decoder.decode(fp, encode_nominal=encode_nominal,
return_type=return_type) | [
"def",
"load",
"(",
"fp",
",",
"encode_nominal",
"=",
"False",
",",
"return_type",
"=",
"DENSE",
")",
":",
"decoder",
"=",
"ArffDecoder",
"(",
")",
"return",
"decoder",
".",
"decode",
"(",
"fp",
",",
"encode_nominal",
"=",
"encode_nominal",
",",
"return_ty... | Load a file-like object containing the ARFF document and convert it into
a Python object.
:param fp: a file-like object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
:return: a dictionary. | [
"Load",
"a",
"file",
"-",
"like",
"object",
"containing",
"the",
"ARFF",
"document",
"and",
"convert",
"it",
"into",
"a",
"Python",
"object",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L1043-L1059 | train | 205,682 |
renatopp/liac-arff | arff.py | loads | def loads(s, encode_nominal=False, return_type=DENSE):
'''Convert a string instance containing the ARFF document into a Python
object.
:param s: a string object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
:return: a dictionary.
'''
decoder = ArffDecoder()
return decoder.decode(s, encode_nominal=encode_nominal,
return_type=return_type) | python | def loads(s, encode_nominal=False, return_type=DENSE):
'''Convert a string instance containing the ARFF document into a Python
object.
:param s: a string object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
:return: a dictionary.
'''
decoder = ArffDecoder()
return decoder.decode(s, encode_nominal=encode_nominal,
return_type=return_type) | [
"def",
"loads",
"(",
"s",
",",
"encode_nominal",
"=",
"False",
",",
"return_type",
"=",
"DENSE",
")",
":",
"decoder",
"=",
"ArffDecoder",
"(",
")",
"return",
"decoder",
".",
"decode",
"(",
"s",
",",
"encode_nominal",
"=",
"encode_nominal",
",",
"return_typ... | Convert a string instance containing the ARFF document into a Python
object.
:param s: a string object.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
:return: a dictionary. | [
"Convert",
"a",
"string",
"instance",
"containing",
"the",
"ARFF",
"document",
"into",
"a",
"Python",
"object",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L1061-L1077 | train | 205,683 |
renatopp/liac-arff | arff.py | dump | def dump(obj, fp):
'''Serialize an object representing the ARFF document to a given file-like
object.
:param obj: a dictionary.
:param fp: a file-like object.
'''
encoder = ArffEncoder()
generator = encoder.iter_encode(obj)
last_row = next(generator)
for row in generator:
fp.write(last_row + u'\n')
last_row = row
fp.write(last_row)
return fp | python | def dump(obj, fp):
'''Serialize an object representing the ARFF document to a given file-like
object.
:param obj: a dictionary.
:param fp: a file-like object.
'''
encoder = ArffEncoder()
generator = encoder.iter_encode(obj)
last_row = next(generator)
for row in generator:
fp.write(last_row + u'\n')
last_row = row
fp.write(last_row)
return fp | [
"def",
"dump",
"(",
"obj",
",",
"fp",
")",
":",
"encoder",
"=",
"ArffEncoder",
"(",
")",
"generator",
"=",
"encoder",
".",
"iter_encode",
"(",
"obj",
")",
"last_row",
"=",
"next",
"(",
"generator",
")",
"for",
"row",
"in",
"generator",
":",
"fp",
"."... | Serialize an object representing the ARFF document to a given file-like
object.
:param obj: a dictionary.
:param fp: a file-like object. | [
"Serialize",
"an",
"object",
"representing",
"the",
"ARFF",
"document",
"to",
"a",
"given",
"file",
"-",
"like",
"object",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L1079-L1095 | train | 205,684 |
renatopp/liac-arff | arff.py | ArffDecoder._decode | def _decode(self, s, encode_nominal=False, matrix_type=DENSE):
'''Do the job the ``encode``.'''
# Make sure this method is idempotent
self._current_line = 0
# If string, convert to a list of lines
if isinstance(s, basestring):
s = s.strip('\r\n ').replace('\r\n', '\n').split('\n')
# Create the return object
obj = {
u'description': u'',
u'relation': u'',
u'attributes': [],
u'data': []
}
attribute_names = {}
# Create the data helper object
data = _get_data_object_for_decoding(matrix_type)
# Read all lines
STATE = _TK_DESCRIPTION
s = iter(s)
for row in s:
self._current_line += 1
# Ignore empty lines
row = row.strip(' \r\n')
if not row: continue
u_row = row.upper()
# DESCRIPTION -----------------------------------------------------
if u_row.startswith(_TK_DESCRIPTION) and STATE == _TK_DESCRIPTION:
obj['description'] += self._decode_comment(row) + '\n'
# -----------------------------------------------------------------
# RELATION --------------------------------------------------------
elif u_row.startswith(_TK_RELATION):
if STATE != _TK_DESCRIPTION:
raise BadLayout()
STATE = _TK_RELATION
obj['relation'] = self._decode_relation(row)
# -----------------------------------------------------------------
# ATTRIBUTE -------------------------------------------------------
elif u_row.startswith(_TK_ATTRIBUTE):
if STATE != _TK_RELATION and STATE != _TK_ATTRIBUTE:
raise BadLayout()
STATE = _TK_ATTRIBUTE
attr = self._decode_attribute(row)
if attr[0] in attribute_names:
raise BadAttributeName(attr[0], attribute_names[attr[0]])
else:
attribute_names[attr[0]] = self._current_line
obj['attributes'].append(attr)
if isinstance(attr[1], (list, tuple)):
if encode_nominal:
conversor = EncodedNominalConversor(attr[1])
else:
conversor = NominalConversor(attr[1])
else:
CONVERSOR_MAP = {'STRING': unicode,
'INTEGER': lambda x: int(float(x)),
'NUMERIC': float,
'REAL': float}
conversor = CONVERSOR_MAP[attr[1]]
self._conversors.append(conversor)
# -----------------------------------------------------------------
# DATA ------------------------------------------------------------
elif u_row.startswith(_TK_DATA):
if STATE != _TK_ATTRIBUTE:
raise BadLayout()
break
# -----------------------------------------------------------------
# COMMENT ---------------------------------------------------------
elif u_row.startswith(_TK_COMMENT):
pass
# -----------------------------------------------------------------
else:
# Never found @DATA
raise BadLayout()
def stream():
for row in s:
self._current_line += 1
row = row.strip()
# Ignore empty lines and comment lines.
if row and not row.startswith(_TK_COMMENT):
yield row
# Alter the data object
obj['data'] = data.decode_rows(stream(), self._conversors)
if obj['description'].endswith('\n'):
obj['description'] = obj['description'][:-1]
return obj | python | def _decode(self, s, encode_nominal=False, matrix_type=DENSE):
'''Do the job the ``encode``.'''
# Make sure this method is idempotent
self._current_line = 0
# If string, convert to a list of lines
if isinstance(s, basestring):
s = s.strip('\r\n ').replace('\r\n', '\n').split('\n')
# Create the return object
obj = {
u'description': u'',
u'relation': u'',
u'attributes': [],
u'data': []
}
attribute_names = {}
# Create the data helper object
data = _get_data_object_for_decoding(matrix_type)
# Read all lines
STATE = _TK_DESCRIPTION
s = iter(s)
for row in s:
self._current_line += 1
# Ignore empty lines
row = row.strip(' \r\n')
if not row: continue
u_row = row.upper()
# DESCRIPTION -----------------------------------------------------
if u_row.startswith(_TK_DESCRIPTION) and STATE == _TK_DESCRIPTION:
obj['description'] += self._decode_comment(row) + '\n'
# -----------------------------------------------------------------
# RELATION --------------------------------------------------------
elif u_row.startswith(_TK_RELATION):
if STATE != _TK_DESCRIPTION:
raise BadLayout()
STATE = _TK_RELATION
obj['relation'] = self._decode_relation(row)
# -----------------------------------------------------------------
# ATTRIBUTE -------------------------------------------------------
elif u_row.startswith(_TK_ATTRIBUTE):
if STATE != _TK_RELATION and STATE != _TK_ATTRIBUTE:
raise BadLayout()
STATE = _TK_ATTRIBUTE
attr = self._decode_attribute(row)
if attr[0] in attribute_names:
raise BadAttributeName(attr[0], attribute_names[attr[0]])
else:
attribute_names[attr[0]] = self._current_line
obj['attributes'].append(attr)
if isinstance(attr[1], (list, tuple)):
if encode_nominal:
conversor = EncodedNominalConversor(attr[1])
else:
conversor = NominalConversor(attr[1])
else:
CONVERSOR_MAP = {'STRING': unicode,
'INTEGER': lambda x: int(float(x)),
'NUMERIC': float,
'REAL': float}
conversor = CONVERSOR_MAP[attr[1]]
self._conversors.append(conversor)
# -----------------------------------------------------------------
# DATA ------------------------------------------------------------
elif u_row.startswith(_TK_DATA):
if STATE != _TK_ATTRIBUTE:
raise BadLayout()
break
# -----------------------------------------------------------------
# COMMENT ---------------------------------------------------------
elif u_row.startswith(_TK_COMMENT):
pass
# -----------------------------------------------------------------
else:
# Never found @DATA
raise BadLayout()
def stream():
for row in s:
self._current_line += 1
row = row.strip()
# Ignore empty lines and comment lines.
if row and not row.startswith(_TK_COMMENT):
yield row
# Alter the data object
obj['data'] = data.decode_rows(stream(), self._conversors)
if obj['description'].endswith('\n'):
obj['description'] = obj['description'][:-1]
return obj | [
"def",
"_decode",
"(",
"self",
",",
"s",
",",
"encode_nominal",
"=",
"False",
",",
"matrix_type",
"=",
"DENSE",
")",
":",
"# Make sure this method is idempotent",
"self",
".",
"_current_line",
"=",
"0",
"# If string, convert to a list of lines",
"if",
"isinstance",
... | Do the job the ``encode``. | [
"Do",
"the",
"job",
"the",
"encode",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L768-L873 | train | 205,685 |
renatopp/liac-arff | arff.py | ArffDecoder.decode | def decode(self, s, encode_nominal=False, return_type=DENSE):
'''Returns the Python representation of a given ARFF file.
When a file object is passed as an argument, this method reads lines
iteratively, avoiding to load unnecessary information to the memory.
:param s: a string or file object with the ARFF file.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
'''
try:
return self._decode(s, encode_nominal=encode_nominal,
matrix_type=return_type)
except ArffException as e:
e.line = self._current_line
raise e | python | def decode(self, s, encode_nominal=False, return_type=DENSE):
'''Returns the Python representation of a given ARFF file.
When a file object is passed as an argument, this method reads lines
iteratively, avoiding to load unnecessary information to the memory.
:param s: a string or file object with the ARFF file.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_.
'''
try:
return self._decode(s, encode_nominal=encode_nominal,
matrix_type=return_type)
except ArffException as e:
e.line = self._current_line
raise e | [
"def",
"decode",
"(",
"self",
",",
"s",
",",
"encode_nominal",
"=",
"False",
",",
"return_type",
"=",
"DENSE",
")",
":",
"try",
":",
"return",
"self",
".",
"_decode",
"(",
"s",
",",
"encode_nominal",
"=",
"encode_nominal",
",",
"matrix_type",
"=",
"retur... | Returns the Python representation of a given ARFF file.
When a file object is passed as an argument, this method reads lines
iteratively, avoiding to load unnecessary information to the memory.
:param s: a string or file object with the ARFF file.
:param encode_nominal: boolean, if True perform a label encoding
while reading the .arff file.
:param return_type: determines the data structure used to store the
dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
`arff.DENSE_GEN` or `arff.LOD_GEN`.
Consult the sections on `working with sparse data`_ and `loading
progressively`_. | [
"Returns",
"the",
"Python",
"representation",
"of",
"a",
"given",
"ARFF",
"file",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L875-L895 | train | 205,686 |
renatopp/liac-arff | arff.py | ArffEncoder.encode | def encode(self, obj):
'''Encodes a given object to an ARFF file.
:param obj: the object containing the ARFF information.
:return: the ARFF file as an unicode string.
'''
data = [row for row in self.iter_encode(obj)]
return u'\n'.join(data) | python | def encode(self, obj):
'''Encodes a given object to an ARFF file.
:param obj: the object containing the ARFF information.
:return: the ARFF file as an unicode string.
'''
data = [row for row in self.iter_encode(obj)]
return u'\n'.join(data) | [
"def",
"encode",
"(",
"self",
",",
"obj",
")",
":",
"data",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
".",
"iter_encode",
"(",
"obj",
")",
"]",
"return",
"u'\\n'",
".",
"join",
"(",
"data",
")"
] | Encodes a given object to an ARFF file.
:param obj: the object containing the ARFF information.
:return: the ARFF file as an unicode string. | [
"Encodes",
"a",
"given",
"object",
"to",
"an",
"ARFF",
"file",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L968-L976 | train | 205,687 |
renatopp/liac-arff | arff.py | ArffEncoder.iter_encode | def iter_encode(self, obj):
'''The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as unicode strings.
'''
# DESCRIPTION
if obj.get('description', None):
for row in obj['description'].split('\n'):
yield self._encode_comment(row)
# RELATION
if not obj.get('relation'):
raise BadObject('Relation name not found or with invalid value.')
yield self._encode_relation(obj['relation'])
yield u''
# ATTRIBUTES
if not obj.get('attributes'):
raise BadObject('Attributes not found.')
attribute_names = set()
for attr in obj['attributes']:
# Verify for bad object format
if not isinstance(attr, (tuple, list)) or \
len(attr) != 2 or \
not isinstance(attr[0], basestring):
raise BadObject('Invalid attribute declaration "%s"'%str(attr))
if isinstance(attr[1], basestring):
# Verify for invalid types
if attr[1] not in _SIMPLE_TYPES:
raise BadObject('Invalid attribute type "%s"'%str(attr))
# Verify for bad object format
elif not isinstance(attr[1], (tuple, list)):
raise BadObject('Invalid attribute type "%s"'%str(attr))
# Verify attribute name is not used twice
if attr[0] in attribute_names:
raise BadObject('Trying to use attribute name "%s" for the '
'second time.' % str(attr[0]))
else:
attribute_names.add(attr[0])
yield self._encode_attribute(attr[0], attr[1])
yield u''
attributes = obj['attributes']
# DATA
yield _TK_DATA
if 'data' in obj:
data = _get_data_object_for_encoding(obj.get('data'))
for line in data.encode_data(obj.get('data'), attributes):
yield line
yield u'' | python | def iter_encode(self, obj):
'''The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as unicode strings.
'''
# DESCRIPTION
if obj.get('description', None):
for row in obj['description'].split('\n'):
yield self._encode_comment(row)
# RELATION
if not obj.get('relation'):
raise BadObject('Relation name not found or with invalid value.')
yield self._encode_relation(obj['relation'])
yield u''
# ATTRIBUTES
if not obj.get('attributes'):
raise BadObject('Attributes not found.')
attribute_names = set()
for attr in obj['attributes']:
# Verify for bad object format
if not isinstance(attr, (tuple, list)) or \
len(attr) != 2 or \
not isinstance(attr[0], basestring):
raise BadObject('Invalid attribute declaration "%s"'%str(attr))
if isinstance(attr[1], basestring):
# Verify for invalid types
if attr[1] not in _SIMPLE_TYPES:
raise BadObject('Invalid attribute type "%s"'%str(attr))
# Verify for bad object format
elif not isinstance(attr[1], (tuple, list)):
raise BadObject('Invalid attribute type "%s"'%str(attr))
# Verify attribute name is not used twice
if attr[0] in attribute_names:
raise BadObject('Trying to use attribute name "%s" for the '
'second time.' % str(attr[0]))
else:
attribute_names.add(attr[0])
yield self._encode_attribute(attr[0], attr[1])
yield u''
attributes = obj['attributes']
# DATA
yield _TK_DATA
if 'data' in obj:
data = _get_data_object_for_encoding(obj.get('data'))
for line in data.encode_data(obj.get('data'), attributes):
yield line
yield u'' | [
"def",
"iter_encode",
"(",
"self",
",",
"obj",
")",
":",
"# DESCRIPTION",
"if",
"obj",
".",
"get",
"(",
"'description'",
",",
"None",
")",
":",
"for",
"row",
"in",
"obj",
"[",
"'description'",
"]",
".",
"split",
"(",
"'\\n'",
")",
":",
"yield",
"self... | The iterative version of `arff.ArffEncoder.encode`.
This encodes iteratively a given object and return, one-by-one, the
lines of the ARFF file.
:param obj: the object containing the ARFF information.
:return: (yields) the ARFF file as unicode strings. | [
"The",
"iterative",
"version",
"of",
"arff",
".",
"ArffEncoder",
".",
"encode",
"."
] | 6771f4cdd13d0eca74d3ebbaa6290297dd0a381d | https://github.com/renatopp/liac-arff/blob/6771f4cdd13d0eca74d3ebbaa6290297dd0a381d/arff.py#L978-L1038 | train | 205,688 |
rpi-ws281x/rpi-ws281x-python | library/rpi_ws281x/rpi_ws281x.py | PixelStrip.begin | def begin(self):
"""Initialize library, must be called once before other functions are
called.
"""
resp = ws.ws2811_init(self._leds)
if resp != 0:
str_resp = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, str_resp)) | python | def begin(self):
"""Initialize library, must be called once before other functions are
called.
"""
resp = ws.ws2811_init(self._leds)
if resp != 0:
str_resp = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, str_resp)) | [
"def",
"begin",
"(",
"self",
")",
":",
"resp",
"=",
"ws",
".",
"ws2811_init",
"(",
"self",
".",
"_leds",
")",
"if",
"resp",
"!=",
"0",
":",
"str_resp",
"=",
"ws",
".",
"ws2811_get_return_t_str",
"(",
"resp",
")",
"raise",
"RuntimeError",
"(",
"'ws2811_... | Initialize library, must be called once before other functions are
called. | [
"Initialize",
"library",
"must",
"be",
"called",
"once",
"before",
"other",
"functions",
"are",
"called",
"."
] | 4cd940d13eef9abe1111dadc859c197fce2f833b | https://github.com/rpi-ws281x/rpi-ws281x-python/blob/4cd940d13eef9abe1111dadc859c197fce2f833b/library/rpi_ws281x/rpi_ws281x.py#L116-L124 | train | 205,689 |
rpi-ws281x/rpi-ws281x-python | library/rpi_ws281x/rpi_ws281x.py | PixelStrip.show | def show(self):
"""Update the display with the data from the LED buffer."""
resp = ws.ws2811_render(self._leds)
if resp != 0:
str_resp = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, str_resp)) | python | def show(self):
"""Update the display with the data from the LED buffer."""
resp = ws.ws2811_render(self._leds)
if resp != 0:
str_resp = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, str_resp)) | [
"def",
"show",
"(",
"self",
")",
":",
"resp",
"=",
"ws",
".",
"ws2811_render",
"(",
"self",
".",
"_leds",
")",
"if",
"resp",
"!=",
"0",
":",
"str_resp",
"=",
"ws",
".",
"ws2811_get_return_t_str",
"(",
"resp",
")",
"raise",
"RuntimeError",
"(",
"'ws2811... | Update the display with the data from the LED buffer. | [
"Update",
"the",
"display",
"with",
"the",
"data",
"from",
"the",
"LED",
"buffer",
"."
] | 4cd940d13eef9abe1111dadc859c197fce2f833b | https://github.com/rpi-ws281x/rpi-ws281x-python/blob/4cd940d13eef9abe1111dadc859c197fce2f833b/library/rpi_ws281x/rpi_ws281x.py#L126-L131 | train | 205,690 |
itamarst/eliot | eliot/logwriter.py | ThreadedWriter.startService | def startService(self):
"""
Start the writer thread.
"""
Service.startService(self)
self._thread = threading.Thread(target=self._writer)
self._thread.start()
addDestination(self) | python | def startService(self):
"""
Start the writer thread.
"""
Service.startService(self)
self._thread = threading.Thread(target=self._writer)
self._thread.start()
addDestination(self) | [
"def",
"startService",
"(",
"self",
")",
":",
"Service",
".",
"startService",
"(",
"self",
")",
"self",
".",
"_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_writer",
")",
"self",
".",
"_thread",
".",
"start",
"(",
")",
... | Start the writer thread. | [
"Start",
"the",
"writer",
"thread",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/logwriter.py#L57-L64 | train | 205,691 |
itamarst/eliot | eliot/logwriter.py | ThreadedWriter.stopService | def stopService(self):
"""
Stop the writer thread, wait for it to finish.
"""
Service.stopService(self)
removeDestination(self)
self._reactor.callFromThread(self._reactor.stop)
return deferToThreadPool(
self._mainReactor,
self._mainReactor.getThreadPool(), self._thread.join) | python | def stopService(self):
"""
Stop the writer thread, wait for it to finish.
"""
Service.stopService(self)
removeDestination(self)
self._reactor.callFromThread(self._reactor.stop)
return deferToThreadPool(
self._mainReactor,
self._mainReactor.getThreadPool(), self._thread.join) | [
"def",
"stopService",
"(",
"self",
")",
":",
"Service",
".",
"stopService",
"(",
"self",
")",
"removeDestination",
"(",
"self",
")",
"self",
".",
"_reactor",
".",
"callFromThread",
"(",
"self",
".",
"_reactor",
".",
"stop",
")",
"return",
"deferToThreadPool"... | Stop the writer thread, wait for it to finish. | [
"Stop",
"the",
"writer",
"thread",
"wait",
"for",
"it",
"to",
"finish",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/logwriter.py#L66-L75 | train | 205,692 |
itamarst/eliot | eliot/_message.py | Message.write | def write(self, logger=None, action=None):
"""
Write the message to the given logger.
This will additionally include a timestamp, the action context if any,
and any other fields.
Byte field names will be converted to Unicode.
@type logger: L{eliot.ILogger} or C{None} indicating the default one.
@param action: The L{Action} which is the context for this message. If
C{None}, the L{Action} will be deduced from the current call
stack.
"""
if logger is None:
logger = _output._DEFAULT_LOGGER
logged_dict = self._freeze(action=action)
logger.write(logged_dict, self._serializer) | python | def write(self, logger=None, action=None):
"""
Write the message to the given logger.
This will additionally include a timestamp, the action context if any,
and any other fields.
Byte field names will be converted to Unicode.
@type logger: L{eliot.ILogger} or C{None} indicating the default one.
@param action: The L{Action} which is the context for this message. If
C{None}, the L{Action} will be deduced from the current call
stack.
"""
if logger is None:
logger = _output._DEFAULT_LOGGER
logged_dict = self._freeze(action=action)
logger.write(logged_dict, self._serializer) | [
"def",
"write",
"(",
"self",
",",
"logger",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"if",
"logger",
"is",
"None",
":",
"logger",
"=",
"_output",
".",
"_DEFAULT_LOGGER",
"logged_dict",
"=",
"self",
".",
"_freeze",
"(",
"action",
"=",
"action"... | Write the message to the given logger.
This will additionally include a timestamp, the action context if any,
and any other fields.
Byte field names will be converted to Unicode.
@type logger: L{eliot.ILogger} or C{None} indicating the default one.
@param action: The L{Action} which is the context for this message. If
C{None}, the L{Action} will be deduced from the current call
stack. | [
"Write",
"the",
"message",
"to",
"the",
"given",
"logger",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/_message.py#L129-L147 | train | 205,693 |
itamarst/eliot | eliot/dask.py | _add_logging | def _add_logging(dsk, ignore=None):
"""
Add logging to a Dask graph.
@param dsk: The Dask graph.
@return: New Dask graph.
"""
ctx = current_action()
result = {}
# Use topological sort to ensure Eliot actions are in logical order of
# execution in Dask:
keys = toposort(dsk)
# Give each key a string name. Some keys are just aliases to other
# keys, so make sure we have underlying key available. Later on might
# want to shorten them as well.
def simplify(k):
if isinstance(k, str):
return k
return "-".join(str(o) for o in k)
key_names = {}
for key in keys:
value = dsk[key]
if not callable(value) and value in keys:
# It's an alias for another key:
key_names[key] = key_names[value]
else:
key_names[key] = simplify(key)
# 2. Create Eliot child Actions for each key, in topological order:
key_to_action_id = {
key: str(ctx.serialize_task_id(), "utf-8")
for key in keys
}
# 3. Replace function with wrapper that logs appropriate Action:
for key in keys:
func = dsk[key][0]
args = dsk[key][1:]
if not callable(func):
# This key is just an alias for another key, no need to add
# logging:
result[key] = dsk[key]
continue
wrapped_func = _RunWithEliotContext(
task_id=key_to_action_id[key],
func=func,
key=key_names[key],
dependencies=[key_names[k] for k in get_dependencies(dsk, key)],
)
result[key] = (wrapped_func, ) + tuple(args)
assert result.keys() == dsk.keys()
return result | python | def _add_logging(dsk, ignore=None):
"""
Add logging to a Dask graph.
@param dsk: The Dask graph.
@return: New Dask graph.
"""
ctx = current_action()
result = {}
# Use topological sort to ensure Eliot actions are in logical order of
# execution in Dask:
keys = toposort(dsk)
# Give each key a string name. Some keys are just aliases to other
# keys, so make sure we have underlying key available. Later on might
# want to shorten them as well.
def simplify(k):
if isinstance(k, str):
return k
return "-".join(str(o) for o in k)
key_names = {}
for key in keys:
value = dsk[key]
if not callable(value) and value in keys:
# It's an alias for another key:
key_names[key] = key_names[value]
else:
key_names[key] = simplify(key)
# 2. Create Eliot child Actions for each key, in topological order:
key_to_action_id = {
key: str(ctx.serialize_task_id(), "utf-8")
for key in keys
}
# 3. Replace function with wrapper that logs appropriate Action:
for key in keys:
func = dsk[key][0]
args = dsk[key][1:]
if not callable(func):
# This key is just an alias for another key, no need to add
# logging:
result[key] = dsk[key]
continue
wrapped_func = _RunWithEliotContext(
task_id=key_to_action_id[key],
func=func,
key=key_names[key],
dependencies=[key_names[k] for k in get_dependencies(dsk, key)],
)
result[key] = (wrapped_func, ) + tuple(args)
assert result.keys() == dsk.keys()
return result | [
"def",
"_add_logging",
"(",
"dsk",
",",
"ignore",
"=",
"None",
")",
":",
"ctx",
"=",
"current_action",
"(",
")",
"result",
"=",
"{",
"}",
"# Use topological sort to ensure Eliot actions are in logical order of",
"# execution in Dask:",
"keys",
"=",
"toposort",
"(",
... | Add logging to a Dask graph.
@param dsk: The Dask graph.
@return: New Dask graph. | [
"Add",
"logging",
"to",
"a",
"Dask",
"graph",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/dask.py#L79-L135 | train | 205,694 |
itamarst/eliot | eliot/_generators.py | eliot_friendly_generator_function | def eliot_friendly_generator_function(original):
"""
Decorate a generator function so that the Eliot action context is
preserved across ``yield`` expressions.
"""
@wraps(original)
def wrapper(*a, **kw):
# Keep track of whether the next value to deliver to the generator is
# a non-exception or an exception.
ok = True
# Keep track of the next value to deliver to the generator.
value_in = None
# Create the generator with a call to the generator function. This
# happens with whatever Eliot action context happens to be active,
# which is fine and correct and also irrelevant because no code in the
# generator function can run until we call send or throw on it.
gen = original(*a, **kw)
# Initialize the per-generator context to a copy of the current context.
context = copy_context()
while True:
try:
# Whichever way we invoke the generator, we will do it
# with the Eliot action context stack we've saved for it.
# Then the context manager will re-save it and restore the
# "outside" stack for us.
#
# Regarding the support of Twisted's inlineCallbacks-like
# functionality (see eliot.twisted.inline_callbacks):
#
# The invocation may raise the inlineCallbacks internal
# control flow exception _DefGen_Return. It is not wrong to
# just let that propagate upwards here but inlineCallbacks
# does think it is wrong. The behavior triggers a
# DeprecationWarning to try to get us to fix our code. We
# could explicitly handle and re-raise the _DefGen_Return but
# only at the expense of depending on a private Twisted API.
# For now, I'm opting to try to encourage Twisted to fix the
# situation (or at least not worsen it):
# https://twistedmatrix.com/trac/ticket/9590
#
# Alternatively, _DefGen_Return is only required on Python 2.
# When Python 2 support is dropped, this concern can be
# eliminated by always using `return value` instead of
# `returnValue(value)` (and adding the necessary logic to the
# StopIteration handler below).
def go():
if ok:
value_out = gen.send(value_in)
else:
value_out = gen.throw(*value_in)
# We have obtained a value from the generator. In
# giving it to us, it has given up control. Note this
# fact here. Importantly, this is within the
# generator's action context so that we get a good
# indication of where the yield occurred.
#
# This is noisy, enable only for debugging:
if wrapper.debug:
Message.log(message_type=u"yielded")
return value_out
value_out = context.run(go)
except StopIteration:
# When the generator raises this, it is signaling
# completion. Leave the loop.
break
else:
try:
# Pass the generator's result along to whoever is
# driving. Capture the result as the next value to
# send inward.
value_in = yield value_out
except:
# Or capture the exception if that's the flavor of the
# next value. This could possibly include GeneratorExit
# which turns out to be just fine because throwing it into
# the inner generator effectively propagates the close
# (and with the right context!) just as you would want.
# True, the GeneratorExit does get re-throwing out of the
# gen.throw call and hits _the_generator_context's
# contextmanager. But @contextmanager extremely
# conveniently eats it for us! Thanks, @contextmanager!
ok = False
value_in = exc_info()
else:
ok = True
wrapper.debug = False
return wrapper | python | def eliot_friendly_generator_function(original):
"""
Decorate a generator function so that the Eliot action context is
preserved across ``yield`` expressions.
"""
@wraps(original)
def wrapper(*a, **kw):
# Keep track of whether the next value to deliver to the generator is
# a non-exception or an exception.
ok = True
# Keep track of the next value to deliver to the generator.
value_in = None
# Create the generator with a call to the generator function. This
# happens with whatever Eliot action context happens to be active,
# which is fine and correct and also irrelevant because no code in the
# generator function can run until we call send or throw on it.
gen = original(*a, **kw)
# Initialize the per-generator context to a copy of the current context.
context = copy_context()
while True:
try:
# Whichever way we invoke the generator, we will do it
# with the Eliot action context stack we've saved for it.
# Then the context manager will re-save it and restore the
# "outside" stack for us.
#
# Regarding the support of Twisted's inlineCallbacks-like
# functionality (see eliot.twisted.inline_callbacks):
#
# The invocation may raise the inlineCallbacks internal
# control flow exception _DefGen_Return. It is not wrong to
# just let that propagate upwards here but inlineCallbacks
# does think it is wrong. The behavior triggers a
# DeprecationWarning to try to get us to fix our code. We
# could explicitly handle and re-raise the _DefGen_Return but
# only at the expense of depending on a private Twisted API.
# For now, I'm opting to try to encourage Twisted to fix the
# situation (or at least not worsen it):
# https://twistedmatrix.com/trac/ticket/9590
#
# Alternatively, _DefGen_Return is only required on Python 2.
# When Python 2 support is dropped, this concern can be
# eliminated by always using `return value` instead of
# `returnValue(value)` (and adding the necessary logic to the
# StopIteration handler below).
def go():
if ok:
value_out = gen.send(value_in)
else:
value_out = gen.throw(*value_in)
# We have obtained a value from the generator. In
# giving it to us, it has given up control. Note this
# fact here. Importantly, this is within the
# generator's action context so that we get a good
# indication of where the yield occurred.
#
# This is noisy, enable only for debugging:
if wrapper.debug:
Message.log(message_type=u"yielded")
return value_out
value_out = context.run(go)
except StopIteration:
# When the generator raises this, it is signaling
# completion. Leave the loop.
break
else:
try:
# Pass the generator's result along to whoever is
# driving. Capture the result as the next value to
# send inward.
value_in = yield value_out
except:
# Or capture the exception if that's the flavor of the
# next value. This could possibly include GeneratorExit
# which turns out to be just fine because throwing it into
# the inner generator effectively propagates the close
# (and with the right context!) just as you would want.
# True, the GeneratorExit does get re-throwing out of the
# gen.throw call and hits _the_generator_context's
# contextmanager. But @contextmanager extremely
# conveniently eats it for us! Thanks, @contextmanager!
ok = False
value_in = exc_info()
else:
ok = True
wrapper.debug = False
return wrapper | [
"def",
"eliot_friendly_generator_function",
"(",
"original",
")",
":",
"@",
"wraps",
"(",
"original",
")",
"def",
"wrapper",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"# Keep track of whether the next value to deliver to the generator is",
"# a non-exception or an e... | Decorate a generator function so that the Eliot action context is
preserved across ``yield`` expressions. | [
"Decorate",
"a",
"generator",
"function",
"so",
"that",
"the",
"Eliot",
"action",
"context",
"is",
"preserved",
"across",
"yield",
"expressions",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/_generators.py#L46-L137 | train | 205,695 |
itamarst/eliot | eliot/journald.py | sd_journal_send | def sd_journal_send(**kwargs):
"""
Send a message to the journald log.
@param kwargs: Mapping between field names to values, both as bytes.
@raise IOError: If the operation failed.
"""
# The function uses printf formatting, so we need to quote
# percentages.
fields = [
_ffi.new(
"char[]", key.encode("ascii") + b'=' + value.replace(b"%", b"%%"))
for key, value in kwargs.items()]
fields.append(_ffi.NULL)
result = _journald.sd_journal_send(*fields)
if result != 0:
raise IOError(-result, strerror(-result)) | python | def sd_journal_send(**kwargs):
"""
Send a message to the journald log.
@param kwargs: Mapping between field names to values, both as bytes.
@raise IOError: If the operation failed.
"""
# The function uses printf formatting, so we need to quote
# percentages.
fields = [
_ffi.new(
"char[]", key.encode("ascii") + b'=' + value.replace(b"%", b"%%"))
for key, value in kwargs.items()]
fields.append(_ffi.NULL)
result = _journald.sd_journal_send(*fields)
if result != 0:
raise IOError(-result, strerror(-result)) | [
"def",
"sd_journal_send",
"(",
"*",
"*",
"kwargs",
")",
":",
"# The function uses printf formatting, so we need to quote",
"# percentages.",
"fields",
"=",
"[",
"_ffi",
".",
"new",
"(",
"\"char[]\"",
",",
"key",
".",
"encode",
"(",
"\"ascii\"",
")",
"+",
"b'='",
... | Send a message to the journald log.
@param kwargs: Mapping between field names to values, both as bytes.
@raise IOError: If the operation failed. | [
"Send",
"a",
"message",
"to",
"the",
"journald",
"log",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/journald.py#L28-L45 | train | 205,696 |
itamarst/eliot | eliot/twisted.py | inline_callbacks | def inline_callbacks(original, debug=False):
"""
Decorate a function like ``inlineCallbacks`` would but in a more
Eliot-friendly way. Use it just like ``inlineCallbacks`` but where you
want Eliot action contexts to Do The Right Thing inside the decorated
function.
"""
f = eliot_friendly_generator_function(original)
if debug:
f.debug = True
return inlineCallbacks(f) | python | def inline_callbacks(original, debug=False):
"""
Decorate a function like ``inlineCallbacks`` would but in a more
Eliot-friendly way. Use it just like ``inlineCallbacks`` but where you
want Eliot action contexts to Do The Right Thing inside the decorated
function.
"""
f = eliot_friendly_generator_function(original)
if debug:
f.debug = True
return inlineCallbacks(f) | [
"def",
"inline_callbacks",
"(",
"original",
",",
"debug",
"=",
"False",
")",
":",
"f",
"=",
"eliot_friendly_generator_function",
"(",
"original",
")",
"if",
"debug",
":",
"f",
".",
"debug",
"=",
"True",
"return",
"inlineCallbacks",
"(",
"f",
")"
] | Decorate a function like ``inlineCallbacks`` would but in a more
Eliot-friendly way. Use it just like ``inlineCallbacks`` but where you
want Eliot action contexts to Do The Right Thing inside the decorated
function. | [
"Decorate",
"a",
"function",
"like",
"inlineCallbacks",
"would",
"but",
"in",
"a",
"more",
"Eliot",
"-",
"friendly",
"way",
".",
"Use",
"it",
"just",
"like",
"inlineCallbacks",
"but",
"where",
"you",
"want",
"Eliot",
"action",
"contexts",
"to",
"Do",
"The",
... | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/twisted.py#L252-L262 | train | 205,697 |
itamarst/eliot | eliot/twisted.py | DeferredContext.addCallbacks | def addCallbacks(
self,
callback,
errback=None,
callbackArgs=None,
callbackKeywords=None,
errbackArgs=None,
errbackKeywords=None
):
"""
Add a pair of callbacks that will be run in the context of an eliot
action.
@return: C{self}
@rtype: L{DeferredContext}
@raises AlreadyFinished: L{DeferredContext.addActionFinish} has been
called. This indicates a programmer error.
"""
if self._finishAdded:
raise AlreadyFinished()
if errback is None:
errback = _passthrough
def callbackWithContext(*args, **kwargs):
return self._action.run(callback, *args, **kwargs)
def errbackWithContext(*args, **kwargs):
return self._action.run(errback, *args, **kwargs)
self.result.addCallbacks(
callbackWithContext, errbackWithContext, callbackArgs,
callbackKeywords, errbackArgs, errbackKeywords)
return self | python | def addCallbacks(
self,
callback,
errback=None,
callbackArgs=None,
callbackKeywords=None,
errbackArgs=None,
errbackKeywords=None
):
"""
Add a pair of callbacks that will be run in the context of an eliot
action.
@return: C{self}
@rtype: L{DeferredContext}
@raises AlreadyFinished: L{DeferredContext.addActionFinish} has been
called. This indicates a programmer error.
"""
if self._finishAdded:
raise AlreadyFinished()
if errback is None:
errback = _passthrough
def callbackWithContext(*args, **kwargs):
return self._action.run(callback, *args, **kwargs)
def errbackWithContext(*args, **kwargs):
return self._action.run(errback, *args, **kwargs)
self.result.addCallbacks(
callbackWithContext, errbackWithContext, callbackArgs,
callbackKeywords, errbackArgs, errbackKeywords)
return self | [
"def",
"addCallbacks",
"(",
"self",
",",
"callback",
",",
"errback",
"=",
"None",
",",
"callbackArgs",
"=",
"None",
",",
"callbackKeywords",
"=",
"None",
",",
"errbackArgs",
"=",
"None",
",",
"errbackKeywords",
"=",
"None",
")",
":",
"if",
"self",
".",
"... | Add a pair of callbacks that will be run in the context of an eliot
action.
@return: C{self}
@rtype: L{DeferredContext}
@raises AlreadyFinished: L{DeferredContext.addActionFinish} has been
called. This indicates a programmer error. | [
"Add",
"a",
"pair",
"of",
"callbacks",
"that",
"will",
"be",
"run",
"in",
"the",
"context",
"of",
"an",
"eliot",
"action",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/twisted.py#L67-L101 | train | 205,698 |
itamarst/eliot | eliot/twisted.py | DeferredContext.addCallback | def addCallback(self, callback, *args, **kw):
"""
Add a success callback that will be run in the context of an eliot
action.
@return: C{self}
@rtype: L{DeferredContext}
@raises AlreadyFinished: L{DeferredContext.addActionFinish} has been
called. This indicates a programmer error.
"""
return self.addCallbacks(
callback, _passthrough, callbackArgs=args, callbackKeywords=kw) | python | def addCallback(self, callback, *args, **kw):
"""
Add a success callback that will be run in the context of an eliot
action.
@return: C{self}
@rtype: L{DeferredContext}
@raises AlreadyFinished: L{DeferredContext.addActionFinish} has been
called. This indicates a programmer error.
"""
return self.addCallbacks(
callback, _passthrough, callbackArgs=args, callbackKeywords=kw) | [
"def",
"addCallback",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"addCallbacks",
"(",
"callback",
",",
"_passthrough",
",",
"callbackArgs",
"=",
"args",
",",
"callbackKeywords",
"=",
"kw",
")"
] | Add a success callback that will be run in the context of an eliot
action.
@return: C{self}
@rtype: L{DeferredContext}
@raises AlreadyFinished: L{DeferredContext.addActionFinish} has been
called. This indicates a programmer error. | [
"Add",
"a",
"success",
"callback",
"that",
"will",
"be",
"run",
"in",
"the",
"context",
"of",
"an",
"eliot",
"action",
"."
] | c03c96520c5492fadfc438b4b0f6336e2785ba2d | https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/twisted.py#L103-L115 | train | 205,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.