repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pivotal-energy-solutions/django-datatable-view | datatableview/views/base.py | DatatableJSONResponseMixin.get_json_response_object | def get_json_response_object(self, datatable):
"""
Returns the JSON-compatible dictionary that will be serialized for an AJAX response.
The value names are in the form "s~" for strings, "i~" for integers, and "a~" for arrays,
if you're unfamiliar with the old C-style jargon used in data... | python | def get_json_response_object(self, datatable):
"""
Returns the JSON-compatible dictionary that will be serialized for an AJAX response.
The value names are in the form "s~" for strings, "i~" for integers, and "a~" for arrays,
if you're unfamiliar with the old C-style jargon used in data... | [
"def",
"get_json_response_object",
"(",
"self",
",",
"datatable",
")",
":",
"# Ensure the object list is calculated.",
"# Calling get_records() will do this implicitly, but we want simultaneous access to the",
"# 'total_initial_record_count', and 'unpaged_record_count' values.",
"datatable",
... | Returns the JSON-compatible dictionary that will be serialized for an AJAX response.
The value names are in the form "s~" for strings, "i~" for integers, and "a~" for arrays,
if you're unfamiliar with the old C-style jargon used in dataTables.js. "aa~" means
"array of arrays". In some instanc... | [
"Returns",
"the",
"JSON",
"-",
"compatible",
"dictionary",
"that",
"will",
"be",
"serialized",
"for",
"an",
"AJAX",
"response",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/base.py#L28-L55 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/base.py | DatatableJSONResponseMixin.serialize_to_json | def serialize_to_json(self, response_data):
""" Returns the JSON string for the compiled data object. """
indent = None
if settings.DEBUG:
indent = 4
# Serialize to JSON with Django's encoder: Adds date/time, decimal,
# and UUID support.
return json.dumps(re... | python | def serialize_to_json(self, response_data):
""" Returns the JSON string for the compiled data object. """
indent = None
if settings.DEBUG:
indent = 4
# Serialize to JSON with Django's encoder: Adds date/time, decimal,
# and UUID support.
return json.dumps(re... | [
"def",
"serialize_to_json",
"(",
"self",
",",
"response_data",
")",
":",
"indent",
"=",
"None",
"if",
"settings",
".",
"DEBUG",
":",
"indent",
"=",
"4",
"# Serialize to JSON with Django's encoder: Adds date/time, decimal,",
"# and UUID support.",
"return",
"json",
".",
... | Returns the JSON string for the compiled data object. | [
"Returns",
"the",
"JSON",
"string",
"for",
"the",
"compiled",
"data",
"object",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/base.py#L57-L66 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/base.py | DatatableMixin.get_ajax | def get_ajax(self, request, *args, **kwargs):
""" Called when accessed via AJAX on the request method specified by the Datatable. """
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data),
con... | python | def get_ajax(self, request, *args, **kwargs):
""" Called when accessed via AJAX on the request method specified by the Datatable. """
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data),
con... | [
"def",
"get_ajax",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response_data",
"=",
"self",
".",
"get_json_response_object",
"(",
"self",
".",
"_datatable",
")",
"response",
"=",
"HttpResponse",
"(",
"self",
".",
"s... | Called when accessed via AJAX on the request method specified by the Datatable. | [
"Called",
"when",
"accessed",
"via",
"AJAX",
"on",
"the",
"request",
"method",
"specified",
"by",
"the",
"Datatable",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/base.py#L79-L86 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/base.py | MultipleDatatableMixin.get_active_ajax_datatable | def get_active_ajax_datatable(self):
""" Returns a single datatable according to the hint GET variable from an AJAX request. """
data = getattr(self.request, self.request.method)
datatables_dict = self.get_datatables(only=data['datatable'])
return list(datatables_dict.values())[0] | python | def get_active_ajax_datatable(self):
""" Returns a single datatable according to the hint GET variable from an AJAX request. """
data = getattr(self.request, self.request.method)
datatables_dict = self.get_datatables(only=data['datatable'])
return list(datatables_dict.values())[0] | [
"def",
"get_active_ajax_datatable",
"(",
"self",
")",
":",
"data",
"=",
"getattr",
"(",
"self",
".",
"request",
",",
"self",
".",
"request",
".",
"method",
")",
"datatables_dict",
"=",
"self",
".",
"get_datatables",
"(",
"only",
"=",
"data",
"[",
"'datatab... | Returns a single datatable according to the hint GET variable from an AJAX request. | [
"Returns",
"a",
"single",
"datatable",
"according",
"to",
"the",
"hint",
"GET",
"variable",
"from",
"an",
"AJAX",
"request",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/base.py#L199-L203 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/base.py | MultipleDatatableMixin.get_datatables | def get_datatables(self, only=None):
""" Returns a dict of the datatables served by this view. """
if not hasattr(self, '_datatables'):
self._datatables = {}
datatable_classes = self.get_datatable_classes()
for name, datatable_class in datatable_classes.items():
... | python | def get_datatables(self, only=None):
""" Returns a dict of the datatables served by this view. """
if not hasattr(self, '_datatables'):
self._datatables = {}
datatable_classes = self.get_datatable_classes()
for name, datatable_class in datatable_classes.items():
... | [
"def",
"get_datatables",
"(",
"self",
",",
"only",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_datatables'",
")",
":",
"self",
".",
"_datatables",
"=",
"{",
"}",
"datatable_classes",
"=",
"self",
".",
"get_datatable_classes",
"(",
... | Returns a dict of the datatables served by this view. | [
"Returns",
"a",
"dict",
"of",
"the",
"datatables",
"served",
"by",
"this",
"view",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/base.py#L205-L246 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/base.py | MultipleDatatableMixin.get_default_datatable_kwargs | def get_default_datatable_kwargs(self, **kwargs):
"""
Builds the default set of kwargs for initializing a Datatable class. Note that by default
the MultipleDatatableMixin does not support any configuration via the view's class
attributes, and instead relies completely on the Datatable c... | python | def get_default_datatable_kwargs(self, **kwargs):
"""
Builds the default set of kwargs for initializing a Datatable class. Note that by default
the MultipleDatatableMixin does not support any configuration via the view's class
attributes, and instead relies completely on the Datatable c... | [
"def",
"get_default_datatable_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'view'",
"]",
"=",
"self",
"# This is provided by default, but if the view is instantiated outside of the request cycle",
"# (such as for the purposes of embedding that view's dat... | Builds the default set of kwargs for initializing a Datatable class. Note that by default
the MultipleDatatableMixin does not support any configuration via the view's class
attributes, and instead relies completely on the Datatable class itself to declare its
configuration details. | [
"Builds",
"the",
"default",
"set",
"of",
"kwargs",
"for",
"initializing",
"a",
"Datatable",
"class",
".",
"Note",
"that",
"by",
"default",
"the",
"MultipleDatatableMixin",
"does",
"not",
"support",
"any",
"configuration",
"via",
"the",
"view",
"s",
"class",
"a... | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/base.py#L254-L274 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/columns.py | get_column_for_modelfield | def get_column_for_modelfield(model_field):
""" Return the built-in Column class for a model field class. """
# If the field points to another model, we want to get the pk field of that other model and use
# that as the real field. It is possible that a ForeignKey points to a model with table
# inheri... | python | def get_column_for_modelfield(model_field):
""" Return the built-in Column class for a model field class. """
# If the field points to another model, we want to get the pk field of that other model and use
# that as the real field. It is possible that a ForeignKey points to a model with table
# inheri... | [
"def",
"get_column_for_modelfield",
"(",
"model_field",
")",
":",
"# If the field points to another model, we want to get the pk field of that other model and use",
"# that as the real field. It is possible that a ForeignKey points to a model with table",
"# inheritance, however, so we need to trav... | Return the built-in Column class for a model field class. | [
"Return",
"the",
"built",
"-",
"in",
"Column",
"class",
"for",
"a",
"model",
"field",
"class",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/columns.py#L52-L63 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/columns.py | CompoundColumn.get_source_value | def get_source_value(self, obj, source, **kwargs):
"""
Treat ``field`` as a nested sub-Column instance, which explicitly stands in as the object
to which term coercions and the query type lookup are delegated.
"""
result = []
for sub_source in self.expand_source(source):
... | python | def get_source_value(self, obj, source, **kwargs):
"""
Treat ``field`` as a nested sub-Column instance, which explicitly stands in as the object
to which term coercions and the query type lookup are delegated.
"""
result = []
for sub_source in self.expand_source(source):
... | [
"def",
"get_source_value",
"(",
"self",
",",
"obj",
",",
"source",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"sub_source",
"in",
"self",
".",
"expand_source",
"(",
"source",
")",
":",
"# Call super() to get default logic, but send it t... | Treat ``field`` as a nested sub-Column instance, which explicitly stands in as the object
to which term coercions and the query type lookup are delegated. | [
"Treat",
"field",
"as",
"a",
"nested",
"sub",
"-",
"Column",
"instance",
"which",
"explicitly",
"stands",
"in",
"as",
"the",
"object",
"to",
"which",
"term",
"coercions",
"and",
"the",
"query",
"type",
"lookup",
"are",
"delegated",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/columns.py#L544-L554 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/columns.py | CompoundColumn._get_flat_db_sources | def _get_flat_db_sources(self, model):
""" Return a flattened representation of the individual ``sources`` lists. """
sources = []
for source in self.sources:
for sub_source in self.expand_source(source):
target_field = self.resolve_source(model, sub_source)
... | python | def _get_flat_db_sources(self, model):
""" Return a flattened representation of the individual ``sources`` lists. """
sources = []
for source in self.sources:
for sub_source in self.expand_source(source):
target_field = self.resolve_source(model, sub_source)
... | [
"def",
"_get_flat_db_sources",
"(",
"self",
",",
"model",
")",
":",
"sources",
"=",
"[",
"]",
"for",
"source",
"in",
"self",
".",
"sources",
":",
"for",
"sub_source",
"in",
"self",
".",
"expand_source",
"(",
"source",
")",
":",
"target_field",
"=",
"self... | Return a flattened representation of the individual ``sources`` lists. | [
"Return",
"a",
"flattened",
"representation",
"of",
"the",
"individual",
"sources",
"lists",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/columns.py#L562-L570 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/columns.py | CompoundColumn.get_source_handler | def get_source_handler(self, model, source):
""" Allow the nested Column source to be its own handler. """
if isinstance(source, Column):
return source
# Generate a generic handler for the source
modelfield = resolve_orm_path(model, source)
column_class = get_column_... | python | def get_source_handler(self, model, source):
""" Allow the nested Column source to be its own handler. """
if isinstance(source, Column):
return source
# Generate a generic handler for the source
modelfield = resolve_orm_path(model, source)
column_class = get_column_... | [
"def",
"get_source_handler",
"(",
"self",
",",
"model",
",",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"Column",
")",
":",
"return",
"source",
"# Generate a generic handler for the source",
"modelfield",
"=",
"resolve_orm_path",
"(",
"model",
","... | Allow the nested Column source to be its own handler. | [
"Allow",
"the",
"nested",
"Column",
"source",
"to",
"be",
"its",
"own",
"handler",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/columns.py#L572-L580 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.dispatch | def dispatch(self, request, *args, **kwargs):
""" Introduces the ``ensure_csrf_cookie`` decorator and handles xeditable choices ajax. """
if request.GET.get(self.xeditable_fieldname_param):
return self.get_ajax_xeditable_choices(request, *args, **kwargs)
return super(XEditableMixin, ... | python | def dispatch(self, request, *args, **kwargs):
""" Introduces the ``ensure_csrf_cookie`` decorator and handles xeditable choices ajax. """
if request.GET.get(self.xeditable_fieldname_param):
return self.get_ajax_xeditable_choices(request, *args, **kwargs)
return super(XEditableMixin, ... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"GET",
".",
"get",
"(",
"self",
".",
"xeditable_fieldname_param",
")",
":",
"return",
"self",
".",
"get_ajax_xeditable_choices",
"(... | Introduces the ``ensure_csrf_cookie`` decorator and handles xeditable choices ajax. | [
"Introduces",
"the",
"ensure_csrf_cookie",
"decorator",
"and",
"handles",
"xeditable",
"choices",
"ajax",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L26-L30 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.get_ajax_xeditable_choices | def get_ajax_xeditable_choices(self, request, *args, **kwargs):
""" AJAX GET handler for xeditable queries asking for field choice lists. """
field_name = request.GET.get(self.xeditable_fieldname_param)
if not field_name:
return HttpResponseBadRequest("Field name must be given")
... | python | def get_ajax_xeditable_choices(self, request, *args, **kwargs):
""" AJAX GET handler for xeditable queries asking for field choice lists. """
field_name = request.GET.get(self.xeditable_fieldname_param)
if not field_name:
return HttpResponseBadRequest("Field name must be given")
... | [
"def",
"get_ajax_xeditable_choices",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"field_name",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"self",
".",
"xeditable_fieldname_param",
")",
"if",
"not",
"field_name",
":",... | AJAX GET handler for xeditable queries asking for field choice lists. | [
"AJAX",
"GET",
"handler",
"for",
"xeditable",
"queries",
"asking",
"for",
"field",
"choice",
"lists",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L32-L62 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.post | def post(self, request, *args, **kwargs):
"""
Builds a dynamic form that targets only the field in question, and saves the modification.
"""
self.object_list = None
form = self.get_xeditable_form(self.get_xeditable_form_class())
if form.is_valid():
obj = self.... | python | def post(self, request, *args, **kwargs):
"""
Builds a dynamic form that targets only the field in question, and saves the modification.
"""
self.object_list = None
form = self.get_xeditable_form(self.get_xeditable_form_class())
if form.is_valid():
obj = self.... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"object_list",
"=",
"None",
"form",
"=",
"self",
".",
"get_xeditable_form",
"(",
"self",
".",
"get_xeditable_form_class",
"(",
")",
")",
"if",... | Builds a dynamic form that targets only the field in question, and saves the modification. | [
"Builds",
"a",
"dynamic",
"form",
"that",
"targets",
"only",
"the",
"field",
"in",
"question",
"and",
"saves",
"the",
"modification",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L64-L85 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.get_xeditable_form_kwargs | def get_xeditable_form_kwargs(self):
""" Returns a dict of keyword arguments to be sent to the xeditable form class. """
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.reques... | python | def get_xeditable_form_kwargs(self):
""" Returns a dict of keyword arguments to be sent to the xeditable form class. """
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.reques... | [
"def",
"get_xeditable_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'model'",
":",
"self",
".",
"get_queryset",
"(",
")",
".",
"model",
",",
"}",
"if",
"self",
".",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PUT'",
")",
":",
"k... | Returns a dict of keyword arguments to be sent to the xeditable form class. | [
"Returns",
"a",
"dict",
"of",
"keyword",
"arguments",
"to",
"be",
"sent",
"to",
"the",
"xeditable",
"form",
"class",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L91-L100 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.get_update_object | def get_update_object(self, form):
"""
Retrieves the target object based on the update form's ``pk`` and the table's queryset.
"""
pk = form.cleaned_data['pk']
queryset = self.get_queryset()
try:
obj = queryset.get(pk=pk)
except queryset.model.DoesNotE... | python | def get_update_object(self, form):
"""
Retrieves the target object based on the update form's ``pk`` and the table's queryset.
"""
pk = form.cleaned_data['pk']
queryset = self.get_queryset()
try:
obj = queryset.get(pk=pk)
except queryset.model.DoesNotE... | [
"def",
"get_update_object",
"(",
"self",
",",
"form",
")",
":",
"pk",
"=",
"form",
".",
"cleaned_data",
"[",
"'pk'",
"]",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"try",
":",
"obj",
"=",
"queryset",
".",
"get",
"(",
"pk",
"=",
"pk",
... | Retrieves the target object based on the update form's ``pk`` and the table's queryset. | [
"Retrieves",
"the",
"target",
"object",
"based",
"on",
"the",
"update",
"form",
"s",
"pk",
"and",
"the",
"table",
"s",
"queryset",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L106-L117 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.update_object | def update_object(self, form, obj):
""" Saves the new value to the target object. """
field_name = form.cleaned_data['name']
value = form.cleaned_data['value']
setattr(obj, field_name, value)
save_kwargs = {}
if CAN_UPDATE_FIELDS:
save_kwargs['update_fields'] ... | python | def update_object(self, form, obj):
""" Saves the new value to the target object. """
field_name = form.cleaned_data['name']
value = form.cleaned_data['value']
setattr(obj, field_name, value)
save_kwargs = {}
if CAN_UPDATE_FIELDS:
save_kwargs['update_fields'] ... | [
"def",
"update_object",
"(",
"self",
",",
"form",
",",
"obj",
")",
":",
"field_name",
"=",
"form",
".",
"cleaned_data",
"[",
"'name'",
"]",
"value",
"=",
"form",
".",
"cleaned_data",
"[",
"'value'",
"]",
"setattr",
"(",
"obj",
",",
"field_name",
",",
"... | Saves the new value to the target object. | [
"Saves",
"the",
"new",
"value",
"to",
"the",
"target",
"object",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L119-L132 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | XEditableMixin.get_field_choices | def get_field_choices(self, field, field_name):
"""
Returns the valid choices for ``field``. The ``field_name`` argument is given for
convenience.
"""
if self.request.GET.get('select2'):
names = ['id', 'text']
else:
names = ['value', 'text']
... | python | def get_field_choices(self, field, field_name):
"""
Returns the valid choices for ``field``. The ``field_name`` argument is given for
convenience.
"""
if self.request.GET.get('select2'):
names = ['id', 'text']
else:
names = ['value', 'text']
... | [
"def",
"get_field_choices",
"(",
"self",
",",
"field",
",",
"field_name",
")",
":",
"if",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'select2'",
")",
":",
"names",
"=",
"[",
"'id'",
",",
"'text'",
"]",
"else",
":",
"names",
"=",
"[",
"'v... | Returns the valid choices for ``field``. The ``field_name`` argument is given for
convenience. | [
"Returns",
"the",
"valid",
"choices",
"for",
"field",
".",
"The",
"field_name",
"argument",
"is",
"given",
"for",
"convenience",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L134-L149 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/datatables.py | ValuesDatatable.preload_record_data | def preload_record_data(self, obj):
"""
Modifies the ``obj`` values dict to alias the selected values to the column name that asked
for its selection.
For example, a datatable that declares a column ``'blog'`` which has a related lookup source
``'blog__name'`` will ensure that t... | python | def preload_record_data(self, obj):
"""
Modifies the ``obj`` values dict to alias the selected values to the column name that asked
for its selection.
For example, a datatable that declares a column ``'blog'`` which has a related lookup source
``'blog__name'`` will ensure that t... | [
"def",
"preload_record_data",
"(",
"self",
",",
"obj",
")",
":",
"data",
"=",
"{",
"}",
"for",
"orm_path",
",",
"column_name",
"in",
"self",
".",
"value_queries",
".",
"items",
"(",
")",
":",
"value",
"=",
"obj",
"[",
"orm_path",
"]",
"if",
"column_nam... | Modifies the ``obj`` values dict to alias the selected values to the column name that asked
for its selection.
For example, a datatable that declares a column ``'blog'`` which has a related lookup source
``'blog__name'`` will ensure that the selected value exists in ``obj`` at both keys
... | [
"Modifies",
"the",
"obj",
"values",
"dict",
"to",
"alias",
"the",
"selected",
"values",
"to",
"the",
"column",
"name",
"that",
"asked",
"for",
"its",
"selection",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/datatables.py#L962-L998 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/datatables.py | LegacyDatatable.resolve_virtual_columns | def resolve_virtual_columns(self, *names):
"""
Assume that all ``names`` are legacy-style tuple declarations, and generate modern columns
instances to match the behavior of the old syntax.
"""
from .views.legacy import get_field_definition
virtual_columns = {}
for... | python | def resolve_virtual_columns(self, *names):
"""
Assume that all ``names`` are legacy-style tuple declarations, and generate modern columns
instances to match the behavior of the old syntax.
"""
from .views.legacy import get_field_definition
virtual_columns = {}
for... | [
"def",
"resolve_virtual_columns",
"(",
"self",
",",
"*",
"names",
")",
":",
"from",
".",
"views",
".",
"legacy",
"import",
"get_field_definition",
"virtual_columns",
"=",
"{",
"}",
"for",
"name",
"in",
"names",
":",
"field",
"=",
"get_field_definition",
"(",
... | Assume that all ``names`` are legacy-style tuple declarations, and generate modern columns
instances to match the behavior of the old syntax. | [
"Assume",
"that",
"all",
"names",
"are",
"legacy",
"-",
"style",
"tuple",
"declarations",
"and",
"generate",
"modern",
"columns",
"instances",
"to",
"match",
"the",
"behavior",
"of",
"the",
"old",
"syntax",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/datatables.py#L1010-L1032 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/forms.py | XEditableUpdateForm.set_value_field | def set_value_field(self, model, field_name):
"""
Adds a ``value`` field to this form that uses the appropriate formfield for the named target
field. This will help to ensure that the value is correctly validated.
"""
fields = fields_for_model(model, fields=[field_name])
... | python | def set_value_field(self, model, field_name):
"""
Adds a ``value`` field to this form that uses the appropriate formfield for the named target
field. This will help to ensure that the value is correctly validated.
"""
fields = fields_for_model(model, fields=[field_name])
... | [
"def",
"set_value_field",
"(",
"self",
",",
"model",
",",
"field_name",
")",
":",
"fields",
"=",
"fields_for_model",
"(",
"model",
",",
"fields",
"=",
"[",
"field_name",
"]",
")",
"self",
".",
"fields",
"[",
"'value'",
"]",
"=",
"fields",
"[",
"field_nam... | Adds a ``value`` field to this form that uses the appropriate formfield for the named target
field. This will help to ensure that the value is correctly validated. | [
"Adds",
"a",
"value",
"field",
"to",
"this",
"form",
"that",
"uses",
"the",
"appropriate",
"formfield",
"for",
"the",
"named",
"target",
"field",
".",
"This",
"will",
"help",
"to",
"ensure",
"that",
"the",
"value",
"is",
"correctly",
"validated",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/forms.py#L30-L36 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/forms.py | XEditableUpdateForm.clean_name | def clean_name(self):
""" Validates that the ``name`` field corresponds to a field on the model. """
field_name = self.cleaned_data['name']
# get_all_field_names is deprecated in Django 1.8, this also fixes proxied models
if hasattr(self.model._meta, 'get_fields'):
field_name... | python | def clean_name(self):
""" Validates that the ``name`` field corresponds to a field on the model. """
field_name = self.cleaned_data['name']
# get_all_field_names is deprecated in Django 1.8, this also fixes proxied models
if hasattr(self.model._meta, 'get_fields'):
field_name... | [
"def",
"clean_name",
"(",
"self",
")",
":",
"field_name",
"=",
"self",
".",
"cleaned_data",
"[",
"'name'",
"]",
"# get_all_field_names is deprecated in Django 1.8, this also fixes proxied models",
"if",
"hasattr",
"(",
"self",
".",
"model",
".",
"_meta",
",",
"'get_fi... | Validates that the ``name`` field corresponds to a field on the model. | [
"Validates",
"that",
"the",
"name",
"field",
"corresponds",
"to",
"a",
"field",
"on",
"the",
"model",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/forms.py#L38-L48 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/views/legacy.py | get_field_definition | def get_field_definition(field_definition):
""" Normalizes a field definition into its component parts, even if some are missing. """
if not isinstance(field_definition, (tuple, list)):
field_definition = [field_definition]
else:
field_definition = list(field_definition)
if len(field_de... | python | def get_field_definition(field_definition):
""" Normalizes a field definition into its component parts, even if some are missing. """
if not isinstance(field_definition, (tuple, list)):
field_definition = [field_definition]
else:
field_definition = list(field_definition)
if len(field_de... | [
"def",
"get_field_definition",
"(",
"field_definition",
")",
":",
"if",
"not",
"isinstance",
"(",
"field_definition",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"field_definition",
"=",
"[",
"field_definition",
"]",
"else",
":",
"field_definition",
"=",
"l... | Normalizes a field definition into its component parts, even if some are missing. | [
"Normalizes",
"a",
"field",
"definition",
"into",
"its",
"component",
"parts",
"even",
"if",
"some",
"are",
"missing",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/legacy.py#L31-L51 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/cache.py | get_cached_data | def get_cached_data(datatable, **kwargs):
""" Returns the cached object list under the appropriate key, or None if not set. """
cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))
data = cache.get(cache_key)
log.debug("Reading data from cache at %r: %r", cache_key, data)
return da... | python | def get_cached_data(datatable, **kwargs):
""" Returns the cached object list under the appropriate key, or None if not set. """
cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))
data = cache.get(cache_key)
log.debug("Reading data from cache at %r: %r", cache_key, data)
return da... | [
"def",
"get_cached_data",
"(",
"datatable",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"'%s%s'",
"%",
"(",
"CACHE_PREFIX",
",",
"datatable",
".",
"get_cache_key",
"(",
"*",
"*",
"kwargs",
")",
")",
"data",
"=",
"cache",
".",
"get",
"(",
"cach... | Returns the cached object list under the appropriate key, or None if not set. | [
"Returns",
"the",
"cached",
"object",
"list",
"under",
"the",
"appropriate",
"key",
"or",
"None",
"if",
"not",
"set",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/cache.py#L101-L106 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/cache.py | cache_data | def cache_data(datatable, data, **kwargs):
""" Stores the object list in the cache under the appropriate key. """
cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))
log.debug("Setting data to cache at %r: %r", cache_key, data)
cache.set(cache_key, data) | python | def cache_data(datatable, data, **kwargs):
""" Stores the object list in the cache under the appropriate key. """
cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))
log.debug("Setting data to cache at %r: %r", cache_key, data)
cache.set(cache_key, data) | [
"def",
"cache_data",
"(",
"datatable",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"'%s%s'",
"%",
"(",
"CACHE_PREFIX",
",",
"datatable",
".",
"get_cache_key",
"(",
"*",
"*",
"kwargs",
")",
")",
"log",
".",
"debug",
"(",
"\"Setting... | Stores the object list in the cache under the appropriate key. | [
"Stores",
"the",
"object",
"list",
"in",
"the",
"cache",
"under",
"the",
"appropriate",
"key",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/cache.py#L109-L113 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/helpers.py | keyed_helper | def keyed_helper(helper):
"""
Decorator for helper functions that operate on direct values instead of model instances.
A keyed helper is one that can be used normally in the view's own custom callbacks, but also
supports direct access in the column declaration, such as in the example:
datatabl... | python | def keyed_helper(helper):
"""
Decorator for helper functions that operate on direct values instead of model instances.
A keyed helper is one that can be used normally in the view's own custom callbacks, but also
supports direct access in the column declaration, such as in the example:
datatabl... | [
"def",
"keyed_helper",
"(",
"helper",
")",
":",
"@",
"wraps",
"(",
"helper",
")",
"def",
"wrapper",
"(",
"instance",
"=",
"None",
",",
"key",
"=",
"None",
",",
"attr",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"set",... | Decorator for helper functions that operate on direct values instead of model instances.
A keyed helper is one that can be used normally in the view's own custom callbacks, but also
supports direct access in the column declaration, such as in the example:
datatable_options = {
'columns': [... | [
"Decorator",
"for",
"helper",
"functions",
"that",
"operate",
"on",
"direct",
"values",
"instead",
"of",
"model",
"instances",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/helpers.py#L32-L84 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/helpers.py | itemgetter | def itemgetter(k, ellipsis=False, key=None):
"""
Looks up ``k`` as an index of the column's value.
If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to
indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default
``'...'``.
If a... | python | def itemgetter(k, ellipsis=False, key=None):
"""
Looks up ``k`` as an index of the column's value.
If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to
indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default
``'...'``.
If a... | [
"def",
"itemgetter",
"(",
"k",
",",
"ellipsis",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"def",
"helper",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"default_value",
"=",
"kwargs",
".",
"get",
"(",
"'default_value'"... | Looks up ``k`` as an index of the column's value.
If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to
indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default
``'...'``.
If a ``key`` is given, it may be a function which maps the ta... | [
"Looks",
"up",
"k",
"as",
"an",
"index",
"of",
"the",
"column",
"s",
"value",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/helpers.py#L150-L187 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/helpers.py | attrgetter | def attrgetter(attr, key=None):
"""
Looks up ``attr`` on the target value. If the result is a callable, it will be called in place
without arguments.
If a ``key`` is given, it may be a function which maps the target value to something else
before the attribute lookup takes place.
Examples::
... | python | def attrgetter(attr, key=None):
"""
Looks up ``attr`` on the target value. If the result is a callable, it will be called in place
without arguments.
If a ``key`` is given, it may be a function which maps the target value to something else
before the attribute lookup takes place.
Examples::
... | [
"def",
"attrgetter",
"(",
"attr",
",",
"key",
"=",
"None",
")",
":",
"def",
"helper",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"instance",
"for",
"bit",
"in",
"attr",
".",
"split",
"(",
"'.'",
")",
":",
... | Looks up ``attr`` on the target value. If the result is a callable, it will be called in place
without arguments.
If a ``key`` is given, it may be a function which maps the target value to something else
before the attribute lookup takes place.
Examples::
# Explicitly selecting the sources an... | [
"Looks",
"up",
"attr",
"on",
"the",
"target",
"value",
".",
"If",
"the",
"result",
"is",
"a",
"callable",
"it",
"will",
"be",
"called",
"in",
"place",
"without",
"arguments",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/helpers.py#L190-L218 | train |
pivotal-energy-solutions/django-datatable-view | datatableview/helpers.py | make_processor | def make_processor(func, arg=None):
"""
A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs tha... | python | def make_processor(func, arg=None):
"""
A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs tha... | [
"def",
"make_processor",
"(",
"func",
",",
"arg",
"=",
"None",
")",
":",
"def",
"helper",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"kwargs",
".",
"get",
"(",
"'default_value'",
")",
"if",
"value",
"is",
"N... | A pre-called processor that wraps the execution of the target callable ``func``.
This is useful for when ``func`` is a third party mapping function that can take your column's
value and return an expected result, but doesn't understand all of the extra kwargs that get
sent to processor callbacks. Because ... | [
"A",
"pre",
"-",
"called",
"processor",
"that",
"wraps",
"the",
"execution",
"of",
"the",
"target",
"callable",
"func",
"."
] | 00b77a9b5051c34e258c51b06c020e92edf15034 | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/helpers.py#L402-L428 | train |
Imgur/imgurpython | examples/upload.py | upload_kitten | def upload_kitten(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
# Here's the metadata for the upload. All of these are optional, including
# this config dict itself.
config = {
'album': album,
'name': 'Catastrophe!',
'title': 'Catastrophe!',
'description': 'Cute kit... | python | def upload_kitten(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
# Here's the metadata for the upload. All of these are optional, including
# this config dict itself.
config = {
'album': album,
'name': 'Catastrophe!',
'title': 'Catastrophe!',
'description': 'Cute kit... | [
"def",
"upload_kitten",
"(",
"client",
")",
":",
"# Here's the metadata for the upload. All of these are optional, including",
"# this config dict itself.",
"config",
"=",
"{",
"'album'",
":",
"album",
",",
"'name'",
":",
"'Catastrophe!'",
",",
"'title'",
":",
"'Catastrophe... | Upload a picture of a kitten. We don't ship one, so get creative! | [
"Upload",
"a",
"picture",
"of",
"a",
"kitten",
".",
"We",
"don",
"t",
"ship",
"one",
"so",
"get",
"creative!"
] | 48abc45a143ee9d2485c22a63b7cd55701d8163c | https://github.com/Imgur/imgurpython/blob/48abc45a143ee9d2485c22a63b7cd55701d8163c/examples/upload.py#L19-L38 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _isdst | def _isdst(dt):
"""Check if date is in dst.
"""
if type(dt) == datetime.date:
dt = datetime.datetime.combine(dt, datetime.datetime.min.time())
dtc = dt.replace(year=datetime.datetime.now().year)
if time.localtime(dtc.timestamp()).tm_isdst == 1:
return True
return False | python | def _isdst(dt):
"""Check if date is in dst.
"""
if type(dt) == datetime.date:
dt = datetime.datetime.combine(dt, datetime.datetime.min.time())
dtc = dt.replace(year=datetime.datetime.now().year)
if time.localtime(dtc.timestamp()).tm_isdst == 1:
return True
return False | [
"def",
"_isdst",
"(",
"dt",
")",
":",
"if",
"type",
"(",
"dt",
")",
"==",
"datetime",
".",
"date",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"dt",
",",
"datetime",
".",
"datetime",
".",
"min",
".",
"time",
"(",
")",
")",
... | Check if date is in dst. | [
"Check",
"if",
"date",
"is",
"in",
"dst",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L13-L21 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _mktime | def _mktime(time_struct):
"""Custom mktime because Windows can't be arsed to properly do pre-Epoch
dates, probably because it's busy counting all its chromosomes.
"""
try:
return time.mktime(time_struct)
except OverflowError:
dt = datetime.datetime(*time_struct[:6])
ep = date... | python | def _mktime(time_struct):
"""Custom mktime because Windows can't be arsed to properly do pre-Epoch
dates, probably because it's busy counting all its chromosomes.
"""
try:
return time.mktime(time_struct)
except OverflowError:
dt = datetime.datetime(*time_struct[:6])
ep = date... | [
"def",
"_mktime",
"(",
"time_struct",
")",
":",
"try",
":",
"return",
"time",
".",
"mktime",
"(",
"time_struct",
")",
"except",
"OverflowError",
":",
"dt",
"=",
"datetime",
".",
"datetime",
"(",
"*",
"time_struct",
"[",
":",
"6",
"]",
")",
"ep",
"=",
... | Custom mktime because Windows can't be arsed to properly do pre-Epoch
dates, probably because it's busy counting all its chromosomes. | [
"Custom",
"mktime",
"because",
"Windows",
"can",
"t",
"be",
"arsed",
"to",
"properly",
"do",
"pre",
"-",
"Epoch",
"dates",
"probably",
"because",
"it",
"s",
"busy",
"counting",
"all",
"its",
"chromosomes",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L24-L40 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _strftime | def _strftime(pattern, time_struct=time.localtime()):
"""Custom strftime because Windows is shit again.
"""
try:
return time.strftime(pattern, time_struct)
except OSError:
dt = datetime.datetime.fromtimestamp(_mktime(time_struct))
# This is incredibly hacky and will probably brea... | python | def _strftime(pattern, time_struct=time.localtime()):
"""Custom strftime because Windows is shit again.
"""
try:
return time.strftime(pattern, time_struct)
except OSError:
dt = datetime.datetime.fromtimestamp(_mktime(time_struct))
# This is incredibly hacky and will probably brea... | [
"def",
"_strftime",
"(",
"pattern",
",",
"time_struct",
"=",
"time",
".",
"localtime",
"(",
")",
")",
":",
"try",
":",
"return",
"time",
".",
"strftime",
"(",
"pattern",
",",
"time_struct",
")",
"except",
"OSError",
":",
"dt",
"=",
"datetime",
".",
"da... | Custom strftime because Windows is shit again. | [
"Custom",
"strftime",
"because",
"Windows",
"is",
"shit",
"again",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L43-L61 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _gmtime | def _gmtime(timestamp):
"""Custom gmtime because yada yada.
"""
try:
return time.gmtime(timestamp)
except OSError:
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
dst = int(_isdst(dt))
return time.struct_time(dt.timetuple()[:8] + tuple([dst])) | python | def _gmtime(timestamp):
"""Custom gmtime because yada yada.
"""
try:
return time.gmtime(timestamp)
except OSError:
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
dst = int(_isdst(dt))
return time.struct_time(dt.timetuple()[:8] + tuple([dst])) | [
"def",
"_gmtime",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"time",
".",
"gmtime",
"(",
"timestamp",
")",
"except",
"OSError",
":",
"dt",
"=",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"+",
"datetime",
".",
"timedelta... | Custom gmtime because yada yada. | [
"Custom",
"gmtime",
"because",
"yada",
"yada",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L64-L72 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _dtfromtimestamp | def _dtfromtimestamp(timestamp):
"""Custom datetime timestamp constructor. because Windows. again.
"""
try:
return datetime.datetime.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
... | python | def _dtfromtimestamp(timestamp):
"""Custom datetime timestamp constructor. because Windows. again.
"""
try:
return datetime.datetime.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
... | [
"def",
"_dtfromtimestamp",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
")",
"except",
"OSError",
":",
"timestamp",
"-=",
"time",
".",
"timezone",
"dt",
"=",
"datetime",
".",
"datetime... | Custom datetime timestamp constructor. because Windows. again. | [
"Custom",
"datetime",
"timestamp",
"constructor",
".",
"because",
"Windows",
".",
"again",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L75-L86 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _dfromtimestamp | def _dfromtimestamp(timestamp):
"""Custom date timestamp constructor. ditto
"""
try:
return datetime.date.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
d = datetime.date(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
if _isdst(d):
ti... | python | def _dfromtimestamp(timestamp):
"""Custom date timestamp constructor. ditto
"""
try:
return datetime.date.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
d = datetime.date(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
if _isdst(d):
ti... | [
"def",
"_dfromtimestamp",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"datetime",
".",
"date",
".",
"fromtimestamp",
"(",
"timestamp",
")",
"except",
"OSError",
":",
"timestamp",
"-=",
"time",
".",
"timezone",
"d",
"=",
"datetime",
".",
"date",
"(",
... | Custom date timestamp constructor. ditto | [
"Custom",
"date",
"timestamp",
"constructor",
".",
"ditto"
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L89-L100 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | guesstype | def guesstype(timestr):
"""Tries to guess whether a string represents a time or a time delta and
returns the appropriate object.
:param timestr (required)
The string to be analyzed
"""
timestr_full = " {} ".format(timestr)
if timestr_full.find(" in ") != -1 or timestr_full.find(" ago ")... | python | def guesstype(timestr):
"""Tries to guess whether a string represents a time or a time delta and
returns the appropriate object.
:param timestr (required)
The string to be analyzed
"""
timestr_full = " {} ".format(timestr)
if timestr_full.find(" in ") != -1 or timestr_full.find(" ago ")... | [
"def",
"guesstype",
"(",
"timestr",
")",
":",
"timestr_full",
"=",
"\" {} \"",
".",
"format",
"(",
"timestr",
")",
"if",
"timestr_full",
".",
"find",
"(",
"\" in \"",
")",
"!=",
"-",
"1",
"or",
"timestr_full",
".",
"find",
"(",
"\" ago \"",
")",
"!=",
... | Tries to guess whether a string represents a time or a time delta and
returns the appropriate object.
:param timestr (required)
The string to be analyzed | [
"Tries",
"to",
"guess",
"whether",
"a",
"string",
"represents",
"a",
"time",
"or",
"a",
"time",
"delta",
"and",
"returns",
"the",
"appropriate",
"object",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L112-L128 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | _round | def _round(num):
"""A custom rounding function that's a bit more 'strict'.
"""
deci = num - math.floor(num)
if deci > 0.8:
return int(math.floor(num) + 1)
else:
return int(math.floor(num)) | python | def _round(num):
"""A custom rounding function that's a bit more 'strict'.
"""
deci = num - math.floor(num)
if deci > 0.8:
return int(math.floor(num) + 1)
else:
return int(math.floor(num)) | [
"def",
"_round",
"(",
"num",
")",
":",
"deci",
"=",
"num",
"-",
"math",
".",
"floor",
"(",
"num",
")",
"if",
"deci",
">",
"0.8",
":",
"return",
"int",
"(",
"math",
".",
"floor",
"(",
"num",
")",
"+",
"1",
")",
"else",
":",
"return",
"int",
"(... | A custom rounding function that's a bit more 'strict'. | [
"A",
"custom",
"rounding",
"function",
"that",
"s",
"a",
"bit",
"more",
"strict",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L131-L138 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | Chronyk.datetime | def datetime(self, timezone=None):
"""Returns a datetime object.
This object retains all information, including timezones.
:param timezone = self.timezone
The timezone (in seconds west of UTC) to return the value in. By
default, the timezone used when constructing the c... | python | def datetime(self, timezone=None):
"""Returns a datetime object.
This object retains all information, including timezones.
:param timezone = self.timezone
The timezone (in seconds west of UTC) to return the value in. By
default, the timezone used when constructing the c... | [
"def",
"datetime",
"(",
"self",
",",
"timezone",
"=",
"None",
")",
":",
"if",
"timezone",
"is",
"None",
":",
"timezone",
"=",
"self",
".",
"timezone",
"return",
"_dtfromtimestamp",
"(",
"self",
".",
"__timestamp__",
"-",
"timezone",
")"
] | Returns a datetime object.
This object retains all information, including timezones.
:param timezone = self.timezone
The timezone (in seconds west of UTC) to return the value in. By
default, the timezone used when constructing the class is used
(local one by default... | [
"Returns",
"a",
"datetime",
"object",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L499-L512 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | Chronyk.ctime | def ctime(self, timezone=None):
"""Returns a ctime string.
:param timezone = self.timezone
The timezone (in seconds west of UTC) to return the value in. By
default, the timezone used when constructing the class is used
(local one by default). To use UTC, use timezone... | python | def ctime(self, timezone=None):
"""Returns a ctime string.
:param timezone = self.timezone
The timezone (in seconds west of UTC) to return the value in. By
default, the timezone used when constructing the class is used
(local one by default). To use UTC, use timezone... | [
"def",
"ctime",
"(",
"self",
",",
"timezone",
"=",
"None",
")",
":",
"if",
"timezone",
"is",
"None",
":",
"timezone",
"=",
"self",
".",
"timezone",
"return",
"time",
".",
"ctime",
"(",
"self",
".",
"__timestamp__",
"-",
"timezone",
")"
] | Returns a ctime string.
:param timezone = self.timezone
The timezone (in seconds west of UTC) to return the value in. By
default, the timezone used when constructing the class is used
(local one by default). To use UTC, use timezone = 0. To use the
local tz, use ... | [
"Returns",
"a",
"ctime",
"string",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L541-L552 | train |
KoffeinFlummi/Chronyk | chronyk/chronyk.py | Chronyk.timestring | def timestring(self, pattern="%Y-%m-%d %H:%M:%S", timezone=None):
"""Returns a time string.
:param pattern = "%Y-%m-%d %H:%M:%S"
The format used. By default, an ISO-type format is used. The
syntax here is identical to the one used by time.strftime() and
time.strptime... | python | def timestring(self, pattern="%Y-%m-%d %H:%M:%S", timezone=None):
"""Returns a time string.
:param pattern = "%Y-%m-%d %H:%M:%S"
The format used. By default, an ISO-type format is used. The
syntax here is identical to the one used by time.strftime() and
time.strptime... | [
"def",
"timestring",
"(",
"self",
",",
"pattern",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
",",
"timezone",
"=",
"None",
")",
":",
"if",
"timezone",
"is",
"None",
":",
"timezone",
"=",
"self",
".",
"timezone",
"timestamp",
"=",
"self",
".",
"__timestamp__",
"-",
"tim... | Returns a time string.
:param pattern = "%Y-%m-%d %H:%M:%S"
The format used. By default, an ISO-type format is used. The
syntax here is identical to the one used by time.strftime() and
time.strptime().
:param timezone = self.timezone
The timezone (in sec... | [
"Returns",
"a",
"time",
"string",
"."
] | 5a9f3518d2e831884dea7e8c077d6e7350df2fbe | https://github.com/KoffeinFlummi/Chronyk/blob/5a9f3518d2e831884dea7e8c077d6e7350df2fbe/chronyk/chronyk.py#L554-L572 | train |
sjkingo/python-freshdesk | freshdesk/v2/api.py | TicketAPI.get_ticket | def get_ticket(self, ticket_id):
"""Fetches the ticket for the given ticket ID"""
url = 'tickets/%d' % ticket_id
ticket = self._api._get(url)
return Ticket(**ticket) | python | def get_ticket(self, ticket_id):
"""Fetches the ticket for the given ticket ID"""
url = 'tickets/%d' % ticket_id
ticket = self._api._get(url)
return Ticket(**ticket) | [
"def",
"get_ticket",
"(",
"self",
",",
"ticket_id",
")",
":",
"url",
"=",
"'tickets/%d'",
"%",
"ticket_id",
"ticket",
"=",
"self",
".",
"_api",
".",
"_get",
"(",
"url",
")",
"return",
"Ticket",
"(",
"*",
"*",
"ticket",
")"
] | Fetches the ticket for the given ticket ID | [
"Fetches",
"the",
"ticket",
"for",
"the",
"given",
"ticket",
"ID"
] | 39edca5d86e73de5619b1d082d9d8b5c0ae626c8 | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L11-L15 | train |
sjkingo/python-freshdesk | freshdesk/v2/api.py | TicketAPI.create_outbound_email | def create_outbound_email(self, subject, description, email, email_config_id, **kwargs):
"""Creates an outbound email"""
url = 'tickets/outbound_email'
priority = kwargs.get('priority', 1)
data = {
'subject': subject,
'description': description,
'prior... | python | def create_outbound_email(self, subject, description, email, email_config_id, **kwargs):
"""Creates an outbound email"""
url = 'tickets/outbound_email'
priority = kwargs.get('priority', 1)
data = {
'subject': subject,
'description': description,
'prior... | [
"def",
"create_outbound_email",
"(",
"self",
",",
"subject",
",",
"description",
",",
"email",
",",
"email_config_id",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"'tickets/outbound_email'",
"priority",
"=",
"kwargs",
".",
"get",
"(",
"'priority'",
",",
"... | Creates an outbound email | [
"Creates",
"an",
"outbound",
"email"
] | 39edca5d86e73de5619b1d082d9d8b5c0ae626c8 | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L53-L66 | train |
sjkingo/python-freshdesk | freshdesk/v2/api.py | TicketAPI.update_ticket | def update_ticket(self, ticket_id, **kwargs):
"""Updates a ticket from a given ticket ID"""
url = 'tickets/%d' % ticket_id
ticket = self._api._put(url, data=json.dumps(kwargs))
return Ticket(**ticket) | python | def update_ticket(self, ticket_id, **kwargs):
"""Updates a ticket from a given ticket ID"""
url = 'tickets/%d' % ticket_id
ticket = self._api._put(url, data=json.dumps(kwargs))
return Ticket(**ticket) | [
"def",
"update_ticket",
"(",
"self",
",",
"ticket_id",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"'tickets/%d'",
"%",
"ticket_id",
"ticket",
"=",
"self",
".",
"_api",
".",
"_put",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"kwargs"... | Updates a ticket from a given ticket ID | [
"Updates",
"a",
"ticket",
"from",
"a",
"given",
"ticket",
"ID"
] | 39edca5d86e73de5619b1d082d9d8b5c0ae626c8 | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L68-L72 | train |
sjkingo/python-freshdesk | freshdesk/v2/api.py | AgentAPI.get_agent | def get_agent(self, agent_id):
"""Fetches the agent for the given agent ID"""
url = 'agents/%s' % agent_id
return Agent(**self._api._get(url)) | python | def get_agent(self, agent_id):
"""Fetches the agent for the given agent ID"""
url = 'agents/%s' % agent_id
return Agent(**self._api._get(url)) | [
"def",
"get_agent",
"(",
"self",
",",
"agent_id",
")",
":",
"url",
"=",
"'agents/%s'",
"%",
"agent_id",
"return",
"Agent",
"(",
"*",
"*",
"self",
".",
"_api",
".",
"_get",
"(",
"url",
")",
")"
] | Fetches the agent for the given agent ID | [
"Fetches",
"the",
"agent",
"for",
"the",
"given",
"agent",
"ID"
] | 39edca5d86e73de5619b1d082d9d8b5c0ae626c8 | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L360-L363 | train |
sjkingo/python-freshdesk | freshdesk/v2/api.py | AgentAPI.update_agent | def update_agent(self, agent_id, **kwargs):
"""Updates an agent"""
url = 'agents/%s' % agent_id
agent = self._api._put(url, data=json.dumps(kwargs))
return Agent(**agent) | python | def update_agent(self, agent_id, **kwargs):
"""Updates an agent"""
url = 'agents/%s' % agent_id
agent = self._api._put(url, data=json.dumps(kwargs))
return Agent(**agent) | [
"def",
"update_agent",
"(",
"self",
",",
"agent_id",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"'agents/%s'",
"%",
"agent_id",
"agent",
"=",
"self",
".",
"_api",
".",
"_put",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"kwargs",
"... | Updates an agent | [
"Updates",
"an",
"agent"
] | 39edca5d86e73de5619b1d082d9d8b5c0ae626c8 | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L365-L369 | train |
sjkingo/python-freshdesk | freshdesk/v1/api.py | API._action | def _action(self, res):
"""Returns JSON response or raise exception if errors are present"""
try:
j = res.json()
except:
res.raise_for_status()
j = {}
if 'Retry-After' in res.headers:
raise HTTPError('403 Forbidden: API rate-limit has been... | python | def _action(self, res):
"""Returns JSON response or raise exception if errors are present"""
try:
j = res.json()
except:
res.raise_for_status()
j = {}
if 'Retry-After' in res.headers:
raise HTTPError('403 Forbidden: API rate-limit has been... | [
"def",
"_action",
"(",
"self",
",",
"res",
")",
":",
"try",
":",
"j",
"=",
"res",
".",
"json",
"(",
")",
"except",
":",
"res",
".",
"raise_for_status",
"(",
")",
"j",
"=",
"{",
"}",
"if",
"'Retry-After'",
"in",
"res",
".",
"headers",
":",
"raise"... | Returns JSON response or raise exception if errors are present | [
"Returns",
"JSON",
"response",
"or",
"raise",
"exception",
"if",
"errors",
"are",
"present"
] | 39edca5d86e73de5619b1d082d9d8b5c0ae626c8 | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v1/api.py#L293-L318 | train |
pysal/mapclassify | mapclassify/classifiers.py | headTail_breaks | def headTail_breaks(values, cuts):
"""
head tail breaks helper function
"""
values = np.array(values)
mean = np.mean(values)
cuts.append(mean)
if len(values) > 1:
return headTail_breaks(values[values >= mean], cuts)
return cuts | python | def headTail_breaks(values, cuts):
"""
head tail breaks helper function
"""
values = np.array(values)
mean = np.mean(values)
cuts.append(mean)
if len(values) > 1:
return headTail_breaks(values[values >= mean], cuts)
return cuts | [
"def",
"headTail_breaks",
"(",
"values",
",",
"cuts",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"values",
")",
"mean",
"=",
"np",
".",
"mean",
"(",
"values",
")",
"cuts",
".",
"append",
"(",
"mean",
")",
"if",
"len",
"(",
"values",
")",
"... | head tail breaks helper function | [
"head",
"tail",
"breaks",
"helper",
"function"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L35-L44 | train |
pysal/mapclassify | mapclassify/classifiers.py | quantile | def quantile(y, k=4):
"""
Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import n... | python | def quantile(y, k=4):
"""
Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import n... | [
"def",
"quantile",
"(",
"y",
",",
"k",
"=",
"4",
")",
":",
"w",
"=",
"100.",
"/",
"k",
"p",
"=",
"np",
".",
"arange",
"(",
"w",
",",
"100",
"+",
"w",
",",
"w",
")",
"if",
"p",
"[",
"-",
"1",
"]",
">",
"100.0",
":",
"p",
"[",
"-",
"1",... | Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import numpy as np
>>> import mapclass... | [
"Calculates",
"the",
"quantiles",
"for",
"an",
"array"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L47-L97 | train |
pysal/mapclassify | mapclassify/classifiers.py | bin1d | def bin1d(x, bins):
"""
Place values of a 1-d array into bins and determine counts of values in
each bin
Parameters
----------
x : array
(n, 1), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
binIds : array
... | python | def bin1d(x, bins):
"""
Place values of a 1-d array into bins and determine counts of values in
each bin
Parameters
----------
x : array
(n, 1), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
binIds : array
... | [
"def",
"bin1d",
"(",
"x",
",",
"bins",
")",
":",
"left",
"=",
"[",
"-",
"float",
"(",
"\"inf\"",
")",
"]",
"left",
".",
"extend",
"(",
"bins",
"[",
"0",
":",
"-",
"1",
"]",
")",
"right",
"=",
"bins",
"cuts",
"=",
"list",
"(",
"zip",
"(",
"l... | Place values of a 1-d array into bins and determine counts of values in
each bin
Parameters
----------
x : array
(n, 1), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
binIds : array
1-d array of integer bin Ids
... | [
"Place",
"values",
"of",
"a",
"1",
"-",
"d",
"array",
"into",
"bins",
"and",
"determine",
"counts",
"of",
"values",
"in",
"each",
"bin"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L231-L278 | train |
pysal/mapclassify | mapclassify/classifiers.py | _kmeans | def _kmeans(y, k=5):
"""
Helper function to do kmeans in one dimension
"""
y = y * 1. # KMEANS needs float or double dtype
centroids = KMEANS(y, k)[0]
centroids.sort()
try:
class_ids = np.abs(y - centroids).argmin(axis=1)
except:
class_ids = np.abs(y[:, np.newaxis] - ce... | python | def _kmeans(y, k=5):
"""
Helper function to do kmeans in one dimension
"""
y = y * 1. # KMEANS needs float or double dtype
centroids = KMEANS(y, k)[0]
centroids.sort()
try:
class_ids = np.abs(y - centroids).argmin(axis=1)
except:
class_ids = np.abs(y[:, np.newaxis] - ce... | [
"def",
"_kmeans",
"(",
"y",
",",
"k",
"=",
"5",
")",
":",
"y",
"=",
"y",
"*",
"1.",
"# KMEANS needs float or double dtype",
"centroids",
"=",
"KMEANS",
"(",
"y",
",",
"k",
")",
"[",
"0",
"]",
"centroids",
".",
"sort",
"(",
")",
"try",
":",
"class_i... | Helper function to do kmeans in one dimension | [
"Helper",
"function",
"to",
"do",
"kmeans",
"in",
"one",
"dimension"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L289-L310 | train |
pysal/mapclassify | mapclassify/classifiers.py | natural_breaks | def natural_breaks(values, k=5):
"""
natural breaks helper function
Jenks natural breaks is kmeans in one dimension
"""
values = np.array(values)
uv = np.unique(values)
uvk = len(uv)
if uvk < k:
Warn('Warning: Not enough unique values in array to form k classes',
Us... | python | def natural_breaks(values, k=5):
"""
natural breaks helper function
Jenks natural breaks is kmeans in one dimension
"""
values = np.array(values)
uv = np.unique(values)
uvk = len(uv)
if uvk < k:
Warn('Warning: Not enough unique values in array to form k classes',
Us... | [
"def",
"natural_breaks",
"(",
"values",
",",
"k",
"=",
"5",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"values",
")",
"uv",
"=",
"np",
".",
"unique",
"(",
"values",
")",
"uvk",
"=",
"len",
"(",
"uv",
")",
"if",
"uvk",
"<",
"k",
":",
"W... | natural breaks helper function
Jenks natural breaks is kmeans in one dimension | [
"natural",
"breaks",
"helper",
"function"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L313-L332 | train |
pysal/mapclassify | mapclassify/classifiers.py | _fit | def _fit(y, classes):
"""Calculate the total sum of squares for a vector y classified into
classes
Parameters
----------
y : array
(n,1), variable to be classified
classes : array
(k,1), integer values denoting class membership
"""
tss = 0
for class_def in cl... | python | def _fit(y, classes):
"""Calculate the total sum of squares for a vector y classified into
classes
Parameters
----------
y : array
(n,1), variable to be classified
classes : array
(k,1), integer values denoting class membership
"""
tss = 0
for class_def in cl... | [
"def",
"_fit",
"(",
"y",
",",
"classes",
")",
":",
"tss",
"=",
"0",
"for",
"class_def",
"in",
"classes",
":",
"yc",
"=",
"y",
"[",
"class_def",
"]",
"css",
"=",
"yc",
"-",
"yc",
".",
"mean",
"(",
")",
"css",
"*=",
"css",
"tss",
"+=",
"sum",
"... | Calculate the total sum of squares for a vector y classified into
classes
Parameters
----------
y : array
(n,1), variable to be classified
classes : array
(k,1), integer values denoting class membership | [
"Calculate",
"the",
"total",
"sum",
"of",
"squares",
"for",
"a",
"vector",
"y",
"classified",
"into",
"classes"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2226-L2245 | train |
pysal/mapclassify | mapclassify/classifiers.py | gadf | def gadf(y, method="Quantiles", maxk=15, pct=0.8):
"""
Evaluate the Goodness of Absolute Deviation Fit of a Classifier
Finds the minimum value of k for which gadf>pct
Parameters
----------
y : array
(n, 1) values to be classified
method : {'Quantiles, 'Fisher_Jenks', 'Max... | python | def gadf(y, method="Quantiles", maxk=15, pct=0.8):
"""
Evaluate the Goodness of Absolute Deviation Fit of a Classifier
Finds the minimum value of k for which gadf>pct
Parameters
----------
y : array
(n, 1) values to be classified
method : {'Quantiles, 'Fisher_Jenks', 'Max... | [
"def",
"gadf",
"(",
"y",
",",
"method",
"=",
"\"Quantiles\"",
",",
"maxk",
"=",
"15",
",",
"pct",
"=",
"0.8",
")",
":",
"y",
"=",
"np",
".",
"array",
"(",
"y",
")",
"adam",
"=",
"(",
"np",
".",
"abs",
"(",
"y",
"-",
"np",
".",
"median",
"("... | Evaluate the Goodness of Absolute Deviation Fit of a Classifier
Finds the minimum value of k for which gadf>pct
Parameters
----------
y : array
(n, 1) values to be classified
method : {'Quantiles, 'Fisher_Jenks', 'Maximum_Breaks', 'Natrual_Breaks'}
maxk : int
m... | [
"Evaluate",
"the",
"Goodness",
"of",
"Absolute",
"Deviation",
"Fit",
"of",
"a",
"Classifier",
"Finds",
"the",
"minimum",
"value",
"of",
"k",
"for",
"which",
"gadf",
">",
"pct"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2255-L2325 | train |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.make | def make(cls, *args, **kwargs):
"""
Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` cre... | python | def make(cls, *args, **kwargs):
"""
Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` cre... | [
"def",
"make",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# only flag overrides return flag",
"to_annotate",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"return_object",
"=",
"kwargs",
".",
"pop",
"(",
"'return_object'",
",",
"... | Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` creates a function that returns classifications; it
... | [
"Configure",
"and",
"create",
"a",
"classifier",
"that",
"will",
"consume",
"data",
"and",
"produce",
"classifications",
"given",
"the",
"configuration",
"options",
"specified",
"by",
"this",
"function",
"."
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L476-L618 | train |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.get_tss | def get_tss(self):
"""
Total sum of squares around class means
Returns sum of squares over all class means
"""
tss = 0
for class_def in self.classes:
if len(class_def) > 0:
yc = self.y[class_def]
css = yc - yc.mean()
... | python | def get_tss(self):
"""
Total sum of squares around class means
Returns sum of squares over all class means
"""
tss = 0
for class_def in self.classes:
if len(class_def) > 0:
yc = self.y[class_def]
css = yc - yc.mean()
... | [
"def",
"get_tss",
"(",
"self",
")",
":",
"tss",
"=",
"0",
"for",
"class_def",
"in",
"self",
".",
"classes",
":",
"if",
"len",
"(",
"class_def",
")",
">",
"0",
":",
"yc",
"=",
"self",
".",
"y",
"[",
"class_def",
"]",
"css",
"=",
"yc",
"-",
"yc",... | Total sum of squares around class means
Returns sum of squares over all class means | [
"Total",
"sum",
"of",
"squares",
"around",
"class",
"means"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L663-L676 | train |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.get_gadf | def get_gadf(self):
"""
Goodness of absolute deviation of fit
"""
adam = (np.abs(self.y - np.median(self.y))).sum()
gadf = 1 - self.adcm / adam
return gadf | python | def get_gadf(self):
"""
Goodness of absolute deviation of fit
"""
adam = (np.abs(self.y - np.median(self.y))).sum()
gadf = 1 - self.adcm / adam
return gadf | [
"def",
"get_gadf",
"(",
"self",
")",
":",
"adam",
"=",
"(",
"np",
".",
"abs",
"(",
"self",
".",
"y",
"-",
"np",
".",
"median",
"(",
"self",
".",
"y",
")",
")",
")",
".",
"sum",
"(",
")",
"gadf",
"=",
"1",
"-",
"self",
".",
"adcm",
"/",
"a... | Goodness of absolute deviation of fit | [
"Goodness",
"of",
"absolute",
"deviation",
"of",
"fit"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L699-L705 | train |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.find_bin | def find_bin(self, x):
"""
Sort input or inputs according to the current bin estimate
Parameters
----------
x : array or numeric
a value or array of values to fit within the estimated
bins
Returns
-------
a... | python | def find_bin(self, x):
"""
Sort input or inputs according to the current bin estimate
Parameters
----------
x : array or numeric
a value or array of values to fit within the estimated
bins
Returns
-------
a... | [
"def",
"find_bin",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
".",
"flatten",
"(",
")",
"right",
"=",
"np",
".",
"digitize",
"(",
"x",
",",
"self",
".",
"bins",
",",
"right",
"=",
"True",
")",
"if",
"right... | Sort input or inputs according to the current bin estimate
Parameters
----------
x : array or numeric
a value or array of values to fit within the estimated
bins
Returns
-------
a bin index or array of bin indices that cla... | [
"Sort",
"input",
"or",
"inputs",
"according",
"to",
"the",
"current",
"bin",
"estimate"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L751-L779 | train |
pysal/mapclassify | mapclassify/classifiers.py | Fisher_Jenks_Sampled.update | def update(self, y=None, inplace=False, **kwargs):
"""
Add data or change classification parameters.
Parameters
----------
y : array
(n,1) array of data to classify
inplace : bool
whether to conduct the up... | python | def update(self, y=None, inplace=False, **kwargs):
"""
Add data or change classification parameters.
Parameters
----------
y : array
(n,1) array of data to classify
inplace : bool
whether to conduct the up... | [
"def",
"update",
"(",
"self",
",",
"y",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'k'",
":",
"kwargs",
".",
"pop",
"(",
"'k'",
",",
"self",
".",
"k",
")",
"}",
")",
"kwar... | Add data or change classification parameters.
Parameters
----------
y : array
(n,1) array of data to classify
inplace : bool
whether to conduct the update in place or to return a
copy estimated fro... | [
"Add",
"data",
"or",
"change",
"classification",
"parameters",
"."
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L1586-L1609 | train |
pysal/mapclassify | mapclassify/classifiers.py | Max_P_Classifier._ss | def _ss(self, class_def):
"""calculates sum of squares for a class"""
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
return sum(css) | python | def _ss(self, class_def):
"""calculates sum of squares for a class"""
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
return sum(css) | [
"def",
"_ss",
"(",
"self",
",",
"class_def",
")",
":",
"yc",
"=",
"self",
".",
"y",
"[",
"class_def",
"]",
"css",
"=",
"yc",
"-",
"yc",
".",
"mean",
"(",
")",
"css",
"*=",
"css",
"return",
"sum",
"(",
"css",
")"
] | calculates sum of squares for a class | [
"calculates",
"sum",
"of",
"squares",
"for",
"a",
"class"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2178-L2183 | train |
pysal/mapclassify | mapclassify/classifiers.py | Max_P_Classifier._swap | def _swap(self, class1, class2, a):
"""evaluate cost of moving a from class1 to class2"""
ss1 = self._ss(class1)
ss2 = self._ss(class2)
tss1 = ss1 + ss2
class1c = copy.copy(class1)
class2c = copy.copy(class2)
class1c.remove(a)
class2c.append(a)
ss1... | python | def _swap(self, class1, class2, a):
"""evaluate cost of moving a from class1 to class2"""
ss1 = self._ss(class1)
ss2 = self._ss(class2)
tss1 = ss1 + ss2
class1c = copy.copy(class1)
class2c = copy.copy(class2)
class1c.remove(a)
class2c.append(a)
ss1... | [
"def",
"_swap",
"(",
"self",
",",
"class1",
",",
"class2",
",",
"a",
")",
":",
"ss1",
"=",
"self",
".",
"_ss",
"(",
"class1",
")",
"ss2",
"=",
"self",
".",
"_ss",
"(",
"class2",
")",
"tss1",
"=",
"ss1",
"+",
"ss2",
"class1c",
"=",
"copy",
".",
... | evaluate cost of moving a from class1 to class2 | [
"evaluate",
"cost",
"of",
"moving",
"a",
"from",
"class1",
"to",
"class2"
] | 5b22ec33f5802becf40557614d90cd38efa1676e | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2185-L2200 | train |
abarker/pdfCropMargins | src/pdfCropMargins/calculate_bounding_boxes.py | get_bounding_box_list_render_image | def get_bounding_box_list_render_image(pdf_file_name, input_doc):
"""Calculate the bounding box list by directly rendering each page of the PDF as
an image file. The MediaBox and CropBox values in input_doc should have
already been set to the chosen page size before the rendering."""
program_to_use = ... | python | def get_bounding_box_list_render_image(pdf_file_name, input_doc):
"""Calculate the bounding box list by directly rendering each page of the PDF as
an image file. The MediaBox and CropBox values in input_doc should have
already been set to the chosen page size before the rendering."""
program_to_use = ... | [
"def",
"get_bounding_box_list_render_image",
"(",
"pdf_file_name",
",",
"input_doc",
")",
":",
"program_to_use",
"=",
"\"pdftoppm\"",
"# default to pdftoppm",
"if",
"args",
".",
"gsRender",
":",
"program_to_use",
"=",
"\"Ghostscript\"",
"# Threshold value set in range 0-255, ... | Calculate the bounding box list by directly rendering each page of the PDF as
an image file. The MediaBox and CropBox values in input_doc should have
already been set to the chosen page size before the rendering. | [
"Calculate",
"the",
"bounding",
"box",
"list",
"by",
"directly",
"rendering",
"each",
"page",
"of",
"the",
"PDF",
"as",
"an",
"image",
"file",
".",
"The",
"MediaBox",
"and",
"CropBox",
"values",
"in",
"input_doc",
"should",
"have",
"already",
"been",
"set",
... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/calculate_bounding_boxes.py#L116-L206 | train |
abarker/pdfCropMargins | src/pdfCropMargins/calculate_bounding_boxes.py | render_pdf_file_to_image_files | def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use):
"""Render all the pages of the PDF file at pdf_file_name to image files with
path and filename prefix given by output_filename_root. Any directories must
have already been created, and the calling program is responsibl... | python | def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use):
"""Render all the pages of the PDF file at pdf_file_name to image files with
path and filename prefix given by output_filename_root. Any directories must
have already been created, and the calling program is responsibl... | [
"def",
"render_pdf_file_to_image_files",
"(",
"pdf_file_name",
",",
"output_filename_root",
",",
"program_to_use",
")",
":",
"res_x",
"=",
"str",
"(",
"args",
".",
"resX",
")",
"res_y",
"=",
"str",
"(",
"args",
".",
"resY",
")",
"if",
"program_to_use",
"==",
... | Render all the pages of the PDF file at pdf_file_name to image files with
path and filename prefix given by output_filename_root. Any directories must
have already been created, and the calling program is responsible for
deleting any directories or image files. The program program_to_use,
currently ei... | [
"Render",
"all",
"the",
"pages",
"of",
"the",
"PDF",
"file",
"at",
"pdf_file_name",
"to",
"image",
"files",
"with",
"path",
"and",
"filename",
"prefix",
"given",
"by",
"output_filename_root",
".",
"Any",
"directories",
"must",
"have",
"already",
"been",
"creat... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/calculate_bounding_boxes.py#L208-L237 | train |
abarker/pdfCropMargins | src/pdfCropMargins/calculate_bounding_boxes.py | calculate_bounding_box_from_image | def calculate_bounding_box_from_image(im, curr_page):
"""This function uses a PIL routine to get the bounding box of the rendered
image."""
xMax, y_max = im.size
bounding_box = im.getbbox() # note this uses ltrb convention
if not bounding_box:
#print("\nWarning: could not calculate a boundin... | python | def calculate_bounding_box_from_image(im, curr_page):
"""This function uses a PIL routine to get the bounding box of the rendered
image."""
xMax, y_max = im.size
bounding_box = im.getbbox() # note this uses ltrb convention
if not bounding_box:
#print("\nWarning: could not calculate a boundin... | [
"def",
"calculate_bounding_box_from_image",
"(",
"im",
",",
"curr_page",
")",
":",
"xMax",
",",
"y_max",
"=",
"im",
".",
"size",
"bounding_box",
"=",
"im",
".",
"getbbox",
"(",
")",
"# note this uses ltrb convention",
"if",
"not",
"bounding_box",
":",
"#print(\"... | This function uses a PIL routine to get the bounding box of the rendered
image. | [
"This",
"function",
"uses",
"a",
"PIL",
"routine",
"to",
"get",
"the",
"bounding",
"box",
"of",
"the",
"rendered",
"image",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/calculate_bounding_boxes.py#L239-L270 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | samefile | def samefile(path1, path2):
"""Test if paths refer to the same file or directory."""
if system_os == "Linux" or system_os == "Cygwin":
return os.path.samefile(path1, path2)
return (get_canonical_absolute_expanded_path(path1) ==
get_canonical_absolute_expanded_path(path2)) | python | def samefile(path1, path2):
"""Test if paths refer to the same file or directory."""
if system_os == "Linux" or system_os == "Cygwin":
return os.path.samefile(path1, path2)
return (get_canonical_absolute_expanded_path(path1) ==
get_canonical_absolute_expanded_path(path2)) | [
"def",
"samefile",
"(",
"path1",
",",
"path2",
")",
":",
"if",
"system_os",
"==",
"\"Linux\"",
"or",
"system_os",
"==",
"\"Cygwin\"",
":",
"return",
"os",
".",
"path",
".",
"samefile",
"(",
"path1",
",",
"path2",
")",
"return",
"(",
"get_canonical_absolute... | Test if paths refer to the same file or directory. | [
"Test",
"if",
"paths",
"refer",
"to",
"the",
"same",
"file",
"or",
"directory",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L135-L140 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | convert_windows_path_to_cygwin | def convert_windows_path_to_cygwin(path):
"""Convert a Windows path to a Cygwin path. Just handles the basic case."""
if len(path) > 2 and path[1] == ":" and path[2] == "\\":
newpath = cygwin_full_path_prefix + "/" + path[0]
if len(path) > 3: newpath += "/" + path[3:]
path = newpath
... | python | def convert_windows_path_to_cygwin(path):
"""Convert a Windows path to a Cygwin path. Just handles the basic case."""
if len(path) > 2 and path[1] == ":" and path[2] == "\\":
newpath = cygwin_full_path_prefix + "/" + path[0]
if len(path) > 3: newpath += "/" + path[3:]
path = newpath
... | [
"def",
"convert_windows_path_to_cygwin",
"(",
"path",
")",
":",
"if",
"len",
"(",
"path",
")",
">",
"2",
"and",
"path",
"[",
"1",
"]",
"==",
"\":\"",
"and",
"path",
"[",
"2",
"]",
"==",
"\"\\\\\"",
":",
"newpath",
"=",
"cygwin_full_path_prefix",
"+",
"... | Convert a Windows path to a Cygwin path. Just handles the basic case. | [
"Convert",
"a",
"Windows",
"path",
"to",
"a",
"Cygwin",
"path",
".",
"Just",
"handles",
"the",
"basic",
"case",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L167-L174 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | remove_program_temp_directory | def remove_program_temp_directory():
"""Remove the global temp directory and all its contents."""
if os.path.exists(program_temp_directory):
max_retries = 3
curr_retries = 0
time_between_retries = 1
while True:
try:
shutil.rmtree(program_temp_directory... | python | def remove_program_temp_directory():
"""Remove the global temp directory and all its contents."""
if os.path.exists(program_temp_directory):
max_retries = 3
curr_retries = 0
time_between_retries = 1
while True:
try:
shutil.rmtree(program_temp_directory... | [
"def",
"remove_program_temp_directory",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"program_temp_directory",
")",
":",
"max_retries",
"=",
"3",
"curr_retries",
"=",
"0",
"time_between_retries",
"=",
"1",
"while",
"True",
":",
"try",
":",
"sh... | Remove the global temp directory and all its contents. | [
"Remove",
"the",
"global",
"temp",
"directory",
"and",
"all",
"its",
"contents",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L191-L208 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | call_external_subprocess | def call_external_subprocess(command_list,
stdin_filename=None, stdout_filename=None, stderr_filename=None,
env=None):
"""Run the command and arguments in the command_list. Will search the system
PATH for commands to execute, but no shell is started. Redirects any... | python | def call_external_subprocess(command_list,
stdin_filename=None, stdout_filename=None, stderr_filename=None,
env=None):
"""Run the command and arguments in the command_list. Will search the system
PATH for commands to execute, but no shell is started. Redirects any... | [
"def",
"call_external_subprocess",
"(",
"command_list",
",",
"stdin_filename",
"=",
"None",
",",
"stdout_filename",
"=",
"None",
",",
"stderr_filename",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"stdin_filename",
":",
"stdin",
"=",
"open",
"(",
"... | Run the command and arguments in the command_list. Will search the system
PATH for commands to execute, but no shell is started. Redirects any selected
outputs to the given filename. Waits for command completion. | [
"Run",
"the",
"command",
"and",
"arguments",
"in",
"the",
"command_list",
".",
"Will",
"search",
"the",
"system",
"PATH",
"for",
"commands",
"to",
"execute",
"but",
"no",
"shell",
"is",
"started",
".",
"Redirects",
"any",
"selected",
"outputs",
"to",
"the",
... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L279-L306 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | run_external_subprocess_in_background | def run_external_subprocess_in_background(command_list, env=None):
"""Runs the command and arguments in the list as a background process."""
if system_os == "Windows":
DETACHED_PROCESS = 0x00000008
p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None,
stderr=No... | python | def run_external_subprocess_in_background(command_list, env=None):
"""Runs the command and arguments in the list as a background process."""
if system_os == "Windows":
DETACHED_PROCESS = 0x00000008
p = subprocess.Popen(command_list, shell=False, stdin=None, stdout=None,
stderr=No... | [
"def",
"run_external_subprocess_in_background",
"(",
"command_list",
",",
"env",
"=",
"None",
")",
":",
"if",
"system_os",
"==",
"\"Windows\"",
":",
"DETACHED_PROCESS",
"=",
"0x00000008",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command_list",
",",
"shell",
"... | Runs the command and arguments in the list as a background process. | [
"Runs",
"the",
"command",
"and",
"arguments",
"in",
"the",
"list",
"as",
"a",
"background",
"process",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L308-L317 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | function_call_with_timeout | def function_call_with_timeout(fun_name, fun_args, secs=5):
"""Run a Python function with a timeout. No interprocess communication or
return values are handled. Setting secs to 0 gives infinite timeout."""
from multiprocessing import Process, Queue
p = Process(target=fun_name, args=tuple(fun_args))
... | python | def function_call_with_timeout(fun_name, fun_args, secs=5):
"""Run a Python function with a timeout. No interprocess communication or
return values are handled. Setting secs to 0 gives infinite timeout."""
from multiprocessing import Process, Queue
p = Process(target=fun_name, args=tuple(fun_args))
... | [
"def",
"function_call_with_timeout",
"(",
"fun_name",
",",
"fun_args",
",",
"secs",
"=",
"5",
")",
":",
"from",
"multiprocessing",
"import",
"Process",
",",
"Queue",
"p",
"=",
"Process",
"(",
"target",
"=",
"fun_name",
",",
"args",
"=",
"tuple",
"(",
"fun_... | Run a Python function with a timeout. No interprocess communication or
return values are handled. Setting secs to 0 gives infinite timeout. | [
"Run",
"a",
"Python",
"function",
"with",
"a",
"timeout",
".",
"No",
"interprocess",
"communication",
"or",
"return",
"values",
"are",
"handled",
".",
"Setting",
"secs",
"to",
"0",
"gives",
"infinite",
"timeout",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L331-L349 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | fix_pdf_with_ghostscript_to_tmp_file | def fix_pdf_with_ghostscript_to_tmp_file(input_doc_fname):
"""Attempt to fix a bad PDF file with a Ghostscript command, writing the output
PDF to a temporary file and returning the filename. Caller is responsible for
deleting the file."""
if not gs_executable: init_and_test_gs_executable(exit_on_fail=... | python | def fix_pdf_with_ghostscript_to_tmp_file(input_doc_fname):
"""Attempt to fix a bad PDF file with a Ghostscript command, writing the output
PDF to a temporary file and returning the filename. Caller is responsible for
deleting the file."""
if not gs_executable: init_and_test_gs_executable(exit_on_fail=... | [
"def",
"fix_pdf_with_ghostscript_to_tmp_file",
"(",
"input_doc_fname",
")",
":",
"if",
"not",
"gs_executable",
":",
"init_and_test_gs_executable",
"(",
"exit_on_fail",
"=",
"True",
")",
"temp_file_name",
"=",
"get_temporary_filename",
"(",
"extension",
"=",
"\".pdf\"",
... | Attempt to fix a bad PDF file with a Ghostscript command, writing the output
PDF to a temporary file and returning the filename. Caller is responsible for
deleting the file. | [
"Attempt",
"to",
"fix",
"a",
"bad",
"PDF",
"file",
"with",
"a",
"Ghostscript",
"command",
"writing",
"the",
"output",
"PDF",
"to",
"a",
"temporary",
"file",
"and",
"returning",
"the",
"filename",
".",
"Caller",
"is",
"responsible",
"for",
"deleting",
"the",
... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L532-L554 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | get_bounding_box_list_ghostscript | def get_bounding_box_list_ghostscript(input_doc_fname, res_x, res_y, full_page_box):
"""Call Ghostscript to get the bounding box list. Cannot set a threshold
with this method."""
if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)
res = str(res_x) + "x" + str(res_y)
box_arg = "-dU... | python | def get_bounding_box_list_ghostscript(input_doc_fname, res_x, res_y, full_page_box):
"""Call Ghostscript to get the bounding box list. Cannot set a threshold
with this method."""
if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)
res = str(res_x) + "x" + str(res_y)
box_arg = "-dU... | [
"def",
"get_bounding_box_list_ghostscript",
"(",
"input_doc_fname",
",",
"res_x",
",",
"res_y",
",",
"full_page_box",
")",
":",
"if",
"not",
"gs_executable",
":",
"init_and_test_gs_executable",
"(",
"exit_on_fail",
"=",
"True",
")",
"res",
"=",
"str",
"(",
"res_x"... | Call Ghostscript to get the bounding box list. Cannot set a threshold
with this method. | [
"Call",
"Ghostscript",
"to",
"get",
"the",
"bounding",
"box",
"list",
".",
"Cannot",
"set",
"a",
"threshold",
"with",
"this",
"method",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L556-L602 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | render_pdf_file_to_image_files_pdftoppm_ppm | def render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name, root_output_file_path,
res_x=150, res_y=150, extra_args=None):
"""Use the pdftoppm program to render a PDF file to .png images. The
root_output_file_path is prepended to all the output files, which have nu... | python | def render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name, root_output_file_path,
res_x=150, res_y=150, extra_args=None):
"""Use the pdftoppm program to render a PDF file to .png images. The
root_output_file_path is prepended to all the output files, which have nu... | [
"def",
"render_pdf_file_to_image_files_pdftoppm_ppm",
"(",
"pdf_file_name",
",",
"root_output_file_path",
",",
"res_x",
"=",
"150",
",",
"res_y",
"=",
"150",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"[",... | Use the pdftoppm program to render a PDF file to .png images. The
root_output_file_path is prepended to all the output files, which have numbers
and extensions added. Extra arguments can be passed as a list in extra_args.
Return the command output. | [
"Use",
"the",
"pdftoppm",
"program",
"to",
"render",
"a",
"PDF",
"file",
"to",
".",
"png",
"images",
".",
"The",
"root_output_file_path",
"is",
"prepended",
"to",
"all",
"the",
"output",
"files",
"which",
"have",
"numbers",
"and",
"extensions",
"added",
".",... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L604-L624 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | render_pdf_file_to_image_files_pdftoppm_pgm | def render_pdf_file_to_image_files_pdftoppm_pgm(pdf_file_name, root_output_file_path,
res_x=150, res_y=150):
"""Same as renderPdfFileToImageFile_pdftoppm_ppm but with -gray option for pgm."""
comm_output = render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name,
... | python | def render_pdf_file_to_image_files_pdftoppm_pgm(pdf_file_name, root_output_file_path,
res_x=150, res_y=150):
"""Same as renderPdfFileToImageFile_pdftoppm_ppm but with -gray option for pgm."""
comm_output = render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name,
... | [
"def",
"render_pdf_file_to_image_files_pdftoppm_pgm",
"(",
"pdf_file_name",
",",
"root_output_file_path",
",",
"res_x",
"=",
"150",
",",
"res_y",
"=",
"150",
")",
":",
"comm_output",
"=",
"render_pdf_file_to_image_files_pdftoppm_ppm",
"(",
"pdf_file_name",
",",
"root_outp... | Same as renderPdfFileToImageFile_pdftoppm_ppm but with -gray option for pgm. | [
"Same",
"as",
"renderPdfFileToImageFile_pdftoppm_ppm",
"but",
"with",
"-",
"gray",
"option",
"for",
"pgm",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L626-L632 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | render_pdf_file_to_image_files__ghostscript_png | def render_pdf_file_to_image_files__ghostscript_png(pdf_file_name,
root_output_file_path,
res_x=150, res_y=150):
"""Use Ghostscript to render a PDF file to .png images. The root_output_file_path
is prepended... | python | def render_pdf_file_to_image_files__ghostscript_png(pdf_file_name,
root_output_file_path,
res_x=150, res_y=150):
"""Use Ghostscript to render a PDF file to .png images. The root_output_file_path
is prepended... | [
"def",
"render_pdf_file_to_image_files__ghostscript_png",
"(",
"pdf_file_name",
",",
"root_output_file_path",
",",
"res_x",
"=",
"150",
",",
"res_y",
"=",
"150",
")",
":",
"# For gs commands see",
"# http://ghostscript.com/doc/current/Devices.htm#File_formats",
"# http://ghostscr... | Use Ghostscript to render a PDF file to .png images. The root_output_file_path
is prepended to all the output files, which have numbers and extensions added.
Return the command output. | [
"Use",
"Ghostscript",
"to",
"render",
"a",
"PDF",
"file",
"to",
".",
"png",
"images",
".",
"The",
"root_output_file_path",
"is",
"prepended",
"to",
"all",
"the",
"output",
"files",
"which",
"have",
"numbers",
"and",
"extensions",
"added",
".",
"Return",
"the... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L634-L648 | train |
abarker/pdfCropMargins | src/pdfCropMargins/external_program_calls.py | show_preview | def show_preview(viewer_path, pdf_file_name):
"""Run the PDF viewer at the path viewer_path on the file pdf_file_name."""
try:
cmd = [viewer_path, pdf_file_name]
run_external_subprocess_in_background(cmd)
except (subprocess.CalledProcessError, OSError, IOError) as e:
print("\nWarning... | python | def show_preview(viewer_path, pdf_file_name):
"""Run the PDF viewer at the path viewer_path on the file pdf_file_name."""
try:
cmd = [viewer_path, pdf_file_name]
run_external_subprocess_in_background(cmd)
except (subprocess.CalledProcessError, OSError, IOError) as e:
print("\nWarning... | [
"def",
"show_preview",
"(",
"viewer_path",
",",
"pdf_file_name",
")",
":",
"try",
":",
"cmd",
"=",
"[",
"viewer_path",
",",
"pdf_file_name",
"]",
"run_external_subprocess_in_background",
"(",
"cmd",
")",
"except",
"(",
"subprocess",
".",
"CalledProcessError",
",",... | Run the PDF viewer at the path viewer_path on the file pdf_file_name. | [
"Run",
"the",
"PDF",
"viewer",
"at",
"the",
"path",
"viewer_path",
"on",
"the",
"file",
"pdf_file_name",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L673-L682 | train |
abarker/pdfCropMargins | src/pdfCropMargins/pdfCropMargins.py | main | def main():
"""Run main, catching any exceptions and cleaning up the temp directories."""
cleanup_and_exit = sys.exit # Function to do cleanup and exit before the import.
exit_code = 0
# Imports are done here inside the try block so some ugly (and useless)
# traceback info is avoided on user's ^C ... | python | def main():
"""Run main, catching any exceptions and cleaning up the temp directories."""
cleanup_and_exit = sys.exit # Function to do cleanup and exit before the import.
exit_code = 0
# Imports are done here inside the try block so some ugly (and useless)
# traceback info is avoided on user's ^C ... | [
"def",
"main",
"(",
")",
":",
"cleanup_and_exit",
"=",
"sys",
".",
"exit",
"# Function to do cleanup and exit before the import.",
"exit_code",
"=",
"0",
"# Imports are done here inside the try block so some ugly (and useless)",
"# traceback info is avoided on user's ^C (KeyboardInterr... | Run main, catching any exceptions and cleaning up the temp directories. | [
"Run",
"main",
"catching",
"any",
"exceptions",
"and",
"cleaning",
"up",
"the",
"temp",
"directories",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/pdfCropMargins.py#L70-L113 | train |
abarker/pdfCropMargins | src/pdfCropMargins/main_pdfCropMargins.py | get_full_page_box_list_assigning_media_and_crop | def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False):
"""Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format.""... | python | def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False):
"""Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format.""... | [
"def",
"get_full_page_box_list_assigning_media_and_crop",
"(",
"input_doc",
",",
"quiet",
"=",
"False",
")",
":",
"full_page_box_list",
"=",
"[",
"]",
"rotation_list",
"=",
"[",
"]",
"if",
"args",
".",
"verbose",
"and",
"not",
"quiet",
":",
"print",
"(",
"\"\\... | Get a list of all the full-page box values for each page. The argument
input_doc should be a PdfFileReader object. The boxes on the list are in the
simple 4-float list format used by this program, not RectangleObject format. | [
"Get",
"a",
"list",
"of",
"all",
"the",
"full",
"-",
"page",
"box",
"values",
"for",
"each",
"page",
".",
"The",
"argument",
"input_doc",
"should",
"be",
"a",
"PdfFileReader",
"object",
".",
"The",
"boxes",
"on",
"the",
"list",
"are",
"in",
"the",
"sim... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/main_pdfCropMargins.py#L207-L236 | train |
abarker/pdfCropMargins | src/pdfCropMargins/main_pdfCropMargins.py | set_cropped_metadata | def set_cropped_metadata(input_doc, output_doc, metadata_info):
"""Set the metadata for the output document. Mostly just copied over, but
"Producer" has a string appended to indicate that this program modified the
file. That allows for the undo operation to make sure that this
program cropped the file... | python | def set_cropped_metadata(input_doc, output_doc, metadata_info):
"""Set the metadata for the output document. Mostly just copied over, but
"Producer" has a string appended to indicate that this program modified the
file. That allows for the undo operation to make sure that this
program cropped the file... | [
"def",
"set_cropped_metadata",
"(",
"input_doc",
",",
"output_doc",
",",
"metadata_info",
")",
":",
"# Setting metadata with pyPdf requires low-level pyPdf operations, see",
"# http://stackoverflow.com/questions/2574676/change-metadata-of-pdf-file-with-pypdf",
"if",
"not",
"metadata_info... | Set the metadata for the output document. Mostly just copied over, but
"Producer" has a string appended to indicate that this program modified the
file. That allows for the undo operation to make sure that this
program cropped the file in the first place. | [
"Set",
"the",
"metadata",
"for",
"the",
"output",
"document",
".",
"Mostly",
"just",
"copied",
"over",
"but",
"Producer",
"has",
"a",
"string",
"appended",
"to",
"indicate",
"that",
"this",
"program",
"modified",
"the",
"file",
".",
"That",
"allows",
"for",
... | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/main_pdfCropMargins.py#L448-L494 | train |
abarker/pdfCropMargins | src/pdfCropMargins/main_pdfCropMargins.py | apply_crop_list | def apply_crop_list(crop_list, input_doc, page_nums_to_crop,
already_cropped_by_this_program):
"""Apply the crop list to the pages of the input PdfFileReader object."""
if args.restore and not already_cropped_by_this_program:
print("\nWarning from pdfCropMargin... | python | def apply_crop_list(crop_list, input_doc, page_nums_to_crop,
already_cropped_by_this_program):
"""Apply the crop list to the pages of the input PdfFileReader object."""
if args.restore and not already_cropped_by_this_program:
print("\nWarning from pdfCropMargin... | [
"def",
"apply_crop_list",
"(",
"crop_list",
",",
"input_doc",
",",
"page_nums_to_crop",
",",
"already_cropped_by_this_program",
")",
":",
"if",
"args",
".",
"restore",
"and",
"not",
"already_cropped_by_this_program",
":",
"print",
"(",
"\"\\nWarning from pdfCropMargins: T... | Apply the crop list to the pages of the input PdfFileReader object. | [
"Apply",
"the",
"crop",
"list",
"to",
"the",
"pages",
"of",
"the",
"input",
"PdfFileReader",
"object",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/main_pdfCropMargins.py#L497-L562 | train |
abarker/pdfCropMargins | src/pdfCropMargins/main_pdfCropMargins.py | setup_output_document | def setup_output_document(input_doc, tmp_input_doc, metadata_info,
copy_document_catalog=True):
"""Create the output `PdfFileWriter` objects and copy over the relevant info."""
# NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters
# see... | python | def setup_output_document(input_doc, tmp_input_doc, metadata_info,
copy_document_catalog=True):
"""Create the output `PdfFileWriter` objects and copy over the relevant info."""
# NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters
# see... | [
"def",
"setup_output_document",
"(",
"input_doc",
",",
"tmp_input_doc",
",",
"metadata_info",
",",
"copy_document_catalog",
"=",
"True",
")",
":",
"# NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters",
"# seems to cause problems (writer can hang on write), so only... | Create the output `PdfFileWriter` objects and copy over the relevant info. | [
"Create",
"the",
"output",
"PdfFileWriter",
"objects",
"and",
"copy",
"over",
"the",
"relevant",
"info",
"."
] | 55aca874613750ebf4ae69fd8851bdbb7696d6ac | https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/main_pdfCropMargins.py#L564-L689 | train |
miracle2k/flask-assets | src/flask_assets.py | FlaskConfigStorage.setdefault | def setdefault(self, key, value):
"""We may not always be connected to an app, but we still need
to provide a way to the base environment to set it's defaults.
"""
try:
super(FlaskConfigStorage, self).setdefault(key, value)
except RuntimeError:
self._defau... | python | def setdefault(self, key, value):
"""We may not always be connected to an app, but we still need
to provide a way to the base environment to set it's defaults.
"""
try:
super(FlaskConfigStorage, self).setdefault(key, value)
except RuntimeError:
self._defau... | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"super",
"(",
"FlaskConfigStorage",
",",
"self",
")",
".",
"setdefault",
"(",
"key",
",",
"value",
")",
"except",
"RuntimeError",
":",
"self",
".",
"_defaults",
".",
"__s... | We may not always be connected to an app, but we still need
to provide a way to the base environment to set it's defaults. | [
"We",
"may",
"not",
"always",
"be",
"connected",
"to",
"an",
"app",
"but",
"we",
"still",
"need",
"to",
"provide",
"a",
"way",
"to",
"the",
"base",
"environment",
"to",
"set",
"it",
"s",
"defaults",
"."
] | ea9ff985bc96b79edb12ad4bed69403173f75562 | https://github.com/miracle2k/flask-assets/blob/ea9ff985bc96b79edb12ad4bed69403173f75562/src/flask_assets.py#L75-L82 | train |
miracle2k/flask-assets | src/flask_assets.py | Environment._app | def _app(self):
"""The application object to work with; this is either the app
that we have been bound to, or the current application.
"""
if self.app is not None:
return self.app
ctx = _request_ctx_stack.top
if ctx is not None:
return ctx.app
... | python | def _app(self):
"""The application object to work with; this is either the app
that we have been bound to, or the current application.
"""
if self.app is not None:
return self.app
ctx = _request_ctx_stack.top
if ctx is not None:
return ctx.app
... | [
"def",
"_app",
"(",
"self",
")",
":",
"if",
"self",
".",
"app",
"is",
"not",
"None",
":",
"return",
"self",
".",
"app",
"ctx",
"=",
"_request_ctx_stack",
".",
"top",
"if",
"ctx",
"is",
"not",
"None",
":",
"return",
"ctx",
".",
"app",
"try",
":",
... | The application object to work with; this is either the app
that we have been bound to, or the current application. | [
"The",
"application",
"object",
"to",
"work",
"with",
";",
"this",
"is",
"either",
"the",
"app",
"that",
"we",
"have",
"been",
"bound",
"to",
"or",
"the",
"current",
"application",
"."
] | ea9ff985bc96b79edb12ad4bed69403173f75562 | https://github.com/miracle2k/flask-assets/blob/ea9ff985bc96b79edb12ad4bed69403173f75562/src/flask_assets.py#L310-L330 | train |
miracle2k/flask-assets | src/flask_assets.py | Environment.from_yaml | def from_yaml(self, path):
"""Register bundles from a YAML configuration file"""
bundles = YAMLLoader(path).load_bundles()
for name in bundles:
self.register(name, bundles[name]) | python | def from_yaml(self, path):
"""Register bundles from a YAML configuration file"""
bundles = YAMLLoader(path).load_bundles()
for name in bundles:
self.register(name, bundles[name]) | [
"def",
"from_yaml",
"(",
"self",
",",
"path",
")",
":",
"bundles",
"=",
"YAMLLoader",
"(",
"path",
")",
".",
"load_bundles",
"(",
")",
"for",
"name",
"in",
"bundles",
":",
"self",
".",
"register",
"(",
"name",
",",
"bundles",
"[",
"name",
"]",
")"
] | Register bundles from a YAML configuration file | [
"Register",
"bundles",
"from",
"a",
"YAML",
"configuration",
"file"
] | ea9ff985bc96b79edb12ad4bed69403173f75562 | https://github.com/miracle2k/flask-assets/blob/ea9ff985bc96b79edb12ad4bed69403173f75562/src/flask_assets.py#L361-L365 | train |
miracle2k/flask-assets | src/flask_assets.py | Environment.from_module | def from_module(self, path):
"""Register bundles from a Python module"""
bundles = PythonLoader(path).load_bundles()
for name in bundles:
self.register(name, bundles[name]) | python | def from_module(self, path):
"""Register bundles from a Python module"""
bundles = PythonLoader(path).load_bundles()
for name in bundles:
self.register(name, bundles[name]) | [
"def",
"from_module",
"(",
"self",
",",
"path",
")",
":",
"bundles",
"=",
"PythonLoader",
"(",
"path",
")",
".",
"load_bundles",
"(",
")",
"for",
"name",
"in",
"bundles",
":",
"self",
".",
"register",
"(",
"name",
",",
"bundles",
"[",
"name",
"]",
")... | Register bundles from a Python module | [
"Register",
"bundles",
"from",
"a",
"Python",
"module"
] | ea9ff985bc96b79edb12ad4bed69403173f75562 | https://github.com/miracle2k/flask-assets/blob/ea9ff985bc96b79edb12ad4bed69403173f75562/src/flask_assets.py#L367-L371 | train |
persephone-tools/persephone | persephone/__init__.py | handle_unhandled_exception | def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
"""Handler for unhandled exceptions that will write to the logs"""
if issubclass(exc_type, KeyboardInterrupt):
# call the default excepthook saved at __excepthook__
sys.__excepthook__(exc_type, exc_value, exc_traceback)
... | python | def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
"""Handler for unhandled exceptions that will write to the logs"""
if issubclass(exc_type, KeyboardInterrupt):
# call the default excepthook saved at __excepthook__
sys.__excepthook__(exc_type, exc_value, exc_traceback)
... | [
"def",
"handle_unhandled_exception",
"(",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
":",
"if",
"issubclass",
"(",
"exc_type",
",",
"KeyboardInterrupt",
")",
":",
"# call the default excepthook saved at __excepthook__",
"sys",
".",
"__excepthook__",
"(",
"... | Handler for unhandled exceptions that will write to the logs | [
"Handler",
"for",
"unhandled",
"exceptions",
"that",
"will",
"write",
"to",
"the",
"logs"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/__init__.py#L6-L13 | train |
persephone-tools/persephone | persephone/utterance.py | write_transcriptions | def write_transcriptions(utterances: List[Utterance],
tgt_dir: Path, ext: str, lazy: bool) -> None:
""" Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
... | python | def write_transcriptions(utterances: List[Utterance],
tgt_dir: Path, ext: str, lazy: bool) -> None:
""" Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
... | [
"def",
"write_transcriptions",
"(",
"utterances",
":",
"List",
"[",
"Utterance",
"]",
",",
"tgt_dir",
":",
"Path",
",",
"ext",
":",
"str",
",",
"lazy",
":",
"bool",
")",
"->",
"None",
":",
"tgt_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"e... | Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
tgt_dir: The directory in which to write the text of the utterances,
one file per utterance.
ext: The file ... | [
"Write",
"the",
"utterance",
"transcriptions",
"to",
"files",
"in",
"the",
"tgt_dir",
".",
"Is",
"lazy",
"and",
"checks",
"if",
"the",
"file",
"already",
"exists",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utterance.py#L45-L65 | train |
persephone-tools/persephone | persephone/utterance.py | remove_duplicates | def remove_duplicates(utterances: List[Utterance]) -> List[Utterance]:
""" Removes utterances with the same start_time, end_time and text. Other
metadata isn't considered.
"""
filtered_utters = []
utter_set = set() # type: Set[Tuple[int, int, str]]
for utter in utterances:
if (utter.sta... | python | def remove_duplicates(utterances: List[Utterance]) -> List[Utterance]:
""" Removes utterances with the same start_time, end_time and text. Other
metadata isn't considered.
"""
filtered_utters = []
utter_set = set() # type: Set[Tuple[int, int, str]]
for utter in utterances:
if (utter.sta... | [
"def",
"remove_duplicates",
"(",
"utterances",
":",
"List",
"[",
"Utterance",
"]",
")",
"->",
"List",
"[",
"Utterance",
"]",
":",
"filtered_utters",
"=",
"[",
"]",
"utter_set",
"=",
"set",
"(",
")",
"# type: Set[Tuple[int, int, str]]",
"for",
"utter",
"in",
... | Removes utterances with the same start_time, end_time and text. Other
metadata isn't considered. | [
"Removes",
"utterances",
"with",
"the",
"same",
"start_time",
"end_time",
"and",
"text",
".",
"Other",
"metadata",
"isn",
"t",
"considered",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utterance.py#L67-L80 | train |
persephone-tools/persephone | persephone/utterance.py | make_speaker_utters | def make_speaker_utters(utterances: List[Utterance]) -> Dict[str, List[Utterance]]:
""" Creates a dictionary mapping from speakers to their utterances. """
speaker_utters = defaultdict(list) # type: DefaultDict[str, List[Utterance]]
for utter in utterances:
speaker_utters[utter.speaker].append(utte... | python | def make_speaker_utters(utterances: List[Utterance]) -> Dict[str, List[Utterance]]:
""" Creates a dictionary mapping from speakers to their utterances. """
speaker_utters = defaultdict(list) # type: DefaultDict[str, List[Utterance]]
for utter in utterances:
speaker_utters[utter.speaker].append(utte... | [
"def",
"make_speaker_utters",
"(",
"utterances",
":",
"List",
"[",
"Utterance",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"Utterance",
"]",
"]",
":",
"speaker_utters",
"=",
"defaultdict",
"(",
"list",
")",
"# type: DefaultDict[str, List[Utterance]]",... | Creates a dictionary mapping from speakers to their utterances. | [
"Creates",
"a",
"dictionary",
"mapping",
"from",
"speakers",
"to",
"their",
"utterances",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utterance.py#L106-L113 | train |
persephone-tools/persephone | persephone/utterance.py | remove_too_short | def remove_too_short(utterances: List[Utterance],
_winlen=25, winstep=10) -> List[Utterance]:
""" Removes utterances that will probably have issues with CTC because of
the number of frames being less than the number of tokens in the
transcription. Assuming char tokenization to minimize ... | python | def remove_too_short(utterances: List[Utterance],
_winlen=25, winstep=10) -> List[Utterance]:
""" Removes utterances that will probably have issues with CTC because of
the number of frames being less than the number of tokens in the
transcription. Assuming char tokenization to minimize ... | [
"def",
"remove_too_short",
"(",
"utterances",
":",
"List",
"[",
"Utterance",
"]",
",",
"_winlen",
"=",
"25",
",",
"winstep",
"=",
"10",
")",
"->",
"List",
"[",
"Utterance",
"]",
":",
"def",
"is_too_short",
"(",
"utterance",
":",
"Utterance",
")",
"->",
... | Removes utterances that will probably have issues with CTC because of
the number of frames being less than the number of tokens in the
transcription. Assuming char tokenization to minimize false negatives. | [
"Removes",
"utterances",
"that",
"will",
"probably",
"have",
"issues",
"with",
"CTC",
"because",
"of",
"the",
"number",
"of",
"frames",
"being",
"less",
"than",
"the",
"number",
"of",
"tokens",
"in",
"the",
"transcription",
".",
"Assuming",
"char",
"tokenizati... | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utterance.py#L128-L141 | train |
persephone-tools/persephone | persephone/distance.py | min_edit_distance | def min_edit_distance(
source: Sequence[T], target: Sequence[T],
ins_cost: Callable[..., int] = lambda _x: 1,
del_cost: Callable[..., int] = lambda _x: 1,
sub_cost: Callable[..., int] = lambda x, y: 0 if x == y else 1) -> int:
"""Calculates the minimum edit distance between two seque... | python | def min_edit_distance(
source: Sequence[T], target: Sequence[T],
ins_cost: Callable[..., int] = lambda _x: 1,
del_cost: Callable[..., int] = lambda _x: 1,
sub_cost: Callable[..., int] = lambda x, y: 0 if x == y else 1) -> int:
"""Calculates the minimum edit distance between two seque... | [
"def",
"min_edit_distance",
"(",
"source",
":",
"Sequence",
"[",
"T",
"]",
",",
"target",
":",
"Sequence",
"[",
"T",
"]",
",",
"ins_cost",
":",
"Callable",
"[",
"...",
",",
"int",
"]",
"=",
"lambda",
"_x",
":",
"1",
",",
"del_cost",
":",
"Callable",
... | Calculates the minimum edit distance between two sequences.
Uses the Levenshtein weighting as a default, but offers keyword arguments
to supply functions to measure the costs for editing with different
elements.
Args:
ins_cost: A function describing the cost of inserting a given char
d... | [
"Calculates",
"the",
"minimum",
"edit",
"distance",
"between",
"two",
"sequences",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/distance.py#L9-L51 | train |
persephone-tools/persephone | persephone/distance.py | word_error_rate | def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float:
""" Calculate the word error rate of a sequence against a reference.
Args:
ref: The gold-standard reference sequence
hyp: The hypothesis to be evaluated against the reference.
Returns:
The word error rate of the supp... | python | def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float:
""" Calculate the word error rate of a sequence against a reference.
Args:
ref: The gold-standard reference sequence
hyp: The hypothesis to be evaluated against the reference.
Returns:
The word error rate of the supp... | [
"def",
"word_error_rate",
"(",
"ref",
":",
"Sequence",
"[",
"T",
"]",
",",
"hyp",
":",
"Sequence",
"[",
"T",
"]",
")",
"->",
"float",
":",
"if",
"len",
"(",
"ref",
")",
"==",
"0",
":",
"raise",
"EmptyReferenceException",
"(",
"\"Cannot calculating word e... | Calculate the word error rate of a sequence against a reference.
Args:
ref: The gold-standard reference sequence
hyp: The hypothesis to be evaluated against the reference.
Returns:
The word error rate of the supplied hypothesis with respect to the
reference string.
Raises:... | [
"Calculate",
"the",
"word",
"error",
"rate",
"of",
"a",
"sequence",
"against",
"a",
"reference",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/distance.py#L178-L200 | train |
persephone-tools/persephone | persephone/model.py | dense_to_human_readable | def dense_to_human_readable(dense_repr: Sequence[Sequence[int]], index_to_label: Dict[int, str]) -> List[List[str]]:
""" Converts a dense representation of model decoded output into human
readable, using a mapping from indices to labels. """
transcripts = []
for dense_r in dense_repr:
non_empty... | python | def dense_to_human_readable(dense_repr: Sequence[Sequence[int]], index_to_label: Dict[int, str]) -> List[List[str]]:
""" Converts a dense representation of model decoded output into human
readable, using a mapping from indices to labels. """
transcripts = []
for dense_r in dense_repr:
non_empty... | [
"def",
"dense_to_human_readable",
"(",
"dense_repr",
":",
"Sequence",
"[",
"Sequence",
"[",
"int",
"]",
"]",
",",
"index_to_label",
":",
"Dict",
"[",
"int",
",",
"str",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"transcripts",
"=",... | Converts a dense representation of model decoded output into human
readable, using a mapping from indices to labels. | [
"Converts",
"a",
"dense",
"representation",
"of",
"model",
"decoded",
"output",
"into",
"human",
"readable",
"using",
"a",
"mapping",
"from",
"indices",
"to",
"labels",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/model.py#L36-L46 | train |
persephone-tools/persephone | persephone/model.py | decode | def decode(model_path_prefix: Union[str, Path],
input_paths: Sequence[Path],
label_set: Set[str],
*,
feature_type: str = "fbank", #TODO Make this None and infer feature_type from dimension of NN input layer.
batch_size: int = 64,
feat_dir: Optional[Path]... | python | def decode(model_path_prefix: Union[str, Path],
input_paths: Sequence[Path],
label_set: Set[str],
*,
feature_type: str = "fbank", #TODO Make this None and infer feature_type from dimension of NN input layer.
batch_size: int = 64,
feat_dir: Optional[Path]... | [
"def",
"decode",
"(",
"model_path_prefix",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"input_paths",
":",
"Sequence",
"[",
"Path",
"]",
",",
"label_set",
":",
"Set",
"[",
"str",
"]",
",",
"*",
",",
"feature_type",
":",
"str",
"=",
"\"fbank\"",
... | Use an existing tensorflow model that exists on disk to decode
WAV files.
Args:
model_path_prefix: The path to the saved tensorflow model.
This is the full prefix to the ".ckpt" file.
input_paths: A sequence of `pathlib.Path`s to WAV files to put through
... | [
"Use",
"an",
"existing",
"tensorflow",
"model",
"that",
"exists",
"on",
"disk",
"to",
"decode",
"WAV",
"files",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/model.py#L68-L153 | train |
persephone-tools/persephone | persephone/model.py | Model.eval | def eval(self, restore_model_path: Optional[str]=None) -> None:
""" Evaluates the model on a test set."""
saver = tf.train.Saver()
with tf.Session(config=allow_growth_config) as sess:
if restore_model_path:
logger.info("restoring model from %s", restore_model_path)
... | python | def eval(self, restore_model_path: Optional[str]=None) -> None:
""" Evaluates the model on a test set."""
saver = tf.train.Saver()
with tf.Session(config=allow_growth_config) as sess:
if restore_model_path:
logger.info("restoring model from %s", restore_model_path)
... | [
"def",
"eval",
"(",
"self",
",",
"restore_model_path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"with",
"tf",
".",
"Session",
"(",
"config",
"=",
"allow_growth_co... | Evaluates the model on a test set. | [
"Evaluates",
"the",
"model",
"on",
"a",
"test",
"set",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/model.py#L258-L299 | train |
persephone-tools/persephone | persephone/model.py | Model.output_best_scores | def output_best_scores(self, best_epoch_str: str) -> None:
"""Output best scores to the filesystem"""
BEST_SCORES_FILENAME = "best_scores.txt"
with open(os.path.join(self.exp_dir, BEST_SCORES_FILENAME),
"w", encoding=ENCODING) as best_f:
print(best_epoch_str, file=b... | python | def output_best_scores(self, best_epoch_str: str) -> None:
"""Output best scores to the filesystem"""
BEST_SCORES_FILENAME = "best_scores.txt"
with open(os.path.join(self.exp_dir, BEST_SCORES_FILENAME),
"w", encoding=ENCODING) as best_f:
print(best_epoch_str, file=b... | [
"def",
"output_best_scores",
"(",
"self",
",",
"best_epoch_str",
":",
"str",
")",
"->",
"None",
":",
"BEST_SCORES_FILENAME",
"=",
"\"best_scores.txt\"",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"exp_dir",
",",
"BEST_SCORES_FILENAM... | Output best scores to the filesystem | [
"Output",
"best",
"scores",
"to",
"the",
"filesystem"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/model.py#L301-L306 | train |
persephone-tools/persephone | persephone/corpus.py | ensure_no_set_overlap | def ensure_no_set_overlap(train: Sequence[str], valid: Sequence[str], test: Sequence[str]) -> None:
""" Ensures no test set data has creeped into the training set."""
logger.debug("Ensuring that the training, validation and test data sets have no overlap")
train_s = set(train)
valid_s = set(valid)
... | python | def ensure_no_set_overlap(train: Sequence[str], valid: Sequence[str], test: Sequence[str]) -> None:
""" Ensures no test set data has creeped into the training set."""
logger.debug("Ensuring that the training, validation and test data sets have no overlap")
train_s = set(train)
valid_s = set(valid)
... | [
"def",
"ensure_no_set_overlap",
"(",
"train",
":",
"Sequence",
"[",
"str",
"]",
",",
"valid",
":",
"Sequence",
"[",
"str",
"]",
",",
"test",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Ensuring that the train... | Ensures no test set data has creeped into the training set. | [
"Ensures",
"no",
"test",
"set",
"data",
"has",
"creeped",
"into",
"the",
"training",
"set",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L31-L47 | train |
persephone-tools/persephone | persephone/corpus.py | get_untranscribed_prefixes_from_file | def get_untranscribed_prefixes_from_file(target_directory: Path) -> List[str]:
"""
The file "untranscribed_prefixes.txt" will specify prefixes which
do not have an associated transcription file if placed in the target directory.
This will fetch those prefixes from that file and will return an empty
... | python | def get_untranscribed_prefixes_from_file(target_directory: Path) -> List[str]:
"""
The file "untranscribed_prefixes.txt" will specify prefixes which
do not have an associated transcription file if placed in the target directory.
This will fetch those prefixes from that file and will return an empty
... | [
"def",
"get_untranscribed_prefixes_from_file",
"(",
"target_directory",
":",
"Path",
")",
"->",
"List",
"[",
"str",
"]",
":",
"untranscribed_prefix_fn",
"=",
"target_directory",
"/",
"\"untranscribed_prefixes.txt\"",
"if",
"untranscribed_prefix_fn",
".",
"exists",
"(",
... | The file "untranscribed_prefixes.txt" will specify prefixes which
do not have an associated transcription file if placed in the target directory.
This will fetch those prefixes from that file and will return an empty
list if that file does not exist.
See find_untranscribed_wavs function for finding un... | [
"The",
"file",
"untranscribed_prefixes",
".",
"txt",
"will",
"specify",
"prefixes",
"which",
"do",
"not",
"have",
"an",
"associated",
"transcription",
"file",
"if",
"placed",
"in",
"the",
"target",
"directory",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L69-L94 | train |
persephone-tools/persephone | persephone/corpus.py | determine_labels | def determine_labels(target_dir: Path, label_type: str) -> Set[str]:
""" Returns a set of all phonemes found in the corpus. Assumes that WAV files and
label files are split into utterances and segregated in a directory which contains a
"wav" subdirectory and "label" subdirectory.
Arguments:
tar... | python | def determine_labels(target_dir: Path, label_type: str) -> Set[str]:
""" Returns a set of all phonemes found in the corpus. Assumes that WAV files and
label files are split into utterances and segregated in a directory which contains a
"wav" subdirectory and "label" subdirectory.
Arguments:
tar... | [
"def",
"determine_labels",
"(",
"target_dir",
":",
"Path",
",",
"label_type",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"logger",
".",
"info",
"(",
"\"Finding phonemes of type %s in directory %s\"",
",",
"label_type",
",",
"target_dir",
")",
"label_dir... | Returns a set of all phonemes found in the corpus. Assumes that WAV files and
label files are split into utterances and segregated in a directory which contains a
"wav" subdirectory and "label" subdirectory.
Arguments:
target_dir: A `Path` to the directory where the corpus data is found
lab... | [
"Returns",
"a",
"set",
"of",
"all",
"phonemes",
"found",
"in",
"the",
"corpus",
".",
"Assumes",
"that",
"WAV",
"files",
"and",
"label",
"files",
"are",
"split",
"into",
"utterances",
"and",
"segregated",
"in",
"a",
"directory",
"which",
"contains",
"a",
"w... | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L617-L645 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.from_elan | def from_elan(cls: Type[CorpusT], org_dir: Path, tgt_dir: Path,
feat_type: str = "fbank", label_type: str = "phonemes",
utterance_filter: Callable[[Utterance], bool] = None,
label_segmenter: Optional[LabelSegmenter] = None,
speakers: List[str] = No... | python | def from_elan(cls: Type[CorpusT], org_dir: Path, tgt_dir: Path,
feat_type: str = "fbank", label_type: str = "phonemes",
utterance_filter: Callable[[Utterance], bool] = None,
label_segmenter: Optional[LabelSegmenter] = None,
speakers: List[str] = No... | [
"def",
"from_elan",
"(",
"cls",
":",
"Type",
"[",
"CorpusT",
"]",
",",
"org_dir",
":",
"Path",
",",
"tgt_dir",
":",
"Path",
",",
"feat_type",
":",
"str",
"=",
"\"fbank\"",
",",
"label_type",
":",
"str",
"=",
"\"phonemes\"",
",",
"utterance_filter",
":",
... | Construct a `Corpus` from ELAN files.
Args:
org_dir: A path to the directory containing the unpreprocessed
data.
tgt_dir: A path to the directory where the preprocessed data will
be stored.
feat_type: A string describing the input speech featu... | [
"Construct",
"a",
"Corpus",
"from",
"ELAN",
"files",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L236-L315 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.set_and_check_directories | def set_and_check_directories(self, tgt_dir: Path) -> None:
"""
Make sure that the required directories exist in the target directory.
set variables accordingly.
"""
logger.info("Setting up directories for corpus in %s", tgt_dir)
# Check directories exist.
if not... | python | def set_and_check_directories(self, tgt_dir: Path) -> None:
"""
Make sure that the required directories exist in the target directory.
set variables accordingly.
"""
logger.info("Setting up directories for corpus in %s", tgt_dir)
# Check directories exist.
if not... | [
"def",
"set_and_check_directories",
"(",
"self",
",",
"tgt_dir",
":",
"Path",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"Setting up directories for corpus in %s\"",
",",
"tgt_dir",
")",
"# Check directories exist.",
"if",
"not",
"tgt_dir",
".",
"is_dir",... | Make sure that the required directories exist in the target directory.
set variables accordingly. | [
"Make",
"sure",
"that",
"the",
"required",
"directories",
"exist",
"in",
"the",
"target",
"directory",
".",
"set",
"variables",
"accordingly",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L338-L355 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.