repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
edx/XBlock | xblock/fields.py | Field.from_string | def from_string(self, serialized):
"""
Returns a native value from a YAML serialized string representation.
Since YAML is a superset of JSON, this is the inverse of to_string.)
"""
self._warn_deprecated_outside_JSONField()
value = yaml.safe_load(serialized)
return self.enforce_type(value) | python | def from_string(self, serialized):
"""
Returns a native value from a YAML serialized string representation.
Since YAML is a superset of JSON, this is the inverse of to_string.)
"""
self._warn_deprecated_outside_JSONField()
value = yaml.safe_load(serialized)
return self.enforce_type(value) | [
"def",
"from_string",
"(",
"self",
",",
"serialized",
")",
":",
"self",
".",
"_warn_deprecated_outside_JSONField",
"(",
")",
"value",
"=",
"yaml",
".",
"safe_load",
"(",
"serialized",
")",
"return",
"self",
".",
"enforce_type",
"(",
"value",
")"
] | Returns a native value from a YAML serialized string representation.
Since YAML is a superset of JSON, this is the inverse of to_string.) | [
"Returns",
"a",
"native",
"value",
"from",
"a",
"YAML",
"serialized",
"string",
"representation",
".",
"Since",
"YAML",
"is",
"a",
"superset",
"of",
"JSON",
"this",
"is",
"the",
"inverse",
"of",
"to_string",
".",
")"
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L637-L644 | train | 234,800 |
edx/XBlock | xblock/fields.py | Field.read_json | def read_json(self, xblock):
"""
Retrieve the serialized value for this field from the specified xblock
"""
self._warn_deprecated_outside_JSONField()
return self.to_json(self.read_from(xblock)) | python | def read_json(self, xblock):
"""
Retrieve the serialized value for this field from the specified xblock
"""
self._warn_deprecated_outside_JSONField()
return self.to_json(self.read_from(xblock)) | [
"def",
"read_json",
"(",
"self",
",",
"xblock",
")",
":",
"self",
".",
"_warn_deprecated_outside_JSONField",
"(",
")",
"return",
"self",
".",
"to_json",
"(",
"self",
".",
"read_from",
"(",
"xblock",
")",
")"
] | Retrieve the serialized value for this field from the specified xblock | [
"Retrieve",
"the",
"serialized",
"value",
"for",
"this",
"field",
"from",
"the",
"specified",
"xblock"
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L664-L669 | train | 234,801 |
edx/XBlock | xblock/fields.py | Field.is_set_on | def is_set_on(self, xblock):
"""
Return whether this field has a non-default value on the supplied xblock
"""
# pylint: disable=protected-access
return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name) | python | def is_set_on(self, xblock):
"""
Return whether this field has a non-default value on the supplied xblock
"""
# pylint: disable=protected-access
return self._is_dirty(xblock) or xblock._field_data.has(xblock, self.name) | [
"def",
"is_set_on",
"(",
"self",
",",
"xblock",
")",
":",
"# pylint: disable=protected-access",
"return",
"self",
".",
"_is_dirty",
"(",
"xblock",
")",
"or",
"xblock",
".",
"_field_data",
".",
"has",
"(",
"xblock",
",",
"self",
".",
"name",
")"
] | Return whether this field has a non-default value on the supplied xblock | [
"Return",
"whether",
"this",
"field",
"has",
"a",
"non",
"-",
"default",
"value",
"on",
"the",
"supplied",
"xblock"
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L683-L688 | train | 234,802 |
edx/XBlock | xblock/fields.py | String.to_string | def to_string(self, value):
"""String gets serialized and deserialized without quote marks."""
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
return self.to_json(value) | python | def to_string(self, value):
"""String gets serialized and deserialized without quote marks."""
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
return self.to_json(value) | [
"def",
"to_string",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"self",
".",
"to_json",
"(",
"value",
")"
] | String gets serialized and deserialized without quote marks. | [
"String",
"gets",
"serialized",
"and",
"deserialized",
"without",
"quote",
"marks",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L904-L908 | train | 234,803 |
edx/XBlock | xblock/fields.py | DateTime.from_json | def from_json(self, value):
"""
Parse the date from an ISO-formatted date string, or None.
"""
if value is None:
return None
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
if isinstance(value, six.text_type):
# Parser interprets empty string as now by default
if value == "":
return None
try:
value = dateutil.parser.parse(value)
except (TypeError, ValueError):
raise ValueError("Could not parse {} as a date".format(value))
if not isinstance(value, datetime.datetime):
raise TypeError(
"Value should be loaded from a string, a datetime object or None, not {}".format(type(value))
)
if value.tzinfo is not None: # pylint: disable=maybe-no-member
return value.astimezone(pytz.utc) # pylint: disable=maybe-no-member
else:
return value.replace(tzinfo=pytz.utc) | python | def from_json(self, value):
"""
Parse the date from an ISO-formatted date string, or None.
"""
if value is None:
return None
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
if isinstance(value, six.text_type):
# Parser interprets empty string as now by default
if value == "":
return None
try:
value = dateutil.parser.parse(value)
except (TypeError, ValueError):
raise ValueError("Could not parse {} as a date".format(value))
if not isinstance(value, datetime.datetime):
raise TypeError(
"Value should be loaded from a string, a datetime object or None, not {}".format(type(value))
)
if value.tzinfo is not None: # pylint: disable=maybe-no-member
return value.astimezone(pytz.utc) # pylint: disable=maybe-no-member
else:
return value.replace(tzinfo=pytz.utc) | [
"def",
"from_json",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"binary_type",
")",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"# Parser interprets empty string as now by default",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"try",
":",
"value",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"\"Could not parse {} as a date\"",
".",
"format",
"(",
"value",
")",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"Value should be loaded from a string, a datetime object or None, not {}\"",
".",
"format",
"(",
"type",
"(",
"value",
")",
")",
")",
"if",
"value",
".",
"tzinfo",
"is",
"not",
"None",
":",
"# pylint: disable=maybe-no-member",
"return",
"value",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
"# pylint: disable=maybe-no-member",
"else",
":",
"return",
"value",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")"
] | Parse the date from an ISO-formatted date string, or None. | [
"Parse",
"the",
"date",
"from",
"an",
"ISO",
"-",
"formatted",
"date",
"string",
"or",
"None",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L954-L981 | train | 234,804 |
edx/XBlock | xblock/fields.py | DateTime.to_json | def to_json(self, value):
"""
Serialize the date as an ISO-formatted date string, or None.
"""
if isinstance(value, datetime.datetime):
return value.strftime(self.DATETIME_FORMAT)
if value is None:
return None
raise TypeError("Value stored must be a datetime object, not {}".format(type(value))) | python | def to_json(self, value):
"""
Serialize the date as an ISO-formatted date string, or None.
"""
if isinstance(value, datetime.datetime):
return value.strftime(self.DATETIME_FORMAT)
if value is None:
return None
raise TypeError("Value stored must be a datetime object, not {}".format(type(value))) | [
"def",
"to_json",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"strftime",
"(",
"self",
".",
"DATETIME_FORMAT",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"raise",
"TypeError",
"(",
"\"Value stored must be a datetime object, not {}\"",
".",
"format",
"(",
"type",
"(",
"value",
")",
")",
")"
] | Serialize the date as an ISO-formatted date string, or None. | [
"Serialize",
"the",
"date",
"as",
"an",
"ISO",
"-",
"formatted",
"date",
"string",
"or",
"None",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L983-L991 | train | 234,805 |
edx/XBlock | xblock/run_script.py | run_script | def run_script(pycode):
"""Run the Python in `pycode`, and return a dict of the resulting globals."""
# Fix up the whitespace in pycode.
if pycode[0] == "\n":
pycode = pycode[1:]
pycode.rstrip()
pycode = textwrap.dedent(pycode)
# execute it.
globs = {}
six.exec_(pycode, globs, globs) # pylint: disable=W0122
return globs | python | def run_script(pycode):
"""Run the Python in `pycode`, and return a dict of the resulting globals."""
# Fix up the whitespace in pycode.
if pycode[0] == "\n":
pycode = pycode[1:]
pycode.rstrip()
pycode = textwrap.dedent(pycode)
# execute it.
globs = {}
six.exec_(pycode, globs, globs) # pylint: disable=W0122
return globs | [
"def",
"run_script",
"(",
"pycode",
")",
":",
"# Fix up the whitespace in pycode.",
"if",
"pycode",
"[",
"0",
"]",
"==",
"\"\\n\"",
":",
"pycode",
"=",
"pycode",
"[",
"1",
":",
"]",
"pycode",
".",
"rstrip",
"(",
")",
"pycode",
"=",
"textwrap",
".",
"dedent",
"(",
"pycode",
")",
"# execute it.",
"globs",
"=",
"{",
"}",
"six",
".",
"exec_",
"(",
"pycode",
",",
"globs",
",",
"globs",
")",
"# pylint: disable=W0122",
"return",
"globs"
] | Run the Python in `pycode`, and return a dict of the resulting globals. | [
"Run",
"the",
"Python",
"in",
"pycode",
"and",
"return",
"a",
"dict",
"of",
"the",
"resulting",
"globals",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/run_script.py#L12-L24 | train | 234,806 |
edx/XBlock | xblock/core.py | SharedBlockBase.open_local_resource | def open_local_resource(cls, uri):
"""
Open a local resource.
The container calls this method when it receives a request for a
resource on a URL which was generated by Runtime.local_resource_url().
It will pass the URI from the original call to local_resource_url()
back to this method. The XBlock must parse this URI and return an open
file-like object for the resource.
For security reasons, the default implementation will return only a
very restricted set of file types, which must be located in a folder
that defaults to "public". The location used for public resources can
be changed on a per-XBlock basis. XBlock authors who want to override
this behavior will need to take care to ensure that the method only
serves legitimate public resources. At the least, the URI should be
matched against a whitelist regex to ensure that you do not serve an
unauthorized resource.
"""
if isinstance(uri, six.binary_type):
uri = uri.decode('utf-8')
# If no resources_dir is set, then this XBlock cannot serve local resources.
if cls.resources_dir is None:
raise DisallowedFileError("This XBlock is not configured to serve local resources")
# Make sure the path starts with whatever public_dir is set to.
if not uri.startswith(cls.public_dir + '/'):
raise DisallowedFileError("Only files from %r/ are allowed: %r" % (cls.public_dir, uri))
# Disalow paths that have a '/.' component, as `/./` is a no-op and `/../`
# can be used to recurse back past the entry point of this XBlock.
if "/." in uri:
raise DisallowedFileError("Only safe file names are allowed: %r" % uri)
return pkg_resources.resource_stream(cls.__module__, os.path.join(cls.resources_dir, uri)) | python | def open_local_resource(cls, uri):
"""
Open a local resource.
The container calls this method when it receives a request for a
resource on a URL which was generated by Runtime.local_resource_url().
It will pass the URI from the original call to local_resource_url()
back to this method. The XBlock must parse this URI and return an open
file-like object for the resource.
For security reasons, the default implementation will return only a
very restricted set of file types, which must be located in a folder
that defaults to "public". The location used for public resources can
be changed on a per-XBlock basis. XBlock authors who want to override
this behavior will need to take care to ensure that the method only
serves legitimate public resources. At the least, the URI should be
matched against a whitelist regex to ensure that you do not serve an
unauthorized resource.
"""
if isinstance(uri, six.binary_type):
uri = uri.decode('utf-8')
# If no resources_dir is set, then this XBlock cannot serve local resources.
if cls.resources_dir is None:
raise DisallowedFileError("This XBlock is not configured to serve local resources")
# Make sure the path starts with whatever public_dir is set to.
if not uri.startswith(cls.public_dir + '/'):
raise DisallowedFileError("Only files from %r/ are allowed: %r" % (cls.public_dir, uri))
# Disalow paths that have a '/.' component, as `/./` is a no-op and `/../`
# can be used to recurse back past the entry point of this XBlock.
if "/." in uri:
raise DisallowedFileError("Only safe file names are allowed: %r" % uri)
return pkg_resources.resource_stream(cls.__module__, os.path.join(cls.resources_dir, uri)) | [
"def",
"open_local_resource",
"(",
"cls",
",",
"uri",
")",
":",
"if",
"isinstance",
"(",
"uri",
",",
"six",
".",
"binary_type",
")",
":",
"uri",
"=",
"uri",
".",
"decode",
"(",
"'utf-8'",
")",
"# If no resources_dir is set, then this XBlock cannot serve local resources.",
"if",
"cls",
".",
"resources_dir",
"is",
"None",
":",
"raise",
"DisallowedFileError",
"(",
"\"This XBlock is not configured to serve local resources\"",
")",
"# Make sure the path starts with whatever public_dir is set to.",
"if",
"not",
"uri",
".",
"startswith",
"(",
"cls",
".",
"public_dir",
"+",
"'/'",
")",
":",
"raise",
"DisallowedFileError",
"(",
"\"Only files from %r/ are allowed: %r\"",
"%",
"(",
"cls",
".",
"public_dir",
",",
"uri",
")",
")",
"# Disalow paths that have a '/.' component, as `/./` is a no-op and `/../`",
"# can be used to recurse back past the entry point of this XBlock.",
"if",
"\"/.\"",
"in",
"uri",
":",
"raise",
"DisallowedFileError",
"(",
"\"Only safe file names are allowed: %r\"",
"%",
"uri",
")",
"return",
"pkg_resources",
".",
"resource_stream",
"(",
"cls",
".",
"__module__",
",",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"resources_dir",
",",
"uri",
")",
")"
] | Open a local resource.
The container calls this method when it receives a request for a
resource on a URL which was generated by Runtime.local_resource_url().
It will pass the URI from the original call to local_resource_url()
back to this method. The XBlock must parse this URI and return an open
file-like object for the resource.
For security reasons, the default implementation will return only a
very restricted set of file types, which must be located in a folder
that defaults to "public". The location used for public resources can
be changed on a per-XBlock basis. XBlock authors who want to override
this behavior will need to take care to ensure that the method only
serves legitimate public resources. At the least, the URI should be
matched against a whitelist regex to ensure that you do not serve an
unauthorized resource. | [
"Open",
"a",
"local",
"resource",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L79-L115 | train | 234,807 |
edx/XBlock | xblock/core.py | XBlock._class_tags | def _class_tags(cls): # pylint: disable=no-self-argument
"""
Collect the tags from all base classes.
"""
class_tags = set()
for base in cls.mro()[1:]: # pylint: disable=no-member
class_tags.update(getattr(base, '_class_tags', set()))
return class_tags | python | def _class_tags(cls): # pylint: disable=no-self-argument
"""
Collect the tags from all base classes.
"""
class_tags = set()
for base in cls.mro()[1:]: # pylint: disable=no-member
class_tags.update(getattr(base, '_class_tags', set()))
return class_tags | [
"def",
"_class_tags",
"(",
"cls",
")",
":",
"# pylint: disable=no-self-argument",
"class_tags",
"=",
"set",
"(",
")",
"for",
"base",
"in",
"cls",
".",
"mro",
"(",
")",
"[",
"1",
":",
"]",
":",
"# pylint: disable=no-member",
"class_tags",
".",
"update",
"(",
"getattr",
"(",
"base",
",",
"'_class_tags'",
",",
"set",
"(",
")",
")",
")",
"return",
"class_tags"
] | Collect the tags from all base classes. | [
"Collect",
"the",
"tags",
"from",
"all",
"base",
"classes",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L135-L144 | train | 234,808 |
edx/XBlock | xblock/core.py | XBlock.tag | def tag(tags):
"""Returns a function that adds the words in `tags` as class tags to this class."""
def dec(cls):
"""Add the words in `tags` as class tags to this class."""
# Add in this class's tags
cls._class_tags.update(tags.replace(",", " ").split()) # pylint: disable=protected-access
return cls
return dec | python | def tag(tags):
"""Returns a function that adds the words in `tags` as class tags to this class."""
def dec(cls):
"""Add the words in `tags` as class tags to this class."""
# Add in this class's tags
cls._class_tags.update(tags.replace(",", " ").split()) # pylint: disable=protected-access
return cls
return dec | [
"def",
"tag",
"(",
"tags",
")",
":",
"def",
"dec",
"(",
"cls",
")",
":",
"\"\"\"Add the words in `tags` as class tags to this class.\"\"\"",
"# Add in this class's tags",
"cls",
".",
"_class_tags",
".",
"update",
"(",
"tags",
".",
"replace",
"(",
"\",\"",
",",
"\" \"",
")",
".",
"split",
"(",
")",
")",
"# pylint: disable=protected-access",
"return",
"cls",
"return",
"dec"
] | Returns a function that adds the words in `tags` as class tags to this class. | [
"Returns",
"a",
"function",
"that",
"adds",
"the",
"words",
"in",
"tags",
"as",
"class",
"tags",
"to",
"this",
"class",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L147-L154 | train | 234,809 |
edx/XBlock | xblock/core.py | XBlock.load_tagged_classes | def load_tagged_classes(cls, tag, fail_silently=True):
"""
Produce a sequence of all XBlock classes tagged with `tag`.
fail_silently causes the code to simply log warnings if a
plugin cannot import. The goal is to be able to use part of
libraries from an XBlock (and thus have it installed), even if
the overall XBlock cannot be used (e.g. depends on Django in a
non-Django application). There is diagreement about whether
this is a good idea, or whether we should see failures early
(e.g. on startup or first page load), and in what
contexts. Hence, the flag.
"""
# Allow this method to access the `_class_tags`
# pylint: disable=W0212
for name, class_ in cls.load_classes(fail_silently):
if tag in class_._class_tags:
yield name, class_ | python | def load_tagged_classes(cls, tag, fail_silently=True):
"""
Produce a sequence of all XBlock classes tagged with `tag`.
fail_silently causes the code to simply log warnings if a
plugin cannot import. The goal is to be able to use part of
libraries from an XBlock (and thus have it installed), even if
the overall XBlock cannot be used (e.g. depends on Django in a
non-Django application). There is diagreement about whether
this is a good idea, or whether we should see failures early
(e.g. on startup or first page load), and in what
contexts. Hence, the flag.
"""
# Allow this method to access the `_class_tags`
# pylint: disable=W0212
for name, class_ in cls.load_classes(fail_silently):
if tag in class_._class_tags:
yield name, class_ | [
"def",
"load_tagged_classes",
"(",
"cls",
",",
"tag",
",",
"fail_silently",
"=",
"True",
")",
":",
"# Allow this method to access the `_class_tags`",
"# pylint: disable=W0212",
"for",
"name",
",",
"class_",
"in",
"cls",
".",
"load_classes",
"(",
"fail_silently",
")",
":",
"if",
"tag",
"in",
"class_",
".",
"_class_tags",
":",
"yield",
"name",
",",
"class_"
] | Produce a sequence of all XBlock classes tagged with `tag`.
fail_silently causes the code to simply log warnings if a
plugin cannot import. The goal is to be able to use part of
libraries from an XBlock (and thus have it installed), even if
the overall XBlock cannot be used (e.g. depends on Django in a
non-Django application). There is diagreement about whether
this is a good idea, or whether we should see failures early
(e.g. on startup or first page load), and in what
contexts. Hence, the flag. | [
"Produce",
"a",
"sequence",
"of",
"all",
"XBlock",
"classes",
"tagged",
"with",
"tag",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L157-L174 | train | 234,810 |
edx/XBlock | xblock/core.py | XBlock.render | def render(self, view, context=None):
"""Render `view` with this block's runtime and the supplied `context`"""
return self.runtime.render(self, view, context) | python | def render(self, view, context=None):
"""Render `view` with this block's runtime and the supplied `context`"""
return self.runtime.render(self, view, context) | [
"def",
"render",
"(",
"self",
",",
"view",
",",
"context",
"=",
"None",
")",
":",
"return",
"self",
".",
"runtime",
".",
"render",
"(",
"self",
",",
"view",
",",
"context",
")"
] | Render `view` with this block's runtime and the supplied `context` | [
"Render",
"view",
"with",
"this",
"block",
"s",
"runtime",
"and",
"the",
"supplied",
"context"
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L200-L202 | train | 234,811 |
edx/XBlock | xblock/core.py | XBlock.add_xml_to_node | def add_xml_to_node(self, node):
"""
For exporting, set data on etree.Element `node`.
"""
super(XBlock, self).add_xml_to_node(node)
# Add children for each of our children.
self.add_children_to_node(node) | python | def add_xml_to_node(self, node):
"""
For exporting, set data on etree.Element `node`.
"""
super(XBlock, self).add_xml_to_node(node)
# Add children for each of our children.
self.add_children_to_node(node) | [
"def",
"add_xml_to_node",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"XBlock",
",",
"self",
")",
".",
"add_xml_to_node",
"(",
"node",
")",
"# Add children for each of our children.",
"self",
".",
"add_children_to_node",
"(",
"node",
")"
] | For exporting, set data on etree.Element `node`. | [
"For",
"exporting",
"set",
"data",
"on",
"etree",
".",
"Element",
"node",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L222-L228 | train | 234,812 |
edx/XBlock | xblock/core.py | XBlockAside.aside_for | def aside_for(cls, view_name):
"""
A decorator to indicate a function is the aside view for the given view_name.
Aside views should have a signature like:
@XBlockAside.aside_for('student_view')
def student_aside(self, block, context=None):
...
return Fragment(...)
"""
# pylint: disable=protected-access
def _decorator(func): # pylint: disable=missing-docstring
if not hasattr(func, '_aside_for'):
func._aside_for = []
func._aside_for.append(view_name) # pylint: disable=protected-access
return func
return _decorator | python | def aside_for(cls, view_name):
"""
A decorator to indicate a function is the aside view for the given view_name.
Aside views should have a signature like:
@XBlockAside.aside_for('student_view')
def student_aside(self, block, context=None):
...
return Fragment(...)
"""
# pylint: disable=protected-access
def _decorator(func): # pylint: disable=missing-docstring
if not hasattr(func, '_aside_for'):
func._aside_for = []
func._aside_for.append(view_name) # pylint: disable=protected-access
return func
return _decorator | [
"def",
"aside_for",
"(",
"cls",
",",
"view_name",
")",
":",
"# pylint: disable=protected-access",
"def",
"_decorator",
"(",
"func",
")",
":",
"# pylint: disable=missing-docstring",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'_aside_for'",
")",
":",
"func",
".",
"_aside_for",
"=",
"[",
"]",
"func",
".",
"_aside_for",
".",
"append",
"(",
"view_name",
")",
"# pylint: disable=protected-access",
"return",
"func",
"return",
"_decorator"
] | A decorator to indicate a function is the aside view for the given view_name.
Aside views should have a signature like:
@XBlockAside.aside_for('student_view')
def student_aside(self, block, context=None):
...
return Fragment(...) | [
"A",
"decorator",
"to",
"indicate",
"a",
"function",
"is",
"the",
"aside",
"view",
"for",
"the",
"given",
"view_name",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L239-L257 | train | 234,813 |
edx/XBlock | xblock/core.py | XBlockAside.aside_view_declaration | def aside_view_declaration(self, view_name):
"""
Find and return a function object if one is an aside_view for the given view_name
Aside methods declare their view provision via @XBlockAside.aside_for(view_name)
This function finds those declarations for a block.
Arguments:
view_name (string): the name of the view requested.
Returns:
either the function or None
"""
if view_name in self._combined_asides: # pylint: disable=unsupported-membership-test
return getattr(self, self._combined_asides[view_name]) # pylint: disable=unsubscriptable-object
else:
return None | python | def aside_view_declaration(self, view_name):
"""
Find and return a function object if one is an aside_view for the given view_name
Aside methods declare their view provision via @XBlockAside.aside_for(view_name)
This function finds those declarations for a block.
Arguments:
view_name (string): the name of the view requested.
Returns:
either the function or None
"""
if view_name in self._combined_asides: # pylint: disable=unsupported-membership-test
return getattr(self, self._combined_asides[view_name]) # pylint: disable=unsubscriptable-object
else:
return None | [
"def",
"aside_view_declaration",
"(",
"self",
",",
"view_name",
")",
":",
"if",
"view_name",
"in",
"self",
".",
"_combined_asides",
":",
"# pylint: disable=unsupported-membership-test",
"return",
"getattr",
"(",
"self",
",",
"self",
".",
"_combined_asides",
"[",
"view_name",
"]",
")",
"# pylint: disable=unsubscriptable-object",
"else",
":",
"return",
"None"
] | Find and return a function object if one is an aside_view for the given view_name
Aside methods declare their view provision via @XBlockAside.aside_for(view_name)
This function finds those declarations for a block.
Arguments:
view_name (string): the name of the view requested.
Returns:
either the function or None | [
"Find",
"and",
"return",
"a",
"function",
"object",
"if",
"one",
"is",
"an",
"aside_view",
"for",
"the",
"given",
"view_name"
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L282-L298 | train | 234,814 |
edx/XBlock | xblock/core.py | XBlockAside.needs_serialization | def needs_serialization(self):
"""
Return True if the aside has any data to serialize to XML.
If all of the aside's data is empty or a default value, then the aside shouldn't
be serialized as XML at all.
"""
return any(field.is_set_on(self) for field in six.itervalues(self.fields)) | python | def needs_serialization(self):
"""
Return True if the aside has any data to serialize to XML.
If all of the aside's data is empty or a default value, then the aside shouldn't
be serialized as XML at all.
"""
return any(field.is_set_on(self) for field in six.itervalues(self.fields)) | [
"def",
"needs_serialization",
"(",
"self",
")",
":",
"return",
"any",
"(",
"field",
".",
"is_set_on",
"(",
"self",
")",
"for",
"field",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"fields",
")",
")"
] | Return True if the aside has any data to serialize to XML.
If all of the aside's data is empty or a default value, then the aside shouldn't
be serialized as XML at all. | [
"Return",
"True",
"if",
"the",
"aside",
"has",
"any",
"data",
"to",
"serialize",
"to",
"XML",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/core.py#L300-L307 | train | 234,815 |
edx/XBlock | xblock/validation.py | Validation.add | def add(self, message):
"""
Add a new validation message to this instance.
Args:
message (ValidationMessage): A validation message to add to this instance's list of messages.
"""
if not isinstance(message, ValidationMessage):
raise TypeError("Argument must of type ValidationMessage")
self.messages.append(message) | python | def add(self, message):
"""
Add a new validation message to this instance.
Args:
message (ValidationMessage): A validation message to add to this instance's list of messages.
"""
if not isinstance(message, ValidationMessage):
raise TypeError("Argument must of type ValidationMessage")
self.messages.append(message) | [
"def",
"add",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"ValidationMessage",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument must of type ValidationMessage\"",
")",
"self",
".",
"messages",
".",
"append",
"(",
"message",
")"
] | Add a new validation message to this instance.
Args:
message (ValidationMessage): A validation message to add to this instance's list of messages. | [
"Add",
"a",
"new",
"validation",
"message",
"to",
"this",
"instance",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L87-L96 | train | 234,816 |
edx/XBlock | xblock/validation.py | Validation.add_messages | def add_messages(self, validation):
"""
Adds all the messages in the specified `Validation` object to this instance's
messages array.
Args:
validation (Validation): An object containing the messages to add to this instance's messages.
"""
if not isinstance(validation, Validation):
raise TypeError("Argument must be of type Validation")
self.messages.extend(validation.messages) | python | def add_messages(self, validation):
"""
Adds all the messages in the specified `Validation` object to this instance's
messages array.
Args:
validation (Validation): An object containing the messages to add to this instance's messages.
"""
if not isinstance(validation, Validation):
raise TypeError("Argument must be of type Validation")
self.messages.extend(validation.messages) | [
"def",
"add_messages",
"(",
"self",
",",
"validation",
")",
":",
"if",
"not",
"isinstance",
"(",
"validation",
",",
"Validation",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument must be of type Validation\"",
")",
"self",
".",
"messages",
".",
"extend",
"(",
"validation",
".",
"messages",
")"
] | Adds all the messages in the specified `Validation` object to this instance's
messages array.
Args:
validation (Validation): An object containing the messages to add to this instance's messages. | [
"Adds",
"all",
"the",
"messages",
"in",
"the",
"specified",
"Validation",
"object",
"to",
"this",
"instance",
"s",
"messages",
"array",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L98-L109 | train | 234,817 |
edx/XBlock | xblock/validation.py | Validation.to_json | def to_json(self):
"""
Convert to a json-serializable representation.
Returns:
dict: A dict representation that is json-serializable.
"""
return {
"xblock_id": six.text_type(self.xblock_id),
"messages": [message.to_json() for message in self.messages],
"empty": self.empty
} | python | def to_json(self):
"""
Convert to a json-serializable representation.
Returns:
dict: A dict representation that is json-serializable.
"""
return {
"xblock_id": six.text_type(self.xblock_id),
"messages": [message.to_json() for message in self.messages],
"empty": self.empty
} | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"\"xblock_id\"",
":",
"six",
".",
"text_type",
"(",
"self",
".",
"xblock_id",
")",
",",
"\"messages\"",
":",
"[",
"message",
".",
"to_json",
"(",
")",
"for",
"message",
"in",
"self",
".",
"messages",
"]",
",",
"\"empty\"",
":",
"self",
".",
"empty",
"}"
] | Convert to a json-serializable representation.
Returns:
dict: A dict representation that is json-serializable. | [
"Convert",
"to",
"a",
"json",
"-",
"serializable",
"representation",
"."
] | 368bf46e2c0ee69bbb21817f428c4684936e18ee | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L111-L122 | train | 234,818 |
hmeine/qimage2ndarray | qimage2ndarray/__init__.py | recarray_view | def recarray_view(qimage):
"""Returns recarray_ view of a given 32-bit color QImage_'s
memory.
The result is a 2D array with a complex record dtype, offering the
named fields 'r','g','b', and 'a' and corresponding long names.
Thus, each color components can be accessed either via string
indexing or via attribute lookup (through numpy.recarray_):
For your convenience, `qimage` may also be a filename, see
`Loading and Saving Images`_ in the documentation.
>>> from PyQt4.QtGui import QImage, qRgb
>>> qimg = QImage(320, 240, QImage.Format_ARGB32)
>>> qimg.fill(qRgb(12,34,56))
>>>
>>> import qimage2ndarray
>>> v = qimage2ndarray.recarray_view(qimg)
>>>
>>> red = v["r"]
>>> red[10,10]
12
>>> pixel = v[10,10]
>>> pixel["r"]
12
>>> (v.g == v["g"]).all()
True
>>> (v.alpha == 255).all()
True
:param qimage: image whose memory shall be accessed via NumPy
:type qimage: QImage_ with 32-bit pixel type
:rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`"""
raw = _qimage_or_filename_view(qimage)
if raw.itemsize != 4:
raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)")
return raw.view(bgra_dtype, _np.recarray) | python | def recarray_view(qimage):
"""Returns recarray_ view of a given 32-bit color QImage_'s
memory.
The result is a 2D array with a complex record dtype, offering the
named fields 'r','g','b', and 'a' and corresponding long names.
Thus, each color components can be accessed either via string
indexing or via attribute lookup (through numpy.recarray_):
For your convenience, `qimage` may also be a filename, see
`Loading and Saving Images`_ in the documentation.
>>> from PyQt4.QtGui import QImage, qRgb
>>> qimg = QImage(320, 240, QImage.Format_ARGB32)
>>> qimg.fill(qRgb(12,34,56))
>>>
>>> import qimage2ndarray
>>> v = qimage2ndarray.recarray_view(qimg)
>>>
>>> red = v["r"]
>>> red[10,10]
12
>>> pixel = v[10,10]
>>> pixel["r"]
12
>>> (v.g == v["g"]).all()
True
>>> (v.alpha == 255).all()
True
:param qimage: image whose memory shall be accessed via NumPy
:type qimage: QImage_ with 32-bit pixel type
:rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype`"""
raw = _qimage_or_filename_view(qimage)
if raw.itemsize != 4:
raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)")
return raw.view(bgra_dtype, _np.recarray) | [
"def",
"recarray_view",
"(",
"qimage",
")",
":",
"raw",
"=",
"_qimage_or_filename_view",
"(",
"qimage",
")",
"if",
"raw",
".",
"itemsize",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)\"",
")",
"return",
"raw",
".",
"view",
"(",
"bgra_dtype",
",",
"_np",
".",
"recarray",
")"
] | Returns recarray_ view of a given 32-bit color QImage_'s
memory.
The result is a 2D array with a complex record dtype, offering the
named fields 'r','g','b', and 'a' and corresponding long names.
Thus, each color components can be accessed either via string
indexing or via attribute lookup (through numpy.recarray_):
For your convenience, `qimage` may also be a filename, see
`Loading and Saving Images`_ in the documentation.
>>> from PyQt4.QtGui import QImage, qRgb
>>> qimg = QImage(320, 240, QImage.Format_ARGB32)
>>> qimg.fill(qRgb(12,34,56))
>>>
>>> import qimage2ndarray
>>> v = qimage2ndarray.recarray_view(qimg)
>>>
>>> red = v["r"]
>>> red[10,10]
12
>>> pixel = v[10,10]
>>> pixel["r"]
12
>>> (v.g == v["g"]).all()
True
>>> (v.alpha == 255).all()
True
:param qimage: image whose memory shall be accessed via NumPy
:type qimage: QImage_ with 32-bit pixel type
:rtype: numpy.ndarray_ with shape (height, width) and dtype :data:`bgra_dtype` | [
"Returns",
"recarray_",
"view",
"of",
"a",
"given",
"32",
"-",
"bit",
"color",
"QImage_",
"s",
"memory",
"."
] | 023f3c67f90e646ce2fd80418fed85b9c7660bfc | https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L137-L173 | train | 234,819 |
hmeine/qimage2ndarray | qimage2ndarray/__init__.py | gray2qimage | def gray2qimage(gray, normalize = False):
"""Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_
with a gray colormap. The first dimension represents the vertical
image axis.
The parameter `normalize` can be used to normalize an image's
value range to 0..255:
`normalize` = (nmin, nmax):
scale & clip image values from nmin..nmax to 0..255
`normalize` = nmax:
lets nmin default to zero, i.e. scale & clip the range 0..nmax
to 0..255
`normalize` = True:
scale image values to 0..255 (same as passing (gray.min(),
gray.max()))
If the source array `gray` contains masked values, the result will
have only 255 shades of gray, and one color map entry will be used
to make the corresponding pixels transparent.
A full alpha channel cannot be supported with indexed images;
instead, use `array2qimage` to convert into a 32-bit QImage.
:param gray: image data which should be converted (copied) into a QImage_
:type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_
:param normalize: normalization parameter (see above, default: no value changing)
:type normalize: bool, scalar, or pair
:rtype: QImage_ with RGB32 or ARGB32 format"""
if _np.ndim(gray) != 2:
raise ValueError("gray2QImage can only convert 2D arrays" +
" (try using array2qimage)" if _np.ndim(gray) == 3 else "")
h, w = gray.shape
result = _qt.QImage(w, h, _qt.QImage.Format_Indexed8)
if not _np.ma.is_masked(gray):
for i in range(256):
result.setColor(i, _qt.qRgb(i,i,i))
_qimageview(result)[:] = _normalize255(gray, normalize)
else:
# map gray value 1 to gray value 0, in order to make room for
# transparent colormap entry:
result.setColor(0, _qt.qRgb(0,0,0))
for i in range(2, 256):
result.setColor(i-1, _qt.qRgb(i,i,i))
_qimageview(result)[:] = _normalize255(gray, normalize, clip = (1, 255)) - 1
result.setColor(255, 0)
_qimageview(result)[gray.mask] = 255
return result | python | def gray2qimage(gray, normalize = False):
"""Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_
with a gray colormap. The first dimension represents the vertical
image axis.
The parameter `normalize` can be used to normalize an image's
value range to 0..255:
`normalize` = (nmin, nmax):
scale & clip image values from nmin..nmax to 0..255
`normalize` = nmax:
lets nmin default to zero, i.e. scale & clip the range 0..nmax
to 0..255
`normalize` = True:
scale image values to 0..255 (same as passing (gray.min(),
gray.max()))
If the source array `gray` contains masked values, the result will
have only 255 shades of gray, and one color map entry will be used
to make the corresponding pixels transparent.
A full alpha channel cannot be supported with indexed images;
instead, use `array2qimage` to convert into a 32-bit QImage.
:param gray: image data which should be converted (copied) into a QImage_
:type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_
:param normalize: normalization parameter (see above, default: no value changing)
:type normalize: bool, scalar, or pair
:rtype: QImage_ with RGB32 or ARGB32 format"""
if _np.ndim(gray) != 2:
raise ValueError("gray2QImage can only convert 2D arrays" +
" (try using array2qimage)" if _np.ndim(gray) == 3 else "")
h, w = gray.shape
result = _qt.QImage(w, h, _qt.QImage.Format_Indexed8)
if not _np.ma.is_masked(gray):
for i in range(256):
result.setColor(i, _qt.qRgb(i,i,i))
_qimageview(result)[:] = _normalize255(gray, normalize)
else:
# map gray value 1 to gray value 0, in order to make room for
# transparent colormap entry:
result.setColor(0, _qt.qRgb(0,0,0))
for i in range(2, 256):
result.setColor(i-1, _qt.qRgb(i,i,i))
_qimageview(result)[:] = _normalize255(gray, normalize, clip = (1, 255)) - 1
result.setColor(255, 0)
_qimageview(result)[gray.mask] = 255
return result | [
"def",
"gray2qimage",
"(",
"gray",
",",
"normalize",
"=",
"False",
")",
":",
"if",
"_np",
".",
"ndim",
"(",
"gray",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"gray2QImage can only convert 2D arrays\"",
"+",
"\" (try using array2qimage)\"",
"if",
"_np",
".",
"ndim",
"(",
"gray",
")",
"==",
"3",
"else",
"\"\"",
")",
"h",
",",
"w",
"=",
"gray",
".",
"shape",
"result",
"=",
"_qt",
".",
"QImage",
"(",
"w",
",",
"h",
",",
"_qt",
".",
"QImage",
".",
"Format_Indexed8",
")",
"if",
"not",
"_np",
".",
"ma",
".",
"is_masked",
"(",
"gray",
")",
":",
"for",
"i",
"in",
"range",
"(",
"256",
")",
":",
"result",
".",
"setColor",
"(",
"i",
",",
"_qt",
".",
"qRgb",
"(",
"i",
",",
"i",
",",
"i",
")",
")",
"_qimageview",
"(",
"result",
")",
"[",
":",
"]",
"=",
"_normalize255",
"(",
"gray",
",",
"normalize",
")",
"else",
":",
"# map gray value 1 to gray value 0, in order to make room for",
"# transparent colormap entry:",
"result",
".",
"setColor",
"(",
"0",
",",
"_qt",
".",
"qRgb",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"256",
")",
":",
"result",
".",
"setColor",
"(",
"i",
"-",
"1",
",",
"_qt",
".",
"qRgb",
"(",
"i",
",",
"i",
",",
"i",
")",
")",
"_qimageview",
"(",
"result",
")",
"[",
":",
"]",
"=",
"_normalize255",
"(",
"gray",
",",
"normalize",
",",
"clip",
"=",
"(",
"1",
",",
"255",
")",
")",
"-",
"1",
"result",
".",
"setColor",
"(",
"255",
",",
"0",
")",
"_qimageview",
"(",
"result",
")",
"[",
"gray",
".",
"mask",
"]",
"=",
"255",
"return",
"result"
] | Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_
with a gray colormap. The first dimension represents the vertical
image axis.
The parameter `normalize` can be used to normalize an image's
value range to 0..255:
`normalize` = (nmin, nmax):
scale & clip image values from nmin..nmax to 0..255
`normalize` = nmax:
lets nmin default to zero, i.e. scale & clip the range 0..nmax
to 0..255
`normalize` = True:
scale image values to 0..255 (same as passing (gray.min(),
gray.max()))
If the source array `gray` contains masked values, the result will
have only 255 shades of gray, and one color map entry will be used
to make the corresponding pixels transparent.
A full alpha channel cannot be supported with indexed images;
instead, use `array2qimage` to convert into a 32-bit QImage.
:param gray: image data which should be converted (copied) into a QImage_
:type gray: 2D or 3D numpy.ndarray_ or `numpy.ma.array <masked arrays>`_
:param normalize: normalization parameter (see above, default: no value changing)
:type normalize: bool, scalar, or pair
:rtype: QImage_ with RGB32 or ARGB32 format | [
"Convert",
"the",
"2D",
"numpy",
"array",
"gray",
"into",
"a",
"8",
"-",
"bit",
"indexed",
"QImage_",
"with",
"a",
"gray",
"colormap",
".",
"The",
"first",
"dimension",
"represents",
"the",
"vertical",
"image",
"axis",
"."
] | 023f3c67f90e646ce2fd80418fed85b9c7660bfc | https://github.com/hmeine/qimage2ndarray/blob/023f3c67f90e646ce2fd80418fed85b9c7660bfc/qimage2ndarray/__init__.py#L203-L258 | train | 234,820 |
ampl/amplpy | amplpy/ampl.py | AMPL.getVariable | def getVariable(self, name):
"""
Get the variable with the corresponding name.
Args:
name: Name of the variable to be found.
Raises:
TypeError: if the specified variable does not exist.
"""
return lock_and_call(
lambda: Variable(self._impl.getVariable(name)),
self._lock
) | python | def getVariable(self, name):
"""
Get the variable with the corresponding name.
Args:
name: Name of the variable to be found.
Raises:
TypeError: if the specified variable does not exist.
"""
return lock_and_call(
lambda: Variable(self._impl.getVariable(name)),
self._lock
) | [
"def",
"getVariable",
"(",
"self",
",",
"name",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Variable",
"(",
"self",
".",
"_impl",
".",
"getVariable",
"(",
"name",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Get the variable with the corresponding name.
Args:
name: Name of the variable to be found.
Raises:
TypeError: if the specified variable does not exist. | [
"Get",
"the",
"variable",
"with",
"the",
"corresponding",
"name",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L175-L188 | train | 234,821 |
ampl/amplpy | amplpy/ampl.py | AMPL.getConstraint | def getConstraint(self, name):
"""
Get the constraint with the corresponding name.
Args:
name: Name of the constraint to be found.
Raises:
TypeError: if the specified constraint does not exist.
"""
return lock_and_call(
lambda: Constraint(self._impl.getConstraint(name)),
self._lock
) | python | def getConstraint(self, name):
"""
Get the constraint with the corresponding name.
Args:
name: Name of the constraint to be found.
Raises:
TypeError: if the specified constraint does not exist.
"""
return lock_and_call(
lambda: Constraint(self._impl.getConstraint(name)),
self._lock
) | [
"def",
"getConstraint",
"(",
"self",
",",
"name",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Constraint",
"(",
"self",
".",
"_impl",
".",
"getConstraint",
"(",
"name",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Get the constraint with the corresponding name.
Args:
name: Name of the constraint to be found.
Raises:
TypeError: if the specified constraint does not exist. | [
"Get",
"the",
"constraint",
"with",
"the",
"corresponding",
"name",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L190-L203 | train | 234,822 |
ampl/amplpy | amplpy/ampl.py | AMPL.getObjective | def getObjective(self, name):
"""
Get the objective with the corresponding name.
Args:
name: Name of the objective to be found.
Raises:
TypeError: if the specified objective does not exist.
"""
return lock_and_call(
lambda: Objective(self._impl.getObjective(name)),
self._lock
) | python | def getObjective(self, name):
"""
Get the objective with the corresponding name.
Args:
name: Name of the objective to be found.
Raises:
TypeError: if the specified objective does not exist.
"""
return lock_and_call(
lambda: Objective(self._impl.getObjective(name)),
self._lock
) | [
"def",
"getObjective",
"(",
"self",
",",
"name",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Objective",
"(",
"self",
".",
"_impl",
".",
"getObjective",
"(",
"name",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Get the objective with the corresponding name.
Args:
name: Name of the objective to be found.
Raises:
TypeError: if the specified objective does not exist. | [
"Get",
"the",
"objective",
"with",
"the",
"corresponding",
"name",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L205-L218 | train | 234,823 |
ampl/amplpy | amplpy/ampl.py | AMPL.getSet | def getSet(self, name):
"""
Get the set with the corresponding name.
Args:
name: Name of the set to be found.
Raises:
TypeError: if the specified set does not exist.
"""
return lock_and_call(
lambda: Set(self._impl.getSet(name)),
self._lock
) | python | def getSet(self, name):
"""
Get the set with the corresponding name.
Args:
name: Name of the set to be found.
Raises:
TypeError: if the specified set does not exist.
"""
return lock_and_call(
lambda: Set(self._impl.getSet(name)),
self._lock
) | [
"def",
"getSet",
"(",
"self",
",",
"name",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Set",
"(",
"self",
".",
"_impl",
".",
"getSet",
"(",
"name",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Get the set with the corresponding name.
Args:
name: Name of the set to be found.
Raises:
TypeError: if the specified set does not exist. | [
"Get",
"the",
"set",
"with",
"the",
"corresponding",
"name",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L220-L233 | train | 234,824 |
ampl/amplpy | amplpy/ampl.py | AMPL.getParameter | def getParameter(self, name):
"""
Get the parameter with the corresponding name.
Args:
name: Name of the parameter to be found.
Raises:
TypeError: if the specified parameter does not exist.
"""
return lock_and_call(
lambda: Parameter(self._impl.getParameter(name)),
self._lock
) | python | def getParameter(self, name):
"""
Get the parameter with the corresponding name.
Args:
name: Name of the parameter to be found.
Raises:
TypeError: if the specified parameter does not exist.
"""
return lock_and_call(
lambda: Parameter(self._impl.getParameter(name)),
self._lock
) | [
"def",
"getParameter",
"(",
"self",
",",
"name",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Parameter",
"(",
"self",
".",
"_impl",
".",
"getParameter",
"(",
"name",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Get the parameter with the corresponding name.
Args:
name: Name of the parameter to be found.
Raises:
TypeError: if the specified parameter does not exist. | [
"Get",
"the",
"parameter",
"with",
"the",
"corresponding",
"name",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L235-L248 | train | 234,825 |
ampl/amplpy | amplpy/ampl.py | AMPL.eval | def eval(self, amplstatements, **kwargs):
"""
Parses AMPL code and evaluates it as a possibly empty sequence of AMPL
declarations and statements.
As a side effect, it invalidates all entities (as the passed statements
can contain any arbitrary command); the lists of entities will be
re-populated lazily (at first access)
The output of interpreting the statements is passed to the current
OutputHandler (see getOutputHandler and
setOutputHandler).
By default, errors and warnings are printed on stdout.
This behavior can be changed reassigning an ErrorHandler
using setErrorHandler.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running.
"""
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
lock_and_call(
lambda: self._impl.eval(amplstatements),
self._lock
)
self._errorhandler_wrapper.check() | python | def eval(self, amplstatements, **kwargs):
"""
Parses AMPL code and evaluates it as a possibly empty sequence of AMPL
declarations and statements.
As a side effect, it invalidates all entities (as the passed statements
can contain any arbitrary command); the lists of entities will be
re-populated lazily (at first access)
The output of interpreting the statements is passed to the current
OutputHandler (see getOutputHandler and
setOutputHandler).
By default, errors and warnings are printed on stdout.
This behavior can be changed reassigning an ErrorHandler
using setErrorHandler.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running.
"""
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
lock_and_call(
lambda: self._impl.eval(amplstatements),
self._lock
)
self._errorhandler_wrapper.check() | [
"def",
"eval",
"(",
"self",
",",
"amplstatements",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_langext",
"is",
"not",
"None",
":",
"amplstatements",
"=",
"self",
".",
"_langext",
".",
"translate",
"(",
"amplstatements",
",",
"*",
"*",
"kwargs",
")",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"eval",
"(",
"amplstatements",
")",
",",
"self",
".",
"_lock",
")",
"self",
".",
"_errorhandler_wrapper",
".",
"check",
"(",
")"
] | Parses AMPL code and evaluates it as a possibly empty sequence of AMPL
declarations and statements.
As a side effect, it invalidates all entities (as the passed statements
can contain any arbitrary command); the lists of entities will be
re-populated lazily (at first access)
The output of interpreting the statements is passed to the current
OutputHandler (see getOutputHandler and
setOutputHandler).
By default, errors and warnings are printed on stdout.
This behavior can be changed reassigning an ErrorHandler
using setErrorHandler.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running. | [
"Parses",
"AMPL",
"code",
"and",
"evaluates",
"it",
"as",
"a",
"possibly",
"empty",
"sequence",
"of",
"AMPL",
"declarations",
"and",
"statements",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L250-L282 | train | 234,826 |
ampl/amplpy | amplpy/ampl.py | AMPL.isBusy | def isBusy(self):
"""
Returns true if the underlying engine is doing an async operation.
"""
# return self._impl.isBusy()
if self._lock.acquire(False):
self._lock.release()
return False
else:
return True | python | def isBusy(self):
"""
Returns true if the underlying engine is doing an async operation.
"""
# return self._impl.isBusy()
if self._lock.acquire(False):
self._lock.release()
return False
else:
return True | [
"def",
"isBusy",
"(",
"self",
")",
":",
"# return self._impl.isBusy()",
"if",
"self",
".",
"_lock",
".",
"acquire",
"(",
"False",
")",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"return",
"False",
"else",
":",
"return",
"True"
] | Returns true if the underlying engine is doing an async operation. | [
"Returns",
"true",
"if",
"the",
"underlying",
"engine",
"is",
"doing",
"an",
"async",
"operation",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L326-L335 | train | 234,827 |
ampl/amplpy | amplpy/ampl.py | AMPL.evalAsync | def evalAsync(self, amplstatements, callback, **kwargs):
"""
Interpret the given AMPL statement asynchronously.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
callback: Callback to be executed when the statement has been
interpreted.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running.
"""
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
def async_call():
self._lock.acquire()
try:
self._impl.eval(amplstatements)
self._errorhandler_wrapper.check()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start() | python | def evalAsync(self, amplstatements, callback, **kwargs):
"""
Interpret the given AMPL statement asynchronously.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
callback: Callback to be executed when the statement has been
interpreted.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running.
"""
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
def async_call():
self._lock.acquire()
try:
self._impl.eval(amplstatements)
self._errorhandler_wrapper.check()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start() | [
"def",
"evalAsync",
"(",
"self",
",",
"amplstatements",
",",
"callback",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_langext",
"is",
"not",
"None",
":",
"amplstatements",
"=",
"self",
".",
"_langext",
".",
"translate",
"(",
"amplstatements",
",",
"*",
"*",
"kwargs",
")",
"def",
"async_call",
"(",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_impl",
".",
"eval",
"(",
"amplstatements",
")",
"self",
".",
"_errorhandler_wrapper",
".",
"check",
"(",
")",
"except",
"Exception",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"raise",
"else",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"callback",
".",
"run",
"(",
")",
"Thread",
"(",
"target",
"=",
"async_call",
")",
".",
"start",
"(",
")"
] | Interpret the given AMPL statement asynchronously.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
callback: Callback to be executed when the statement has been
interpreted.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running. | [
"Interpret",
"the",
"given",
"AMPL",
"statement",
"asynchronously",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L410-L440 | train | 234,828 |
ampl/amplpy | amplpy/ampl.py | AMPL.solveAsync | def solveAsync(self, callback):
"""
Solve the current model asynchronously.
Args:
callback: Callback to be executed when the solver is done.
"""
def async_call():
self._lock.acquire()
try:
self._impl.solve()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start() | python | def solveAsync(self, callback):
"""
Solve the current model asynchronously.
Args:
callback: Callback to be executed when the solver is done.
"""
def async_call():
self._lock.acquire()
try:
self._impl.solve()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start() | [
"def",
"solveAsync",
"(",
"self",
",",
"callback",
")",
":",
"def",
"async_call",
"(",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_impl",
".",
"solve",
"(",
")",
"except",
"Exception",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"raise",
"else",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"callback",
".",
"run",
"(",
")",
"Thread",
"(",
"target",
"=",
"async_call",
")",
".",
"start",
"(",
")"
] | Solve the current model asynchronously.
Args:
callback: Callback to be executed when the solver is done. | [
"Solve",
"the",
"current",
"model",
"asynchronously",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L442-L459 | train | 234,829 |
ampl/amplpy | amplpy/ampl.py | AMPL.setOption | def setOption(self, name, value):
"""
Set an AMPL option to a specified value.
Args:
name: Name of the option to be set (alphanumeric without spaces).
value: The value the option must be set to.
Raises:
InvalidArgumet: if the option name is not valid.
TypeError: if the value has an invalid type.
"""
if isinstance(value, bool):
lock_and_call(
lambda: self._impl.setBoolOption(name, value),
self._lock
)
elif isinstance(value, int):
lock_and_call(
lambda: self._impl.setIntOption(name, value),
self._lock
)
elif isinstance(value, float):
lock_and_call(
lambda: self._impl.setDblOption(name, value),
self._lock
)
elif isinstance(value, basestring):
lock_and_call(
lambda: self._impl.setOption(name, value),
self._lock
)
else:
raise TypeError | python | def setOption(self, name, value):
"""
Set an AMPL option to a specified value.
Args:
name: Name of the option to be set (alphanumeric without spaces).
value: The value the option must be set to.
Raises:
InvalidArgumet: if the option name is not valid.
TypeError: if the value has an invalid type.
"""
if isinstance(value, bool):
lock_and_call(
lambda: self._impl.setBoolOption(name, value),
self._lock
)
elif isinstance(value, int):
lock_and_call(
lambda: self._impl.setIntOption(name, value),
self._lock
)
elif isinstance(value, float):
lock_and_call(
lambda: self._impl.setDblOption(name, value),
self._lock
)
elif isinstance(value, basestring):
lock_and_call(
lambda: self._impl.setOption(name, value),
self._lock
)
else:
raise TypeError | [
"def",
"setOption",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setBoolOption",
"(",
"name",
",",
"value",
")",
",",
"self",
".",
"_lock",
")",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setIntOption",
"(",
"name",
",",
"value",
")",
",",
"self",
".",
"_lock",
")",
"elif",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setDblOption",
"(",
"name",
",",
"value",
")",
",",
"self",
".",
"_lock",
")",
"elif",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setOption",
"(",
"name",
",",
"value",
")",
",",
"self",
".",
"_lock",
")",
"else",
":",
"raise",
"TypeError"
] | Set an AMPL option to a specified value.
Args:
name: Name of the option to be set (alphanumeric without spaces).
value: The value the option must be set to.
Raises:
InvalidArgumet: if the option name is not valid.
TypeError: if the value has an invalid type. | [
"Set",
"an",
"AMPL",
"option",
"to",
"a",
"specified",
"value",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L500-L535 | train | 234,830 |
ampl/amplpy | amplpy/ampl.py | AMPL.getOption | def getOption(self, name):
"""
Get the current value of the specified option. If the option does not
exist, returns None.
Args:
name: Option name.
Returns:
Value of the option.
Raises:
InvalidArgumet: if the option name is not valid.
"""
try:
value = lock_and_call(
lambda: self._impl.getOption(name).value(),
self._lock
)
except RuntimeError:
return None
else:
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value | python | def getOption(self, name):
"""
Get the current value of the specified option. If the option does not
exist, returns None.
Args:
name: Option name.
Returns:
Value of the option.
Raises:
InvalidArgumet: if the option name is not valid.
"""
try:
value = lock_and_call(
lambda: self._impl.getOption(name).value(),
self._lock
)
except RuntimeError:
return None
else:
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value | [
"def",
"getOption",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"value",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getOption",
"(",
"name",
")",
".",
"value",
"(",
")",
",",
"self",
".",
"_lock",
")",
"except",
"RuntimeError",
":",
"return",
"None",
"else",
":",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"try",
":",
"return",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"value"
] | Get the current value of the specified option. If the option does not
exist, returns None.
Args:
name: Option name.
Returns:
Value of the option.
Raises:
InvalidArgumet: if the option name is not valid. | [
"Get",
"the",
"current",
"value",
"of",
"the",
"specified",
"option",
".",
"If",
"the",
"option",
"does",
"not",
"exist",
"returns",
"None",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L537-L565 | train | 234,831 |
ampl/amplpy | amplpy/ampl.py | AMPL.getValue | def getValue(self, scalarExpression):
"""
Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression.
"""
return lock_and_call(
lambda: Utils.castVariant(self._impl.getValue(scalarExpression)),
self._lock
) | python | def getValue(self, scalarExpression):
"""
Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression.
"""
return lock_and_call(
lambda: Utils.castVariant(self._impl.getValue(scalarExpression)),
self._lock
) | [
"def",
"getValue",
"(",
"self",
",",
"scalarExpression",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Utils",
".",
"castVariant",
"(",
"self",
".",
"_impl",
".",
"getValue",
"(",
"scalarExpression",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression. | [
"Get",
"a",
"scalar",
"value",
"from",
"the",
"underlying",
"AMPL",
"interpreter",
"as",
"a",
"double",
"or",
"a",
"string",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L612-L627 | train | 234,832 |
ampl/amplpy | amplpy/ampl.py | AMPL.setData | def setData(self, data, setName=None):
"""
Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices values of the
DataFrame are to be assigned.
Raises:
AMPLException: if the data assignment procedure was not successful.
"""
if not isinstance(data, DataFrame):
if pd is not None and isinstance(data, pd.DataFrame):
data = DataFrame.fromPandas(data)
if setName is None:
lock_and_call(
lambda: self._impl.setData(data._impl),
self._lock
)
else:
lock_and_call(
lambda: self._impl.setData(data._impl, setName),
self._lock
) | python | def setData(self, data, setName=None):
"""
Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices values of the
DataFrame are to be assigned.
Raises:
AMPLException: if the data assignment procedure was not successful.
"""
if not isinstance(data, DataFrame):
if pd is not None and isinstance(data, pd.DataFrame):
data = DataFrame.fromPandas(data)
if setName is None:
lock_and_call(
lambda: self._impl.setData(data._impl),
self._lock
)
else:
lock_and_call(
lambda: self._impl.setData(data._impl, setName),
self._lock
) | [
"def",
"setData",
"(",
"self",
",",
"data",
",",
"setName",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"DataFrame",
")",
":",
"if",
"pd",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"data",
",",
"pd",
".",
"DataFrame",
")",
":",
"data",
"=",
"DataFrame",
".",
"fromPandas",
"(",
"data",
")",
"if",
"setName",
"is",
"None",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setData",
"(",
"data",
".",
"_impl",
")",
",",
"self",
".",
"_lock",
")",
"else",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setData",
"(",
"data",
".",
"_impl",
",",
"setName",
")",
",",
"self",
".",
"_lock",
")"
] | Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices values of the
DataFrame are to be assigned.
Raises:
AMPLException: if the data assignment procedure was not successful. | [
"Assign",
"the",
"data",
"in",
"the",
"dataframe",
"to",
"the",
"AMPL",
"entities",
"with",
"the",
"names",
"corresponding",
"to",
"the",
"column",
"names",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L629-L655 | train | 234,833 |
ampl/amplpy | amplpy/ampl.py | AMPL.writeTable | def writeTable(self, tableName):
"""
Write the table corresponding to the specified name, equivalent to the
AMPL statement
.. code-block:: ampl
write table tableName;
Args:
tableName: Name of the table to be written.
"""
lock_and_call(
lambda: self._impl.writeTable(tableName),
self._lock
) | python | def writeTable(self, tableName):
"""
Write the table corresponding to the specified name, equivalent to the
AMPL statement
.. code-block:: ampl
write table tableName;
Args:
tableName: Name of the table to be written.
"""
lock_and_call(
lambda: self._impl.writeTable(tableName),
self._lock
) | [
"def",
"writeTable",
"(",
"self",
",",
"tableName",
")",
":",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"writeTable",
"(",
"tableName",
")",
",",
"self",
".",
"_lock",
")"
] | Write the table corresponding to the specified name, equivalent to the
AMPL statement
.. code-block:: ampl
write table tableName;
Args:
tableName: Name of the table to be written. | [
"Write",
"the",
"table",
"corresponding",
"to",
"the",
"specified",
"name",
"equivalent",
"to",
"the",
"AMPL",
"statement"
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L674-L689 | train | 234,834 |
ampl/amplpy | amplpy/ampl.py | AMPL.display | def display(self, *amplExpressions):
"""
Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions to be evaluated.
"""
exprs = list(map(str, amplExpressions))
lock_and_call(
lambda: self._impl.displayLst(exprs, len(exprs)),
self._lock
) | python | def display(self, *amplExpressions):
"""
Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions to be evaluated.
"""
exprs = list(map(str, amplExpressions))
lock_and_call(
lambda: self._impl.displayLst(exprs, len(exprs)),
self._lock
) | [
"def",
"display",
"(",
"self",
",",
"*",
"amplExpressions",
")",
":",
"exprs",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"amplExpressions",
")",
")",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"displayLst",
"(",
"exprs",
",",
"len",
"(",
"exprs",
")",
")",
",",
"self",
".",
"_lock",
")"
] | Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions to be evaluated. | [
"Writes",
"on",
"the",
"current",
"OutputHandler",
"the",
"outcome",
"of",
"the",
"AMPL",
"statement",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L691-L708 | train | 234,835 |
ampl/amplpy | amplpy/ampl.py | AMPL.setOutputHandler | def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output(self, kind, msg):
outputhandler.output(kind, msg)
self._outputhandler = outputhandler
self._outputhandler_internal = OutputHandlerInternal()
lock_and_call(
lambda: self._impl.setOutputHandler(
self._outputhandler_internal
),
self._lock
) | python | def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output(self, kind, msg):
outputhandler.output(kind, msg)
self._outputhandler = outputhandler
self._outputhandler_internal = OutputHandlerInternal()
lock_and_call(
lambda: self._impl.setOutputHandler(
self._outputhandler_internal
),
self._lock
) | [
"def",
"setOutputHandler",
"(",
"self",
",",
"outputhandler",
")",
":",
"class",
"OutputHandlerInternal",
"(",
"amplpython",
".",
"OutputHandler",
")",
":",
"def",
"output",
"(",
"self",
",",
"kind",
",",
"msg",
")",
":",
"outputhandler",
".",
"output",
"(",
"kind",
",",
"msg",
")",
"self",
".",
"_outputhandler",
"=",
"outputhandler",
"self",
".",
"_outputhandler_internal",
"=",
"OutputHandlerInternal",
"(",
")",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setOutputHandler",
"(",
"self",
".",
"_outputhandler_internal",
")",
",",
"self",
".",
"_lock",
")"
] | Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands. | [
"Sets",
"a",
"new",
"output",
"handler",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L710-L729 | train | 234,836 |
ampl/amplpy | amplpy/ampl.py | AMPL.setErrorHandler | def setErrorHandler(self, errorhandler):
"""
Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings.
"""
class ErrorHandlerWrapper(ErrorHandler):
def __init__(self, errorhandler):
self.errorhandler = errorhandler
self.last_exception = None
def error(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.error(exception)
except Exception as e:
self.last_exception = e
def warning(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.warning(exception)
except Exception as e:
self.last_exception = e
def check(self):
if self.last_exception is not None:
e, self.last_exception = self.last_exception, None
raise e
errorhandler_wrapper = ErrorHandlerWrapper(errorhandler)
class InnerErrorHandler(amplpython.ErrorHandler):
def error(self, exception):
errorhandler_wrapper.error(exception)
def warning(self, exception):
errorhandler_wrapper.warning(exception)
self._errorhandler = errorhandler
self._errorhandler_inner = InnerErrorHandler()
self._errorhandler_wrapper = errorhandler_wrapper
lock_and_call(
lambda: self._impl.setErrorHandler(self._errorhandler_inner),
self._lock
) | python | def setErrorHandler(self, errorhandler):
"""
Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings.
"""
class ErrorHandlerWrapper(ErrorHandler):
def __init__(self, errorhandler):
self.errorhandler = errorhandler
self.last_exception = None
def error(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.error(exception)
except Exception as e:
self.last_exception = e
def warning(self, exception):
if isinstance(exception, amplpython.AMPLException):
exception = AMPLException(exception)
try:
self.errorhandler.warning(exception)
except Exception as e:
self.last_exception = e
def check(self):
if self.last_exception is not None:
e, self.last_exception = self.last_exception, None
raise e
errorhandler_wrapper = ErrorHandlerWrapper(errorhandler)
class InnerErrorHandler(amplpython.ErrorHandler):
def error(self, exception):
errorhandler_wrapper.error(exception)
def warning(self, exception):
errorhandler_wrapper.warning(exception)
self._errorhandler = errorhandler
self._errorhandler_inner = InnerErrorHandler()
self._errorhandler_wrapper = errorhandler_wrapper
lock_and_call(
lambda: self._impl.setErrorHandler(self._errorhandler_inner),
self._lock
) | [
"def",
"setErrorHandler",
"(",
"self",
",",
"errorhandler",
")",
":",
"class",
"ErrorHandlerWrapper",
"(",
"ErrorHandler",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"errorhandler",
")",
":",
"self",
".",
"errorhandler",
"=",
"errorhandler",
"self",
".",
"last_exception",
"=",
"None",
"def",
"error",
"(",
"self",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"amplpython",
".",
"AMPLException",
")",
":",
"exception",
"=",
"AMPLException",
"(",
"exception",
")",
"try",
":",
"self",
".",
"errorhandler",
".",
"error",
"(",
"exception",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"last_exception",
"=",
"e",
"def",
"warning",
"(",
"self",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"amplpython",
".",
"AMPLException",
")",
":",
"exception",
"=",
"AMPLException",
"(",
"exception",
")",
"try",
":",
"self",
".",
"errorhandler",
".",
"warning",
"(",
"exception",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"last_exception",
"=",
"e",
"def",
"check",
"(",
"self",
")",
":",
"if",
"self",
".",
"last_exception",
"is",
"not",
"None",
":",
"e",
",",
"self",
".",
"last_exception",
"=",
"self",
".",
"last_exception",
",",
"None",
"raise",
"e",
"errorhandler_wrapper",
"=",
"ErrorHandlerWrapper",
"(",
"errorhandler",
")",
"class",
"InnerErrorHandler",
"(",
"amplpython",
".",
"ErrorHandler",
")",
":",
"def",
"error",
"(",
"self",
",",
"exception",
")",
":",
"errorhandler_wrapper",
".",
"error",
"(",
"exception",
")",
"def",
"warning",
"(",
"self",
",",
"exception",
")",
":",
"errorhandler_wrapper",
".",
"warning",
"(",
"exception",
")",
"self",
".",
"_errorhandler",
"=",
"errorhandler",
"self",
".",
"_errorhandler_inner",
"=",
"InnerErrorHandler",
"(",
")",
"self",
".",
"_errorhandler_wrapper",
"=",
"errorhandler_wrapper",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"setErrorHandler",
"(",
"self",
".",
"_errorhandler_inner",
")",
",",
"self",
".",
"_lock",
")"
] | Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings. | [
"Sets",
"a",
"new",
"error",
"handler",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L731-L779 | train | 234,837 |
ampl/amplpy | amplpy/ampl.py | AMPL.getVariables | def getVariables(self):
"""
Get all the variables declared.
"""
variables = lock_and_call(
lambda: self._impl.getVariables(),
self._lock
)
return EntityMap(variables, Variable) | python | def getVariables(self):
"""
Get all the variables declared.
"""
variables = lock_and_call(
lambda: self._impl.getVariables(),
self._lock
)
return EntityMap(variables, Variable) | [
"def",
"getVariables",
"(",
"self",
")",
":",
"variables",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getVariables",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"variables",
",",
"Variable",
")"
] | Get all the variables declared. | [
"Get",
"all",
"the",
"variables",
"declared",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L799-L807 | train | 234,838 |
ampl/amplpy | amplpy/ampl.py | AMPL.getConstraints | def getConstraints(self):
"""
Get all the constraints declared.
"""
constraints = lock_and_call(
lambda: self._impl.getConstraints(),
self._lock
)
return EntityMap(constraints, Constraint) | python | def getConstraints(self):
"""
Get all the constraints declared.
"""
constraints = lock_and_call(
lambda: self._impl.getConstraints(),
self._lock
)
return EntityMap(constraints, Constraint) | [
"def",
"getConstraints",
"(",
"self",
")",
":",
"constraints",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getConstraints",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"constraints",
",",
"Constraint",
")"
] | Get all the constraints declared. | [
"Get",
"all",
"the",
"constraints",
"declared",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L809-L817 | train | 234,839 |
ampl/amplpy | amplpy/ampl.py | AMPL.getObjectives | def getObjectives(self):
"""
Get all the objectives declared.
"""
objectives = lock_and_call(
lambda: self._impl.getObjectives(),
self._lock
)
return EntityMap(objectives, Objective) | python | def getObjectives(self):
"""
Get all the objectives declared.
"""
objectives = lock_and_call(
lambda: self._impl.getObjectives(),
self._lock
)
return EntityMap(objectives, Objective) | [
"def",
"getObjectives",
"(",
"self",
")",
":",
"objectives",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getObjectives",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"objectives",
",",
"Objective",
")"
] | Get all the objectives declared. | [
"Get",
"all",
"the",
"objectives",
"declared",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L819-L827 | train | 234,840 |
ampl/amplpy | amplpy/ampl.py | AMPL.getSets | def getSets(self):
"""
Get all the sets declared.
"""
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) | python | def getSets(self):
"""
Get all the sets declared.
"""
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) | [
"def",
"getSets",
"(",
"self",
")",
":",
"sets",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getSets",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"sets",
",",
"Set",
")"
] | Get all the sets declared. | [
"Get",
"all",
"the",
"sets",
"declared",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L829-L837 | train | 234,841 |
ampl/amplpy | amplpy/ampl.py | AMPL.getParameters | def getParameters(self):
"""
Get all the parameters declared.
"""
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) | python | def getParameters(self):
"""
Get all the parameters declared.
"""
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) | [
"def",
"getParameters",
"(",
"self",
")",
":",
"parameters",
"=",
"lock_and_call",
"(",
"lambda",
":",
"self",
".",
"_impl",
".",
"getParameters",
"(",
")",
",",
"self",
".",
"_lock",
")",
"return",
"EntityMap",
"(",
"parameters",
",",
"Parameter",
")"
] | Get all the parameters declared. | [
"Get",
"all",
"the",
"parameters",
"declared",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L839-L847 | train | 234,842 |
ampl/amplpy | amplpy/ampl.py | AMPL.getCurrentObjective | def getCurrentObjective(self):
"""
Get the the current objective. Returns `None` if no objective is set.
"""
name = self._impl.getCurrentObjectiveName()
if name == '':
return None
else:
return self.getObjective(name) | python | def getCurrentObjective(self):
"""
Get the the current objective. Returns `None` if no objective is set.
"""
name = self._impl.getCurrentObjectiveName()
if name == '':
return None
else:
return self.getObjective(name) | [
"def",
"getCurrentObjective",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_impl",
".",
"getCurrentObjectiveName",
"(",
")",
"if",
"name",
"==",
"''",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
"getObjective",
"(",
"name",
")"
] | Get the the current objective. Returns `None` if no objective is set. | [
"Get",
"the",
"the",
"current",
"objective",
".",
"Returns",
"None",
"if",
"no",
"objective",
"is",
"set",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L849-L857 | train | 234,843 |
ampl/amplpy | amplpy/ampl.py | AMPL._obj | def _obj(self):
"""
Get an objective.
"""
class Objectives(object):
def __getitem__(_self, name):
return self.getObjective(name)
def __iter__(_self):
return self.getObjectives()
return Objectives() | python | def _obj(self):
"""
Get an objective.
"""
class Objectives(object):
def __getitem__(_self, name):
return self.getObjective(name)
def __iter__(_self):
return self.getObjectives()
return Objectives() | [
"def",
"_obj",
"(",
"self",
")",
":",
"class",
"Objectives",
"(",
"object",
")",
":",
"def",
"__getitem__",
"(",
"_self",
",",
"name",
")",
":",
"return",
"self",
".",
"getObjective",
"(",
"name",
")",
"def",
"__iter__",
"(",
"_self",
")",
":",
"return",
"self",
".",
"getObjectives",
"(",
")",
"return",
"Objectives",
"(",
")"
] | Get an objective. | [
"Get",
"an",
"objective",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L891-L902 | train | 234,844 |
ampl/amplpy | amplpy/ampl.py | AMPL.exportData | def exportData(self, datfile):
"""
Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute).
"""
def ampl_set(name, values):
def format_entry(e):
return repr(e).replace(' ', '')
return 'set {0} := {1};'.format(
name, ','.join(format_entry(e) for e in values)
)
def ampl_param(name, values):
def format_entry(k, v):
k = repr(k).strip('()').replace(' ', '')
if v == inf:
v = "Infinity"
elif v == -inf:
v = "-Infinity"
else:
v = repr(v).strip('()').replace(' ', '')
return '[{0}]{1}'.format(k, v)
return 'param {0} := {1};'.format(
name, ''.join(format_entry(k, v) for k, v in values.items())
)
with open(datfile, 'w') as f:
for name, entity in self.getSets():
values = entity.getValues().toList()
print(ampl_set(name, values), file=f)
for name, entity in self.getParameters():
if entity.isScalar():
print(
'param {} := {};'.format(name, entity.value()),
file=f
)
else:
values = entity.getValues().toDict()
print(ampl_param(name, values), file=f) | python | def exportData(self, datfile):
"""
Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute).
"""
def ampl_set(name, values):
def format_entry(e):
return repr(e).replace(' ', '')
return 'set {0} := {1};'.format(
name, ','.join(format_entry(e) for e in values)
)
def ampl_param(name, values):
def format_entry(k, v):
k = repr(k).strip('()').replace(' ', '')
if v == inf:
v = "Infinity"
elif v == -inf:
v = "-Infinity"
else:
v = repr(v).strip('()').replace(' ', '')
return '[{0}]{1}'.format(k, v)
return 'param {0} := {1};'.format(
name, ''.join(format_entry(k, v) for k, v in values.items())
)
with open(datfile, 'w') as f:
for name, entity in self.getSets():
values = entity.getValues().toList()
print(ampl_set(name, values), file=f)
for name, entity in self.getParameters():
if entity.isScalar():
print(
'param {} := {};'.format(name, entity.value()),
file=f
)
else:
values = entity.getValues().toDict()
print(ampl_param(name, values), file=f) | [
"def",
"exportData",
"(",
"self",
",",
"datfile",
")",
":",
"def",
"ampl_set",
"(",
"name",
",",
"values",
")",
":",
"def",
"format_entry",
"(",
"e",
")",
":",
"return",
"repr",
"(",
"e",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"'set {0} := {1};'",
".",
"format",
"(",
"name",
",",
"','",
".",
"join",
"(",
"format_entry",
"(",
"e",
")",
"for",
"e",
"in",
"values",
")",
")",
"def",
"ampl_param",
"(",
"name",
",",
"values",
")",
":",
"def",
"format_entry",
"(",
"k",
",",
"v",
")",
":",
"k",
"=",
"repr",
"(",
"k",
")",
".",
"strip",
"(",
"'()'",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"v",
"==",
"inf",
":",
"v",
"=",
"\"Infinity\"",
"elif",
"v",
"==",
"-",
"inf",
":",
"v",
"=",
"\"-Infinity\"",
"else",
":",
"v",
"=",
"repr",
"(",
"v",
")",
".",
"strip",
"(",
"'()'",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"return",
"'[{0}]{1}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"return",
"'param {0} := {1};'",
".",
"format",
"(",
"name",
",",
"''",
".",
"join",
"(",
"format_entry",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"values",
".",
"items",
"(",
")",
")",
")",
"with",
"open",
"(",
"datfile",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"name",
",",
"entity",
"in",
"self",
".",
"getSets",
"(",
")",
":",
"values",
"=",
"entity",
".",
"getValues",
"(",
")",
".",
"toList",
"(",
")",
"print",
"(",
"ampl_set",
"(",
"name",
",",
"values",
")",
",",
"file",
"=",
"f",
")",
"for",
"name",
",",
"entity",
"in",
"self",
".",
"getParameters",
"(",
")",
":",
"if",
"entity",
".",
"isScalar",
"(",
")",
":",
"print",
"(",
"'param {} := {};'",
".",
"format",
"(",
"name",
",",
"entity",
".",
"value",
"(",
")",
")",
",",
"file",
"=",
"f",
")",
"else",
":",
"values",
"=",
"entity",
".",
"getValues",
"(",
")",
".",
"toDict",
"(",
")",
"print",
"(",
"ampl_param",
"(",
"name",
",",
"values",
")",
",",
"file",
"=",
"f",
")"
] | Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute). | [
"Create",
"a",
".",
"dat",
"file",
"with",
"the",
"data",
"that",
"has",
"been",
"loaded",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L959-L1003 | train | 234,845 |
ampl/amplpy | amplpy/ampl.py | AMPL.importGurobiSolution | def importGurobiSolution(self, grbmodel):
"""
Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved.
"""
self.eval(''.join(
'let {} := {};'.format(var.VarName, var.X)
for var in grbmodel.getVars()
if '$' not in var.VarName
)) | python | def importGurobiSolution(self, grbmodel):
"""
Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved.
"""
self.eval(''.join(
'let {} := {};'.format(var.VarName, var.X)
for var in grbmodel.getVars()
if '$' not in var.VarName
)) | [
"def",
"importGurobiSolution",
"(",
"self",
",",
"grbmodel",
")",
":",
"self",
".",
"eval",
"(",
"''",
".",
"join",
"(",
"'let {} := {};'",
".",
"format",
"(",
"var",
".",
"VarName",
",",
"var",
".",
"X",
")",
"for",
"var",
"in",
"grbmodel",
".",
"getVars",
"(",
")",
"if",
"'$'",
"not",
"in",
"var",
".",
"VarName",
")",
")"
] | Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved. | [
"Import",
"the",
"solution",
"from",
"a",
"gurobipy",
".",
"Model",
"object",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1070-L1081 | train | 234,846 |
ampl/amplpy | amplpy/ampl.py | AMPL._startRecording | def _startRecording(self, filename):
"""
Start recording the session to a file for debug purposes.
"""
self.setOption('_log_file_name', filename)
self.setOption('_log_input_only', True)
self.setOption('_log', True) | python | def _startRecording(self, filename):
"""
Start recording the session to a file for debug purposes.
"""
self.setOption('_log_file_name', filename)
self.setOption('_log_input_only', True)
self.setOption('_log', True) | [
"def",
"_startRecording",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"setOption",
"(",
"'_log_file_name'",
",",
"filename",
")",
"self",
".",
"setOption",
"(",
"'_log_input_only'",
",",
"True",
")",
"self",
".",
"setOption",
"(",
"'_log'",
",",
"True",
")"
] | Start recording the session to a file for debug purposes. | [
"Start",
"recording",
"the",
"session",
"to",
"a",
"file",
"for",
"debug",
"purposes",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1084-L1090 | train | 234,847 |
ampl/amplpy | amplpy/ampl.py | AMPL._loadSession | def _loadSession(self, filename):
"""
Load a recorded session.
"""
try:
self.eval(open(filename).read())
except RuntimeError as e:
print(e) | python | def _loadSession(self, filename):
"""
Load a recorded session.
"""
try:
self.eval(open(filename).read())
except RuntimeError as e:
print(e) | [
"def",
"_loadSession",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"self",
".",
"eval",
"(",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"print",
"(",
"e",
")"
] | Load a recorded session. | [
"Load",
"a",
"recorded",
"session",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1098-L1105 | train | 234,848 |
ampl/amplpy | setup.py | ls_dir | def ls_dir(base_dir):
"""List files recursively."""
return [
os.path.join(dirpath.replace(base_dir, '', 1), f)
for (dirpath, dirnames, files) in os.walk(base_dir)
for f in files
] | python | def ls_dir(base_dir):
"""List files recursively."""
return [
os.path.join(dirpath.replace(base_dir, '', 1), f)
for (dirpath, dirnames, files) in os.walk(base_dir)
for f in files
] | [
"def",
"ls_dir",
"(",
"base_dir",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
".",
"replace",
"(",
"base_dir",
",",
"''",
",",
"1",
")",
",",
"f",
")",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"base_dir",
")",
"for",
"f",
"in",
"files",
"]"
] | List files recursively. | [
"List",
"files",
"recursively",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/setup.py#L45-L51 | train | 234,849 |
ampl/amplpy | amplpy/entity.py | Entity.get | def get(self, *index):
"""
Get the instance with the specified index.
Returns:
The corresponding instance.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
if len(index) == 0:
return self.wrapFunction(self._impl.get())
else:
return self.wrapFunction(self._impl.get(Tuple(index)._impl)) | python | def get(self, *index):
"""
Get the instance with the specified index.
Returns:
The corresponding instance.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
if len(index) == 0:
return self.wrapFunction(self._impl.get())
else:
return self.wrapFunction(self._impl.get(Tuple(index)._impl)) | [
"def",
"get",
"(",
"self",
",",
"*",
"index",
")",
":",
"assert",
"self",
".",
"wrapFunction",
"is",
"not",
"None",
"if",
"len",
"(",
"index",
")",
"==",
"1",
"and",
"isinstance",
"(",
"index",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"index",
"=",
"index",
"[",
"0",
"]",
"if",
"len",
"(",
"index",
")",
"==",
"0",
":",
"return",
"self",
".",
"wrapFunction",
"(",
"self",
".",
"_impl",
".",
"get",
"(",
")",
")",
"else",
":",
"return",
"self",
".",
"wrapFunction",
"(",
"self",
".",
"_impl",
".",
"get",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
")",
")"
] | Get the instance with the specified index.
Returns:
The corresponding instance. | [
"Get",
"the",
"instance",
"with",
"the",
"specified",
"index",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L60-L73 | train | 234,850 |
ampl/amplpy | amplpy/entity.py | Entity.find | def find(self, *index):
"""
Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
it = self._impl.find(Tuple(index)._impl)
if it == self._impl.end():
return None
else:
return self.wrapFunction(it) | python | def find(self, *index):
"""
Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`.
"""
assert self.wrapFunction is not None
if len(index) == 1 and isinstance(index[0], (tuple, list)):
index = index[0]
it = self._impl.find(Tuple(index)._impl)
if it == self._impl.end():
return None
else:
return self.wrapFunction(it) | [
"def",
"find",
"(",
"self",
",",
"*",
"index",
")",
":",
"assert",
"self",
".",
"wrapFunction",
"is",
"not",
"None",
"if",
"len",
"(",
"index",
")",
"==",
"1",
"and",
"isinstance",
"(",
"index",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"index",
"=",
"index",
"[",
"0",
"]",
"it",
"=",
"self",
".",
"_impl",
".",
"find",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
")",
"if",
"it",
"==",
"self",
".",
"_impl",
".",
"end",
"(",
")",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
"wrapFunction",
"(",
"it",
")"
] | Searches the current entity for an instance with the specified index.
Returns:
The wanted instance if found, otherwise it returns `None`. | [
"Searches",
"the",
"current",
"entity",
"for",
"an",
"instance",
"with",
"the",
"specified",
"index",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L75-L89 | train | 234,851 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.addRow | def addRow(self, *value):
"""
Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column.
"""
if len(value) == 1 and isinstance(value[0], (tuple, list)):
value = value[0]
assert len(value) == self.getNumCols()
self._impl.addRow(Tuple(value)._impl) | python | def addRow(self, *value):
"""
Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column.
"""
if len(value) == 1 and isinstance(value[0], (tuple, list)):
value = value[0]
assert len(value) == self.getNumCols()
self._impl.addRow(Tuple(value)._impl) | [
"def",
"addRow",
"(",
"self",
",",
"*",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"1",
"and",
"isinstance",
"(",
"value",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"value",
"=",
"value",
"[",
"0",
"]",
"assert",
"len",
"(",
"value",
")",
"==",
"self",
".",
"getNumCols",
"(",
")",
"self",
".",
"_impl",
".",
"addRow",
"(",
"Tuple",
"(",
"value",
")",
".",
"_impl",
")"
] | Add a row to the DataFrame. The size of the tuple must be equal to the
total number of columns in the dataframe.
Args:
value: A single argument with a tuple containing all the values
for the row to be added, or multiple arguments with the values for
each column. | [
"Add",
"a",
"row",
"to",
"the",
"DataFrame",
".",
"The",
"size",
"of",
"the",
"tuple",
"must",
"be",
"equal",
"to",
"the",
"total",
"number",
"of",
"columns",
"in",
"the",
"dataframe",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L155-L168 | train | 234,852 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.addColumn | def addColumn(self, header, values=[]):
"""
Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column.
"""
if len(values) == 0:
self._impl.addColumn(header)
else:
assert len(values) == self.getNumRows()
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.addColumnStr(header, values)
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.addColumnDbl(header, values)
else:
raise NotImplementedError | python | def addColumn(self, header, values=[]):
"""
Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column.
"""
if len(values) == 0:
self._impl.addColumn(header)
else:
assert len(values) == self.getNumRows()
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.addColumnStr(header, values)
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.addColumnDbl(header, values)
else:
raise NotImplementedError | [
"def",
"addColumn",
"(",
"self",
",",
"header",
",",
"values",
"=",
"[",
"]",
")",
":",
"if",
"len",
"(",
"values",
")",
"==",
"0",
":",
"self",
".",
"_impl",
".",
"addColumn",
"(",
"header",
")",
"else",
":",
"assert",
"len",
"(",
"values",
")",
"==",
"self",
".",
"getNumRows",
"(",
")",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"addColumnStr",
"(",
"header",
",",
"values",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"addColumnDbl",
"(",
"header",
",",
"values",
")",
"else",
":",
"raise",
"NotImplementedError"
] | Add a new column with the corresponding header and values to the
dataframe.
Args:
header: The name of the new column.
values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column. | [
"Add",
"a",
"new",
"column",
"with",
"the",
"corresponding",
"header",
"and",
"values",
"to",
"the",
"dataframe",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L170-L192 | train | 234,853 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.setColumn | def setColumn(self, header, values):
"""
Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set.
"""
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setColumnStr(header, values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setColumnDbl(header, values, len(values))
else:
print(values)
raise NotImplementedError | python | def setColumn(self, header, values):
"""
Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set.
"""
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setColumnStr(header, values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setColumnDbl(header, values, len(values))
else:
print(values)
raise NotImplementedError | [
"def",
"setColumn",
"(",
"self",
",",
"header",
",",
"values",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setColumnStr",
"(",
"header",
",",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setColumnDbl",
"(",
"header",
",",
"values",
",",
"len",
"(",
"values",
")",
")",
"else",
":",
"print",
"(",
"values",
")",
"raise",
"NotImplementedError"
] | Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set. | [
"Set",
"the",
"values",
"of",
"a",
"column",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L203-L220 | train | 234,854 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.getRow | def getRow(self, key):
"""
Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row.
"""
return Row(self._impl.getRow(Tuple(key)._impl)) | python | def getRow(self, key):
"""
Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row.
"""
return Row(self._impl.getRow(Tuple(key)._impl)) | [
"def",
"getRow",
"(",
"self",
",",
"key",
")",
":",
"return",
"Row",
"(",
"self",
".",
"_impl",
".",
"getRow",
"(",
"Tuple",
"(",
"key",
")",
".",
"_impl",
")",
")"
] | Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row. | [
"Get",
"a",
"row",
"by",
"value",
"of",
"the",
"indexing",
"columns",
".",
"If",
"the",
"index",
"is",
"not",
"specified",
"gets",
"the",
"only",
"row",
"of",
"a",
"dataframe",
"with",
"no",
"indexing",
"columns",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L222-L233 | train | 234,855 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.getRowByIndex | def getRowByIndex(self, index):
"""
Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row.
"""
assert isinstance(index, int)
return Row(self._impl.getRowByIndex(index)) | python | def getRowByIndex(self, index):
"""
Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row.
"""
assert isinstance(index, int)
return Row(self._impl.getRowByIndex(index)) | [
"def",
"getRowByIndex",
"(",
"self",
",",
"index",
")",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
"return",
"Row",
"(",
"self",
".",
"_impl",
".",
"getRowByIndex",
"(",
"index",
")",
")"
] | Get row by numeric index.
Args:
index: Zero-based index of the row to get.
Returns:
The corresponding row. | [
"Get",
"row",
"by",
"numeric",
"index",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L235-L246 | train | 234,856 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.getHeaders | def getHeaders(self):
"""
Get the headers of this DataFrame.
Returns:
The headers of this DataFrame.
"""
headers = self._impl.getHeaders()
return tuple(
headers.getIndex(i) for i in range(self._impl.getNumCols())
) | python | def getHeaders(self):
"""
Get the headers of this DataFrame.
Returns:
The headers of this DataFrame.
"""
headers = self._impl.getHeaders()
return tuple(
headers.getIndex(i) for i in range(self._impl.getNumCols())
) | [
"def",
"getHeaders",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"_impl",
".",
"getHeaders",
"(",
")",
"return",
"tuple",
"(",
"headers",
".",
"getIndex",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_impl",
".",
"getNumCols",
"(",
")",
")",
")"
] | Get the headers of this DataFrame.
Returns:
The headers of this DataFrame. | [
"Get",
"the",
"headers",
"of",
"this",
"DataFrame",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L248-L258 | train | 234,857 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.setValues | def setValues(self, values):
"""
Set the values of a DataFrame from a dictionary.
Args:
values: Dictionary with the values to set.
"""
ncols = self.getNumCols()
nindices = self.getNumIndices()
for key, value in values.items():
key = Utils.convToList(key)
assert len(key) == nindices
value = Utils.convToList(value)
assert len(value) == ncols-nindices
self.addRow(key + value) | python | def setValues(self, values):
"""
Set the values of a DataFrame from a dictionary.
Args:
values: Dictionary with the values to set.
"""
ncols = self.getNumCols()
nindices = self.getNumIndices()
for key, value in values.items():
key = Utils.convToList(key)
assert len(key) == nindices
value = Utils.convToList(value)
assert len(value) == ncols-nindices
self.addRow(key + value) | [
"def",
"setValues",
"(",
"self",
",",
"values",
")",
":",
"ncols",
"=",
"self",
".",
"getNumCols",
"(",
")",
"nindices",
"=",
"self",
".",
"getNumIndices",
"(",
")",
"for",
"key",
",",
"value",
"in",
"values",
".",
"items",
"(",
")",
":",
"key",
"=",
"Utils",
".",
"convToList",
"(",
"key",
")",
"assert",
"len",
"(",
"key",
")",
"==",
"nindices",
"value",
"=",
"Utils",
".",
"convToList",
"(",
"value",
")",
"assert",
"len",
"(",
"value",
")",
"==",
"ncols",
"-",
"nindices",
"self",
".",
"addRow",
"(",
"key",
"+",
"value",
")"
] | Set the values of a DataFrame from a dictionary.
Args:
values: Dictionary with the values to set. | [
"Set",
"the",
"values",
"of",
"a",
"DataFrame",
"from",
"a",
"dictionary",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L260-L274 | train | 234,858 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.toDict | def toDict(self):
"""
Return a dictionary with the DataFrame data.
"""
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
elif nindices == 1:
key = row[0]
else:
key = None
if len(row) - nindices == 0:
d[key] = None
elif len(row) - nindices == 1:
d[key] = row[nindices]
else:
d[key] = tuple(row[nindices:])
return d | python | def toDict(self):
"""
Return a dictionary with the DataFrame data.
"""
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
elif nindices == 1:
key = row[0]
else:
key = None
if len(row) - nindices == 0:
d[key] = None
elif len(row) - nindices == 1:
d[key] = row[nindices]
else:
d[key] = tuple(row[nindices:])
return d | [
"def",
"toDict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"nindices",
"=",
"self",
".",
"getNumIndices",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
")",
":",
"row",
"=",
"list",
"(",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
")",
"if",
"nindices",
">",
"1",
":",
"key",
"=",
"tuple",
"(",
"row",
"[",
":",
"nindices",
"]",
")",
"elif",
"nindices",
"==",
"1",
":",
"key",
"=",
"row",
"[",
"0",
"]",
"else",
":",
"key",
"=",
"None",
"if",
"len",
"(",
"row",
")",
"-",
"nindices",
"==",
"0",
":",
"d",
"[",
"key",
"]",
"=",
"None",
"elif",
"len",
"(",
"row",
")",
"-",
"nindices",
"==",
"1",
":",
"d",
"[",
"key",
"]",
"=",
"row",
"[",
"nindices",
"]",
"else",
":",
"d",
"[",
"key",
"]",
"=",
"tuple",
"(",
"row",
"[",
"nindices",
":",
"]",
")",
"return",
"d"
] | Return a dictionary with the DataFrame data. | [
"Return",
"a",
"dictionary",
"with",
"the",
"DataFrame",
"data",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L276-L296 | train | 234,859 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.toList | def toList(self):
"""
Return a list with the DataFrame data.
"""
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByIndex(i)[0]
for i in range(self.getNumRows())
] | python | def toList(self):
"""
Return a list with the DataFrame data.
"""
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByIndex(i)[0]
for i in range(self.getNumRows())
] | [
"def",
"toList",
"(",
"self",
")",
":",
"if",
"self",
".",
"getNumCols",
"(",
")",
">",
"1",
":",
"return",
"[",
"tuple",
"(",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
")",
"]",
"else",
":",
"return",
"[",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
")",
"]"
] | Return a list with the DataFrame data. | [
"Return",
"a",
"list",
"with",
"the",
"DataFrame",
"data",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L298-L311 | train | 234,860 |
ampl/amplpy | amplpy/dataframe.py | DataFrame.toPandas | def toPandas(self):
"""
Return a pandas DataFrame with the DataFrame data.
"""
assert pd is not None
nindices = self.getNumIndices()
headers = self.getHeaders()
columns = {
header: list(self.getColumn(header))
for header in headers[nindices:]
}
index = zip(*[
list(self.getColumn(header))
for header in headers[:nindices]
])
index = [key if len(key) > 1 else key[0] for key in index]
if index == []:
return pd.DataFrame(columns, index=None)
else:
return pd.DataFrame(columns, index=index) | python | def toPandas(self):
"""
Return a pandas DataFrame with the DataFrame data.
"""
assert pd is not None
nindices = self.getNumIndices()
headers = self.getHeaders()
columns = {
header: list(self.getColumn(header))
for header in headers[nindices:]
}
index = zip(*[
list(self.getColumn(header))
for header in headers[:nindices]
])
index = [key if len(key) > 1 else key[0] for key in index]
if index == []:
return pd.DataFrame(columns, index=None)
else:
return pd.DataFrame(columns, index=index) | [
"def",
"toPandas",
"(",
"self",
")",
":",
"assert",
"pd",
"is",
"not",
"None",
"nindices",
"=",
"self",
".",
"getNumIndices",
"(",
")",
"headers",
"=",
"self",
".",
"getHeaders",
"(",
")",
"columns",
"=",
"{",
"header",
":",
"list",
"(",
"self",
".",
"getColumn",
"(",
"header",
")",
")",
"for",
"header",
"in",
"headers",
"[",
"nindices",
":",
"]",
"}",
"index",
"=",
"zip",
"(",
"*",
"[",
"list",
"(",
"self",
".",
"getColumn",
"(",
"header",
")",
")",
"for",
"header",
"in",
"headers",
"[",
":",
"nindices",
"]",
"]",
")",
"index",
"=",
"[",
"key",
"if",
"len",
"(",
"key",
")",
">",
"1",
"else",
"key",
"[",
"0",
"]",
"for",
"key",
"in",
"index",
"]",
"if",
"index",
"==",
"[",
"]",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"columns",
",",
"index",
"=",
"None",
")",
"else",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"columns",
",",
"index",
"=",
"index",
")"
] | Return a pandas DataFrame with the DataFrame data. | [
"Return",
"a",
"pandas",
"DataFrame",
"with",
"the",
"DataFrame",
"data",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L313-L332 | train | 234,861 |
ampl/amplpy | amplpy/parameter.py | Parameter.set | def set(self, *args):
"""
Set the value of a single instance of this parameter.
Args:
args: value if the parameter is scalar, index and value
otherwise.
Raises:
RuntimeError: If the entity has been deleted in the underlying
AMPL.
TypeError: If the parameter is not scalar and the index is not
provided.
"""
assert len(args) in (1, 2)
if len(args) == 1:
value = args[0]
self._impl.set(value)
else:
index, value = args
if isinstance(value, Real):
self._impl.setTplDbl(Tuple(index)._impl, value)
elif isinstance(value, basestring):
self._impl.setTplStr(Tuple(index)._impl, value)
else:
raise TypeError | python | def set(self, *args):
"""
Set the value of a single instance of this parameter.
Args:
args: value if the parameter is scalar, index and value
otherwise.
Raises:
RuntimeError: If the entity has been deleted in the underlying
AMPL.
TypeError: If the parameter is not scalar and the index is not
provided.
"""
assert len(args) in (1, 2)
if len(args) == 1:
value = args[0]
self._impl.set(value)
else:
index, value = args
if isinstance(value, Real):
self._impl.setTplDbl(Tuple(index)._impl, value)
elif isinstance(value, basestring):
self._impl.setTplStr(Tuple(index)._impl, value)
else:
raise TypeError | [
"def",
"set",
"(",
"self",
",",
"*",
"args",
")",
":",
"assert",
"len",
"(",
"args",
")",
"in",
"(",
"1",
",",
"2",
")",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"value",
"=",
"args",
"[",
"0",
"]",
"self",
".",
"_impl",
".",
"set",
"(",
"value",
")",
"else",
":",
"index",
",",
"value",
"=",
"args",
"if",
"isinstance",
"(",
"value",
",",
"Real",
")",
":",
"self",
".",
"_impl",
".",
"setTplDbl",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
",",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"self",
".",
"_impl",
".",
"setTplStr",
"(",
"Tuple",
"(",
"index",
")",
".",
"_impl",
",",
"value",
")",
"else",
":",
"raise",
"TypeError"
] | Set the value of a single instance of this parameter.
Args:
args: value if the parameter is scalar, index and value
otherwise.
Raises:
RuntimeError: If the entity has been deleted in the underlying
AMPL.
TypeError: If the parameter is not scalar and the index is not
provided. | [
"Set",
"the",
"value",
"of",
"a",
"single",
"instance",
"of",
"this",
"parameter",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/parameter.py#L70-L96 | train | 234,862 |
ampl/amplpy | amplpy/set.py | Set.setValues | def setValues(self, values):
"""
Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arity of the set. In the case of
a list of tuples, the arity of each tuple must be equal to the arity
of the set.
For example, considering the following AMPL entities and corresponding
Python objects:
.. code-block:: ampl
set A := 1..2;
param p{i in A} := i+10;
set AA;
The following is valid:
.. code-block:: python
A, AA = ampl.getSet('A'), ampl.getSet('AA')
AA.setValues(A.getValues()) # AA has now the members {1, 2}
"""
if isinstance(values, (list, set)):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesStr(values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesDbl(values, len(values))
elif all(isinstance(value, tuple) for value in values):
self._impl.setValues(Utils.toTupleArray(values), len(values))
else:
raise TypeError
else:
if np is not None and isinstance(values, np.ndarray):
self.setValues(DataFrame.fromNumpy(values).toList())
return
Entity.setValues(self, values) | python | def setValues(self, values):
"""
Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arity of the set. In the case of
a list of tuples, the arity of each tuple must be equal to the arity
of the set.
For example, considering the following AMPL entities and corresponding
Python objects:
.. code-block:: ampl
set A := 1..2;
param p{i in A} := i+10;
set AA;
The following is valid:
.. code-block:: python
A, AA = ampl.getSet('A'), ampl.getSet('AA')
AA.setValues(A.getValues()) # AA has now the members {1, 2}
"""
if isinstance(values, (list, set)):
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
self._impl.setValuesStr(values, len(values))
elif all(isinstance(value, Real) for value in values):
values = list(map(float, values))
self._impl.setValuesDbl(values, len(values))
elif all(isinstance(value, tuple) for value in values):
self._impl.setValues(Utils.toTupleArray(values), len(values))
else:
raise TypeError
else:
if np is not None and isinstance(values, np.ndarray):
self.setValues(DataFrame.fromNumpy(values).toList())
return
Entity.setValues(self, values) | [
"def",
"setValues",
"(",
"self",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"set",
")",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesStr",
"(",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"Real",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"values",
")",
")",
"self",
".",
"_impl",
".",
"setValuesDbl",
"(",
"values",
",",
"len",
"(",
"values",
")",
")",
"elif",
"all",
"(",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"for",
"value",
"in",
"values",
")",
":",
"self",
".",
"_impl",
".",
"setValues",
"(",
"Utils",
".",
"toTupleArray",
"(",
"values",
")",
",",
"len",
"(",
"values",
")",
")",
"else",
":",
"raise",
"TypeError",
"else",
":",
"if",
"np",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
":",
"self",
".",
"setValues",
"(",
"DataFrame",
".",
"fromNumpy",
"(",
"values",
")",
".",
"toList",
"(",
")",
")",
"return",
"Entity",
".",
"setValues",
"(",
"self",
",",
"values",
")"
] | Set the tuples in this set. Valid only for non-indexed sets.
Args:
values: A list of tuples or a :class:`~amplpy.DataFrame`.
In the case of a :class:`~amplpy.DataFrame`, the number of indexing
columns of the must be equal to the arity of the set. In the case of
a list of tuples, the arity of each tuple must be equal to the arity
of the set.
For example, considering the following AMPL entities and corresponding
Python objects:
.. code-block:: ampl
set A := 1..2;
param p{i in A} := i+10;
set AA;
The following is valid:
.. code-block:: python
A, AA = ampl.getSet('A'), ampl.getSet('AA')
AA.setValues(A.getValues()) # AA has now the members {1, 2} | [
"Set",
"the",
"tuples",
"in",
"this",
"set",
".",
"Valid",
"only",
"for",
"non",
"-",
"indexed",
"sets",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/set.py#L80-L123 | train | 234,863 |
ampl/amplpy | amplpy/errorhandler.py | ErrorHandler.error | def error(self, amplexception):
"""
Receives notification of an error.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Error:\n{:s}'.format(msg))
raise amplexception | python | def error(self, amplexception):
"""
Receives notification of an error.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Error:\n{:s}'.format(msg))
raise amplexception | [
"def",
"error",
"(",
"self",
",",
"amplexception",
")",
":",
"msg",
"=",
"'\\t'",
"+",
"str",
"(",
"amplexception",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"print",
"(",
"'Error:\\n{:s}'",
".",
"format",
"(",
"msg",
")",
")",
"raise",
"amplexception"
] | Receives notification of an error. | [
"Receives",
"notification",
"of",
"an",
"error",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/errorhandler.py#L18-L24 | train | 234,864 |
ampl/amplpy | amplpy/errorhandler.py | ErrorHandler.warning | def warning(self, amplexception):
"""
Receives notification of a warning.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Warning:\n{:s}'.format(msg)) | python | def warning(self, amplexception):
"""
Receives notification of a warning.
"""
msg = '\t'+str(amplexception).replace('\n', '\n\t')
print('Warning:\n{:s}'.format(msg)) | [
"def",
"warning",
"(",
"self",
",",
"amplexception",
")",
":",
"msg",
"=",
"'\\t'",
"+",
"str",
"(",
"amplexception",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\t'",
")",
"print",
"(",
"'Warning:\\n{:s}'",
".",
"format",
"(",
"msg",
")",
")"
] | Receives notification of a warning. | [
"Receives",
"notification",
"of",
"a",
"warning",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/errorhandler.py#L26-L31 | train | 234,865 |
ampl/amplpy | amplpy/utils.py | register_magics | def register_magics(store_name='_ampl_cells', ampl_object=None):
"""
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
"""
from IPython.core.magic import (
Magics, magics_class, cell_magic, line_magic
)
@magics_class
class StoreAMPL(Magics):
def __init__(self, shell=None, **kwargs):
Magics.__init__(self, shell=shell, **kwargs)
self._store = []
shell.user_ns[store_name] = self._store
@cell_magic
def ampl(self, line, cell):
"""Store the cell in the store"""
self._store.append(cell)
@cell_magic
def ampl_eval(self, line, cell):
"""Evaluate the cell"""
ampl_object.eval(cell)
@line_magic
def get_ampl(self, line):
"""Retrieve the store"""
return self._store
get_ipython().register_magics(StoreAMPL) | python | def register_magics(store_name='_ampl_cells', ampl_object=None):
"""
Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells.
"""
from IPython.core.magic import (
Magics, magics_class, cell_magic, line_magic
)
@magics_class
class StoreAMPL(Magics):
def __init__(self, shell=None, **kwargs):
Magics.__init__(self, shell=shell, **kwargs)
self._store = []
shell.user_ns[store_name] = self._store
@cell_magic
def ampl(self, line, cell):
"""Store the cell in the store"""
self._store.append(cell)
@cell_magic
def ampl_eval(self, line, cell):
"""Evaluate the cell"""
ampl_object.eval(cell)
@line_magic
def get_ampl(self, line):
"""Retrieve the store"""
return self._store
get_ipython().register_magics(StoreAMPL) | [
"def",
"register_magics",
"(",
"store_name",
"=",
"'_ampl_cells'",
",",
"ampl_object",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"core",
".",
"magic",
"import",
"(",
"Magics",
",",
"magics_class",
",",
"cell_magic",
",",
"line_magic",
")",
"@",
"magics_class",
"class",
"StoreAMPL",
"(",
"Magics",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"shell",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"Magics",
".",
"__init__",
"(",
"self",
",",
"shell",
"=",
"shell",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_store",
"=",
"[",
"]",
"shell",
".",
"user_ns",
"[",
"store_name",
"]",
"=",
"self",
".",
"_store",
"@",
"cell_magic",
"def",
"ampl",
"(",
"self",
",",
"line",
",",
"cell",
")",
":",
"\"\"\"Store the cell in the store\"\"\"",
"self",
".",
"_store",
".",
"append",
"(",
"cell",
")",
"@",
"cell_magic",
"def",
"ampl_eval",
"(",
"self",
",",
"line",
",",
"cell",
")",
":",
"\"\"\"Evaluate the cell\"\"\"",
"ampl_object",
".",
"eval",
"(",
"cell",
")",
"@",
"line_magic",
"def",
"get_ampl",
"(",
"self",
",",
"line",
")",
":",
"\"\"\"Retrieve the store\"\"\"",
"return",
"self",
".",
"_store",
"get_ipython",
"(",
")",
".",
"register_magics",
"(",
"StoreAMPL",
")"
] | Register jupyter notebook magics ``%%ampl`` and ``%%ampl_eval``.
Args:
store_name: Name of the store where ``%%ampl cells`` will be stored.
ampl_object: Object used to evaluate ``%%ampl_eval`` cells. | [
"Register",
"jupyter",
"notebook",
"magics",
"%%ampl",
"and",
"%%ampl_eval",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/utils.py#L11-L45 | train | 234,866 |
ampl/amplpy | amplpy/variable.py | Variable.fix | def fix(self, value=None):
"""
Fix all instances of this variable to a value if provided or to
their current value otherwise.
Args:
value: value to be set.
"""
if value is None:
self._impl.fix()
else:
self._impl.fix(value) | python | def fix(self, value=None):
"""
Fix all instances of this variable to a value if provided or to
their current value otherwise.
Args:
value: value to be set.
"""
if value is None:
self._impl.fix()
else:
self._impl.fix(value) | [
"def",
"fix",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"self",
".",
"_impl",
".",
"fix",
"(",
")",
"else",
":",
"self",
".",
"_impl",
".",
"fix",
"(",
"value",
")"
] | Fix all instances of this variable to a value if provided or to
their current value otherwise.
Args:
value: value to be set. | [
"Fix",
"all",
"instances",
"of",
"this",
"variable",
"to",
"a",
"value",
"if",
"provided",
"or",
"to",
"their",
"current",
"value",
"otherwise",
"."
] | 39df6954049a11a8f666aed26853259b4687099a | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/variable.py#L38-L50 | train | 234,867 |
eventable/vobject | vobject/base.py | toVName | def toVName(name, stripNum=0, upper=False):
"""
Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off.
"""
if upper:
name = name.upper()
if stripNum != 0:
name = name[:-stripNum]
return name.replace('_', '-') | python | def toVName(name, stripNum=0, upper=False):
"""
Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off.
"""
if upper:
name = name.upper()
if stripNum != 0:
name = name[:-stripNum]
return name.replace('_', '-') | [
"def",
"toVName",
"(",
"name",
",",
"stripNum",
"=",
"0",
",",
"upper",
"=",
"False",
")",
":",
"if",
"upper",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"stripNum",
"!=",
"0",
":",
"name",
"=",
"name",
"[",
":",
"-",
"stripNum",
"]",
"return",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")"
] | Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off. | [
"Turn",
"a",
"Python",
"name",
"into",
"an",
"iCalendar",
"style",
"name",
"optionally",
"uppercase",
"and",
"with",
"characters",
"stripped",
"off",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L261-L270 | train | 234,868 |
eventable/vobject | vobject/base.py | readComponents | def readComponents(streamOrString, validate=False, transform=True,
ignoreUnreadable=False, allowQP=False):
"""
Generate one Component at a time from a stream.
"""
if isinstance(streamOrString, basestring):
stream = six.StringIO(streamOrString)
else:
stream = streamOrString
try:
stack = Stack()
versionLine = None
n = 0
for line, n in getLogicalLines(stream, allowQP):
if ignoreUnreadable:
try:
vline = textLineToContentLine(line, n)
except VObjectError as e:
if e.lineNumber is not None:
msg = "Skipped line {lineNumber}, message: {msg}"
else:
msg = "Skipped a line, message: {msg}"
logger.error(msg.format(**{'lineNumber': e.lineNumber, 'msg': str(e)}))
continue
else:
vline = textLineToContentLine(line, n)
if vline.name == "VERSION":
versionLine = vline
stack.modifyTop(vline)
elif vline.name == "BEGIN":
stack.push(Component(vline.value, group=vline.group))
elif vline.name == "PROFILE":
if not stack.top():
stack.push(Component())
stack.top().setProfile(vline.value)
elif vline.name == "END":
if len(stack) == 0:
err = "Attempted to end the {0} component but it was never opened"
raise ParseError(err.format(vline.value), n)
if vline.value.upper() == stack.topName(): # START matches END
if len(stack) == 1:
component = stack.pop()
if versionLine is not None:
component.setBehaviorFromVersionLine(versionLine)
else:
behavior = getBehavior(component.name)
if behavior:
component.setBehavior(behavior)
if validate:
component.validate(raiseException=True)
if transform:
component.transformChildrenToNative()
yield component # EXIT POINT
else:
stack.modifyTop(stack.pop())
else:
err = "{0} component wasn't closed"
raise ParseError(err.format(stack.topName()), n)
else:
stack.modifyTop(vline) # not a START or END line
if stack.top():
if stack.topName() is None:
logger.warning("Top level component was never named")
elif stack.top().useBegin:
raise ParseError("Component {0!s} was never closed".format(
(stack.topName())), n)
yield stack.pop()
except ParseError as e:
e.input = streamOrString
raise | python | def readComponents(streamOrString, validate=False, transform=True,
ignoreUnreadable=False, allowQP=False):
"""
Generate one Component at a time from a stream.
"""
if isinstance(streamOrString, basestring):
stream = six.StringIO(streamOrString)
else:
stream = streamOrString
try:
stack = Stack()
versionLine = None
n = 0
for line, n in getLogicalLines(stream, allowQP):
if ignoreUnreadable:
try:
vline = textLineToContentLine(line, n)
except VObjectError as e:
if e.lineNumber is not None:
msg = "Skipped line {lineNumber}, message: {msg}"
else:
msg = "Skipped a line, message: {msg}"
logger.error(msg.format(**{'lineNumber': e.lineNumber, 'msg': str(e)}))
continue
else:
vline = textLineToContentLine(line, n)
if vline.name == "VERSION":
versionLine = vline
stack.modifyTop(vline)
elif vline.name == "BEGIN":
stack.push(Component(vline.value, group=vline.group))
elif vline.name == "PROFILE":
if not stack.top():
stack.push(Component())
stack.top().setProfile(vline.value)
elif vline.name == "END":
if len(stack) == 0:
err = "Attempted to end the {0} component but it was never opened"
raise ParseError(err.format(vline.value), n)
if vline.value.upper() == stack.topName(): # START matches END
if len(stack) == 1:
component = stack.pop()
if versionLine is not None:
component.setBehaviorFromVersionLine(versionLine)
else:
behavior = getBehavior(component.name)
if behavior:
component.setBehavior(behavior)
if validate:
component.validate(raiseException=True)
if transform:
component.transformChildrenToNative()
yield component # EXIT POINT
else:
stack.modifyTop(stack.pop())
else:
err = "{0} component wasn't closed"
raise ParseError(err.format(stack.topName()), n)
else:
stack.modifyTop(vline) # not a START or END line
if stack.top():
if stack.topName() is None:
logger.warning("Top level component was never named")
elif stack.top().useBegin:
raise ParseError("Component {0!s} was never closed".format(
(stack.topName())), n)
yield stack.pop()
except ParseError as e:
e.input = streamOrString
raise | [
"def",
"readComponents",
"(",
"streamOrString",
",",
"validate",
"=",
"False",
",",
"transform",
"=",
"True",
",",
"ignoreUnreadable",
"=",
"False",
",",
"allowQP",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"streamOrString",
",",
"basestring",
")",
":",
"stream",
"=",
"six",
".",
"StringIO",
"(",
"streamOrString",
")",
"else",
":",
"stream",
"=",
"streamOrString",
"try",
":",
"stack",
"=",
"Stack",
"(",
")",
"versionLine",
"=",
"None",
"n",
"=",
"0",
"for",
"line",
",",
"n",
"in",
"getLogicalLines",
"(",
"stream",
",",
"allowQP",
")",
":",
"if",
"ignoreUnreadable",
":",
"try",
":",
"vline",
"=",
"textLineToContentLine",
"(",
"line",
",",
"n",
")",
"except",
"VObjectError",
"as",
"e",
":",
"if",
"e",
".",
"lineNumber",
"is",
"not",
"None",
":",
"msg",
"=",
"\"Skipped line {lineNumber}, message: {msg}\"",
"else",
":",
"msg",
"=",
"\"Skipped a line, message: {msg}\"",
"logger",
".",
"error",
"(",
"msg",
".",
"format",
"(",
"*",
"*",
"{",
"'lineNumber'",
":",
"e",
".",
"lineNumber",
",",
"'msg'",
":",
"str",
"(",
"e",
")",
"}",
")",
")",
"continue",
"else",
":",
"vline",
"=",
"textLineToContentLine",
"(",
"line",
",",
"n",
")",
"if",
"vline",
".",
"name",
"==",
"\"VERSION\"",
":",
"versionLine",
"=",
"vline",
"stack",
".",
"modifyTop",
"(",
"vline",
")",
"elif",
"vline",
".",
"name",
"==",
"\"BEGIN\"",
":",
"stack",
".",
"push",
"(",
"Component",
"(",
"vline",
".",
"value",
",",
"group",
"=",
"vline",
".",
"group",
")",
")",
"elif",
"vline",
".",
"name",
"==",
"\"PROFILE\"",
":",
"if",
"not",
"stack",
".",
"top",
"(",
")",
":",
"stack",
".",
"push",
"(",
"Component",
"(",
")",
")",
"stack",
".",
"top",
"(",
")",
".",
"setProfile",
"(",
"vline",
".",
"value",
")",
"elif",
"vline",
".",
"name",
"==",
"\"END\"",
":",
"if",
"len",
"(",
"stack",
")",
"==",
"0",
":",
"err",
"=",
"\"Attempted to end the {0} component but it was never opened\"",
"raise",
"ParseError",
"(",
"err",
".",
"format",
"(",
"vline",
".",
"value",
")",
",",
"n",
")",
"if",
"vline",
".",
"value",
".",
"upper",
"(",
")",
"==",
"stack",
".",
"topName",
"(",
")",
":",
"# START matches END",
"if",
"len",
"(",
"stack",
")",
"==",
"1",
":",
"component",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"versionLine",
"is",
"not",
"None",
":",
"component",
".",
"setBehaviorFromVersionLine",
"(",
"versionLine",
")",
"else",
":",
"behavior",
"=",
"getBehavior",
"(",
"component",
".",
"name",
")",
"if",
"behavior",
":",
"component",
".",
"setBehavior",
"(",
"behavior",
")",
"if",
"validate",
":",
"component",
".",
"validate",
"(",
"raiseException",
"=",
"True",
")",
"if",
"transform",
":",
"component",
".",
"transformChildrenToNative",
"(",
")",
"yield",
"component",
"# EXIT POINT",
"else",
":",
"stack",
".",
"modifyTop",
"(",
"stack",
".",
"pop",
"(",
")",
")",
"else",
":",
"err",
"=",
"\"{0} component wasn't closed\"",
"raise",
"ParseError",
"(",
"err",
".",
"format",
"(",
"stack",
".",
"topName",
"(",
")",
")",
",",
"n",
")",
"else",
":",
"stack",
".",
"modifyTop",
"(",
"vline",
")",
"# not a START or END line",
"if",
"stack",
".",
"top",
"(",
")",
":",
"if",
"stack",
".",
"topName",
"(",
")",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Top level component was never named\"",
")",
"elif",
"stack",
".",
"top",
"(",
")",
".",
"useBegin",
":",
"raise",
"ParseError",
"(",
"\"Component {0!s} was never closed\"",
".",
"format",
"(",
"(",
"stack",
".",
"topName",
"(",
")",
")",
")",
",",
"n",
")",
"yield",
"stack",
".",
"pop",
"(",
")",
"except",
"ParseError",
"as",
"e",
":",
"e",
".",
"input",
"=",
"streamOrString",
"raise"
] | Generate one Component at a time from a stream. | [
"Generate",
"one",
"Component",
"at",
"a",
"time",
"from",
"a",
"stream",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1075-L1147 | train | 234,869 |
eventable/vobject | vobject/base.py | readOne | def readOne(stream, validate=False, transform=True, ignoreUnreadable=False,
allowQP=False):
"""
Return the first component from stream.
"""
return next(readComponents(stream, validate, transform, ignoreUnreadable,
allowQP)) | python | def readOne(stream, validate=False, transform=True, ignoreUnreadable=False,
allowQP=False):
"""
Return the first component from stream.
"""
return next(readComponents(stream, validate, transform, ignoreUnreadable,
allowQP)) | [
"def",
"readOne",
"(",
"stream",
",",
"validate",
"=",
"False",
",",
"transform",
"=",
"True",
",",
"ignoreUnreadable",
"=",
"False",
",",
"allowQP",
"=",
"False",
")",
":",
"return",
"next",
"(",
"readComponents",
"(",
"stream",
",",
"validate",
",",
"transform",
",",
"ignoreUnreadable",
",",
"allowQP",
")",
")"
] | Return the first component from stream. | [
"Return",
"the",
"first",
"component",
"from",
"stream",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1150-L1156 | train | 234,870 |
eventable/vobject | vobject/base.py | registerBehavior | def registerBehavior(behavior, name=None, default=False, id=None):
"""
Register the given behavior.
If default is True (or if this is the first version registered with this
name), the version will be the default if no id is given.
"""
if not name:
name = behavior.name.upper()
if id is None:
id = behavior.versionString
if name in __behaviorRegistry:
if default:
__behaviorRegistry[name].insert(0, (id, behavior))
else:
__behaviorRegistry[name].append((id, behavior))
else:
__behaviorRegistry[name] = [(id, behavior)] | python | def registerBehavior(behavior, name=None, default=False, id=None):
"""
Register the given behavior.
If default is True (or if this is the first version registered with this
name), the version will be the default if no id is given.
"""
if not name:
name = behavior.name.upper()
if id is None:
id = behavior.versionString
if name in __behaviorRegistry:
if default:
__behaviorRegistry[name].insert(0, (id, behavior))
else:
__behaviorRegistry[name].append((id, behavior))
else:
__behaviorRegistry[name] = [(id, behavior)] | [
"def",
"registerBehavior",
"(",
"behavior",
",",
"name",
"=",
"None",
",",
"default",
"=",
"False",
",",
"id",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"behavior",
".",
"name",
".",
"upper",
"(",
")",
"if",
"id",
"is",
"None",
":",
"id",
"=",
"behavior",
".",
"versionString",
"if",
"name",
"in",
"__behaviorRegistry",
":",
"if",
"default",
":",
"__behaviorRegistry",
"[",
"name",
"]",
".",
"insert",
"(",
"0",
",",
"(",
"id",
",",
"behavior",
")",
")",
"else",
":",
"__behaviorRegistry",
"[",
"name",
"]",
".",
"append",
"(",
"(",
"id",
",",
"behavior",
")",
")",
"else",
":",
"__behaviorRegistry",
"[",
"name",
"]",
"=",
"[",
"(",
"id",
",",
"behavior",
")",
"]"
] | Register the given behavior.
If default is True (or if this is the first version registered with this
name), the version will be the default if no id is given. | [
"Register",
"the",
"given",
"behavior",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1163-L1180 | train | 234,871 |
eventable/vobject | vobject/base.py | getBehavior | def getBehavior(name, id=None):
"""
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
"""
name = name.upper()
if name in __behaviorRegistry:
if id:
for n, behavior in __behaviorRegistry[name]:
if n == id:
return behavior
return __behaviorRegistry[name][0][1]
return None | python | def getBehavior(name, id=None):
"""
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
"""
name = name.upper()
if name in __behaviorRegistry:
if id:
for n, behavior in __behaviorRegistry[name]:
if n == id:
return behavior
return __behaviorRegistry[name][0][1]
return None | [
"def",
"getBehavior",
"(",
"name",
",",
"id",
"=",
"None",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"name",
"in",
"__behaviorRegistry",
":",
"if",
"id",
":",
"for",
"n",
",",
"behavior",
"in",
"__behaviorRegistry",
"[",
"name",
"]",
":",
"if",
"n",
"==",
"id",
":",
"return",
"behavior",
"return",
"__behaviorRegistry",
"[",
"name",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
"return",
"None"
] | Return a matching behavior if it exists, or None.
If id is None, return the default for name. | [
"Return",
"a",
"matching",
"behavior",
"if",
"it",
"exists",
"or",
"None",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L1183-L1197 | train | 234,872 |
eventable/vobject | vobject/base.py | VBase.validate | def validate(self, *args, **kwds):
"""
Call the behavior's validate method, or return True.
"""
if self.behavior:
return self.behavior.validate(self, *args, **kwds)
return True | python | def validate(self, *args, **kwds):
"""
Call the behavior's validate method, or return True.
"""
if self.behavior:
return self.behavior.validate(self, *args, **kwds)
return True | [
"def",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"self",
".",
"behavior",
":",
"return",
"self",
".",
"behavior",
".",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
"True"
] | Call the behavior's validate method, or return True. | [
"Call",
"the",
"behavior",
"s",
"validate",
"method",
"or",
"return",
"True",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L119-L125 | train | 234,873 |
eventable/vobject | vobject/base.py | VBase.autoBehavior | def autoBehavior(self, cascade=False):
"""
Set behavior if name is in self.parentBehavior.knownChildren.
If cascade is True, unset behavior and parentBehavior for all
descendants, then recalculate behavior and parentBehavior.
"""
parentBehavior = self.parentBehavior
if parentBehavior is not None:
knownChildTup = parentBehavior.knownChildren.get(self.name, None)
if knownChildTup is not None:
behavior = getBehavior(self.name, knownChildTup[2])
if behavior is not None:
self.setBehavior(behavior, cascade)
if isinstance(self, ContentLine) and self.encoded:
self.behavior.decode(self)
elif isinstance(self, ContentLine):
self.behavior = parentBehavior.defaultBehavior
if self.encoded and self.behavior:
self.behavior.decode(self) | python | def autoBehavior(self, cascade=False):
"""
Set behavior if name is in self.parentBehavior.knownChildren.
If cascade is True, unset behavior and parentBehavior for all
descendants, then recalculate behavior and parentBehavior.
"""
parentBehavior = self.parentBehavior
if parentBehavior is not None:
knownChildTup = parentBehavior.knownChildren.get(self.name, None)
if knownChildTup is not None:
behavior = getBehavior(self.name, knownChildTup[2])
if behavior is not None:
self.setBehavior(behavior, cascade)
if isinstance(self, ContentLine) and self.encoded:
self.behavior.decode(self)
elif isinstance(self, ContentLine):
self.behavior = parentBehavior.defaultBehavior
if self.encoded and self.behavior:
self.behavior.decode(self) | [
"def",
"autoBehavior",
"(",
"self",
",",
"cascade",
"=",
"False",
")",
":",
"parentBehavior",
"=",
"self",
".",
"parentBehavior",
"if",
"parentBehavior",
"is",
"not",
"None",
":",
"knownChildTup",
"=",
"parentBehavior",
".",
"knownChildren",
".",
"get",
"(",
"self",
".",
"name",
",",
"None",
")",
"if",
"knownChildTup",
"is",
"not",
"None",
":",
"behavior",
"=",
"getBehavior",
"(",
"self",
".",
"name",
",",
"knownChildTup",
"[",
"2",
"]",
")",
"if",
"behavior",
"is",
"not",
"None",
":",
"self",
".",
"setBehavior",
"(",
"behavior",
",",
"cascade",
")",
"if",
"isinstance",
"(",
"self",
",",
"ContentLine",
")",
"and",
"self",
".",
"encoded",
":",
"self",
".",
"behavior",
".",
"decode",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"self",
",",
"ContentLine",
")",
":",
"self",
".",
"behavior",
"=",
"parentBehavior",
".",
"defaultBehavior",
"if",
"self",
".",
"encoded",
"and",
"self",
".",
"behavior",
":",
"self",
".",
"behavior",
".",
"decode",
"(",
"self",
")"
] | Set behavior if name is in self.parentBehavior.knownChildren.
If cascade is True, unset behavior and parentBehavior for all
descendants, then recalculate behavior and parentBehavior. | [
"Set",
"behavior",
"if",
"name",
"is",
"in",
"self",
".",
"parentBehavior",
".",
"knownChildren",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L141-L160 | train | 234,874 |
eventable/vobject | vobject/base.py | VBase.setBehavior | def setBehavior(self, behavior, cascade=True):
"""
Set behavior. If cascade is True, autoBehavior all descendants.
"""
self.behavior = behavior
if cascade:
for obj in self.getChildren():
obj.parentBehavior = behavior
obj.autoBehavior(True) | python | def setBehavior(self, behavior, cascade=True):
"""
Set behavior. If cascade is True, autoBehavior all descendants.
"""
self.behavior = behavior
if cascade:
for obj in self.getChildren():
obj.parentBehavior = behavior
obj.autoBehavior(True) | [
"def",
"setBehavior",
"(",
"self",
",",
"behavior",
",",
"cascade",
"=",
"True",
")",
":",
"self",
".",
"behavior",
"=",
"behavior",
"if",
"cascade",
":",
"for",
"obj",
"in",
"self",
".",
"getChildren",
"(",
")",
":",
"obj",
".",
"parentBehavior",
"=",
"behavior",
"obj",
".",
"autoBehavior",
"(",
"True",
")"
] | Set behavior. If cascade is True, autoBehavior all descendants. | [
"Set",
"behavior",
".",
"If",
"cascade",
"is",
"True",
"autoBehavior",
"all",
"descendants",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L162-L170 | train | 234,875 |
eventable/vobject | vobject/base.py | VBase.serialize | def serialize(self, buf=None, lineLength=75, validate=True, behavior=None):
"""
Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists.
"""
if not behavior:
behavior = self.behavior
if behavior:
if DEBUG:
logger.debug("serializing {0!s} with behavior {1!s}".format(self.name, behavior))
return behavior.serialize(self, buf, lineLength, validate)
else:
if DEBUG:
logger.debug("serializing {0!s} without behavior".format(self.name))
return defaultSerialize(self, buf, lineLength) | python | def serialize(self, buf=None, lineLength=75, validate=True, behavior=None):
"""
Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists.
"""
if not behavior:
behavior = self.behavior
if behavior:
if DEBUG:
logger.debug("serializing {0!s} with behavior {1!s}".format(self.name, behavior))
return behavior.serialize(self, buf, lineLength, validate)
else:
if DEBUG:
logger.debug("serializing {0!s} without behavior".format(self.name))
return defaultSerialize(self, buf, lineLength) | [
"def",
"serialize",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"lineLength",
"=",
"75",
",",
"validate",
"=",
"True",
",",
"behavior",
"=",
"None",
")",
":",
"if",
"not",
"behavior",
":",
"behavior",
"=",
"self",
".",
"behavior",
"if",
"behavior",
":",
"if",
"DEBUG",
":",
"logger",
".",
"debug",
"(",
"\"serializing {0!s} with behavior {1!s}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"behavior",
")",
")",
"return",
"behavior",
".",
"serialize",
"(",
"self",
",",
"buf",
",",
"lineLength",
",",
"validate",
")",
"else",
":",
"if",
"DEBUG",
":",
"logger",
".",
"debug",
"(",
"\"serializing {0!s} without behavior\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"defaultSerialize",
"(",
"self",
",",
"buf",
",",
"lineLength",
")"
] | Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists. | [
"Serialize",
"to",
"buf",
"if",
"it",
"exists",
"otherwise",
"return",
"a",
"string",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L242-L258 | train | 234,876 |
eventable/vobject | vobject/base.py | ContentLine.valueRepr | def valueRepr(self):
"""
Transform the representation of the value
according to the behavior, if any.
"""
v = self.value
if self.behavior:
v = self.behavior.valueRepr(self)
return v | python | def valueRepr(self):
"""
Transform the representation of the value
according to the behavior, if any.
"""
v = self.value
if self.behavior:
v = self.behavior.valueRepr(self)
return v | [
"def",
"valueRepr",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"value",
"if",
"self",
".",
"behavior",
":",
"v",
"=",
"self",
".",
"behavior",
".",
"valueRepr",
"(",
"self",
")",
"return",
"v"
] | Transform the representation of the value
according to the behavior, if any. | [
"Transform",
"the",
"representation",
"of",
"the",
"value",
"according",
"to",
"the",
"behavior",
"if",
"any",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L419-L427 | train | 234,877 |
eventable/vobject | vobject/base.py | Component.setProfile | def setProfile(self, name):
"""
Assign a PROFILE to this unnamed component.
Used by vCard, not by vCalendar.
"""
if self.name or self.useBegin:
if self.name == name:
return
raise VObjectError("This component already has a PROFILE or "
"uses BEGIN.")
self.name = name.upper() | python | def setProfile(self, name):
"""
Assign a PROFILE to this unnamed component.
Used by vCard, not by vCalendar.
"""
if self.name or self.useBegin:
if self.name == name:
return
raise VObjectError("This component already has a PROFILE or "
"uses BEGIN.")
self.name = name.upper() | [
"def",
"setProfile",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"name",
"or",
"self",
".",
"useBegin",
":",
"if",
"self",
".",
"name",
"==",
"name",
":",
"return",
"raise",
"VObjectError",
"(",
"\"This component already has a PROFILE or \"",
"\"uses BEGIN.\"",
")",
"self",
".",
"name",
"=",
"name",
".",
"upper",
"(",
")"
] | Assign a PROFILE to this unnamed component.
Used by vCard, not by vCalendar. | [
"Assign",
"a",
"PROFILE",
"to",
"this",
"unnamed",
"component",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L501-L512 | train | 234,878 |
eventable/vobject | vobject/base.py | Component.add | def add(self, objOrName, group=None):
"""
Add objOrName to contents, set behavior if it can be inferred.
If objOrName is a string, create an empty component or line based on
behavior. If no behavior is found for the object, add a ContentLine.
group is an optional prefix to the name of the object (see RFC 2425).
"""
if isinstance(objOrName, VBase):
obj = objOrName
if self.behavior:
obj.parentBehavior = self.behavior
obj.autoBehavior(True)
else:
name = objOrName.upper()
try:
id = self.behavior.knownChildren[name][2]
behavior = getBehavior(name, id)
if behavior.isComponent:
obj = Component(name)
else:
obj = ContentLine(name, [], '', group)
obj.parentBehavior = self.behavior
obj.behavior = behavior
obj = obj.transformToNative()
except (KeyError, AttributeError):
obj = ContentLine(objOrName, [], '', group)
if obj.behavior is None and self.behavior is not None:
if isinstance(obj, ContentLine):
obj.behavior = self.behavior.defaultBehavior
self.contents.setdefault(obj.name.lower(), []).append(obj)
return obj | python | def add(self, objOrName, group=None):
"""
Add objOrName to contents, set behavior if it can be inferred.
If objOrName is a string, create an empty component or line based on
behavior. If no behavior is found for the object, add a ContentLine.
group is an optional prefix to the name of the object (see RFC 2425).
"""
if isinstance(objOrName, VBase):
obj = objOrName
if self.behavior:
obj.parentBehavior = self.behavior
obj.autoBehavior(True)
else:
name = objOrName.upper()
try:
id = self.behavior.knownChildren[name][2]
behavior = getBehavior(name, id)
if behavior.isComponent:
obj = Component(name)
else:
obj = ContentLine(name, [], '', group)
obj.parentBehavior = self.behavior
obj.behavior = behavior
obj = obj.transformToNative()
except (KeyError, AttributeError):
obj = ContentLine(objOrName, [], '', group)
if obj.behavior is None and self.behavior is not None:
if isinstance(obj, ContentLine):
obj.behavior = self.behavior.defaultBehavior
self.contents.setdefault(obj.name.lower(), []).append(obj)
return obj | [
"def",
"add",
"(",
"self",
",",
"objOrName",
",",
"group",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"objOrName",
",",
"VBase",
")",
":",
"obj",
"=",
"objOrName",
"if",
"self",
".",
"behavior",
":",
"obj",
".",
"parentBehavior",
"=",
"self",
".",
"behavior",
"obj",
".",
"autoBehavior",
"(",
"True",
")",
"else",
":",
"name",
"=",
"objOrName",
".",
"upper",
"(",
")",
"try",
":",
"id",
"=",
"self",
".",
"behavior",
".",
"knownChildren",
"[",
"name",
"]",
"[",
"2",
"]",
"behavior",
"=",
"getBehavior",
"(",
"name",
",",
"id",
")",
"if",
"behavior",
".",
"isComponent",
":",
"obj",
"=",
"Component",
"(",
"name",
")",
"else",
":",
"obj",
"=",
"ContentLine",
"(",
"name",
",",
"[",
"]",
",",
"''",
",",
"group",
")",
"obj",
".",
"parentBehavior",
"=",
"self",
".",
"behavior",
"obj",
".",
"behavior",
"=",
"behavior",
"obj",
"=",
"obj",
".",
"transformToNative",
"(",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"obj",
"=",
"ContentLine",
"(",
"objOrName",
",",
"[",
"]",
",",
"''",
",",
"group",
")",
"if",
"obj",
".",
"behavior",
"is",
"None",
"and",
"self",
".",
"behavior",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ContentLine",
")",
":",
"obj",
".",
"behavior",
"=",
"self",
".",
"behavior",
".",
"defaultBehavior",
"self",
".",
"contents",
".",
"setdefault",
"(",
"obj",
".",
"name",
".",
"lower",
"(",
")",
",",
"[",
"]",
")",
".",
"append",
"(",
"obj",
")",
"return",
"obj"
] | Add objOrName to contents, set behavior if it can be inferred.
If objOrName is a string, create an empty component or line based on
behavior. If no behavior is found for the object, add a ContentLine.
group is an optional prefix to the name of the object (see RFC 2425). | [
"Add",
"objOrName",
"to",
"contents",
"set",
"behavior",
"if",
"it",
"can",
"be",
"inferred",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L580-L612 | train | 234,879 |
eventable/vobject | vobject/base.py | Component.remove | def remove(self, obj):
"""
Remove obj from contents.
"""
named = self.contents.get(obj.name.lower())
if named:
try:
named.remove(obj)
if len(named) == 0:
del self.contents[obj.name.lower()]
except ValueError:
pass | python | def remove(self, obj):
"""
Remove obj from contents.
"""
named = self.contents.get(obj.name.lower())
if named:
try:
named.remove(obj)
if len(named) == 0:
del self.contents[obj.name.lower()]
except ValueError:
pass | [
"def",
"remove",
"(",
"self",
",",
"obj",
")",
":",
"named",
"=",
"self",
".",
"contents",
".",
"get",
"(",
"obj",
".",
"name",
".",
"lower",
"(",
")",
")",
"if",
"named",
":",
"try",
":",
"named",
".",
"remove",
"(",
"obj",
")",
"if",
"len",
"(",
"named",
")",
"==",
"0",
":",
"del",
"self",
".",
"contents",
"[",
"obj",
".",
"name",
".",
"lower",
"(",
")",
"]",
"except",
"ValueError",
":",
"pass"
] | Remove obj from contents. | [
"Remove",
"obj",
"from",
"contents",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L614-L625 | train | 234,880 |
eventable/vobject | vobject/base.py | Component.setBehaviorFromVersionLine | def setBehaviorFromVersionLine(self, versionLine):
"""
Set behavior if one matches name, versionLine.value.
"""
v = getBehavior(self.name, versionLine.value)
if v:
self.setBehavior(v) | python | def setBehaviorFromVersionLine(self, versionLine):
"""
Set behavior if one matches name, versionLine.value.
"""
v = getBehavior(self.name, versionLine.value)
if v:
self.setBehavior(v) | [
"def",
"setBehaviorFromVersionLine",
"(",
"self",
",",
"versionLine",
")",
":",
"v",
"=",
"getBehavior",
"(",
"self",
".",
"name",
",",
"versionLine",
".",
"value",
")",
"if",
"v",
":",
"self",
".",
"setBehavior",
"(",
"v",
")"
] | Set behavior if one matches name, versionLine.value. | [
"Set",
"behavior",
"if",
"one",
"matches",
"name",
"versionLine",
".",
"value",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L657-L663 | train | 234,881 |
eventable/vobject | vobject/base.py | Component.transformChildrenToNative | def transformChildrenToNative(self):
"""
Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent.
"""
for childArray in (self.contents[k] for k in self.sortChildKeys()):
for child in childArray:
child = child.transformToNative()
child.transformChildrenToNative() | python | def transformChildrenToNative(self):
"""
Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent.
"""
for childArray in (self.contents[k] for k in self.sortChildKeys()):
for child in childArray:
child = child.transformToNative()
child.transformChildrenToNative() | [
"def",
"transformChildrenToNative",
"(",
"self",
")",
":",
"for",
"childArray",
"in",
"(",
"self",
".",
"contents",
"[",
"k",
"]",
"for",
"k",
"in",
"self",
".",
"sortChildKeys",
"(",
")",
")",
":",
"for",
"child",
"in",
"childArray",
":",
"child",
"=",
"child",
".",
"transformToNative",
"(",
")",
"child",
".",
"transformChildrenToNative",
"(",
")"
] | Recursively replace children with their native representation.
Sort to get dependency order right, like vtimezone before vevent. | [
"Recursively",
"replace",
"children",
"with",
"their",
"native",
"representation",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L665-L674 | train | 234,882 |
eventable/vobject | vobject/base.py | Component.transformChildrenFromNative | def transformChildrenFromNative(self, clearBehavior=True):
"""
Recursively transform native children to vanilla representations.
"""
for childArray in self.contents.values():
for child in childArray:
child = child.transformFromNative()
child.transformChildrenFromNative(clearBehavior)
if clearBehavior:
child.behavior = None
child.parentBehavior = None | python | def transformChildrenFromNative(self, clearBehavior=True):
"""
Recursively transform native children to vanilla representations.
"""
for childArray in self.contents.values():
for child in childArray:
child = child.transformFromNative()
child.transformChildrenFromNative(clearBehavior)
if clearBehavior:
child.behavior = None
child.parentBehavior = None | [
"def",
"transformChildrenFromNative",
"(",
"self",
",",
"clearBehavior",
"=",
"True",
")",
":",
"for",
"childArray",
"in",
"self",
".",
"contents",
".",
"values",
"(",
")",
":",
"for",
"child",
"in",
"childArray",
":",
"child",
"=",
"child",
".",
"transformFromNative",
"(",
")",
"child",
".",
"transformChildrenFromNative",
"(",
"clearBehavior",
")",
"if",
"clearBehavior",
":",
"child",
".",
"behavior",
"=",
"None",
"child",
".",
"parentBehavior",
"=",
"None"
] | Recursively transform native children to vanilla representations. | [
"Recursively",
"transform",
"native",
"children",
"to",
"vanilla",
"representations",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L676-L686 | train | 234,883 |
eventable/vobject | docs/build/lib/vobject/change_tz.py | change_tz | def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
"""
Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only convert dates that are in utc
utc_tz (tzinfo): the tzinfo to compare to for UTC when processing
utc_only=True
"""
for vevent in getattr(cal, 'vevent_list', []):
start = getattr(vevent, 'dtstart', None)
end = getattr(vevent, 'dtend', None)
for node in (start, end):
if node:
dt = node.value
if (isinstance(dt, datetime) and
(not utc_only or dt.tzinfo == utc_tz)):
if dt.tzinfo is None:
dt = dt.replace(tzinfo = default)
node.value = dt.astimezone(new_timezone) | python | def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc):
"""
Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only convert dates that are in utc
utc_tz (tzinfo): the tzinfo to compare to for UTC when processing
utc_only=True
"""
for vevent in getattr(cal, 'vevent_list', []):
start = getattr(vevent, 'dtstart', None)
end = getattr(vevent, 'dtend', None)
for node in (start, end):
if node:
dt = node.value
if (isinstance(dt, datetime) and
(not utc_only or dt.tzinfo == utc_tz)):
if dt.tzinfo is None:
dt = dt.replace(tzinfo = default)
node.value = dt.astimezone(new_timezone) | [
"def",
"change_tz",
"(",
"cal",
",",
"new_timezone",
",",
"default",
",",
"utc_only",
"=",
"False",
",",
"utc_tz",
"=",
"icalendar",
".",
"utc",
")",
":",
"for",
"vevent",
"in",
"getattr",
"(",
"cal",
",",
"'vevent_list'",
",",
"[",
"]",
")",
":",
"start",
"=",
"getattr",
"(",
"vevent",
",",
"'dtstart'",
",",
"None",
")",
"end",
"=",
"getattr",
"(",
"vevent",
",",
"'dtend'",
",",
"None",
")",
"for",
"node",
"in",
"(",
"start",
",",
"end",
")",
":",
"if",
"node",
":",
"dt",
"=",
"node",
".",
"value",
"if",
"(",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
"and",
"(",
"not",
"utc_only",
"or",
"dt",
".",
"tzinfo",
"==",
"utc_tz",
")",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"default",
")",
"node",
".",
"value",
"=",
"dt",
".",
"astimezone",
"(",
"new_timezone",
")"
] | Change the timezone of the specified component.
Args:
cal (Component): the component to change
new_timezone (tzinfo): the timezone to change to
default (tzinfo): a timezone to assume if the dtstart or dtend in cal
doesn't have an existing timezone
utc_only (bool): only convert dates that are in utc
utc_tz (tzinfo): the tzinfo to compare to for UTC when processing
utc_only=True | [
"Change",
"the",
"timezone",
"of",
"the",
"specified",
"component",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/change_tz.py#L13-L37 | train | 234,884 |
eventable/vobject | docs/build/lib/vobject/base.py | defaultSerialize | def defaultSerialize(obj, buf, lineLength):
"""
Encode and fold obj and its children, write to buf or return a string.
"""
outbuf = buf or six.StringIO()
if isinstance(obj, Component):
if obj.group is None:
groupString = ''
else:
groupString = obj.group + '.'
if obj.useBegin:
foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name),
lineLength)
for child in obj.getSortedChildren():
# validate is recursive, we only need to validate once
child.serialize(outbuf, lineLength, validate=False)
if obj.useBegin:
foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name),
lineLength)
elif isinstance(obj, ContentLine):
startedEncoded = obj.encoded
if obj.behavior and not startedEncoded:
obj.behavior.encode(obj)
s = six.StringIO()
if obj.group is not None:
s.write(obj.group + '.')
s.write(obj.name.upper())
keys = sorted(obj.params.keys())
for key in keys:
paramstr = ','.join(dquoteEscape(p) for p in obj.params[key])
s.write(";{0}={1}".format(key, paramstr))
s.write(":{0}".format(str_(obj.value)))
if obj.behavior and not startedEncoded:
obj.behavior.decode(obj)
foldOneLine(outbuf, s.getvalue(), lineLength)
return buf or outbuf.getvalue() | python | def defaultSerialize(obj, buf, lineLength):
"""
Encode and fold obj and its children, write to buf or return a string.
"""
outbuf = buf or six.StringIO()
if isinstance(obj, Component):
if obj.group is None:
groupString = ''
else:
groupString = obj.group + '.'
if obj.useBegin:
foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name),
lineLength)
for child in obj.getSortedChildren():
# validate is recursive, we only need to validate once
child.serialize(outbuf, lineLength, validate=False)
if obj.useBegin:
foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name),
lineLength)
elif isinstance(obj, ContentLine):
startedEncoded = obj.encoded
if obj.behavior and not startedEncoded:
obj.behavior.encode(obj)
s = six.StringIO()
if obj.group is not None:
s.write(obj.group + '.')
s.write(obj.name.upper())
keys = sorted(obj.params.keys())
for key in keys:
paramstr = ','.join(dquoteEscape(p) for p in obj.params[key])
s.write(";{0}={1}".format(key, paramstr))
s.write(":{0}".format(str_(obj.value)))
if obj.behavior and not startedEncoded:
obj.behavior.decode(obj)
foldOneLine(outbuf, s.getvalue(), lineLength)
return buf or outbuf.getvalue() | [
"def",
"defaultSerialize",
"(",
"obj",
",",
"buf",
",",
"lineLength",
")",
":",
"outbuf",
"=",
"buf",
"or",
"six",
".",
"StringIO",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Component",
")",
":",
"if",
"obj",
".",
"group",
"is",
"None",
":",
"groupString",
"=",
"''",
"else",
":",
"groupString",
"=",
"obj",
".",
"group",
"+",
"'.'",
"if",
"obj",
".",
"useBegin",
":",
"foldOneLine",
"(",
"outbuf",
",",
"\"{0}BEGIN:{1}\"",
".",
"format",
"(",
"groupString",
",",
"obj",
".",
"name",
")",
",",
"lineLength",
")",
"for",
"child",
"in",
"obj",
".",
"getSortedChildren",
"(",
")",
":",
"# validate is recursive, we only need to validate once",
"child",
".",
"serialize",
"(",
"outbuf",
",",
"lineLength",
",",
"validate",
"=",
"False",
")",
"if",
"obj",
".",
"useBegin",
":",
"foldOneLine",
"(",
"outbuf",
",",
"\"{0}END:{1}\"",
".",
"format",
"(",
"groupString",
",",
"obj",
".",
"name",
")",
",",
"lineLength",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"ContentLine",
")",
":",
"startedEncoded",
"=",
"obj",
".",
"encoded",
"if",
"obj",
".",
"behavior",
"and",
"not",
"startedEncoded",
":",
"obj",
".",
"behavior",
".",
"encode",
"(",
"obj",
")",
"s",
"=",
"six",
".",
"StringIO",
"(",
")",
"if",
"obj",
".",
"group",
"is",
"not",
"None",
":",
"s",
".",
"write",
"(",
"obj",
".",
"group",
"+",
"'.'",
")",
"s",
".",
"write",
"(",
"obj",
".",
"name",
".",
"upper",
"(",
")",
")",
"keys",
"=",
"sorted",
"(",
"obj",
".",
"params",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"paramstr",
"=",
"','",
".",
"join",
"(",
"dquoteEscape",
"(",
"p",
")",
"for",
"p",
"in",
"obj",
".",
"params",
"[",
"key",
"]",
")",
"s",
".",
"write",
"(",
"\";{0}={1}\"",
".",
"format",
"(",
"key",
",",
"paramstr",
")",
")",
"s",
".",
"write",
"(",
"\":{0}\"",
".",
"format",
"(",
"str_",
"(",
"obj",
".",
"value",
")",
")",
")",
"if",
"obj",
".",
"behavior",
"and",
"not",
"startedEncoded",
":",
"obj",
".",
"behavior",
".",
"decode",
"(",
"obj",
")",
"foldOneLine",
"(",
"outbuf",
",",
"s",
".",
"getvalue",
"(",
")",
",",
"lineLength",
")",
"return",
"buf",
"or",
"outbuf",
".",
"getvalue",
"(",
")"
] | Encode and fold obj and its children, write to buf or return a string. | [
"Encode",
"and",
"fold",
"obj",
"and",
"its",
"children",
"write",
"to",
"buf",
"or",
"return",
"a",
"string",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/base.py#L977-L1017 | train | 234,885 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | toUnicode | def toUnicode(s):
"""
Take a string or unicode, turn it into unicode, decoding as utf-8
"""
if isinstance(s, six.binary_type):
s = s.decode('utf-8')
return s | python | def toUnicode(s):
"""
Take a string or unicode, turn it into unicode, decoding as utf-8
"""
if isinstance(s, six.binary_type):
s = s.decode('utf-8')
return s | [
"def",
"toUnicode",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"s"
] | Take a string or unicode, turn it into unicode, decoding as utf-8 | [
"Take",
"a",
"string",
"or",
"unicode",
"turn",
"it",
"into",
"unicode",
"decoding",
"as",
"utf",
"-",
"8"
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L54-L60 | train | 234,886 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | numToDigits | def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s | python | def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s | [
"def",
"numToDigits",
"(",
"num",
",",
"places",
")",
":",
"s",
"=",
"str",
"(",
"num",
")",
"if",
"len",
"(",
"s",
")",
"<",
"places",
":",
"return",
"(",
"\"0\"",
"*",
"(",
"places",
"-",
"len",
"(",
"s",
")",
")",
")",
"+",
"s",
"elif",
"len",
"(",
"s",
")",
">",
"places",
":",
"return",
"s",
"[",
"len",
"(",
"s",
")",
"-",
"places",
":",
"]",
"else",
":",
"return",
"s"
] | Helper, for converting numbers to textual digits. | [
"Helper",
"for",
"converting",
"numbers",
"to",
"textual",
"digits",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1503-L1513 | train | 234,887 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | timedeltaToString | def timedeltaToString(delta):
"""
Convert timedelta to an ical DURATION.
"""
if delta.days == 0:
sign = 1
else:
sign = delta.days / abs(delta.days)
delta = abs(delta)
days = delta.days
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
seconds = int(delta.seconds % 60)
output = ''
if sign == -1:
output += '-'
output += 'P'
if days:
output += '{}D'.format(days)
if hours or minutes or seconds:
output += 'T'
elif not days: # Deal with zero duration
output += 'T0S'
if hours:
output += '{}H'.format(hours)
if minutes:
output += '{}M'.format(minutes)
if seconds:
output += '{}S'.format(seconds)
return output | python | def timedeltaToString(delta):
"""
Convert timedelta to an ical DURATION.
"""
if delta.days == 0:
sign = 1
else:
sign = delta.days / abs(delta.days)
delta = abs(delta)
days = delta.days
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
seconds = int(delta.seconds % 60)
output = ''
if sign == -1:
output += '-'
output += 'P'
if days:
output += '{}D'.format(days)
if hours or minutes or seconds:
output += 'T'
elif not days: # Deal with zero duration
output += 'T0S'
if hours:
output += '{}H'.format(hours)
if minutes:
output += '{}M'.format(minutes)
if seconds:
output += '{}S'.format(seconds)
return output | [
"def",
"timedeltaToString",
"(",
"delta",
")",
":",
"if",
"delta",
".",
"days",
"==",
"0",
":",
"sign",
"=",
"1",
"else",
":",
"sign",
"=",
"delta",
".",
"days",
"/",
"abs",
"(",
"delta",
".",
"days",
")",
"delta",
"=",
"abs",
"(",
"delta",
")",
"days",
"=",
"delta",
".",
"days",
"hours",
"=",
"int",
"(",
"delta",
".",
"seconds",
"/",
"3600",
")",
"minutes",
"=",
"int",
"(",
"(",
"delta",
".",
"seconds",
"%",
"3600",
")",
"/",
"60",
")",
"seconds",
"=",
"int",
"(",
"delta",
".",
"seconds",
"%",
"60",
")",
"output",
"=",
"''",
"if",
"sign",
"==",
"-",
"1",
":",
"output",
"+=",
"'-'",
"output",
"+=",
"'P'",
"if",
"days",
":",
"output",
"+=",
"'{}D'",
".",
"format",
"(",
"days",
")",
"if",
"hours",
"or",
"minutes",
"or",
"seconds",
":",
"output",
"+=",
"'T'",
"elif",
"not",
"days",
":",
"# Deal with zero duration",
"output",
"+=",
"'T0S'",
"if",
"hours",
":",
"output",
"+=",
"'{}H'",
".",
"format",
"(",
"hours",
")",
"if",
"minutes",
":",
"output",
"+=",
"'{}M'",
".",
"format",
"(",
"minutes",
")",
"if",
"seconds",
":",
"output",
"+=",
"'{}S'",
".",
"format",
"(",
"seconds",
")",
"return",
"output"
] | Convert timedelta to an ical DURATION. | [
"Convert",
"timedelta",
"to",
"an",
"ical",
"DURATION",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1515-L1545 | train | 234,888 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | stringToTextValues | def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
"""
Returns list of strings.
"""
if charList is None:
charList = escapableCharList
def escapableChar (c):
return c in charList
def error(msg):
if strict:
raise ParseError(msg)
else:
logging.error(msg)
# vars which control state machine
charIterator = enumerate(s)
state = "read normal"
current = []
results = []
while True:
try:
charIndex, char = next(charIterator)
except:
char = "eof"
if state == "read normal":
if char == '\\':
state = "read escaped char"
elif char == listSeparator:
state = "read normal"
current = "".join(current)
results.append(current)
current = []
elif char == "eof":
state = "end"
else:
state = "read normal"
current.append(char)
elif state == "read escaped char":
if escapableChar(char):
state = "read normal"
if char in 'nN':
current.append('\n')
else:
current.append(char)
else:
state = "read normal"
# leave unrecognized escaped characters for later passes
current.append('\\' + char)
elif state == "end": # an end state
if len(current) or len(results) == 0:
current = "".join(current)
results.append(current)
return results
elif state == "error": # an end state
return results
else:
state = "error"
error("unknown state: '{0!s}' reached in {1!s}".format(state, s)) | python | def stringToTextValues(s, listSeparator=',', charList=None, strict=False):
"""
Returns list of strings.
"""
if charList is None:
charList = escapableCharList
def escapableChar (c):
return c in charList
def error(msg):
if strict:
raise ParseError(msg)
else:
logging.error(msg)
# vars which control state machine
charIterator = enumerate(s)
state = "read normal"
current = []
results = []
while True:
try:
charIndex, char = next(charIterator)
except:
char = "eof"
if state == "read normal":
if char == '\\':
state = "read escaped char"
elif char == listSeparator:
state = "read normal"
current = "".join(current)
results.append(current)
current = []
elif char == "eof":
state = "end"
else:
state = "read normal"
current.append(char)
elif state == "read escaped char":
if escapableChar(char):
state = "read normal"
if char in 'nN':
current.append('\n')
else:
current.append(char)
else:
state = "read normal"
# leave unrecognized escaped characters for later passes
current.append('\\' + char)
elif state == "end": # an end state
if len(current) or len(results) == 0:
current = "".join(current)
results.append(current)
return results
elif state == "error": # an end state
return results
else:
state = "error"
error("unknown state: '{0!s}' reached in {1!s}".format(state, s)) | [
"def",
"stringToTextValues",
"(",
"s",
",",
"listSeparator",
"=",
"','",
",",
"charList",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"if",
"charList",
"is",
"None",
":",
"charList",
"=",
"escapableCharList",
"def",
"escapableChar",
"(",
"c",
")",
":",
"return",
"c",
"in",
"charList",
"def",
"error",
"(",
"msg",
")",
":",
"if",
"strict",
":",
"raise",
"ParseError",
"(",
"msg",
")",
"else",
":",
"logging",
".",
"error",
"(",
"msg",
")",
"# vars which control state machine",
"charIterator",
"=",
"enumerate",
"(",
"s",
")",
"state",
"=",
"\"read normal\"",
"current",
"=",
"[",
"]",
"results",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"charIndex",
",",
"char",
"=",
"next",
"(",
"charIterator",
")",
"except",
":",
"char",
"=",
"\"eof\"",
"if",
"state",
"==",
"\"read normal\"",
":",
"if",
"char",
"==",
"'\\\\'",
":",
"state",
"=",
"\"read escaped char\"",
"elif",
"char",
"==",
"listSeparator",
":",
"state",
"=",
"\"read normal\"",
"current",
"=",
"\"\"",
".",
"join",
"(",
"current",
")",
"results",
".",
"append",
"(",
"current",
")",
"current",
"=",
"[",
"]",
"elif",
"char",
"==",
"\"eof\"",
":",
"state",
"=",
"\"end\"",
"else",
":",
"state",
"=",
"\"read normal\"",
"current",
".",
"append",
"(",
"char",
")",
"elif",
"state",
"==",
"\"read escaped char\"",
":",
"if",
"escapableChar",
"(",
"char",
")",
":",
"state",
"=",
"\"read normal\"",
"if",
"char",
"in",
"'nN'",
":",
"current",
".",
"append",
"(",
"'\\n'",
")",
"else",
":",
"current",
".",
"append",
"(",
"char",
")",
"else",
":",
"state",
"=",
"\"read normal\"",
"# leave unrecognized escaped characters for later passes",
"current",
".",
"append",
"(",
"'\\\\'",
"+",
"char",
")",
"elif",
"state",
"==",
"\"end\"",
":",
"# an end state",
"if",
"len",
"(",
"current",
")",
"or",
"len",
"(",
"results",
")",
"==",
"0",
":",
"current",
"=",
"\"\"",
".",
"join",
"(",
"current",
")",
"results",
".",
"append",
"(",
"current",
")",
"return",
"results",
"elif",
"state",
"==",
"\"error\"",
":",
"# an end state",
"return",
"results",
"else",
":",
"state",
"=",
"\"error\"",
"error",
"(",
"\"unknown state: '{0!s}' reached in {1!s}\"",
".",
"format",
"(",
"state",
",",
"s",
")",
")"
] | Returns list of strings. | [
"Returns",
"list",
"of",
"strings",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1636-L1702 | train | 234,889 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | parseDtstart | def parseDtstart(contentline, allowSignatureMismatch=False):
"""
Convert a contentline's value into a date or date-time.
A variety of clients don't serialize dates with the appropriate VALUE
parameter, so rather than failing on these (technically invalid) lines,
if allowSignatureMismatch is True, try to parse both varieties.
"""
tzinfo = getTzid(getattr(contentline, 'tzid_param', None))
valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper()
if valueParam == "DATE":
return stringToDate(contentline.value)
elif valueParam == "DATE-TIME":
try:
return stringToDateTime(contentline.value, tzinfo)
except:
if allowSignatureMismatch:
return stringToDate(contentline.value)
else:
raise | python | def parseDtstart(contentline, allowSignatureMismatch=False):
"""
Convert a contentline's value into a date or date-time.
A variety of clients don't serialize dates with the appropriate VALUE
parameter, so rather than failing on these (technically invalid) lines,
if allowSignatureMismatch is True, try to parse both varieties.
"""
tzinfo = getTzid(getattr(contentline, 'tzid_param', None))
valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper()
if valueParam == "DATE":
return stringToDate(contentline.value)
elif valueParam == "DATE-TIME":
try:
return stringToDateTime(contentline.value, tzinfo)
except:
if allowSignatureMismatch:
return stringToDate(contentline.value)
else:
raise | [
"def",
"parseDtstart",
"(",
"contentline",
",",
"allowSignatureMismatch",
"=",
"False",
")",
":",
"tzinfo",
"=",
"getTzid",
"(",
"getattr",
"(",
"contentline",
",",
"'tzid_param'",
",",
"None",
")",
")",
"valueParam",
"=",
"getattr",
"(",
"contentline",
",",
"'value_param'",
",",
"'DATE-TIME'",
")",
".",
"upper",
"(",
")",
"if",
"valueParam",
"==",
"\"DATE\"",
":",
"return",
"stringToDate",
"(",
"contentline",
".",
"value",
")",
"elif",
"valueParam",
"==",
"\"DATE-TIME\"",
":",
"try",
":",
"return",
"stringToDateTime",
"(",
"contentline",
".",
"value",
",",
"tzinfo",
")",
"except",
":",
"if",
"allowSignatureMismatch",
":",
"return",
"stringToDate",
"(",
"contentline",
".",
"value",
")",
"else",
":",
"raise"
] | Convert a contentline's value into a date or date-time.
A variety of clients don't serialize dates with the appropriate VALUE
parameter, so rather than failing on these (technically invalid) lines,
if allowSignatureMismatch is True, try to parse both varieties. | [
"Convert",
"a",
"contentline",
"s",
"value",
"into",
"a",
"date",
"or",
"date",
"-",
"time",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1823-L1842 | train | 234,890 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | tzinfo_eq | def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
return True
return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)
if not dt_test(datetime.datetime(startYear, 1, 1)):
return False
for year in range(startYear, endYear):
for transitionTo in 'daylight', 'standard':
t1=getTransition(transitionTo, year, tzinfo1)
t2=getTransition(transitionTo, year, tzinfo2)
if t1 != t2 or not dt_test(t1):
return False
return True | python | def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
return True
return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)
if not dt_test(datetime.datetime(startYear, 1, 1)):
return False
for year in range(startYear, endYear):
for transitionTo in 'daylight', 'standard':
t1=getTransition(transitionTo, year, tzinfo1)
t2=getTransition(transitionTo, year, tzinfo2)
if t1 != t2 or not dt_test(t1):
return False
return True | [
"def",
"tzinfo_eq",
"(",
"tzinfo1",
",",
"tzinfo2",
",",
"startYear",
"=",
"2000",
",",
"endYear",
"=",
"2020",
")",
":",
"if",
"tzinfo1",
"==",
"tzinfo2",
":",
"return",
"True",
"elif",
"tzinfo1",
"is",
"None",
"or",
"tzinfo2",
"is",
"None",
":",
"return",
"False",
"def",
"dt_test",
"(",
"dt",
")",
":",
"if",
"dt",
"is",
"None",
":",
"return",
"True",
"return",
"tzinfo1",
".",
"utcoffset",
"(",
"dt",
")",
"==",
"tzinfo2",
".",
"utcoffset",
"(",
"dt",
")",
"if",
"not",
"dt_test",
"(",
"datetime",
".",
"datetime",
"(",
"startYear",
",",
"1",
",",
"1",
")",
")",
":",
"return",
"False",
"for",
"year",
"in",
"range",
"(",
"startYear",
",",
"endYear",
")",
":",
"for",
"transitionTo",
"in",
"'daylight'",
",",
"'standard'",
":",
"t1",
"=",
"getTransition",
"(",
"transitionTo",
",",
"year",
",",
"tzinfo1",
")",
"t2",
"=",
"getTransition",
"(",
"transitionTo",
",",
"year",
",",
"tzinfo2",
")",
"if",
"t1",
"!=",
"t2",
"or",
"not",
"dt_test",
"(",
"t1",
")",
":",
"return",
"False",
"return",
"True"
] | Compare offsets and DST transitions from startYear to endYear. | [
"Compare",
"offsets",
"and",
"DST",
"transitions",
"from",
"startYear",
"to",
"endYear",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1929-L1951 | train | 234,891 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | TimezoneComponent.registerTzinfo | def registerTzinfo(obj, tzinfo):
"""
Register tzinfo if it's not already registered, return its tzid.
"""
tzid = obj.pickTzid(tzinfo)
if tzid and not getTzid(tzid, False):
registerTzid(tzid, tzinfo)
return tzid | python | def registerTzinfo(obj, tzinfo):
"""
Register tzinfo if it's not already registered, return its tzid.
"""
tzid = obj.pickTzid(tzinfo)
if tzid and not getTzid(tzid, False):
registerTzid(tzid, tzinfo)
return tzid | [
"def",
"registerTzinfo",
"(",
"obj",
",",
"tzinfo",
")",
":",
"tzid",
"=",
"obj",
".",
"pickTzid",
"(",
"tzinfo",
")",
"if",
"tzid",
"and",
"not",
"getTzid",
"(",
"tzid",
",",
"False",
")",
":",
"registerTzid",
"(",
"tzid",
",",
"tzinfo",
")",
"return",
"tzid"
] | Register tzinfo if it's not already registered, return its tzid. | [
"Register",
"tzinfo",
"if",
"it",
"s",
"not",
"already",
"registered",
"return",
"its",
"tzid",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L121-L128 | train | 234,892 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | TimezoneComponent.pickTzid | def pickTzid(tzinfo, allowUTC=False):
"""
Given a tzinfo class, use known APIs to determine TZID, or use tzname.
"""
if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
# If tzinfo is UTC, we don't need a TZID
return None
# try PyICU's tzid key
if hasattr(tzinfo, 'tzid'):
return toUnicode(tzinfo.tzid)
# try pytz zone key
if hasattr(tzinfo, 'zone'):
return toUnicode(tzinfo.zone)
# try tzical's tzid key
elif hasattr(tzinfo, '_tzid'):
return toUnicode(tzinfo._tzid)
else:
# return tzname for standard (non-DST) time
notDST = datetime.timedelta(0)
for month in range(1, 13):
dt = datetime.datetime(2000, month, 1)
if tzinfo.dst(dt) == notDST:
return toUnicode(tzinfo.tzname(dt))
# there was no standard time in 2000!
raise VObjectError("Unable to guess TZID for tzinfo {0!s}"
.format(tzinfo)) | python | def pickTzid(tzinfo, allowUTC=False):
"""
Given a tzinfo class, use known APIs to determine TZID, or use tzname.
"""
if tzinfo is None or (not allowUTC and tzinfo_eq(tzinfo, utc)):
# If tzinfo is UTC, we don't need a TZID
return None
# try PyICU's tzid key
if hasattr(tzinfo, 'tzid'):
return toUnicode(tzinfo.tzid)
# try pytz zone key
if hasattr(tzinfo, 'zone'):
return toUnicode(tzinfo.zone)
# try tzical's tzid key
elif hasattr(tzinfo, '_tzid'):
return toUnicode(tzinfo._tzid)
else:
# return tzname for standard (non-DST) time
notDST = datetime.timedelta(0)
for month in range(1, 13):
dt = datetime.datetime(2000, month, 1)
if tzinfo.dst(dt) == notDST:
return toUnicode(tzinfo.tzname(dt))
# there was no standard time in 2000!
raise VObjectError("Unable to guess TZID for tzinfo {0!s}"
.format(tzinfo)) | [
"def",
"pickTzid",
"(",
"tzinfo",
",",
"allowUTC",
"=",
"False",
")",
":",
"if",
"tzinfo",
"is",
"None",
"or",
"(",
"not",
"allowUTC",
"and",
"tzinfo_eq",
"(",
"tzinfo",
",",
"utc",
")",
")",
":",
"# If tzinfo is UTC, we don't need a TZID",
"return",
"None",
"# try PyICU's tzid key",
"if",
"hasattr",
"(",
"tzinfo",
",",
"'tzid'",
")",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"tzid",
")",
"# try pytz zone key",
"if",
"hasattr",
"(",
"tzinfo",
",",
"'zone'",
")",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"zone",
")",
"# try tzical's tzid key",
"elif",
"hasattr",
"(",
"tzinfo",
",",
"'_tzid'",
")",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"_tzid",
")",
"else",
":",
"# return tzname for standard (non-DST) time",
"notDST",
"=",
"datetime",
".",
"timedelta",
"(",
"0",
")",
"for",
"month",
"in",
"range",
"(",
"1",
",",
"13",
")",
":",
"dt",
"=",
"datetime",
".",
"datetime",
"(",
"2000",
",",
"month",
",",
"1",
")",
"if",
"tzinfo",
".",
"dst",
"(",
"dt",
")",
"==",
"notDST",
":",
"return",
"toUnicode",
"(",
"tzinfo",
".",
"tzname",
"(",
"dt",
")",
")",
"# there was no standard time in 2000!",
"raise",
"VObjectError",
"(",
"\"Unable to guess TZID for tzinfo {0!s}\"",
".",
"format",
"(",
"tzinfo",
")",
")"
] | Given a tzinfo class, use known APIs to determine TZID, or use tzname. | [
"Given",
"a",
"tzinfo",
"class",
"use",
"known",
"APIs",
"to",
"determine",
"TZID",
"or",
"use",
"tzname",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L325-L352 | train | 234,893 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | RecurringBehavior.transformToNative | def transformToNative(obj):
"""
Turn a recurring Component into a RecurringComponent.
"""
if not obj.isNative:
object.__setattr__(obj, '__class__', RecurringComponent)
obj.isNative = True
return obj | python | def transformToNative(obj):
"""
Turn a recurring Component into a RecurringComponent.
"""
if not obj.isNative:
object.__setattr__(obj, '__class__', RecurringComponent)
obj.isNative = True
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"not",
"obj",
".",
"isNative",
":",
"object",
".",
"__setattr__",
"(",
"obj",
",",
"'__class__'",
",",
"RecurringComponent",
")",
"obj",
".",
"isNative",
"=",
"True",
"return",
"obj"
] | Turn a recurring Component into a RecurringComponent. | [
"Turn",
"a",
"recurring",
"Component",
"into",
"a",
"RecurringComponent",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L667-L674 | train | 234,894 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | RecurringBehavior.generateImplicitParameters | def generateImplicitParameters(obj):
"""
Generate a UID if one does not exist.
This is just a dummy implementation, for now.
"""
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeToString(now)
host = socket.gethostname()
obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand,
host))) | python | def generateImplicitParameters(obj):
"""
Generate a UID if one does not exist.
This is just a dummy implementation, for now.
"""
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeToString(now)
host = socket.gethostname()
obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand,
host))) | [
"def",
"generateImplicitParameters",
"(",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'uid'",
")",
":",
"rand",
"=",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"100000",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"utc",
")",
"now",
"=",
"dateTimeToString",
"(",
"now",
")",
"host",
"=",
"socket",
".",
"gethostname",
"(",
")",
"obj",
".",
"add",
"(",
"ContentLine",
"(",
"'UID'",
",",
"[",
"]",
",",
"\"{0} - {1}@{2}\"",
".",
"format",
"(",
"now",
",",
"rand",
",",
"host",
")",
")",
")"
] | Generate a UID if one does not exist.
This is just a dummy implementation, for now. | [
"Generate",
"a",
"UID",
"if",
"one",
"does",
"not",
"exist",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L684-L696 | train | 234,895 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | DateOrDateTimeBehavior.transformToNative | def transformToNative(obj):
"""
Turn obj.value into a date or datetime.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value=obj.value
obj.value=parseDtstart(obj, allowSignatureMismatch=True)
if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME':
if hasattr(obj, 'tzid_param'):
# Keep a copy of the original TZID around
obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param]
del obj.tzid_param
return obj | python | def transformToNative(obj):
"""
Turn obj.value into a date or datetime.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value=obj.value
obj.value=parseDtstart(obj, allowSignatureMismatch=True)
if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME':
if hasattr(obj, 'tzid_param'):
# Keep a copy of the original TZID around
obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param]
del obj.tzid_param
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"True",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"return",
"obj",
"obj",
".",
"value",
"=",
"obj",
".",
"value",
"obj",
".",
"value",
"=",
"parseDtstart",
"(",
"obj",
",",
"allowSignatureMismatch",
"=",
"True",
")",
"if",
"getattr",
"(",
"obj",
",",
"'value_param'",
",",
"'DATE-TIME'",
")",
".",
"upper",
"(",
")",
"==",
"'DATE-TIME'",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'tzid_param'",
")",
":",
"# Keep a copy of the original TZID around",
"obj",
".",
"params",
"[",
"'X-VOBJ-ORIGINAL-TZID'",
"]",
"=",
"[",
"obj",
".",
"tzid_param",
"]",
"del",
"obj",
".",
"tzid_param",
"return",
"obj"
] | Turn obj.value into a date or datetime. | [
"Turn",
"obj",
".",
"value",
"into",
"a",
"date",
"or",
"datetime",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L762-L778 | train | 234,896 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | DateOrDateTimeBehavior.transformFromNative | def transformFromNative(obj):
"""
Replace the date or datetime in obj.value with an ISO 8601 string.
"""
if type(obj.value) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = dateToString(obj.value)
return obj
else:
return DateTimeBehavior.transformFromNative(obj) | python | def transformFromNative(obj):
"""
Replace the date or datetime in obj.value with an ISO 8601 string.
"""
if type(obj.value) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = dateToString(obj.value)
return obj
else:
return DateTimeBehavior.transformFromNative(obj) | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
".",
"value",
")",
"==",
"datetime",
".",
"date",
":",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value_param",
"=",
"'DATE'",
"obj",
".",
"value",
"=",
"dateToString",
"(",
"obj",
".",
"value",
")",
"return",
"obj",
"else",
":",
"return",
"DateTimeBehavior",
".",
"transformFromNative",
"(",
"obj",
")"
] | Replace the date or datetime in obj.value with an ISO 8601 string. | [
"Replace",
"the",
"date",
"or",
"datetime",
"in",
"obj",
".",
"value",
"with",
"an",
"ISO",
"8601",
"string",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L781-L791 | train | 234,897 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | MultiDateBehavior.transformFromNative | def transformFromNative(obj):
"""
Replace the date, datetime or period tuples in obj.value with
appropriate strings.
"""
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([dateToString(val) for val in obj.value])
return obj
# Fixme: handle PERIOD case
else:
if obj.isNative:
obj.isNative = False
transformed = []
tzid = None
for val in obj.value:
if tzid is None and type(val) == datetime.datetime:
tzid = TimezoneComponent.registerTzinfo(val.tzinfo)
if tzid is not None:
obj.tzid_param = tzid
transformed.append(dateTimeToString(val))
obj.value = ','.join(transformed)
return obj | python | def transformFromNative(obj):
"""
Replace the date, datetime or period tuples in obj.value with
appropriate strings.
"""
if obj.value and type(obj.value[0]) == datetime.date:
obj.isNative = False
obj.value_param = 'DATE'
obj.value = ','.join([dateToString(val) for val in obj.value])
return obj
# Fixme: handle PERIOD case
else:
if obj.isNative:
obj.isNative = False
transformed = []
tzid = None
for val in obj.value:
if tzid is None and type(val) == datetime.datetime:
tzid = TimezoneComponent.registerTzinfo(val.tzinfo)
if tzid is not None:
obj.tzid_param = tzid
transformed.append(dateTimeToString(val))
obj.value = ','.join(transformed)
return obj | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"value",
"and",
"type",
"(",
"obj",
".",
"value",
"[",
"0",
"]",
")",
"==",
"datetime",
".",
"date",
":",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value_param",
"=",
"'DATE'",
"obj",
".",
"value",
"=",
"','",
".",
"join",
"(",
"[",
"dateToString",
"(",
"val",
")",
"for",
"val",
"in",
"obj",
".",
"value",
"]",
")",
"return",
"obj",
"# Fixme: handle PERIOD case",
"else",
":",
"if",
"obj",
".",
"isNative",
":",
"obj",
".",
"isNative",
"=",
"False",
"transformed",
"=",
"[",
"]",
"tzid",
"=",
"None",
"for",
"val",
"in",
"obj",
".",
"value",
":",
"if",
"tzid",
"is",
"None",
"and",
"type",
"(",
"val",
")",
"==",
"datetime",
".",
"datetime",
":",
"tzid",
"=",
"TimezoneComponent",
".",
"registerTzinfo",
"(",
"val",
".",
"tzinfo",
")",
"if",
"tzid",
"is",
"not",
"None",
":",
"obj",
".",
"tzid_param",
"=",
"tzid",
"transformed",
".",
"append",
"(",
"dateTimeToString",
"(",
"val",
")",
")",
"obj",
".",
"value",
"=",
"','",
".",
"join",
"(",
"transformed",
")",
"return",
"obj"
] | Replace the date, datetime or period tuples in obj.value with
appropriate strings. | [
"Replace",
"the",
"date",
"datetime",
"or",
"period",
"tuples",
"in",
"obj",
".",
"value",
"with",
"appropriate",
"strings",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L825-L848 | train | 234,898 |
eventable/vobject | docs/build/lib/vobject/icalendar.py | MultiTextBehavior.decode | def decode(cls, line):
"""
Remove backslash escaping from line.value, then split on commas.
"""
if line.encoded:
line.value = stringToTextValues(line.value,
listSeparator=cls.listSeparator)
line.encoded=False | python | def decode(cls, line):
"""
Remove backslash escaping from line.value, then split on commas.
"""
if line.encoded:
line.value = stringToTextValues(line.value,
listSeparator=cls.listSeparator)
line.encoded=False | [
"def",
"decode",
"(",
"cls",
",",
"line",
")",
":",
"if",
"line",
".",
"encoded",
":",
"line",
".",
"value",
"=",
"stringToTextValues",
"(",
"line",
".",
"value",
",",
"listSeparator",
"=",
"cls",
".",
"listSeparator",
")",
"line",
".",
"encoded",
"=",
"False"
] | Remove backslash escaping from line.value, then split on commas. | [
"Remove",
"backslash",
"escaping",
"from",
"line",
".",
"value",
"then",
"split",
"on",
"commas",
"."
] | 498555a553155ea9b26aace93332ae79365ecb31 | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L860-L867 | train | 234,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.