Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
XCObject.Copy | (self) | Make a copy of this object.
The new object will have its own copy of lists and dicts. Any XCObject
objects owned by this object (marked "strong") will be copied in the
new object, even those found in lists. If this object has any weak
references to other XCObjects, the same references are added to the new
object without making a copy.
| Make a copy of this object. | def Copy(self):
"""Make a copy of this object.
The new object will have its own copy of lists and dicts. Any XCObject
objects owned by this object (marked "strong") will be copied in the
new object, even those found in lists. If this object has any weak
references to other XCObjects, the same references are added to the new
object without making a copy.
"""
that = self.__class__(id=self.id, parent=self.parent)
for key, value in self._properties.iteritems():
is_strong = self._schema[key][2]
if isinstance(value, XCObject):
if is_strong:
new_value = value.Copy()
new_value.parent = that
that._properties[key] = new_value
else:
that._properties[key] = value
elif isinstance(value, str) or isinstance(value, unicode) or \
isinstance(value, int):
that._properties[key] = value
elif isinstance(value, list):
if is_strong:
# If is_strong is True, each element is an XCObject, so it's safe to
# call Copy.
that._properties[key] = []
for item in value:
new_item = item.Copy()
new_item.parent = that
that._properties[key].append(new_item)
else:
that._properties[key] = value[:]
elif isinstance(value, dict):
# dicts are never strong.
if is_strong:
raise TypeError('Strong dict for key ' + key + ' in ' + \
self.__class__.__name__)
else:
that._properties[key] = value.copy()
else:
raise TypeError('Unexpected type ' + value.__class__.__name__ + \
' for key ' + key + ' in ' + self.__class__.__name__)
return that | [
"def",
"Copy",
"(",
"self",
")",
":",
"that",
"=",
"self",
".",
"__class__",
"(",
"id",
"=",
"self",
".",
"id",
",",
"parent",
"=",
"self",
".",
"parent",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_properties",
".",
"iteritems",
"(",
")",
":",
"is_strong",
"=",
"self",
".",
"_schema",
"[",
"key",
"]",
"[",
"2",
"]",
"if",
"isinstance",
"(",
"value",
",",
"XCObject",
")",
":",
"if",
"is_strong",
":",
"new_value",
"=",
"value",
".",
"Copy",
"(",
")",
"new_value",
".",
"parent",
"=",
"that",
"that",
".",
"_properties",
"[",
"key",
"]",
"=",
"new_value",
"else",
":",
"that",
".",
"_properties",
"[",
"key",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
"or",
"isinstance",
"(",
"value",
",",
"unicode",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"that",
".",
"_properties",
"[",
"key",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"is_strong",
":",
"# If is_strong is True, each element is an XCObject, so it's safe to",
"# call Copy.",
"that",
".",
"_properties",
"[",
"key",
"]",
"=",
"[",
"]",
"for",
"item",
"in",
"value",
":",
"new_item",
"=",
"item",
".",
"Copy",
"(",
")",
"new_item",
".",
"parent",
"=",
"that",
"that",
".",
"_properties",
"[",
"key",
"]",
".",
"append",
"(",
"new_item",
")",
"else",
":",
"that",
".",
"_properties",
"[",
"key",
"]",
"=",
"value",
"[",
":",
"]",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"# dicts are never strong.",
"if",
"is_strong",
":",
"raise",
"TypeError",
"(",
"'Strong dict for key '",
"+",
"key",
"+",
"' in '",
"+",
"self",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"that",
".",
"_properties",
"[",
"key",
"]",
"=",
"value",
".",
"copy",
"(",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Unexpected type '",
"+",
"value",
".",
"__class__",
".",
"__name__",
"+",
"' for key '",
"+",
"key",
"+",
"' in '",
"+",
"self",
".",
"__class__",
".",
"__name__",
")",
"return",
"that"
] | [
305,
2
] | [
351,
15
] | python | en | ['en', 'en', 'en'] | True |
XCObject.Name | (self) | Return the name corresponding to an object.
Not all objects necessarily need to be nameable, and not all that do have
a "name" property. Override as needed.
| Return the name corresponding to an object. | def Name(self):
"""Return the name corresponding to an object.
Not all objects necessarily need to be nameable, and not all that do have
a "name" property. Override as needed.
"""
# If the schema indicates that "name" is required, try to access the
# property even if it doesn't exist. This will result in a KeyError
# being raised for the property that should be present, which seems more
# appropriate than NotImplementedError in this case.
if 'name' in self._properties or \
('name' in self._schema and self._schema['name'][3]):
return self._properties['name']
raise NotImplementedError(self.__class__.__name__ + ' must implement Name') | [
"def",
"Name",
"(",
"self",
")",
":",
"# If the schema indicates that \"name\" is required, try to access the",
"# property even if it doesn't exist. This will result in a KeyError",
"# being raised for the property that should be present, which seems more",
"# appropriate than NotImplementedError in this case.",
"if",
"'name'",
"in",
"self",
".",
"_properties",
"or",
"(",
"'name'",
"in",
"self",
".",
"_schema",
"and",
"self",
".",
"_schema",
"[",
"'name'",
"]",
"[",
"3",
"]",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"raise",
"NotImplementedError",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"' must implement Name'",
")"
] | [
353,
2
] | [
368,
79
] | python | en | ['en', 'en', 'en'] | True |
XCObject.Comment | (self) | Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it.
| Return a comment string for the object. | def Comment(self):
"""Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it.
"""
return self.Name() | [
"def",
"Comment",
"(",
"self",
")",
":",
"return",
"self",
".",
"Name",
"(",
")"
] | [
370,
2
] | [
380,
22
] | python | en | ['en', 'en', 'en'] | True |
XCObject.ComputeIDs | (self, recursive=True, overwrite=True, seed_hash=None) | Set "id" properties deterministically.
An object's "id" property is set based on a hash of its class type and
name, as well as the class type and name of all ancestor objects. As
such, it is only advisable to call ComputeIDs once an entire project file
tree is built.
If recursive is True, recurse into all descendant objects and update their
hashes.
If overwrite is True, any existing value set in the "id" property will be
replaced.
| Set "id" properties deterministically. | def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None):
"""Set "id" properties deterministically.
An object's "id" property is set based on a hash of its class type and
name, as well as the class type and name of all ancestor objects. As
such, it is only advisable to call ComputeIDs once an entire project file
tree is built.
If recursive is True, recurse into all descendant objects and update their
hashes.
If overwrite is True, any existing value set in the "id" property will be
replaced.
"""
def _HashUpdate(hash, data):
"""Update hash with data's length and contents.
If the hash were updated only with the value of data, it would be
possible for clowns to induce collisions by manipulating the names of
their objects. By adding the length, it's exceedingly less likely that
ID collisions will be encountered, intentionally or not.
"""
hash.update(struct.pack('>i', len(data)))
hash.update(data)
if seed_hash is None:
seed_hash = _new_sha1()
hash = seed_hash.copy()
hashables = self.Hashables()
assert len(hashables) > 0
for hashable in hashables:
_HashUpdate(hash, hashable)
if recursive:
hashables_for_child = self.HashablesForChild()
if hashables_for_child is None:
child_hash = hash
else:
assert len(hashables_for_child) > 0
child_hash = seed_hash.copy()
for hashable in hashables_for_child:
_HashUpdate(child_hash, hashable)
for child in self.Children():
child.ComputeIDs(recursive, overwrite, child_hash)
if overwrite or self.id is None:
# Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is
# is 160 bits. Instead of throwing out 64 bits of the digest, xor them
# into the portion that gets used.
assert hash.digest_size % 4 == 0
digest_int_count = hash.digest_size / 4
digest_ints = struct.unpack('>' + 'I' * digest_int_count, hash.digest())
id_ints = [0, 0, 0]
for index in xrange(0, digest_int_count):
id_ints[index % 3] ^= digest_ints[index]
self.id = '%08X%08X%08X' % tuple(id_ints) | [
"def",
"ComputeIDs",
"(",
"self",
",",
"recursive",
"=",
"True",
",",
"overwrite",
"=",
"True",
",",
"seed_hash",
"=",
"None",
")",
":",
"def",
"_HashUpdate",
"(",
"hash",
",",
"data",
")",
":",
"\"\"\"Update hash with data's length and contents.\n\n If the hash were updated only with the value of data, it would be\n possible for clowns to induce collisions by manipulating the names of\n their objects. By adding the length, it's exceedingly less likely that\n ID collisions will be encountered, intentionally or not.\n \"\"\"",
"hash",
".",
"update",
"(",
"struct",
".",
"pack",
"(",
"'>i'",
",",
"len",
"(",
"data",
")",
")",
")",
"hash",
".",
"update",
"(",
"data",
")",
"if",
"seed_hash",
"is",
"None",
":",
"seed_hash",
"=",
"_new_sha1",
"(",
")",
"hash",
"=",
"seed_hash",
".",
"copy",
"(",
")",
"hashables",
"=",
"self",
".",
"Hashables",
"(",
")",
"assert",
"len",
"(",
"hashables",
")",
">",
"0",
"for",
"hashable",
"in",
"hashables",
":",
"_HashUpdate",
"(",
"hash",
",",
"hashable",
")",
"if",
"recursive",
":",
"hashables_for_child",
"=",
"self",
".",
"HashablesForChild",
"(",
")",
"if",
"hashables_for_child",
"is",
"None",
":",
"child_hash",
"=",
"hash",
"else",
":",
"assert",
"len",
"(",
"hashables_for_child",
")",
">",
"0",
"child_hash",
"=",
"seed_hash",
".",
"copy",
"(",
")",
"for",
"hashable",
"in",
"hashables_for_child",
":",
"_HashUpdate",
"(",
"child_hash",
",",
"hashable",
")",
"for",
"child",
"in",
"self",
".",
"Children",
"(",
")",
":",
"child",
".",
"ComputeIDs",
"(",
"recursive",
",",
"overwrite",
",",
"child_hash",
")",
"if",
"overwrite",
"or",
"self",
".",
"id",
"is",
"None",
":",
"# Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is",
"# is 160 bits. Instead of throwing out 64 bits of the digest, xor them",
"# into the portion that gets used.",
"assert",
"hash",
".",
"digest_size",
"%",
"4",
"==",
"0",
"digest_int_count",
"=",
"hash",
".",
"digest_size",
"/",
"4",
"digest_ints",
"=",
"struct",
".",
"unpack",
"(",
"'>'",
"+",
"'I'",
"*",
"digest_int_count",
",",
"hash",
".",
"digest",
"(",
")",
")",
"id_ints",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"for",
"index",
"in",
"xrange",
"(",
"0",
",",
"digest_int_count",
")",
":",
"id_ints",
"[",
"index",
"%",
"3",
"]",
"^=",
"digest_ints",
"[",
"index",
"]",
"self",
".",
"id",
"=",
"'%08X%08X%08X'",
"%",
"tuple",
"(",
"id_ints",
")"
] | [
396,
2
] | [
456,
47
] | python | en | ['es', 'en', 'en'] | True |
XCObject.EnsureNoIDCollisions | (self) | Verifies that no two objects have the same ID. Checks all descendants.
| Verifies that no two objects have the same ID. Checks all descendants.
| def EnsureNoIDCollisions(self):
"""Verifies that no two objects have the same ID. Checks all descendants.
"""
ids = {}
descendants = self.Descendants()
for descendant in descendants:
if descendant.id in ids:
other = ids[descendant.id]
raise KeyError(
'Duplicate ID %s, objects "%s" and "%s" in "%s"' % \
(descendant.id, str(descendant._properties),
str(other._properties), self._properties['rootObject'].Name()))
ids[descendant.id] = descendant | [
"def",
"EnsureNoIDCollisions",
"(",
"self",
")",
":",
"ids",
"=",
"{",
"}",
"descendants",
"=",
"self",
".",
"Descendants",
"(",
")",
"for",
"descendant",
"in",
"descendants",
":",
"if",
"descendant",
".",
"id",
"in",
"ids",
":",
"other",
"=",
"ids",
"[",
"descendant",
".",
"id",
"]",
"raise",
"KeyError",
"(",
"'Duplicate ID %s, objects \"%s\" and \"%s\" in \"%s\"'",
"%",
"(",
"descendant",
".",
"id",
",",
"str",
"(",
"descendant",
".",
"_properties",
")",
",",
"str",
"(",
"other",
".",
"_properties",
")",
",",
"self",
".",
"_properties",
"[",
"'rootObject'",
"]",
".",
"Name",
"(",
")",
")",
")",
"ids",
"[",
"descendant",
".",
"id",
"]",
"=",
"descendant"
] | [
458,
2
] | [
471,
37
] | python | en | ['en', 'en', 'en'] | True |
XCObject.Children | (self) | Returns a list of all of this object's owned (strong) children. | Returns a list of all of this object's owned (strong) children. | def Children(self):
"""Returns a list of all of this object's owned (strong) children."""
children = []
for property, attributes in self._schema.iteritems():
(is_list, property_type, is_strong) = attributes[0:3]
if is_strong and property in self._properties:
if not is_list:
children.append(self._properties[property])
else:
children.extend(self._properties[property])
return children | [
"def",
"Children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"for",
"property",
",",
"attributes",
"in",
"self",
".",
"_schema",
".",
"iteritems",
"(",
")",
":",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
")",
"=",
"attributes",
"[",
"0",
":",
"3",
"]",
"if",
"is_strong",
"and",
"property",
"in",
"self",
".",
"_properties",
":",
"if",
"not",
"is_list",
":",
"children",
".",
"append",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"else",
":",
"children",
".",
"extend",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"return",
"children"
] | [
473,
2
] | [
484,
19
] | python | en | ['en', 'en', 'en'] | True |
XCObject.Descendants | (self) | Returns a list of all of this object's descendants, including this
object.
| Returns a list of all of this object's descendants, including this
object.
| def Descendants(self):
"""Returns a list of all of this object's descendants, including this
object.
"""
children = self.Children()
descendants = [self]
for child in children:
descendants.extend(child.Descendants())
return descendants | [
"def",
"Descendants",
"(",
"self",
")",
":",
"children",
"=",
"self",
".",
"Children",
"(",
")",
"descendants",
"=",
"[",
"self",
"]",
"for",
"child",
"in",
"children",
":",
"descendants",
".",
"extend",
"(",
"child",
".",
"Descendants",
"(",
")",
")",
"return",
"descendants"
] | [
486,
2
] | [
495,
22
] | python | en | ['en', 'en', 'en'] | True |
XCObject._EncodeComment | (self, comment) | Encodes a comment to be placed in the project file output, mimicing
Xcode behavior.
| Encodes a comment to be placed in the project file output, mimicing
Xcode behavior.
| def _EncodeComment(self, comment):
"""Encodes a comment to be placed in the project file output, mimicing
Xcode behavior.
"""
# This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If
# the string already contains a "*/", it is turned into "(*)/". This keeps
# the file writer from outputting something that would be treated as the
# end of a comment in the middle of something intended to be entirely a
# comment.
return '/* ' + comment.replace('*/', '(*)/') + ' */' | [
"def",
"_EncodeComment",
"(",
"self",
",",
"comment",
")",
":",
"# This mimics Xcode behavior by wrapping the comment in \"/*\" and \"*/\". If",
"# the string already contains a \"*/\", it is turned into \"(*)/\". This keeps",
"# the file writer from outputting something that would be treated as the",
"# end of a comment in the middle of something intended to be entirely a",
"# comment.",
"return",
"'/* '",
"+",
"comment",
".",
"replace",
"(",
"'*/'",
",",
"'(*)/'",
")",
"+",
"' */'"
] | [
503,
2
] | [
514,
56
] | python | en | ['en', 'en', 'en'] | True |
XCObject._EncodeString | (self, value) | Encodes a string to be placed in the project file output, mimicing
Xcode behavior.
| Encodes a string to be placed in the project file output, mimicing
Xcode behavior.
| def _EncodeString(self, value):
"""Encodes a string to be placed in the project file output, mimicing
Xcode behavior.
"""
# Use quotation marks when any character outside of the range A-Z, a-z, 0-9,
# $ (dollar sign), . (period), and _ (underscore) is present. Also use
# quotation marks to represent empty strings.
#
# Escape " (double-quote) and \ (backslash) by preceding them with a
# backslash.
#
# Some characters below the printable ASCII range are encoded specially:
# 7 ^G BEL is encoded as "\a"
# 8 ^H BS is encoded as "\b"
# 11 ^K VT is encoded as "\v"
# 12 ^L NP is encoded as "\f"
# 127 ^? DEL is passed through as-is without escaping
# - In PBXFileReference and PBXBuildFile objects:
# 9 ^I HT is passed through as-is without escaping
# 10 ^J NL is passed through as-is without escaping
# 13 ^M CR is passed through as-is without escaping
# - In other objects:
# 9 ^I HT is encoded as "\t"
# 10 ^J NL is encoded as "\n"
# 13 ^M CR is encoded as "\n" rendering it indistinguishable from
# 10 ^J NL
# All other characters within the ASCII control character range (0 through
# 31 inclusive) are encoded as "\U001f" referring to the Unicode code point
# in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e".
# Characters above the ASCII range are passed through to the output encoded
# as UTF-8 without any escaping. These mappings are contained in the
# class' _encode_transforms list.
if _unquoted.search(value) and not _quoted.search(value):
return value
return '"' + _escaped.sub(self._EncodeTransform, value) + '"' | [
"def",
"_EncodeString",
"(",
"self",
",",
"value",
")",
":",
"# Use quotation marks when any character outside of the range A-Z, a-z, 0-9,",
"# $ (dollar sign), . (period), and _ (underscore) is present. Also use",
"# quotation marks to represent empty strings.",
"#",
"# Escape \" (double-quote) and \\ (backslash) by preceding them with a",
"# backslash.",
"#",
"# Some characters below the printable ASCII range are encoded specially:",
"# 7 ^G BEL is encoded as \"\\a\"",
"# 8 ^H BS is encoded as \"\\b\"",
"# 11 ^K VT is encoded as \"\\v\"",
"# 12 ^L NP is encoded as \"\\f\"",
"# 127 ^? DEL is passed through as-is without escaping",
"# - In PBXFileReference and PBXBuildFile objects:",
"# 9 ^I HT is passed through as-is without escaping",
"# 10 ^J NL is passed through as-is without escaping",
"# 13 ^M CR is passed through as-is without escaping",
"# - In other objects:",
"# 9 ^I HT is encoded as \"\\t\"",
"# 10 ^J NL is encoded as \"\\n\"",
"# 13 ^M CR is encoded as \"\\n\" rendering it indistinguishable from",
"# 10 ^J NL",
"# All other characters within the ASCII control character range (0 through",
"# 31 inclusive) are encoded as \"\\U001f\" referring to the Unicode code point",
"# in hexadecimal. For example, character 14 (^N SO) is encoded as \"\\U000e\".",
"# Characters above the ASCII range are passed through to the output encoded",
"# as UTF-8 without any escaping. These mappings are contained in the",
"# class' _encode_transforms list.",
"if",
"_unquoted",
".",
"search",
"(",
"value",
")",
"and",
"not",
"_quoted",
".",
"search",
"(",
"value",
")",
":",
"return",
"value",
"return",
"'\"'",
"+",
"_escaped",
".",
"sub",
"(",
"self",
".",
"_EncodeTransform",
",",
"value",
")",
"+",
"'\"'"
] | [
531,
2
] | [
568,
65
] | python | en | ['en', 'en', 'en'] | True |
XCObject._XCPrintableValue | (self, tabs, value, flatten_list=False) | Returns a representation of value that may be printed in a project file,
mimicing Xcode's behavior.
_XCPrintableValue can handle str and int values, XCObjects (which are
made printable by returning their id property), and list and dict objects
composed of any of the above types. When printing a list or dict, and
_should_print_single_line is False, the tabs parameter is used to determine
how much to indent the lines corresponding to the items in the list or
dict.
If flatten_list is True, single-element lists will be transformed into
strings.
| Returns a representation of value that may be printed in a project file,
mimicing Xcode's behavior. | def _XCPrintableValue(self, tabs, value, flatten_list=False):
"""Returns a representation of value that may be printed in a project file,
mimicing Xcode's behavior.
_XCPrintableValue can handle str and int values, XCObjects (which are
made printable by returning their id property), and list and dict objects
composed of any of the above types. When printing a list or dict, and
_should_print_single_line is False, the tabs parameter is used to determine
how much to indent the lines corresponding to the items in the list or
dict.
If flatten_list is True, single-element lists will be transformed into
strings.
"""
printable = ''
comment = None
if self._should_print_single_line:
sep = ' '
element_tabs = ''
end_tabs = ''
else:
sep = '\n'
element_tabs = '\t' * (tabs + 1)
end_tabs = '\t' * tabs
if isinstance(value, XCObject):
printable += value.id
comment = value.Comment()
elif isinstance(value, str):
printable += self._EncodeString(value)
elif isinstance(value, unicode):
printable += self._EncodeString(value.encode('utf-8'))
elif isinstance(value, int):
printable += str(value)
elif isinstance(value, list):
if flatten_list and len(value) <= 1:
if len(value) == 0:
printable += self._EncodeString('')
else:
printable += self._EncodeString(value[0])
else:
printable = '(' + sep
for item in value:
printable += element_tabs + \
self._XCPrintableValue(tabs + 1, item, flatten_list) + \
',' + sep
printable += end_tabs + ')'
elif isinstance(value, dict):
printable = '{' + sep
for item_key, item_value in sorted(value.iteritems()):
printable += element_tabs + \
self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \
self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \
sep
printable += end_tabs + '}'
else:
raise TypeError("Can't make " + value.__class__.__name__ + ' printable')
if comment != None:
printable += ' ' + self._EncodeComment(comment)
return printable | [
"def",
"_XCPrintableValue",
"(",
"self",
",",
"tabs",
",",
"value",
",",
"flatten_list",
"=",
"False",
")",
":",
"printable",
"=",
"''",
"comment",
"=",
"None",
"if",
"self",
".",
"_should_print_single_line",
":",
"sep",
"=",
"' '",
"element_tabs",
"=",
"''",
"end_tabs",
"=",
"''",
"else",
":",
"sep",
"=",
"'\\n'",
"element_tabs",
"=",
"'\\t'",
"*",
"(",
"tabs",
"+",
"1",
")",
"end_tabs",
"=",
"'\\t'",
"*",
"tabs",
"if",
"isinstance",
"(",
"value",
",",
"XCObject",
")",
":",
"printable",
"+=",
"value",
".",
"id",
"comment",
"=",
"value",
".",
"Comment",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"printable",
"+=",
"self",
".",
"_EncodeString",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"printable",
"+=",
"self",
".",
"_EncodeString",
"(",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"printable",
"+=",
"str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"flatten_list",
"and",
"len",
"(",
"value",
")",
"<=",
"1",
":",
"if",
"len",
"(",
"value",
")",
"==",
"0",
":",
"printable",
"+=",
"self",
".",
"_EncodeString",
"(",
"''",
")",
"else",
":",
"printable",
"+=",
"self",
".",
"_EncodeString",
"(",
"value",
"[",
"0",
"]",
")",
"else",
":",
"printable",
"=",
"'('",
"+",
"sep",
"for",
"item",
"in",
"value",
":",
"printable",
"+=",
"element_tabs",
"+",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
"+",
"1",
",",
"item",
",",
"flatten_list",
")",
"+",
"','",
"+",
"sep",
"printable",
"+=",
"end_tabs",
"+",
"')'",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"printable",
"=",
"'{'",
"+",
"sep",
"for",
"item_key",
",",
"item_value",
"in",
"sorted",
"(",
"value",
".",
"iteritems",
"(",
")",
")",
":",
"printable",
"+=",
"element_tabs",
"+",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
"+",
"1",
",",
"item_key",
",",
"flatten_list",
")",
"+",
"' = '",
"+",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
"+",
"1",
",",
"item_value",
",",
"flatten_list",
")",
"+",
"';'",
"+",
"sep",
"printable",
"+=",
"end_tabs",
"+",
"'}'",
"else",
":",
"raise",
"TypeError",
"(",
"\"Can't make \"",
"+",
"value",
".",
"__class__",
".",
"__name__",
"+",
"' printable'",
")",
"if",
"comment",
"!=",
"None",
":",
"printable",
"+=",
"' '",
"+",
"self",
".",
"_EncodeComment",
"(",
"comment",
")",
"return",
"printable"
] | [
573,
2
] | [
636,
20
] | python | en | ['en', 'en', 'en'] | True |
XCObject._XCKVPrint | (self, file, tabs, key, value) | Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline.
| Prints a key and value, members of an XCObject's _properties dictionary,
to file. | def _XCKVPrint(self, file, tabs, key, value):
"""Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline.
"""
if self._should_print_single_line:
printable = ''
after_kv = ' '
else:
printable = '\t' * tabs
after_kv = '\n'
# Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy
# objects without comments. Sometimes it prints them with comments, but
# the majority of the time, it doesn't. To avoid unnecessary changes to
# the project file after Xcode opens it, don't write comments for
# remoteGlobalIDString. This is a sucky hack and it would certainly be
# cleaner to extend the schema to indicate whether or not a comment should
# be printed, but since this is the only case where the problem occurs and
# Xcode itself can't seem to make up its mind, the hack will suffice.
#
# Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].
if key == 'remoteGlobalIDString' and isinstance(self,
PBXContainerItemProxy):
value_to_print = value.id
else:
value_to_print = value
# PBXBuildFile's settings property is represented in the output as a dict,
# but a hack here has it represented as a string. Arrange to strip off the
# quotes so that it shows up in the output as expected.
if key == 'settings' and isinstance(self, PBXBuildFile):
strip_value_quotes = True
else:
strip_value_quotes = False
# In another one-off, let's set flatten_list on buildSettings properties
# of XCBuildConfiguration objects, because that's how Xcode treats them.
if key == 'buildSettings' and isinstance(self, XCBuildConfiguration):
flatten_list = True
else:
flatten_list = False
try:
printable_key = self._XCPrintableValue(tabs, key, flatten_list)
printable_value = self._XCPrintableValue(tabs, value_to_print,
flatten_list)
if strip_value_quotes and len(printable_value) > 1 and \
printable_value[0] == '"' and printable_value[-1] == '"':
printable_value = printable_value[1:-1]
printable += printable_key + ' = ' + printable_value + ';' + after_kv
except TypeError, e:
gyp.common.ExceptionAppend(e,
'while printing key "%s"' % key)
raise
self._XCPrint(file, 0, printable) | [
"def",
"_XCKVPrint",
"(",
"self",
",",
"file",
",",
"tabs",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"_should_print_single_line",
":",
"printable",
"=",
"''",
"after_kv",
"=",
"' '",
"else",
":",
"printable",
"=",
"'\\t'",
"*",
"tabs",
"after_kv",
"=",
"'\\n'",
"# Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy",
"# objects without comments. Sometimes it prints them with comments, but",
"# the majority of the time, it doesn't. To avoid unnecessary changes to",
"# the project file after Xcode opens it, don't write comments for",
"# remoteGlobalIDString. This is a sucky hack and it would certainly be",
"# cleaner to extend the schema to indicate whether or not a comment should",
"# be printed, but since this is the only case where the problem occurs and",
"# Xcode itself can't seem to make up its mind, the hack will suffice.",
"#",
"# Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].",
"if",
"key",
"==",
"'remoteGlobalIDString'",
"and",
"isinstance",
"(",
"self",
",",
"PBXContainerItemProxy",
")",
":",
"value_to_print",
"=",
"value",
".",
"id",
"else",
":",
"value_to_print",
"=",
"value",
"# PBXBuildFile's settings property is represented in the output as a dict,",
"# but a hack here has it represented as a string. Arrange to strip off the",
"# quotes so that it shows up in the output as expected.",
"if",
"key",
"==",
"'settings'",
"and",
"isinstance",
"(",
"self",
",",
"PBXBuildFile",
")",
":",
"strip_value_quotes",
"=",
"True",
"else",
":",
"strip_value_quotes",
"=",
"False",
"# In another one-off, let's set flatten_list on buildSettings properties",
"# of XCBuildConfiguration objects, because that's how Xcode treats them.",
"if",
"key",
"==",
"'buildSettings'",
"and",
"isinstance",
"(",
"self",
",",
"XCBuildConfiguration",
")",
":",
"flatten_list",
"=",
"True",
"else",
":",
"flatten_list",
"=",
"False",
"try",
":",
"printable_key",
"=",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
",",
"key",
",",
"flatten_list",
")",
"printable_value",
"=",
"self",
".",
"_XCPrintableValue",
"(",
"tabs",
",",
"value_to_print",
",",
"flatten_list",
")",
"if",
"strip_value_quotes",
"and",
"len",
"(",
"printable_value",
")",
">",
"1",
"and",
"printable_value",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"printable_value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"printable_value",
"=",
"printable_value",
"[",
"1",
":",
"-",
"1",
"]",
"printable",
"+=",
"printable_key",
"+",
"' = '",
"+",
"printable_value",
"+",
"';'",
"+",
"after_kv",
"except",
"TypeError",
",",
"e",
":",
"gyp",
".",
"common",
".",
"ExceptionAppend",
"(",
"e",
",",
"'while printing key \"%s\"'",
"%",
"key",
")",
"raise",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"0",
",",
"printable",
")"
] | [
638,
2
] | [
698,
37
] | python | en | ['en', 'en', 'en'] | True |
XCObject.Print | (self, file=sys.stdout) | Prints a reprentation of this object to file, adhering to Xcode output
formatting.
| Prints a reprentation of this object to file, adhering to Xcode output
formatting.
| def Print(self, file=sys.stdout):
"""Prints a reprentation of this object to file, adhering to Xcode output
formatting.
"""
self.VerifyHasRequiredProperties()
if self._should_print_single_line:
# When printing an object in a single line, Xcode doesn't put any space
# between the beginning of a dictionary (or presumably a list) and the
# first contained item, so you wind up with snippets like
# ...CDEF = {isa = PBXFileReference; fileRef = 0123...
# If it were me, I would have put a space in there after the opening
# curly, but I guess this is just another one of those inconsistencies
# between how Xcode prints PBXFileReference and PBXBuildFile objects as
# compared to other objects. Mimic Xcode's behavior here by using an
# empty string for sep.
sep = ''
end_tabs = 0
else:
sep = '\n'
end_tabs = 2
# Start the object. For example, '\t\tPBXProject = {\n'.
self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep)
# "isa" isn't in the _properties dictionary, it's an intrinsic property
# of the class which the object belongs to. Xcode always outputs "isa"
# as the first element of an object dictionary.
self._XCKVPrint(file, 3, 'isa', self.__class__.__name__)
# The remaining elements of an object dictionary are sorted alphabetically.
for property, value in sorted(self._properties.iteritems()):
self._XCKVPrint(file, 3, property, value)
# End the object.
self._XCPrint(file, end_tabs, '};\n') | [
"def",
"Print",
"(",
"self",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"VerifyHasRequiredProperties",
"(",
")",
"if",
"self",
".",
"_should_print_single_line",
":",
"# When printing an object in a single line, Xcode doesn't put any space",
"# between the beginning of a dictionary (or presumably a list) and the",
"# first contained item, so you wind up with snippets like",
"# ...CDEF = {isa = PBXFileReference; fileRef = 0123...",
"# If it were me, I would have put a space in there after the opening",
"# curly, but I guess this is just another one of those inconsistencies",
"# between how Xcode prints PBXFileReference and PBXBuildFile objects as",
"# compared to other objects. Mimic Xcode's behavior here by using an",
"# empty string for sep.",
"sep",
"=",
"''",
"end_tabs",
"=",
"0",
"else",
":",
"sep",
"=",
"'\\n'",
"end_tabs",
"=",
"2",
"# Start the object. For example, '\\t\\tPBXProject = {\\n'.",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"2",
",",
"self",
".",
"_XCPrintableValue",
"(",
"2",
",",
"self",
")",
"+",
"' = {'",
"+",
"sep",
")",
"# \"isa\" isn't in the _properties dictionary, it's an intrinsic property",
"# of the class which the object belongs to. Xcode always outputs \"isa\"",
"# as the first element of an object dictionary.",
"self",
".",
"_XCKVPrint",
"(",
"file",
",",
"3",
",",
"'isa'",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"# The remaining elements of an object dictionary are sorted alphabetically.",
"for",
"property",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"_properties",
".",
"iteritems",
"(",
")",
")",
":",
"self",
".",
"_XCKVPrint",
"(",
"file",
",",
"3",
",",
"property",
",",
"value",
")",
"# End the object.",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"end_tabs",
",",
"'};\\n'",
")"
] | [
700,
2
] | [
736,
41
] | python | en | ['en', 'en', 'en'] | True |
XCObject.UpdateProperties | (self, properties, do_copy=False) | Merge the supplied properties into the _properties dictionary.
The input properties must adhere to the class schema or a KeyError or
TypeError exception will be raised. If adding an object of an XCObject
subclass and the schema indicates a strong relationship, the object's
parent will be set to this object.
If do_copy is True, then lists, dicts, strong-owned XCObjects, and
strong-owned XCObjects in lists will be copied instead of having their
references added.
| Merge the supplied properties into the _properties dictionary. | def UpdateProperties(self, properties, do_copy=False):
"""Merge the supplied properties into the _properties dictionary.
The input properties must adhere to the class schema or a KeyError or
TypeError exception will be raised. If adding an object of an XCObject
subclass and the schema indicates a strong relationship, the object's
parent will be set to this object.
If do_copy is True, then lists, dicts, strong-owned XCObjects, and
strong-owned XCObjects in lists will be copied instead of having their
references added.
"""
if properties is None:
return
for property, value in properties.iteritems():
# Make sure the property is in the schema.
if not property in self._schema:
raise KeyError(property + ' not in ' + self.__class__.__name__)
# Make sure the property conforms to the schema.
(is_list, property_type, is_strong) = self._schema[property][0:3]
if is_list:
if value.__class__ != list:
raise TypeError(
property + ' of ' + self.__class__.__name__ + \
' must be list, not ' + value.__class__.__name__)
for item in value:
if not isinstance(item, property_type) and \
not (item.__class__ == unicode and property_type == str):
# Accept unicode where str is specified. str is treated as
# UTF-8-encoded.
raise TypeError(
'item of ' + property + ' of ' + self.__class__.__name__ + \
' must be ' + property_type.__name__ + ', not ' + \
item.__class__.__name__)
elif not isinstance(value, property_type) and \
not (value.__class__ == unicode and property_type == str):
# Accept unicode where str is specified. str is treated as
# UTF-8-encoded.
raise TypeError(
property + ' of ' + self.__class__.__name__ + ' must be ' + \
property_type.__name__ + ', not ' + value.__class__.__name__)
# Checks passed, perform the assignment.
if do_copy:
if isinstance(value, XCObject):
if is_strong:
self._properties[property] = value.Copy()
else:
self._properties[property] = value
elif isinstance(value, str) or isinstance(value, unicode) or \
isinstance(value, int):
self._properties[property] = value
elif isinstance(value, list):
if is_strong:
# If is_strong is True, each element is an XCObject, so it's safe
# to call Copy.
self._properties[property] = []
for item in value:
self._properties[property].append(item.Copy())
else:
self._properties[property] = value[:]
elif isinstance(value, dict):
self._properties[property] = value.copy()
else:
raise TypeError("Don't know how to copy a " + \
value.__class__.__name__ + ' object for ' + \
property + ' in ' + self.__class__.__name__)
else:
self._properties[property] = value
# Set up the child's back-reference to this object. Don't use |value|
# any more because it may not be right if do_copy is true.
if is_strong:
if not is_list:
self._properties[property].parent = self
else:
for item in self._properties[property]:
item.parent = self | [
"def",
"UpdateProperties",
"(",
"self",
",",
"properties",
",",
"do_copy",
"=",
"False",
")",
":",
"if",
"properties",
"is",
"None",
":",
"return",
"for",
"property",
",",
"value",
"in",
"properties",
".",
"iteritems",
"(",
")",
":",
"# Make sure the property is in the schema.",
"if",
"not",
"property",
"in",
"self",
".",
"_schema",
":",
"raise",
"KeyError",
"(",
"property",
"+",
"' not in '",
"+",
"self",
".",
"__class__",
".",
"__name__",
")",
"# Make sure the property conforms to the schema.",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
")",
"=",
"self",
".",
"_schema",
"[",
"property",
"]",
"[",
"0",
":",
"3",
"]",
"if",
"is_list",
":",
"if",
"value",
".",
"__class__",
"!=",
"list",
":",
"raise",
"TypeError",
"(",
"property",
"+",
"' of '",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"' must be list, not '",
"+",
"value",
".",
"__class__",
".",
"__name__",
")",
"for",
"item",
"in",
"value",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"property_type",
")",
"and",
"not",
"(",
"item",
".",
"__class__",
"==",
"unicode",
"and",
"property_type",
"==",
"str",
")",
":",
"# Accept unicode where str is specified. str is treated as",
"# UTF-8-encoded.",
"raise",
"TypeError",
"(",
"'item of '",
"+",
"property",
"+",
"' of '",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"' must be '",
"+",
"property_type",
".",
"__name__",
"+",
"', not '",
"+",
"item",
".",
"__class__",
".",
"__name__",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"property_type",
")",
"and",
"not",
"(",
"value",
".",
"__class__",
"==",
"unicode",
"and",
"property_type",
"==",
"str",
")",
":",
"# Accept unicode where str is specified. str is treated as",
"# UTF-8-encoded.",
"raise",
"TypeError",
"(",
"property",
"+",
"' of '",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"' must be '",
"+",
"property_type",
".",
"__name__",
"+",
"', not '",
"+",
"value",
".",
"__class__",
".",
"__name__",
")",
"# Checks passed, perform the assignment.",
"if",
"do_copy",
":",
"if",
"isinstance",
"(",
"value",
",",
"XCObject",
")",
":",
"if",
"is_strong",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"value",
".",
"Copy",
"(",
")",
"else",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
"or",
"isinstance",
"(",
"value",
",",
"unicode",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"is_strong",
":",
"# If is_strong is True, each element is an XCObject, so it's safe",
"# to call Copy.",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"[",
"]",
"for",
"item",
"in",
"value",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
".",
"append",
"(",
"item",
".",
"Copy",
"(",
")",
")",
"else",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"value",
"[",
":",
"]",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"value",
".",
"copy",
"(",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Don't know how to copy a \"",
"+",
"value",
".",
"__class__",
".",
"__name__",
"+",
"' object for '",
"+",
"property",
"+",
"' in '",
"+",
"self",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
"=",
"value",
"# Set up the child's back-reference to this object. Don't use |value|",
"# any more because it may not be right if do_copy is true.",
"if",
"is_strong",
":",
"if",
"not",
"is_list",
":",
"self",
".",
"_properties",
"[",
"property",
"]",
".",
"parent",
"=",
"self",
"else",
":",
"for",
"item",
"in",
"self",
".",
"_properties",
"[",
"property",
"]",
":",
"item",
".",
"parent",
"=",
"self"
] | [
738,
2
] | [
818,
30
] | python | en | ['en', 'en', 'en'] | True |
XCObject.VerifyHasRequiredProperties | (self) | Ensure that all properties identified as required by the schema are
set.
| Ensure that all properties identified as required by the schema are
set.
| def VerifyHasRequiredProperties(self):
"""Ensure that all properties identified as required by the schema are
set.
"""
# TODO(mark): A stronger verification mechanism is needed. Some
# subclasses need to perform validation beyond what the schema can enforce.
for property, attributes in self._schema.iteritems():
(is_list, property_type, is_strong, is_required) = attributes[0:4]
if is_required and not property in self._properties:
raise KeyError(self.__class__.__name__ + ' requires ' + property) | [
"def",
"VerifyHasRequiredProperties",
"(",
"self",
")",
":",
"# TODO(mark): A stronger verification mechanism is needed. Some",
"# subclasses need to perform validation beyond what the schema can enforce.",
"for",
"property",
",",
"attributes",
"in",
"self",
".",
"_schema",
".",
"iteritems",
"(",
")",
":",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
",",
"is_required",
")",
"=",
"attributes",
"[",
"0",
":",
"4",
"]",
"if",
"is_required",
"and",
"not",
"property",
"in",
"self",
".",
"_properties",
":",
"raise",
"KeyError",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"' requires '",
"+",
"property",
")"
] | [
860,
2
] | [
870,
73
] | python | en | ['en', 'en', 'en'] | True |
XCObject._SetDefaultsFromSchema | (self) | Assign object default values according to the schema. This will not
overwrite properties that have already been set. | Assign object default values according to the schema. This will not
overwrite properties that have already been set. | def _SetDefaultsFromSchema(self):
"""Assign object default values according to the schema. This will not
overwrite properties that have already been set."""
defaults = {}
for property, attributes in self._schema.iteritems():
(is_list, property_type, is_strong, is_required) = attributes[0:4]
if is_required and len(attributes) >= 5 and \
not property in self._properties:
default = attributes[4]
defaults[property] = default
if len(defaults) > 0:
# Use do_copy=True so that each new object gets its own copy of strong
# objects, lists, and dicts.
self.UpdateProperties(defaults, do_copy=True) | [
"def",
"_SetDefaultsFromSchema",
"(",
"self",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"property",
",",
"attributes",
"in",
"self",
".",
"_schema",
".",
"iteritems",
"(",
")",
":",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
",",
"is_required",
")",
"=",
"attributes",
"[",
"0",
":",
"4",
"]",
"if",
"is_required",
"and",
"len",
"(",
"attributes",
")",
">=",
"5",
"and",
"not",
"property",
"in",
"self",
".",
"_properties",
":",
"default",
"=",
"attributes",
"[",
"4",
"]",
"defaults",
"[",
"property",
"]",
"=",
"default",
"if",
"len",
"(",
"defaults",
")",
">",
"0",
":",
"# Use do_copy=True so that each new object gets its own copy of strong",
"# objects, lists, and dicts.",
"self",
".",
"UpdateProperties",
"(",
"defaults",
",",
"do_copy",
"=",
"True",
")"
] | [
872,
2
] | [
888,
51
] | python | en | ['en', 'en', 'en'] | True |
XCHierarchicalElement.Hashables | (self) | Custom hashables for XCHierarchicalElements.
XCHierarchicalElements are special. Generally, their hashes shouldn't
change if the paths don't change. The normal XCObject implementation of
Hashables adds a hashable for each object, which means that if
the hierarchical structure changes (possibly due to changes caused when
TakeOverOnlyChild runs and encounters slight changes in the hierarchy),
the hashes will change. For example, if a project file initially contains
a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent
a/b. If someone later adds a/f2 to the project file, a/b can no longer be
collapsed, and f1 winds up with parent b and grandparent a. That would
be sufficient to change f1's hash.
To counteract this problem, hashables for all XCHierarchicalElements except
for the main group (which has neither a name nor a path) are taken to be
just the set of path components. Because hashables are inherited from
parents, this provides assurance that a/b/f1 has the same set of hashables
whether its parent is b or a/b.
The main group is a special case. As it is permitted to have no name or
path, it is permitted to use the standard XCObject hash mechanism. This
is not considered a problem because there can be only one main group.
| Custom hashables for XCHierarchicalElements. | def Hashables(self):
"""Custom hashables for XCHierarchicalElements.
XCHierarchicalElements are special. Generally, their hashes shouldn't
change if the paths don't change. The normal XCObject implementation of
Hashables adds a hashable for each object, which means that if
the hierarchical structure changes (possibly due to changes caused when
TakeOverOnlyChild runs and encounters slight changes in the hierarchy),
the hashes will change. For example, if a project file initially contains
a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent
a/b. If someone later adds a/f2 to the project file, a/b can no longer be
collapsed, and f1 winds up with parent b and grandparent a. That would
be sufficient to change f1's hash.
To counteract this problem, hashables for all XCHierarchicalElements except
for the main group (which has neither a name nor a path) are taken to be
just the set of path components. Because hashables are inherited from
parents, this provides assurance that a/b/f1 has the same set of hashables
whether its parent is b or a/b.
The main group is a special case. As it is permitted to have no name or
path, it is permitted to use the standard XCObject hash mechanism. This
is not considered a problem because there can be only one main group.
"""
if self == self.PBXProjectAncestor()._properties['mainGroup']:
# super
return XCObject.Hashables(self)
hashables = []
# Put the name in first, ensuring that if TakeOverOnlyChild collapses
# children into a top-level group like "Source", the name always goes
# into the list of hashables without interfering with path components.
if 'name' in self._properties:
# Make it less likely for people to manipulate hashes by following the
# pattern of always pushing an object type value onto the list first.
hashables.append(self.__class__.__name__ + '.name')
hashables.append(self._properties['name'])
# NOTE: This still has the problem that if an absolute path is encountered,
# including paths with a sourceTree, they'll still inherit their parents'
# hashables, even though the paths aren't relative to their parents. This
# is not expected to be much of a problem in practice.
path = self.PathFromSourceTreeAndPath()
if path != None:
components = path.split(posixpath.sep)
for component in components:
hashables.append(self.__class__.__name__ + '.path')
hashables.append(component)
hashables.extend(self._hashables)
return hashables | [
"def",
"Hashables",
"(",
"self",
")",
":",
"if",
"self",
"==",
"self",
".",
"PBXProjectAncestor",
"(",
")",
".",
"_properties",
"[",
"'mainGroup'",
"]",
":",
"# super",
"return",
"XCObject",
".",
"Hashables",
"(",
"self",
")",
"hashables",
"=",
"[",
"]",
"# Put the name in first, ensuring that if TakeOverOnlyChild collapses",
"# children into a top-level group like \"Source\", the name always goes",
"# into the list of hashables without interfering with path components.",
"if",
"'name'",
"in",
"self",
".",
"_properties",
":",
"# Make it less likely for people to manipulate hashes by following the",
"# pattern of always pushing an object type value onto the list first.",
"hashables",
".",
"append",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"'.name'",
")",
"hashables",
".",
"append",
"(",
"self",
".",
"_properties",
"[",
"'name'",
"]",
")",
"# NOTE: This still has the problem that if an absolute path is encountered,",
"# including paths with a sourceTree, they'll still inherit their parents'",
"# hashables, even though the paths aren't relative to their parents. This",
"# is not expected to be much of a problem in practice.",
"path",
"=",
"self",
".",
"PathFromSourceTreeAndPath",
"(",
")",
"if",
"path",
"!=",
"None",
":",
"components",
"=",
"path",
".",
"split",
"(",
"posixpath",
".",
"sep",
")",
"for",
"component",
"in",
"components",
":",
"hashables",
".",
"append",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"'.path'",
")",
"hashables",
".",
"append",
"(",
"component",
")",
"hashables",
".",
"extend",
"(",
"self",
".",
"_hashables",
")",
"return",
"hashables"
] | [
950,
2
] | [
1003,
20
] | python | en | ['en', 'en', 'en'] | True |
PBXGroup.AddOrGetFileByPath | (self, path, hierarchical) | Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned, otherwise, a
new one will be created, added to the correct group, and returned.
If path identifies a directory by virtue of carrying a trailing slash,
this method returns a PBXFileReference of "folder" type. If path
identifies a variant, by virtue of it identifying a file inside a directory
with an ".lproj" extension, this method returns a PBXVariantGroup
containing the variant named by path, and possibly other variants. For
all other paths, a "normal" PBXFileReference will be returned.
| Returns an existing or new file reference corresponding to path. | def AddOrGetFileByPath(self, path, hierarchical):
"""Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned, otherwise, a
new one will be created, added to the correct group, and returned.
If path identifies a directory by virtue of carrying a trailing slash,
this method returns a PBXFileReference of "folder" type. If path
identifies a variant, by virtue of it identifying a file inside a directory
with an ".lproj" extension, this method returns a PBXVariantGroup
containing the variant named by path, and possibly other variants. For
all other paths, a "normal" PBXFileReference will be returned.
"""
# Adding or getting a directory? Directories end with a trailing slash.
is_dir = False
if path.endswith('/'):
is_dir = True
path = posixpath.normpath(path)
if is_dir:
path = path + '/'
# Adding or getting a variant? Variants are files inside directories
# with an ".lproj" extension. Xcode uses variants for localization. For
# a variant path/to/Language.lproj/MainMenu.nib, put a variant group named
# MainMenu.nib inside path/to, and give it a variant named Language. In
# this example, grandparent would be set to path/to and parent_root would
# be set to Language.
variant_name = None
parent = posixpath.dirname(path)
grandparent = posixpath.dirname(parent)
parent_basename = posixpath.basename(parent)
(parent_root, parent_ext) = posixpath.splitext(parent_basename)
if parent_ext == '.lproj':
variant_name = parent_root
if grandparent == '':
grandparent = None
# Putting a directory inside a variant group is not currently supported.
assert not is_dir or variant_name is None
path_split = path.split(posixpath.sep)
if len(path_split) == 1 or \
((is_dir or variant_name != None) and len(path_split) == 2) or \
not hierarchical:
# The PBXFileReference or PBXVariantGroup will be added to or gotten from
# this PBXGroup, no recursion necessary.
if variant_name is None:
# Add or get a PBXFileReference.
file_ref = self.GetChildByPath(path)
if file_ref != None:
assert file_ref.__class__ == PBXFileReference
else:
file_ref = PBXFileReference({'path': path})
self.AppendChild(file_ref)
else:
# Add or get a PBXVariantGroup. The variant group name is the same
# as the basename (MainMenu.nib in the example above). grandparent
# specifies the path to the variant group itself, and path_split[-2:]
# is the path of the specific variant relative to its group.
variant_group_name = posixpath.basename(path)
variant_group_ref = self.AddOrGetVariantGroupByNameAndPath(
variant_group_name, grandparent)
variant_path = posixpath.sep.join(path_split[-2:])
variant_ref = variant_group_ref.GetChildByPath(variant_path)
if variant_ref != None:
assert variant_ref.__class__ == PBXFileReference
else:
variant_ref = PBXFileReference({'name': variant_name,
'path': variant_path})
variant_group_ref.AppendChild(variant_ref)
# The caller is interested in the variant group, not the specific
# variant file.
file_ref = variant_group_ref
return file_ref
else:
# Hierarchical recursion. Add or get a PBXGroup corresponding to the
# outermost path component, and then recurse into it, chopping off that
# path component.
next_dir = path_split[0]
group_ref = self.GetChildByPath(next_dir)
if group_ref != None:
assert group_ref.__class__ == PBXGroup
else:
group_ref = PBXGroup({'path': next_dir})
self.AppendChild(group_ref)
return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]),
hierarchical) | [
"def",
"AddOrGetFileByPath",
"(",
"self",
",",
"path",
",",
"hierarchical",
")",
":",
"# Adding or getting a directory? Directories end with a trailing slash.",
"is_dir",
"=",
"False",
"if",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"is_dir",
"=",
"True",
"path",
"=",
"posixpath",
".",
"normpath",
"(",
"path",
")",
"if",
"is_dir",
":",
"path",
"=",
"path",
"+",
"'/'",
"# Adding or getting a variant? Variants are files inside directories",
"# with an \".lproj\" extension. Xcode uses variants for localization. For",
"# a variant path/to/Language.lproj/MainMenu.nib, put a variant group named",
"# MainMenu.nib inside path/to, and give it a variant named Language. In",
"# this example, grandparent would be set to path/to and parent_root would",
"# be set to Language.",
"variant_name",
"=",
"None",
"parent",
"=",
"posixpath",
".",
"dirname",
"(",
"path",
")",
"grandparent",
"=",
"posixpath",
".",
"dirname",
"(",
"parent",
")",
"parent_basename",
"=",
"posixpath",
".",
"basename",
"(",
"parent",
")",
"(",
"parent_root",
",",
"parent_ext",
")",
"=",
"posixpath",
".",
"splitext",
"(",
"parent_basename",
")",
"if",
"parent_ext",
"==",
"'.lproj'",
":",
"variant_name",
"=",
"parent_root",
"if",
"grandparent",
"==",
"''",
":",
"grandparent",
"=",
"None",
"# Putting a directory inside a variant group is not currently supported.",
"assert",
"not",
"is_dir",
"or",
"variant_name",
"is",
"None",
"path_split",
"=",
"path",
".",
"split",
"(",
"posixpath",
".",
"sep",
")",
"if",
"len",
"(",
"path_split",
")",
"==",
"1",
"or",
"(",
"(",
"is_dir",
"or",
"variant_name",
"!=",
"None",
")",
"and",
"len",
"(",
"path_split",
")",
"==",
"2",
")",
"or",
"not",
"hierarchical",
":",
"# The PBXFileReference or PBXVariantGroup will be added to or gotten from",
"# this PBXGroup, no recursion necessary.",
"if",
"variant_name",
"is",
"None",
":",
"# Add or get a PBXFileReference.",
"file_ref",
"=",
"self",
".",
"GetChildByPath",
"(",
"path",
")",
"if",
"file_ref",
"!=",
"None",
":",
"assert",
"file_ref",
".",
"__class__",
"==",
"PBXFileReference",
"else",
":",
"file_ref",
"=",
"PBXFileReference",
"(",
"{",
"'path'",
":",
"path",
"}",
")",
"self",
".",
"AppendChild",
"(",
"file_ref",
")",
"else",
":",
"# Add or get a PBXVariantGroup. The variant group name is the same",
"# as the basename (MainMenu.nib in the example above). grandparent",
"# specifies the path to the variant group itself, and path_split[-2:]",
"# is the path of the specific variant relative to its group.",
"variant_group_name",
"=",
"posixpath",
".",
"basename",
"(",
"path",
")",
"variant_group_ref",
"=",
"self",
".",
"AddOrGetVariantGroupByNameAndPath",
"(",
"variant_group_name",
",",
"grandparent",
")",
"variant_path",
"=",
"posixpath",
".",
"sep",
".",
"join",
"(",
"path_split",
"[",
"-",
"2",
":",
"]",
")",
"variant_ref",
"=",
"variant_group_ref",
".",
"GetChildByPath",
"(",
"variant_path",
")",
"if",
"variant_ref",
"!=",
"None",
":",
"assert",
"variant_ref",
".",
"__class__",
"==",
"PBXFileReference",
"else",
":",
"variant_ref",
"=",
"PBXFileReference",
"(",
"{",
"'name'",
":",
"variant_name",
",",
"'path'",
":",
"variant_path",
"}",
")",
"variant_group_ref",
".",
"AppendChild",
"(",
"variant_ref",
")",
"# The caller is interested in the variant group, not the specific",
"# variant file.",
"file_ref",
"=",
"variant_group_ref",
"return",
"file_ref",
"else",
":",
"# Hierarchical recursion. Add or get a PBXGroup corresponding to the",
"# outermost path component, and then recurse into it, chopping off that",
"# path component.",
"next_dir",
"=",
"path_split",
"[",
"0",
"]",
"group_ref",
"=",
"self",
".",
"GetChildByPath",
"(",
"next_dir",
")",
"if",
"group_ref",
"!=",
"None",
":",
"assert",
"group_ref",
".",
"__class__",
"==",
"PBXGroup",
"else",
":",
"group_ref",
"=",
"PBXGroup",
"(",
"{",
"'path'",
":",
"next_dir",
"}",
")",
"self",
".",
"AppendChild",
"(",
"group_ref",
")",
"return",
"group_ref",
".",
"AddOrGetFileByPath",
"(",
"posixpath",
".",
"sep",
".",
"join",
"(",
"path_split",
"[",
"1",
":",
"]",
")",
",",
"hierarchical",
")"
] | [
1212,
2
] | [
1303,
55
] | python | en | ['en', 'en', 'en'] | True |
PBXGroup.AddOrGetVariantGroupByNameAndPath | (self, name, path) | Returns an existing or new PBXVariantGroup for name and path.
If a PBXVariantGroup identified by the name and path arguments is already
present as a child of this object, it is returned. Otherwise, a new
PBXVariantGroup with the correct properties is created, added as a child,
and returned.
This method will generally be called by AddOrGetFileByPath, which knows
when to create a variant group based on the structure of the pathnames
passed to it.
| Returns an existing or new PBXVariantGroup for name and path. | def AddOrGetVariantGroupByNameAndPath(self, name, path):
"""Returns an existing or new PBXVariantGroup for name and path.
If a PBXVariantGroup identified by the name and path arguments is already
present as a child of this object, it is returned. Otherwise, a new
PBXVariantGroup with the correct properties is created, added as a child,
and returned.
This method will generally be called by AddOrGetFileByPath, which knows
when to create a variant group based on the structure of the pathnames
passed to it.
"""
key = (name, path)
if key in self._variant_children_by_name_and_path:
variant_group_ref = self._variant_children_by_name_and_path[key]
assert variant_group_ref.__class__ == PBXVariantGroup
return variant_group_ref
variant_group_properties = {'name': name}
if path != None:
variant_group_properties['path'] = path
variant_group_ref = PBXVariantGroup(variant_group_properties)
self.AppendChild(variant_group_ref)
return variant_group_ref | [
"def",
"AddOrGetVariantGroupByNameAndPath",
"(",
"self",
",",
"name",
",",
"path",
")",
":",
"key",
"=",
"(",
"name",
",",
"path",
")",
"if",
"key",
"in",
"self",
".",
"_variant_children_by_name_and_path",
":",
"variant_group_ref",
"=",
"self",
".",
"_variant_children_by_name_and_path",
"[",
"key",
"]",
"assert",
"variant_group_ref",
".",
"__class__",
"==",
"PBXVariantGroup",
"return",
"variant_group_ref",
"variant_group_properties",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"path",
"!=",
"None",
":",
"variant_group_properties",
"[",
"'path'",
"]",
"=",
"path",
"variant_group_ref",
"=",
"PBXVariantGroup",
"(",
"variant_group_properties",
")",
"self",
".",
"AppendChild",
"(",
"variant_group_ref",
")",
"return",
"variant_group_ref"
] | [
1305,
2
] | [
1330,
28
] | python | en | ['en', 'en', 'en'] | True |
PBXGroup.TakeOverOnlyChild | (self, recurse=False) | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e.
| If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children. | def TakeOverOnlyChild(self, recurse=False):
"""If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e.
"""
# At this stage, check that child class types are PBXGroup exactly,
# instead of using isinstance. The only subclass of PBXGroup,
# PBXVariantGroup, should not participate in reparenting in the same way:
# reparenting by merging different object types would be wrong.
while len(self._properties['children']) == 1 and \
self._properties['children'][0].__class__ == PBXGroup:
# Loop to take over the innermost only-child group possible.
child = self._properties['children'][0]
# Assume the child's properties, including its children. Save a copy
# of this object's old properties, because they'll still be needed.
# This object retains its existing id and parent attributes.
old_properties = self._properties
self._properties = child._properties
self._children_by_path = child._children_by_path
if not 'sourceTree' in self._properties or \
self._properties['sourceTree'] == '<group>':
# The child was relative to its parent. Fix up the path. Note that
# children with a sourceTree other than "<group>" are not relative to
# their parents, so no path fix-up is needed in that case.
if 'path' in old_properties:
if 'path' in self._properties:
# Both the original parent and child have paths set.
self._properties['path'] = posixpath.join(old_properties['path'],
self._properties['path'])
else:
# Only the original parent has a path, use it.
self._properties['path'] = old_properties['path']
if 'sourceTree' in old_properties:
# The original parent had a sourceTree set, use it.
self._properties['sourceTree'] = old_properties['sourceTree']
# If the original parent had a name set, keep using it. If the original
# parent didn't have a name but the child did, let the child's name
# live on. If the name attribute seems unnecessary now, get rid of it.
if 'name' in old_properties and old_properties['name'] != None and \
old_properties['name'] != self.Name():
self._properties['name'] = old_properties['name']
if 'name' in self._properties and 'path' in self._properties and \
self._properties['name'] == self._properties['path']:
del self._properties['name']
# Notify all children of their new parent.
for child in self._properties['children']:
child.parent = self
# If asked to recurse, recurse.
if recurse:
for child in self._properties['children']:
if child.__class__ == PBXGroup:
child.TakeOverOnlyChild(recurse) | [
"def",
"TakeOverOnlyChild",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"# At this stage, check that child class types are PBXGroup exactly,",
"# instead of using isinstance. The only subclass of PBXGroup,",
"# PBXVariantGroup, should not participate in reparenting in the same way:",
"# reparenting by merging different object types would be wrong.",
"while",
"len",
"(",
"self",
".",
"_properties",
"[",
"'children'",
"]",
")",
"==",
"1",
"and",
"self",
".",
"_properties",
"[",
"'children'",
"]",
"[",
"0",
"]",
".",
"__class__",
"==",
"PBXGroup",
":",
"# Loop to take over the innermost only-child group possible.",
"child",
"=",
"self",
".",
"_properties",
"[",
"'children'",
"]",
"[",
"0",
"]",
"# Assume the child's properties, including its children. Save a copy",
"# of this object's old properties, because they'll still be needed.",
"# This object retains its existing id and parent attributes.",
"old_properties",
"=",
"self",
".",
"_properties",
"self",
".",
"_properties",
"=",
"child",
".",
"_properties",
"self",
".",
"_children_by_path",
"=",
"child",
".",
"_children_by_path",
"if",
"not",
"'sourceTree'",
"in",
"self",
".",
"_properties",
"or",
"self",
".",
"_properties",
"[",
"'sourceTree'",
"]",
"==",
"'<group>'",
":",
"# The child was relative to its parent. Fix up the path. Note that",
"# children with a sourceTree other than \"<group>\" are not relative to",
"# their parents, so no path fix-up is needed in that case.",
"if",
"'path'",
"in",
"old_properties",
":",
"if",
"'path'",
"in",
"self",
".",
"_properties",
":",
"# Both the original parent and child have paths set.",
"self",
".",
"_properties",
"[",
"'path'",
"]",
"=",
"posixpath",
".",
"join",
"(",
"old_properties",
"[",
"'path'",
"]",
",",
"self",
".",
"_properties",
"[",
"'path'",
"]",
")",
"else",
":",
"# Only the original parent has a path, use it.",
"self",
".",
"_properties",
"[",
"'path'",
"]",
"=",
"old_properties",
"[",
"'path'",
"]",
"if",
"'sourceTree'",
"in",
"old_properties",
":",
"# The original parent had a sourceTree set, use it.",
"self",
".",
"_properties",
"[",
"'sourceTree'",
"]",
"=",
"old_properties",
"[",
"'sourceTree'",
"]",
"# If the original parent had a name set, keep using it. If the original",
"# parent didn't have a name but the child did, let the child's name",
"# live on. If the name attribute seems unnecessary now, get rid of it.",
"if",
"'name'",
"in",
"old_properties",
"and",
"old_properties",
"[",
"'name'",
"]",
"!=",
"None",
"and",
"old_properties",
"[",
"'name'",
"]",
"!=",
"self",
".",
"Name",
"(",
")",
":",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"=",
"old_properties",
"[",
"'name'",
"]",
"if",
"'name'",
"in",
"self",
".",
"_properties",
"and",
"'path'",
"in",
"self",
".",
"_properties",
"and",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"==",
"self",
".",
"_properties",
"[",
"'path'",
"]",
":",
"del",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"# Notify all children of their new parent.",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"'children'",
"]",
":",
"child",
".",
"parent",
"=",
"self",
"# If asked to recurse, recurse.",
"if",
"recurse",
":",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"'children'",
"]",
":",
"if",
"child",
".",
"__class__",
"==",
"PBXGroup",
":",
"child",
".",
"TakeOverOnlyChild",
"(",
"recurse",
")"
] | [
1332,
2
] | [
1400,
42
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.ConfigurationNamed | (self, name) | Convenience accessor to obtain an XCBuildConfiguration by name. | Convenience accessor to obtain an XCBuildConfiguration by name. | def ConfigurationNamed(self, name):
"""Convenience accessor to obtain an XCBuildConfiguration by name."""
for configuration in self._properties['buildConfigurations']:
if configuration._properties['name'] == name:
return configuration
raise KeyError(name) | [
"def",
"ConfigurationNamed",
"(",
"self",
",",
"name",
")",
":",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"if",
"configuration",
".",
"_properties",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"configuration",
"raise",
"KeyError",
"(",
"name",
")"
] | [
1604,
2
] | [
1610,
24
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.DefaultConfiguration | (self) | Convenience accessor to obtain the default XCBuildConfiguration. | Convenience accessor to obtain the default XCBuildConfiguration. | def DefaultConfiguration(self):
"""Convenience accessor to obtain the default XCBuildConfiguration."""
return self.ConfigurationNamed(self._properties['defaultConfigurationName']) | [
"def",
"DefaultConfiguration",
"(",
"self",
")",
":",
"return",
"self",
".",
"ConfigurationNamed",
"(",
"self",
".",
"_properties",
"[",
"'defaultConfigurationName'",
"]",
")"
] | [
1612,
2
] | [
1614,
80
] | python | en | ['en', 'fr', 'en'] | True |
XCConfigurationList.HasBuildSetting | (self, key) | Determines the state of a build setting in all XCBuildConfiguration
child objects.
If all child objects have key in their build settings, and the value is the
same in all child objects, returns 1.
If no child objects have the key in their build settings, returns 0.
If some, but not all, child objects have the key in their build settings,
or if any children have different values for the key, returns -1.
| Determines the state of a build setting in all XCBuildConfiguration
child objects. | def HasBuildSetting(self, key):
"""Determines the state of a build setting in all XCBuildConfiguration
child objects.
If all child objects have key in their build settings, and the value is the
same in all child objects, returns 1.
If no child objects have the key in their build settings, returns 0.
If some, but not all, child objects have the key in their build settings,
or if any children have different values for the key, returns -1.
"""
has = None
value = None
for configuration in self._properties['buildConfigurations']:
configuration_has = configuration.HasBuildSetting(key)
if has is None:
has = configuration_has
elif has != configuration_has:
return -1
if configuration_has:
configuration_value = configuration.GetBuildSetting(key)
if value is None:
value = configuration_value
elif value != configuration_value:
return -1
if not has:
return 0
return 1 | [
"def",
"HasBuildSetting",
"(",
"self",
",",
"key",
")",
":",
"has",
"=",
"None",
"value",
"=",
"None",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration_has",
"=",
"configuration",
".",
"HasBuildSetting",
"(",
"key",
")",
"if",
"has",
"is",
"None",
":",
"has",
"=",
"configuration_has",
"elif",
"has",
"!=",
"configuration_has",
":",
"return",
"-",
"1",
"if",
"configuration_has",
":",
"configuration_value",
"=",
"configuration",
".",
"GetBuildSetting",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"configuration_value",
"elif",
"value",
"!=",
"configuration_value",
":",
"return",
"-",
"1",
"if",
"not",
"has",
":",
"return",
"0",
"return",
"1"
] | [
1616,
2
] | [
1648,
12
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.GetBuildSetting | (self, key) | Gets the build setting for key.
All child XCConfiguration objects must have the same value set for the
setting, or a ValueError will be raised.
| Gets the build setting for key. | def GetBuildSetting(self, key):
"""Gets the build setting for key.
All child XCConfiguration objects must have the same value set for the
setting, or a ValueError will be raised.
"""
# TODO(mark): This is wrong for build settings that are lists. The list
# contents should be compared (and a list copy returned?)
value = None
for configuration in self._properties['buildConfigurations']:
configuration_value = configuration.GetBuildSetting(key)
if value is None:
value = configuration_value
else:
if value != configuration_value:
raise ValueError('Variant values for ' + key)
return value | [
"def",
"GetBuildSetting",
"(",
"self",
",",
"key",
")",
":",
"# TODO(mark): This is wrong for build settings that are lists. The list",
"# contents should be compared (and a list copy returned?)",
"value",
"=",
"None",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration_value",
"=",
"configuration",
".",
"GetBuildSetting",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"configuration_value",
"else",
":",
"if",
"value",
"!=",
"configuration_value",
":",
"raise",
"ValueError",
"(",
"'Variant values for '",
"+",
"key",
")",
"return",
"value"
] | [
1650,
2
] | [
1669,
16
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.SetBuildSetting | (self, key, value) | Sets the build setting for key to value in all child
XCBuildConfiguration objects.
| Sets the build setting for key to value in all child
XCBuildConfiguration objects.
| def SetBuildSetting(self, key, value):
"""Sets the build setting for key to value in all child
XCBuildConfiguration objects.
"""
for configuration in self._properties['buildConfigurations']:
configuration.SetBuildSetting(key, value) | [
"def",
"SetBuildSetting",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration",
".",
"SetBuildSetting",
"(",
"key",
",",
"value",
")"
] | [
1671,
2
] | [
1677,
47
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.AppendBuildSetting | (self, key, value) | Appends value to the build setting for key, which is treated as a list,
in all child XCBuildConfiguration objects.
| Appends value to the build setting for key, which is treated as a list,
in all child XCBuildConfiguration objects.
| def AppendBuildSetting(self, key, value):
"""Appends value to the build setting for key, which is treated as a list,
in all child XCBuildConfiguration objects.
"""
for configuration in self._properties['buildConfigurations']:
configuration.AppendBuildSetting(key, value) | [
"def",
"AppendBuildSetting",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration",
".",
"AppendBuildSetting",
"(",
"key",
",",
"value",
")"
] | [
1679,
2
] | [
1685,
50
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.DelBuildSetting | (self, key) | Deletes the build setting key from all child XCBuildConfiguration
objects.
| Deletes the build setting key from all child XCBuildConfiguration
objects.
| def DelBuildSetting(self, key):
"""Deletes the build setting key from all child XCBuildConfiguration
objects.
"""
for configuration in self._properties['buildConfigurations']:
configuration.DelBuildSetting(key) | [
"def",
"DelBuildSetting",
"(",
"self",
",",
"key",
")",
":",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration",
".",
"DelBuildSetting",
"(",
"key",
")"
] | [
1687,
2
] | [
1693,
40
] | python | en | ['en', 'en', 'en'] | True |
XCConfigurationList.SetBaseConfiguration | (self, value) | Sets the build configuration in all child XCBuildConfiguration objects.
| Sets the build configuration in all child XCBuildConfiguration objects.
| def SetBaseConfiguration(self, value):
"""Sets the build configuration in all child XCBuildConfiguration objects.
"""
for configuration in self._properties['buildConfigurations']:
configuration.SetBaseConfiguration(value) | [
"def",
"SetBaseConfiguration",
"(",
"self",
",",
"value",
")",
":",
"for",
"configuration",
"in",
"self",
".",
"_properties",
"[",
"'buildConfigurations'",
"]",
":",
"configuration",
".",
"SetBaseConfiguration",
"(",
"value",
")"
] | [
1695,
2
] | [
1700,
47
] | python | en | ['en', 'en', 'en'] | True |
XCBuildPhase._AddPathToDict | (self, pbxbuildfile, path) | Adds path to the dict tracking paths belonging to this build phase.
If the path is already a member of this build phase, raises an exception.
| Adds path to the dict tracking paths belonging to this build phase. | def _AddPathToDict(self, pbxbuildfile, path):
"""Adds path to the dict tracking paths belonging to this build phase.
If the path is already a member of this build phase, raises an exception.
"""
if path in self._files_by_path:
raise ValueError('Found multiple build files with path ' + path)
self._files_by_path[path] = pbxbuildfile | [
"def",
"_AddPathToDict",
"(",
"self",
",",
"pbxbuildfile",
",",
"path",
")",
":",
"if",
"path",
"in",
"self",
".",
"_files_by_path",
":",
"raise",
"ValueError",
"(",
"'Found multiple build files with path '",
"+",
"path",
")",
"self",
".",
"_files_by_path",
"[",
"path",
"]",
"=",
"pbxbuildfile"
] | [
1777,
2
] | [
1785,
44
] | python | en | ['en', 'en', 'en'] | True |
XCBuildPhase._AddBuildFileToDicts | (self, pbxbuildfile, path=None) | Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.
If path is specified, then it is the path that is being added to the
phase, and pbxbuildfile must contain either a PBXFileReference directly
referencing that path, or it must contain a PBXVariantGroup that itself
contains a PBXFileReference referencing the path.
If path is not specified, either the PBXFileReference's path or the paths
of all children of the PBXVariantGroup are taken as being added to the
phase.
If the path is already present in the phase, raises an exception.
If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile
are already present in the phase, referenced by a different PBXBuildFile
object, raises an exception. This does not raise an exception when
a PBXFileReference or PBXVariantGroup reappear and are referenced by the
same PBXBuildFile that has already introduced them, because in the case
of PBXVariantGroup objects, they may correspond to multiple paths that are
not all added simultaneously. When this situation occurs, the path needs
to be added to _files_by_path, but nothing needs to change in
_files_by_xcfilelikeelement, and the caller should have avoided adding
the PBXBuildFile if it is already present in the list of children.
| Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. | def _AddBuildFileToDicts(self, pbxbuildfile, path=None):
"""Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.
If path is specified, then it is the path that is being added to the
phase, and pbxbuildfile must contain either a PBXFileReference directly
referencing that path, or it must contain a PBXVariantGroup that itself
contains a PBXFileReference referencing the path.
If path is not specified, either the PBXFileReference's path or the paths
of all children of the PBXVariantGroup are taken as being added to the
phase.
If the path is already present in the phase, raises an exception.
If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile
are already present in the phase, referenced by a different PBXBuildFile
object, raises an exception. This does not raise an exception when
a PBXFileReference or PBXVariantGroup reappear and are referenced by the
same PBXBuildFile that has already introduced them, because in the case
of PBXVariantGroup objects, they may correspond to multiple paths that are
not all added simultaneously. When this situation occurs, the path needs
to be added to _files_by_path, but nothing needs to change in
_files_by_xcfilelikeelement, and the caller should have avoided adding
the PBXBuildFile if it is already present in the list of children.
"""
xcfilelikeelement = pbxbuildfile._properties['fileRef']
paths = []
if path != None:
# It's best when the caller provides the path.
if isinstance(xcfilelikeelement, PBXVariantGroup):
paths.append(path)
else:
# If the caller didn't provide a path, there can be either multiple
# paths (PBXVariantGroup) or one.
if isinstance(xcfilelikeelement, PBXVariantGroup):
for variant in xcfilelikeelement._properties['children']:
paths.append(variant.FullPath())
else:
paths.append(xcfilelikeelement.FullPath())
# Add the paths first, because if something's going to raise, the
# messages provided by _AddPathToDict are more useful owing to its
# having access to a real pathname and not just an object's Name().
for a_path in paths:
self._AddPathToDict(pbxbuildfile, a_path)
# If another PBXBuildFile references this XCFileLikeElement, there's a
# problem.
if xcfilelikeelement in self._files_by_xcfilelikeelement and \
self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile:
raise ValueError('Found multiple build files for ' + \
xcfilelikeelement.Name())
self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile | [
"def",
"_AddBuildFileToDicts",
"(",
"self",
",",
"pbxbuildfile",
",",
"path",
"=",
"None",
")",
":",
"xcfilelikeelement",
"=",
"pbxbuildfile",
".",
"_properties",
"[",
"'fileRef'",
"]",
"paths",
"=",
"[",
"]",
"if",
"path",
"!=",
"None",
":",
"# It's best when the caller provides the path.",
"if",
"isinstance",
"(",
"xcfilelikeelement",
",",
"PBXVariantGroup",
")",
":",
"paths",
".",
"append",
"(",
"path",
")",
"else",
":",
"# If the caller didn't provide a path, there can be either multiple",
"# paths (PBXVariantGroup) or one.",
"if",
"isinstance",
"(",
"xcfilelikeelement",
",",
"PBXVariantGroup",
")",
":",
"for",
"variant",
"in",
"xcfilelikeelement",
".",
"_properties",
"[",
"'children'",
"]",
":",
"paths",
".",
"append",
"(",
"variant",
".",
"FullPath",
"(",
")",
")",
"else",
":",
"paths",
".",
"append",
"(",
"xcfilelikeelement",
".",
"FullPath",
"(",
")",
")",
"# Add the paths first, because if something's going to raise, the",
"# messages provided by _AddPathToDict are more useful owing to its",
"# having access to a real pathname and not just an object's Name().",
"for",
"a_path",
"in",
"paths",
":",
"self",
".",
"_AddPathToDict",
"(",
"pbxbuildfile",
",",
"a_path",
")",
"# If another PBXBuildFile references this XCFileLikeElement, there's a",
"# problem.",
"if",
"xcfilelikeelement",
"in",
"self",
".",
"_files_by_xcfilelikeelement",
"and",
"self",
".",
"_files_by_xcfilelikeelement",
"[",
"xcfilelikeelement",
"]",
"!=",
"pbxbuildfile",
":",
"raise",
"ValueError",
"(",
"'Found multiple build files for '",
"+",
"xcfilelikeelement",
".",
"Name",
"(",
")",
")",
"self",
".",
"_files_by_xcfilelikeelement",
"[",
"xcfilelikeelement",
"]",
"=",
"pbxbuildfile"
] | [
1787,
2
] | [
1841,
70
] | python | en | ['en', 'en', 'en'] | True |
PBXCopyFilesBuildPhase.SetDestination | (self, path) | Set the dstSubfolderSpec and dstPath properties from path.
path may be specified in the same notation used for XCHierarchicalElements,
specifically, "$(DIR)/path".
| Set the dstSubfolderSpec and dstPath properties from path. | def SetDestination(self, path):
"""Set the dstSubfolderSpec and dstPath properties from path.
path may be specified in the same notation used for XCHierarchicalElements,
specifically, "$(DIR)/path".
"""
path_tree_match = self.path_tree_re.search(path)
if path_tree_match:
# Everything else needs to be relative to an Xcode variable.
path_tree = path_tree_match.group(1)
relative_path = path_tree_match.group(3)
if path_tree in self.path_tree_to_subfolder:
subfolder = self.path_tree_to_subfolder[path_tree]
if relative_path is None:
relative_path = ''
else:
# The path starts with an unrecognized Xcode variable
# name like $(SRCROOT). Xcode will still handle this
# as an "absolute path" that starts with the variable.
subfolder = 0
relative_path = path
elif path.startswith('/'):
# Special case. Absolute paths are in dstSubfolderSpec 0.
subfolder = 0
relative_path = path[1:]
else:
raise ValueError('Can\'t use path %s in a %s' % \
(path, self.__class__.__name__))
self._properties['dstPath'] = relative_path
self._properties['dstSubfolderSpec'] = subfolder | [
"def",
"SetDestination",
"(",
"self",
",",
"path",
")",
":",
"path_tree_match",
"=",
"self",
".",
"path_tree_re",
".",
"search",
"(",
"path",
")",
"if",
"path_tree_match",
":",
"# Everything else needs to be relative to an Xcode variable.",
"path_tree",
"=",
"path_tree_match",
".",
"group",
"(",
"1",
")",
"relative_path",
"=",
"path_tree_match",
".",
"group",
"(",
"3",
")",
"if",
"path_tree",
"in",
"self",
".",
"path_tree_to_subfolder",
":",
"subfolder",
"=",
"self",
".",
"path_tree_to_subfolder",
"[",
"path_tree",
"]",
"if",
"relative_path",
"is",
"None",
":",
"relative_path",
"=",
"''",
"else",
":",
"# The path starts with an unrecognized Xcode variable",
"# name like $(SRCROOT). Xcode will still handle this",
"# as an \"absolute path\" that starts with the variable.",
"subfolder",
"=",
"0",
"relative_path",
"=",
"path",
"elif",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"# Special case. Absolute paths are in dstSubfolderSpec 0.",
"subfolder",
"=",
"0",
"relative_path",
"=",
"path",
"[",
"1",
":",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Can\\'t use path %s in a %s'",
"%",
"(",
"path",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"_properties",
"[",
"'dstPath'",
"]",
"=",
"relative_path",
"self",
".",
"_properties",
"[",
"'dstSubfolderSpec'",
"]",
"=",
"subfolder"
] | [
1976,
2
] | [
2008,
52
] | python | en | ['en', 'en', 'en'] | True |
ConfiguredAssetFilesystemDataConnector.__init__ | (
self,
name: str,
datasource_name: str,
base_directory: str,
assets: dict,
execution_engine: Optional[ExecutionEngine] = None,
default_regex: Optional[dict] = None,
glob_directive: str = "**/*",
sorters: Optional[list] = None,
batch_spec_passthrough: Optional[dict] = None,
) |
Base class for DataConnectors that connect to data on a filesystem. This class supports the configuration of default_regex
and sorters for filtering and sorting data_references. It takes in configured `assets` as a dictionary.
Args:
name (str): name of ConfiguredAssetFilesystemDataConnector
datasource_name (str): Name of datasource that this DataConnector is connected to
assets (dict): configured assets as a dictionary. These can each have their own regex and sorters
execution_engine (ExecutionEngine): ExecutionEngine object to actually read the data
default_regex (dict): Optional dict the filter and organize the data_references.
glob_directive (str): glob for selecting files in directory (defaults to *)
sorters (list): Optional list if you want to sort the data_references
batch_spec_passthrough (dict): dictionary with keys that will be added directly to batch_spec
|
Base class for DataConnectors that connect to data on a filesystem. This class supports the configuration of default_regex
and sorters for filtering and sorting data_references. It takes in configured `assets` as a dictionary. | def __init__(
self,
name: str,
datasource_name: str,
base_directory: str,
assets: dict,
execution_engine: Optional[ExecutionEngine] = None,
default_regex: Optional[dict] = None,
glob_directive: str = "**/*",
sorters: Optional[list] = None,
batch_spec_passthrough: Optional[dict] = None,
):
"""
Base class for DataConnectors that connect to data on a filesystem. This class supports the configuration of default_regex
and sorters for filtering and sorting data_references. It takes in configured `assets` as a dictionary.
Args:
name (str): name of ConfiguredAssetFilesystemDataConnector
datasource_name (str): Name of datasource that this DataConnector is connected to
assets (dict): configured assets as a dictionary. These can each have their own regex and sorters
execution_engine (ExecutionEngine): ExecutionEngine object to actually read the data
default_regex (dict): Optional dict the filter and organize the data_references.
glob_directive (str): glob for selecting files in directory (defaults to *)
sorters (list): Optional list if you want to sort the data_references
batch_spec_passthrough (dict): dictionary with keys that will be added directly to batch_spec
"""
logger.debug(f'Constructing ConfiguredAssetFilesystemDataConnector "{name}".')
super().__init__(
name=name,
datasource_name=datasource_name,
assets=assets,
execution_engine=execution_engine,
default_regex=default_regex,
sorters=sorters,
batch_spec_passthrough=batch_spec_passthrough,
)
self._base_directory = base_directory
self._glob_directive = glob_directive | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"datasource_name",
":",
"str",
",",
"base_directory",
":",
"str",
",",
"assets",
":",
"dict",
",",
"execution_engine",
":",
"Optional",
"[",
"ExecutionEngine",
"]",
"=",
"None",
",",
"default_regex",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"glob_directive",
":",
"str",
"=",
"\"**/*\"",
",",
"sorters",
":",
"Optional",
"[",
"list",
"]",
"=",
"None",
",",
"batch_spec_passthrough",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
")",
":",
"logger",
".",
"debug",
"(",
"f'Constructing ConfiguredAssetFilesystemDataConnector \"{name}\".'",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
"=",
"name",
",",
"datasource_name",
"=",
"datasource_name",
",",
"assets",
"=",
"assets",
",",
"execution_engine",
"=",
"execution_engine",
",",
"default_regex",
"=",
"default_regex",
",",
"sorters",
"=",
"sorters",
",",
"batch_spec_passthrough",
"=",
"batch_spec_passthrough",
",",
")",
"self",
".",
"_base_directory",
"=",
"base_directory",
"self",
".",
"_glob_directive",
"=",
"glob_directive"
] | [
29,
4
] | [
69,
45
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilesystemDataConnector.base_directory | (self) |
Accessor method for base_directory. If directory is a relative path, interpret it as relative to the
root directory. If it is absolute, then keep as-is.
|
Accessor method for base_directory. If directory is a relative path, interpret it as relative to the
root directory. If it is absolute, then keep as-is.
| def base_directory(self) -> str:
"""
Accessor method for base_directory. If directory is a relative path, interpret it as relative to the
root directory. If it is absolute, then keep as-is.
"""
return normalize_directory_path(
dir_path=self._base_directory,
root_directory_path=self.data_context_root_directory,
) | [
"def",
"base_directory",
"(",
"self",
")",
"->",
"str",
":",
"return",
"normalize_directory_path",
"(",
"dir_path",
"=",
"self",
".",
"_base_directory",
",",
"root_directory_path",
"=",
"self",
".",
"data_context_root_directory",
",",
")"
] | [
102,
4
] | [
110,
9
] | python | en | ['en', 'error', 'th'] | False |
ExpectTableColumnCountToEqual.validate_configuration | (self, configuration: Optional[ExpectationConfiguration]) |
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
True if the configuration has been validated successfully. Otherwise, raises an exception
|
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation. | def validate_configuration(self, configuration: Optional[ExpectationConfiguration]):
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
True if the configuration has been validated successfully. Otherwise, raises an exception
"""
# Setting up a configuration
super().validate_configuration(configuration)
# Ensuring that a proper value has been provided
try:
assert (
"value" in configuration.kwargs
), "An expected column count must be provided"
assert isinstance(
configuration.kwargs["value"], (int, dict)
), "Provided threshold must be an integer"
if isinstance(configuration.kwargs["value"], dict):
assert (
"$PARAMETER" in configuration.kwargs["value"]
), 'Evaluation Parameter dict for value kwarg must have "$PARAMETER" key.'
except AssertionError as e:
raise InvalidExpectationConfigurationError(str(e))
return True | [
"def",
"validate_configuration",
"(",
"self",
",",
"configuration",
":",
"Optional",
"[",
"ExpectationConfiguration",
"]",
")",
":",
"# Setting up a configuration",
"super",
"(",
")",
".",
"validate_configuration",
"(",
"configuration",
")",
"# Ensuring that a proper value has been provided",
"try",
":",
"assert",
"(",
"\"value\"",
"in",
"configuration",
".",
"kwargs",
")",
",",
"\"An expected column count must be provided\"",
"assert",
"isinstance",
"(",
"configuration",
".",
"kwargs",
"[",
"\"value\"",
"]",
",",
"(",
"int",
",",
"dict",
")",
")",
",",
"\"Provided threshold must be an integer\"",
"if",
"isinstance",
"(",
"configuration",
".",
"kwargs",
"[",
"\"value\"",
"]",
",",
"dict",
")",
":",
"assert",
"(",
"\"$PARAMETER\"",
"in",
"configuration",
".",
"kwargs",
"[",
"\"value\"",
"]",
")",
",",
"'Evaluation Parameter dict for value kwarg must have \"$PARAMETER\" key.'",
"except",
"AssertionError",
"as",
"e",
":",
"raise",
"InvalidExpectationConfigurationError",
"(",
"str",
"(",
"e",
")",
")",
"return",
"True"
] | [
76,
4
] | [
106,
19
] | python | en | ['en', 'error', 'th'] | False |
assert_how_to_buttons | (
context,
index_page_locator_info: str,
index_links_dict: Dict,
show_how_to_buttons=True,
) | Helper function to assert presence or non-presence of how-to buttons and related content in various
Data Docs pages.
| Helper function to assert presence or non-presence of how-to buttons and related content in various
Data Docs pages.
| def assert_how_to_buttons(
context,
index_page_locator_info: str,
index_links_dict: Dict,
show_how_to_buttons=True,
):
"""Helper function to assert presence or non-presence of how-to buttons and related content in various
Data Docs pages.
"""
# these are simple checks for presence of certain page elements
show_walkthrough_button = "Show Walkthrough"
walkthrough_modal = "Great Expectations Walkthrough"
cta_footer = (
"To continue exploring Great Expectations check out one of these tutorials..."
)
how_to_edit_suite_button = "How to Edit This Suite"
how_to_edit_suite_modal = "How to Edit This Expectation Suite"
action_card = "Actions"
how_to_page_elements_dict = {
"index_pages": [show_walkthrough_button, walkthrough_modal, cta_footer],
"expectation_suites": [
how_to_edit_suite_button,
how_to_edit_suite_modal,
show_walkthrough_button,
walkthrough_modal,
],
"validation_results": [
how_to_edit_suite_button,
how_to_edit_suite_modal,
show_walkthrough_button,
walkthrough_modal,
],
"profiling_results": [action_card, show_walkthrough_button, walkthrough_modal],
}
data_docs_site_dir = os.path.join(
context._context_root_directory,
context._project_config.data_docs_sites["local_site"]["store_backend"][
"base_directory"
],
)
page_paths_dict = {
"index_pages": [index_page_locator_info[7:]],
"expectation_suites": [
os.path.join(data_docs_site_dir, link_dict["filepath"])
for link_dict in index_links_dict.get("expectations_links", [])
],
"validation_results": [
os.path.join(data_docs_site_dir, link_dict["filepath"])
for link_dict in index_links_dict.get("validations_links", [])
],
"profiling_results": [
os.path.join(data_docs_site_dir, link_dict["filepath"])
for link_dict in index_links_dict.get("profiling_links", [])
],
}
for page_type, page_paths in page_paths_dict.items():
for page_path in page_paths:
with open(page_path) as f:
page = f.read()
for how_to_element in how_to_page_elements_dict[page_type]:
if show_how_to_buttons:
assert how_to_element in page
else:
assert how_to_element not in page | [
"def",
"assert_how_to_buttons",
"(",
"context",
",",
"index_page_locator_info",
":",
"str",
",",
"index_links_dict",
":",
"Dict",
",",
"show_how_to_buttons",
"=",
"True",
",",
")",
":",
"# these are simple checks for presence of certain page elements",
"show_walkthrough_button",
"=",
"\"Show Walkthrough\"",
"walkthrough_modal",
"=",
"\"Great Expectations Walkthrough\"",
"cta_footer",
"=",
"(",
"\"To continue exploring Great Expectations check out one of these tutorials...\"",
")",
"how_to_edit_suite_button",
"=",
"\"How to Edit This Suite\"",
"how_to_edit_suite_modal",
"=",
"\"How to Edit This Expectation Suite\"",
"action_card",
"=",
"\"Actions\"",
"how_to_page_elements_dict",
"=",
"{",
"\"index_pages\"",
":",
"[",
"show_walkthrough_button",
",",
"walkthrough_modal",
",",
"cta_footer",
"]",
",",
"\"expectation_suites\"",
":",
"[",
"how_to_edit_suite_button",
",",
"how_to_edit_suite_modal",
",",
"show_walkthrough_button",
",",
"walkthrough_modal",
",",
"]",
",",
"\"validation_results\"",
":",
"[",
"how_to_edit_suite_button",
",",
"how_to_edit_suite_modal",
",",
"show_walkthrough_button",
",",
"walkthrough_modal",
",",
"]",
",",
"\"profiling_results\"",
":",
"[",
"action_card",
",",
"show_walkthrough_button",
",",
"walkthrough_modal",
"]",
",",
"}",
"data_docs_site_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"context",
".",
"_context_root_directory",
",",
"context",
".",
"_project_config",
".",
"data_docs_sites",
"[",
"\"local_site\"",
"]",
"[",
"\"store_backend\"",
"]",
"[",
"\"base_directory\"",
"]",
",",
")",
"page_paths_dict",
"=",
"{",
"\"index_pages\"",
":",
"[",
"index_page_locator_info",
"[",
"7",
":",
"]",
"]",
",",
"\"expectation_suites\"",
":",
"[",
"os",
".",
"path",
".",
"join",
"(",
"data_docs_site_dir",
",",
"link_dict",
"[",
"\"filepath\"",
"]",
")",
"for",
"link_dict",
"in",
"index_links_dict",
".",
"get",
"(",
"\"expectations_links\"",
",",
"[",
"]",
")",
"]",
",",
"\"validation_results\"",
":",
"[",
"os",
".",
"path",
".",
"join",
"(",
"data_docs_site_dir",
",",
"link_dict",
"[",
"\"filepath\"",
"]",
")",
"for",
"link_dict",
"in",
"index_links_dict",
".",
"get",
"(",
"\"validations_links\"",
",",
"[",
"]",
")",
"]",
",",
"\"profiling_results\"",
":",
"[",
"os",
".",
"path",
".",
"join",
"(",
"data_docs_site_dir",
",",
"link_dict",
"[",
"\"filepath\"",
"]",
")",
"for",
"link_dict",
"in",
"index_links_dict",
".",
"get",
"(",
"\"profiling_links\"",
",",
"[",
"]",
")",
"]",
",",
"}",
"for",
"page_type",
",",
"page_paths",
"in",
"page_paths_dict",
".",
"items",
"(",
")",
":",
"for",
"page_path",
"in",
"page_paths",
":",
"with",
"open",
"(",
"page_path",
")",
"as",
"f",
":",
"page",
"=",
"f",
".",
"read",
"(",
")",
"for",
"how_to_element",
"in",
"how_to_page_elements_dict",
"[",
"page_type",
"]",
":",
"if",
"show_how_to_buttons",
":",
"assert",
"how_to_element",
"in",
"page",
"else",
":",
"assert",
"how_to_element",
"not",
"in",
"page"
] | [
21,
0
] | [
89,
57
] | python | en | ['en', 'en', 'en'] | True |
test_site_builder_with_custom_site_section_builders_config | (tmp_path_factory) | Test that site builder can handle partially specified custom site_section_builders config | Test that site builder can handle partially specified custom site_section_builders config | def test_site_builder_with_custom_site_section_builders_config(tmp_path_factory):
"""Test that site builder can handle partially specified custom site_section_builders config"""
base_dir = str(tmp_path_factory.mktemp("project_dir"))
project_dir = os.path.join(base_dir, "project_path")
os.mkdir(project_dir)
# fixture config swaps site section builder source stores and specifies custom run_name_filters
shutil.copy(
file_relative_path(
__file__, "../test_fixtures/great_expectations_custom_local_site_config.yml"
),
str(os.path.join(project_dir, "great_expectations.yml")),
)
context = DataContext(context_root_dir=project_dir)
local_site_config = context._project_config.data_docs_sites.get("local_site")
module_name = "great_expectations.render.renderer.site_builder"
site_builder = instantiate_class_from_config(
config=local_site_config,
runtime_environment={
"data_context": context,
"root_directory": context.root_directory,
"site_name": "local_site",
},
config_defaults={"module_name": module_name},
)
site_section_builders = site_builder.site_section_builders
expectations_site_section_builder = site_section_builders["expectations"]
assert isinstance(expectations_site_section_builder.source_store, ValidationsStore)
validations_site_section_builder = site_section_builders["validations"]
assert isinstance(validations_site_section_builder.source_store, ExpectationsStore)
assert validations_site_section_builder.run_name_filter == {
"not_equals": "custom_validations_filter"
}
profiling_site_section_builder = site_section_builders["profiling"]
assert isinstance(validations_site_section_builder.source_store, ExpectationsStore)
assert profiling_site_section_builder.run_name_filter == {
"equals": "custom_profiling_filter"
} | [
"def",
"test_site_builder_with_custom_site_section_builders_config",
"(",
"tmp_path_factory",
")",
":",
"base_dir",
"=",
"str",
"(",
"tmp_path_factory",
".",
"mktemp",
"(",
"\"project_dir\"",
")",
")",
"project_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"\"project_path\"",
")",
"os",
".",
"mkdir",
"(",
"project_dir",
")",
"# fixture config swaps site section builder source stores and specifies custom run_name_filters",
"shutil",
".",
"copy",
"(",
"file_relative_path",
"(",
"__file__",
",",
"\"../test_fixtures/great_expectations_custom_local_site_config.yml\"",
")",
",",
"str",
"(",
"os",
".",
"path",
".",
"join",
"(",
"project_dir",
",",
"\"great_expectations.yml\"",
")",
")",
",",
")",
"context",
"=",
"DataContext",
"(",
"context_root_dir",
"=",
"project_dir",
")",
"local_site_config",
"=",
"context",
".",
"_project_config",
".",
"data_docs_sites",
".",
"get",
"(",
"\"local_site\"",
")",
"module_name",
"=",
"\"great_expectations.render.renderer.site_builder\"",
"site_builder",
"=",
"instantiate_class_from_config",
"(",
"config",
"=",
"local_site_config",
",",
"runtime_environment",
"=",
"{",
"\"data_context\"",
":",
"context",
",",
"\"root_directory\"",
":",
"context",
".",
"root_directory",
",",
"\"site_name\"",
":",
"\"local_site\"",
",",
"}",
",",
"config_defaults",
"=",
"{",
"\"module_name\"",
":",
"module_name",
"}",
",",
")",
"site_section_builders",
"=",
"site_builder",
".",
"site_section_builders",
"expectations_site_section_builder",
"=",
"site_section_builders",
"[",
"\"expectations\"",
"]",
"assert",
"isinstance",
"(",
"expectations_site_section_builder",
".",
"source_store",
",",
"ValidationsStore",
")",
"validations_site_section_builder",
"=",
"site_section_builders",
"[",
"\"validations\"",
"]",
"assert",
"isinstance",
"(",
"validations_site_section_builder",
".",
"source_store",
",",
"ExpectationsStore",
")",
"assert",
"validations_site_section_builder",
".",
"run_name_filter",
"==",
"{",
"\"not_equals\"",
":",
"\"custom_validations_filter\"",
"}",
"profiling_site_section_builder",
"=",
"site_section_builders",
"[",
"\"profiling\"",
"]",
"assert",
"isinstance",
"(",
"validations_site_section_builder",
".",
"source_store",
",",
"ExpectationsStore",
")",
"assert",
"profiling_site_section_builder",
".",
"run_name_filter",
"==",
"{",
"\"equals\"",
":",
"\"custom_profiling_filter\"",
"}"
] | [
579,
0
] | [
620,
5
] | python | en | ['en', 'en', 'en'] | True |
datetime_column_evrs | () | hand-crafted EVRS for datetime columns | hand-crafted EVRS for datetime columns | def datetime_column_evrs():
"""hand-crafted EVRS for datetime columns"""
with open(
file_relative_path(__file__, "../fixtures/datetime_column_evrs.json")
) as infile:
return expectationSuiteValidationResultSchema.load(
json.load(infile, object_pairs_hook=OrderedDict)
) | [
"def",
"datetime_column_evrs",
"(",
")",
":",
"with",
"open",
"(",
"file_relative_path",
"(",
"__file__",
",",
"\"../fixtures/datetime_column_evrs.json\"",
")",
")",
"as",
"infile",
":",
"return",
"expectationSuiteValidationResultSchema",
".",
"load",
"(",
"json",
".",
"load",
"(",
"infile",
",",
"object_pairs_hook",
"=",
"OrderedDict",
")",
")"
] | [
11,
0
] | [
18,
9
] | python | en | ['en', 'en', 'en'] | True |
test_ProfilingResultsOverviewSectionRenderer_render_variable_types | (
datetime_column_evrs,
) | Build a type table from a type expectations and assert that we correctly infer column type
for datetime. Other types would be useful to test for as well. | Build a type table from a type expectations and assert that we correctly infer column type
for datetime. Other types would be useful to test for as well. | def test_ProfilingResultsOverviewSectionRenderer_render_variable_types(
datetime_column_evrs,
):
"""Build a type table from a type expectations and assert that we correctly infer column type
for datetime. Other types would be useful to test for as well."""
content_blocks = []
ProfilingResultsOverviewSectionRenderer._render_variable_types(
datetime_column_evrs, content_blocks
)
assert len(content_blocks) == 1
type_table = content_blocks[0].table
filtered = [row for row in type_table if row[0] == "datetime"]
assert filtered == [["datetime", "2"]] | [
"def",
"test_ProfilingResultsOverviewSectionRenderer_render_variable_types",
"(",
"datetime_column_evrs",
",",
")",
":",
"content_blocks",
"=",
"[",
"]",
"ProfilingResultsOverviewSectionRenderer",
".",
"_render_variable_types",
"(",
"datetime_column_evrs",
",",
"content_blocks",
")",
"assert",
"len",
"(",
"content_blocks",
")",
"==",
"1",
"type_table",
"=",
"content_blocks",
"[",
"0",
"]",
".",
"table",
"filtered",
"=",
"[",
"row",
"for",
"row",
"in",
"type_table",
"if",
"row",
"[",
"0",
"]",
"==",
"\"datetime\"",
"]",
"assert",
"filtered",
"==",
"[",
"[",
"\"datetime\"",
",",
"\"2\"",
"]",
"]"
] | [
21,
0
] | [
34,
42
] | python | en | ['en', 'en', 'en'] | True |
parse_result_format | (result_format) | This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexpected_count. | This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexpected_count. | def parse_result_format(result_format):
"""This is a simple helper utility that can be used to parse a string result_format into the dict format used
internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where
there is no need to specify a custom partial_unexpected_count."""
if isinstance(result_format, str):
result_format = {"result_format": result_format, "partial_unexpected_count": 20}
else:
if "partial_unexpected_count" not in result_format:
result_format["partial_unexpected_count"] = 20
return result_format | [
"def",
"parse_result_format",
"(",
"result_format",
")",
":",
"if",
"isinstance",
"(",
"result_format",
",",
"str",
")",
":",
"result_format",
"=",
"{",
"\"result_format\"",
":",
"result_format",
",",
"\"partial_unexpected_count\"",
":",
"20",
"}",
"else",
":",
"if",
"\"partial_unexpected_count\"",
"not",
"in",
"result_format",
":",
"result_format",
"[",
"\"partial_unexpected_count\"",
"]",
"=",
"20",
"return",
"result_format"
] | [
35,
0
] | [
45,
24
] | python | en | ['en', 'en', 'en'] | True |
ExpectationConfiguration.patch | (self, op: str, path: str, value: Any) |
Args:
op: A jsonpatch operation. One of 'add', 'replace', or 'remove'
path: A jsonpatch path for the patch operation
value: The value to patch
Returns:
The patched ExpectationConfiguration object
| def patch(self, op: str, path: str, value: Any) -> "ExpectationConfiguration":
"""
Args:
op: A jsonpatch operation. One of 'add', 'replace', or 'remove'
path: A jsonpatch path for the patch operation
value: The value to patch
Returns:
The patched ExpectationConfiguration object
"""
if op not in ["add", "replace", "remove"]:
raise ValueError("Op must be either 'add', 'replace', or 'remove'")
try:
valid_path = path.split("/")[1]
except IndexError:
raise IndexError(
"Ensure you have a valid jsonpatch path of the form '/path/foo' "
"(see http://jsonpatch.com/)"
)
if valid_path not in self.get_runtime_kwargs().keys():
raise ValueError("Path not available in kwargs (see http://jsonpatch.com/)")
# TODO: Call validate_kwargs when implemented
patch = jsonpatch.JsonPatch([{"op": op, "path": path, "value": value}])
patch.apply(self.kwargs, in_place=True)
return self | [
"def",
"patch",
"(",
"self",
",",
"op",
":",
"str",
",",
"path",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"\"ExpectationConfiguration\"",
":",
"if",
"op",
"not",
"in",
"[",
"\"add\"",
",",
"\"replace\"",
",",
"\"remove\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Op must be either 'add', 'replace', or 'remove'\"",
")",
"try",
":",
"valid_path",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"[",
"1",
"]",
"except",
"IndexError",
":",
"raise",
"IndexError",
"(",
"\"Ensure you have a valid jsonpatch path of the form '/path/foo' \"",
"\"(see http://jsonpatch.com/)\"",
")",
"if",
"valid_path",
"not",
"in",
"self",
".",
"get_runtime_kwargs",
"(",
")",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Path not available in kwargs (see http://jsonpatch.com/)\"",
")",
"# TODO: Call validate_kwargs when implemented",
"patch",
"=",
"jsonpatch",
".",
"JsonPatch",
"(",
"[",
"{",
"\"op\"",
":",
"op",
",",
"\"path\"",
":",
"path",
",",
"\"value\"",
":",
"value",
"}",
"]",
")",
"patch",
".",
"apply",
"(",
"self",
".",
"kwargs",
",",
"in_place",
"=",
"True",
")",
"return",
"self"
] | [
930,
4
] | [
959,
19
] | python | en | ['en', 'error', 'th'] | False |
|
ExpectationConfiguration.isEquivalentTo | (self, other, match_type="success") | ExpectationConfiguration equivalence does not include meta, and relies on *equivalence* of kwargs. | ExpectationConfiguration equivalence does not include meta, and relies on *equivalence* of kwargs. | def isEquivalentTo(self, other, match_type="success"):
"""ExpectationConfiguration equivalence does not include meta, and relies on *equivalence* of kwargs."""
if not isinstance(other, self.__class__):
if isinstance(other, dict):
try:
other = expectationConfigurationSchema.load(other)
except ValidationError:
logger.debug(
"Unable to evaluate equivalence of ExpectationConfiguration object with dict because "
"dict other could not be instantiated as an ExpectationConfiguration"
)
return NotImplemented
else:
# Delegate comparison to the other instance
return NotImplemented
if match_type == "domain":
return all(
(
self.expectation_type == other.expectation_type,
self.get_domain_kwargs() == other.get_domain_kwargs(),
)
)
elif match_type == "success":
return all(
(
self.expectation_type == other.expectation_type,
self.get_success_kwargs() == other.get_success_kwargs(),
)
)
elif match_type == "runtime":
return all(
(
self.expectation_type == other.expectation_type,
self.kwargs == other.kwargs,
)
) | [
"def",
"isEquivalentTo",
"(",
"self",
",",
"other",
",",
"match_type",
"=",
"\"success\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"dict",
")",
":",
"try",
":",
"other",
"=",
"expectationConfigurationSchema",
".",
"load",
"(",
"other",
")",
"except",
"ValidationError",
":",
"logger",
".",
"debug",
"(",
"\"Unable to evaluate equivalence of ExpectationConfiguration object with dict because \"",
"\"dict other could not be instantiated as an ExpectationConfiguration\"",
")",
"return",
"NotImplemented",
"else",
":",
"# Delegate comparison to the other instance",
"return",
"NotImplemented",
"if",
"match_type",
"==",
"\"domain\"",
":",
"return",
"all",
"(",
"(",
"self",
".",
"expectation_type",
"==",
"other",
".",
"expectation_type",
",",
"self",
".",
"get_domain_kwargs",
"(",
")",
"==",
"other",
".",
"get_domain_kwargs",
"(",
")",
",",
")",
")",
"elif",
"match_type",
"==",
"\"success\"",
":",
"return",
"all",
"(",
"(",
"self",
".",
"expectation_type",
"==",
"other",
".",
"expectation_type",
",",
"self",
".",
"get_success_kwargs",
"(",
")",
"==",
"other",
".",
"get_success_kwargs",
"(",
")",
",",
")",
")",
"elif",
"match_type",
"==",
"\"runtime\"",
":",
"return",
"all",
"(",
"(",
"self",
".",
"expectation_type",
"==",
"other",
".",
"expectation_type",
",",
"self",
".",
"kwargs",
"==",
"other",
".",
"kwargs",
",",
")",
")"
] | [
1114,
4
] | [
1151,
13
] | python | en | ['en', 'en', 'en'] | True |
ExpectationConfiguration.__eq__ | (self, other) | ExpectationConfiguration equality does include meta, but ignores instance identity. | ExpectationConfiguration equality does include meta, but ignores instance identity. | def __eq__(self, other):
"""ExpectationConfiguration equality does include meta, but ignores instance identity."""
if not isinstance(other, self.__class__):
# Delegate comparison to the other instance's __eq__.
return NotImplemented
this_kwargs: dict = convert_to_json_serializable(self.kwargs)
other_kwargs: dict = convert_to_json_serializable(other.kwargs)
this_meta: dict = convert_to_json_serializable(self.meta)
other_meta: dict = convert_to_json_serializable(other.meta)
return all(
(
self.expectation_type == other.expectation_type,
this_kwargs == other_kwargs,
this_meta == other_meta,
)
) | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"# Delegate comparison to the other instance's __eq__.",
"return",
"NotImplemented",
"this_kwargs",
":",
"dict",
"=",
"convert_to_json_serializable",
"(",
"self",
".",
"kwargs",
")",
"other_kwargs",
":",
"dict",
"=",
"convert_to_json_serializable",
"(",
"other",
".",
"kwargs",
")",
"this_meta",
":",
"dict",
"=",
"convert_to_json_serializable",
"(",
"self",
".",
"meta",
")",
"other_meta",
":",
"dict",
"=",
"convert_to_json_serializable",
"(",
"other",
".",
"meta",
")",
"return",
"all",
"(",
"(",
"self",
".",
"expectation_type",
"==",
"other",
".",
"expectation_type",
",",
"this_kwargs",
"==",
"other_kwargs",
",",
"this_meta",
"==",
"other_meta",
",",
")",
")"
] | [
1153,
4
] | [
1168,
9
] | python | en | ['en', 'en', 'en'] | True |
escape | (string) | Escape a string such that it can be embedded into a Ninja file without
further interpretation. | Escape a string such that it can be embedded into a Ninja file without
further interpretation. | def escape(string):
"""Escape a string such that it can be embedded into a Ninja file without
further interpretation."""
assert '\n' not in string, 'Ninja syntax does not allow newlines'
# We only have one special metacharacter: '$'.
return string.replace('$', '$$') | [
"def",
"escape",
"(",
"string",
")",
":",
"assert",
"'\\n'",
"not",
"in",
"string",
",",
"'Ninja syntax does not allow newlines'",
"# We only have one special metacharacter: '$'.",
"return",
"string",
".",
"replace",
"(",
"'$'",
",",
"'$$'",
")"
] | [
154,
0
] | [
159,
36
] | python | en | ['en', 'en', 'en'] | True |
Writer._count_dollars_before_index | (self, s, i) | Returns the number of '$' characters right in front of s[i]. | Returns the number of '$' characters right in front of s[i]. | def _count_dollars_before_index(self, s, i):
"""Returns the number of '$' characters right in front of s[i]."""
dollar_count = 0
dollar_index = i - 1
while dollar_index > 0 and s[dollar_index] == '$':
dollar_count += 1
dollar_index -= 1
return dollar_count | [
"def",
"_count_dollars_before_index",
"(",
"self",
",",
"s",
",",
"i",
")",
":",
"dollar_count",
"=",
"0",
"dollar_index",
"=",
"i",
"-",
"1",
"while",
"dollar_index",
">",
"0",
"and",
"s",
"[",
"dollar_index",
"]",
"==",
"'$'",
":",
"dollar_count",
"+=",
"1",
"dollar_index",
"-=",
"1",
"return",
"dollar_count"
] | [
101,
4
] | [
108,
25
] | python | en | ['en', 'en', 'en'] | True |
Writer._line | (self, text, indent=0) | Write 'text' word-wrapped at self.width characters. | Write 'text' word-wrapped at self.width characters. | def _line(self, text, indent=0):
"""Write 'text' word-wrapped at self.width characters."""
leading_space = ' ' * indent
while len(leading_space) + len(text) > self.width:
# The text is too wide; wrap if possible.
# Find the rightmost space that would obey our width constraint and
# that's not an escaped space.
available_space = self.width - len(leading_space) - len(' $')
space = available_space
while True:
space = text.rfind(' ', 0, space)
if space < 0 or \
self._count_dollars_before_index(text, space) % 2 == 0:
break
if space < 0:
# No such space; just use the first unescaped space we can find.
space = available_space - 1
while True:
space = text.find(' ', space + 1)
if space < 0 or \
self._count_dollars_before_index(text, space) % 2 == 0:
break
if space < 0:
# Give up on breaking.
break
self.output.write(leading_space + text[0:space] + ' $\n')
text = text[space+1:]
# Subsequent lines are continuations, so indent them.
leading_space = ' ' * (indent+2)
self.output.write(leading_space + text + '\n') | [
"def",
"_line",
"(",
"self",
",",
"text",
",",
"indent",
"=",
"0",
")",
":",
"leading_space",
"=",
"' '",
"*",
"indent",
"while",
"len",
"(",
"leading_space",
")",
"+",
"len",
"(",
"text",
")",
">",
"self",
".",
"width",
":",
"# The text is too wide; wrap if possible.",
"# Find the rightmost space that would obey our width constraint and",
"# that's not an escaped space.",
"available_space",
"=",
"self",
".",
"width",
"-",
"len",
"(",
"leading_space",
")",
"-",
"len",
"(",
"' $'",
")",
"space",
"=",
"available_space",
"while",
"True",
":",
"space",
"=",
"text",
".",
"rfind",
"(",
"' '",
",",
"0",
",",
"space",
")",
"if",
"space",
"<",
"0",
"or",
"self",
".",
"_count_dollars_before_index",
"(",
"text",
",",
"space",
")",
"%",
"2",
"==",
"0",
":",
"break",
"if",
"space",
"<",
"0",
":",
"# No such space; just use the first unescaped space we can find.",
"space",
"=",
"available_space",
"-",
"1",
"while",
"True",
":",
"space",
"=",
"text",
".",
"find",
"(",
"' '",
",",
"space",
"+",
"1",
")",
"if",
"space",
"<",
"0",
"or",
"self",
".",
"_count_dollars_before_index",
"(",
"text",
",",
"space",
")",
"%",
"2",
"==",
"0",
":",
"break",
"if",
"space",
"<",
"0",
":",
"# Give up on breaking.",
"break",
"self",
".",
"output",
".",
"write",
"(",
"leading_space",
"+",
"text",
"[",
"0",
":",
"space",
"]",
"+",
"' $\\n'",
")",
"text",
"=",
"text",
"[",
"space",
"+",
"1",
":",
"]",
"# Subsequent lines are continuations, so indent them.",
"leading_space",
"=",
"' '",
"*",
"(",
"indent",
"+",
"2",
")",
"self",
".",
"output",
".",
"write",
"(",
"leading_space",
"+",
"text",
"+",
"'\\n'",
")"
] | [
110,
4
] | [
144,
54
] | python | en | ['en', 'en', 'en'] | True |
ExpectColumnMinToBeBetween.validate_configuration | (self, configuration: Optional[ExpectationConfiguration]) |
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
True if the configuration has been validated successfully. Otherwise, raises an exception
|
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation. | def validate_configuration(self, configuration: Optional[ExpectationConfiguration]):
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
True if the configuration has been validated successfully. Otherwise, raises an exception
"""
super().validate_configuration(configuration=configuration)
self.validate_metric_value_between_configuration(configuration=configuration) | [
"def",
"validate_configuration",
"(",
"self",
",",
"configuration",
":",
"Optional",
"[",
"ExpectationConfiguration",
"]",
")",
":",
"super",
"(",
")",
".",
"validate_configuration",
"(",
"configuration",
"=",
"configuration",
")",
"self",
".",
"validate_metric_value_between_configuration",
"(",
"configuration",
"=",
"configuration",
")"
] | [
105,
4
] | [
117,
85
] | python | en | ['en', 'error', 'th'] | False |
declaration_path | (decl, with_defaults=None) |
Returns a list of parent declarations names.
Args:
decl (declaration_t): declaration for which declaration path
should be calculated.
Returns:
list[(str | basestring)]: list of names, where first item is the top
parent name and last item the inputted
declaration name.
|
Returns a list of parent declarations names. | def declaration_path(decl, with_defaults=None):
"""
Returns a list of parent declarations names.
Args:
decl (declaration_t): declaration for which declaration path
should be calculated.
Returns:
list[(str | basestring)]: list of names, where first item is the top
parent name and last item the inputted
declaration name.
"""
if with_defaults is not None:
# Deprecated since 1.9.0, will be removed in 2.0.0
warnings.warn(
"The with_defaults parameter is deprecated.\n", DeprecationWarning)
if not decl:
return []
if not decl.cache.declaration_path:
result = [decl.name]
parent = decl.parent
while parent:
if parent.cache.declaration_path:
result.reverse()
decl.cache.declaration_path = parent.cache.declaration_path + \
result
return decl.cache.declaration_path
else:
result.append(parent.name)
parent = parent.parent
result.reverse()
decl.cache.declaration_path = result
return result
else:
return decl.cache.declaration_path | [
"def",
"declaration_path",
"(",
"decl",
",",
"with_defaults",
"=",
"None",
")",
":",
"if",
"with_defaults",
"is",
"not",
"None",
":",
"# Deprecated since 1.9.0, will be removed in 2.0.0",
"warnings",
".",
"warn",
"(",
"\"The with_defaults parameter is deprecated.\\n\"",
",",
"DeprecationWarning",
")",
"if",
"not",
"decl",
":",
"return",
"[",
"]",
"if",
"not",
"decl",
".",
"cache",
".",
"declaration_path",
":",
"result",
"=",
"[",
"decl",
".",
"name",
"]",
"parent",
"=",
"decl",
".",
"parent",
"while",
"parent",
":",
"if",
"parent",
".",
"cache",
".",
"declaration_path",
":",
"result",
".",
"reverse",
"(",
")",
"decl",
".",
"cache",
".",
"declaration_path",
"=",
"parent",
".",
"cache",
".",
"declaration_path",
"+",
"result",
"return",
"decl",
".",
"cache",
".",
"declaration_path",
"else",
":",
"result",
".",
"append",
"(",
"parent",
".",
"name",
")",
"parent",
"=",
"parent",
".",
"parent",
"result",
".",
"reverse",
"(",
")",
"decl",
".",
"cache",
".",
"declaration_path",
"=",
"result",
"return",
"result",
"else",
":",
"return",
"decl",
".",
"cache",
".",
"declaration_path"
] | [
8,
0
] | [
45,
42
] | python | en | ['en', 'error', 'th'] | False |
partial_declaration_path | (decl) |
Returns a list of parent declarations names without template arguments that
have default value.
Args:
decl (declaration_t): declaration for which the partial declaration
path should be calculated.
Returns:
list[(str | basestring)]: list of names, where first item is the top
parent name and last item the inputted
declaration name.
|
Returns a list of parent declarations names without template arguments that
have default value. | def partial_declaration_path(decl):
"""
Returns a list of parent declarations names without template arguments that
have default value.
Args:
decl (declaration_t): declaration for which the partial declaration
path should be calculated.
Returns:
list[(str | basestring)]: list of names, where first item is the top
parent name and last item the inputted
declaration name.
"""
# TODO:
# If parent declaration cache already has declaration_path, reuse it for
# calculation.
if not decl:
return []
if not decl.cache.partial_declaration_path:
result = [decl.partial_name]
parent = decl.parent
while parent:
if parent.cache.partial_declaration_path:
result.reverse()
decl.cache.partial_declaration_path \
= parent.cache.partial_declaration_path + result
return decl.cache.partial_declaration_path
else:
result.append(parent.partial_name)
parent = parent.parent
result.reverse()
decl.cache.partial_declaration_path = result
return result
else:
return decl.cache.partial_declaration_path | [
"def",
"partial_declaration_path",
"(",
"decl",
")",
":",
"# TODO:",
"# If parent declaration cache already has declaration_path, reuse it for",
"# calculation.",
"if",
"not",
"decl",
":",
"return",
"[",
"]",
"if",
"not",
"decl",
".",
"cache",
".",
"partial_declaration_path",
":",
"result",
"=",
"[",
"decl",
".",
"partial_name",
"]",
"parent",
"=",
"decl",
".",
"parent",
"while",
"parent",
":",
"if",
"parent",
".",
"cache",
".",
"partial_declaration_path",
":",
"result",
".",
"reverse",
"(",
")",
"decl",
".",
"cache",
".",
"partial_declaration_path",
"=",
"parent",
".",
"cache",
".",
"partial_declaration_path",
"+",
"result",
"return",
"decl",
".",
"cache",
".",
"partial_declaration_path",
"else",
":",
"result",
".",
"append",
"(",
"parent",
".",
"partial_name",
")",
"parent",
"=",
"parent",
".",
"parent",
"result",
".",
"reverse",
"(",
")",
"decl",
".",
"cache",
".",
"partial_declaration_path",
"=",
"result",
"return",
"result",
"else",
":",
"return",
"decl",
".",
"cache",
".",
"partial_declaration_path"
] | [
48,
0
] | [
84,
50
] | python | en | ['en', 'error', 'th'] | False |
full_name | (decl, with_defaults=True) |
Returns declaration full qualified name.
If `decl` belongs to anonymous namespace or class, the function will return
C++ illegal qualified name.
Args:
decl (declaration_t): declaration for which the full qualified name
should be calculated.
Returns:
list[(str | basestring)]: full name of the declaration.
|
Returns declaration full qualified name. | def full_name(decl, with_defaults=True):
"""
Returns declaration full qualified name.
If `decl` belongs to anonymous namespace or class, the function will return
C++ illegal qualified name.
Args:
decl (declaration_t): declaration for which the full qualified name
should be calculated.
Returns:
list[(str | basestring)]: full name of the declaration.
"""
if None is decl:
raise RuntimeError("Unable to generate full name for None object!")
if with_defaults:
if not decl.cache.full_name:
path = declaration_path(decl)
if path == [""]:
# Declarations without names are allowed (for examples class
# or struct instances). In this case set an empty name..
decl.cache.full_name = ""
else:
decl.cache.full_name = full_name_from_declaration_path(path)
return decl.cache.full_name
else:
if not decl.cache.full_partial_name:
path = partial_declaration_path(decl)
if path == [""]:
# Declarations without names are allowed (for examples class
# or struct instances). In this case set an empty name.
decl.cache.full_partial_name = ""
else:
decl.cache.full_partial_name = \
full_name_from_declaration_path(path)
return decl.cache.full_partial_name | [
"def",
"full_name",
"(",
"decl",
",",
"with_defaults",
"=",
"True",
")",
":",
"if",
"None",
"is",
"decl",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to generate full name for None object!\"",
")",
"if",
"with_defaults",
":",
"if",
"not",
"decl",
".",
"cache",
".",
"full_name",
":",
"path",
"=",
"declaration_path",
"(",
"decl",
")",
"if",
"path",
"==",
"[",
"\"\"",
"]",
":",
"# Declarations without names are allowed (for examples class",
"# or struct instances). In this case set an empty name..",
"decl",
".",
"cache",
".",
"full_name",
"=",
"\"\"",
"else",
":",
"decl",
".",
"cache",
".",
"full_name",
"=",
"full_name_from_declaration_path",
"(",
"path",
")",
"return",
"decl",
".",
"cache",
".",
"full_name",
"else",
":",
"if",
"not",
"decl",
".",
"cache",
".",
"full_partial_name",
":",
"path",
"=",
"partial_declaration_path",
"(",
"decl",
")",
"if",
"path",
"==",
"[",
"\"\"",
"]",
":",
"# Declarations without names are allowed (for examples class",
"# or struct instances). In this case set an empty name.",
"decl",
".",
"cache",
".",
"full_partial_name",
"=",
"\"\"",
"else",
":",
"decl",
".",
"cache",
".",
"full_partial_name",
"=",
"full_name_from_declaration_path",
"(",
"path",
")",
"return",
"decl",
".",
"cache",
".",
"full_partial_name"
] | [
96,
0
] | [
134,
43
] | python | en | ['en', 'error', 'th'] | False |
get_named_parent | (decl) |
Returns a reference to a named parent declaration.
Args:
decl (declaration_t): the child declaration
Returns:
declaration_t: the declaration or None if not found.
|
Returns a reference to a named parent declaration. | def get_named_parent(decl):
"""
Returns a reference to a named parent declaration.
Args:
decl (declaration_t): the child declaration
Returns:
declaration_t: the declaration or None if not found.
"""
if not decl:
return None
parent = decl.parent
while parent and (not parent.name or parent.name == '::'):
parent = parent.parent
return parent | [
"def",
"get_named_parent",
"(",
"decl",
")",
":",
"if",
"not",
"decl",
":",
"return",
"None",
"parent",
"=",
"decl",
".",
"parent",
"while",
"parent",
"and",
"(",
"not",
"parent",
".",
"name",
"or",
"parent",
".",
"name",
"==",
"'::'",
")",
":",
"parent",
"=",
"parent",
".",
"parent",
"return",
"parent"
] | [
137,
0
] | [
155,
17
] | python | en | ['en', 'error', 'th'] | False |
test_comprehensive_list_of_messages | () | Ensure that we have a comprehensive set of tests for known messages, by
forcing a manual update to this list when a message is added or removed, and
reminding the developer to add or remove the associate test. | Ensure that we have a comprehensive set of tests for known messages, by
forcing a manual update to this list when a message is added or removed, and
reminding the developer to add or remove the associate test. | def test_comprehensive_list_of_messages():
"""Ensure that we have a comprehensive set of tests for known messages, by
forcing a manual update to this list when a message is added or removed, and
reminding the developer to add or remove the associate test."""
valid_message_list = list(valid_usage_statistics_messages.keys())
# NOTE: If you are changing the expected valid message list below, you need
# to also update one or more tests below!
assert set(valid_message_list) == {
"cli.checkpoint.delete",
"cli.checkpoint.list",
"cli.checkpoint.new",
"cli.checkpoint.run",
"cli.checkpoint.script",
"cli.datasource.delete",
"cli.datasource.list",
"cli.datasource.new",
"cli.datasource.profile",
"cli.docs.build",
"cli.docs.clean",
"cli.docs.list",
"cli.init.create",
"cli.new_ds_choice",
"cli.project.check_config",
"cli.project.upgrade",
"cli.store.list",
"cli.suite.delete",
"cli.suite.demo",
"cli.suite.edit",
"cli.suite.list",
"cli.suite.new",
"cli.suite.scaffold",
"cli.validation_operator.list",
"cli.validation_operator.run",
"data_asset.validate",
"data_context.__init__",
"data_context.add_datasource",
"data_context.build_data_docs",
"data_context.open_data_docs",
"data_context.save_expectation_suite",
"datasource.sqlalchemy.connect",
"data_context.test_yaml_config",
} | [
"def",
"test_comprehensive_list_of_messages",
"(",
")",
":",
"valid_message_list",
"=",
"list",
"(",
"valid_usage_statistics_messages",
".",
"keys",
"(",
")",
")",
"# NOTE: If you are changing the expected valid message list below, you need",
"# to also update one or more tests below!",
"assert",
"set",
"(",
"valid_message_list",
")",
"==",
"{",
"\"cli.checkpoint.delete\"",
",",
"\"cli.checkpoint.list\"",
",",
"\"cli.checkpoint.new\"",
",",
"\"cli.checkpoint.run\"",
",",
"\"cli.checkpoint.script\"",
",",
"\"cli.datasource.delete\"",
",",
"\"cli.datasource.list\"",
",",
"\"cli.datasource.new\"",
",",
"\"cli.datasource.profile\"",
",",
"\"cli.docs.build\"",
",",
"\"cli.docs.clean\"",
",",
"\"cli.docs.list\"",
",",
"\"cli.init.create\"",
",",
"\"cli.new_ds_choice\"",
",",
"\"cli.project.check_config\"",
",",
"\"cli.project.upgrade\"",
",",
"\"cli.store.list\"",
",",
"\"cli.suite.delete\"",
",",
"\"cli.suite.demo\"",
",",
"\"cli.suite.edit\"",
",",
"\"cli.suite.list\"",
",",
"\"cli.suite.new\"",
",",
"\"cli.suite.scaffold\"",
",",
"\"cli.validation_operator.list\"",
",",
"\"cli.validation_operator.run\"",
",",
"\"data_asset.validate\"",
",",
"\"data_context.__init__\"",
",",
"\"data_context.add_datasource\"",
",",
"\"data_context.build_data_docs\"",
",",
"\"data_context.open_data_docs\"",
",",
"\"data_context.save_expectation_suite\"",
",",
"\"datasource.sqlalchemy.connect\"",
",",
"\"data_context.test_yaml_config\"",
",",
"}"
] | [
19,
0
] | [
61,
5
] | python | en | ['en', 'en', 'en'] | True |
ValidationResultsPageRenderer.__init__ | (self, column_section_renderer=None, run_info_at_end: bool = False) |
Args:
column_section_renderer:
run_info_at_end: Move the run info (Info, Batch Markers, Batch Kwargs) to the end
of the rendered output rather than after Statistics.
|
Args:
column_section_renderer:
run_info_at_end: Move the run info (Info, Batch Markers, Batch Kwargs) to the end
of the rendered output rather than after Statistics.
| def __init__(self, column_section_renderer=None, run_info_at_end: bool = False):
"""
Args:
column_section_renderer:
run_info_at_end: Move the run info (Info, Batch Markers, Batch Kwargs) to the end
of the rendered output rather than after Statistics.
"""
super().__init__()
if column_section_renderer is None:
column_section_renderer = {
"class_name": "ValidationResultsColumnSectionRenderer"
}
module_name = "great_expectations.render.renderer.column_section_renderer"
self._column_section_renderer = instantiate_class_from_config(
config=column_section_renderer,
runtime_environment={},
config_defaults={
"module_name": column_section_renderer.get("module_name", module_name)
},
)
if not self._column_section_renderer:
raise ClassInstantiationError(
module_name=module_name,
package_name=None,
class_name=column_section_renderer["class_name"],
)
self.run_info_at_end = run_info_at_end | [
"def",
"__init__",
"(",
"self",
",",
"column_section_renderer",
"=",
"None",
",",
"run_info_at_end",
":",
"bool",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"if",
"column_section_renderer",
"is",
"None",
":",
"column_section_renderer",
"=",
"{",
"\"class_name\"",
":",
"\"ValidationResultsColumnSectionRenderer\"",
"}",
"module_name",
"=",
"\"great_expectations.render.renderer.column_section_renderer\"",
"self",
".",
"_column_section_renderer",
"=",
"instantiate_class_from_config",
"(",
"config",
"=",
"column_section_renderer",
",",
"runtime_environment",
"=",
"{",
"}",
",",
"config_defaults",
"=",
"{",
"\"module_name\"",
":",
"column_section_renderer",
".",
"get",
"(",
"\"module_name\"",
",",
"module_name",
")",
"}",
",",
")",
"if",
"not",
"self",
".",
"_column_section_renderer",
":",
"raise",
"ClassInstantiationError",
"(",
"module_name",
"=",
"module_name",
",",
"package_name",
"=",
"None",
",",
"class_name",
"=",
"column_section_renderer",
"[",
"\"class_name\"",
"]",
",",
")",
"self",
".",
"run_info_at_end",
"=",
"run_info_at_end"
] | [
32,
4
] | [
58,
46
] | python | en | ['en', 'error', 'th'] | False |
ValidationResultsPageRenderer.render_validation_operator_result | (
self, validation_operator_result: ValidationOperatorResult
) |
Render a ValidationOperatorResult which can have multiple ExpectationSuiteValidationResult
Args:
validation_operator_result: ValidationOperatorResult
Returns:
List[RenderedDocumentContent]
|
Render a ValidationOperatorResult which can have multiple ExpectationSuiteValidationResult | def render_validation_operator_result(
self, validation_operator_result: ValidationOperatorResult
) -> List[RenderedDocumentContent]:
"""
Render a ValidationOperatorResult which can have multiple ExpectationSuiteValidationResult
Args:
validation_operator_result: ValidationOperatorResult
Returns:
List[RenderedDocumentContent]
"""
return [
self.render(validation_result)
for validation_result in validation_operator_result.list_validation_results()
] | [
"def",
"render_validation_operator_result",
"(",
"self",
",",
"validation_operator_result",
":",
"ValidationOperatorResult",
")",
"->",
"List",
"[",
"RenderedDocumentContent",
"]",
":",
"return",
"[",
"self",
".",
"render",
"(",
"validation_result",
")",
"for",
"validation_result",
"in",
"validation_operator_result",
".",
"list_validation_results",
"(",
")",
"]"
] | [
60,
4
] | [
75,
9
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilePathDataConnector.__init__ | (
self,
name: str,
datasource_name: str,
assets: dict,
execution_engine: Optional[ExecutionEngine] = None,
default_regex: Optional[dict] = None,
sorters: Optional[list] = None,
batch_spec_passthrough: Optional[dict] = None,
) |
Base class for DataConnectors that connect to filesystem-like data by taking in
configured `assets` as a dictionary. This class supports the configuration of default_regex and
sorters for filtering and sorting data_references.
Args:
name (str): name of ConfiguredAssetFilePathDataConnector
datasource_name (str): Name of datasource that this DataConnector is connected to
assets (dict): configured assets as a dictionary. These can each have their own regex and sorters
execution_engine (ExecutionEngine): Execution Engine object to actually read the data
default_regex (dict): Optional dict the filter and organize the data_references.
sorters (list): Optional list if you want to sort the data_references
batch_spec_passthrough (dict): dictionary with keys that will be added directly to batch_spec
|
Base class for DataConnectors that connect to filesystem-like data by taking in
configured `assets` as a dictionary. This class supports the configuration of default_regex and
sorters for filtering and sorting data_references. | def __init__(
self,
name: str,
datasource_name: str,
assets: dict,
execution_engine: Optional[ExecutionEngine] = None,
default_regex: Optional[dict] = None,
sorters: Optional[list] = None,
batch_spec_passthrough: Optional[dict] = None,
):
"""
Base class for DataConnectors that connect to filesystem-like data by taking in
configured `assets` as a dictionary. This class supports the configuration of default_regex and
sorters for filtering and sorting data_references.
Args:
name (str): name of ConfiguredAssetFilePathDataConnector
datasource_name (str): Name of datasource that this DataConnector is connected to
assets (dict): configured assets as a dictionary. These can each have their own regex and sorters
execution_engine (ExecutionEngine): Execution Engine object to actually read the data
default_regex (dict): Optional dict the filter and organize the data_references.
sorters (list): Optional list if you want to sort the data_references
batch_spec_passthrough (dict): dictionary with keys that will be added directly to batch_spec
"""
logger.debug(f'Constructing ConfiguredAssetFilePathDataConnector "{name}".')
super().__init__(
name=name,
datasource_name=datasource_name,
execution_engine=execution_engine,
default_regex=default_regex,
sorters=sorters,
batch_spec_passthrough=batch_spec_passthrough,
)
if assets is None:
assets = {}
_assets: Dict[str, Union[dict, Asset]] = assets
self._assets = _assets
self._build_assets_from_config(config=assets) | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"datasource_name",
":",
"str",
",",
"assets",
":",
"dict",
",",
"execution_engine",
":",
"Optional",
"[",
"ExecutionEngine",
"]",
"=",
"None",
",",
"default_regex",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"sorters",
":",
"Optional",
"[",
"list",
"]",
"=",
"None",
",",
"batch_spec_passthrough",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
")",
":",
"logger",
".",
"debug",
"(",
"f'Constructing ConfiguredAssetFilePathDataConnector \"{name}\".'",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
"=",
"name",
",",
"datasource_name",
"=",
"datasource_name",
",",
"execution_engine",
"=",
"execution_engine",
",",
"default_regex",
"=",
"default_regex",
",",
"sorters",
"=",
"sorters",
",",
"batch_spec_passthrough",
"=",
"batch_spec_passthrough",
",",
")",
"if",
"assets",
"is",
"None",
":",
"assets",
"=",
"{",
"}",
"_assets",
":",
"Dict",
"[",
"str",
",",
"Union",
"[",
"dict",
",",
"Asset",
"]",
"]",
"=",
"assets",
"self",
".",
"_assets",
"=",
"_assets",
"self",
".",
"_build_assets_from_config",
"(",
"config",
"=",
"assets",
")"
] | [
33,
4
] | [
71,
53
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilePathDataConnector.get_available_data_asset_names | (self) |
Return the list of asset names known by this DataConnector.
Returns:
A list of available names
|
Return the list of asset names known by this DataConnector. | def get_available_data_asset_names(self) -> List[str]:
"""
Return the list of asset names known by this DataConnector.
Returns:
A list of available names
"""
return list(self.assets.keys()) | [
"def",
"get_available_data_asset_names",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"list",
"(",
"self",
".",
"assets",
".",
"keys",
"(",
")",
")"
] | [
104,
4
] | [
111,
39
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilePathDataConnector._get_data_reference_list | (
self, data_asset_name: Optional[str] = None
) |
List objects in the underlying data store to create a list of data_references.
This method is used to refresh the cache.
|
List objects in the underlying data store to create a list of data_references.
This method is used to refresh the cache.
| def _get_data_reference_list(
self, data_asset_name: Optional[str] = None
) -> List[str]:
"""
List objects in the underlying data store to create a list of data_references.
This method is used to refresh the cache.
"""
asset: Optional[Asset] = self._get_asset(data_asset_name=data_asset_name)
path_list: List[str] = self._get_data_reference_list_for_asset(asset=asset)
return path_list | [
"def",
"_get_data_reference_list",
"(",
"self",
",",
"data_asset_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"asset",
":",
"Optional",
"[",
"Asset",
"]",
"=",
"self",
".",
"_get_asset",
"(",
"data_asset_name",
"=",
"data_asset_name",
")",
"path_list",
":",
"List",
"[",
"str",
"]",
"=",
"self",
".",
"_get_data_reference_list_for_asset",
"(",
"asset",
"=",
"asset",
")",
"return",
"path_list"
] | [
134,
4
] | [
143,
24
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilePathDataConnector.get_data_reference_list_count | (self) |
Returns the list of data_references known by this DataConnector by looping over all data_asset_names in
_data_references_cache
Returns:
number of data_references known by this DataConnector.
|
Returns the list of data_references known by this DataConnector by looping over all data_asset_names in
_data_references_cache | def get_data_reference_list_count(self) -> int:
"""
Returns the list of data_references known by this DataConnector by looping over all data_asset_names in
_data_references_cache
Returns:
number of data_references known by this DataConnector.
"""
total_references: int = sum(
[
len(self._data_references_cache[data_asset_name])
for data_asset_name in self._data_references_cache
]
)
return total_references | [
"def",
"get_data_reference_list_count",
"(",
"self",
")",
"->",
"int",
":",
"total_references",
":",
"int",
"=",
"sum",
"(",
"[",
"len",
"(",
"self",
".",
"_data_references_cache",
"[",
"data_asset_name",
"]",
")",
"for",
"data_asset_name",
"in",
"self",
".",
"_data_references_cache",
"]",
")",
"return",
"total_references"
] | [
145,
4
] | [
160,
31
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilePathDataConnector.get_unmatched_data_references | (self) |
Returns the list of data_references unmatched by configuration by looping through items in _data_references_cache
and returning data_reference that do not have an associated data_asset.
Returns:
list of data_references that are not matched by configuration.
|
Returns the list of data_references unmatched by configuration by looping through items in _data_references_cache
and returning data_reference that do not have an associated data_asset. | def get_unmatched_data_references(self) -> List[str]:
"""
Returns the list of data_references unmatched by configuration by looping through items in _data_references_cache
and returning data_reference that do not have an associated data_asset.
Returns:
list of data_references that are not matched by configuration.
"""
unmatched_data_references: List[str] = []
for (
data_asset_name,
data_reference_sub_cache,
) in self._data_references_cache.items():
unmatched_data_references += [
k for k, v in data_reference_sub_cache.items() if v is None
]
return unmatched_data_references | [
"def",
"get_unmatched_data_references",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"unmatched_data_references",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"for",
"(",
"data_asset_name",
",",
"data_reference_sub_cache",
",",
")",
"in",
"self",
".",
"_data_references_cache",
".",
"items",
"(",
")",
":",
"unmatched_data_references",
"+=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"data_reference_sub_cache",
".",
"items",
"(",
")",
"if",
"v",
"is",
"None",
"]",
"return",
"unmatched_data_references"
] | [
162,
4
] | [
179,
40
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredAssetFilePathDataConnector.build_batch_spec | (self, batch_definition: BatchDefinition) |
Build BatchSpec from batch_definition by calling DataConnector's build_batch_spec function.
Args:
batch_definition (BatchDefinition): to be used to build batch_spec
Returns:
BatchSpec built from batch_definition
|
Build BatchSpec from batch_definition by calling DataConnector's build_batch_spec function. | def build_batch_spec(self, batch_definition: BatchDefinition) -> PathBatchSpec:
"""
Build BatchSpec from batch_definition by calling DataConnector's build_batch_spec function.
Args:
batch_definition (BatchDefinition): to be used to build batch_spec
Returns:
BatchSpec built from batch_definition
"""
data_asset_name: str = batch_definition.data_asset_name
if (
data_asset_name in self.assets
and self.assets[data_asset_name].batch_spec_passthrough
and isinstance(self.assets[data_asset_name].batch_spec_passthrough, dict)
):
# batch_spec_passthrough from data_asset
batch_spec_passthrough = deepcopy(
self.assets[data_asset_name]["batch_spec_passthrough"]
)
batch_definition_batch_spec_passthrough = (
deepcopy(batch_definition.batch_spec_passthrough) or {}
)
# batch_spec_passthrough from Batch Definition supersedes batch_spec_passthrough from data_asset
batch_spec_passthrough.update(batch_definition_batch_spec_passthrough)
batch_definition.batch_spec_passthrough = batch_spec_passthrough
batch_spec: PathBatchSpec = super().build_batch_spec(
batch_definition=batch_definition
)
return batch_spec | [
"def",
"build_batch_spec",
"(",
"self",
",",
"batch_definition",
":",
"BatchDefinition",
")",
"->",
"PathBatchSpec",
":",
"data_asset_name",
":",
"str",
"=",
"batch_definition",
".",
"data_asset_name",
"if",
"(",
"data_asset_name",
"in",
"self",
".",
"assets",
"and",
"self",
".",
"assets",
"[",
"data_asset_name",
"]",
".",
"batch_spec_passthrough",
"and",
"isinstance",
"(",
"self",
".",
"assets",
"[",
"data_asset_name",
"]",
".",
"batch_spec_passthrough",
",",
"dict",
")",
")",
":",
"# batch_spec_passthrough from data_asset",
"batch_spec_passthrough",
"=",
"deepcopy",
"(",
"self",
".",
"assets",
"[",
"data_asset_name",
"]",
"[",
"\"batch_spec_passthrough\"",
"]",
")",
"batch_definition_batch_spec_passthrough",
"=",
"(",
"deepcopy",
"(",
"batch_definition",
".",
"batch_spec_passthrough",
")",
"or",
"{",
"}",
")",
"# batch_spec_passthrough from Batch Definition supersedes batch_spec_passthrough from data_asset",
"batch_spec_passthrough",
".",
"update",
"(",
"batch_definition_batch_spec_passthrough",
")",
"batch_definition",
".",
"batch_spec_passthrough",
"=",
"batch_spec_passthrough",
"batch_spec",
":",
"PathBatchSpec",
"=",
"super",
"(",
")",
".",
"build_batch_spec",
"(",
"batch_definition",
"=",
"batch_definition",
")",
"return",
"batch_spec"
] | [
227,
4
] | [
259,
25
] | python | en | ['en', 'error', 'th'] | False |
test_database_store_backend_id_initialization | (caplog, sa, test_backends) |
What does this test and why?
NOTE: This test only has one key column which may not mirror actual functionality
A StoreBackend should have a store_backend_id property. That store_backend_id should be read and initialized
from an existing persistent store_backend_id during instantiation, or a new store_backend_id should be generated
and persisted. The store_backend_id should be a valid UUIDv4
If a new store_backend_id cannot be persisted, use an ephemeral store_backend_id.
Persistence should be in a .ge_store_id file for for filesystem and blob-stores.
If an existing data_context_id is available in the great_expectations.yml, use this as the expectation_store id.
If a store_backend_id is provided via manually_initialize_store_backend_id, make sure it is retrievable.
Note: StoreBackend & TupleStoreBackend are abstract classes, so we will test the
concrete classes that inherit from them.
See also test_store_backends::test_StoreBackend_id_initialization
|
What does this test and why? | def test_database_store_backend_id_initialization(caplog, sa, test_backends):
"""
What does this test and why?
NOTE: This test only has one key column which may not mirror actual functionality
A StoreBackend should have a store_backend_id property. That store_backend_id should be read and initialized
from an existing persistent store_backend_id during instantiation, or a new store_backend_id should be generated
and persisted. The store_backend_id should be a valid UUIDv4
If a new store_backend_id cannot be persisted, use an ephemeral store_backend_id.
Persistence should be in a .ge_store_id file for for filesystem and blob-stores.
If an existing data_context_id is available in the great_expectations.yml, use this as the expectation_store id.
If a store_backend_id is provided via manually_initialize_store_backend_id, make sure it is retrievable.
Note: StoreBackend & TupleStoreBackend are abstract classes, so we will test the
concrete classes that inherit from them.
See also test_store_backends::test_StoreBackend_id_initialization
"""
if "postgresql" not in test_backends:
pytest.skip("test_database_store_backend_id_initialization requires postgresql")
store_backend = DatabaseStoreBackend(
credentials={
"drivername": "postgresql",
"username": "postgres",
"password": "",
"host": os.getenv("GE_TEST_LOCAL_DB_HOSTNAME", "localhost"),
"port": "5432",
"database": "test_ci",
},
table_name="test_database_store_backend_id_initialization",
key_columns=["k1", "k2", "k3"],
)
# Check that store_backend_id exists can be read
assert store_backend.store_backend_id is not None
# Check that store_backend_id is a valid UUID
assert test_utils.validate_uuid4(store_backend.store_backend_id)
# Test that expectations store can be created with specified store_backend_id
expectations_store_with_database_backend = instantiate_class_from_config(
config={
"class_name": "ExpectationsStore",
"store_backend": {
"class_name": "DatabaseStoreBackend",
"credentials": {
"drivername": "postgresql",
"username": "postgres",
"password": "",
"host": os.getenv("GE_TEST_LOCAL_DB_HOSTNAME", "localhost"),
"port": "5432",
"database": "test_ci",
},
"manually_initialize_store_backend_id": "00000000-0000-0000-0000-000000aaaaaa",
"table_name": "ge_expectations_store",
"key_columns": {"expectation_suite_name"},
},
# "name": "postgres_expectations_store",
},
runtime_environment=None,
config_defaults={
"module_name": "great_expectations.data_context.store",
"store_name": "postgres_expectations_store",
},
)
assert (
expectations_store_with_database_backend.store_backend_id
== "00000000-0000-0000-0000-000000aaaaaa"
) | [
"def",
"test_database_store_backend_id_initialization",
"(",
"caplog",
",",
"sa",
",",
"test_backends",
")",
":",
"if",
"\"postgresql\"",
"not",
"in",
"test_backends",
":",
"pytest",
".",
"skip",
"(",
"\"test_database_store_backend_id_initialization requires postgresql\"",
")",
"store_backend",
"=",
"DatabaseStoreBackend",
"(",
"credentials",
"=",
"{",
"\"drivername\"",
":",
"\"postgresql\"",
",",
"\"username\"",
":",
"\"postgres\"",
",",
"\"password\"",
":",
"\"\"",
",",
"\"host\"",
":",
"os",
".",
"getenv",
"(",
"\"GE_TEST_LOCAL_DB_HOSTNAME\"",
",",
"\"localhost\"",
")",
",",
"\"port\"",
":",
"\"5432\"",
",",
"\"database\"",
":",
"\"test_ci\"",
",",
"}",
",",
"table_name",
"=",
"\"test_database_store_backend_id_initialization\"",
",",
"key_columns",
"=",
"[",
"\"k1\"",
",",
"\"k2\"",
",",
"\"k3\"",
"]",
",",
")",
"# Check that store_backend_id exists can be read",
"assert",
"store_backend",
".",
"store_backend_id",
"is",
"not",
"None",
"# Check that store_backend_id is a valid UUID",
"assert",
"test_utils",
".",
"validate_uuid4",
"(",
"store_backend",
".",
"store_backend_id",
")",
"# Test that expectations store can be created with specified store_backend_id",
"expectations_store_with_database_backend",
"=",
"instantiate_class_from_config",
"(",
"config",
"=",
"{",
"\"class_name\"",
":",
"\"ExpectationsStore\"",
",",
"\"store_backend\"",
":",
"{",
"\"class_name\"",
":",
"\"DatabaseStoreBackend\"",
",",
"\"credentials\"",
":",
"{",
"\"drivername\"",
":",
"\"postgresql\"",
",",
"\"username\"",
":",
"\"postgres\"",
",",
"\"password\"",
":",
"\"\"",
",",
"\"host\"",
":",
"os",
".",
"getenv",
"(",
"\"GE_TEST_LOCAL_DB_HOSTNAME\"",
",",
"\"localhost\"",
")",
",",
"\"port\"",
":",
"\"5432\"",
",",
"\"database\"",
":",
"\"test_ci\"",
",",
"}",
",",
"\"manually_initialize_store_backend_id\"",
":",
"\"00000000-0000-0000-0000-000000aaaaaa\"",
",",
"\"table_name\"",
":",
"\"ge_expectations_store\"",
",",
"\"key_columns\"",
":",
"{",
"\"expectation_suite_name\"",
"}",
",",
"}",
",",
"# \"name\": \"postgres_expectations_store\",",
"}",
",",
"runtime_environment",
"=",
"None",
",",
"config_defaults",
"=",
"{",
"\"module_name\"",
":",
"\"great_expectations.data_context.store\"",
",",
"\"store_name\"",
":",
"\"postgres_expectations_store\"",
",",
"}",
",",
")",
"assert",
"(",
"expectations_store_with_database_backend",
".",
"store_backend_id",
"==",
"\"00000000-0000-0000-0000-000000aaaaaa\"",
")"
] | [
148,
0
] | [
219,
5
] | python | en | ['en', 'error', 'th'] | False |
S3GlobReaderBatchKwargsGenerator.__init__ | (
self,
name="default",
datasource=None,
bucket=None,
reader_options=None,
assets=None,
delimiter="/",
reader_method=None,
boto3_options=None,
max_keys=1000,
) | Initialize a new S3GlobReaderBatchKwargsGenerator
Args:
name: the name of the batch kwargs generator
datasource: the datasource to which it is attached
bucket: the name of the s3 bucket from which it generates batch_kwargs
reader_options: options passed to the datasource reader method
assets: asset configuration (see class docstring for more information)
delimiter: the BUCKET KEY delimiter
reader_method: the reader_method to include in generated batch_kwargs
boto3_options: dictionary of key-value pairs to use when creating boto3 client or resource objects
max_keys: the maximum number of keys to fetch in a single list_objects request to s3
| Initialize a new S3GlobReaderBatchKwargsGenerator | def __init__(
self,
name="default",
datasource=None,
bucket=None,
reader_options=None,
assets=None,
delimiter="/",
reader_method=None,
boto3_options=None,
max_keys=1000,
):
"""Initialize a new S3GlobReaderBatchKwargsGenerator
Args:
name: the name of the batch kwargs generator
datasource: the datasource to which it is attached
bucket: the name of the s3 bucket from which it generates batch_kwargs
reader_options: options passed to the datasource reader method
assets: asset configuration (see class docstring for more information)
delimiter: the BUCKET KEY delimiter
reader_method: the reader_method to include in generated batch_kwargs
boto3_options: dictionary of key-value pairs to use when creating boto3 client or resource objects
max_keys: the maximum number of keys to fetch in a single list_objects request to s3
"""
super().__init__(name, datasource=datasource)
if reader_options is None:
reader_options = {}
if assets is None:
assets = {"default": {"prefix": "", "regex_filter": ".*"}}
self._bucket = bucket
self._reader_method = reader_method
self._reader_options = reader_options
self._assets = assets
self._delimiter = delimiter
if boto3_options is None:
boto3_options = {}
self._max_keys = max_keys
self._iterators = {}
try:
self._s3 = boto3.client("s3", **boto3_options)
except TypeError:
raise (
ImportError(
"Unable to load boto3, which is required for S3 batch kwargs generator"
)
) | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"\"default\"",
",",
"datasource",
"=",
"None",
",",
"bucket",
"=",
"None",
",",
"reader_options",
"=",
"None",
",",
"assets",
"=",
"None",
",",
"delimiter",
"=",
"\"/\"",
",",
"reader_method",
"=",
"None",
",",
"boto3_options",
"=",
"None",
",",
"max_keys",
"=",
"1000",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
",",
"datasource",
"=",
"datasource",
")",
"if",
"reader_options",
"is",
"None",
":",
"reader_options",
"=",
"{",
"}",
"if",
"assets",
"is",
"None",
":",
"assets",
"=",
"{",
"\"default\"",
":",
"{",
"\"prefix\"",
":",
"\"\"",
",",
"\"regex_filter\"",
":",
"\".*\"",
"}",
"}",
"self",
".",
"_bucket",
"=",
"bucket",
"self",
".",
"_reader_method",
"=",
"reader_method",
"self",
".",
"_reader_options",
"=",
"reader_options",
"self",
".",
"_assets",
"=",
"assets",
"self",
".",
"_delimiter",
"=",
"delimiter",
"if",
"boto3_options",
"is",
"None",
":",
"boto3_options",
"=",
"{",
"}",
"self",
".",
"_max_keys",
"=",
"max_keys",
"self",
".",
"_iterators",
"=",
"{",
"}",
"try",
":",
"self",
".",
"_s3",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
",",
"*",
"*",
"boto3_options",
")",
"except",
"TypeError",
":",
"raise",
"(",
"ImportError",
"(",
"\"Unable to load boto3, which is required for S3 batch kwargs generator\"",
")",
")"
] | [
62,
4
] | [
110,
13
] | python | en | ['en', 'pl', 'en'] | True |
get_tweet | (tweet_id) | Looks up data for a single tweet. | Looks up data for a single tweet. | def get_tweet(tweet_id):
"""Looks up data for a single tweet."""
twitter = Twitter(logs_to_cloud=False)
return twitter.get_tweet(tweet_id) | [
"def",
"get_tweet",
"(",
"tweet_id",
")",
":",
"twitter",
"=",
"Twitter",
"(",
"logs_to_cloud",
"=",
"False",
")",
"return",
"twitter",
".",
"get_tweet",
"(",
"tweet_id",
")"
] | [
14,
0
] | [
18,
38
] | python | en | ['en', 'en', 'en'] | True |
get_tweet_text | (tweet_id) | Looks up the text for a single tweet. | Looks up the text for a single tweet. | def get_tweet_text(tweet_id):
"""Looks up the text for a single tweet."""
tweet = get_tweet(tweet_id)
analysis = Analysis(logs_to_cloud=False)
return analysis.get_expanded_text(tweet) | [
"def",
"get_tweet_text",
"(",
"tweet_id",
")",
":",
"tweet",
"=",
"get_tweet",
"(",
"tweet_id",
")",
"analysis",
"=",
"Analysis",
"(",
"logs_to_cloud",
"=",
"False",
")",
"return",
"analysis",
".",
"get_expanded_text",
"(",
"tweet",
")"
] | [
21,
0
] | [
26,
44
] | python | en | ['en', 'en', 'en'] | True |
BaseDatasource.__init__ | (
self,
name: str,
execution_engine=None,
data_context_root_directory: Optional[str] = None,
) |
Build a new Datasource.
Args:
name: the name for the datasource
execution_engine (ClassConfig): the type of compute engine to produce
data_context_root_directory: Installation directory path (if installed on a filesystem).
|
Build a new Datasource. | def __init__(
self,
name: str,
execution_engine=None,
data_context_root_directory: Optional[str] = None,
):
"""
Build a new Datasource.
Args:
name: the name for the datasource
execution_engine (ClassConfig): the type of compute engine to produce
data_context_root_directory: Installation directory path (if installed on a filesystem).
"""
self._name = name
self._data_context_root_directory = data_context_root_directory
try:
self._execution_engine = instantiate_class_from_config(
config=execution_engine,
runtime_environment={},
config_defaults={"module_name": "great_expectations.execution_engine"},
)
self._datasource_config = {
"execution_engine": execution_engine,
}
except Exception as e:
raise ge_exceptions.ExecutionEngineError(message=str(e))
self._data_connectors = {} | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"execution_engine",
"=",
"None",
",",
"data_context_root_directory",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_data_context_root_directory",
"=",
"data_context_root_directory",
"try",
":",
"self",
".",
"_execution_engine",
"=",
"instantiate_class_from_config",
"(",
"config",
"=",
"execution_engine",
",",
"runtime_environment",
"=",
"{",
"}",
",",
"config_defaults",
"=",
"{",
"\"module_name\"",
":",
"\"great_expectations.execution_engine\"",
"}",
",",
")",
"self",
".",
"_datasource_config",
"=",
"{",
"\"execution_engine\"",
":",
"execution_engine",
",",
"}",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ge_exceptions",
".",
"ExecutionEngineError",
"(",
"message",
"=",
"str",
"(",
"e",
")",
")",
"self",
".",
"_data_connectors",
"=",
"{",
"}"
] | [
27,
4
] | [
57,
34
] | python | en | ['en', 'error', 'th'] | False |
BaseDatasource.get_batch_from_batch_definition | (
self,
batch_definition: BatchDefinition,
batch_data: Any = None,
) |
Note: this method should *not* be used when getting a Batch from a BatchRequest, since it does not capture BatchRequest metadata.
|
Note: this method should *not* be used when getting a Batch from a BatchRequest, since it does not capture BatchRequest metadata.
| def get_batch_from_batch_definition(
self,
batch_definition: BatchDefinition,
batch_data: Any = None,
) -> Batch:
"""
Note: this method should *not* be used when getting a Batch from a BatchRequest, since it does not capture BatchRequest metadata.
"""
if not isinstance(batch_data, type(None)):
# TODO: <Alex>Abe: Are the comments below still pertinent? Or can they be deleted?</Alex>
# NOTE Abe 20201014: Maybe do more careful type checking here?
# Seems like we should verify that batch_data is compatible with the execution_engine...?
batch_spec, batch_markers = None, None
else:
data_connector: DataConnector = self.data_connectors[
batch_definition.data_connector_name
]
(
batch_data,
batch_spec,
batch_markers,
) = data_connector.get_batch_data_and_metadata(
batch_definition=batch_definition
)
new_batch: Batch = Batch(
data=batch_data,
batch_request=None,
batch_definition=batch_definition,
batch_spec=batch_spec,
batch_markers=batch_markers,
)
return new_batch | [
"def",
"get_batch_from_batch_definition",
"(",
"self",
",",
"batch_definition",
":",
"BatchDefinition",
",",
"batch_data",
":",
"Any",
"=",
"None",
",",
")",
"->",
"Batch",
":",
"if",
"not",
"isinstance",
"(",
"batch_data",
",",
"type",
"(",
"None",
")",
")",
":",
"# TODO: <Alex>Abe: Are the comments below still pertinent? Or can they be deleted?</Alex>",
"# NOTE Abe 20201014: Maybe do more careful type checking here?",
"# Seems like we should verify that batch_data is compatible with the execution_engine...?",
"batch_spec",
",",
"batch_markers",
"=",
"None",
",",
"None",
"else",
":",
"data_connector",
":",
"DataConnector",
"=",
"self",
".",
"data_connectors",
"[",
"batch_definition",
".",
"data_connector_name",
"]",
"(",
"batch_data",
",",
"batch_spec",
",",
"batch_markers",
",",
")",
"=",
"data_connector",
".",
"get_batch_data_and_metadata",
"(",
"batch_definition",
"=",
"batch_definition",
")",
"new_batch",
":",
"Batch",
"=",
"Batch",
"(",
"data",
"=",
"batch_data",
",",
"batch_request",
"=",
"None",
",",
"batch_definition",
"=",
"batch_definition",
",",
"batch_spec",
"=",
"batch_spec",
",",
"batch_markers",
"=",
"batch_markers",
",",
")",
"return",
"new_batch"
] | [
59,
4
] | [
90,
24
] | python | en | ['en', 'error', 'th'] | False |
BaseDatasource.get_batch_definition_list_from_batch_request | (
self, batch_request: BatchRequest
) |
Validates batch request and utilizes the classes'
Data Connectors' property to get a list of batch definition given
a batch request
Args:
:param batch_request: A BatchRequest object used to request a batch
:return: A list of batch definitions
|
Validates batch request and utilizes the classes'
Data Connectors' property to get a list of batch definition given
a batch request
Args:
:param batch_request: A BatchRequest object used to request a batch
:return: A list of batch definitions
| def get_batch_definition_list_from_batch_request(
self, batch_request: BatchRequest
) -> List[BatchDefinition]:
"""
Validates batch request and utilizes the classes'
Data Connectors' property to get a list of batch definition given
a batch request
Args:
:param batch_request: A BatchRequest object used to request a batch
:return: A list of batch definitions
"""
self._validate_batch_request(batch_request=batch_request)
data_connector: DataConnector = self.data_connectors[
batch_request.data_connector_name
]
return data_connector.get_batch_definition_list_from_batch_request(
batch_request=batch_request
) | [
"def",
"get_batch_definition_list_from_batch_request",
"(",
"self",
",",
"batch_request",
":",
"BatchRequest",
")",
"->",
"List",
"[",
"BatchDefinition",
"]",
":",
"self",
".",
"_validate_batch_request",
"(",
"batch_request",
"=",
"batch_request",
")",
"data_connector",
":",
"DataConnector",
"=",
"self",
".",
"data_connectors",
"[",
"batch_request",
".",
"data_connector_name",
"]",
"return",
"data_connector",
".",
"get_batch_definition_list_from_batch_request",
"(",
"batch_request",
"=",
"batch_request",
")"
] | [
100,
4
] | [
118,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseDatasource.get_batch_list_from_batch_request | (
self, batch_request: Union[BatchRequest, RuntimeBatchRequest]
) |
Processes batch_request and returns the (possibly empty) list of batch objects.
Args:
:batch_request encapsulation of request parameters necessary to identify the (possibly multiple) batches
:returns possibly empty list of batch objects; each batch object contains a dataset and associated metatada
|
Processes batch_request and returns the (possibly empty) list of batch objects. | def get_batch_list_from_batch_request(
self, batch_request: Union[BatchRequest, RuntimeBatchRequest]
) -> List[Batch]:
"""
Processes batch_request and returns the (possibly empty) list of batch objects.
Args:
:batch_request encapsulation of request parameters necessary to identify the (possibly multiple) batches
:returns possibly empty list of batch objects; each batch object contains a dataset and associated metatada
"""
self._validate_batch_request(batch_request=batch_request)
data_connector: DataConnector = self.data_connectors[
batch_request.data_connector_name
]
batch_definition_list: List[
BatchDefinition
] = data_connector.get_batch_definition_list_from_batch_request(
batch_request=batch_request
)
if isinstance(batch_request, RuntimeBatchRequest):
# This is a runtime batch_request
if len(batch_definition_list) != 1:
raise ValueError(
"RuntimeBatchRequests must specify exactly one corresponding BatchDefinition"
)
batch_definition = batch_definition_list[0]
runtime_parameters = batch_request.runtime_parameters
# noinspection PyArgumentList
(
batch_data,
batch_spec,
batch_markers,
) = data_connector.get_batch_data_and_metadata(
batch_definition=batch_definition,
runtime_parameters=runtime_parameters,
)
new_batch: Batch = Batch(
data=batch_data,
batch_request=batch_request,
batch_definition=batch_definition,
batch_spec=batch_spec,
batch_markers=batch_markers,
)
return [new_batch]
else:
batches: List[Batch] = []
for batch_definition in batch_definition_list:
batch_definition.batch_spec_passthrough = (
batch_request.batch_spec_passthrough
)
batch_data: Any
batch_spec: PathBatchSpec
batch_markers: BatchMarkers
(
batch_data,
batch_spec,
batch_markers,
) = data_connector.get_batch_data_and_metadata(
batch_definition=batch_definition
)
new_batch: Batch = Batch(
data=batch_data,
batch_request=batch_request,
batch_definition=batch_definition,
batch_spec=batch_spec,
batch_markers=batch_markers,
)
batches.append(new_batch)
return batches | [
"def",
"get_batch_list_from_batch_request",
"(",
"self",
",",
"batch_request",
":",
"Union",
"[",
"BatchRequest",
",",
"RuntimeBatchRequest",
"]",
")",
"->",
"List",
"[",
"Batch",
"]",
":",
"self",
".",
"_validate_batch_request",
"(",
"batch_request",
"=",
"batch_request",
")",
"data_connector",
":",
"DataConnector",
"=",
"self",
".",
"data_connectors",
"[",
"batch_request",
".",
"data_connector_name",
"]",
"batch_definition_list",
":",
"List",
"[",
"BatchDefinition",
"]",
"=",
"data_connector",
".",
"get_batch_definition_list_from_batch_request",
"(",
"batch_request",
"=",
"batch_request",
")",
"if",
"isinstance",
"(",
"batch_request",
",",
"RuntimeBatchRequest",
")",
":",
"# This is a runtime batch_request",
"if",
"len",
"(",
"batch_definition_list",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"RuntimeBatchRequests must specify exactly one corresponding BatchDefinition\"",
")",
"batch_definition",
"=",
"batch_definition_list",
"[",
"0",
"]",
"runtime_parameters",
"=",
"batch_request",
".",
"runtime_parameters",
"# noinspection PyArgumentList",
"(",
"batch_data",
",",
"batch_spec",
",",
"batch_markers",
",",
")",
"=",
"data_connector",
".",
"get_batch_data_and_metadata",
"(",
"batch_definition",
"=",
"batch_definition",
",",
"runtime_parameters",
"=",
"runtime_parameters",
",",
")",
"new_batch",
":",
"Batch",
"=",
"Batch",
"(",
"data",
"=",
"batch_data",
",",
"batch_request",
"=",
"batch_request",
",",
"batch_definition",
"=",
"batch_definition",
",",
"batch_spec",
"=",
"batch_spec",
",",
"batch_markers",
"=",
"batch_markers",
",",
")",
"return",
"[",
"new_batch",
"]",
"else",
":",
"batches",
":",
"List",
"[",
"Batch",
"]",
"=",
"[",
"]",
"for",
"batch_definition",
"in",
"batch_definition_list",
":",
"batch_definition",
".",
"batch_spec_passthrough",
"=",
"(",
"batch_request",
".",
"batch_spec_passthrough",
")",
"batch_data",
":",
"Any",
"batch_spec",
":",
"PathBatchSpec",
"batch_markers",
":",
"BatchMarkers",
"(",
"batch_data",
",",
"batch_spec",
",",
"batch_markers",
",",
")",
"=",
"data_connector",
".",
"get_batch_data_and_metadata",
"(",
"batch_definition",
"=",
"batch_definition",
")",
"new_batch",
":",
"Batch",
"=",
"Batch",
"(",
"data",
"=",
"batch_data",
",",
"batch_request",
"=",
"batch_request",
",",
"batch_definition",
"=",
"batch_definition",
",",
"batch_spec",
"=",
"batch_spec",
",",
"batch_markers",
"=",
"batch_markers",
",",
")",
"batches",
".",
"append",
"(",
"new_batch",
")",
"return",
"batches"
] | [
120,
4
] | [
196,
26
] | python | en | ['en', 'error', 'th'] | False |
BaseDatasource._build_data_connector_from_config | (
self,
name: str,
config: Dict[str, Any],
) | Build a DataConnector using the provided configuration and return the newly-built DataConnector. | Build a DataConnector using the provided configuration and return the newly-built DataConnector. | def _build_data_connector_from_config(
self,
name: str,
config: Dict[str, Any],
) -> DataConnector:
"""Build a DataConnector using the provided configuration and return the newly-built DataConnector."""
new_data_connector: DataConnector = instantiate_class_from_config(
config=config,
runtime_environment={
"name": name,
"datasource_name": self.name,
"execution_engine": self.execution_engine,
},
config_defaults={
"module_name": "great_expectations.datasource.data_connector"
},
)
new_data_connector.data_context_root_directory = (
self._data_context_root_directory
)
self.data_connectors[name] = new_data_connector
return new_data_connector | [
"def",
"_build_data_connector_from_config",
"(",
"self",
",",
"name",
":",
"str",
",",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
")",
"->",
"DataConnector",
":",
"new_data_connector",
":",
"DataConnector",
"=",
"instantiate_class_from_config",
"(",
"config",
"=",
"config",
",",
"runtime_environment",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"datasource_name\"",
":",
"self",
".",
"name",
",",
"\"execution_engine\"",
":",
"self",
".",
"execution_engine",
",",
"}",
",",
"config_defaults",
"=",
"{",
"\"module_name\"",
":",
"\"great_expectations.datasource.data_connector\"",
"}",
",",
")",
"new_data_connector",
".",
"data_context_root_directory",
"=",
"(",
"self",
".",
"_data_context_root_directory",
")",
"self",
".",
"data_connectors",
"[",
"name",
"]",
"=",
"new_data_connector",
"return",
"new_data_connector"
] | [
198,
4
] | [
220,
33
] | python | en | ['en', 'en', 'en'] | True |
BaseDatasource.get_available_data_asset_names | (
self, data_connector_names: Optional[Union[list, str]] = None
) |
Returns a dictionary of data_asset_names that the specified data
connector can provide. Note that some data_connectors may not be
capable of describing specific named data assets, and some (such as
inferred_asset_data_connector) require the user to configure
data asset names.
Args:
data_connector_names: the DataConnector for which to get available data asset names.
Returns:
dictionary consisting of sets of data assets available for the specified data connectors:
::
{
data_connector_name: {
names: [ (data_asset_1, data_asset_1_type), (data_asset_2, data_asset_2_type) ... ]
}
...
}
|
Returns a dictionary of data_asset_names that the specified data
connector can provide. Note that some data_connectors may not be
capable of describing specific named data assets, and some (such as
inferred_asset_data_connector) require the user to configure
data asset names. | def get_available_data_asset_names(
self, data_connector_names: Optional[Union[list, str]] = None
) -> Dict[str, List[str]]:
"""
Returns a dictionary of data_asset_names that the specified data
connector can provide. Note that some data_connectors may not be
capable of describing specific named data assets, and some (such as
inferred_asset_data_connector) require the user to configure
data asset names.
Args:
data_connector_names: the DataConnector for which to get available data asset names.
Returns:
dictionary consisting of sets of data assets available for the specified data connectors:
::
{
data_connector_name: {
names: [ (data_asset_1, data_asset_1_type), (data_asset_2, data_asset_2_type) ... ]
}
...
}
"""
available_data_asset_names: dict = {}
if data_connector_names is None:
data_connector_names = self.data_connectors.keys()
elif isinstance(data_connector_names, str):
data_connector_names = [data_connector_names]
for data_connector_name in data_connector_names:
data_connector: DataConnector = self.data_connectors[data_connector_name]
available_data_asset_names[
data_connector_name
] = data_connector.get_available_data_asset_names()
return available_data_asset_names | [
"def",
"get_available_data_asset_names",
"(",
"self",
",",
"data_connector_names",
":",
"Optional",
"[",
"Union",
"[",
"list",
",",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"available_data_asset_names",
":",
"dict",
"=",
"{",
"}",
"if",
"data_connector_names",
"is",
"None",
":",
"data_connector_names",
"=",
"self",
".",
"data_connectors",
".",
"keys",
"(",
")",
"elif",
"isinstance",
"(",
"data_connector_names",
",",
"str",
")",
":",
"data_connector_names",
"=",
"[",
"data_connector_names",
"]",
"for",
"data_connector_name",
"in",
"data_connector_names",
":",
"data_connector",
":",
"DataConnector",
"=",
"self",
".",
"data_connectors",
"[",
"data_connector_name",
"]",
"available_data_asset_names",
"[",
"data_connector_name",
"]",
"=",
"data_connector",
".",
"get_available_data_asset_names",
"(",
")",
"return",
"available_data_asset_names"
] | [
222,
4
] | [
258,
41
] | python | en | ['en', 'error', 'th'] | False |
BaseDatasource.name | (self) |
Property for datasource name
|
Property for datasource name
| def name(self) -> str:
"""
Property for datasource name
"""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
323,
4
] | [
327,
25
] | python | en | ['en', 'error', 'th'] | False |
Datasource.__init__ | (
self,
name: str,
execution_engine=None,
data_connectors=None,
data_context_root_directory: Optional[str] = None,
) |
Build a new Datasource with data connectors.
Args:
name: the name for the datasource
execution_engine (ClassConfig): the type of compute engine to produce
data_connectors: DataConnectors to add to the datasource
data_context_root_directory: Installation directory path (if installed on a filesystem).
|
Build a new Datasource with data connectors. | def __init__(
self,
name: str,
execution_engine=None,
data_connectors=None,
data_context_root_directory: Optional[str] = None,
):
"""
Build a new Datasource with data connectors.
Args:
name: the name for the datasource
execution_engine (ClassConfig): the type of compute engine to produce
data_connectors: DataConnectors to add to the datasource
data_context_root_directory: Installation directory path (if installed on a filesystem).
"""
self._name = name
super().__init__(
name=name,
execution_engine=execution_engine,
data_context_root_directory=data_context_root_directory,
)
if data_connectors is None:
data_connectors = {}
self._data_connectors = data_connectors
self._datasource_config.update(
{"data_connectors": copy.deepcopy(data_connectors)}
)
self._init_data_connectors(data_connector_configs=data_connectors) | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"execution_engine",
"=",
"None",
",",
"data_connectors",
"=",
"None",
",",
"data_context_root_directory",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
":",
"self",
".",
"_name",
"=",
"name",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
"=",
"name",
",",
"execution_engine",
"=",
"execution_engine",
",",
"data_context_root_directory",
"=",
"data_context_root_directory",
",",
")",
"if",
"data_connectors",
"is",
"None",
":",
"data_connectors",
"=",
"{",
"}",
"self",
".",
"_data_connectors",
"=",
"data_connectors",
"self",
".",
"_datasource_config",
".",
"update",
"(",
"{",
"\"data_connectors\"",
":",
"copy",
".",
"deepcopy",
"(",
"data_connectors",
")",
"}",
")",
"self",
".",
"_init_data_connectors",
"(",
"data_connector_configs",
"=",
"data_connectors",
")"
] | [
349,
4
] | [
379,
74
] | python | en | ['en', 'error', 'th'] | False |
ExpectColumnProportionOfUniqueValuesToBeBetween.validate_configuration | (self, configuration: Optional[ExpectationConfiguration]) |
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
True if the configuration has been validated successfully. Otherwise, raises an exception
|
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation. | def validate_configuration(self, configuration: Optional[ExpectationConfiguration]):
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
True if the configuration has been validated successfully. Otherwise, raises an exception
"""
super().validate_configuration(configuration)
self.validate_metric_value_between_configuration(configuration=configuration) | [
"def",
"validate_configuration",
"(",
"self",
",",
"configuration",
":",
"Optional",
"[",
"ExpectationConfiguration",
"]",
")",
":",
"super",
"(",
")",
".",
"validate_configuration",
"(",
"configuration",
")",
"self",
".",
"validate_metric_value_between_configuration",
"(",
"configuration",
"=",
"configuration",
")"
] | [
108,
4
] | [
120,
85
] | python | en | ['en', 'error', 'th'] | False |
reset_downloads_folder | () | Clears the downloads folder.
If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. | Clears the downloads folder.
If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. | def reset_downloads_folder():
''' Clears the downloads folder.
If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. '''
if os.path.exists(downloads_path) and not os.listdir(downloads_path) == []:
archived_downloads_folder = os.path.join(downloads_path, '..',
ARCHIVE_DIR)
reset_downloads_folder_assistant(archived_downloads_folder) | [
"def",
"reset_downloads_folder",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"downloads_path",
")",
"and",
"not",
"os",
".",
"listdir",
"(",
"downloads_path",
")",
"==",
"[",
"]",
":",
"archived_downloads_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"downloads_path",
",",
"'..'",
",",
"ARCHIVE_DIR",
")",
"reset_downloads_folder_assistant",
"(",
"archived_downloads_folder",
")"
] | [
21,
0
] | [
27,
67
] | python | en | ['en', 'en', 'en'] | True |
is_element_present | (driver, selector, by=By.CSS_SELECTOR) |
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
@Returns
Boolean (is element present)
|
Returns whether the specified element selector is present on the page.
| def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
@Returns
Boolean (is element present)
"""
try:
driver.find_element(by=by, value=selector)
return True
except Exception:
return False | [
"def",
"is_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"try",
":",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"True",
"except",
"Exception",
":",
"return",
"False"
] | [
41,
0
] | [
55,
20
] | python | en | ['en', 'error', 'th'] | False |
is_element_visible | (driver, selector, by=By.CSS_SELECTOR) |
Returns whether the specified element selector is visible on the page.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
@Returns
Boolean (is element visible)
|
Returns whether the specified element selector is visible on the page.
| def is_element_visible(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is visible on the page.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
@Returns
Boolean (is element visible)
"""
try:
element = driver.find_element(by=by, value=selector)
return element.is_displayed()
except Exception:
return False | [
"def",
"is_element_visible",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"element",
".",
"is_displayed",
"(",
")",
"except",
"Exception",
":",
"return",
"False"
] | [
58,
0
] | [
72,
20
] | python | en | ['en', 'error', 'th'] | False |
is_text_visible | (driver, text, selector, by=By.CSS_SELECTOR) |
Returns whether the specified text is visible in the specified selector.
@Params
driver - the webdriver object (required)
text - the text string to search for
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
@Returns
Boolean (is text visible)
|
Returns whether the specified text is visible in the specified selector.
| def is_text_visible(driver, text, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified text is visible in the specified selector.
@Params
driver - the webdriver object (required)
text - the text string to search for
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
@Returns
Boolean (is text visible)
"""
try:
element = driver.find_element(by=by, value=selector)
return element.is_displayed() and text in element.text
except Exception:
return False | [
"def",
"is_text_visible",
"(",
"driver",
",",
"text",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"element",
".",
"is_displayed",
"(",
")",
"and",
"text",
"in",
"element",
".",
"text",
"except",
"Exception",
":",
"return",
"False"
] | [
75,
0
] | [
90,
20
] | python | en | ['en', 'error', 'th'] | False |
hover_on_element | (driver, selector, by=By.CSS_SELECTOR) |
Fires the hover event for the specified element by the given selector.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
|
Fires the hover event for the specified element by the given selector.
| def hover_on_element(driver, selector, by=By.CSS_SELECTOR):
"""
Fires the hover event for the specified element by the given selector.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
"""
element = driver.find_element(by=by, value=selector)
hover = ActionChains(driver).move_to_element(element)
hover.perform() | [
"def",
"hover_on_element",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"hover",
"=",
"ActionChains",
"(",
"driver",
")",
".",
"move_to_element",
"(",
"element",
")",
"hover",
".",
"perform",
"(",
")"
] | [
93,
0
] | [
103,
19
] | python | en | ['en', 'error', 'th'] | False |
hover_element | (driver, element) |
Similar to hover_on_element(), but uses found element, not a selector.
|
Similar to hover_on_element(), but uses found element, not a selector.
| def hover_element(driver, element):
"""
Similar to hover_on_element(), but uses found element, not a selector.
"""
hover = ActionChains(driver).move_to_element(element)
hover.perform() | [
"def",
"hover_element",
"(",
"driver",
",",
"element",
")",
":",
"hover",
"=",
"ActionChains",
"(",
"driver",
")",
".",
"move_to_element",
"(",
"element",
")",
"hover",
".",
"perform",
"(",
")"
] | [
106,
0
] | [
111,
19
] | python | en | ['en', 'error', 'th'] | False |
hover_and_click | (driver, hover_selector, click_selector,
hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT) |
Fires the hover event for a specified element by a given selector, then
clicks on another element specified. Useful for dropdown hover based menus.
@Params
driver - the webdriver object (required)
hover_selector - the css selector to hover over (required)
click_selector - the css selector to click on (required)
hover_by - the hover selector type to search by (Default: By.CSS_SELECTOR)
click_by - the click selector type to search by (Default: By.CSS_SELECTOR)
timeout - number of seconds to wait for click element to appear after hover
|
Fires the hover event for a specified element by a given selector, then
clicks on another element specified. Useful for dropdown hover based menus.
| def hover_and_click(driver, hover_selector, click_selector,
hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
"""
Fires the hover event for a specified element by a given selector, then
clicks on another element specified. Useful for dropdown hover based menus.
@Params
driver - the webdriver object (required)
hover_selector - the css selector to hover over (required)
click_selector - the css selector to click on (required)
hover_by - the hover selector type to search by (Default: By.CSS_SELECTOR)
click_by - the click selector type to search by (Default: By.CSS_SELECTOR)
timeout - number of seconds to wait for click element to appear after hover
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
element = driver.find_element(by=hover_by, value=hover_selector)
hover = ActionChains(driver).move_to_element(element)
for x in range(int(timeout * 10)):
try:
hover.perform()
element = driver.find_element(by=click_by, value=click_selector)
element.click()
return element
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
message = (
"Element {%s} was not present after %s second%s!"
"" % (click_selector, timeout, plural))
timeout_exception(NoSuchElementException, message) | [
"def",
"hover_and_click",
"(",
"driver",
",",
"hover_selector",
",",
"click_selector",
",",
"hover_by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"click_by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"hover_by",
",",
"value",
"=",
"hover_selector",
")",
"hover",
"=",
"ActionChains",
"(",
"driver",
")",
".",
"move_to_element",
"(",
"element",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"try",
":",
"hover",
".",
"perform",
"(",
")",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"click_by",
",",
"value",
"=",
"click_selector",
")",
"element",
".",
"click",
"(",
")",
"return",
"element",
"except",
"Exception",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Element {%s} was not present after %s second%s!\"",
"\"\"",
"%",
"(",
"click_selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"NoSuchElementException",
",",
"message",
")"
] | [
119,
0
] | [
154,
54
] | python | en | ['en', 'error', 'th'] | False |
hover_element_and_click | (driver, element, click_selector,
click_by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT) |
Similar to hover_and_click(), but assumes top element is already found.
|
Similar to hover_and_click(), but assumes top element is already found.
| def hover_element_and_click(driver, element, click_selector,
click_by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
"""
Similar to hover_and_click(), but assumes top element is already found.
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
hover = ActionChains(driver).move_to_element(element)
for x in range(int(timeout * 10)):
try:
hover.perform()
element = driver.find_element(by=click_by, value=click_selector)
element.click()
return element
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
message = (
"Element {%s} was not present after %s second%s!"
"" % (click_selector, timeout, plural))
timeout_exception(NoSuchElementException, message) | [
"def",
"hover_element_and_click",
"(",
"driver",
",",
"element",
",",
"click_selector",
",",
"click_by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"hover",
"=",
"ActionChains",
"(",
"driver",
")",
".",
"move_to_element",
"(",
"element",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"try",
":",
"hover",
".",
"perform",
"(",
")",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"click_by",
",",
"value",
"=",
"click_selector",
")",
"element",
".",
"click",
"(",
")",
"return",
"element",
"except",
"Exception",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Element {%s} was not present after %s second%s!\"",
"\"\"",
"%",
"(",
"click_selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"NoSuchElementException",
",",
"message",
")"
] | [
157,
0
] | [
183,
54
] | python | en | ['en', 'error', 'th'] | False |
wait_for_element_present | (driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the specified element by the given selector. Returns the
element object if the element is present on the page. The element can be
invisible. Raises an exception if the element does not appear in the
specified timeout.
@Params
driver - the webdriver object
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object
|
Searches for the specified element by the given selector. Returns the
element object if the element is present on the page. The element can be
invisible. Raises an exception if the element does not appear in the
specified timeout.
| def wait_for_element_present(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector. Returns the
element object if the element is present on the page. The element can be
invisible. Raises an exception if the element does not appear in the
specified timeout.
@Params
driver - the webdriver object
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object
"""
element = None
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
element = driver.find_element(by=by, value=selector)
return element
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
if not element:
message = (
"Element {%s} was not present after %s second%s!"
"" % (selector, timeout, plural))
timeout_exception(NoSuchElementException, message) | [
"def",
"wait_for_element_present",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"element",
"=",
"None",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"element",
"except",
"Exception",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"if",
"not",
"element",
":",
"message",
"=",
"(",
"\"Element {%s} was not present after %s second%s!\"",
"\"\"",
"%",
"(",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"NoSuchElementException",
",",
"message",
")"
] | [
215,
0
] | [
250,
58
] | python | en | ['en', 'error', 'th'] | False |
wait_for_element_visible | (driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the specified element by the given selector. Returns the
element object if the element is present and visible on the page.
Raises an exception if the element does not appear in the
specified timeout.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object
|
Searches for the specified element by the given selector. Returns the
element object if the element is present and visible on the page.
Raises an exception if the element does not appear in the
specified timeout.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds | def wait_for_element_visible(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector. Returns the
element object if the element is present and visible on the page.
Raises an exception if the element does not appear in the
specified timeout.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object
"""
element = None
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
element = driver.find_element(by=by, value=selector)
if element.is_displayed():
return element
else:
element = None
raise Exception()
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
if not element and by != By.LINK_TEXT:
message = (
"Element {%s} was not visible after %s second%s!"
"" % (selector, timeout, plural))
timeout_exception(ElementNotVisibleException, message)
if not element and by == By.LINK_TEXT:
message = (
"Link text {%s} was not visible after %s second%s!"
"" % (selector, timeout, plural))
timeout_exception(ElementNotVisibleException, message) | [
"def",
"wait_for_element_visible",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"element",
"=",
"None",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"if",
"element",
".",
"is_displayed",
"(",
")",
":",
"return",
"element",
"else",
":",
"element",
"=",
"None",
"raise",
"Exception",
"(",
")",
"except",
"Exception",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"if",
"not",
"element",
"and",
"by",
"!=",
"By",
".",
"LINK_TEXT",
":",
"message",
"=",
"(",
"\"Element {%s} was not visible after %s second%s!\"",
"\"\"",
"%",
"(",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"ElementNotVisibleException",
",",
"message",
")",
"if",
"not",
"element",
"and",
"by",
"==",
"By",
".",
"LINK_TEXT",
":",
"message",
"=",
"(",
"\"Link text {%s} was not visible after %s second%s!\"",
"\"\"",
"%",
"(",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"ElementNotVisibleException",
",",
"message",
")"
] | [
253,
0
] | [
298,
62
] | python | en | ['en', 'error', 'th'] | False |
wait_for_text_visible | (driver, text, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the specified element by the given selector. Returns the
element object if the text is present in the element and visible
on the page. Raises an exception if the text or element do not appear
in the specified timeout.
@Params
driver - the webdriver object (required)
text - the text that is being searched for in the element (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object that contains the text searched for
|
Searches for the specified element by the given selector. Returns the
element object if the text is present in the element and visible
on the page. Raises an exception if the text or element do not appear
in the specified timeout.
| def wait_for_text_visible(driver, text, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector. Returns the
element object if the text is present in the element and visible
on the page. Raises an exception if the text or element do not appear
in the specified timeout.
@Params
driver - the webdriver object (required)
text - the text that is being searched for in the element (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object that contains the text searched for
"""
element = None
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
element = driver.find_element(by=by, value=selector)
if element.is_displayed() and text in element.text:
return element
else:
element = None
raise Exception()
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
if not element:
message = (
"Expected text {%s} for {%s} was not visible after %s second%s!"
"" % (text, selector, timeout, plural))
timeout_exception(ElementNotVisibleException, message) | [
"def",
"wait_for_text_visible",
"(",
"driver",
",",
"text",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"element",
"=",
"None",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"if",
"element",
".",
"is_displayed",
"(",
")",
"and",
"text",
"in",
"element",
".",
"text",
":",
"return",
"element",
"else",
":",
"element",
"=",
"None",
"raise",
"Exception",
"(",
")",
"except",
"Exception",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"if",
"not",
"element",
":",
"message",
"=",
"(",
"\"Expected text {%s} for {%s} was not visible after %s second%s!\"",
"\"\"",
"%",
"(",
"text",
",",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"ElementNotVisibleException",
",",
"message",
")"
] | [
301,
0
] | [
341,
62
] | python | en | ['en', 'error', 'th'] | False |
wait_for_exact_text_visible | (driver, text, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the specified element by the given selector. Returns the
element object if the text matches exactly with the text in the element,
and the text is visible.
Raises an exception if the text or element do not appear
in the specified timeout.
@Params
driver - the webdriver object (required)
text - the exact text that is expected for the element (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object that contains the text searched for
|
Searches for the specified element by the given selector. Returns the
element object if the text matches exactly with the text in the element,
and the text is visible.
Raises an exception if the text or element do not appear
in the specified timeout.
| def wait_for_exact_text_visible(driver, text, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector. Returns the
element object if the text matches exactly with the text in the element,
and the text is visible.
Raises an exception if the text or element do not appear
in the specified timeout.
@Params
driver - the webdriver object (required)
text - the exact text that is expected for the element (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object that contains the text searched for
"""
element = None
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
element = driver.find_element(by=by, value=selector)
if element.is_displayed() and text.strip() == element.text.strip():
return element
else:
element = None
raise Exception()
except Exception:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
if not element:
message = (
"Expected exact text {%s} for {%s} was not visible "
"after %s second%s!" % (text, selector, timeout, plural))
timeout_exception(ElementNotVisibleException, message) | [
"def",
"wait_for_exact_text_visible",
"(",
"driver",
",",
"text",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"element",
"=",
"None",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"if",
"element",
".",
"is_displayed",
"(",
")",
"and",
"text",
".",
"strip",
"(",
")",
"==",
"element",
".",
"text",
".",
"strip",
"(",
")",
":",
"return",
"element",
"else",
":",
"element",
"=",
"None",
"raise",
"Exception",
"(",
")",
"except",
"Exception",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"if",
"not",
"element",
":",
"message",
"=",
"(",
"\"Expected exact text {%s} for {%s} was not visible \"",
"\"after %s second%s!\"",
"%",
"(",
"text",
",",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"ElementNotVisibleException",
",",
"message",
")"
] | [
344,
0
] | [
385,
62
] | python | en | ['en', 'error', 'th'] | False |
wait_for_element_absent | (driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the specified element by the given selector.
Raises an exception if the element is still present after the
specified timeout.
@Params
driver - the webdriver object
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
|
Searches for the specified element by the given selector.
Raises an exception if the element is still present after the
specified timeout.
| def wait_for_element_absent(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector.
Raises an exception if the element is still present after the
specified timeout.
@Params
driver - the webdriver object
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
driver.find_element(by=by, value=selector)
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
except Exception:
return True
plural = "s"
if timeout == 1:
plural = ""
message = (
"Element {%s} was still present after %s second%s!"
"" % (selector, timeout, plural))
timeout_exception(Exception, message) | [
"def",
"wait_for_element_absent",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"except",
"Exception",
":",
"return",
"True",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Element {%s} was still present after %s second%s!\"",
"\"\"",
"%",
"(",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")"
] | [
388,
0
] | [
418,
41
] | python | en | ['en', 'error', 'th'] | False |
wait_for_element_not_visible | (driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the specified element by the given selector.
Raises an exception if the element is still visible after the
specified timeout.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for the element in seconds
|
Searches for the specified element by the given selector.
Raises an exception if the element is still visible after the
specified timeout.
| def wait_for_element_not_visible(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector.
Raises an exception if the element is still visible after the
specified timeout.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for the element in seconds
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
element = driver.find_element(by=by, value=selector)
if element.is_displayed():
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
else:
return True
except Exception:
return True
plural = "s"
if timeout == 1:
plural = ""
message = (
"Element {%s} was still visible after %s second%s!"
"" % (selector, timeout, plural))
timeout_exception(Exception, message) | [
"def",
"wait_for_element_not_visible",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"if",
"element",
".",
"is_displayed",
"(",
")",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"else",
":",
"return",
"True",
"except",
"Exception",
":",
"return",
"True",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Element {%s} was still visible after %s second%s!\"",
"\"\"",
"%",
"(",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")"
] | [
421,
0
] | [
454,
41
] | python | en | ['en', 'error', 'th'] | False |
wait_for_text_not_visible | (driver, text, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT) |
Searches for the text in the element of the given selector on the page.
Returns True if the text is not visible on the page within the timeout.
Raises an exception if the text is still present after the timeout.
@Params
driver - the webdriver object (required)
text - the text that is being searched for in the element (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object that contains the text searched for
|
Searches for the text in the element of the given selector on the page.
Returns True if the text is not visible on the page within the timeout.
Raises an exception if the text is still present after the timeout.
| def wait_for_text_not_visible(driver, text, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the text in the element of the given selector on the page.
Returns True if the text is not visible on the page within the timeout.
Raises an exception if the text is still present after the timeout.
@Params
driver - the webdriver object (required)
text - the text that is being searched for in the element (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
timeout - the time to wait for elements in seconds
@Returns
A web element object that contains the text searched for
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
if not is_text_visible(driver, text, selector, by=by):
return True
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
message = (
"Text {%s} in {%s} was still visible after %s "
"second%s!" % (text, selector, timeout, plural))
timeout_exception(Exception, message) | [
"def",
"wait_for_text_not_visible",
"(",
"driver",
",",
"text",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"if",
"not",
"is_text_visible",
"(",
"driver",
",",
"text",
",",
"selector",
",",
"by",
"=",
"by",
")",
":",
"return",
"True",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Text {%s} in {%s} was still visible after %s \"",
"\"second%s!\"",
"%",
"(",
"text",
",",
"selector",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")"
] | [
457,
0
] | [
488,
41
] | python | en | ['en', 'error', 'th'] | False |
find_visible_elements | (driver, selector, by=By.CSS_SELECTOR) |
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
|
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
| def find_visible_elements(driver, selector, by=By.CSS_SELECTOR):
"""
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator for identifying the page element (required)
by - the type of selector being used (Default: By.CSS_SELECTOR)
"""
elements = driver.find_elements(by=by, value=selector)
try:
v_elems = [element for element in elements if element.is_displayed()]
return v_elems
except (StaleElementReferenceException, ENI_Exception):
time.sleep(0.1)
elements = driver.find_elements(by=by, value=selector)
v_elems = []
for element in elements:
if element.is_displayed():
v_elems.append(element)
return v_elems | [
"def",
"find_visible_elements",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"elements",
"=",
"driver",
".",
"find_elements",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"try",
":",
"v_elems",
"=",
"[",
"element",
"for",
"element",
"in",
"elements",
"if",
"element",
".",
"is_displayed",
"(",
")",
"]",
"return",
"v_elems",
"except",
"(",
"StaleElementReferenceException",
",",
"ENI_Exception",
")",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"elements",
"=",
"driver",
".",
"find_elements",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"v_elems",
"=",
"[",
"]",
"for",
"element",
"in",
"elements",
":",
"if",
"element",
".",
"is_displayed",
"(",
")",
":",
"v_elems",
".",
"append",
"(",
"element",
")",
"return",
"v_elems"
] | [
491,
0
] | [
511,
22
] | python | en | ['en', 'error', 'th'] | False |
save_screenshot | (driver, name, folder=None) |
Saves a screenshot to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
The screenshot will be in PNG format.
|
Saves a screenshot to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
The screenshot will be in PNG format.
| def save_screenshot(driver, name, folder=None):
"""
Saves a screenshot to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
The screenshot will be in PNG format.
"""
if not name.endswith(".png"):
name = name + ".png"
if folder:
abs_path = os.path.abspath('.')
file_path = abs_path + "/%s" % folder
if not os.path.exists(file_path):
os.makedirs(file_path)
screenshot_path = "%s/%s" % (file_path, name)
else:
screenshot_path = name
try:
element = driver.find_element(by=By.TAG_NAME, value="body")
element_png = element.screenshot_as_png
with open(screenshot_path, "wb") as file:
file.write(element_png)
except Exception:
if driver:
driver.get_screenshot_as_file(screenshot_path)
else:
pass | [
"def",
"save_screenshot",
"(",
"driver",
",",
"name",
",",
"folder",
"=",
"None",
")",
":",
"if",
"not",
"name",
".",
"endswith",
"(",
"\".png\"",
")",
":",
"name",
"=",
"name",
"+",
"\".png\"",
"if",
"folder",
":",
"abs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"file_path",
"=",
"abs_path",
"+",
"\"/%s\"",
"%",
"folder",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"os",
".",
"makedirs",
"(",
"file_path",
")",
"screenshot_path",
"=",
"\"%s/%s\"",
"%",
"(",
"file_path",
",",
"name",
")",
"else",
":",
"screenshot_path",
"=",
"name",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"TAG_NAME",
",",
"value",
"=",
"\"body\"",
")",
"element_png",
"=",
"element",
".",
"screenshot_as_png",
"with",
"open",
"(",
"screenshot_path",
",",
"\"wb\"",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"element_png",
")",
"except",
"Exception",
":",
"if",
"driver",
":",
"driver",
".",
"get_screenshot_as_file",
"(",
"screenshot_path",
")",
"else",
":",
"pass"
] | [
514,
0
] | [
539,
16
] | python | en | ['en', 'error', 'th'] | False |
save_page_source | (driver, name, folder=None) |
Saves the page HTML to the current directory (or given subfolder).
If the folder specified doesn't exist, it will get created.
@Params
name - The file name to save the current page's HTML to.
folder - The folder to save the file to. (Default = current folder)
|
Saves the page HTML to the current directory (or given subfolder).
If the folder specified doesn't exist, it will get created.
| def save_page_source(driver, name, folder=None):
"""
Saves the page HTML to the current directory (or given subfolder).
If the folder specified doesn't exist, it will get created.
@Params
name - The file name to save the current page's HTML to.
folder - The folder to save the file to. (Default = current folder)
"""
if not name.endswith(".html"):
name = name + ".html"
if folder:
abs_path = os.path.abspath('.')
file_path = abs_path + "/%s" % folder
if not os.path.exists(file_path):
os.makedirs(file_path)
html_file_path = "%s/%s" % (file_path, name)
else:
html_file_path = name
page_source = driver.page_source
html_file = codecs.open(html_file_path, "w+", "utf-8")
rendered_source = log_helper.get_html_source_with_base_href(
driver, page_source)
html_file.write(rendered_source)
html_file.close() | [
"def",
"save_page_source",
"(",
"driver",
",",
"name",
",",
"folder",
"=",
"None",
")",
":",
"if",
"not",
"name",
".",
"endswith",
"(",
"\".html\"",
")",
":",
"name",
"=",
"name",
"+",
"\".html\"",
"if",
"folder",
":",
"abs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"file_path",
"=",
"abs_path",
"+",
"\"/%s\"",
"%",
"folder",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"os",
".",
"makedirs",
"(",
"file_path",
")",
"html_file_path",
"=",
"\"%s/%s\"",
"%",
"(",
"file_path",
",",
"name",
")",
"else",
":",
"html_file_path",
"=",
"name",
"page_source",
"=",
"driver",
".",
"page_source",
"html_file",
"=",
"codecs",
".",
"open",
"(",
"html_file_path",
",",
"\"w+\"",
",",
"\"utf-8\"",
")",
"rendered_source",
"=",
"log_helper",
".",
"get_html_source_with_base_href",
"(",
"driver",
",",
"page_source",
")",
"html_file",
".",
"write",
"(",
"rendered_source",
")",
"html_file",
".",
"close",
"(",
")"
] | [
542,
0
] | [
565,
21
] | python | en | ['en', 'error', 'th'] | False |
save_test_failure_data | (driver, name, browser_type, folder=None) |
Saves failure data to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
|
Saves failure data to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
| def save_test_failure_data(driver, name, browser_type, folder=None):
"""
Saves failure data to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
"""
import traceback
if folder:
abs_path = os.path.abspath('.')
file_path = abs_path + "/%s" % folder
if not os.path.exists(file_path):
os.makedirs(file_path)
failure_data_file_path = "%s/%s" % (file_path, name)
else:
failure_data_file_path = name
failure_data_file = codecs.open(failure_data_file_path, "w+", "utf-8")
last_page = _get_last_page(driver)
data_to_save = []
data_to_save.append("Last_Page: %s" % last_page)
data_to_save.append("Browser: %s " % browser_type)
data_to_save.append("Traceback: " + ''.join(
traceback.format_exception(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2])))
failure_data_file.writelines("\r\n".join(data_to_save))
failure_data_file.close() | [
"def",
"save_test_failure_data",
"(",
"driver",
",",
"name",
",",
"browser_type",
",",
"folder",
"=",
"None",
")",
":",
"import",
"traceback",
"if",
"folder",
":",
"abs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"file_path",
"=",
"abs_path",
"+",
"\"/%s\"",
"%",
"folder",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"os",
".",
"makedirs",
"(",
"file_path",
")",
"failure_data_file_path",
"=",
"\"%s/%s\"",
"%",
"(",
"file_path",
",",
"name",
")",
"else",
":",
"failure_data_file_path",
"=",
"name",
"failure_data_file",
"=",
"codecs",
".",
"open",
"(",
"failure_data_file_path",
",",
"\"w+\"",
",",
"\"utf-8\"",
")",
"last_page",
"=",
"_get_last_page",
"(",
"driver",
")",
"data_to_save",
"=",
"[",
"]",
"data_to_save",
".",
"append",
"(",
"\"Last_Page: %s\"",
"%",
"last_page",
")",
"data_to_save",
".",
"append",
"(",
"\"Browser: %s \"",
"%",
"browser_type",
")",
"data_to_save",
".",
"append",
"(",
"\"Traceback: \"",
"+",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
")",
")",
"failure_data_file",
".",
"writelines",
"(",
"\"\\r\\n\"",
".",
"join",
"(",
"data_to_save",
")",
")",
"failure_data_file",
".",
"close",
"(",
")"
] | [
578,
0
] | [
602,
29
] | python | en | ['en', 'error', 'th'] | False |
wait_for_and_accept_alert | (driver, timeout=settings.LARGE_TIMEOUT) |
Wait for and accept an alert. Returns the text from the alert.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
|
Wait for and accept an alert. Returns the text from the alert.
| def wait_for_and_accept_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for and accept an alert. Returns the text from the alert.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
"""
alert = wait_for_and_switch_to_alert(driver, timeout)
alert_text = alert.text
alert.accept()
return alert_text | [
"def",
"wait_for_and_accept_alert",
"(",
"driver",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"alert",
"=",
"wait_for_and_switch_to_alert",
"(",
"driver",
",",
"timeout",
")",
"alert_text",
"=",
"alert",
".",
"text",
"alert",
".",
"accept",
"(",
")",
"return",
"alert_text"
] | [
605,
0
] | [
615,
21
] | python | en | ['en', 'error', 'th'] | False |
wait_for_and_dismiss_alert | (driver, timeout=settings.LARGE_TIMEOUT) |
Wait for and dismiss an alert. Returns the text from the alert.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
|
Wait for and dismiss an alert. Returns the text from the alert.
| def wait_for_and_dismiss_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for and dismiss an alert. Returns the text from the alert.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
"""
alert = wait_for_and_switch_to_alert(driver, timeout)
alert_text = alert.text
alert.dismiss()
return alert_text | [
"def",
"wait_for_and_dismiss_alert",
"(",
"driver",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"alert",
"=",
"wait_for_and_switch_to_alert",
"(",
"driver",
",",
"timeout",
")",
"alert_text",
"=",
"alert",
".",
"text",
"alert",
".",
"dismiss",
"(",
")",
"return",
"alert_text"
] | [
618,
0
] | [
628,
21
] | python | en | ['en', 'error', 'th'] | False |
wait_for_and_switch_to_alert | (driver, timeout=settings.LARGE_TIMEOUT) |
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
|
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
| def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
alert = driver.switch_to.alert
# Raises exception if no alert present
dummy_variable = alert.text # noqa
return alert
except NoAlertPresentException:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
message = (
"Alert was not present after %s seconds!" % timeout)
timeout_exception(Exception, message) | [
"def",
"wait_for_and_switch_to_alert",
"(",
"driver",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"alert",
"=",
"driver",
".",
"switch_to",
".",
"alert",
"# Raises exception if no alert present",
"dummy_variable",
"=",
"alert",
".",
"text",
"# noqa",
"return",
"alert",
"except",
"NoAlertPresentException",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"message",
"=",
"(",
"\"Alert was not present after %s seconds!\"",
"%",
"timeout",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")"
] | [
631,
0
] | [
656,
41
] | python | en | ['en', 'error', 'th'] | False |
switch_to_frame | (driver, frame, timeout=settings.SMALL_TIMEOUT) |
Wait for an iframe to appear, and switch to it. This should be
usable as a drop-in replacement for driver.switch_to.frame().
@Params
driver - the webdriver object (required)
frame - the frame element, name, id, index, or selector
timeout - the time to wait for the alert in seconds
|
Wait for an iframe to appear, and switch to it. This should be
usable as a drop-in replacement for driver.switch_to.frame().
| def switch_to_frame(driver, frame, timeout=settings.SMALL_TIMEOUT):
"""
Wait for an iframe to appear, and switch to it. This should be
usable as a drop-in replacement for driver.switch_to.frame().
@Params
driver - the webdriver object (required)
frame - the frame element, name, id, index, or selector
timeout - the time to wait for the alert in seconds
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
driver.switch_to.frame(frame)
return True
except NoSuchFrameException:
if type(frame) is str:
by = None
if page_utils.is_xpath_selector(frame):
by = By.XPATH
else:
by = By.CSS_SELECTOR
if is_element_visible(driver, frame, by=by):
try:
element = driver.find_element(by=by, value=frame)
driver.switch_to.frame(element)
return True
except Exception:
pass
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
message = (
"Frame {%s} was not visible after %s second%s!"
"" % (frame, timeout, plural))
timeout_exception(Exception, message) | [
"def",
"switch_to_frame",
"(",
"driver",
",",
"frame",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"driver",
".",
"switch_to",
".",
"frame",
"(",
"frame",
")",
"return",
"True",
"except",
"NoSuchFrameException",
":",
"if",
"type",
"(",
"frame",
")",
"is",
"str",
":",
"by",
"=",
"None",
"if",
"page_utils",
".",
"is_xpath_selector",
"(",
"frame",
")",
":",
"by",
"=",
"By",
".",
"XPATH",
"else",
":",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
"if",
"is_element_visible",
"(",
"driver",
",",
"frame",
",",
"by",
"=",
"by",
")",
":",
"try",
":",
"element",
"=",
"driver",
".",
"find_element",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"frame",
")",
"driver",
".",
"switch_to",
".",
"frame",
"(",
"element",
")",
"return",
"True",
"except",
"Exception",
":",
"pass",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Frame {%s} was not visible after %s second%s!\"",
"\"\"",
"%",
"(",
"frame",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")"
] | [
659,
0
] | [
699,
41
] | python | en | ['en', 'error', 'th'] | False |
switch_to_window | (driver, window, timeout=settings.SMALL_TIMEOUT) |
Wait for a window to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.window().
@Params
driver - the webdriver object (required)
window - the window index or window handle
timeout - the time to wait for the window in seconds
|
Wait for a window to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.window().
| def switch_to_window(driver, window, timeout=settings.SMALL_TIMEOUT):
"""
Wait for a window to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.window().
@Params
driver - the webdriver object (required)
window - the window index or window handle
timeout - the time to wait for the window in seconds
"""
start_ms = time.time() * 1000.0
stop_ms = start_ms + (timeout * 1000.0)
if isinstance(window, int):
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
window_handle = driver.window_handles[window]
driver.switch_to.window(window_handle)
return True
except IndexError:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
message = (
"Window {%s} was not present after %s second%s!"
"" % (window, timeout, plural))
timeout_exception(Exception, message)
else:
window_handle = window
for x in range(int(timeout * 10)):
s_utils.check_if_time_limit_exceeded()
try:
driver.switch_to.window(window_handle)
return True
except NoSuchWindowException:
now_ms = time.time() * 1000.0
if now_ms >= stop_ms:
break
time.sleep(0.1)
plural = "s"
if timeout == 1:
plural = ""
message = (
"Window {%s} was not present after %s second%s!"
"" % (window, timeout, plural))
timeout_exception(Exception, message) | [
"def",
"switch_to_window",
"(",
"driver",
",",
"window",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
":",
"start_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"stop_ms",
"=",
"start_ms",
"+",
"(",
"timeout",
"*",
"1000.0",
")",
"if",
"isinstance",
"(",
"window",
",",
"int",
")",
":",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"window_handle",
"=",
"driver",
".",
"window_handles",
"[",
"window",
"]",
"driver",
".",
"switch_to",
".",
"window",
"(",
"window_handle",
")",
"return",
"True",
"except",
"IndexError",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Window {%s} was not present after %s second%s!\"",
"\"\"",
"%",
"(",
"window",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")",
"else",
":",
"window_handle",
"=",
"window",
"for",
"x",
"in",
"range",
"(",
"int",
"(",
"timeout",
"*",
"10",
")",
")",
":",
"s_utils",
".",
"check_if_time_limit_exceeded",
"(",
")",
"try",
":",
"driver",
".",
"switch_to",
".",
"window",
"(",
"window_handle",
")",
"return",
"True",
"except",
"NoSuchWindowException",
":",
"now_ms",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000.0",
"if",
"now_ms",
">=",
"stop_ms",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"plural",
"=",
"\"s\"",
"if",
"timeout",
"==",
"1",
":",
"plural",
"=",
"\"\"",
"message",
"=",
"(",
"\"Window {%s} was not present after %s second%s!\"",
"\"\"",
"%",
"(",
"window",
",",
"timeout",
",",
"plural",
")",
")",
"timeout_exception",
"(",
"Exception",
",",
"message",
")"
] | [
702,
0
] | [
750,
45
] | python | en | ['en', 'error', 'th'] | False |
Mark.cli_as_experimental | (func: Callable) | Apply as a decorator to CLI commands that are Experimental. | Apply as a decorator to CLI commands that are Experimental. | def cli_as_experimental(func: Callable) -> Callable:
"""Apply as a decorator to CLI commands that are Experimental."""
@wraps(func)
def wrapper(*args, **kwargs):
cli_message(
"<yellow>Heads up! This feature is Experimental. It may change. "
"Please give us your feedback!</yellow>"
)
func(*args, **kwargs)
return wrapper | [
"def",
"cli_as_experimental",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cli_message",
"(",
"\"<yellow>Heads up! This feature is Experimental. It may change. \"",
"\"Please give us your feedback!</yellow>\"",
")",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | [
18,
4
] | [
29,
22
] | python | en | ['en', 'en', 'en'] | True |
Mark.cli_as_beta | (func: Callable) | Apply as a decorator to CLI commands that are beta. | Apply as a decorator to CLI commands that are beta. | def cli_as_beta(func: Callable) -> Callable:
"""Apply as a decorator to CLI commands that are beta."""
@wraps(func)
def wrapper(*args, **kwargs):
cli_message(
"<yellow>Heads up! This feature is in Beta. Please give us "
"your feedback!</yellow>"
)
func(*args, **kwargs)
return wrapper | [
"def",
"cli_as_beta",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cli_message",
"(",
"\"<yellow>Heads up! This feature is in Beta. Please give us \"",
"\"your feedback!</yellow>\"",
")",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | [
32,
4
] | [
43,
22
] | python | en | ['en', 'en', 'en'] | True |
Mark.cli_as_deprecation | (
message: str = "<yellow>Heads up! This feature will be deprecated in the next major release</yellow>",
) | Apply as a decorator to CLI commands that will be deprecated. | Apply as a decorator to CLI commands that will be deprecated. | def cli_as_deprecation(
message: str = "<yellow>Heads up! This feature will be deprecated in the next major release</yellow>",
) -> Callable:
"""Apply as a decorator to CLI commands that will be deprecated."""
def inner_decorator(func):
@wraps(func)
def wrapped(*args, **kwargs):
cli_message(message)
func(*args, **kwargs)
return wrapped
return inner_decorator | [
"def",
"cli_as_deprecation",
"(",
"message",
":",
"str",
"=",
"\"<yellow>Heads up! This feature will be deprecated in the next major release</yellow>\"",
",",
")",
"->",
"Callable",
":",
"def",
"inner_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cli_message",
"(",
"message",
")",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped",
"return",
"inner_decorator"
] | [
46,
4
] | [
59,
30
] | python | en | ['en', 'en', 'en'] | True |
test_expect_column_values_to_be_of_type | (spark_session, test_dataframe) |
data asset expectation
|
data asset expectation
| def test_expect_column_values_to_be_of_type(spark_session, test_dataframe):
"""
data asset expectation
"""
from pyspark.sql.utils import AnalysisException
assert test_dataframe.expect_column_values_to_be_of_type(
"address.street", "StringType"
).success
assert test_dataframe.expect_column_values_to_be_of_type(
"`non.nested`", "StringType"
).success
assert test_dataframe.expect_column_values_to_be_of_type(
"name", "StringType"
).success
with pytest.raises(AnalysisException):
test_dataframe.expect_column_values_to_be_of_type("non.nested", "StringType") | [
"def",
"test_expect_column_values_to_be_of_type",
"(",
"spark_session",
",",
"test_dataframe",
")",
":",
"from",
"pyspark",
".",
"sql",
".",
"utils",
"import",
"AnalysisException",
"assert",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"address.street\"",
",",
"\"StringType\"",
")",
".",
"success",
"assert",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"`non.nested`\"",
",",
"\"StringType\"",
")",
".",
"success",
"assert",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"name\"",
",",
"\"StringType\"",
")",
".",
"success",
"with",
"pytest",
".",
"raises",
"(",
"AnalysisException",
")",
":",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"non.nested\"",
",",
"\"StringType\"",
")"
] | [
122,
0
] | [
138,
85
] | python | en | ['en', 'error', 'th'] | False |
test_expect_column_values_to_be_of_type | (spark_session, test_dataframe) |
data asset expectation
|
data asset expectation
| def test_expect_column_values_to_be_of_type(spark_session, test_dataframe):
"""
data asset expectation
"""
from pyspark.sql.utils import AnalysisException
assert test_dataframe.expect_column_values_to_be_of_type(
"address.street", "StringType"
).success
assert test_dataframe.expect_column_values_to_be_of_type(
"`non.nested`", "StringType"
).success
assert test_dataframe.expect_column_values_to_be_of_type(
"name", "StringType"
).success
with pytest.raises(AnalysisException):
test_dataframe.expect_column_values_to_be_of_type("non.nested", "StringType") | [
"def",
"test_expect_column_values_to_be_of_type",
"(",
"spark_session",
",",
"test_dataframe",
")",
":",
"from",
"pyspark",
".",
"sql",
".",
"utils",
"import",
"AnalysisException",
"assert",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"address.street\"",
",",
"\"StringType\"",
")",
".",
"success",
"assert",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"`non.nested`\"",
",",
"\"StringType\"",
")",
".",
"success",
"assert",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"name\"",
",",
"\"StringType\"",
")",
".",
"success",
"with",
"pytest",
".",
"raises",
"(",
"AnalysisException",
")",
":",
"test_dataframe",
".",
"expect_column_values_to_be_of_type",
"(",
"\"non.nested\"",
",",
"\"StringType\"",
")"
] | [
145,
0
] | [
161,
85
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.