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 |
---|---|---|---|---|---|---|---|---|---|---|---|
get_global_namespace | (decls) |
Get the global namespace (::) from a declaration tree.
Args:
decls (list[declaration_t]): a list of declarations
Returns:
namespace_t: the global namespace_t object (::)
|
Get the global namespace (::) from a declaration tree. | def get_global_namespace(decls):
"""
Get the global namespace (::) from a declaration tree.
Args:
decls (list[declaration_t]): a list of declarations
Returns:
namespace_t: the global namespace_t object (::)
"""
found = [
decl for decl in scopedef.make_flatten(decls) if decl.name == '::' and
isinstance(decl, namespace_t)]
if len(found) == 1:
return found[0]
raise RuntimeError("Unable to find global namespace.") | [
"def",
"get_global_namespace",
"(",
"decls",
")",
":",
"found",
"=",
"[",
"decl",
"for",
"decl",
"in",
"scopedef",
".",
"make_flatten",
"(",
"decls",
")",
"if",
"decl",
".",
"name",
"==",
"'::'",
"and",
"isinstance",
"(",
"decl",
",",
"namespace_t",
")",
"]",
"if",
"len",
"(",
"found",
")",
"==",
"1",
":",
"return",
"found",
"[",
"0",
"]",
"raise",
"RuntimeError",
"(",
"\"Unable to find global namespace.\"",
")"
] | [
337,
0
] | [
353,
58
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.__init__ | (self, name='', declarations=None) |
Creates an object that describes a C++ namespace declaration.
Args:
name (str): name of the namespace
declarations (list[declaration_t]): list of declarations
|
Creates an object that describes a C++ namespace declaration. | def __init__(self, name='', declarations=None):
"""
Creates an object that describes a C++ namespace declaration.
Args:
name (str): name of the namespace
declarations (list[declaration_t]): list of declarations
"""
scopedef.scopedef_t.__init__(self, name)
if not declarations:
declarations = []
# List of all declarations belonging to this namespace
self._declarations = declarations | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"''",
",",
"declarations",
"=",
"None",
")",
":",
"scopedef",
".",
"scopedef_t",
".",
"__init__",
"(",
"self",
",",
"name",
")",
"if",
"not",
"declarations",
":",
"declarations",
"=",
"[",
"]",
"# List of all declarations belonging to this namespace",
"self",
".",
"_declarations",
"=",
"declarations"
] | [
22,
4
] | [
35,
41
] | python | en | ['en', 'error', 'th'] | False |
namespace_t._get__cmp__scope_items | (self) |
Implementation detail.
|
Implementation detail. | def _get__cmp__scope_items(self):
"""
Implementation detail.
"""
return [self.declarations.sort()] | [
"def",
"_get__cmp__scope_items",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"declarations",
".",
"sort",
"(",
")",
"]"
] | [
43,
4
] | [
48,
41
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.declarations | (self) |
List of children declarations.
Returns:
list[declaration_t]
|
List of children declarations. | def declarations(self):
"""
List of children declarations.
Returns:
list[declaration_t]
"""
return scopedef.scopedef_t.declarations.fget(self) | [
"def",
"declarations",
"(",
"self",
")",
":",
"return",
"scopedef",
".",
"scopedef_t",
".",
"declarations",
".",
"fget",
"(",
"self",
")"
] | [
54,
4
] | [
61,
58
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.declarations | (self, declarations) |
Set list of all declarations defined in the namespace.
Args:
declarations (list[declaration_t]): list of declarations
|
Set list of all declarations defined in the namespace. | def declarations(self, declarations):
"""
Set list of all declarations defined in the namespace.
Args:
declarations (list[declaration_t]): list of declarations
"""
self._declarations = declarations | [
"def",
"declarations",
"(",
"self",
",",
"declarations",
")",
":",
"self",
".",
"_declarations",
"=",
"declarations"
] | [
64,
4
] | [
72,
41
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.take_parenting | (self, inst) |
Takes parenting from inst and transfers it to self.
Args:
inst (namespace_t): a namespace declaration
|
Takes parenting from inst and transfers it to self. | def take_parenting(self, inst):
"""
Takes parenting from inst and transfers it to self.
Args:
inst (namespace_t): a namespace declaration
"""
if self is inst:
return
for decl in inst.declarations:
decl.parent = self
self.declarations.append(decl)
inst.declarations = [] | [
"def",
"take_parenting",
"(",
"self",
",",
"inst",
")",
":",
"if",
"self",
"is",
"inst",
":",
"return",
"for",
"decl",
"in",
"inst",
".",
"declarations",
":",
"decl",
".",
"parent",
"=",
"self",
"self",
".",
"declarations",
".",
"append",
"(",
"decl",
")",
"inst",
".",
"declarations",
"=",
"[",
"]"
] | [
74,
4
] | [
88,
30
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.remove_declaration | (self, decl) |
Removes declaration from members list.
:param decl: declaration to be removed
:type decl: :class:`declaration_t`
|
Removes declaration from members list. | def remove_declaration(self, decl):
"""
Removes declaration from members list.
:param decl: declaration to be removed
:type decl: :class:`declaration_t`
"""
del self.declarations[self.declarations.index(decl)]
decl.cache.reset() | [
"def",
"remove_declaration",
"(",
"self",
",",
"decl",
")",
":",
"del",
"self",
".",
"declarations",
"[",
"self",
".",
"declarations",
".",
"index",
"(",
"decl",
")",
"]",
"decl",
".",
"cache",
".",
"reset",
"(",
")"
] | [
95,
4
] | [
105,
26
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.namespace | (self, name=None, function=None, recursive=None) |
Returns reference to namespace declaration that matches
a defined criteria.
|
Returns reference to namespace declaration that matches
a defined criteria. | def namespace(self, name=None, function=None, recursive=None):
"""
Returns reference to namespace declaration that matches
a defined criteria.
"""
return (
self._find_single(
scopedef.scopedef_t._impl_matchers[namespace_t.namespace],
name=name,
function=function,
recursive=recursive)
) | [
"def",
"namespace",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"recursive",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_single",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
".",
"namespace",
"]",
",",
"name",
"=",
"name",
",",
"function",
"=",
"function",
",",
"recursive",
"=",
"recursive",
")",
")"
] | [
110,
4
] | [
123,
9
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.namespaces | (
self,
name=None,
function=None,
recursive=None,
allow_empty=None) |
Returns a set of namespace declarations that match
a defined criteria.
|
Returns a set of namespace declarations that match
a defined criteria. | def namespaces(
self,
name=None,
function=None,
recursive=None,
allow_empty=None):
"""
Returns a set of namespace declarations that match
a defined criteria.
"""
return (
self._find_multiple(
scopedef.scopedef_t._impl_matchers[namespace_t.namespace],
name=name,
function=function,
recursive=recursive,
allow_empty=allow_empty)
) | [
"def",
"namespaces",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"recursive",
"=",
"None",
",",
"allow_empty",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_multiple",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
".",
"namespace",
"]",
",",
"name",
"=",
"name",
",",
"function",
"=",
"function",
",",
"recursive",
"=",
"recursive",
",",
"allow_empty",
"=",
"allow_empty",
")",
")"
] | [
125,
4
] | [
144,
9
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.nss | (self, name=None, function=None, recursive=None, allow_empty=None) |
Deprecated method. Use the namespaces() method instead.
Deprecated since v1.9.0. Will be removed in v2.0.0
|
Deprecated method. Use the namespaces() method instead. | def nss(self, name=None, function=None, recursive=None, allow_empty=None):
"""
Deprecated method. Use the namespaces() method instead.
Deprecated since v1.9.0. Will be removed in v2.0.0
"""
warnings.warn(
"The nss() method is deprecated. \n" +
"Please use the namespaces() method instead.",
DeprecationWarning)
return self.namespaces(name, function, recursive, allow_empty) | [
"def",
"nss",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"recursive",
"=",
"None",
",",
"allow_empty",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The nss() method is deprecated. \\n\"",
"+",
"\"Please use the namespaces() method instead.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"namespaces",
"(",
"name",
",",
"function",
",",
"recursive",
",",
"allow_empty",
")"
] | [
146,
4
] | [
157,
70
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.free_function | (
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None) |
Returns reference to free function declaration that matches
a defined criteria.
|
Returns reference to free function declaration that matches
a defined criteria. | def free_function(
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None):
"""
Returns reference to free function declaration that matches
a defined criteria.
"""
return (
self._find_single(
scopedef.scopedef_t._impl_matchers[namespace_t.free_function],
name=name,
function=function,
decl_type=self._impl_decl_types[namespace_t.free_function],
return_type=return_type,
arg_types=arg_types,
header_dir=header_dir,
header_file=header_file,
recursive=recursive)
) | [
"def",
"free_function",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_single",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
".",
"free_function",
"]",
",",
"name",
"=",
"name",
",",
"function",
"=",
"function",
",",
"decl_type",
"=",
"self",
".",
"_impl_decl_types",
"[",
"namespace_t",
".",
"free_function",
"]",
",",
"return_type",
"=",
"return_type",
",",
"arg_types",
"=",
"arg_types",
",",
"header_dir",
"=",
"header_dir",
",",
"header_file",
"=",
"header_file",
",",
"recursive",
"=",
"recursive",
")",
")"
] | [
159,
4
] | [
185,
9
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.free_fun | (
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None) |
Deprecated method. Use the free_function() method instead.
Deprecated since v1.9.0. Will be removed in v2.0.0
|
Deprecated method. Use the free_function() method instead. | def free_fun(
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None):
"""
Deprecated method. Use the free_function() method instead.
Deprecated since v1.9.0. Will be removed in v2.0.0
"""
warnings.warn(
"The free_fun() method is deprecated. \n" +
"Please use the free_function() method instead.",
DeprecationWarning)
return self.free_function(
name, function,
return_type, arg_types,
header_dir, header_file,
recursive) | [
"def",
"free_fun",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The free_fun() method is deprecated. \\n\"",
"+",
"\"Please use the free_function() method instead.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"free_function",
"(",
"name",
",",
"function",
",",
"return_type",
",",
"arg_types",
",",
"header_dir",
",",
"header_file",
",",
"recursive",
")"
] | [
187,
4
] | [
210,
22
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.free_functions | (
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None) |
Returns a set of free function declarations that match
a defined criteria.
|
Returns a set of free function declarations that match
a defined criteria. | def free_functions(
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None):
"""
Returns a set of free function declarations that match
a defined criteria.
"""
return (
self._find_multiple(
scopedef.scopedef_t._impl_matchers[namespace_t.free_function],
name=name,
function=function,
decl_type=self._impl_decl_types[namespace_t.free_function],
return_type=return_type,
arg_types=arg_types,
header_dir=header_dir,
header_file=header_file,
recursive=recursive,
allow_empty=allow_empty)
) | [
"def",
"free_functions",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
",",
"allow_empty",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_multiple",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
".",
"free_function",
"]",
",",
"name",
"=",
"name",
",",
"function",
"=",
"function",
",",
"decl_type",
"=",
"self",
".",
"_impl_decl_types",
"[",
"namespace_t",
".",
"free_function",
"]",
",",
"return_type",
"=",
"return_type",
",",
"arg_types",
"=",
"arg_types",
",",
"header_dir",
"=",
"header_dir",
",",
"header_file",
"=",
"header_file",
",",
"recursive",
"=",
"recursive",
",",
"allow_empty",
"=",
"allow_empty",
")",
")"
] | [
212,
4
] | [
240,
9
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.free_funs | (
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None) |
Deprecated method. Use the free_functions() method instead.
Deprecated since v1.9.0. Will be removed in v2.0.0
|
Deprecated method. Use the free_functions() method instead. | def free_funs(
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None):
"""
Deprecated method. Use the free_functions() method instead.
Deprecated since v1.9.0. Will be removed in v2.0.0
"""
warnings.warn(
"The free_funs() method is deprecated. \n" +
"Please use the free_functions() method instead.",
DeprecationWarning)
return self.free_functions(
name, function,
return_type, arg_types,
header_dir, header_file,
recursive, allow_empty) | [
"def",
"free_funs",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
",",
"allow_empty",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The free_funs() method is deprecated. \\n\"",
"+",
"\"Please use the free_functions() method instead.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"free_functions",
"(",
"name",
",",
"function",
",",
"return_type",
",",
"arg_types",
",",
"header_dir",
",",
"header_file",
",",
"recursive",
",",
"allow_empty",
")"
] | [
242,
4
] | [
266,
35
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.free_operator | (
self,
name=None,
function=None,
symbol=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None) |
Returns reference to free operator declaration that matches
a defined criteria.
|
Returns reference to free operator declaration that matches
a defined criteria. | def free_operator(
self,
name=None,
function=None,
symbol=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None):
"""
Returns reference to free operator declaration that matches
a defined criteria.
"""
return (
self._find_single(
scopedef.scopedef_t._impl_matchers[namespace_t.free_operator],
name=self._build_operator_name(name, function, symbol),
symbol=symbol,
function=self._build_operator_function(name, function),
decl_type=self._impl_decl_types[namespace_t.free_operator],
return_type=return_type,
arg_types=arg_types,
header_dir=header_dir,
header_file=header_file,
recursive=recursive)
) | [
"def",
"free_operator",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_single",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
".",
"free_operator",
"]",
",",
"name",
"=",
"self",
".",
"_build_operator_name",
"(",
"name",
",",
"function",
",",
"symbol",
")",
",",
"symbol",
"=",
"symbol",
",",
"function",
"=",
"self",
".",
"_build_operator_function",
"(",
"name",
",",
"function",
")",
",",
"decl_type",
"=",
"self",
".",
"_impl_decl_types",
"[",
"namespace_t",
".",
"free_operator",
"]",
",",
"return_type",
"=",
"return_type",
",",
"arg_types",
"=",
"arg_types",
",",
"header_dir",
"=",
"header_dir",
",",
"header_file",
"=",
"header_file",
",",
"recursive",
"=",
"recursive",
")",
")"
] | [
268,
4
] | [
295,
9
] | python | en | ['en', 'error', 'th'] | False |
namespace_t.free_operators | (
self,
name=None,
function=None,
symbol=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None) |
Returns a set of free operator declarations that match
a defined criteria.
|
Returns a set of free operator declarations that match
a defined criteria. | def free_operators(
self,
name=None,
function=None,
symbol=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None):
"""
Returns a set of free operator declarations that match
a defined criteria.
"""
return (
self._find_multiple(
scopedef.scopedef_t._impl_matchers[namespace_t.free_operator],
name=self._build_operator_name(name, function, symbol),
symbol=symbol,
function=self._build_operator_function(name, function),
decl_type=self._impl_decl_types[namespace_t.free_operator],
return_type=return_type,
arg_types=arg_types,
header_dir=header_dir,
header_file=header_file,
recursive=recursive,
allow_empty=allow_empty)
) | [
"def",
"free_operators",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
",",
"allow_empty",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"_find_multiple",
"(",
"scopedef",
".",
"scopedef_t",
".",
"_impl_matchers",
"[",
"namespace_t",
".",
"free_operator",
"]",
",",
"name",
"=",
"self",
".",
"_build_operator_name",
"(",
"name",
",",
"function",
",",
"symbol",
")",
",",
"symbol",
"=",
"symbol",
",",
"function",
"=",
"self",
".",
"_build_operator_function",
"(",
"name",
",",
"function",
")",
",",
"decl_type",
"=",
"self",
".",
"_impl_decl_types",
"[",
"namespace_t",
".",
"free_operator",
"]",
",",
"return_type",
"=",
"return_type",
",",
"arg_types",
"=",
"arg_types",
",",
"header_dir",
"=",
"header_dir",
",",
"header_file",
"=",
"header_file",
",",
"recursive",
"=",
"recursive",
",",
"allow_empty",
"=",
"allow_empty",
")",
")"
] | [
297,
4
] | [
327,
9
] | python | en | ['en', 'error', 'th'] | False |
WinTool._UseSeparateMspdbsrv | (self, env, args) | Allows to use a unique instance of mspdbsrv.exe per linker instead of a
shared one. | Allows to use a unique instance of mspdbsrv.exe per linker instead of a
shared one. | def _UseSeparateMspdbsrv(self, env, args):
"""Allows to use a unique instance of mspdbsrv.exe per linker instead of a
shared one."""
if len(args) < 1:
raise Exception("Not enough arguments")
if args[0] != 'link.exe':
return
# Use the output filename passed to the linker to generate an endpoint name
# for mspdbsrv.exe.
endpoint_name = None
for arg in args:
m = _LINK_EXE_OUT_ARG.match(arg)
if m:
endpoint_name = re.sub(r'\W+', '',
'%s_%d' % (m.group('out'), os.getpid()))
break
if endpoint_name is None:
return
# Adds the appropriate environment variable. This will be read by link.exe
# to know which instance of mspdbsrv.exe it should connect to (if it's
# not set then the default endpoint is used).
env['_MSPDBSRV_ENDPOINT_'] = endpoint_name | [
"def",
"_UseSeparateMspdbsrv",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"Not enough arguments\"",
")",
"if",
"args",
"[",
"0",
"]",
"!=",
"'link.exe'",
":",
"return",
"# Use the output filename passed to the linker to generate an endpoint name",
"# for mspdbsrv.exe.",
"endpoint_name",
"=",
"None",
"for",
"arg",
"in",
"args",
":",
"m",
"=",
"_LINK_EXE_OUT_ARG",
".",
"match",
"(",
"arg",
")",
"if",
"m",
":",
"endpoint_name",
"=",
"re",
".",
"sub",
"(",
"r'\\W+'",
",",
"''",
",",
"'%s_%d'",
"%",
"(",
"m",
".",
"group",
"(",
"'out'",
")",
",",
"os",
".",
"getpid",
"(",
")",
")",
")",
"break",
"if",
"endpoint_name",
"is",
"None",
":",
"return",
"# Adds the appropriate environment variable. This will be read by link.exe",
"# to know which instance of mspdbsrv.exe it should connect to (if it's",
"# not set then the default endpoint is used).",
"env",
"[",
"'_MSPDBSRV_ENDPOINT_'",
"]",
"=",
"endpoint_name"
] | [
36,
2
] | [
61,
46
] | python | en | ['en', 'en', 'en'] | True |
WinTool.Dispatch | (self, args) | Dispatches a string command to a method. | Dispatches a string command to a method. | def Dispatch(self, args):
"""Dispatches a string command to a method."""
if len(args) < 1:
raise Exception("Not enough arguments")
method = "Exec%s" % self._CommandifyName(args[0])
return getattr(self, method)(*args[1:]) | [
"def",
"Dispatch",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"Not enough arguments\"",
")",
"method",
"=",
"\"Exec%s\"",
"%",
"self",
".",
"_CommandifyName",
"(",
"args",
"[",
"0",
"]",
")",
"return",
"getattr",
"(",
"self",
",",
"method",
")",
"(",
"*",
"args",
"[",
"1",
":",
"]",
")"
] | [
63,
2
] | [
69,
43
] | python | en | ['en', 'en', 'en'] | True |
WinTool._CommandifyName | (self, name_string) | Transforms a tool name like recursive-mirror to RecursiveMirror. | Transforms a tool name like recursive-mirror to RecursiveMirror. | def _CommandifyName(self, name_string):
"""Transforms a tool name like recursive-mirror to RecursiveMirror."""
return name_string.title().replace('-', '') | [
"def",
"_CommandifyName",
"(",
"self",
",",
"name_string",
")",
":",
"return",
"name_string",
".",
"title",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")"
] | [
71,
2
] | [
73,
47
] | python | en | ['en', 'el-Latn', 'en'] | True |
WinTool._GetEnv | (self, arch) | Gets the saved environment from a file for a given architecture. | Gets the saved environment from a file for a given architecture. | def _GetEnv(self, arch):
"""Gets the saved environment from a file for a given architecture."""
# The environment is saved as an "environment block" (see CreateProcess
# and msvs_emulation for details). We convert to a dict here.
# Drop last 2 NULs, one for list terminator, one for trailing vs. separator.
pairs = open(arch).read()[:-2].split('\0')
kvs = [item.split('=', 1) for item in pairs]
return dict(kvs) | [
"def",
"_GetEnv",
"(",
"self",
",",
"arch",
")",
":",
"# The environment is saved as an \"environment block\" (see CreateProcess",
"# and msvs_emulation for details). We convert to a dict here.",
"# Drop last 2 NULs, one for list terminator, one for trailing vs. separator.",
"pairs",
"=",
"open",
"(",
"arch",
")",
".",
"read",
"(",
")",
"[",
":",
"-",
"2",
"]",
".",
"split",
"(",
"'\\0'",
")",
"kvs",
"=",
"[",
"item",
".",
"split",
"(",
"'='",
",",
"1",
")",
"for",
"item",
"in",
"pairs",
"]",
"return",
"dict",
"(",
"kvs",
")"
] | [
75,
2
] | [
82,
20
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecStamp | (self, path) | Simple stamp command. | Simple stamp command. | def ExecStamp(self, path):
"""Simple stamp command."""
open(path, 'w').close() | [
"def",
"ExecStamp",
"(",
"self",
",",
"path",
")",
":",
"open",
"(",
"path",
",",
"'w'",
")",
".",
"close",
"(",
")"
] | [
84,
2
] | [
86,
27
] | python | en | ['et', 'en', 'en'] | True |
WinTool.ExecRecursiveMirror | (self, source, dest) | Emulation of rm -rf out && cp -af in out. | Emulation of rm -rf out && cp -af in out. | def ExecRecursiveMirror(self, source, dest):
"""Emulation of rm -rf out && cp -af in out."""
if os.path.exists(dest):
if os.path.isdir(dest):
def _on_error(fn, path, excinfo):
# The operation failed, possibly because the file is set to
# read-only. If that's why, make it writable and try the op again.
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWRITE)
fn(path)
shutil.rmtree(dest, onerror=_on_error)
else:
if not os.access(dest, os.W_OK):
# Attempt to make the file writable before deleting it.
os.chmod(dest, stat.S_IWRITE)
os.unlink(dest)
if os.path.isdir(source):
shutil.copytree(source, dest)
else:
shutil.copy2(source, dest) | [
"def",
"ExecRecursiveMirror",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dest",
")",
":",
"def",
"_on_error",
"(",
"fn",
",",
"path",
",",
"excinfo",
")",
":",
"# The operation failed, possibly because the file is set to",
"# read-only. If that's why, make it writable and try the op again.",
"if",
"not",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"W_OK",
")",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"stat",
".",
"S_IWRITE",
")",
"fn",
"(",
"path",
")",
"shutil",
".",
"rmtree",
"(",
"dest",
",",
"onerror",
"=",
"_on_error",
")",
"else",
":",
"if",
"not",
"os",
".",
"access",
"(",
"dest",
",",
"os",
".",
"W_OK",
")",
":",
"# Attempt to make the file writable before deleting it.",
"os",
".",
"chmod",
"(",
"dest",
",",
"stat",
".",
"S_IWRITE",
")",
"os",
".",
"unlink",
"(",
"dest",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
":",
"shutil",
".",
"copytree",
"(",
"source",
",",
"dest",
")",
"else",
":",
"shutil",
".",
"copy2",
"(",
"source",
",",
"dest",
")"
] | [
88,
2
] | [
108,
32
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecLinkWrapper | (self, arch, use_separate_mspdbsrv, *args) | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe.
| Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe.
| def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
"""Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe.
"""
env = self._GetEnv(arch)
if use_separate_mspdbsrv == 'True':
self._UseSeparateMspdbsrv(env, args)
link = subprocess.Popen([args[0].replace('/', '\\')] + list(args[1:]),
shell=True,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, _ = link.communicate()
for line in out.splitlines():
if (not line.startswith(' Creating library ') and
not line.startswith('Generating code') and
not line.startswith('Finished generating code')):
print line
return link.returncode | [
"def",
"ExecLinkWrapper",
"(",
"self",
",",
"arch",
",",
"use_separate_mspdbsrv",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"if",
"use_separate_mspdbsrv",
"==",
"'True'",
":",
"self",
".",
"_UseSeparateMspdbsrv",
"(",
"env",
",",
"args",
")",
"link",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"args",
"[",
"0",
"]",
".",
"replace",
"(",
"'/'",
",",
"'\\\\'",
")",
"]",
"+",
"list",
"(",
"args",
"[",
"1",
":",
"]",
")",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"link",
".",
"communicate",
"(",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"' Creating library '",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"'Generating code'",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"'Finished generating code'",
")",
")",
":",
"print",
"line",
"return",
"link",
".",
"returncode"
] | [
110,
2
] | [
129,
26
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecLinkWithManifests | (self, arch, embed_manifest, out, ldcmd, resname,
mt, rc, intermediate_manifest, *manifests) | A wrapper for handling creating a manifest resource and then executing
a link command. | A wrapper for handling creating a manifest resource and then executing
a link command. | def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
mt, rc, intermediate_manifest, *manifests):
"""A wrapper for handling creating a manifest resource and then executing
a link command."""
# The 'normal' way to do manifests is to have link generate a manifest
# based on gathering dependencies from the object files, then merge that
# manifest with other manifests supplied as sources, convert the merged
# manifest to a resource, and then *relink*, including the compiled
# version of the manifest resource. This breaks incremental linking, and
# is generally overly complicated. Instead, we merge all the manifests
# provided (along with one that includes what would normally be in the
# linker-generated one, see msvs_emulation.py), and include that into the
# first and only link. We still tell link to generate a manifest, but we
# only use that to assert that our simpler process did not miss anything.
variables = {
'python': sys.executable,
'arch': arch,
'out': out,
'ldcmd': ldcmd,
'resname': resname,
'mt': mt,
'rc': rc,
'intermediate_manifest': intermediate_manifest,
'manifests': ' '.join(manifests),
}
add_to_ld = ''
if manifests:
subprocess.check_call(
'%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
'-manifest %(manifests)s -out:%(out)s.manifest' % variables)
if embed_manifest == 'True':
subprocess.check_call(
'%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
' %(out)s.manifest.rc %(resname)s' % variables)
subprocess.check_call(
'%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
'%(out)s.manifest.rc' % variables)
add_to_ld = ' %(out)s.manifest.res' % variables
subprocess.check_call(ldcmd + add_to_ld)
# Run mt.exe on the theoretically complete manifest we generated, merging
# it with the one the linker generated to confirm that the linker
# generated one does not add anything. This is strictly unnecessary for
# correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
# used in a #pragma comment.
if manifests:
# Merge the intermediate one with ours to .assert.manifest, then check
# that .assert.manifest is identical to ours.
subprocess.check_call(
'%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
'-manifest %(out)s.manifest %(intermediate_manifest)s '
'-out:%(out)s.assert.manifest' % variables)
assert_manifest = '%(out)s.assert.manifest' % variables
our_manifest = '%(out)s.manifest' % variables
# Load and normalize the manifests. mt.exe sometimes removes whitespace,
# and sometimes doesn't unfortunately.
with open(our_manifest, 'rb') as our_f:
with open(assert_manifest, 'rb') as assert_f:
our_data = our_f.read().translate(None, string.whitespace)
assert_data = assert_f.read().translate(None, string.whitespace)
if our_data != assert_data:
os.unlink(out)
def dump(filename):
sys.stderr.write('%s\n-----\n' % filename)
with open(filename, 'rb') as f:
sys.stderr.write(f.read() + '\n-----\n')
dump(intermediate_manifest)
dump(our_manifest)
dump(assert_manifest)
sys.stderr.write(
'Linker generated manifest "%s" added to final manifest "%s" '
'(result in "%s"). '
'Were /MANIFEST switches used in #pragma statements? ' % (
intermediate_manifest, our_manifest, assert_manifest))
return 1 | [
"def",
"ExecLinkWithManifests",
"(",
"self",
",",
"arch",
",",
"embed_manifest",
",",
"out",
",",
"ldcmd",
",",
"resname",
",",
"mt",
",",
"rc",
",",
"intermediate_manifest",
",",
"*",
"manifests",
")",
":",
"# The 'normal' way to do manifests is to have link generate a manifest",
"# based on gathering dependencies from the object files, then merge that",
"# manifest with other manifests supplied as sources, convert the merged",
"# manifest to a resource, and then *relink*, including the compiled",
"# version of the manifest resource. This breaks incremental linking, and",
"# is generally overly complicated. Instead, we merge all the manifests",
"# provided (along with one that includes what would normally be in the",
"# linker-generated one, see msvs_emulation.py), and include that into the",
"# first and only link. We still tell link to generate a manifest, but we",
"# only use that to assert that our simpler process did not miss anything.",
"variables",
"=",
"{",
"'python'",
":",
"sys",
".",
"executable",
",",
"'arch'",
":",
"arch",
",",
"'out'",
":",
"out",
",",
"'ldcmd'",
":",
"ldcmd",
",",
"'resname'",
":",
"resname",
",",
"'mt'",
":",
"mt",
",",
"'rc'",
":",
"rc",
",",
"'intermediate_manifest'",
":",
"intermediate_manifest",
",",
"'manifests'",
":",
"' '",
".",
"join",
"(",
"manifests",
")",
",",
"}",
"add_to_ld",
"=",
"''",
"if",
"manifests",
":",
"subprocess",
".",
"check_call",
"(",
"'%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '",
"'-manifest %(manifests)s -out:%(out)s.manifest'",
"%",
"variables",
")",
"if",
"embed_manifest",
"==",
"'True'",
":",
"subprocess",
".",
"check_call",
"(",
"'%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'",
"' %(out)s.manifest.rc %(resname)s'",
"%",
"variables",
")",
"subprocess",
".",
"check_call",
"(",
"'%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '",
"'%(out)s.manifest.rc'",
"%",
"variables",
")",
"add_to_ld",
"=",
"' %(out)s.manifest.res'",
"%",
"variables",
"subprocess",
".",
"check_call",
"(",
"ldcmd",
"+",
"add_to_ld",
")",
"# Run mt.exe on the theoretically complete manifest we generated, merging",
"# it with the one the linker generated to confirm that the linker",
"# generated one does not add anything. This is strictly unnecessary for",
"# correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not",
"# used in a #pragma comment.",
"if",
"manifests",
":",
"# Merge the intermediate one with ours to .assert.manifest, then check",
"# that .assert.manifest is identical to ours.",
"subprocess",
".",
"check_call",
"(",
"'%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '",
"'-manifest %(out)s.manifest %(intermediate_manifest)s '",
"'-out:%(out)s.assert.manifest'",
"%",
"variables",
")",
"assert_manifest",
"=",
"'%(out)s.assert.manifest'",
"%",
"variables",
"our_manifest",
"=",
"'%(out)s.manifest'",
"%",
"variables",
"# Load and normalize the manifests. mt.exe sometimes removes whitespace,",
"# and sometimes doesn't unfortunately.",
"with",
"open",
"(",
"our_manifest",
",",
"'rb'",
")",
"as",
"our_f",
":",
"with",
"open",
"(",
"assert_manifest",
",",
"'rb'",
")",
"as",
"assert_f",
":",
"our_data",
"=",
"our_f",
".",
"read",
"(",
")",
".",
"translate",
"(",
"None",
",",
"string",
".",
"whitespace",
")",
"assert_data",
"=",
"assert_f",
".",
"read",
"(",
")",
".",
"translate",
"(",
"None",
",",
"string",
".",
"whitespace",
")",
"if",
"our_data",
"!=",
"assert_data",
":",
"os",
".",
"unlink",
"(",
"out",
")",
"def",
"dump",
"(",
"filename",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s\\n-----\\n'",
"%",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"f",
".",
"read",
"(",
")",
"+",
"'\\n-----\\n'",
")",
"dump",
"(",
"intermediate_manifest",
")",
"dump",
"(",
"our_manifest",
")",
"dump",
"(",
"assert_manifest",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Linker generated manifest \"%s\" added to final manifest \"%s\" '",
"'(result in \"%s\"). '",
"'Were /MANIFEST switches used in #pragma statements? '",
"%",
"(",
"intermediate_manifest",
",",
"our_manifest",
",",
"assert_manifest",
")",
")",
"return",
"1"
] | [
131,
2
] | [
205,
16
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecManifestWrapper | (self, arch, *args) | Run manifest tool with environment set. Strip out undesirable warning
(some XML blocks are recognized by the OS loader, but not the manifest
tool). | Run manifest tool with environment set. Strip out undesirable warning
(some XML blocks are recognized by the OS loader, but not the manifest
tool). | def ExecManifestWrapper(self, arch, *args):
"""Run manifest tool with environment set. Strip out undesirable warning
(some XML blocks are recognized by the OS loader, but not the manifest
tool)."""
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
for line in out.splitlines():
if line and 'manifest authoring warning 81010002' not in line:
print line
return popen.returncode | [
"def",
"ExecManifestWrapper",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"popen",
".",
"communicate",
"(",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
"and",
"'manifest authoring warning 81010002'",
"not",
"in",
"line",
":",
"print",
"line",
"return",
"popen",
".",
"returncode"
] | [
207,
2
] | [
218,
27
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecManifestToRc | (self, arch, *args) | Creates a resource file pointing a SxS assembly manifest.
|args| is tuple containing path to resource file, path to manifest file
and resource name which can be "1" (for executables) or "2" (for DLLs). | Creates a resource file pointing a SxS assembly manifest.
|args| is tuple containing path to resource file, path to manifest file
and resource name which can be "1" (for executables) or "2" (for DLLs). | def ExecManifestToRc(self, arch, *args):
"""Creates a resource file pointing a SxS assembly manifest.
|args| is tuple containing path to resource file, path to manifest file
and resource name which can be "1" (for executables) or "2" (for DLLs)."""
manifest_path, resource_path, resource_name = args
with open(resource_path, 'wb') as output:
output.write('#include <windows.h>\n%s RT_MANIFEST "%s"' % (
resource_name,
os.path.abspath(manifest_path).replace('\\', '/'))) | [
"def",
"ExecManifestToRc",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"manifest_path",
",",
"resource_path",
",",
"resource_name",
"=",
"args",
"with",
"open",
"(",
"resource_path",
",",
"'wb'",
")",
"as",
"output",
":",
"output",
".",
"write",
"(",
"'#include <windows.h>\\n%s RT_MANIFEST \"%s\"'",
"%",
"(",
"resource_name",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"manifest_path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
")",
")"
] | [
220,
2
] | [
228,
59
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecMidlWrapper | (self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
*flags) | Filter noisy filenames output from MIDL compile step that isn't
quietable via command line flags.
| Filter noisy filenames output from MIDL compile step that isn't
quietable via command line flags.
| def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl,
*flags):
"""Filter noisy filenames output from MIDL compile step that isn't
quietable via command line flags.
"""
args = ['midl', '/nologo'] + list(flags) + [
'/out', outdir,
'/tlb', tlb,
'/h', h,
'/dlldata', dlldata,
'/iid', iid,
'/proxy', proxy,
idl]
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
# Filter junk out of stdout, and write filtered versions. Output we want
# to filter is pairs of lines that look like this:
# Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl
# objidl.idl
lines = out.splitlines()
prefixes = ('Processing ', '64 bit Processing ')
processing = set(os.path.basename(x)
for x in lines if x.startswith(prefixes))
for line in lines:
if not line.startswith(prefixes) and line not in processing:
print line
return popen.returncode | [
"def",
"ExecMidlWrapper",
"(",
"self",
",",
"arch",
",",
"outdir",
",",
"tlb",
",",
"h",
",",
"dlldata",
",",
"iid",
",",
"proxy",
",",
"idl",
",",
"*",
"flags",
")",
":",
"args",
"=",
"[",
"'midl'",
",",
"'/nologo'",
"]",
"+",
"list",
"(",
"flags",
")",
"+",
"[",
"'/out'",
",",
"outdir",
",",
"'/tlb'",
",",
"tlb",
",",
"'/h'",
",",
"h",
",",
"'/dlldata'",
",",
"dlldata",
",",
"'/iid'",
",",
"iid",
",",
"'/proxy'",
",",
"proxy",
",",
"idl",
"]",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"popen",
".",
"communicate",
"(",
")",
"# Filter junk out of stdout, and write filtered versions. Output we want",
"# to filter is pairs of lines that look like this:",
"# Processing C:\\Program Files (x86)\\Microsoft SDKs\\...\\include\\objidl.idl",
"# objidl.idl",
"lines",
"=",
"out",
".",
"splitlines",
"(",
")",
"prefixes",
"=",
"(",
"'Processing '",
",",
"'64 bit Processing '",
")",
"processing",
"=",
"set",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"x",
")",
"for",
"x",
"in",
"lines",
"if",
"x",
".",
"startswith",
"(",
"prefixes",
")",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"prefixes",
")",
"and",
"line",
"not",
"in",
"processing",
":",
"print",
"line",
"return",
"popen",
".",
"returncode"
] | [
230,
2
] | [
258,
27
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecAsmWrapper | (self, arch, *args) | Filter logo banner from invocations of asm.exe. | Filter logo banner from invocations of asm.exe. | def ExecAsmWrapper(self, arch, *args):
"""Filter logo banner from invocations of asm.exe."""
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
for line in out.splitlines():
if (not line.startswith('Copyright (C) Microsoft Corporation') and
not line.startswith('Microsoft (R) Macro Assembler') and
not line.startswith(' Assembling: ') and
line):
print line
return popen.returncode | [
"def",
"ExecAsmWrapper",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"popen",
".",
"communicate",
"(",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"'Copyright (C) Microsoft Corporation'",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"'Microsoft (R) Macro Assembler'",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"' Assembling: '",
")",
"and",
"line",
")",
":",
"print",
"line",
"return",
"popen",
".",
"returncode"
] | [
260,
2
] | [
272,
27
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecRcWrapper | (self, arch, *args) | Filter logo banner from invocations of rc.exe. Older versions of RC
don't support the /nologo flag. | Filter logo banner from invocations of rc.exe. Older versions of RC
don't support the /nologo flag. | def ExecRcWrapper(self, arch, *args):
"""Filter logo banner from invocations of rc.exe. Older versions of RC
don't support the /nologo flag."""
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
for line in out.splitlines():
if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and
not line.startswith('Copyright (C) Microsoft Corporation') and
line):
print line
return popen.returncode | [
"def",
"ExecRcWrapper",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"popen",
".",
"communicate",
"(",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"'Microsoft (R) Windows (R) Resource Compiler'",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"'Copyright (C) Microsoft Corporation'",
")",
"and",
"line",
")",
":",
"print",
"line",
"return",
"popen",
".",
"returncode"
] | [
274,
2
] | [
286,
27
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecActionWrapper | (self, arch, rspfile, *dir) | Runs an action command line from a response file using the environment
for |arch|. If |dir| is supplied, use that as the working directory. | Runs an action command line from a response file using the environment
for |arch|. If |dir| is supplied, use that as the working directory. | def ExecActionWrapper(self, arch, rspfile, *dir):
"""Runs an action command line from a response file using the environment
for |arch|. If |dir| is supplied, use that as the working directory."""
env = self._GetEnv(arch)
# TODO(scottmg): This is a temporary hack to get some specific variables
# through to actions that are set after gyp-time. http://crbug.com/333738.
for k, v in os.environ.iteritems():
if k not in env:
env[k] = v
args = open(rspfile).read()
dir = dir[0] if dir else None
return subprocess.call(args, shell=True, env=env, cwd=dir) | [
"def",
"ExecActionWrapper",
"(",
"self",
",",
"arch",
",",
"rspfile",
",",
"*",
"dir",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"# TODO(scottmg): This is a temporary hack to get some specific variables",
"# through to actions that are set after gyp-time. http://crbug.com/333738.",
"for",
"k",
",",
"v",
"in",
"os",
".",
"environ",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"env",
":",
"env",
"[",
"k",
"]",
"=",
"v",
"args",
"=",
"open",
"(",
"rspfile",
")",
".",
"read",
"(",
")",
"dir",
"=",
"dir",
"[",
"0",
"]",
"if",
"dir",
"else",
"None",
"return",
"subprocess",
".",
"call",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"cwd",
"=",
"dir",
")"
] | [
288,
2
] | [
299,
62
] | python | en | ['en', 'en', 'en'] | True |
WinTool.ExecClCompile | (self, project_dir, selected_files) | Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files. | Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files. | def ExecClCompile(self, project_dir, selected_files):
"""Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files."""
project_dir = os.path.relpath(project_dir, BASE_DIR)
selected_files = selected_files.split(';')
ninja_targets = [os.path.join(project_dir, filename) + '^^'
for filename in selected_files]
cmd = ['ninja.exe']
cmd.extend(ninja_targets)
return subprocess.call(cmd, shell=True, cwd=BASE_DIR) | [
"def",
"ExecClCompile",
"(",
"self",
",",
"project_dir",
",",
"selected_files",
")",
":",
"project_dir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"project_dir",
",",
"BASE_DIR",
")",
"selected_files",
"=",
"selected_files",
".",
"split",
"(",
"';'",
")",
"ninja_targets",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"project_dir",
",",
"filename",
")",
"+",
"'^^'",
"for",
"filename",
"in",
"selected_files",
"]",
"cmd",
"=",
"[",
"'ninja.exe'",
"]",
"cmd",
".",
"extend",
"(",
"ninja_targets",
")",
"return",
"subprocess",
".",
"call",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"BASE_DIR",
")"
] | [
301,
2
] | [
310,
57
] | python | en | ['en', 'en', 'en'] | True |
_objdump_lexer_tokens | (asm_lexer) |
Common objdump lexer tokens to wrap an ASM lexer.
|
Common objdump lexer tokens to wrap an ASM lexer.
| def _objdump_lexer_tokens(asm_lexer):
"""
Common objdump lexer tokens to wrap an ASM lexer.
"""
hex_re = r'[0-9A-Za-z]'
return {
'root': [
# File name & format:
('(.*?)(:)( +file format )(.*?)$',
bygroups(Name.Label, Punctuation, Text, String)),
# Section header
('(Disassembly of section )(.*?)(:)$',
bygroups(Text, Name.Label, Punctuation)),
# Function labels
# (With offset)
('('+hex_re+'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$',
bygroups(Number.Hex, Text, Punctuation, Name.Function,
Punctuation, Number.Hex, Punctuation)),
# (Without offset)
('('+hex_re+'+)( )(<)(.*?)(>:)$',
bygroups(Number.Hex, Text, Punctuation, Name.Function,
Punctuation)),
# Code line with disassembled instructions
('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *\t)([a-zA-Z].*?)$',
bygroups(Text, Name.Label, Text, Number.Hex, Text,
using(asm_lexer))),
# Code line with ascii
('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *)(.*?)$',
bygroups(Text, Name.Label, Text, Number.Hex, Text, String)),
# Continued code line, only raw opcodes without disassembled
# instruction
('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)$',
bygroups(Text, Name.Label, Text, Number.Hex)),
# Skipped a few bytes
(r'\t\.\.\.$', Text),
# Relocation line
# (With offset)
(r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)([-+])(0x'+hex_re+'+)$',
bygroups(Text, Name.Label, Text, Name.Property, Text,
Name.Constant, Punctuation, Number.Hex)),
# (Without offset)
(r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)$',
bygroups(Text, Name.Label, Text, Name.Property, Text,
Name.Constant)),
(r'[^\n]+\n', Other)
]
} | [
"def",
"_objdump_lexer_tokens",
"(",
"asm_lexer",
")",
":",
"hex_re",
"=",
"r'[0-9A-Za-z]'",
"return",
"{",
"'root'",
":",
"[",
"# File name & format:",
"(",
"'(.*?)(:)( +file format )(.*?)$'",
",",
"bygroups",
"(",
"Name",
".",
"Label",
",",
"Punctuation",
",",
"Text",
",",
"String",
")",
")",
",",
"# Section header",
"(",
"'(Disassembly of section )(.*?)(:)$'",
",",
"bygroups",
"(",
"Text",
",",
"Name",
".",
"Label",
",",
"Punctuation",
")",
")",
",",
"# Function labels",
"# (With offset)",
"(",
"'('",
"+",
"hex_re",
"+",
"'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$'",
",",
"bygroups",
"(",
"Number",
".",
"Hex",
",",
"Text",
",",
"Punctuation",
",",
"Name",
".",
"Function",
",",
"Punctuation",
",",
"Number",
".",
"Hex",
",",
"Punctuation",
")",
")",
",",
"# (Without offset)",
"(",
"'('",
"+",
"hex_re",
"+",
"'+)( )(<)(.*?)(>:)$'",
",",
"bygroups",
"(",
"Number",
".",
"Hex",
",",
"Text",
",",
"Punctuation",
",",
"Name",
".",
"Function",
",",
"Punctuation",
")",
")",
",",
"# Code line with disassembled instructions",
"(",
"'( *)('",
"+",
"hex_re",
"+",
"r'+:)(\\t)((?:'",
"+",
"hex_re",
"+",
"hex_re",
"+",
"' )+)( *\\t)([a-zA-Z].*?)$'",
",",
"bygroups",
"(",
"Text",
",",
"Name",
".",
"Label",
",",
"Text",
",",
"Number",
".",
"Hex",
",",
"Text",
",",
"using",
"(",
"asm_lexer",
")",
")",
")",
",",
"# Code line with ascii",
"(",
"'( *)('",
"+",
"hex_re",
"+",
"r'+:)(\\t)((?:'",
"+",
"hex_re",
"+",
"hex_re",
"+",
"' )+)( *)(.*?)$'",
",",
"bygroups",
"(",
"Text",
",",
"Name",
".",
"Label",
",",
"Text",
",",
"Number",
".",
"Hex",
",",
"Text",
",",
"String",
")",
")",
",",
"# Continued code line, only raw opcodes without disassembled",
"# instruction",
"(",
"'( *)('",
"+",
"hex_re",
"+",
"r'+:)(\\t)((?:'",
"+",
"hex_re",
"+",
"hex_re",
"+",
"' )+)$'",
",",
"bygroups",
"(",
"Text",
",",
"Name",
".",
"Label",
",",
"Text",
",",
"Number",
".",
"Hex",
")",
")",
",",
"# Skipped a few bytes",
"(",
"r'\\t\\.\\.\\.$'",
",",
"Text",
")",
",",
"# Relocation line",
"# (With offset)",
"(",
"r'(\\t\\t\\t)('",
"+",
"hex_re",
"+",
"r'+:)( )([^\\t]+)(\\t)(.*?)([-+])(0x'",
"+",
"hex_re",
"+",
"'+)$'",
",",
"bygroups",
"(",
"Text",
",",
"Name",
".",
"Label",
",",
"Text",
",",
"Name",
".",
"Property",
",",
"Text",
",",
"Name",
".",
"Constant",
",",
"Punctuation",
",",
"Number",
".",
"Hex",
")",
")",
",",
"# (Without offset)",
"(",
"r'(\\t\\t\\t)('",
"+",
"hex_re",
"+",
"r'+:)( )([^\\t]+)(\\t)(.*?)$'",
",",
"bygroups",
"(",
"Text",
",",
"Name",
".",
"Label",
",",
"Text",
",",
"Name",
".",
"Property",
",",
"Text",
",",
"Name",
".",
"Constant",
")",
")",
",",
"(",
"r'[^\\n]+\\n'",
",",
"Other",
")",
"]",
"}"
] | [
100,
0
] | [
146,
5
] | python | en | ['en', 'error', 'th'] | False |
PreProcessor.__init__ | (
self,
clean_whitespace: bool = True,
clean_header_footer: bool = False,
clean_empty_lines: bool = True,
split_by: str = "word",
split_length: int = 1000,
split_overlap: int = 0,
split_respect_sentence_boundary: bool = True,
) |
:param clean_header_footer: Use heuristic to remove footers and headers across different pages by searching
for the longest common string. This heuristic uses exact matches and therefore
works well for footers like "Copyright 2019 by XXX", but won't detect "Page 3 of 4"
or similar.
:param clean_whitespace: Strip whitespaces before or after each line in the text.
:param clean_empty_lines: Remove more than two empty lines in the text.
:param split_by: Unit for splitting the document. Can be "word", "sentence", or "passage". Set to None to disable splitting.
:param split_length: Max. number of the above split unit (e.g. words) that are allowed in one document. For instance, if n -> 10 & split_by ->
"sentence", then each output document will have 10 sentences.
:param split_overlap: Word overlap between two adjacent documents after a split.
Setting this to a positive number essentially enables the sliding window approach.
For example, if split_by -> `word`,
split_length -> 5 & split_overlap -> 2, then the splits would be like:
[w1 w2 w3 w4 w5, w4 w5 w6 w7 w8, w7 w8 w10 w11 w12].
Set the value to 0 to ensure there is no overlap among the documents after splitting.
:param split_respect_sentence_boundary: Whether to split in partial sentences if split_by -> `word`. If set
to True, the individual split will always have complete sentences &
the number of words will be <= split_length.
|
:param clean_header_footer: Use heuristic to remove footers and headers across different pages by searching
for the longest common string. This heuristic uses exact matches and therefore
works well for footers like "Copyright 2019 by XXX", but won't detect "Page 3 of 4"
or similar.
:param clean_whitespace: Strip whitespaces before or after each line in the text.
:param clean_empty_lines: Remove more than two empty lines in the text.
:param split_by: Unit for splitting the document. Can be "word", "sentence", or "passage". Set to None to disable splitting.
:param split_length: Max. number of the above split unit (e.g. words) that are allowed in one document. For instance, if n -> 10 & split_by ->
"sentence", then each output document will have 10 sentences.
:param split_overlap: Word overlap between two adjacent documents after a split.
Setting this to a positive number essentially enables the sliding window approach.
For example, if split_by -> `word`,
split_length -> 5 & split_overlap -> 2, then the splits would be like:
[w1 w2 w3 w4 w5, w4 w5 w6 w7 w8, w7 w8 w10 w11 w12].
Set the value to 0 to ensure there is no overlap among the documents after splitting.
:param split_respect_sentence_boundary: Whether to split in partial sentences if split_by -> `word`. If set
to True, the individual split will always have complete sentences &
the number of words will be <= split_length.
| def __init__(
self,
clean_whitespace: bool = True,
clean_header_footer: bool = False,
clean_empty_lines: bool = True,
split_by: str = "word",
split_length: int = 1000,
split_overlap: int = 0,
split_respect_sentence_boundary: bool = True,
):
"""
:param clean_header_footer: Use heuristic to remove footers and headers across different pages by searching
for the longest common string. This heuristic uses exact matches and therefore
works well for footers like "Copyright 2019 by XXX", but won't detect "Page 3 of 4"
or similar.
:param clean_whitespace: Strip whitespaces before or after each line in the text.
:param clean_empty_lines: Remove more than two empty lines in the text.
:param split_by: Unit for splitting the document. Can be "word", "sentence", or "passage". Set to None to disable splitting.
:param split_length: Max. number of the above split unit (e.g. words) that are allowed in one document. For instance, if n -> 10 & split_by ->
"sentence", then each output document will have 10 sentences.
:param split_overlap: Word overlap between two adjacent documents after a split.
Setting this to a positive number essentially enables the sliding window approach.
For example, if split_by -> `word`,
split_length -> 5 & split_overlap -> 2, then the splits would be like:
[w1 w2 w3 w4 w5, w4 w5 w6 w7 w8, w7 w8 w10 w11 w12].
Set the value to 0 to ensure there is no overlap among the documents after splitting.
:param split_respect_sentence_boundary: Whether to split in partial sentences if split_by -> `word`. If set
to True, the individual split will always have complete sentences &
the number of words will be <= split_length.
"""
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
self.clean_whitespace = clean_whitespace
self.clean_header_footer = clean_header_footer
self.clean_empty_lines = clean_empty_lines
self.split_by = split_by
self.split_length = split_length
self.split_overlap = split_overlap
self.split_respect_sentence_boundary = split_respect_sentence_boundary | [
"def",
"__init__",
"(",
"self",
",",
"clean_whitespace",
":",
"bool",
"=",
"True",
",",
"clean_header_footer",
":",
"bool",
"=",
"False",
",",
"clean_empty_lines",
":",
"bool",
"=",
"True",
",",
"split_by",
":",
"str",
"=",
"\"word\"",
",",
"split_length",
":",
"int",
"=",
"1000",
",",
"split_overlap",
":",
"int",
"=",
"0",
",",
"split_respect_sentence_boundary",
":",
"bool",
"=",
"True",
",",
")",
":",
"try",
":",
"nltk",
".",
"data",
".",
"find",
"(",
"'tokenizers/punkt'",
")",
"except",
"LookupError",
":",
"nltk",
".",
"download",
"(",
"'punkt'",
")",
"self",
".",
"clean_whitespace",
"=",
"clean_whitespace",
"self",
".",
"clean_header_footer",
"=",
"clean_header_footer",
"self",
".",
"clean_empty_lines",
"=",
"clean_empty_lines",
"self",
".",
"split_by",
"=",
"split_by",
"self",
".",
"split_length",
"=",
"split_length",
"self",
".",
"split_overlap",
"=",
"split_overlap",
"self",
".",
"split_respect_sentence_boundary",
"=",
"split_respect_sentence_boundary"
] | [
16,
4
] | [
57,
78
] | python | en | ['en', 'error', 'th'] | False |
PreProcessor.process | (
self,
document: dict,
clean_whitespace: Optional[bool] = None,
clean_header_footer: Optional[bool] = None,
clean_empty_lines: Optional[bool] = None,
split_by: Optional[str] = None,
split_length: Optional[int] = None,
split_overlap: Optional[int] = None,
split_respect_sentence_boundary: Optional[bool] = None,
) |
Perform document cleaning and splitting. Takes a single document as input and returns a list of documents.
|
Perform document cleaning and splitting. Takes a single document as input and returns a list of documents.
| def process(
self,
document: dict,
clean_whitespace: Optional[bool] = None,
clean_header_footer: Optional[bool] = None,
clean_empty_lines: Optional[bool] = None,
split_by: Optional[str] = None,
split_length: Optional[int] = None,
split_overlap: Optional[int] = None,
split_respect_sentence_boundary: Optional[bool] = None,
) -> List[dict]:
"""
Perform document cleaning and splitting. Takes a single document as input and returns a list of documents.
"""
if clean_whitespace is None:
clean_whitespace = self.clean_whitespace
if clean_header_footer is None:
clean_header_footer = self.clean_header_footer
if clean_empty_lines is None:
clean_empty_lines = self.clean_empty_lines
if split_by is None:
split_by = self.split_by
if split_length is None:
split_length = self.split_length
if split_overlap is None:
split_overlap = self.split_overlap
if split_respect_sentence_boundary is None:
split_respect_sentence_boundary = self.split_respect_sentence_boundary
cleaned_document = self.clean(
document=document,
clean_whitespace=clean_whitespace,
clean_header_footer=clean_header_footer,
clean_empty_lines=clean_empty_lines,
)
split_documents = self.split(
document=cleaned_document,
split_by=split_by,
split_length=split_length,
split_overlap=split_overlap,
split_respect_sentence_boundary=split_respect_sentence_boundary,
)
return split_documents | [
"def",
"process",
"(",
"self",
",",
"document",
":",
"dict",
",",
"clean_whitespace",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"clean_header_footer",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"clean_empty_lines",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"split_by",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"split_length",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"split_overlap",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"split_respect_sentence_boundary",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"if",
"clean_whitespace",
"is",
"None",
":",
"clean_whitespace",
"=",
"self",
".",
"clean_whitespace",
"if",
"clean_header_footer",
"is",
"None",
":",
"clean_header_footer",
"=",
"self",
".",
"clean_header_footer",
"if",
"clean_empty_lines",
"is",
"None",
":",
"clean_empty_lines",
"=",
"self",
".",
"clean_empty_lines",
"if",
"split_by",
"is",
"None",
":",
"split_by",
"=",
"self",
".",
"split_by",
"if",
"split_length",
"is",
"None",
":",
"split_length",
"=",
"self",
".",
"split_length",
"if",
"split_overlap",
"is",
"None",
":",
"split_overlap",
"=",
"self",
".",
"split_overlap",
"if",
"split_respect_sentence_boundary",
"is",
"None",
":",
"split_respect_sentence_boundary",
"=",
"self",
".",
"split_respect_sentence_boundary",
"cleaned_document",
"=",
"self",
".",
"clean",
"(",
"document",
"=",
"document",
",",
"clean_whitespace",
"=",
"clean_whitespace",
",",
"clean_header_footer",
"=",
"clean_header_footer",
",",
"clean_empty_lines",
"=",
"clean_empty_lines",
",",
")",
"split_documents",
"=",
"self",
".",
"split",
"(",
"document",
"=",
"cleaned_document",
",",
"split_by",
"=",
"split_by",
",",
"split_length",
"=",
"split_length",
",",
"split_overlap",
"=",
"split_overlap",
",",
"split_respect_sentence_boundary",
"=",
"split_respect_sentence_boundary",
",",
")",
"return",
"split_documents"
] | [
59,
4
] | [
101,
30
] | python | en | ['en', 'error', 'th'] | False |
PreProcessor.clean | (
self,
document: dict,
clean_whitespace: bool,
clean_header_footer: bool,
clean_empty_lines: bool,
) |
Perform document cleaning on a single document and return a single document. This method will deal with whitespaces, headers, footers
and empty lines. Its exact functionality is defined by the parameters passed into PreProcessor.__init__().
|
Perform document cleaning on a single document and return a single document. This method will deal with whitespaces, headers, footers
and empty lines. Its exact functionality is defined by the parameters passed into PreProcessor.__init__().
| def clean(
self,
document: dict,
clean_whitespace: bool,
clean_header_footer: bool,
clean_empty_lines: bool,
) -> dict:
"""
Perform document cleaning on a single document and return a single document. This method will deal with whitespaces, headers, footers
and empty lines. Its exact functionality is defined by the parameters passed into PreProcessor.__init__().
"""
text = document["text"]
if clean_header_footer:
text = self._find_and_remove_header_footer(
text, n_chars=300, n_first_pages_to_ignore=1, n_last_pages_to_ignore=1
)
if clean_whitespace:
lines = text.splitlines()
cleaned_lines = []
for line in lines:
line = line.strip()
cleaned_lines.append(line)
text = "\n".join(cleaned_lines)
if clean_empty_lines:
text = re.sub(r"\n\n+", "\n\n", text)
document["text"] = text
return document | [
"def",
"clean",
"(",
"self",
",",
"document",
":",
"dict",
",",
"clean_whitespace",
":",
"bool",
",",
"clean_header_footer",
":",
"bool",
",",
"clean_empty_lines",
":",
"bool",
",",
")",
"->",
"dict",
":",
"text",
"=",
"document",
"[",
"\"text\"",
"]",
"if",
"clean_header_footer",
":",
"text",
"=",
"self",
".",
"_find_and_remove_header_footer",
"(",
"text",
",",
"n_chars",
"=",
"300",
",",
"n_first_pages_to_ignore",
"=",
"1",
",",
"n_last_pages_to_ignore",
"=",
"1",
")",
"if",
"clean_whitespace",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"cleaned_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"cleaned_lines",
".",
"append",
"(",
"line",
")",
"text",
"=",
"\"\\n\"",
".",
"join",
"(",
"cleaned_lines",
")",
"if",
"clean_empty_lines",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"\\n\\n+\"",
",",
"\"\\n\\n\"",
",",
"text",
")",
"document",
"[",
"\"text\"",
"]",
"=",
"text",
"return",
"document"
] | [
103,
4
] | [
133,
23
] | python | en | ['en', 'error', 'th'] | False |
PreProcessor.split | (
self,
document: dict,
split_by: str,
split_length: int,
split_overlap: int,
split_respect_sentence_boundary: bool,
) | Perform document splitting on a single document. This method can split on different units, at different lengths,
with different strides. It can also respect sentence boundaries. Its exact functionality is defined by
the parameters passed into PreProcessor.__init__(). Takes a single document as input and returns a list of documents. | Perform document splitting on a single document. This method can split on different units, at different lengths,
with different strides. It can also respect sentence boundaries. Its exact functionality is defined by
the parameters passed into PreProcessor.__init__(). Takes a single document as input and returns a list of documents. | def split(
self,
document: dict,
split_by: str,
split_length: int,
split_overlap: int,
split_respect_sentence_boundary: bool,
) -> List[dict]:
"""Perform document splitting on a single document. This method can split on different units, at different lengths,
with different strides. It can also respect sentence boundaries. Its exact functionality is defined by
the parameters passed into PreProcessor.__init__(). Takes a single document as input and returns a list of documents. """
if not split_by:
return [document]
if not split_length:
raise Exception("split_length needs be set when using split_by.")
if split_respect_sentence_boundary and split_by not in("word","sentence"):
raise NotImplementedError("'split_respect_sentence_boundary=True' is only compatible with"
" split_by='word' or split_by='sentence'.")
text = document["text"]
if split_respect_sentence_boundary and split_by == "word":
# split by words ensuring no sub sentence splits
sentences = nltk.tokenize.sent_tokenize(text)
word_count = 0
list_splits = []
current_slice: List[str] = []
for sen in sentences:
current_word_count = len(sen.split(" "))
if current_word_count > split_length:
logger.warning(f"A sentence found with word count higher than the split length.")
if word_count + current_word_count > split_length:
list_splits.append(current_slice)
# Enable split_stride with split_by='word' while respecting sentence boundaries.
if split_overlap:
overlap = []
w_count = 0
for s in current_slice[::-1]:
sen_len = len(s.split(" "))
if w_count < split_overlap:
overlap.append(s)
w_count += sen_len
else:
break
current_slice = list(reversed(overlap))
word_count = w_count
else:
current_slice = []
word_count = 0
current_slice.append(sen)
word_count += len(sen.split(" "))
if current_slice:
list_splits.append(current_slice)
text_splits = []
for sl in list_splits:
txt = ' '.join(sl)
if len(txt) > 0:
text_splits.append(txt)
else:
# create individual "elements" of passage, sentence, or word
if split_by == "passage":
elements = text.split("\n\n")
elif split_by == "sentence":
elements = nltk.tokenize.sent_tokenize(text)
elif split_by == "word":
elements = text.split(" ")
else:
raise NotImplementedError("PreProcessor only supports 'passage', 'sentence' or 'word' split_by options.")
# concatenate individual elements based on split_length & split_stride
if split_overlap:
segments = windowed(elements, n=split_length, step=split_length - split_overlap)
else:
segments = windowed(elements, n=split_length, step=split_length)
text_splits = []
for seg in segments:
txt = " ".join([t for t in seg if t])
if len(txt) > 0:
text_splits.append(txt)
# create new document dicts for each text split
documents = []
for i, txt in enumerate(text_splits):
doc = deepcopy(document)
doc["text"] = txt
if "meta" not in doc.keys() or doc["meta"] is None:
doc["meta"] = {}
doc["meta"]["_split_id"] = i
documents.append(doc)
return documents | [
"def",
"split",
"(",
"self",
",",
"document",
":",
"dict",
",",
"split_by",
":",
"str",
",",
"split_length",
":",
"int",
",",
"split_overlap",
":",
"int",
",",
"split_respect_sentence_boundary",
":",
"bool",
",",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"if",
"not",
"split_by",
":",
"return",
"[",
"document",
"]",
"if",
"not",
"split_length",
":",
"raise",
"Exception",
"(",
"\"split_length needs be set when using split_by.\"",
")",
"if",
"split_respect_sentence_boundary",
"and",
"split_by",
"not",
"in",
"(",
"\"word\"",
",",
"\"sentence\"",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"'split_respect_sentence_boundary=True' is only compatible with\"",
"\" split_by='word' or split_by='sentence'.\"",
")",
"text",
"=",
"document",
"[",
"\"text\"",
"]",
"if",
"split_respect_sentence_boundary",
"and",
"split_by",
"==",
"\"word\"",
":",
"# split by words ensuring no sub sentence splits",
"sentences",
"=",
"nltk",
".",
"tokenize",
".",
"sent_tokenize",
"(",
"text",
")",
"word_count",
"=",
"0",
"list_splits",
"=",
"[",
"]",
"current_slice",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"for",
"sen",
"in",
"sentences",
":",
"current_word_count",
"=",
"len",
"(",
"sen",
".",
"split",
"(",
"\" \"",
")",
")",
"if",
"current_word_count",
">",
"split_length",
":",
"logger",
".",
"warning",
"(",
"f\"A sentence found with word count higher than the split length.\"",
")",
"if",
"word_count",
"+",
"current_word_count",
">",
"split_length",
":",
"list_splits",
".",
"append",
"(",
"current_slice",
")",
"# Enable split_stride with split_by='word' while respecting sentence boundaries.",
"if",
"split_overlap",
":",
"overlap",
"=",
"[",
"]",
"w_count",
"=",
"0",
"for",
"s",
"in",
"current_slice",
"[",
":",
":",
"-",
"1",
"]",
":",
"sen_len",
"=",
"len",
"(",
"s",
".",
"split",
"(",
"\" \"",
")",
")",
"if",
"w_count",
"<",
"split_overlap",
":",
"overlap",
".",
"append",
"(",
"s",
")",
"w_count",
"+=",
"sen_len",
"else",
":",
"break",
"current_slice",
"=",
"list",
"(",
"reversed",
"(",
"overlap",
")",
")",
"word_count",
"=",
"w_count",
"else",
":",
"current_slice",
"=",
"[",
"]",
"word_count",
"=",
"0",
"current_slice",
".",
"append",
"(",
"sen",
")",
"word_count",
"+=",
"len",
"(",
"sen",
".",
"split",
"(",
"\" \"",
")",
")",
"if",
"current_slice",
":",
"list_splits",
".",
"append",
"(",
"current_slice",
")",
"text_splits",
"=",
"[",
"]",
"for",
"sl",
"in",
"list_splits",
":",
"txt",
"=",
"' '",
".",
"join",
"(",
"sl",
")",
"if",
"len",
"(",
"txt",
")",
">",
"0",
":",
"text_splits",
".",
"append",
"(",
"txt",
")",
"else",
":",
"# create individual \"elements\" of passage, sentence, or word",
"if",
"split_by",
"==",
"\"passage\"",
":",
"elements",
"=",
"text",
".",
"split",
"(",
"\"\\n\\n\"",
")",
"elif",
"split_by",
"==",
"\"sentence\"",
":",
"elements",
"=",
"nltk",
".",
"tokenize",
".",
"sent_tokenize",
"(",
"text",
")",
"elif",
"split_by",
"==",
"\"word\"",
":",
"elements",
"=",
"text",
".",
"split",
"(",
"\" \"",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"PreProcessor only supports 'passage', 'sentence' or 'word' split_by options.\"",
")",
"# concatenate individual elements based on split_length & split_stride",
"if",
"split_overlap",
":",
"segments",
"=",
"windowed",
"(",
"elements",
",",
"n",
"=",
"split_length",
",",
"step",
"=",
"split_length",
"-",
"split_overlap",
")",
"else",
":",
"segments",
"=",
"windowed",
"(",
"elements",
",",
"n",
"=",
"split_length",
",",
"step",
"=",
"split_length",
")",
"text_splits",
"=",
"[",
"]",
"for",
"seg",
"in",
"segments",
":",
"txt",
"=",
"\" \"",
".",
"join",
"(",
"[",
"t",
"for",
"t",
"in",
"seg",
"if",
"t",
"]",
")",
"if",
"len",
"(",
"txt",
")",
">",
"0",
":",
"text_splits",
".",
"append",
"(",
"txt",
")",
"# create new document dicts for each text split",
"documents",
"=",
"[",
"]",
"for",
"i",
",",
"txt",
"in",
"enumerate",
"(",
"text_splits",
")",
":",
"doc",
"=",
"deepcopy",
"(",
"document",
")",
"doc",
"[",
"\"text\"",
"]",
"=",
"txt",
"if",
"\"meta\"",
"not",
"in",
"doc",
".",
"keys",
"(",
")",
"or",
"doc",
"[",
"\"meta\"",
"]",
"is",
"None",
":",
"doc",
"[",
"\"meta\"",
"]",
"=",
"{",
"}",
"doc",
"[",
"\"meta\"",
"]",
"[",
"\"_split_id\"",
"]",
"=",
"i",
"documents",
".",
"append",
"(",
"doc",
")",
"return",
"documents"
] | [
135,
4
] | [
229,
24
] | python | en | ['en', 'en', 'en'] | True |
PreProcessor._find_and_remove_header_footer | (
self, text: str, n_chars: int, n_first_pages_to_ignore: int, n_last_pages_to_ignore: int
) |
Heuristic to find footers and headers across different pages by searching for the longest common string.
For headers we only search in the first n_chars characters (for footer: last n_chars).
Note: This heuristic uses exact matches and therefore works well for footers like "Copyright 2019 by XXX",
but won't detect "Page 3 of 4" or similar.
:param n_chars: number of first/last characters where the header/footer shall be searched in
:param n_first_pages_to_ignore: number of first pages to ignore (e.g. TOCs often don't contain footer/header)
:param n_last_pages_to_ignore: number of last pages to ignore
:return: (cleaned pages, found_header_str, found_footer_str)
|
Heuristic to find footers and headers across different pages by searching for the longest common string.
For headers we only search in the first n_chars characters (for footer: last n_chars).
Note: This heuristic uses exact matches and therefore works well for footers like "Copyright 2019 by XXX",
but won't detect "Page 3 of 4" or similar. | def _find_and_remove_header_footer(
self, text: str, n_chars: int, n_first_pages_to_ignore: int, n_last_pages_to_ignore: int
) -> str:
"""
Heuristic to find footers and headers across different pages by searching for the longest common string.
For headers we only search in the first n_chars characters (for footer: last n_chars).
Note: This heuristic uses exact matches and therefore works well for footers like "Copyright 2019 by XXX",
but won't detect "Page 3 of 4" or similar.
:param n_chars: number of first/last characters where the header/footer shall be searched in
:param n_first_pages_to_ignore: number of first pages to ignore (e.g. TOCs often don't contain footer/header)
:param n_last_pages_to_ignore: number of last pages to ignore
:return: (cleaned pages, found_header_str, found_footer_str)
"""
pages = text.split("\f")
# header
start_of_pages = [p[:n_chars] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]]
found_header = self._find_longest_common_ngram(start_of_pages)
if found_header:
pages = [page.replace(found_header, "") for page in pages]
# footer
end_of_pages = [p[-n_chars:] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]]
found_footer = self._find_longest_common_ngram(end_of_pages)
if found_footer:
pages = [page.replace(found_footer, "") for page in pages]
logger.debug(f"Removed header '{found_header}' and footer '{found_footer}' in document")
text = "\f".join(pages)
return text | [
"def",
"_find_and_remove_header_footer",
"(",
"self",
",",
"text",
":",
"str",
",",
"n_chars",
":",
"int",
",",
"n_first_pages_to_ignore",
":",
"int",
",",
"n_last_pages_to_ignore",
":",
"int",
")",
"->",
"str",
":",
"pages",
"=",
"text",
".",
"split",
"(",
"\"\\f\"",
")",
"# header",
"start_of_pages",
"=",
"[",
"p",
"[",
":",
"n_chars",
"]",
"for",
"p",
"in",
"pages",
"[",
"n_first_pages_to_ignore",
":",
"-",
"n_last_pages_to_ignore",
"]",
"]",
"found_header",
"=",
"self",
".",
"_find_longest_common_ngram",
"(",
"start_of_pages",
")",
"if",
"found_header",
":",
"pages",
"=",
"[",
"page",
".",
"replace",
"(",
"found_header",
",",
"\"\"",
")",
"for",
"page",
"in",
"pages",
"]",
"# footer",
"end_of_pages",
"=",
"[",
"p",
"[",
"-",
"n_chars",
":",
"]",
"for",
"p",
"in",
"pages",
"[",
"n_first_pages_to_ignore",
":",
"-",
"n_last_pages_to_ignore",
"]",
"]",
"found_footer",
"=",
"self",
".",
"_find_longest_common_ngram",
"(",
"end_of_pages",
")",
"if",
"found_footer",
":",
"pages",
"=",
"[",
"page",
".",
"replace",
"(",
"found_footer",
",",
"\"\"",
")",
"for",
"page",
"in",
"pages",
"]",
"logger",
".",
"debug",
"(",
"f\"Removed header '{found_header}' and footer '{found_footer}' in document\"",
")",
"text",
"=",
"\"\\f\"",
".",
"join",
"(",
"pages",
")",
"return",
"text"
] | [
231,
4
] | [
261,
19
] | python | en | ['en', 'error', 'th'] | False |
PreProcessor._ngram | (self, seq: str, n: int) |
Return ngram (of tokens - currently split by whitespace)
:param seq: str, string from which the ngram shall be created
:param n: int, n of ngram
:return: str, ngram as string
|
Return ngram (of tokens - currently split by whitespace)
:param seq: str, string from which the ngram shall be created
:param n: int, n of ngram
:return: str, ngram as string
| def _ngram(self, seq: str, n: int) -> Generator[str, None, None]:
"""
Return ngram (of tokens - currently split by whitespace)
:param seq: str, string from which the ngram shall be created
:param n: int, n of ngram
:return: str, ngram as string
"""
# In order to maintain the original whitespace, but still consider \n and \t for n-gram tokenization,
# we add a space here and remove it after creation of the ngrams again (see below)
seq = seq.replace("\n", " \n")
seq = seq.replace("\t", " \t")
words = seq.split(" ")
ngrams = (
" ".join(words[i : i + n]).replace(" \n", "\n").replace(" \t", "\t") for i in range(0, len(words) - n + 1)
)
return ngrams | [
"def",
"_ngram",
"(",
"self",
",",
"seq",
":",
"str",
",",
"n",
":",
"int",
")",
"->",
"Generator",
"[",
"str",
",",
"None",
",",
"None",
"]",
":",
"# In order to maintain the original whitespace, but still consider \\n and \\t for n-gram tokenization,",
"# we add a space here and remove it after creation of the ngrams again (see below)",
"seq",
"=",
"seq",
".",
"replace",
"(",
"\"\\n\"",
",",
"\" \\n\"",
")",
"seq",
"=",
"seq",
".",
"replace",
"(",
"\"\\t\"",
",",
"\" \\t\"",
")",
"words",
"=",
"seq",
".",
"split",
"(",
"\" \"",
")",
"ngrams",
"=",
"(",
"\" \"",
".",
"join",
"(",
"words",
"[",
"i",
":",
"i",
"+",
"n",
"]",
")",
".",
"replace",
"(",
"\" \\n\"",
",",
"\"\\n\"",
")",
".",
"replace",
"(",
"\" \\t\"",
",",
"\"\\t\"",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"words",
")",
"-",
"n",
"+",
"1",
")",
")",
"return",
"ngrams"
] | [
263,
4
] | [
281,
21
] | python | en | ['en', 'error', 'th'] | False |
PreProcessor._find_longest_common_ngram | (
self, sequences: List[str], max_ngram: int = 30, min_ngram: int = 3
) |
Find the longest common ngram across different text sequences (e.g. start of pages).
Considering all ngrams between the specified range. Helpful for finding footers, headers etc.
:param sequences: list[str], list of strings that shall be searched for common n_grams
:param max_ngram: int, maximum length of ngram to consider
:param min_ngram: minimum length of ngram to consider
:return: str, common string of all sections
|
Find the longest common ngram across different text sequences (e.g. start of pages).
Considering all ngrams between the specified range. Helpful for finding footers, headers etc. | def _find_longest_common_ngram(
self, sequences: List[str], max_ngram: int = 30, min_ngram: int = 3
) -> Optional[str]:
"""
Find the longest common ngram across different text sequences (e.g. start of pages).
Considering all ngrams between the specified range. Helpful for finding footers, headers etc.
:param sequences: list[str], list of strings that shall be searched for common n_grams
:param max_ngram: int, maximum length of ngram to consider
:param min_ngram: minimum length of ngram to consider
:return: str, common string of all sections
"""
sequences = [s for s in sequences if s] # filter empty sequences
if not sequences:
return None
seqs_ngrams = map(partial(self._allngram, min_ngram=min_ngram, max_ngram=max_ngram), sequences)
intersection = reduce(set.intersection, seqs_ngrams)
try:
longest = max(intersection, key=len)
except ValueError:
# no common sequence found
longest = ""
return longest if longest.strip() else None | [
"def",
"_find_longest_common_ngram",
"(",
"self",
",",
"sequences",
":",
"List",
"[",
"str",
"]",
",",
"max_ngram",
":",
"int",
"=",
"30",
",",
"min_ngram",
":",
"int",
"=",
"3",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"sequences",
"=",
"[",
"s",
"for",
"s",
"in",
"sequences",
"if",
"s",
"]",
"# filter empty sequences",
"if",
"not",
"sequences",
":",
"return",
"None",
"seqs_ngrams",
"=",
"map",
"(",
"partial",
"(",
"self",
".",
"_allngram",
",",
"min_ngram",
"=",
"min_ngram",
",",
"max_ngram",
"=",
"max_ngram",
")",
",",
"sequences",
")",
"intersection",
"=",
"reduce",
"(",
"set",
".",
"intersection",
",",
"seqs_ngrams",
")",
"try",
":",
"longest",
"=",
"max",
"(",
"intersection",
",",
"key",
"=",
"len",
")",
"except",
"ValueError",
":",
"# no common sequence found",
"longest",
"=",
"\"\"",
"return",
"longest",
"if",
"longest",
".",
"strip",
"(",
")",
"else",
"None"
] | [
289,
4
] | [
312,
51
] | python | en | ['en', 'error', 'th'] | False |
bob_columnar_table_multi_batch | () |
About the "Bob" User Workflow Fixture
Bob is working with monthly batches of taxi fare data. His data has the following columns:vendor_id,pickup_datetime,dropoff_datetime,passenger_count,trip_distance,rate_code_id,store_and_fwd_flag,pickup_location_id,dropoff_location_id,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount,congestion_surcharge
He wants to check periodically and as new data is added. Similar to Alice:
- He knows what some of the columns mean, but not all - and there are MANY of them (only a subset currently shown in examples and fixtures).
- He can assume that all batches share the same structure.
- There are some columns which share characteristics so he would like to apply the same set of expectations to them.
But he also:
- Wants to verify that the latest batches are not so different from all of the batches last year, if they are he wants to be alerted as maybe there are data collection issues or fares have changed significantly.
Bob configures his Profiler using the yaml configurations and data file locations captured in this fixture.
|
About the "Bob" User Workflow Fixture | def bob_columnar_table_multi_batch():
"""
About the "Bob" User Workflow Fixture
Bob is working with monthly batches of taxi fare data. His data has the following columns:vendor_id,pickup_datetime,dropoff_datetime,passenger_count,trip_distance,rate_code_id,store_and_fwd_flag,pickup_location_id,dropoff_location_id,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount,congestion_surcharge
He wants to check periodically and as new data is added. Similar to Alice:
- He knows what some of the columns mean, but not all - and there are MANY of them (only a subset currently shown in examples and fixtures).
- He can assume that all batches share the same structure.
- There are some columns which share characteristics so he would like to apply the same set of expectations to them.
But he also:
- Wants to verify that the latest batches are not so different from all of the batches last year, if they are he wants to be alerted as maybe there are data collection issues or fares have changed significantly.
Bob configures his Profiler using the yaml configurations and data file locations captured in this fixture.
"""
with open("bob_user_workflow_verbose_profiler_config.yml") as f:
verbose_profiler_config = f.read()
profiler_configs: List[str] = []
profiler_configs.append(verbose_profiler_config)
return {"profiler_configs": profiler_configs} | [
"def",
"bob_columnar_table_multi_batch",
"(",
")",
":",
"with",
"open",
"(",
"\"bob_user_workflow_verbose_profiler_config.yml\"",
")",
"as",
"f",
":",
"verbose_profiler_config",
"=",
"f",
".",
"read",
"(",
")",
"profiler_configs",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"profiler_configs",
".",
"append",
"(",
"verbose_profiler_config",
")",
"return",
"{",
"\"profiler_configs\"",
":",
"profiler_configs",
"}"
] | [
6,
0
] | [
33,
49
] | python | en | ['en', 'error', 'th'] | False |
BaseSummarizer.predict | (self, documents: List[Document], generate_single_summary: bool = False) |
Abstract method for creating a summary.
:param documents: Related documents (e.g. coming from a retriever) that the answer shall be conditioned on.
:param generate_single_summary: Whether to generate a single summary for all documents or one summary per document.
If set to "True", all docs will be joined to a single string that will then
be summarized.
Important: The summary will depend on the order of the supplied documents!
:return: List of Documents, where Document.text contains the summarization and Document.meta["context"]
the original, not summarized text
|
Abstract method for creating a summary. | def predict(self, documents: List[Document], generate_single_summary: bool = False) -> List[Document]:
"""
Abstract method for creating a summary.
:param documents: Related documents (e.g. coming from a retriever) that the answer shall be conditioned on.
:param generate_single_summary: Whether to generate a single summary for all documents or one summary per document.
If set to "True", all docs will be joined to a single string that will then
be summarized.
Important: The summary will depend on the order of the supplied documents!
:return: List of Documents, where Document.text contains the summarization and Document.meta["context"]
the original, not summarized text
"""
pass | [
"def",
"predict",
"(",
"self",
",",
"documents",
":",
"List",
"[",
"Document",
"]",
",",
"generate_single_summary",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"Document",
"]",
":",
"pass"
] | [
14,
4
] | [
26,
12
] | python | en | ['en', 'error', 'th'] | False |
SqlAlchemyDatasource.build_configuration | (
cls, data_asset_type=None, batch_kwargs_generators=None, **kwargs
) |
Build a full configuration object for a datasource, potentially including generators with defaults.
Args:
data_asset_type: A ClassConfig dictionary
batch_kwargs_generators: Generator configuration dictionary
**kwargs: Additional kwargs to be part of the datasource constructor's initialization
Returns:
A complete datasource configuration.
|
Build a full configuration object for a datasource, potentially including generators with defaults. | def build_configuration(
cls, data_asset_type=None, batch_kwargs_generators=None, **kwargs
):
"""
Build a full configuration object for a datasource, potentially including generators with defaults.
Args:
data_asset_type: A ClassConfig dictionary
batch_kwargs_generators: Generator configuration dictionary
**kwargs: Additional kwargs to be part of the datasource constructor's initialization
Returns:
A complete datasource configuration.
"""
if data_asset_type is None:
data_asset_type = {
"class_name": "SqlAlchemyDataset",
"module_name": "great_expectations.dataset",
}
else:
data_asset_type = classConfigSchema.dump(ClassConfig(**data_asset_type))
configuration = kwargs
configuration["data_asset_type"] = data_asset_type
if batch_kwargs_generators is not None:
configuration["batch_kwargs_generators"] = batch_kwargs_generators
return configuration | [
"def",
"build_configuration",
"(",
"cls",
",",
"data_asset_type",
"=",
"None",
",",
"batch_kwargs_generators",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data_asset_type",
"is",
"None",
":",
"data_asset_type",
"=",
"{",
"\"class_name\"",
":",
"\"SqlAlchemyDataset\"",
",",
"\"module_name\"",
":",
"\"great_expectations.dataset\"",
",",
"}",
"else",
":",
"data_asset_type",
"=",
"classConfigSchema",
".",
"dump",
"(",
"ClassConfig",
"(",
"*",
"*",
"data_asset_type",
")",
")",
"configuration",
"=",
"kwargs",
"configuration",
"[",
"\"data_asset_type\"",
"]",
"=",
"data_asset_type",
"if",
"batch_kwargs_generators",
"is",
"not",
"None",
":",
"configuration",
"[",
"\"batch_kwargs_generators\"",
"]",
"=",
"batch_kwargs_generators",
"return",
"configuration"
] | [
171,
4
] | [
200,
28
] | python | en | ['en', 'error', 'th'] | False |
TikaConverter.__init__ | (
self,
tika_url: str = "http://localhost:9998/tika",
remove_numeric_tables: bool = False,
valid_languages: Optional[List[str]] = None
) |
:param tika_url: URL of the Tika server
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
|
:param tika_url: URL of the Tika server
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
| def __init__(
self,
tika_url: str = "http://localhost:9998/tika",
remove_numeric_tables: bool = False,
valid_languages: Optional[List[str]] = None
):
"""
:param tika_url: URL of the Tika server
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
"""
ping = requests.get(tika_url)
if ping.status_code != 200:
raise Exception(f"Apache Tika server is not reachable at the URL '{tika_url}'. To run it locally"
f"with Docker, execute: 'docker run -p 9998:9998 apache/tika:1.24.1'")
self.tika_url = tika_url
super().__init__(remove_numeric_tables=remove_numeric_tables, valid_languages=valid_languages) | [
"def",
"__init__",
"(",
"self",
",",
"tika_url",
":",
"str",
"=",
"\"http://localhost:9998/tika\"",
",",
"remove_numeric_tables",
":",
"bool",
"=",
"False",
",",
"valid_languages",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
":",
"ping",
"=",
"requests",
".",
"get",
"(",
"tika_url",
")",
"if",
"ping",
".",
"status_code",
"!=",
"200",
":",
"raise",
"Exception",
"(",
"f\"Apache Tika server is not reachable at the URL '{tika_url}'. To run it locally\"",
"f\"with Docker, execute: 'docker run -p 9998:9998 apache/tika:1.24.1'\"",
")",
"self",
".",
"tika_url",
"=",
"tika_url",
"super",
"(",
")",
".",
"__init__",
"(",
"remove_numeric_tables",
"=",
"remove_numeric_tables",
",",
"valid_languages",
"=",
"valid_languages",
")"
] | [
41,
4
] | [
65,
102
] | python | en | ['en', 'error', 'th'] | False |
TikaConverter.convert | (
self,
file_path: Path,
meta: Optional[Dict[str, str]] = None,
remove_numeric_tables: Optional[bool] = None,
valid_languages: Optional[List[str]] = None,
) |
:param file_path: path of the file to convert
:param meta: dictionary of meta data key-value pairs to append in the returned document.
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
:return: a list of pages and the extracted meta data of the file.
|
:param file_path: path of the file to convert
:param meta: dictionary of meta data key-value pairs to append in the returned document.
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text. | def convert(
self,
file_path: Path,
meta: Optional[Dict[str, str]] = None,
remove_numeric_tables: Optional[bool] = None,
valid_languages: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""
:param file_path: path of the file to convert
:param meta: dictionary of meta data key-value pairs to append in the returned document.
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
:return: a list of pages and the extracted meta data of the file.
"""
if remove_numeric_tables is None:
remove_numeric_tables = self.remove_numeric_tables
if valid_languages is None:
valid_languages = self.valid_languages
parsed = tikaparser.from_file(file_path.as_posix(), self.tika_url, xmlContent=True)
parser = TikaXHTMLParser()
parser.feed(parsed["content"])
cleaned_pages = []
# TODO investigate title of document appearing in the first extracted page
for page in parser.pages:
lines = page.splitlines()
cleaned_lines = []
for line in lines:
words = line.split()
digits = [word for word in words if any(i.isdigit() for i in word)]
# remove lines having > 40% of words as digits AND not ending with a period(.)
if remove_numeric_tables:
if words and len(digits) / len(words) > 0.4 and not line.strip().endswith("."):
logger.debug(f"Removing line '{line}' from {file_path}")
continue
cleaned_lines.append(line)
page = "\n".join(cleaned_lines)
cleaned_pages.append(page)
if valid_languages:
document_text = "".join(cleaned_pages)
if not self.validate_language(document_text):
logger.warning(
f"The language for {file_path} is not one of {valid_languages}. The file may not have "
f"been decoded in the correct text format."
)
text = "\f".join(cleaned_pages)
document = {"text": text, "meta": {**parsed["metadata"], **(meta or {})}}
return document | [
"def",
"convert",
"(",
"self",
",",
"file_path",
":",
"Path",
",",
"meta",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
",",
"remove_numeric_tables",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"valid_languages",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"remove_numeric_tables",
"is",
"None",
":",
"remove_numeric_tables",
"=",
"self",
".",
"remove_numeric_tables",
"if",
"valid_languages",
"is",
"None",
":",
"valid_languages",
"=",
"self",
".",
"valid_languages",
"parsed",
"=",
"tikaparser",
".",
"from_file",
"(",
"file_path",
".",
"as_posix",
"(",
")",
",",
"self",
".",
"tika_url",
",",
"xmlContent",
"=",
"True",
")",
"parser",
"=",
"TikaXHTMLParser",
"(",
")",
"parser",
".",
"feed",
"(",
"parsed",
"[",
"\"content\"",
"]",
")",
"cleaned_pages",
"=",
"[",
"]",
"# TODO investigate title of document appearing in the first extracted page",
"for",
"page",
"in",
"parser",
".",
"pages",
":",
"lines",
"=",
"page",
".",
"splitlines",
"(",
")",
"cleaned_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"words",
"=",
"line",
".",
"split",
"(",
")",
"digits",
"=",
"[",
"word",
"for",
"word",
"in",
"words",
"if",
"any",
"(",
"i",
".",
"isdigit",
"(",
")",
"for",
"i",
"in",
"word",
")",
"]",
"# remove lines having > 40% of words as digits AND not ending with a period(.)",
"if",
"remove_numeric_tables",
":",
"if",
"words",
"and",
"len",
"(",
"digits",
")",
"/",
"len",
"(",
"words",
")",
">",
"0.4",
"and",
"not",
"line",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"\".\"",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Removing line '{line}' from {file_path}\"",
")",
"continue",
"cleaned_lines",
".",
"append",
"(",
"line",
")",
"page",
"=",
"\"\\n\"",
".",
"join",
"(",
"cleaned_lines",
")",
"cleaned_pages",
".",
"append",
"(",
"page",
")",
"if",
"valid_languages",
":",
"document_text",
"=",
"\"\"",
".",
"join",
"(",
"cleaned_pages",
")",
"if",
"not",
"self",
".",
"validate_language",
"(",
"document_text",
")",
":",
"logger",
".",
"warning",
"(",
"f\"The language for {file_path} is not one of {valid_languages}. The file may not have \"",
"f\"been decoded in the correct text format.\"",
")",
"text",
"=",
"\"\\f\"",
".",
"join",
"(",
"cleaned_pages",
")",
"document",
"=",
"{",
"\"text\"",
":",
"text",
",",
"\"meta\"",
":",
"{",
"*",
"*",
"parsed",
"[",
"\"metadata\"",
"]",
",",
"*",
"*",
"(",
"meta",
"or",
"{",
"}",
")",
"}",
"}",
"return",
"document"
] | [
67,
4
] | [
129,
23
] | python | en | ['en', 'error', 'th'] | False |
DocxToTextConverter.convert | (
self,
file_path: Path,
meta: Optional[Dict[str, str]] = None,
remove_numeric_tables: Optional[bool] = None,
valid_languages: Optional[List[str]] = None,
) |
Extract text from a .docx file.
Note: As docx doesn't contain "page" information, we actually extract and return a list of paragraphs here.
For compliance with other converters we nevertheless opted for keeping the methods name.
:param file_path: Path to the .docx file you want to convert
:param meta: dictionary of meta data key-value pairs to append in the returned document.
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
|
Extract text from a .docx file.
Note: As docx doesn't contain "page" information, we actually extract and return a list of paragraphs here.
For compliance with other converters we nevertheless opted for keeping the methods name. | def convert(
self,
file_path: Path,
meta: Optional[Dict[str, str]] = None,
remove_numeric_tables: Optional[bool] = None,
valid_languages: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""
Extract text from a .docx file.
Note: As docx doesn't contain "page" information, we actually extract and return a list of paragraphs here.
For compliance with other converters we nevertheless opted for keeping the methods name.
:param file_path: Path to the .docx file you want to convert
:param meta: dictionary of meta data key-value pairs to append in the returned document.
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables.
The tabular structures in documents might be noise for the reader model if it
does not have table parsing capability for finding answers. However, tables
may also have long strings that could possible candidate for searching answers.
The rows containing strings are thus retained in this option.
:param valid_languages: validate languages from a list of languages specified in the ISO 639-1
(https://en.wikipedia.org/wiki/ISO_639-1) format.
This option can be used to add test for encoding errors. If the extracted text is
not one of the valid languages, then it might likely be encoding error resulting
in garbled text.
"""
if remove_numeric_tables is None:
remove_numeric_tables = self.remove_numeric_tables
if valid_languages is None:
valid_languages = self.valid_languages
if remove_numeric_tables is True:
raise Exception("'remove_numeric_tables' is not supported by DocxToTextConverter.")
if valid_languages is True:
raise Exception("Language validation using 'valid_languages' is not supported by DocxToTextConverter.")
file = docx.Document(file_path) # Creating word reader object.
paragraphs = [para.text for para in file.paragraphs]
text = "".join(paragraphs)
document = {"text": text, "meta": meta}
return document | [
"def",
"convert",
"(",
"self",
",",
"file_path",
":",
"Path",
",",
"meta",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
",",
"remove_numeric_tables",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"valid_languages",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"remove_numeric_tables",
"is",
"None",
":",
"remove_numeric_tables",
"=",
"self",
".",
"remove_numeric_tables",
"if",
"valid_languages",
"is",
"None",
":",
"valid_languages",
"=",
"self",
".",
"valid_languages",
"if",
"remove_numeric_tables",
"is",
"True",
":",
"raise",
"Exception",
"(",
"\"'remove_numeric_tables' is not supported by DocxToTextConverter.\"",
")",
"if",
"valid_languages",
"is",
"True",
":",
"raise",
"Exception",
"(",
"\"Language validation using 'valid_languages' is not supported by DocxToTextConverter.\"",
")",
"file",
"=",
"docx",
".",
"Document",
"(",
"file_path",
")",
"# Creating word reader object.",
"paragraphs",
"=",
"[",
"para",
".",
"text",
"for",
"para",
"in",
"file",
".",
"paragraphs",
"]",
"text",
"=",
"\"\"",
".",
"join",
"(",
"paragraphs",
")",
"document",
"=",
"{",
"\"text\"",
":",
"text",
",",
"\"meta\"",
":",
"meta",
"}",
"return",
"document"
] | [
12,
4
] | [
50,
23
] | python | en | ['en', 'error', 'th'] | False |
ColumnDomainBuilder._get_domains | (
self,
variables: Optional[ParameterContainer] = None,
) |
Obtains and returns domains for all columns of a table.
|
Obtains and returns domains for all columns of a table.
| def _get_domains(
self,
variables: Optional[ParameterContainer] = None,
) -> List[Domain]:
"""
Obtains and returns domains for all columns of a table.
"""
batch_id: str = self.get_batch_id(variables=variables)
table_column_names: List[str] = self.get_validator(
variables=variables
).get_metric(
metric=MetricConfiguration(
metric_name="table.columns",
metric_domain_kwargs={
"batch_id": batch_id,
},
metric_value_kwargs=None,
metric_dependencies=None,
)
)
column_name: str
domains: List[Domain] = [
Domain(
domain_type=MetricDomainTypes.COLUMN,
domain_kwargs={
"column": column_name,
},
)
for column_name in table_column_names
]
return domains | [
"def",
"_get_domains",
"(",
"self",
",",
"variables",
":",
"Optional",
"[",
"ParameterContainer",
"]",
"=",
"None",
",",
")",
"->",
"List",
"[",
"Domain",
"]",
":",
"batch_id",
":",
"str",
"=",
"self",
".",
"get_batch_id",
"(",
"variables",
"=",
"variables",
")",
"table_column_names",
":",
"List",
"[",
"str",
"]",
"=",
"self",
".",
"get_validator",
"(",
"variables",
"=",
"variables",
")",
".",
"get_metric",
"(",
"metric",
"=",
"MetricConfiguration",
"(",
"metric_name",
"=",
"\"table.columns\"",
",",
"metric_domain_kwargs",
"=",
"{",
"\"batch_id\"",
":",
"batch_id",
",",
"}",
",",
"metric_value_kwargs",
"=",
"None",
",",
"metric_dependencies",
"=",
"None",
",",
")",
")",
"column_name",
":",
"str",
"domains",
":",
"List",
"[",
"Domain",
"]",
"=",
"[",
"Domain",
"(",
"domain_type",
"=",
"MetricDomainTypes",
".",
"COLUMN",
",",
"domain_kwargs",
"=",
"{",
"\"column\"",
":",
"column_name",
",",
"}",
",",
")",
"for",
"column_name",
"in",
"table_column_names",
"]",
"return",
"domains"
] | [
9,
4
] | [
41,
22
] | python | en | ['en', 'error', 'th'] | False |
BaseRLearner.__init__ | (self,
learner=None,
outcome_learner=None,
effect_learner=None,
propensity_learner=ElasticNetPropensityModel(),
ate_alpha=.05,
control_name=0,
n_fold=5,
random_state=None) | Initialize an R-learner.
Args:
learner (optional): a model to estimate outcomes and treatment effects
outcome_learner (optional): a model to estimate outcomes
effect_learner (optional): a model to estimate treatment effects. It needs to take `sample_weight` as an
input argument for `fit()`
propensity_learner (optional): a model to estimate propensity scores. `ElasticNetPropensityModel()` will
be used by default.
ate_alpha (float, optional): the confidence level alpha of the ATE estimate
control_name (str or int, optional): name of control group
n_fold (int, optional): the number of cross validation folds for outcome_learner
random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
| Initialize an R-learner. | def __init__(self,
learner=None,
outcome_learner=None,
effect_learner=None,
propensity_learner=ElasticNetPropensityModel(),
ate_alpha=.05,
control_name=0,
n_fold=5,
random_state=None):
"""Initialize an R-learner.
Args:
learner (optional): a model to estimate outcomes and treatment effects
outcome_learner (optional): a model to estimate outcomes
effect_learner (optional): a model to estimate treatment effects. It needs to take `sample_weight` as an
input argument for `fit()`
propensity_learner (optional): a model to estimate propensity scores. `ElasticNetPropensityModel()` will
be used by default.
ate_alpha (float, optional): the confidence level alpha of the ATE estimate
control_name (str or int, optional): name of control group
n_fold (int, optional): the number of cross validation folds for outcome_learner
random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
"""
assert (learner is not None) or ((outcome_learner is not None) and (effect_learner is not None))
assert propensity_learner is not None
self.model_mu = outcome_learner if outcome_learner is not None else deepcopy(learner)
self.model_tau = effect_learner if effect_learner is not None else deepcopy(learner)
self.model_p = propensity_learner
self.ate_alpha = ate_alpha
self.control_name = control_name
self.random_state = random_state
self.cv = KFold(n_splits=n_fold, shuffle=True, random_state=random_state)
self.propensity = None
self.propensity_model = None | [
"def",
"__init__",
"(",
"self",
",",
"learner",
"=",
"None",
",",
"outcome_learner",
"=",
"None",
",",
"effect_learner",
"=",
"None",
",",
"propensity_learner",
"=",
"ElasticNetPropensityModel",
"(",
")",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
",",
"n_fold",
"=",
"5",
",",
"random_state",
"=",
"None",
")",
":",
"assert",
"(",
"learner",
"is",
"not",
"None",
")",
"or",
"(",
"(",
"outcome_learner",
"is",
"not",
"None",
")",
"and",
"(",
"effect_learner",
"is",
"not",
"None",
")",
")",
"assert",
"propensity_learner",
"is",
"not",
"None",
"self",
".",
"model_mu",
"=",
"outcome_learner",
"if",
"outcome_learner",
"is",
"not",
"None",
"else",
"deepcopy",
"(",
"learner",
")",
"self",
".",
"model_tau",
"=",
"effect_learner",
"if",
"effect_learner",
"is",
"not",
"None",
"else",
"deepcopy",
"(",
"learner",
")",
"self",
".",
"model_p",
"=",
"propensity_learner",
"self",
".",
"ate_alpha",
"=",
"ate_alpha",
"self",
".",
"control_name",
"=",
"control_name",
"self",
".",
"random_state",
"=",
"random_state",
"self",
".",
"cv",
"=",
"KFold",
"(",
"n_splits",
"=",
"n_fold",
",",
"shuffle",
"=",
"True",
",",
"random_state",
"=",
"random_state",
")",
"self",
".",
"propensity",
"=",
"None",
"self",
".",
"propensity_model",
"=",
"None"
] | [
27,
4
] | [
64,
36
] | python | en | ['en', 'en', 'nl'] | True |
BaseRLearner.fit | (self, X, treatment, y, p=None, verbose=True) | Fit the treatment effect and outcome models of the R learner.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
verbose (bool, optional): whether to output progress logs
| Fit the treatment effect and outcome models of the R learner. | def fit(self, X, treatment, y, p=None, verbose=True):
"""Fit the treatment effect and outcome models of the R learner.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
verbose (bool, optional): whether to output progress logs
"""
X, treatment, y = convert_pd_to_np(X, treatment, y)
check_treatment_vector(treatment, self.control_name)
self.t_groups = np.unique(treatment[treatment != self.control_name])
self.t_groups.sort()
if p is None:
self._set_propensity_models(X=X, treatment=treatment, y=y)
p = self.propensity
else:
p = self._format_p(p, self.t_groups)
self._classes = {group: i for i, group in enumerate(self.t_groups)}
self.models_tau = {group: deepcopy(self.model_tau) for group in self.t_groups}
self.vars_c = {}
self.vars_t = {}
if verbose:
logger.info('generating out-of-fold CV outcome estimates')
yhat = cross_val_predict(self.model_mu, X, y, cv=self.cv, n_jobs=-1)
for group in self.t_groups:
mask = (treatment == group) | (treatment == self.control_name)
treatment_filt = treatment[mask]
X_filt = X[mask]
y_filt = y[mask]
yhat_filt = yhat[mask]
p_filt = p[group][mask]
w = (treatment_filt == group).astype(int)
if verbose:
logger.info('training the treatment effect model for {} with R-loss'.format(group))
self.models_tau[group].fit(X_filt, (y_filt - yhat_filt) / (w - p_filt),
sample_weight=(w - p_filt) ** 2)
self.vars_c[group] = (y_filt[w == 0] - yhat_filt[w == 0]).var()
self.vars_t[group] = (y_filt[w == 1] - yhat_filt[w == 1]).var() | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_to_np",
"(",
"X",
",",
"treatment",
",",
"y",
")",
"check_treatment_vector",
"(",
"treatment",
",",
"self",
".",
"control_name",
")",
"self",
".",
"t_groups",
"=",
"np",
".",
"unique",
"(",
"treatment",
"[",
"treatment",
"!=",
"self",
".",
"control_name",
"]",
")",
"self",
".",
"t_groups",
".",
"sort",
"(",
")",
"if",
"p",
"is",
"None",
":",
"self",
".",
"_set_propensity_models",
"(",
"X",
"=",
"X",
",",
"treatment",
"=",
"treatment",
",",
"y",
"=",
"y",
")",
"p",
"=",
"self",
".",
"propensity",
"else",
":",
"p",
"=",
"self",
".",
"_format_p",
"(",
"p",
",",
"self",
".",
"t_groups",
")",
"self",
".",
"_classes",
"=",
"{",
"group",
":",
"i",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"self",
".",
"t_groups",
")",
"}",
"self",
".",
"models_tau",
"=",
"{",
"group",
":",
"deepcopy",
"(",
"self",
".",
"model_tau",
")",
"for",
"group",
"in",
"self",
".",
"t_groups",
"}",
"self",
".",
"vars_c",
"=",
"{",
"}",
"self",
".",
"vars_t",
"=",
"{",
"}",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"'generating out-of-fold CV outcome estimates'",
")",
"yhat",
"=",
"cross_val_predict",
"(",
"self",
".",
"model_mu",
",",
"X",
",",
"y",
",",
"cv",
"=",
"self",
".",
"cv",
",",
"n_jobs",
"=",
"-",
"1",
")",
"for",
"group",
"in",
"self",
".",
"t_groups",
":",
"mask",
"=",
"(",
"treatment",
"==",
"group",
")",
"|",
"(",
"treatment",
"==",
"self",
".",
"control_name",
")",
"treatment_filt",
"=",
"treatment",
"[",
"mask",
"]",
"X_filt",
"=",
"X",
"[",
"mask",
"]",
"y_filt",
"=",
"y",
"[",
"mask",
"]",
"yhat_filt",
"=",
"yhat",
"[",
"mask",
"]",
"p_filt",
"=",
"p",
"[",
"group",
"]",
"[",
"mask",
"]",
"w",
"=",
"(",
"treatment_filt",
"==",
"group",
")",
".",
"astype",
"(",
"int",
")",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"'training the treatment effect model for {} with R-loss'",
".",
"format",
"(",
"group",
")",
")",
"self",
".",
"models_tau",
"[",
"group",
"]",
".",
"fit",
"(",
"X_filt",
",",
"(",
"y_filt",
"-",
"yhat_filt",
")",
"/",
"(",
"w",
"-",
"p_filt",
")",
",",
"sample_weight",
"=",
"(",
"w",
"-",
"p_filt",
")",
"**",
"2",
")",
"self",
".",
"vars_c",
"[",
"group",
"]",
"=",
"(",
"y_filt",
"[",
"w",
"==",
"0",
"]",
"-",
"yhat_filt",
"[",
"w",
"==",
"0",
"]",
")",
".",
"var",
"(",
")",
"self",
".",
"vars_t",
"[",
"group",
"]",
"=",
"(",
"y_filt",
"[",
"w",
"==",
"1",
"]",
"-",
"yhat_filt",
"[",
"w",
"==",
"1",
"]",
")",
".",
"var",
"(",
")"
] | [
72,
4
] | [
119,
75
] | python | en | ['en', 'en', 'en'] | True |
BaseRLearner.predict | (self, X, p=None) | Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
Returns:
(numpy.ndarray): Predictions of treatment effects.
| Predict treatment effects. | def predict(self, X, p=None):
"""Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
Returns:
(numpy.ndarray): Predictions of treatment effects.
"""
X = convert_pd_to_np(X)
te = np.zeros((X.shape[0], self.t_groups.shape[0]))
for i, group in enumerate(self.t_groups):
dhat = self.models_tau[group].predict(X)
te[:, i] = dhat
return te | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"p",
"=",
"None",
")",
":",
"X",
"=",
"convert_pd_to_np",
"(",
"X",
")",
"te",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
")",
")",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"self",
".",
"t_groups",
")",
":",
"dhat",
"=",
"self",
".",
"models_tau",
"[",
"group",
"]",
".",
"predict",
"(",
"X",
")",
"te",
"[",
":",
",",
"i",
"]",
"=",
"dhat",
"return",
"te"
] | [
121,
4
] | [
136,
17
] | python | en | ['fr', 'en', 'en'] | True |
BaseRLearner.fit_predict | (self, X, treatment, y, p=None, return_ci=False,
n_bootstraps=1000, bootstrap_size=10000, verbose=True) | Fit the treatment effect and outcome models of the R learner and predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
return_ci (bool): whether to return confidence intervals
n_bootstraps (int): number of bootstrap iterations
bootstrap_size (int): number of samples per bootstrap
verbose (bool): whether to output progress logs
Returns:
(numpy.ndarray): Predictions of treatment effects. Output dim: [n_samples, n_treatment].
If return_ci, returns CATE [n_samples, n_treatment], LB [n_samples, n_treatment],
UB [n_samples, n_treatment]
| Fit the treatment effect and outcome models of the R learner and predict treatment effects. | def fit_predict(self, X, treatment, y, p=None, return_ci=False,
n_bootstraps=1000, bootstrap_size=10000, verbose=True):
"""Fit the treatment effect and outcome models of the R learner and predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
return_ci (bool): whether to return confidence intervals
n_bootstraps (int): number of bootstrap iterations
bootstrap_size (int): number of samples per bootstrap
verbose (bool): whether to output progress logs
Returns:
(numpy.ndarray): Predictions of treatment effects. Output dim: [n_samples, n_treatment].
If return_ci, returns CATE [n_samples, n_treatment], LB [n_samples, n_treatment],
UB [n_samples, n_treatment]
"""
X, treatment, y = convert_pd_to_np(X, treatment, y)
self.fit(X, treatment, y, p, verbose=verbose)
te = self.predict(X)
if not return_ci:
return te
else:
t_groups_global = self.t_groups
_classes_global = self._classes
model_mu_global = deepcopy(self.model_mu)
models_tau_global = deepcopy(self.models_tau)
te_bootstraps = np.zeros(shape=(X.shape[0], self.t_groups.shape[0], n_bootstraps))
logger.info('Bootstrap Confidence Intervals')
for i in tqdm(range(n_bootstraps)):
if p is None:
p = self.propensity
else:
p = self._format_p(p, self.t_groups)
te_b = self.bootstrap(X, treatment, y, p, size=bootstrap_size)
te_bootstraps[:, :, i] = te_b
te_lower = np.percentile(te_bootstraps, (self.ate_alpha / 2) * 100, axis=2)
te_upper = np.percentile(te_bootstraps, (1 - self.ate_alpha / 2) * 100, axis=2)
# set member variables back to global (currently last bootstrapped outcome)
self.t_groups = t_groups_global
self._classes = _classes_global
self.model_mu = deepcopy(model_mu_global)
self.models_tau = deepcopy(models_tau_global)
return (te, te_lower, te_upper) | [
"def",
"fit_predict",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"return_ci",
"=",
"False",
",",
"n_bootstraps",
"=",
"1000",
",",
"bootstrap_size",
"=",
"10000",
",",
"verbose",
"=",
"True",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_to_np",
"(",
"X",
",",
"treatment",
",",
"y",
")",
"self",
".",
"fit",
"(",
"X",
",",
"treatment",
",",
"y",
",",
"p",
",",
"verbose",
"=",
"verbose",
")",
"te",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"if",
"not",
"return_ci",
":",
"return",
"te",
"else",
":",
"t_groups_global",
"=",
"self",
".",
"t_groups",
"_classes_global",
"=",
"self",
".",
"_classes",
"model_mu_global",
"=",
"deepcopy",
"(",
"self",
".",
"model_mu",
")",
"models_tau_global",
"=",
"deepcopy",
"(",
"self",
".",
"models_tau",
")",
"te_bootstraps",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
",",
"n_bootstraps",
")",
")",
"logger",
".",
"info",
"(",
"'Bootstrap Confidence Intervals'",
")",
"for",
"i",
"in",
"tqdm",
"(",
"range",
"(",
"n_bootstraps",
")",
")",
":",
"if",
"p",
"is",
"None",
":",
"p",
"=",
"self",
".",
"propensity",
"else",
":",
"p",
"=",
"self",
".",
"_format_p",
"(",
"p",
",",
"self",
".",
"t_groups",
")",
"te_b",
"=",
"self",
".",
"bootstrap",
"(",
"X",
",",
"treatment",
",",
"y",
",",
"p",
",",
"size",
"=",
"bootstrap_size",
")",
"te_bootstraps",
"[",
":",
",",
":",
",",
"i",
"]",
"=",
"te_b",
"te_lower",
"=",
"np",
".",
"percentile",
"(",
"te_bootstraps",
",",
"(",
"self",
".",
"ate_alpha",
"/",
"2",
")",
"*",
"100",
",",
"axis",
"=",
"2",
")",
"te_upper",
"=",
"np",
".",
"percentile",
"(",
"te_bootstraps",
",",
"(",
"1",
"-",
"self",
".",
"ate_alpha",
"/",
"2",
")",
"*",
"100",
",",
"axis",
"=",
"2",
")",
"# set member variables back to global (currently last bootstrapped outcome)",
"self",
".",
"t_groups",
"=",
"t_groups_global",
"self",
".",
"_classes",
"=",
"_classes_global",
"self",
".",
"model_mu",
"=",
"deepcopy",
"(",
"model_mu_global",
")",
"self",
".",
"models_tau",
"=",
"deepcopy",
"(",
"models_tau_global",
")",
"return",
"(",
"te",
",",
"te_lower",
",",
"te_upper",
")"
] | [
138,
4
] | [
189,
43
] | python | en | ['en', 'en', 'en'] | True |
BaseRLearner.estimate_ate | (self, X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000) | Estimate the Average Treatment Effect (ATE).
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
bootstrap_ci (bool): whether run bootstrap for confidence intervals
n_bootstraps (int): number of bootstrap iterations
bootstrap_size (int): number of samples per bootstrap
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
| Estimate the Average Treatment Effect (ATE). | def estimate_ate(self, X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000):
"""Estimate the Average Treatment Effect (ATE).
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
bootstrap_ci (bool): whether run bootstrap for confidence intervals
n_bootstraps (int): number of bootstrap iterations
bootstrap_size (int): number of samples per bootstrap
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
"""
X, treatment, y = convert_pd_to_np(X, treatment, y)
te = self.fit_predict(X, treatment, y, p, return_ci=False)
ate = np.zeros(self.t_groups.shape[0])
ate_lb = np.zeros(self.t_groups.shape[0])
ate_ub = np.zeros(self.t_groups.shape[0])
for i, group in enumerate(self.t_groups):
w = (treatment == group).astype(int)
prob_treatment = float(sum(w)) / X.shape[0]
_ate = te[:, i].mean()
se = (np.sqrt((self.vars_t[group] / prob_treatment)
+ (self.vars_c[group] / (1 - prob_treatment))
+ te[:, i].var())
/ X.shape[0])
_ate_lb = _ate - se * norm.ppf(1 - self.ate_alpha / 2)
_ate_ub = _ate + se * norm.ppf(1 - self.ate_alpha / 2)
ate[i] = _ate
ate_lb[i] = _ate_lb
ate_ub[i] = _ate_ub
if not bootstrap_ci:
return ate, ate_lb, ate_ub
else:
t_groups_global = self.t_groups
_classes_global = self._classes
model_mu_global = deepcopy(self.model_mu)
models_tau_global = deepcopy(self.models_tau)
logger.info('Bootstrap Confidence Intervals for ATE')
ate_bootstraps = np.zeros(shape=(self.t_groups.shape[0], n_bootstraps))
for n in tqdm(range(n_bootstraps)):
if p is None:
p = self.propensity
else:
p = self._format_p(p, self.t_groups)
cate_b = self.bootstrap(X, treatment, y, p, size=bootstrap_size)
ate_bootstraps[:, n] = cate_b.mean()
ate_lower = np.percentile(ate_bootstraps, (self.ate_alpha / 2) * 100, axis=1)
ate_upper = np.percentile(ate_bootstraps, (1 - self.ate_alpha / 2) * 100, axis=1)
# set member variables back to global (currently last bootstrapped outcome)
self.t_groups = t_groups_global
self._classes = _classes_global
self.model_mu = deepcopy(model_mu_global)
self.models_tau = deepcopy(models_tau_global)
return ate, ate_lower, ate_upper | [
"def",
"estimate_ate",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"bootstrap_ci",
"=",
"False",
",",
"n_bootstraps",
"=",
"1000",
",",
"bootstrap_size",
"=",
"10000",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_to_np",
"(",
"X",
",",
"treatment",
",",
"y",
")",
"te",
"=",
"self",
".",
"fit_predict",
"(",
"X",
",",
"treatment",
",",
"y",
",",
"p",
",",
"return_ci",
"=",
"False",
")",
"ate",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
")",
"ate_lb",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
")",
"ate_ub",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"self",
".",
"t_groups",
")",
":",
"w",
"=",
"(",
"treatment",
"==",
"group",
")",
".",
"astype",
"(",
"int",
")",
"prob_treatment",
"=",
"float",
"(",
"sum",
"(",
"w",
")",
")",
"/",
"X",
".",
"shape",
"[",
"0",
"]",
"_ate",
"=",
"te",
"[",
":",
",",
"i",
"]",
".",
"mean",
"(",
")",
"se",
"=",
"(",
"np",
".",
"sqrt",
"(",
"(",
"self",
".",
"vars_t",
"[",
"group",
"]",
"/",
"prob_treatment",
")",
"+",
"(",
"self",
".",
"vars_c",
"[",
"group",
"]",
"/",
"(",
"1",
"-",
"prob_treatment",
")",
")",
"+",
"te",
"[",
":",
",",
"i",
"]",
".",
"var",
"(",
")",
")",
"/",
"X",
".",
"shape",
"[",
"0",
"]",
")",
"_ate_lb",
"=",
"_ate",
"-",
"se",
"*",
"norm",
".",
"ppf",
"(",
"1",
"-",
"self",
".",
"ate_alpha",
"/",
"2",
")",
"_ate_ub",
"=",
"_ate",
"+",
"se",
"*",
"norm",
".",
"ppf",
"(",
"1",
"-",
"self",
".",
"ate_alpha",
"/",
"2",
")",
"ate",
"[",
"i",
"]",
"=",
"_ate",
"ate_lb",
"[",
"i",
"]",
"=",
"_ate_lb",
"ate_ub",
"[",
"i",
"]",
"=",
"_ate_ub",
"if",
"not",
"bootstrap_ci",
":",
"return",
"ate",
",",
"ate_lb",
",",
"ate_ub",
"else",
":",
"t_groups_global",
"=",
"self",
".",
"t_groups",
"_classes_global",
"=",
"self",
".",
"_classes",
"model_mu_global",
"=",
"deepcopy",
"(",
"self",
".",
"model_mu",
")",
"models_tau_global",
"=",
"deepcopy",
"(",
"self",
".",
"models_tau",
")",
"logger",
".",
"info",
"(",
"'Bootstrap Confidence Intervals for ATE'",
")",
"ate_bootstraps",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
",",
"n_bootstraps",
")",
")",
"for",
"n",
"in",
"tqdm",
"(",
"range",
"(",
"n_bootstraps",
")",
")",
":",
"if",
"p",
"is",
"None",
":",
"p",
"=",
"self",
".",
"propensity",
"else",
":",
"p",
"=",
"self",
".",
"_format_p",
"(",
"p",
",",
"self",
".",
"t_groups",
")",
"cate_b",
"=",
"self",
".",
"bootstrap",
"(",
"X",
",",
"treatment",
",",
"y",
",",
"p",
",",
"size",
"=",
"bootstrap_size",
")",
"ate_bootstraps",
"[",
":",
",",
"n",
"]",
"=",
"cate_b",
".",
"mean",
"(",
")",
"ate_lower",
"=",
"np",
".",
"percentile",
"(",
"ate_bootstraps",
",",
"(",
"self",
".",
"ate_alpha",
"/",
"2",
")",
"*",
"100",
",",
"axis",
"=",
"1",
")",
"ate_upper",
"=",
"np",
".",
"percentile",
"(",
"ate_bootstraps",
",",
"(",
"1",
"-",
"self",
".",
"ate_alpha",
"/",
"2",
")",
"*",
"100",
",",
"axis",
"=",
"1",
")",
"# set member variables back to global (currently last bootstrapped outcome)",
"self",
".",
"t_groups",
"=",
"t_groups_global",
"self",
".",
"_classes",
"=",
"_classes_global",
"self",
".",
"model_mu",
"=",
"deepcopy",
"(",
"model_mu_global",
")",
"self",
".",
"models_tau",
"=",
"deepcopy",
"(",
"models_tau_global",
")",
"return",
"ate",
",",
"ate_lower",
",",
"ate_upper"
] | [
191,
4
] | [
258,
44
] | python | en | ['en', 'it', 'en'] | True |
BaseRRegressor.__init__ | (self,
learner=None,
outcome_learner=None,
effect_learner=None,
propensity_learner=ElasticNetPropensityModel(),
ate_alpha=.05,
control_name=0,
n_fold=5,
random_state=None) | Initialize an R-learner regressor.
Args:
learner (optional): a model to estimate outcomes and treatment effects
outcome_learner (optional): a model to estimate outcomes
effect_learner (optional): a model to estimate treatment effects. It needs to take `sample_weight` as an
input argument for `fit()`
propensity_learner (optional): a model to estimate propensity scores. `ElasticNetPropensityModel()` will
be used by default.
ate_alpha (float, optional): the confidence level alpha of the ATE estimate
control_name (str or int, optional): name of control group
n_fold (int, optional): the number of cross validation folds for outcome_learner
random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
| Initialize an R-learner regressor. | def __init__(self,
learner=None,
outcome_learner=None,
effect_learner=None,
propensity_learner=ElasticNetPropensityModel(),
ate_alpha=.05,
control_name=0,
n_fold=5,
random_state=None):
"""Initialize an R-learner regressor.
Args:
learner (optional): a model to estimate outcomes and treatment effects
outcome_learner (optional): a model to estimate outcomes
effect_learner (optional): a model to estimate treatment effects. It needs to take `sample_weight` as an
input argument for `fit()`
propensity_learner (optional): a model to estimate propensity scores. `ElasticNetPropensityModel()` will
be used by default.
ate_alpha (float, optional): the confidence level alpha of the ATE estimate
control_name (str or int, optional): name of control group
n_fold (int, optional): the number of cross validation folds for outcome_learner
random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
"""
super().__init__(
learner=learner,
outcome_learner=outcome_learner,
effect_learner=effect_learner,
propensity_learner=propensity_learner,
ate_alpha=ate_alpha,
control_name=control_name,
n_fold=n_fold,
random_state=random_state) | [
"def",
"__init__",
"(",
"self",
",",
"learner",
"=",
"None",
",",
"outcome_learner",
"=",
"None",
",",
"effect_learner",
"=",
"None",
",",
"propensity_learner",
"=",
"ElasticNetPropensityModel",
"(",
")",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
",",
"n_fold",
"=",
"5",
",",
"random_state",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"learner",
"=",
"learner",
",",
"outcome_learner",
"=",
"outcome_learner",
",",
"effect_learner",
"=",
"effect_learner",
",",
"propensity_learner",
"=",
"propensity_learner",
",",
"ate_alpha",
"=",
"ate_alpha",
",",
"control_name",
"=",
"control_name",
",",
"n_fold",
"=",
"n_fold",
",",
"random_state",
"=",
"random_state",
")"
] | [
266,
4
] | [
297,
38
] | python | en | ['en', 'fy', 'nl'] | False |
BaseRClassifier.__init__ | (self,
outcome_learner=None,
effect_learner=None,
propensity_learner=ElasticNetPropensityModel(),
ate_alpha=.05,
control_name=0,
n_fold=5,
random_state=None) | Initialize an R-learner classifier.
Args:
outcome_learner: a model to estimate outcomes. Should be a classifier.
effect_learner: a model to estimate treatment effects. It needs to take `sample_weight` as an
input argument for `fit()`. Should be a regressor.
propensity_learner (optional): a model to estimate propensity scores. `ElasticNetPropensityModel()` will
be used by default.
ate_alpha (float, optional): the confidence level alpha of the ATE estimate
control_name (str or int, optional): name of control group
n_fold (int, optional): the number of cross validation folds for outcome_learner
random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
| Initialize an R-learner classifier. | def __init__(self,
outcome_learner=None,
effect_learner=None,
propensity_learner=ElasticNetPropensityModel(),
ate_alpha=.05,
control_name=0,
n_fold=5,
random_state=None):
"""Initialize an R-learner classifier.
Args:
outcome_learner: a model to estimate outcomes. Should be a classifier.
effect_learner: a model to estimate treatment effects. It needs to take `sample_weight` as an
input argument for `fit()`. Should be a regressor.
propensity_learner (optional): a model to estimate propensity scores. `ElasticNetPropensityModel()` will
be used by default.
ate_alpha (float, optional): the confidence level alpha of the ATE estimate
control_name (str or int, optional): name of control group
n_fold (int, optional): the number of cross validation folds for outcome_learner
random_state (int or RandomState, optional): a seed (int) or random number generator (RandomState)
"""
super().__init__(
learner=None,
outcome_learner=outcome_learner,
effect_learner=effect_learner,
propensity_learner=propensity_learner,
ate_alpha=ate_alpha,
control_name=control_name,
n_fold=n_fold,
random_state=random_state)
if (outcome_learner is None) and (effect_learner is None):
raise ValueError("Either the outcome learner or the effect learner must be specified.") | [
"def",
"__init__",
"(",
"self",
",",
"outcome_learner",
"=",
"None",
",",
"effect_learner",
"=",
"None",
",",
"propensity_learner",
"=",
"ElasticNetPropensityModel",
"(",
")",
",",
"ate_alpha",
"=",
".05",
",",
"control_name",
"=",
"0",
",",
"n_fold",
"=",
"5",
",",
"random_state",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"learner",
"=",
"None",
",",
"outcome_learner",
"=",
"outcome_learner",
",",
"effect_learner",
"=",
"effect_learner",
",",
"propensity_learner",
"=",
"propensity_learner",
",",
"ate_alpha",
"=",
"ate_alpha",
",",
"control_name",
"=",
"control_name",
",",
"n_fold",
"=",
"n_fold",
",",
"random_state",
"=",
"random_state",
")",
"if",
"(",
"outcome_learner",
"is",
"None",
")",
"and",
"(",
"effect_learner",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"Either the outcome learner or the effect learner must be specified.\"",
")"
] | [
305,
4
] | [
337,
99
] | python | en | ['en', 'fy', 'nl'] | False |
BaseRClassifier.fit | (self, X, treatment, y, p=None, verbose=True) | Fit the treatment effect and outcome models of the R learner.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
verbose (bool, optional): whether to output progress logs
| Fit the treatment effect and outcome models of the R learner. | def fit(self, X, treatment, y, p=None, verbose=True):
"""Fit the treatment effect and outcome models of the R learner.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
treatment (np.array or pd.Series): a treatment vector
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
verbose (bool, optional): whether to output progress logs
"""
X, treatment, y = convert_pd_to_np(X, treatment, y)
check_treatment_vector(treatment, self.control_name)
self.t_groups = np.unique(treatment[treatment != self.control_name])
self.t_groups.sort()
if p is None:
self._set_propensity_models(X=X, treatment=treatment, y=y)
p = self.propensity
else:
p = self._format_p(p, self.t_groups)
self._classes = {group: i for i, group in enumerate(self.t_groups)}
self.models_tau = {group: deepcopy(self.model_tau) for group in self.t_groups}
self.vars_c = {}
self.vars_t = {}
if verbose:
logger.info('generating out-of-fold CV outcome estimates')
yhat = cross_val_predict(self.model_mu, X, y, cv=self.cv, method='predict_proba', n_jobs=-1)[:, 1]
for group in self.t_groups:
mask = (treatment == group) | (treatment == self.control_name)
treatment_filt = treatment[mask]
X_filt = X[mask]
y_filt = y[mask]
yhat_filt = yhat[mask]
p_filt = p[group][mask]
w = (treatment_filt == group).astype(int)
if verbose:
logger.info('training the treatment effect model for {} with R-loss'.format(group))
self.models_tau[group].fit(X_filt, (y_filt - yhat_filt) / (w - p_filt),
sample_weight=(w - p_filt) ** 2)
self.vars_c[group] = (y_filt[w == 0] - yhat_filt[w == 0]).var()
self.vars_t[group] = (y_filt[w == 1] - yhat_filt[w == 1]).var() | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_to_np",
"(",
"X",
",",
"treatment",
",",
"y",
")",
"check_treatment_vector",
"(",
"treatment",
",",
"self",
".",
"control_name",
")",
"self",
".",
"t_groups",
"=",
"np",
".",
"unique",
"(",
"treatment",
"[",
"treatment",
"!=",
"self",
".",
"control_name",
"]",
")",
"self",
".",
"t_groups",
".",
"sort",
"(",
")",
"if",
"p",
"is",
"None",
":",
"self",
".",
"_set_propensity_models",
"(",
"X",
"=",
"X",
",",
"treatment",
"=",
"treatment",
",",
"y",
"=",
"y",
")",
"p",
"=",
"self",
".",
"propensity",
"else",
":",
"p",
"=",
"self",
".",
"_format_p",
"(",
"p",
",",
"self",
".",
"t_groups",
")",
"self",
".",
"_classes",
"=",
"{",
"group",
":",
"i",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"self",
".",
"t_groups",
")",
"}",
"self",
".",
"models_tau",
"=",
"{",
"group",
":",
"deepcopy",
"(",
"self",
".",
"model_tau",
")",
"for",
"group",
"in",
"self",
".",
"t_groups",
"}",
"self",
".",
"vars_c",
"=",
"{",
"}",
"self",
".",
"vars_t",
"=",
"{",
"}",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"'generating out-of-fold CV outcome estimates'",
")",
"yhat",
"=",
"cross_val_predict",
"(",
"self",
".",
"model_mu",
",",
"X",
",",
"y",
",",
"cv",
"=",
"self",
".",
"cv",
",",
"method",
"=",
"'predict_proba'",
",",
"n_jobs",
"=",
"-",
"1",
")",
"[",
":",
",",
"1",
"]",
"for",
"group",
"in",
"self",
".",
"t_groups",
":",
"mask",
"=",
"(",
"treatment",
"==",
"group",
")",
"|",
"(",
"treatment",
"==",
"self",
".",
"control_name",
")",
"treatment_filt",
"=",
"treatment",
"[",
"mask",
"]",
"X_filt",
"=",
"X",
"[",
"mask",
"]",
"y_filt",
"=",
"y",
"[",
"mask",
"]",
"yhat_filt",
"=",
"yhat",
"[",
"mask",
"]",
"p_filt",
"=",
"p",
"[",
"group",
"]",
"[",
"mask",
"]",
"w",
"=",
"(",
"treatment_filt",
"==",
"group",
")",
".",
"astype",
"(",
"int",
")",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"'training the treatment effect model for {} with R-loss'",
".",
"format",
"(",
"group",
")",
")",
"self",
".",
"models_tau",
"[",
"group",
"]",
".",
"fit",
"(",
"X_filt",
",",
"(",
"y_filt",
"-",
"yhat_filt",
")",
"/",
"(",
"w",
"-",
"p_filt",
")",
",",
"sample_weight",
"=",
"(",
"w",
"-",
"p_filt",
")",
"**",
"2",
")",
"self",
".",
"vars_c",
"[",
"group",
"]",
"=",
"(",
"y_filt",
"[",
"w",
"==",
"0",
"]",
"-",
"yhat_filt",
"[",
"w",
"==",
"0",
"]",
")",
".",
"var",
"(",
")",
"self",
".",
"vars_t",
"[",
"group",
"]",
"=",
"(",
"y_filt",
"[",
"w",
"==",
"1",
"]",
"-",
"yhat_filt",
"[",
"w",
"==",
"1",
"]",
")",
".",
"var",
"(",
")"
] | [
339,
4
] | [
386,
75
] | python | en | ['en', 'en', 'en'] | True |
BaseRClassifier.predict | (self, X, p=None) | Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
Returns:
(numpy.ndarray): Predictions of treatment effects.
| Predict treatment effects. | def predict(self, X, p=None):
"""Predict treatment effects.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
Returns:
(numpy.ndarray): Predictions of treatment effects.
"""
X = convert_pd_to_np(X)
te = np.zeros((X.shape[0], self.t_groups.shape[0]))
for i, group in enumerate(self.t_groups):
dhat = self.models_tau[group].predict(X)
te[:, i] = dhat
return te | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"p",
"=",
"None",
")",
":",
"X",
"=",
"convert_pd_to_np",
"(",
"X",
")",
"te",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"t_groups",
".",
"shape",
"[",
"0",
"]",
")",
")",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"self",
".",
"t_groups",
")",
":",
"dhat",
"=",
"self",
".",
"models_tau",
"[",
"group",
"]",
".",
"predict",
"(",
"X",
")",
"te",
"[",
":",
",",
"i",
"]",
"=",
"dhat",
"return",
"te"
] | [
388,
4
] | [
403,
17
] | python | en | ['fr', 'en', 'en'] | True |
XGBRRegressor.__init__ | (self,
early_stopping=True,
test_size=0.3,
early_stopping_rounds=30,
effect_learner_objective='rank:pairwise',
effect_learner_n_estimators=500,
random_state=42,
*args,
**kwargs) | Initialize an R-learner regressor with XGBoost model using pairwise ranking objective.
Args:
early_stopping: whether or not to use early stopping when fitting effect learner
test_size (float, optional): the proportion of the dataset to use as validation set when early stopping is
enabled
early_stopping_rounds (int, optional): validation metric needs to improve at least once in every
early_stopping_rounds round(s) to continue training
effect_learner_objective (str, optional): the learning objective for the effect learner
(default = 'rank:pairwise')
effect_learner_n_estimators (int, optional): number of trees to fit for the effect learner (default = 500)
| Initialize an R-learner regressor with XGBoost model using pairwise ranking objective. | def __init__(self,
early_stopping=True,
test_size=0.3,
early_stopping_rounds=30,
effect_learner_objective='rank:pairwise',
effect_learner_n_estimators=500,
random_state=42,
*args,
**kwargs):
"""Initialize an R-learner regressor with XGBoost model using pairwise ranking objective.
Args:
early_stopping: whether or not to use early stopping when fitting effect learner
test_size (float, optional): the proportion of the dataset to use as validation set when early stopping is
enabled
early_stopping_rounds (int, optional): validation metric needs to improve at least once in every
early_stopping_rounds round(s) to continue training
effect_learner_objective (str, optional): the learning objective for the effect learner
(default = 'rank:pairwise')
effect_learner_n_estimators (int, optional): number of trees to fit for the effect learner (default = 500)
"""
assert isinstance(random_state, int), 'random_state should be int.'
objective, metric = get_xgboost_objective_metric(effect_learner_objective)
self.effect_learner_objective = objective
self.effect_learner_eval_metric = metric
self.effect_learner_n_estimators = effect_learner_n_estimators
self.early_stopping = early_stopping
if self.early_stopping:
self.test_size = test_size
self.early_stopping_rounds = early_stopping_rounds
super().__init__(
outcome_learner=XGBRegressor(random_state=random_state, *args, **kwargs),
effect_learner=XGBRegressor(objective=self.effect_learner_objective,
n_estimators=self.effect_learner_n_estimators,
random_state=random_state,
*args,
**kwargs)
) | [
"def",
"__init__",
"(",
"self",
",",
"early_stopping",
"=",
"True",
",",
"test_size",
"=",
"0.3",
",",
"early_stopping_rounds",
"=",
"30",
",",
"effect_learner_objective",
"=",
"'rank:pairwise'",
",",
"effect_learner_n_estimators",
"=",
"500",
",",
"random_state",
"=",
"42",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"random_state",
",",
"int",
")",
",",
"'random_state should be int.'",
"objective",
",",
"metric",
"=",
"get_xgboost_objective_metric",
"(",
"effect_learner_objective",
")",
"self",
".",
"effect_learner_objective",
"=",
"objective",
"self",
".",
"effect_learner_eval_metric",
"=",
"metric",
"self",
".",
"effect_learner_n_estimators",
"=",
"effect_learner_n_estimators",
"self",
".",
"early_stopping",
"=",
"early_stopping",
"if",
"self",
".",
"early_stopping",
":",
"self",
".",
"test_size",
"=",
"test_size",
"self",
".",
"early_stopping_rounds",
"=",
"early_stopping_rounds",
"super",
"(",
")",
".",
"__init__",
"(",
"outcome_learner",
"=",
"XGBRegressor",
"(",
"random_state",
"=",
"random_state",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"effect_learner",
"=",
"XGBRegressor",
"(",
"objective",
"=",
"self",
".",
"effect_learner_objective",
",",
"n_estimators",
"=",
"self",
".",
"effect_learner_n_estimators",
",",
"random_state",
"=",
"random_state",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | [
407,
4
] | [
447,
9
] | python | en | ['en', 'en', 'en'] | True |
XGBRRegressor.fit | (self, X, treatment, y, p=None, verbose=True) | Fit the treatment effect and outcome models of the R learner.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
verbose (bool, optional): whether to output progress logs
| Fit the treatment effect and outcome models of the R learner. | def fit(self, X, treatment, y, p=None, verbose=True):
"""Fit the treatment effect and outcome models of the R learner.
Args:
X (np.matrix or np.array or pd.Dataframe): a feature matrix
y (np.array or pd.Series): an outcome vector
p (np.ndarray or pd.Series or dict, optional): an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
verbose (bool, optional): whether to output progress logs
"""
X, treatment, y = convert_pd_to_np(X, treatment, y)
check_treatment_vector(treatment, self.control_name)
self.t_groups = np.unique(treatment[treatment != self.control_name])
self.t_groups.sort()
if p is None:
self._set_propensity_models(X=X, treatment=treatment, y=y)
p = self.propensity
else:
p = self._format_p(p, self.t_groups)
self._classes = {group: i for i, group in enumerate(self.t_groups)}
self.models_tau = {group: deepcopy(self.model_tau) for group in self.t_groups}
self.vars_c = {}
self.vars_t = {}
if verbose:
logger.info('generating out-of-fold CV outcome estimates')
yhat = cross_val_predict(self.model_mu, X, y, cv=self.cv, n_jobs=-1)
for group in self.t_groups:
treatment_mask = (treatment == group) | (treatment == self.control_name)
treatment_filt = treatment[treatment_mask]
w = (treatment_filt == group).astype(int)
X_filt = X[treatment_mask]
y_filt = y[treatment_mask]
yhat_filt = yhat[treatment_mask]
p_filt = p[group][treatment_mask]
if verbose:
logger.info('training the treatment effect model for {} with R-loss'.format(group))
if self.early_stopping:
X_train_filt, X_test_filt, y_train_filt, y_test_filt, yhat_train_filt, yhat_test_filt, \
w_train, w_test, p_train_filt, p_test_filt = train_test_split(
X_filt, y_filt, yhat_filt, w, p_filt,
test_size=self.test_size, random_state=self.random_state
)
self.models_tau[group].fit(X=X_train_filt,
y=(y_train_filt - yhat_train_filt) / (w_train - p_train_filt),
sample_weight=(w_train - p_train_filt) ** 2,
eval_set=[(X_test_filt,
(y_test_filt - yhat_test_filt) / (w_test - p_test_filt))],
sample_weight_eval_set=[(w_test - p_test_filt) ** 2],
eval_metric=self.effect_learner_eval_metric,
early_stopping_rounds=self.early_stopping_rounds,
verbose=verbose)
else:
self.models_tau[group].fit(X_filt, (y_filt - yhat_filt) / (w - p_filt),
sample_weight=(w - p_filt) ** 2,
eval_metric=self.effect_learner_eval_metric)
self.vars_c[group] = (y_filt[w == 0] - yhat_filt[w == 0]).var()
self.vars_t[group] = (y_filt[w == 1] - yhat_filt[w == 1]).var() | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"treatment",
",",
"y",
",",
"p",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"X",
",",
"treatment",
",",
"y",
"=",
"convert_pd_to_np",
"(",
"X",
",",
"treatment",
",",
"y",
")",
"check_treatment_vector",
"(",
"treatment",
",",
"self",
".",
"control_name",
")",
"self",
".",
"t_groups",
"=",
"np",
".",
"unique",
"(",
"treatment",
"[",
"treatment",
"!=",
"self",
".",
"control_name",
"]",
")",
"self",
".",
"t_groups",
".",
"sort",
"(",
")",
"if",
"p",
"is",
"None",
":",
"self",
".",
"_set_propensity_models",
"(",
"X",
"=",
"X",
",",
"treatment",
"=",
"treatment",
",",
"y",
"=",
"y",
")",
"p",
"=",
"self",
".",
"propensity",
"else",
":",
"p",
"=",
"self",
".",
"_format_p",
"(",
"p",
",",
"self",
".",
"t_groups",
")",
"self",
".",
"_classes",
"=",
"{",
"group",
":",
"i",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"self",
".",
"t_groups",
")",
"}",
"self",
".",
"models_tau",
"=",
"{",
"group",
":",
"deepcopy",
"(",
"self",
".",
"model_tau",
")",
"for",
"group",
"in",
"self",
".",
"t_groups",
"}",
"self",
".",
"vars_c",
"=",
"{",
"}",
"self",
".",
"vars_t",
"=",
"{",
"}",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"'generating out-of-fold CV outcome estimates'",
")",
"yhat",
"=",
"cross_val_predict",
"(",
"self",
".",
"model_mu",
",",
"X",
",",
"y",
",",
"cv",
"=",
"self",
".",
"cv",
",",
"n_jobs",
"=",
"-",
"1",
")",
"for",
"group",
"in",
"self",
".",
"t_groups",
":",
"treatment_mask",
"=",
"(",
"treatment",
"==",
"group",
")",
"|",
"(",
"treatment",
"==",
"self",
".",
"control_name",
")",
"treatment_filt",
"=",
"treatment",
"[",
"treatment_mask",
"]",
"w",
"=",
"(",
"treatment_filt",
"==",
"group",
")",
".",
"astype",
"(",
"int",
")",
"X_filt",
"=",
"X",
"[",
"treatment_mask",
"]",
"y_filt",
"=",
"y",
"[",
"treatment_mask",
"]",
"yhat_filt",
"=",
"yhat",
"[",
"treatment_mask",
"]",
"p_filt",
"=",
"p",
"[",
"group",
"]",
"[",
"treatment_mask",
"]",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"'training the treatment effect model for {} with R-loss'",
".",
"format",
"(",
"group",
")",
")",
"if",
"self",
".",
"early_stopping",
":",
"X_train_filt",
",",
"X_test_filt",
",",
"y_train_filt",
",",
"y_test_filt",
",",
"yhat_train_filt",
",",
"yhat_test_filt",
",",
"w_train",
",",
"w_test",
",",
"p_train_filt",
",",
"p_test_filt",
"=",
"train_test_split",
"(",
"X_filt",
",",
"y_filt",
",",
"yhat_filt",
",",
"w",
",",
"p_filt",
",",
"test_size",
"=",
"self",
".",
"test_size",
",",
"random_state",
"=",
"self",
".",
"random_state",
")",
"self",
".",
"models_tau",
"[",
"group",
"]",
".",
"fit",
"(",
"X",
"=",
"X_train_filt",
",",
"y",
"=",
"(",
"y_train_filt",
"-",
"yhat_train_filt",
")",
"/",
"(",
"w_train",
"-",
"p_train_filt",
")",
",",
"sample_weight",
"=",
"(",
"w_train",
"-",
"p_train_filt",
")",
"**",
"2",
",",
"eval_set",
"=",
"[",
"(",
"X_test_filt",
",",
"(",
"y_test_filt",
"-",
"yhat_test_filt",
")",
"/",
"(",
"w_test",
"-",
"p_test_filt",
")",
")",
"]",
",",
"sample_weight_eval_set",
"=",
"[",
"(",
"w_test",
"-",
"p_test_filt",
")",
"**",
"2",
"]",
",",
"eval_metric",
"=",
"self",
".",
"effect_learner_eval_metric",
",",
"early_stopping_rounds",
"=",
"self",
".",
"early_stopping_rounds",
",",
"verbose",
"=",
"verbose",
")",
"else",
":",
"self",
".",
"models_tau",
"[",
"group",
"]",
".",
"fit",
"(",
"X_filt",
",",
"(",
"y_filt",
"-",
"yhat_filt",
")",
"/",
"(",
"w",
"-",
"p_filt",
")",
",",
"sample_weight",
"=",
"(",
"w",
"-",
"p_filt",
")",
"**",
"2",
",",
"eval_metric",
"=",
"self",
".",
"effect_learner_eval_metric",
")",
"self",
".",
"vars_c",
"[",
"group",
"]",
"=",
"(",
"y_filt",
"[",
"w",
"==",
"0",
"]",
"-",
"yhat_filt",
"[",
"w",
"==",
"0",
"]",
")",
".",
"var",
"(",
")",
"self",
".",
"vars_t",
"[",
"group",
"]",
"=",
"(",
"y_filt",
"[",
"w",
"==",
"1",
"]",
"-",
"yhat_filt",
"[",
"w",
"==",
"1",
"]",
")",
".",
"var",
"(",
")"
] | [
449,
4
] | [
516,
75
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions._ExpectedWarnings | (self, expected) | Compares recorded lines to expected warnings. | Compares recorded lines to expected warnings. | def _ExpectedWarnings(self, expected):
"""Compares recorded lines to expected warnings."""
self.stderr.seek(0)
actual = self.stderr.read().split('\n')
actual = [line for line in actual if line]
self.assertEqual(sorted(expected), sorted(actual)) | [
"def",
"_ExpectedWarnings",
"(",
"self",
",",
"expected",
")",
":",
"self",
".",
"stderr",
".",
"seek",
"(",
"0",
")",
"actual",
"=",
"self",
".",
"stderr",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"actual",
"=",
"[",
"line",
"for",
"line",
"in",
"actual",
"if",
"line",
"]",
"self",
".",
"assertEqual",
"(",
"sorted",
"(",
"expected",
")",
",",
"sorted",
"(",
"actual",
")",
")"
] | [
18,
2
] | [
23,
54
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testValidateMSVSSettings_tool_names | (self) | Tests that only MSVS tool names are allowed. | Tests that only MSVS tool names are allowed. | def testValidateMSVSSettings_tool_names(self):
"""Tests that only MSVS tool names are allowed."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {},
'VCLinkerTool': {},
'VCMIDLTool': {},
'foo': {},
'VCResourceCompilerTool': {},
'VCLibrarianTool': {},
'VCManifestTool': {},
'ClCompile': {}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized tool foo',
'Warning: unrecognized tool ClCompile']) | [
"def",
"testValidateMSVSSettings_tool_names",
"(",
"self",
")",
":",
"MSVSSettings",
".",
"ValidateMSVSSettings",
"(",
"{",
"'VCCLCompilerTool'",
":",
"{",
"}",
",",
"'VCLinkerTool'",
":",
"{",
"}",
",",
"'VCMIDLTool'",
":",
"{",
"}",
",",
"'foo'",
":",
"{",
"}",
",",
"'VCResourceCompilerTool'",
":",
"{",
"}",
",",
"'VCLibrarianTool'",
":",
"{",
"}",
",",
"'VCManifestTool'",
":",
"{",
"}",
",",
"'ClCompile'",
":",
"{",
"}",
"}",
",",
"self",
".",
"stderr",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"'Warning: unrecognized tool foo'",
",",
"'Warning: unrecognized tool ClCompile'",
"]",
")"
] | [
25,
2
] | [
39,
48
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testValidateMSVSSettings_settings | (self) | Tests that for invalid MSVS settings. | Tests that for invalid MSVS settings. | def testValidateMSVSSettings_settings(self):
"""Tests that for invalid MSVS settings."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '5',
'BrowseInformation': 'fdkslj',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '-1',
'CompileAs': '1',
'DebugInformationFormat': '2',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': '1',
'ExceptionHandling': '1',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '1',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '1',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'string1;string2',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '1',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '1',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalDependencies_excluded': 'file3',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '2',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'CLRImageType': '2',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '2',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': '2',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'ErrorReporting': '2',
'FixedBaseAddress': '2',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '2',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '2',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '2',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '2',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '2',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'true',
'Version': 'a string1'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'CPreprocessOptions': 'a string1',
'DefaultCharType': '1',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '1',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'notgood': 'bogus',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'VCResourceCompilerTool': {
'AdditionalOptions': 'a string1',
'AdditionalIncludeDirectories': 'folder1;folder2',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'notgood2': 'bogus',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a string1',
'ManifestResourceFile': 'a_file_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'truel',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}},
self.stderr)
self._ExpectedWarnings([
'Warning: for VCCLCompilerTool/BasicRuntimeChecks, '
'index value (5) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/BrowseInformation, '
"invalid literal for int() with base 10: 'fdkslj'",
'Warning: for VCCLCompilerTool/CallingConvention, '
'index value (-1) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/DebugInformationFormat, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCCLCompilerTool/Enableprefast',
'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ',
'Warning: for VCLinkerTool/TargetMachine, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCMIDLTool/notgood',
'Warning: unrecognized setting VCResourceCompilerTool/notgood2',
'Warning: for VCManifestTool/UpdateFileHashes, '
"expected bool; got 'truel'"
'']) | [
"def",
"testValidateMSVSSettings_settings",
"(",
"self",
")",
":",
"MSVSSettings",
".",
"ValidateMSVSSettings",
"(",
"{",
"'VCCLCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"[",
"'string1'",
",",
"'string2'",
"]",
",",
"'AdditionalUsingDirectories'",
":",
"'folder1;folder2'",
",",
"'AssemblerListingLocation'",
":",
"'a_file_name'",
",",
"'AssemblerOutput'",
":",
"'0'",
",",
"'BasicRuntimeChecks'",
":",
"'5'",
",",
"'BrowseInformation'",
":",
"'fdkslj'",
",",
"'BrowseInformationFile'",
":",
"'a_file_name'",
",",
"'BufferSecurityCheck'",
":",
"'true'",
",",
"'CallingConvention'",
":",
"'-1'",
",",
"'CompileAs'",
":",
"'1'",
",",
"'DebugInformationFormat'",
":",
"'2'",
",",
"'DefaultCharIsUnsigned'",
":",
"'true'",
",",
"'Detect64BitPortabilityProblems'",
":",
"'true'",
",",
"'DisableLanguageExtensions'",
":",
"'true'",
",",
"'DisableSpecificWarnings'",
":",
"'string1;string2'",
",",
"'EnableEnhancedInstructionSet'",
":",
"'1'",
",",
"'EnableFiberSafeOptimizations'",
":",
"'true'",
",",
"'EnableFunctionLevelLinking'",
":",
"'true'",
",",
"'EnableIntrinsicFunctions'",
":",
"'true'",
",",
"'EnablePREfast'",
":",
"'true'",
",",
"'Enableprefast'",
":",
"'bogus'",
",",
"'ErrorReporting'",
":",
"'1'",
",",
"'ExceptionHandling'",
":",
"'1'",
",",
"'ExpandAttributedSource'",
":",
"'true'",
",",
"'FavorSizeOrSpeed'",
":",
"'1'",
",",
"'FloatingPointExceptions'",
":",
"'true'",
",",
"'FloatingPointModel'",
":",
"'1'",
",",
"'ForceConformanceInForLoopScope'",
":",
"'true'",
",",
"'ForcedIncludeFiles'",
":",
"'file1;file2'",
",",
"'ForcedUsingFiles'",
":",
"'file1;file2'",
",",
"'GeneratePreprocessedFile'",
":",
"'1'",
",",
"'GenerateXMLDocumentationFiles'",
":",
"'true'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InlineFunctionExpansion'",
":",
"'1'",
",",
"'KeepComments'",
":",
"'true'",
",",
"'MinimalRebuild'",
":",
"'true'",
",",
"'ObjectFile'",
":",
"'a_file_name'",
",",
"'OmitDefaultLibName'",
":",
"'true'",
",",
"'OmitFramePointers'",
":",
"'true'",
",",
"'OpenMP'",
":",
"'true'",
",",
"'Optimization'",
":",
"'1'",
",",
"'PrecompiledHeaderFile'",
":",
"'a_file_name'",
",",
"'PrecompiledHeaderThrough'",
":",
"'a_file_name'",
",",
"'PreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ProgramDataBaseFileName'",
":",
"'a_file_name'",
",",
"'RuntimeLibrary'",
":",
"'1'",
",",
"'RuntimeTypeInfo'",
":",
"'true'",
",",
"'ShowIncludes'",
":",
"'true'",
",",
"'SmallerTypeCheck'",
":",
"'true'",
",",
"'StringPooling'",
":",
"'true'",
",",
"'StructMemberAlignment'",
":",
"'1'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TreatWChar_tAsBuiltInType'",
":",
"'true'",
",",
"'UndefineAllPreprocessorDefinitions'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'UseFullPaths'",
":",
"'true'",
",",
"'UsePrecompiledHeader'",
":",
"'1'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'1'",
",",
"'WholeProgramOptimization'",
":",
"'true'",
",",
"'XMLDocumentationFileName'",
":",
"'a_file_name'",
",",
"'ZZXYZ'",
":",
"'bogus'",
"}",
",",
"'VCLinkerTool'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2'",
",",
"'AdditionalDependencies_excluded'",
":",
"'file3'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalManifestDependencies'",
":",
"'file1;file2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'AddModuleNamesToAssembly'",
":",
"'file1;file2'",
",",
"'AllowIsolation'",
":",
"'true'",
",",
"'AssemblyDebug'",
":",
"'2'",
",",
"'AssemblyLinkResource'",
":",
"'file1;file2'",
",",
"'BaseAddress'",
":",
"'a string1'",
",",
"'CLRImageType'",
":",
"'2'",
",",
"'CLRThreadAttribute'",
":",
"'2'",
",",
"'CLRUnmanagedCodeCheck'",
":",
"'true'",
",",
"'DataExecutionPrevention'",
":",
"'2'",
",",
"'DelayLoadDLLs'",
":",
"'file1;file2'",
",",
"'DelaySign'",
":",
"'true'",
",",
"'Driver'",
":",
"'2'",
",",
"'EmbedManagedResourceFile'",
":",
"'file1;file2'",
",",
"'EnableCOMDATFolding'",
":",
"'2'",
",",
"'EnableUAC'",
":",
"'true'",
",",
"'EntryPointSymbol'",
":",
"'a string1'",
",",
"'ErrorReporting'",
":",
"'2'",
",",
"'FixedBaseAddress'",
":",
"'2'",
",",
"'ForceSymbolReferences'",
":",
"'file1;file2'",
",",
"'FunctionOrder'",
":",
"'a_file_name'",
",",
"'GenerateDebugInformation'",
":",
"'true'",
",",
"'GenerateManifest'",
":",
"'true'",
",",
"'GenerateMapFile'",
":",
"'true'",
",",
"'HeapCommitSize'",
":",
"'a string1'",
",",
"'HeapReserveSize'",
":",
"'a string1'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreDefaultLibraryNames'",
":",
"'file1;file2'",
",",
"'IgnoreEmbeddedIDL'",
":",
"'true'",
",",
"'IgnoreImportLibrary'",
":",
"'true'",
",",
"'ImportLibrary'",
":",
"'a_file_name'",
",",
"'KeyContainer'",
":",
"'a_file_name'",
",",
"'KeyFile'",
":",
"'a_file_name'",
",",
"'LargeAddressAware'",
":",
"'2'",
",",
"'LinkIncremental'",
":",
"'2'",
",",
"'LinkLibraryDependencies'",
":",
"'true'",
",",
"'LinkTimeCodeGeneration'",
":",
"'2'",
",",
"'ManifestFile'",
":",
"'a_file_name'",
",",
"'MapExports'",
":",
"'true'",
",",
"'MapFileName'",
":",
"'a_file_name'",
",",
"'MergedIDLBaseFileName'",
":",
"'a_file_name'",
",",
"'MergeSections'",
":",
"'a string1'",
",",
"'MidlCommandFile'",
":",
"'a_file_name'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'OptimizeForWindows98'",
":",
"'1'",
",",
"'OptimizeReferences'",
":",
"'2'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'PerUserRedirection'",
":",
"'true'",
",",
"'Profile'",
":",
"'true'",
",",
"'ProfileGuidedDatabase'",
":",
"'a_file_name'",
",",
"'ProgramDatabaseFile'",
":",
"'a_file_name'",
",",
"'RandomizedBaseAddress'",
":",
"'2'",
",",
"'RegisterOutput'",
":",
"'true'",
",",
"'ResourceOnlyDLL'",
":",
"'true'",
",",
"'SetChecksum'",
":",
"'true'",
",",
"'ShowProgress'",
":",
"'2'",
",",
"'StackCommitSize'",
":",
"'a string1'",
",",
"'StackReserveSize'",
":",
"'a string1'",
",",
"'StripPrivateSymbols'",
":",
"'a_file_name'",
",",
"'SubSystem'",
":",
"'2'",
",",
"'SupportUnloadOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'SwapRunFromCD'",
":",
"'true'",
",",
"'SwapRunFromNet'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'2'",
",",
"'TerminalServerAware'",
":",
"'2'",
",",
"'TurnOffAssemblyGeneration'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'TypeLibraryResourceID'",
":",
"'33'",
",",
"'UACExecutionLevel'",
":",
"'2'",
",",
"'UACUIAccess'",
":",
"'true'",
",",
"'UseLibraryDependencyInputs'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'Version'",
":",
"'a string1'",
"}",
",",
"'VCMIDLTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'CPreprocessOptions'",
":",
"'a string1'",
",",
"'DefaultCharType'",
":",
"'1'",
",",
"'DLLDataFileName'",
":",
"'a_file_name'",
",",
"'EnableErrorChecks'",
":",
"'1'",
",",
"'ErrorCheckAllocations'",
":",
"'true'",
",",
"'ErrorCheckBounds'",
":",
"'true'",
",",
"'ErrorCheckEnumRange'",
":",
"'true'",
",",
"'ErrorCheckRefPointers'",
":",
"'true'",
",",
"'ErrorCheckStubData'",
":",
"'true'",
",",
"'GenerateStublessProxies'",
":",
"'true'",
",",
"'GenerateTypeLibrary'",
":",
"'true'",
",",
"'HeaderFileName'",
":",
"'a_file_name'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InterfaceIdentifierFileName'",
":",
"'a_file_name'",
",",
"'MkTypLibCompatible'",
":",
"'true'",
",",
"'notgood'",
":",
"'bogus'",
",",
"'OutputDirectory'",
":",
"'a string1'",
",",
"'PreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ProxyFileName'",
":",
"'a_file_name'",
",",
"'RedirectOutputAndErrors'",
":",
"'a_file_name'",
",",
"'StructMemberAlignment'",
":",
"'1'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TargetEnvironment'",
":",
"'1'",
",",
"'TypeLibraryName'",
":",
"'a_file_name'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ValidateParameters'",
":",
"'true'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'1'",
"}",
",",
"'VCResourceCompilerTool'",
":",
"{",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2'",
",",
"'Culture'",
":",
"'1003'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'notgood2'",
":",
"'bogus'",
",",
"'PreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ResourceOutputFileName'",
":",
"'a string1'",
",",
"'ShowProgress'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'string1;string2'",
"}",
",",
"'VCLibrarianTool'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'ExportNamedFunctions'",
":",
"'string1;string2'",
",",
"'ForceSymbolReferences'",
":",
"'a string1'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'file1;file2'",
",",
"'LinkLibraryDependencies'",
":",
"'true'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
"}",
",",
"'VCManifestTool'",
":",
"{",
"'AdditionalManifestFiles'",
":",
"'file1;file2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'AssemblyIdentity'",
":",
"'a string1'",
",",
"'ComponentFileName'",
":",
"'a_file_name'",
",",
"'DependencyInformationFile'",
":",
"'a_file_name'",
",",
"'GenerateCatalogFiles'",
":",
"'true'",
",",
"'InputResourceManifests'",
":",
"'a string1'",
",",
"'ManifestResourceFile'",
":",
"'a_file_name'",
",",
"'OutputManifestFile'",
":",
"'a_file_name'",
",",
"'RegistrarScriptFile'",
":",
"'a_file_name'",
",",
"'ReplacementsFile'",
":",
"'a_file_name'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'UpdateFileHashes'",
":",
"'truel'",
",",
"'UpdateFileHashesSearchPath'",
":",
"'a_file_name'",
",",
"'UseFAT32Workaround'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'VerboseOutput'",
":",
"'true'",
"}",
"}",
",",
"self",
".",
"stderr",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"'Warning: for VCCLCompilerTool/BasicRuntimeChecks, '",
"'index value (5) not in expected range [0, 4)'",
",",
"'Warning: for VCCLCompilerTool/BrowseInformation, '",
"\"invalid literal for int() with base 10: 'fdkslj'\"",
",",
"'Warning: for VCCLCompilerTool/CallingConvention, '",
"'index value (-1) not in expected range [0, 4)'",
",",
"'Warning: for VCCLCompilerTool/DebugInformationFormat, '",
"'converted value for 2 not specified.'",
",",
"'Warning: unrecognized setting VCCLCompilerTool/Enableprefast'",
",",
"'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ'",
",",
"'Warning: for VCLinkerTool/TargetMachine, '",
"'converted value for 2 not specified.'",
",",
"'Warning: unrecognized setting VCMIDLTool/notgood'",
",",
"'Warning: unrecognized setting VCResourceCompilerTool/notgood2'",
",",
"'Warning: for VCManifestTool/UpdateFileHashes, '",
"\"expected bool; got 'truel'\"",
"''",
"]",
")"
] | [
41,
2
] | [
280,
12
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testValidateMSBuildSettings_settings | (self) | Tests that for invalid MSBuild settings. | Tests that for invalid MSBuild settings. | def testValidateMSBuildSettings_settings(self):
"""Tests that for invalid MSBuild settings."""
MSVSSettings.ValidateMSBuildSettings(
{'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'false',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'BuildingInIDE': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'CompileAsManaged': 'true',
'CreateHotpatchableImage': 'true',
'DebugInformationFormat': 'ProgramDatabase',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'SyncCThrow',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Precise',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'FunctionLevelLinking': 'false',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'false',
'MinimalRebuild': 'true',
'MultiProcessorCompilation': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Disabled',
'PrecompiledHeader': 'NotUsing',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'string1;string2',
'PreprocessOutputPath': 'a string1',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'false',
'ProcessorNumber': '33',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TreatSpecificWarningsAsErrors': 'string1;string2',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UseUnicodeForAssemblerListing': 'true',
'WarningLevel': 'TurnOffAllWarnings',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'Link': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'BuildingInIDE': 'true',
'CLRImageType': 'ForceIJWImage',
'CLRSupportLastError': 'Enabled',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'CreateHotPatchableImage': 'X86Image',
'DataExecutionPrevention': 'false',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': 'NotSet',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'FixedBaseAddress': 'false',
'ForceFileOutput': 'Enabled',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'a_file_list',
'ImageHasSafeExceptionHandlers': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'false',
'LinkDLL': 'true',
'LinkErrorReporting': 'SendErrorReport',
'LinkStatus': 'true',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'MSDOSStubFileName': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': 'false',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'PreventDllBinding': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SectionAlignment': '33',
'SetChecksum': 'true',
'ShowProgress': 'LinkVerboseREF',
'SpecifySectionAttributes': 'a string1',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Console',
'SupportNobindOfDelayLoadedDLL': 'true',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TrackerLogDirectory': 'a_folder',
'TreatLinkerWarningAsErrors': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'AsInvoker',
'UACUIAccess': 'true',
'Version': 'a string1'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'Culture': '0x236',
'IgnoreStandardIncludePath': 'true',
'NullTerminateStrings': 'true',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ApplicationConfigurationMode': 'true',
'ClientStubFile': 'a_file_name',
'CPreprocessOptions': 'a string1',
'DefaultCharType': 'Signed',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'EnableCustom',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateClientFiles': 'Stub',
'GenerateServerFiles': 'None',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'LocaleID': '33',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'ServerStubFile': 'a_file_name',
'StructMemberAlignment': 'NotSet',
'SuppressCompilerWarnings': 'true',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Itanium',
'TrackerLogDirectory': 'a_folder',
'TypeLibFormat': 'NewFormat',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'Lib': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'DisplayLibrary': 'a string1',
'ErrorReporting': 'PromptImmediately',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkTimeCodeGeneration': 'true',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'Name': 'a_file_name',
'OutputFile': 'a_file_name',
'RemoveObjects': 'file1;file2',
'SubSystem': 'Console',
'SuppressStartupBanner': 'true',
'TargetMachine': 'MachineX86i',
'TrackerLogDirectory': 'a_folder',
'TreatLibWarningAsErrors': 'true',
'UseUnicodeResponseFiles': 'true',
'Verbose': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'EnableDPIAwareness': 'fal',
'GenerateCatalogFiles': 'truel',
'GenerateCategoryTags': 'true',
'InputResourceManifests': 'a string1',
'ManifestFromManagedAssembly': 'a_file_name',
'notgood3': 'bogus',
'OutputManifestFile': 'a_file_name',
'OutputResourceManifests': 'a string1',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressDependencyElement': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'a_file_name'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized setting ClCompile/Enableprefast',
'Warning: unrecognized setting ClCompile/ZZXYZ',
'Warning: unrecognized setting Manifest/notgood3',
'Warning: for Manifest/GenerateCatalogFiles, '
"expected bool; got 'truel'",
'Warning: for Lib/TargetMachine, unrecognized enumerated value '
'MachineX86i',
"Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'"]) | [
"def",
"testValidateMSBuildSettings_settings",
"(",
"self",
")",
":",
"MSVSSettings",
".",
"ValidateMSBuildSettings",
"(",
"{",
"'ClCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"[",
"'string1'",
",",
"'string2'",
"]",
",",
"'AdditionalUsingDirectories'",
":",
"'folder1;folder2'",
",",
"'AssemblerListingLocation'",
":",
"'a_file_name'",
",",
"'AssemblerOutput'",
":",
"'NoListing'",
",",
"'BasicRuntimeChecks'",
":",
"'StackFrameRuntimeCheck'",
",",
"'BrowseInformation'",
":",
"'false'",
",",
"'BrowseInformationFile'",
":",
"'a_file_name'",
",",
"'BufferSecurityCheck'",
":",
"'true'",
",",
"'BuildingInIDE'",
":",
"'true'",
",",
"'CallingConvention'",
":",
"'Cdecl'",
",",
"'CompileAs'",
":",
"'CompileAsC'",
",",
"'CompileAsManaged'",
":",
"'true'",
",",
"'CreateHotpatchableImage'",
":",
"'true'",
",",
"'DebugInformationFormat'",
":",
"'ProgramDatabase'",
",",
"'DisableLanguageExtensions'",
":",
"'true'",
",",
"'DisableSpecificWarnings'",
":",
"'string1;string2'",
",",
"'EnableEnhancedInstructionSet'",
":",
"'StreamingSIMDExtensions'",
",",
"'EnableFiberSafeOptimizations'",
":",
"'true'",
",",
"'EnablePREfast'",
":",
"'true'",
",",
"'Enableprefast'",
":",
"'bogus'",
",",
"'ErrorReporting'",
":",
"'Prompt'",
",",
"'ExceptionHandling'",
":",
"'SyncCThrow'",
",",
"'ExpandAttributedSource'",
":",
"'true'",
",",
"'FavorSizeOrSpeed'",
":",
"'Neither'",
",",
"'FloatingPointExceptions'",
":",
"'true'",
",",
"'FloatingPointModel'",
":",
"'Precise'",
",",
"'ForceConformanceInForLoopScope'",
":",
"'true'",
",",
"'ForcedIncludeFiles'",
":",
"'file1;file2'",
",",
"'ForcedUsingFiles'",
":",
"'file1;file2'",
",",
"'FunctionLevelLinking'",
":",
"'false'",
",",
"'GenerateXMLDocumentationFiles'",
":",
"'true'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InlineFunctionExpansion'",
":",
"'OnlyExplicitInline'",
",",
"'IntrinsicFunctions'",
":",
"'false'",
",",
"'MinimalRebuild'",
":",
"'true'",
",",
"'MultiProcessorCompilation'",
":",
"'true'",
",",
"'ObjectFileName'",
":",
"'a_file_name'",
",",
"'OmitDefaultLibName'",
":",
"'true'",
",",
"'OmitFramePointers'",
":",
"'true'",
",",
"'OpenMPSupport'",
":",
"'true'",
",",
"'Optimization'",
":",
"'Disabled'",
",",
"'PrecompiledHeader'",
":",
"'NotUsing'",
",",
"'PrecompiledHeaderFile'",
":",
"'a_file_name'",
",",
"'PrecompiledHeaderOutputFile'",
":",
"'a_file_name'",
",",
"'PreprocessKeepComments'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'PreprocessOutputPath'",
":",
"'a string1'",
",",
"'PreprocessSuppressLineNumbers'",
":",
"'false'",
",",
"'PreprocessToFile'",
":",
"'false'",
",",
"'ProcessorNumber'",
":",
"'33'",
",",
"'ProgramDataBaseFileName'",
":",
"'a_file_name'",
",",
"'RuntimeLibrary'",
":",
"'MultiThreaded'",
",",
"'RuntimeTypeInfo'",
":",
"'true'",
",",
"'ShowIncludes'",
":",
"'true'",
",",
"'SmallerTypeCheck'",
":",
"'true'",
",",
"'StringPooling'",
":",
"'true'",
",",
"'StructMemberAlignment'",
":",
"'1Byte'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TrackerLogDirectory'",
":",
"'a_folder'",
",",
"'TreatSpecificWarningsAsErrors'",
":",
"'string1;string2'",
",",
"'TreatWarningAsError'",
":",
"'true'",
",",
"'TreatWChar_tAsBuiltInType'",
":",
"'true'",
",",
"'UndefineAllPreprocessorDefinitions'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'UseFullPaths'",
":",
"'true'",
",",
"'UseUnicodeForAssemblerListing'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'TurnOffAllWarnings'",
",",
"'WholeProgramOptimization'",
":",
"'true'",
",",
"'XMLDocumentationFileName'",
":",
"'a_file_name'",
",",
"'ZZXYZ'",
":",
"'bogus'",
"}",
",",
"'Link'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalManifestDependencies'",
":",
"'file1;file2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'AddModuleNamesToAssembly'",
":",
"'file1;file2'",
",",
"'AllowIsolation'",
":",
"'true'",
",",
"'AssemblyDebug'",
":",
"''",
",",
"'AssemblyLinkResource'",
":",
"'file1;file2'",
",",
"'BaseAddress'",
":",
"'a string1'",
",",
"'BuildingInIDE'",
":",
"'true'",
",",
"'CLRImageType'",
":",
"'ForceIJWImage'",
",",
"'CLRSupportLastError'",
":",
"'Enabled'",
",",
"'CLRThreadAttribute'",
":",
"'MTAThreadingAttribute'",
",",
"'CLRUnmanagedCodeCheck'",
":",
"'true'",
",",
"'CreateHotPatchableImage'",
":",
"'X86Image'",
",",
"'DataExecutionPrevention'",
":",
"'false'",
",",
"'DelayLoadDLLs'",
":",
"'file1;file2'",
",",
"'DelaySign'",
":",
"'true'",
",",
"'Driver'",
":",
"'NotSet'",
",",
"'EmbedManagedResourceFile'",
":",
"'file1;file2'",
",",
"'EnableCOMDATFolding'",
":",
"'false'",
",",
"'EnableUAC'",
":",
"'true'",
",",
"'EntryPointSymbol'",
":",
"'a string1'",
",",
"'FixedBaseAddress'",
":",
"'false'",
",",
"'ForceFileOutput'",
":",
"'Enabled'",
",",
"'ForceSymbolReferences'",
":",
"'file1;file2'",
",",
"'FunctionOrder'",
":",
"'a_file_name'",
",",
"'GenerateDebugInformation'",
":",
"'true'",
",",
"'GenerateMapFile'",
":",
"'true'",
",",
"'HeapCommitSize'",
":",
"'a string1'",
",",
"'HeapReserveSize'",
":",
"'a string1'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreEmbeddedIDL'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'a_file_list'",
",",
"'ImageHasSafeExceptionHandlers'",
":",
"'true'",
",",
"'ImportLibrary'",
":",
"'a_file_name'",
",",
"'KeyContainer'",
":",
"'a_file_name'",
",",
"'KeyFile'",
":",
"'a_file_name'",
",",
"'LargeAddressAware'",
":",
"'false'",
",",
"'LinkDLL'",
":",
"'true'",
",",
"'LinkErrorReporting'",
":",
"'SendErrorReport'",
",",
"'LinkStatus'",
":",
"'true'",
",",
"'LinkTimeCodeGeneration'",
":",
"'UseLinkTimeCodeGeneration'",
",",
"'ManifestFile'",
":",
"'a_file_name'",
",",
"'MapExports'",
":",
"'true'",
",",
"'MapFileName'",
":",
"'a_file_name'",
",",
"'MergedIDLBaseFileName'",
":",
"'a_file_name'",
",",
"'MergeSections'",
":",
"'a string1'",
",",
"'MidlCommandFile'",
":",
"'a_file_name'",
",",
"'MinimumRequiredVersion'",
":",
"'a string1'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'MSDOSStubFileName'",
":",
"'a_file_name'",
",",
"'NoEntryPoint'",
":",
"'true'",
",",
"'OptimizeReferences'",
":",
"'false'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'PerUserRedirection'",
":",
"'true'",
",",
"'PreventDllBinding'",
":",
"'true'",
",",
"'Profile'",
":",
"'true'",
",",
"'ProfileGuidedDatabase'",
":",
"'a_file_name'",
",",
"'ProgramDatabaseFile'",
":",
"'a_file_name'",
",",
"'RandomizedBaseAddress'",
":",
"'false'",
",",
"'RegisterOutput'",
":",
"'true'",
",",
"'SectionAlignment'",
":",
"'33'",
",",
"'SetChecksum'",
":",
"'true'",
",",
"'ShowProgress'",
":",
"'LinkVerboseREF'",
",",
"'SpecifySectionAttributes'",
":",
"'a string1'",
",",
"'StackCommitSize'",
":",
"'a string1'",
",",
"'StackReserveSize'",
":",
"'a string1'",
",",
"'StripPrivateSymbols'",
":",
"'a_file_name'",
",",
"'SubSystem'",
":",
"'Console'",
",",
"'SupportNobindOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SupportUnloadOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'SwapRunFromCD'",
":",
"'true'",
",",
"'SwapRunFromNET'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'MachineX86'",
",",
"'TerminalServerAware'",
":",
"'false'",
",",
"'TrackerLogDirectory'",
":",
"'a_folder'",
",",
"'TreatLinkerWarningAsErrors'",
":",
"'true'",
",",
"'TurnOffAssemblyGeneration'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'TypeLibraryResourceID'",
":",
"'33'",
",",
"'UACExecutionLevel'",
":",
"'AsInvoker'",
",",
"'UACUIAccess'",
":",
"'true'",
",",
"'Version'",
":",
"'a string1'",
"}",
",",
"'ResourceCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'Culture'",
":",
"'0x236'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'NullTerminateStrings'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ResourceOutputFileName'",
":",
"'a string1'",
",",
"'ShowProgress'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TrackerLogDirectory'",
":",
"'a_folder'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'string1;string2'",
"}",
",",
"'Midl'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'ApplicationConfigurationMode'",
":",
"'true'",
",",
"'ClientStubFile'",
":",
"'a_file_name'",
",",
"'CPreprocessOptions'",
":",
"'a string1'",
",",
"'DefaultCharType'",
":",
"'Signed'",
",",
"'DllDataFileName'",
":",
"'a_file_name'",
",",
"'EnableErrorChecks'",
":",
"'EnableCustom'",
",",
"'ErrorCheckAllocations'",
":",
"'true'",
",",
"'ErrorCheckBounds'",
":",
"'true'",
",",
"'ErrorCheckEnumRange'",
":",
"'true'",
",",
"'ErrorCheckRefPointers'",
":",
"'true'",
",",
"'ErrorCheckStubData'",
":",
"'true'",
",",
"'GenerateClientFiles'",
":",
"'Stub'",
",",
"'GenerateServerFiles'",
":",
"'None'",
",",
"'GenerateStublessProxies'",
":",
"'true'",
",",
"'GenerateTypeLibrary'",
":",
"'true'",
",",
"'HeaderFileName'",
":",
"'a_file_name'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InterfaceIdentifierFileName'",
":",
"'a_file_name'",
",",
"'LocaleID'",
":",
"'33'",
",",
"'MkTypLibCompatible'",
":",
"'true'",
",",
"'OutputDirectory'",
":",
"'a string1'",
",",
"'PreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ProxyFileName'",
":",
"'a_file_name'",
",",
"'RedirectOutputAndErrors'",
":",
"'a_file_name'",
",",
"'ServerStubFile'",
":",
"'a_file_name'",
",",
"'StructMemberAlignment'",
":",
"'NotSet'",
",",
"'SuppressCompilerWarnings'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TargetEnvironment'",
":",
"'Itanium'",
",",
"'TrackerLogDirectory'",
":",
"'a_folder'",
",",
"'TypeLibFormat'",
":",
"'NewFormat'",
",",
"'TypeLibraryName'",
":",
"'a_file_name'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'string1;string2'",
",",
"'ValidateAllParameters'",
":",
"'true'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'1'",
"}",
",",
"'Lib'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'DisplayLibrary'",
":",
"'a string1'",
",",
"'ErrorReporting'",
":",
"'PromptImmediately'",
",",
"'ExportNamedFunctions'",
":",
"'string1;string2'",
",",
"'ForceSymbolReferences'",
":",
"'a string1'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'file1;file2'",
",",
"'LinkTimeCodeGeneration'",
":",
"'true'",
",",
"'MinimumRequiredVersion'",
":",
"'a string1'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'Name'",
":",
"'a_file_name'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'RemoveObjects'",
":",
"'file1;file2'",
",",
"'SubSystem'",
":",
"'Console'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'MachineX86i'",
",",
"'TrackerLogDirectory'",
":",
"'a_folder'",
",",
"'TreatLibWarningAsErrors'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'Verbose'",
":",
"'true'",
"}",
",",
"'Manifest'",
":",
"{",
"'AdditionalManifestFiles'",
":",
"'file1;file2'",
",",
"'AdditionalOptions'",
":",
"'a string1'",
",",
"'AssemblyIdentity'",
":",
"'a string1'",
",",
"'ComponentFileName'",
":",
"'a_file_name'",
",",
"'EnableDPIAwareness'",
":",
"'fal'",
",",
"'GenerateCatalogFiles'",
":",
"'truel'",
",",
"'GenerateCategoryTags'",
":",
"'true'",
",",
"'InputResourceManifests'",
":",
"'a string1'",
",",
"'ManifestFromManagedAssembly'",
":",
"'a_file_name'",
",",
"'notgood3'",
":",
"'bogus'",
",",
"'OutputManifestFile'",
":",
"'a_file_name'",
",",
"'OutputResourceManifests'",
":",
"'a string1'",
",",
"'RegistrarScriptFile'",
":",
"'a_file_name'",
",",
"'ReplacementsFile'",
":",
"'a_file_name'",
",",
"'SuppressDependencyElement'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TrackerLogDirectory'",
":",
"'a_folder'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'UpdateFileHashes'",
":",
"'true'",
",",
"'UpdateFileHashesSearchPath'",
":",
"'a_file_name'",
",",
"'VerboseOutput'",
":",
"'true'",
"}",
",",
"'ProjectReference'",
":",
"{",
"'LinkLibraryDependencies'",
":",
"'true'",
",",
"'UseLibraryDependencyInputs'",
":",
"'true'",
"}",
",",
"'ManifestResourceCompile'",
":",
"{",
"'ResourceOutputFileName'",
":",
"'a_file_name'",
"}",
",",
"''",
":",
"{",
"'EmbedManifest'",
":",
"'true'",
",",
"'GenerateManifest'",
":",
"'true'",
",",
"'IgnoreImportLibrary'",
":",
"'true'",
",",
"'LinkIncremental'",
":",
"'false'",
"}",
"}",
",",
"self",
".",
"stderr",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"'Warning: unrecognized setting ClCompile/Enableprefast'",
",",
"'Warning: unrecognized setting ClCompile/ZZXYZ'",
",",
"'Warning: unrecognized setting Manifest/notgood3'",
",",
"'Warning: for Manifest/GenerateCatalogFiles, '",
"\"expected bool; got 'truel'\"",
",",
"'Warning: for Lib/TargetMachine, unrecognized enumerated value '",
"'MachineX86i'",
",",
"\"Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'\"",
"]",
")"
] | [
282,
2
] | [
558,
78
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testConvertToMSBuildSettings_empty | (self) | Tests an empty conversion. | Tests an empty conversion. | def testConvertToMSBuildSettings_empty(self):
"""Tests an empty conversion."""
msvs_settings = {}
expected_msbuild_settings = {}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([]) | [
"def",
"testConvertToMSBuildSettings_empty",
"(",
"self",
")",
":",
"msvs_settings",
"=",
"{",
"}",
"expected_msbuild_settings",
"=",
"{",
"}",
"actual_msbuild_settings",
"=",
"MSVSSettings",
".",
"ConvertToMSBuildSettings",
"(",
"msvs_settings",
",",
"self",
".",
"stderr",
")",
"self",
".",
"assertEqual",
"(",
"expected_msbuild_settings",
",",
"actual_msbuild_settings",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"]",
")"
] | [
560,
2
] | [
568,
30
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testConvertToMSBuildSettings_minimal | (self) | Tests a minimal conversion. | Tests a minimal conversion. | def testConvertToMSBuildSettings_minimal(self):
"""Tests a minimal conversion."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': '0',
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': '1',
'ErrorReporting': '1',
'DataExecutionPrevention': '2',
},
}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': 'Default',
},
'Link': {
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'LinkErrorReporting': 'PromptImmediately',
'DataExecutionPrevention': 'true',
},
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([]) | [
"def",
"testConvertToMSBuildSettings_minimal",
"(",
"self",
")",
":",
"msvs_settings",
"=",
"{",
"'VCCLCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'dir1'",
",",
"'AdditionalOptions'",
":",
"'/foo'",
",",
"'BasicRuntimeChecks'",
":",
"'0'",
",",
"}",
",",
"'VCLinkerTool'",
":",
"{",
"'LinkTimeCodeGeneration'",
":",
"'1'",
",",
"'ErrorReporting'",
":",
"'1'",
",",
"'DataExecutionPrevention'",
":",
"'2'",
",",
"}",
",",
"}",
"expected_msbuild_settings",
"=",
"{",
"'ClCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'dir1'",
",",
"'AdditionalOptions'",
":",
"'/foo'",
",",
"'BasicRuntimeChecks'",
":",
"'Default'",
",",
"}",
",",
"'Link'",
":",
"{",
"'LinkTimeCodeGeneration'",
":",
"'UseLinkTimeCodeGeneration'",
",",
"'LinkErrorReporting'",
":",
"'PromptImmediately'",
",",
"'DataExecutionPrevention'",
":",
"'true'",
",",
"}",
",",
"}",
"actual_msbuild_settings",
"=",
"MSVSSettings",
".",
"ConvertToMSBuildSettings",
"(",
"msvs_settings",
",",
"self",
".",
"stderr",
")",
"self",
".",
"assertEqual",
"(",
"expected_msbuild_settings",
",",
"actual_msbuild_settings",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"]",
")"
] | [
570,
2
] | [
600,
30
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testConvertToMSBuildSettings_warnings | (self) | Tests conversion that generates warnings. | Tests conversion that generates warnings. | def testConvertToMSBuildSettings_warnings(self):
"""Tests conversion that generates warnings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2',
# These are incorrect values:
'BasicRuntimeChecks': '12',
'BrowseInformation': '21',
'UsePrecompiledHeader': '13',
'GeneratePreprocessedFile': '14'},
'VCLinkerTool': {
# These are incorrect values:
'Driver': '10',
'LinkTimeCodeGeneration': '31',
'ErrorReporting': '21',
'FixedBaseAddress': '6'},
'VCResourceCompilerTool': {
# Custom
'Culture': '1003'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2'},
'Link': {},
'ResourceCompile': {
# Custom
'Culture': '0x03eb'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([
'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to '
'MSBuild, index value (12) not in expected range [0, 4)',
'Warning: while converting VCCLCompilerTool/BrowseInformation to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to '
'MSBuild, index value (13) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to '
'MSBuild, value must be one of [0, 1, 2]; got 14',
'Warning: while converting VCLinkerTool/Driver to '
'MSBuild, index value (10) not in expected range [0, 4)',
'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to '
'MSBuild, index value (31) not in expected range [0, 5)',
'Warning: while converting VCLinkerTool/ErrorReporting to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCLinkerTool/FixedBaseAddress to '
'MSBuild, index value (6) not in expected range [0, 3)',
]) | [
"def",
"testConvertToMSBuildSettings_warnings",
"(",
"self",
")",
":",
"msvs_settings",
"=",
"{",
"'VCCLCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'1'",
",",
"'AdditionalOptions'",
":",
"'2'",
",",
"# These are incorrect values:",
"'BasicRuntimeChecks'",
":",
"'12'",
",",
"'BrowseInformation'",
":",
"'21'",
",",
"'UsePrecompiledHeader'",
":",
"'13'",
",",
"'GeneratePreprocessedFile'",
":",
"'14'",
"}",
",",
"'VCLinkerTool'",
":",
"{",
"# These are incorrect values:",
"'Driver'",
":",
"'10'",
",",
"'LinkTimeCodeGeneration'",
":",
"'31'",
",",
"'ErrorReporting'",
":",
"'21'",
",",
"'FixedBaseAddress'",
":",
"'6'",
"}",
",",
"'VCResourceCompilerTool'",
":",
"{",
"# Custom",
"'Culture'",
":",
"'1003'",
"}",
"}",
"expected_msbuild_settings",
"=",
"{",
"'ClCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'1'",
",",
"'AdditionalOptions'",
":",
"'2'",
"}",
",",
"'Link'",
":",
"{",
"}",
",",
"'ResourceCompile'",
":",
"{",
"# Custom",
"'Culture'",
":",
"'0x03eb'",
"}",
"}",
"actual_msbuild_settings",
"=",
"MSVSSettings",
".",
"ConvertToMSBuildSettings",
"(",
"msvs_settings",
",",
"self",
".",
"stderr",
")",
"self",
".",
"assertEqual",
"(",
"expected_msbuild_settings",
",",
"actual_msbuild_settings",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to '",
"'MSBuild, index value (12) not in expected range [0, 4)'",
",",
"'Warning: while converting VCCLCompilerTool/BrowseInformation to '",
"'MSBuild, index value (21) not in expected range [0, 3)'",
",",
"'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to '",
"'MSBuild, index value (13) not in expected range [0, 3)'",
",",
"'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to '",
"'MSBuild, value must be one of [0, 1, 2]; got 14'",
",",
"'Warning: while converting VCLinkerTool/Driver to '",
"'MSBuild, index value (10) not in expected range [0, 4)'",
",",
"'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to '",
"'MSBuild, index value (31) not in expected range [0, 5)'",
",",
"'Warning: while converting VCLinkerTool/ErrorReporting to '",
"'MSBuild, index value (21) not in expected range [0, 3)'",
",",
"'Warning: while converting VCLinkerTool/FixedBaseAddress to '",
"'MSBuild, index value (6) not in expected range [0, 3)'",
",",
"]",
")"
] | [
602,
2
] | [
652,
10
] | python | en | ['en', 'jv', 'en'] | True |
TestSequenceFunctions.testConvertToMSBuildSettings_full_synthetic | (self) | Tests conversion of all the MSBuild settings. | Tests conversion of all the MSBuild settings. | def testConvertToMSBuildSettings_full_synthetic(self):
"""Tests conversion of all the MSBuild settings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '1',
'BrowseInformation': '2',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '0',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': '0',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '1',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '0',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '2',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '0',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '0',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': '1',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': '1',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '0',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'ErrorReporting': '0',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2;file3',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '1',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '0',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '0',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '3',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '1',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'false',
'UseUnicodeResponseFiles': 'true',
'Version': 'a_string'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': '0',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '2',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'EmbedManifest': 'true',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'ManifestResourceFile': 'my_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string /J',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'true',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': 'NotSet',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'AnySuitable',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'Create',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'WarningLevel': 'Level2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'Link': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': 'ForceIJWImage',
'CLRThreadAttribute': 'STAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': 'Driver',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'NoErrorReport',
'LinkTimeCodeGeneration': 'PGInstrument',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': '',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'true',
'ShowProgress': 'NotSet',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Windows',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineARM',
'TerminalServerAware': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'HighestAvailable',
'UACUIAccess': 'true',
'Version': 'a_string'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '0x03eb',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': 'Unsigned',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'All',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '4',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Win32',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'Lib': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'my_name'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'false'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([]) | [
"def",
"testConvertToMSBuildSettings_full_synthetic",
"(",
"self",
")",
":",
"msvs_settings",
"=",
"{",
"'VCCLCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'AdditionalUsingDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AssemblerListingLocation'",
":",
"'a_file_name'",
",",
"'AssemblerOutput'",
":",
"'0'",
",",
"'BasicRuntimeChecks'",
":",
"'1'",
",",
"'BrowseInformation'",
":",
"'2'",
",",
"'BrowseInformationFile'",
":",
"'a_file_name'",
",",
"'BufferSecurityCheck'",
":",
"'true'",
",",
"'CallingConvention'",
":",
"'0'",
",",
"'CompileAs'",
":",
"'1'",
",",
"'DebugInformationFormat'",
":",
"'4'",
",",
"'DefaultCharIsUnsigned'",
":",
"'true'",
",",
"'Detect64BitPortabilityProblems'",
":",
"'true'",
",",
"'DisableLanguageExtensions'",
":",
"'true'",
",",
"'DisableSpecificWarnings'",
":",
"'d1;d2;d3'",
",",
"'EnableEnhancedInstructionSet'",
":",
"'0'",
",",
"'EnableFiberSafeOptimizations'",
":",
"'true'",
",",
"'EnableFunctionLevelLinking'",
":",
"'true'",
",",
"'EnableIntrinsicFunctions'",
":",
"'true'",
",",
"'EnablePREfast'",
":",
"'true'",
",",
"'ErrorReporting'",
":",
"'1'",
",",
"'ExceptionHandling'",
":",
"'2'",
",",
"'ExpandAttributedSource'",
":",
"'true'",
",",
"'FavorSizeOrSpeed'",
":",
"'0'",
",",
"'FloatingPointExceptions'",
":",
"'true'",
",",
"'FloatingPointModel'",
":",
"'1'",
",",
"'ForceConformanceInForLoopScope'",
":",
"'true'",
",",
"'ForcedIncludeFiles'",
":",
"'file1;file2;file3'",
",",
"'ForcedUsingFiles'",
":",
"'file1;file2;file3'",
",",
"'GeneratePreprocessedFile'",
":",
"'1'",
",",
"'GenerateXMLDocumentationFiles'",
":",
"'true'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InlineFunctionExpansion'",
":",
"'2'",
",",
"'KeepComments'",
":",
"'true'",
",",
"'MinimalRebuild'",
":",
"'true'",
",",
"'ObjectFile'",
":",
"'a_file_name'",
",",
"'OmitDefaultLibName'",
":",
"'true'",
",",
"'OmitFramePointers'",
":",
"'true'",
",",
"'OpenMP'",
":",
"'true'",
",",
"'Optimization'",
":",
"'3'",
",",
"'PrecompiledHeaderFile'",
":",
"'a_file_name'",
",",
"'PrecompiledHeaderThrough'",
":",
"'a_file_name'",
",",
"'PreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ProgramDataBaseFileName'",
":",
"'a_file_name'",
",",
"'RuntimeLibrary'",
":",
"'0'",
",",
"'RuntimeTypeInfo'",
":",
"'true'",
",",
"'ShowIncludes'",
":",
"'true'",
",",
"'SmallerTypeCheck'",
":",
"'true'",
",",
"'StringPooling'",
":",
"'true'",
",",
"'StructMemberAlignment'",
":",
"'1'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TreatWChar_tAsBuiltInType'",
":",
"'true'",
",",
"'UndefineAllPreprocessorDefinitions'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'UseFullPaths'",
":",
"'true'",
",",
"'UsePrecompiledHeader'",
":",
"'1'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'2'",
",",
"'WholeProgramOptimization'",
":",
"'true'",
",",
"'XMLDocumentationFileName'",
":",
"'a_file_name'",
"}",
",",
"'VCLinkerTool'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2;file3'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalLibraryDirectories_excluded'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalManifestDependencies'",
":",
"'file1;file2;file3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'AddModuleNamesToAssembly'",
":",
"'file1;file2;file3'",
",",
"'AllowIsolation'",
":",
"'true'",
",",
"'AssemblyDebug'",
":",
"'0'",
",",
"'AssemblyLinkResource'",
":",
"'file1;file2;file3'",
",",
"'BaseAddress'",
":",
"'a_string'",
",",
"'CLRImageType'",
":",
"'1'",
",",
"'CLRThreadAttribute'",
":",
"'2'",
",",
"'CLRUnmanagedCodeCheck'",
":",
"'true'",
",",
"'DataExecutionPrevention'",
":",
"'0'",
",",
"'DelayLoadDLLs'",
":",
"'file1;file2;file3'",
",",
"'DelaySign'",
":",
"'true'",
",",
"'Driver'",
":",
"'1'",
",",
"'EmbedManagedResourceFile'",
":",
"'file1;file2;file3'",
",",
"'EnableCOMDATFolding'",
":",
"'0'",
",",
"'EnableUAC'",
":",
"'true'",
",",
"'EntryPointSymbol'",
":",
"'a_string'",
",",
"'ErrorReporting'",
":",
"'0'",
",",
"'FixedBaseAddress'",
":",
"'1'",
",",
"'ForceSymbolReferences'",
":",
"'file1;file2;file3'",
",",
"'FunctionOrder'",
":",
"'a_file_name'",
",",
"'GenerateDebugInformation'",
":",
"'true'",
",",
"'GenerateManifest'",
":",
"'true'",
",",
"'GenerateMapFile'",
":",
"'true'",
",",
"'HeapCommitSize'",
":",
"'a_string'",
",",
"'HeapReserveSize'",
":",
"'a_string'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreDefaultLibraryNames'",
":",
"'file1;file2;file3'",
",",
"'IgnoreEmbeddedIDL'",
":",
"'true'",
",",
"'IgnoreImportLibrary'",
":",
"'true'",
",",
"'ImportLibrary'",
":",
"'a_file_name'",
",",
"'KeyContainer'",
":",
"'a_file_name'",
",",
"'KeyFile'",
":",
"'a_file_name'",
",",
"'LargeAddressAware'",
":",
"'2'",
",",
"'LinkIncremental'",
":",
"'1'",
",",
"'LinkLibraryDependencies'",
":",
"'true'",
",",
"'LinkTimeCodeGeneration'",
":",
"'2'",
",",
"'ManifestFile'",
":",
"'a_file_name'",
",",
"'MapExports'",
":",
"'true'",
",",
"'MapFileName'",
":",
"'a_file_name'",
",",
"'MergedIDLBaseFileName'",
":",
"'a_file_name'",
",",
"'MergeSections'",
":",
"'a_string'",
",",
"'MidlCommandFile'",
":",
"'a_file_name'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'OptimizeForWindows98'",
":",
"'1'",
",",
"'OptimizeReferences'",
":",
"'0'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'PerUserRedirection'",
":",
"'true'",
",",
"'Profile'",
":",
"'true'",
",",
"'ProfileGuidedDatabase'",
":",
"'a_file_name'",
",",
"'ProgramDatabaseFile'",
":",
"'a_file_name'",
",",
"'RandomizedBaseAddress'",
":",
"'1'",
",",
"'RegisterOutput'",
":",
"'true'",
",",
"'ResourceOnlyDLL'",
":",
"'true'",
",",
"'SetChecksum'",
":",
"'true'",
",",
"'ShowProgress'",
":",
"'0'",
",",
"'StackCommitSize'",
":",
"'a_string'",
",",
"'StackReserveSize'",
":",
"'a_string'",
",",
"'StripPrivateSymbols'",
":",
"'a_file_name'",
",",
"'SubSystem'",
":",
"'2'",
",",
"'SupportUnloadOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'SwapRunFromCD'",
":",
"'true'",
",",
"'SwapRunFromNet'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'3'",
",",
"'TerminalServerAware'",
":",
"'2'",
",",
"'TurnOffAssemblyGeneration'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'TypeLibraryResourceID'",
":",
"'33'",
",",
"'UACExecutionLevel'",
":",
"'1'",
",",
"'UACUIAccess'",
":",
"'true'",
",",
"'UseLibraryDependencyInputs'",
":",
"'false'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'Version'",
":",
"'a_string'",
"}",
",",
"'VCResourceCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'Culture'",
":",
"'1003'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ResourceOutputFileName'",
":",
"'a_string'",
",",
"'ShowProgress'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'d1;d2;d3'",
"}",
",",
"'VCMIDLTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'CPreprocessOptions'",
":",
"'a_string'",
",",
"'DefaultCharType'",
":",
"'0'",
",",
"'DLLDataFileName'",
":",
"'a_file_name'",
",",
"'EnableErrorChecks'",
":",
"'2'",
",",
"'ErrorCheckAllocations'",
":",
"'true'",
",",
"'ErrorCheckBounds'",
":",
"'true'",
",",
"'ErrorCheckEnumRange'",
":",
"'true'",
",",
"'ErrorCheckRefPointers'",
":",
"'true'",
",",
"'ErrorCheckStubData'",
":",
"'true'",
",",
"'GenerateStublessProxies'",
":",
"'true'",
",",
"'GenerateTypeLibrary'",
":",
"'true'",
",",
"'HeaderFileName'",
":",
"'a_file_name'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InterfaceIdentifierFileName'",
":",
"'a_file_name'",
",",
"'MkTypLibCompatible'",
":",
"'true'",
",",
"'OutputDirectory'",
":",
"'a_string'",
",",
"'PreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ProxyFileName'",
":",
"'a_file_name'",
",",
"'RedirectOutputAndErrors'",
":",
"'a_file_name'",
",",
"'StructMemberAlignment'",
":",
"'3'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TargetEnvironment'",
":",
"'1'",
",",
"'TypeLibraryName'",
":",
"'a_file_name'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ValidateParameters'",
":",
"'true'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'4'",
"}",
",",
"'VCLibrarianTool'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2;file3'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalLibraryDirectories_excluded'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'ExportNamedFunctions'",
":",
"'d1;d2;d3'",
",",
"'ForceSymbolReferences'",
":",
"'a_string'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'file1;file2;file3'",
",",
"'LinkLibraryDependencies'",
":",
"'true'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
"}",
",",
"'VCManifestTool'",
":",
"{",
"'AdditionalManifestFiles'",
":",
"'file1;file2;file3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'AssemblyIdentity'",
":",
"'a_string'",
",",
"'ComponentFileName'",
":",
"'a_file_name'",
",",
"'DependencyInformationFile'",
":",
"'a_file_name'",
",",
"'EmbedManifest'",
":",
"'true'",
",",
"'GenerateCatalogFiles'",
":",
"'true'",
",",
"'InputResourceManifests'",
":",
"'a_string'",
",",
"'ManifestResourceFile'",
":",
"'my_name'",
",",
"'OutputManifestFile'",
":",
"'a_file_name'",
",",
"'RegistrarScriptFile'",
":",
"'a_file_name'",
",",
"'ReplacementsFile'",
":",
"'a_file_name'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'UpdateFileHashes'",
":",
"'true'",
",",
"'UpdateFileHashesSearchPath'",
":",
"'a_file_name'",
",",
"'UseFAT32Workaround'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
",",
"'VerboseOutput'",
":",
"'true'",
"}",
"}",
"expected_msbuild_settings",
"=",
"{",
"'ClCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string /J'",
",",
"'AdditionalUsingDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AssemblerListingLocation'",
":",
"'a_file_name'",
",",
"'AssemblerOutput'",
":",
"'NoListing'",
",",
"'BasicRuntimeChecks'",
":",
"'StackFrameRuntimeCheck'",
",",
"'BrowseInformation'",
":",
"'true'",
",",
"'BrowseInformationFile'",
":",
"'a_file_name'",
",",
"'BufferSecurityCheck'",
":",
"'true'",
",",
"'CallingConvention'",
":",
"'Cdecl'",
",",
"'CompileAs'",
":",
"'CompileAsC'",
",",
"'DebugInformationFormat'",
":",
"'EditAndContinue'",
",",
"'DisableLanguageExtensions'",
":",
"'true'",
",",
"'DisableSpecificWarnings'",
":",
"'d1;d2;d3'",
",",
"'EnableEnhancedInstructionSet'",
":",
"'NotSet'",
",",
"'EnableFiberSafeOptimizations'",
":",
"'true'",
",",
"'EnablePREfast'",
":",
"'true'",
",",
"'ErrorReporting'",
":",
"'Prompt'",
",",
"'ExceptionHandling'",
":",
"'Async'",
",",
"'ExpandAttributedSource'",
":",
"'true'",
",",
"'FavorSizeOrSpeed'",
":",
"'Neither'",
",",
"'FloatingPointExceptions'",
":",
"'true'",
",",
"'FloatingPointModel'",
":",
"'Strict'",
",",
"'ForceConformanceInForLoopScope'",
":",
"'true'",
",",
"'ForcedIncludeFiles'",
":",
"'file1;file2;file3'",
",",
"'ForcedUsingFiles'",
":",
"'file1;file2;file3'",
",",
"'FunctionLevelLinking'",
":",
"'true'",
",",
"'GenerateXMLDocumentationFiles'",
":",
"'true'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InlineFunctionExpansion'",
":",
"'AnySuitable'",
",",
"'IntrinsicFunctions'",
":",
"'true'",
",",
"'MinimalRebuild'",
":",
"'true'",
",",
"'ObjectFileName'",
":",
"'a_file_name'",
",",
"'OmitDefaultLibName'",
":",
"'true'",
",",
"'OmitFramePointers'",
":",
"'true'",
",",
"'OpenMPSupport'",
":",
"'true'",
",",
"'Optimization'",
":",
"'Full'",
",",
"'PrecompiledHeader'",
":",
"'Create'",
",",
"'PrecompiledHeaderFile'",
":",
"'a_file_name'",
",",
"'PrecompiledHeaderOutputFile'",
":",
"'a_file_name'",
",",
"'PreprocessKeepComments'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'PreprocessSuppressLineNumbers'",
":",
"'false'",
",",
"'PreprocessToFile'",
":",
"'true'",
",",
"'ProgramDataBaseFileName'",
":",
"'a_file_name'",
",",
"'RuntimeLibrary'",
":",
"'MultiThreaded'",
",",
"'RuntimeTypeInfo'",
":",
"'true'",
",",
"'ShowIncludes'",
":",
"'true'",
",",
"'SmallerTypeCheck'",
":",
"'true'",
",",
"'StringPooling'",
":",
"'true'",
",",
"'StructMemberAlignment'",
":",
"'1Byte'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TreatWarningAsError'",
":",
"'true'",
",",
"'TreatWChar_tAsBuiltInType'",
":",
"'true'",
",",
"'UndefineAllPreprocessorDefinitions'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'UseFullPaths'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'Level2'",
",",
"'WholeProgramOptimization'",
":",
"'true'",
",",
"'XMLDocumentationFileName'",
":",
"'a_file_name'",
"}",
",",
"'Link'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2;file3'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalManifestDependencies'",
":",
"'file1;file2;file3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'AddModuleNamesToAssembly'",
":",
"'file1;file2;file3'",
",",
"'AllowIsolation'",
":",
"'true'",
",",
"'AssemblyDebug'",
":",
"''",
",",
"'AssemblyLinkResource'",
":",
"'file1;file2;file3'",
",",
"'BaseAddress'",
":",
"'a_string'",
",",
"'CLRImageType'",
":",
"'ForceIJWImage'",
",",
"'CLRThreadAttribute'",
":",
"'STAThreadingAttribute'",
",",
"'CLRUnmanagedCodeCheck'",
":",
"'true'",
",",
"'DataExecutionPrevention'",
":",
"''",
",",
"'DelayLoadDLLs'",
":",
"'file1;file2;file3'",
",",
"'DelaySign'",
":",
"'true'",
",",
"'Driver'",
":",
"'Driver'",
",",
"'EmbedManagedResourceFile'",
":",
"'file1;file2;file3'",
",",
"'EnableCOMDATFolding'",
":",
"''",
",",
"'EnableUAC'",
":",
"'true'",
",",
"'EntryPointSymbol'",
":",
"'a_string'",
",",
"'FixedBaseAddress'",
":",
"'false'",
",",
"'ForceSymbolReferences'",
":",
"'file1;file2;file3'",
",",
"'FunctionOrder'",
":",
"'a_file_name'",
",",
"'GenerateDebugInformation'",
":",
"'true'",
",",
"'GenerateMapFile'",
":",
"'true'",
",",
"'HeapCommitSize'",
":",
"'a_string'",
",",
"'HeapReserveSize'",
":",
"'a_string'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreEmbeddedIDL'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'file1;file2;file3'",
",",
"'ImportLibrary'",
":",
"'a_file_name'",
",",
"'KeyContainer'",
":",
"'a_file_name'",
",",
"'KeyFile'",
":",
"'a_file_name'",
",",
"'LargeAddressAware'",
":",
"'true'",
",",
"'LinkErrorReporting'",
":",
"'NoErrorReport'",
",",
"'LinkTimeCodeGeneration'",
":",
"'PGInstrument'",
",",
"'ManifestFile'",
":",
"'a_file_name'",
",",
"'MapExports'",
":",
"'true'",
",",
"'MapFileName'",
":",
"'a_file_name'",
",",
"'MergedIDLBaseFileName'",
":",
"'a_file_name'",
",",
"'MergeSections'",
":",
"'a_string'",
",",
"'MidlCommandFile'",
":",
"'a_file_name'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'NoEntryPoint'",
":",
"'true'",
",",
"'OptimizeReferences'",
":",
"''",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'PerUserRedirection'",
":",
"'true'",
",",
"'Profile'",
":",
"'true'",
",",
"'ProfileGuidedDatabase'",
":",
"'a_file_name'",
",",
"'ProgramDatabaseFile'",
":",
"'a_file_name'",
",",
"'RandomizedBaseAddress'",
":",
"'false'",
",",
"'RegisterOutput'",
":",
"'true'",
",",
"'SetChecksum'",
":",
"'true'",
",",
"'ShowProgress'",
":",
"'NotSet'",
",",
"'StackCommitSize'",
":",
"'a_string'",
",",
"'StackReserveSize'",
":",
"'a_string'",
",",
"'StripPrivateSymbols'",
":",
"'a_file_name'",
",",
"'SubSystem'",
":",
"'Windows'",
",",
"'SupportUnloadOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'SwapRunFromCD'",
":",
"'true'",
",",
"'SwapRunFromNET'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'MachineARM'",
",",
"'TerminalServerAware'",
":",
"'true'",
",",
"'TurnOffAssemblyGeneration'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'TypeLibraryResourceID'",
":",
"'33'",
",",
"'UACExecutionLevel'",
":",
"'HighestAvailable'",
",",
"'UACUIAccess'",
":",
"'true'",
",",
"'Version'",
":",
"'a_string'",
"}",
",",
"'ResourceCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'Culture'",
":",
"'0x03eb'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ResourceOutputFileName'",
":",
"'a_string'",
",",
"'ShowProgress'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'d1;d2;d3'",
"}",
",",
"'Midl'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'CPreprocessOptions'",
":",
"'a_string'",
",",
"'DefaultCharType'",
":",
"'Unsigned'",
",",
"'DllDataFileName'",
":",
"'a_file_name'",
",",
"'EnableErrorChecks'",
":",
"'All'",
",",
"'ErrorCheckAllocations'",
":",
"'true'",
",",
"'ErrorCheckBounds'",
":",
"'true'",
",",
"'ErrorCheckEnumRange'",
":",
"'true'",
",",
"'ErrorCheckRefPointers'",
":",
"'true'",
",",
"'ErrorCheckStubData'",
":",
"'true'",
",",
"'GenerateStublessProxies'",
":",
"'true'",
",",
"'GenerateTypeLibrary'",
":",
"'true'",
",",
"'HeaderFileName'",
":",
"'a_file_name'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InterfaceIdentifierFileName'",
":",
"'a_file_name'",
",",
"'MkTypLibCompatible'",
":",
"'true'",
",",
"'OutputDirectory'",
":",
"'a_string'",
",",
"'PreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ProxyFileName'",
":",
"'a_file_name'",
",",
"'RedirectOutputAndErrors'",
":",
"'a_file_name'",
",",
"'StructMemberAlignment'",
":",
"'4'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TargetEnvironment'",
":",
"'Win32'",
",",
"'TypeLibraryName'",
":",
"'a_file_name'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'d1;d2;d3'",
",",
"'ValidateAllParameters'",
":",
"'true'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'4'",
"}",
",",
"'Lib'",
":",
"{",
"'AdditionalDependencies'",
":",
"'file1;file2;file3'",
",",
"'AdditionalLibraryDirectories'",
":",
"'folder1;folder2;folder3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'ExportNamedFunctions'",
":",
"'d1;d2;d3'",
",",
"'ForceSymbolReferences'",
":",
"'a_string'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'file1;file2;file3'",
",",
"'ModuleDefinitionFile'",
":",
"'a_file_name'",
",",
"'OutputFile'",
":",
"'a_file_name'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'true'",
"}",
",",
"'Manifest'",
":",
"{",
"'AdditionalManifestFiles'",
":",
"'file1;file2;file3'",
",",
"'AdditionalOptions'",
":",
"'a_string'",
",",
"'AssemblyIdentity'",
":",
"'a_string'",
",",
"'ComponentFileName'",
":",
"'a_file_name'",
",",
"'GenerateCatalogFiles'",
":",
"'true'",
",",
"'InputResourceManifests'",
":",
"'a_string'",
",",
"'OutputManifestFile'",
":",
"'a_file_name'",
",",
"'RegistrarScriptFile'",
":",
"'a_file_name'",
",",
"'ReplacementsFile'",
":",
"'a_file_name'",
",",
"'SuppressStartupBanner'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'a_file_name'",
",",
"'UpdateFileHashes'",
":",
"'true'",
",",
"'UpdateFileHashesSearchPath'",
":",
"'a_file_name'",
",",
"'VerboseOutput'",
":",
"'true'",
"}",
",",
"'ManifestResourceCompile'",
":",
"{",
"'ResourceOutputFileName'",
":",
"'my_name'",
"}",
",",
"'ProjectReference'",
":",
"{",
"'LinkLibraryDependencies'",
":",
"'true'",
",",
"'UseLibraryDependencyInputs'",
":",
"'false'",
"}",
",",
"''",
":",
"{",
"'EmbedManifest'",
":",
"'true'",
",",
"'GenerateManifest'",
":",
"'true'",
",",
"'IgnoreImportLibrary'",
":",
"'true'",
",",
"'LinkIncremental'",
":",
"'false'",
"}",
"}",
"actual_msbuild_settings",
"=",
"MSVSSettings",
".",
"ConvertToMSBuildSettings",
"(",
"msvs_settings",
",",
"self",
".",
"stderr",
")",
"self",
".",
"assertEqual",
"(",
"expected_msbuild_settings",
",",
"actual_msbuild_settings",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"]",
")"
] | [
654,
2
] | [
1087,
30
] | python | en | ['en', 'en', 'en'] | True |
TestSequenceFunctions.testConvertToMSBuildSettings_actual | (self) | Tests the conversion of an actual project.
A VS2008 project with most of the options defined was created through the
VS2008 IDE. It was then converted to VS2010. The tool settings found in
the .vcproj and .vcxproj files were converted to the two dictionaries
msvs_settings and expected_msbuild_settings.
Note that for many settings, the VS2010 converter adds macros like
%(AdditionalIncludeDirectories) to make sure than inherited values are
included. Since the Gyp projects we generate do not use inheritance,
we removed these macros. They were:
ClCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)'
AdditionalOptions: ' %(AdditionalOptions)'
AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)'
DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
ForcedIncludeFiles: ';%(ForcedIncludeFiles)',
ForcedUsingFiles: ';%(ForcedUsingFiles)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
UndefinePreprocessorDefinitions:
';%(UndefinePreprocessorDefinitions)',
Link:
AdditionalDependencies: ';%(AdditionalDependencies)',
AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)',
AdditionalManifestDependencies:
';%(AdditionalManifestDependencies)',
AdditionalOptions: ' %(AdditionalOptions)',
AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)',
AssemblyLinkResource: ';%(AssemblyLinkResource)',
DelayLoadDLLs: ';%(DelayLoadDLLs)',
EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)',
ForceSymbolReferences: ';%(ForceSymbolReferences)',
IgnoreSpecificDefaultLibraries:
';%(IgnoreSpecificDefaultLibraries)',
ResourceCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)',
AdditionalOptions: ' %(AdditionalOptions)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
Manifest:
AdditionalManifestFiles: ';%(AdditionalManifestFiles)',
AdditionalOptions: ' %(AdditionalOptions)',
InputResourceManifests: ';%(InputResourceManifests)',
| Tests the conversion of an actual project. | def testConvertToMSBuildSettings_actual(self):
"""Tests the conversion of an actual project.
A VS2008 project with most of the options defined was created through the
VS2008 IDE. It was then converted to VS2010. The tool settings found in
the .vcproj and .vcxproj files were converted to the two dictionaries
msvs_settings and expected_msbuild_settings.
Note that for many settings, the VS2010 converter adds macros like
%(AdditionalIncludeDirectories) to make sure than inherited values are
included. Since the Gyp projects we generate do not use inheritance,
we removed these macros. They were:
ClCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)'
AdditionalOptions: ' %(AdditionalOptions)'
AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)'
DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
ForcedIncludeFiles: ';%(ForcedIncludeFiles)',
ForcedUsingFiles: ';%(ForcedUsingFiles)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
UndefinePreprocessorDefinitions:
';%(UndefinePreprocessorDefinitions)',
Link:
AdditionalDependencies: ';%(AdditionalDependencies)',
AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)',
AdditionalManifestDependencies:
';%(AdditionalManifestDependencies)',
AdditionalOptions: ' %(AdditionalOptions)',
AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)',
AssemblyLinkResource: ';%(AssemblyLinkResource)',
DelayLoadDLLs: ';%(DelayLoadDLLs)',
EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)',
ForceSymbolReferences: ';%(ForceSymbolReferences)',
IgnoreSpecificDefaultLibraries:
';%(IgnoreSpecificDefaultLibraries)',
ResourceCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)',
AdditionalOptions: ' %(AdditionalOptions)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
Manifest:
AdditionalManifestFiles: ';%(AdditionalManifestFiles)',
AdditionalOptions: ' %(AdditionalOptions)',
InputResourceManifests: ';%(InputResourceManifests)',
"""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)\\a',
'AssemblerOutput': '1',
'BasicRuntimeChecks': '3',
'BrowseInformation': '1',
'BrowseInformationFile': '$(IntDir)\\e',
'BufferSecurityCheck': 'false',
'CallingConvention': '1',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '2',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '2',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'GeneratePreprocessedFile': '2',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': '$(IntDir)\\b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': '$(IntDir)\\$(TargetName).pche',
'PrecompiledHeaderThrough': 'StdAfx.hd',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'ProgramDataBaseFileName': '$(IntDir)\\vc90b.pdb',
'RuntimeLibrary': '3',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'false',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '0',
'UseUnicodeResponseFiles': 'false',
'WarnAsError': 'true',
'WarningLevel': '3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)\\c'},
'VCLinkerTool': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': '1',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': '3',
'CLRThreadAttribute': '1',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': '1',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'ErrorReporting': '2',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'false',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'flob;flok',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': '2',
'LinkIncremental': '0',
'LinkLibraryDependencies': 'false',
'LinkTimeCodeGeneration': '1',
'ManifestFile':
'$(IntDir)\\$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'OptimizeForWindows98': '2',
'OptimizeReferences': '2',
'OutputFile': '$(OutDir)\\$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'false',
'ShowProgress': '1',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': '1',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '1',
'TerminalServerAware': '1',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'false',
'Version': '333'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '3084',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)/$(InputName)3.res',
'ShowProgress': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'DependencyInformationFile': '$(IntDir)\\mt.depdfd',
'EmbedManifest': 'false',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'ManifestResourceFile':
'$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'false',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more /J',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)a',
'AssemblerOutput': 'AssemblyCode',
'BasicRuntimeChecks': 'EnableFastChecks',
'BrowseInformation': 'true',
'BrowseInformationFile': '$(IntDir)e',
'BufferSecurityCheck': 'false',
'CallingConvention': 'FastCall',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Queue',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Size',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': '$(IntDir)b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'NotUsing', # Actual conversion gives ''
'PrecompiledHeaderFile': 'StdAfx.hd',
'PrecompiledHeaderOutputFile': '$(IntDir)$(TargetName).pche',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'PreprocessSuppressLineNumbers': 'true',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': '$(IntDir)vc90b.pdb',
'RuntimeLibrary': 'MultiThreadedDebugDLL',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '4Bytes',
'SuppressStartupBanner': 'false',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'WarningLevel': 'Level3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)c'},
'Link': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': 'true',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': 'ForceSafeILImage',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': 'UpOnly',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'flob;flok',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'QueueForNextLogin',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': '$(IntDir)$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'NoEntryPoint': 'true',
'OptimizeReferences': 'true',
'OutputFile': '$(OutDir)$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'false',
'ShowProgress': 'LinkVerbose',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': 'Console',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': 'RequireAdministrator',
'UACUIAccess': 'true',
'Version': '333'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '0x0c0c',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)%(Filename)3.res',
'ShowProgress': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'false',
'UseLibraryDependencyInputs': 'true'},
'': {
'EmbedManifest': 'false',
'GenerateManifest': 'false',
'IgnoreImportLibrary': 'true',
'LinkIncremental': ''
},
'ManifestResourceCompile': {
'ResourceOutputFileName':
'$(IntDir)$(TargetFileName).embed.manifest.resfdsf'}
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([]) | [
"def",
"testConvertToMSBuildSettings_actual",
"(",
"self",
")",
":",
"msvs_settings",
"=",
"{",
"'VCCLCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'dir1'",
",",
"'AdditionalOptions'",
":",
"'/more'",
",",
"'AdditionalUsingDirectories'",
":",
"'test'",
",",
"'AssemblerListingLocation'",
":",
"'$(IntDir)\\\\a'",
",",
"'AssemblerOutput'",
":",
"'1'",
",",
"'BasicRuntimeChecks'",
":",
"'3'",
",",
"'BrowseInformation'",
":",
"'1'",
",",
"'BrowseInformationFile'",
":",
"'$(IntDir)\\\\e'",
",",
"'BufferSecurityCheck'",
":",
"'false'",
",",
"'CallingConvention'",
":",
"'1'",
",",
"'CompileAs'",
":",
"'1'",
",",
"'DebugInformationFormat'",
":",
"'4'",
",",
"'DefaultCharIsUnsigned'",
":",
"'true'",
",",
"'Detect64BitPortabilityProblems'",
":",
"'true'",
",",
"'DisableLanguageExtensions'",
":",
"'true'",
",",
"'DisableSpecificWarnings'",
":",
"'abc'",
",",
"'EnableEnhancedInstructionSet'",
":",
"'1'",
",",
"'EnableFiberSafeOptimizations'",
":",
"'true'",
",",
"'EnableFunctionLevelLinking'",
":",
"'true'",
",",
"'EnableIntrinsicFunctions'",
":",
"'true'",
",",
"'EnablePREfast'",
":",
"'true'",
",",
"'ErrorReporting'",
":",
"'2'",
",",
"'ExceptionHandling'",
":",
"'2'",
",",
"'ExpandAttributedSource'",
":",
"'true'",
",",
"'FavorSizeOrSpeed'",
":",
"'2'",
",",
"'FloatingPointExceptions'",
":",
"'true'",
",",
"'FloatingPointModel'",
":",
"'1'",
",",
"'ForceConformanceInForLoopScope'",
":",
"'false'",
",",
"'ForcedIncludeFiles'",
":",
"'def'",
",",
"'ForcedUsingFiles'",
":",
"'ge'",
",",
"'GeneratePreprocessedFile'",
":",
"'2'",
",",
"'GenerateXMLDocumentationFiles'",
":",
"'true'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InlineFunctionExpansion'",
":",
"'1'",
",",
"'KeepComments'",
":",
"'true'",
",",
"'MinimalRebuild'",
":",
"'true'",
",",
"'ObjectFile'",
":",
"'$(IntDir)\\\\b'",
",",
"'OmitDefaultLibName'",
":",
"'true'",
",",
"'OmitFramePointers'",
":",
"'true'",
",",
"'OpenMP'",
":",
"'true'",
",",
"'Optimization'",
":",
"'3'",
",",
"'PrecompiledHeaderFile'",
":",
"'$(IntDir)\\\\$(TargetName).pche'",
",",
"'PrecompiledHeaderThrough'",
":",
"'StdAfx.hd'",
",",
"'PreprocessorDefinitions'",
":",
"'WIN32;_DEBUG;_CONSOLE'",
",",
"'ProgramDataBaseFileName'",
":",
"'$(IntDir)\\\\vc90b.pdb'",
",",
"'RuntimeLibrary'",
":",
"'3'",
",",
"'RuntimeTypeInfo'",
":",
"'false'",
",",
"'ShowIncludes'",
":",
"'true'",
",",
"'SmallerTypeCheck'",
":",
"'true'",
",",
"'StringPooling'",
":",
"'true'",
",",
"'StructMemberAlignment'",
":",
"'3'",
",",
"'SuppressStartupBanner'",
":",
"'false'",
",",
"'TreatWChar_tAsBuiltInType'",
":",
"'false'",
",",
"'UndefineAllPreprocessorDefinitions'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'wer'",
",",
"'UseFullPaths'",
":",
"'true'",
",",
"'UsePrecompiledHeader'",
":",
"'0'",
",",
"'UseUnicodeResponseFiles'",
":",
"'false'",
",",
"'WarnAsError'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'3'",
",",
"'WholeProgramOptimization'",
":",
"'true'",
",",
"'XMLDocumentationFileName'",
":",
"'$(IntDir)\\\\c'",
"}",
",",
"'VCLinkerTool'",
":",
"{",
"'AdditionalDependencies'",
":",
"'zx'",
",",
"'AdditionalLibraryDirectories'",
":",
"'asd'",
",",
"'AdditionalManifestDependencies'",
":",
"'s2'",
",",
"'AdditionalOptions'",
":",
"'/mor2'",
",",
"'AddModuleNamesToAssembly'",
":",
"'d1'",
",",
"'AllowIsolation'",
":",
"'false'",
",",
"'AssemblyDebug'",
":",
"'1'",
",",
"'AssemblyLinkResource'",
":",
"'d5'",
",",
"'BaseAddress'",
":",
"'23423'",
",",
"'CLRImageType'",
":",
"'3'",
",",
"'CLRThreadAttribute'",
":",
"'1'",
",",
"'CLRUnmanagedCodeCheck'",
":",
"'true'",
",",
"'DataExecutionPrevention'",
":",
"'0'",
",",
"'DelayLoadDLLs'",
":",
"'d4'",
",",
"'DelaySign'",
":",
"'true'",
",",
"'Driver'",
":",
"'2'",
",",
"'EmbedManagedResourceFile'",
":",
"'d2'",
",",
"'EnableCOMDATFolding'",
":",
"'1'",
",",
"'EnableUAC'",
":",
"'false'",
",",
"'EntryPointSymbol'",
":",
"'f5'",
",",
"'ErrorReporting'",
":",
"'2'",
",",
"'FixedBaseAddress'",
":",
"'1'",
",",
"'ForceSymbolReferences'",
":",
"'d3'",
",",
"'FunctionOrder'",
":",
"'fssdfsd'",
",",
"'GenerateDebugInformation'",
":",
"'true'",
",",
"'GenerateManifest'",
":",
"'false'",
",",
"'GenerateMapFile'",
":",
"'true'",
",",
"'HeapCommitSize'",
":",
"'13'",
",",
"'HeapReserveSize'",
":",
"'12'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreDefaultLibraryNames'",
":",
"'flob;flok'",
",",
"'IgnoreEmbeddedIDL'",
":",
"'true'",
",",
"'IgnoreImportLibrary'",
":",
"'true'",
",",
"'ImportLibrary'",
":",
"'f4'",
",",
"'KeyContainer'",
":",
"'f7'",
",",
"'KeyFile'",
":",
"'f6'",
",",
"'LargeAddressAware'",
":",
"'2'",
",",
"'LinkIncremental'",
":",
"'0'",
",",
"'LinkLibraryDependencies'",
":",
"'false'",
",",
"'LinkTimeCodeGeneration'",
":",
"'1'",
",",
"'ManifestFile'",
":",
"'$(IntDir)\\\\$(TargetFileName).2intermediate.manifest'",
",",
"'MapExports'",
":",
"'true'",
",",
"'MapFileName'",
":",
"'d5'",
",",
"'MergedIDLBaseFileName'",
":",
"'f2'",
",",
"'MergeSections'",
":",
"'f5'",
",",
"'MidlCommandFile'",
":",
"'f1'",
",",
"'ModuleDefinitionFile'",
":",
"'sdsd'",
",",
"'OptimizeForWindows98'",
":",
"'2'",
",",
"'OptimizeReferences'",
":",
"'2'",
",",
"'OutputFile'",
":",
"'$(OutDir)\\\\$(ProjectName)2.exe'",
",",
"'PerUserRedirection'",
":",
"'true'",
",",
"'Profile'",
":",
"'true'",
",",
"'ProfileGuidedDatabase'",
":",
"'$(TargetDir)$(TargetName).pgdd'",
",",
"'ProgramDatabaseFile'",
":",
"'Flob.pdb'",
",",
"'RandomizedBaseAddress'",
":",
"'1'",
",",
"'RegisterOutput'",
":",
"'true'",
",",
"'ResourceOnlyDLL'",
":",
"'true'",
",",
"'SetChecksum'",
":",
"'false'",
",",
"'ShowProgress'",
":",
"'1'",
",",
"'StackCommitSize'",
":",
"'15'",
",",
"'StackReserveSize'",
":",
"'14'",
",",
"'StripPrivateSymbols'",
":",
"'d3'",
",",
"'SubSystem'",
":",
"'1'",
",",
"'SupportUnloadOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'false'",
",",
"'SwapRunFromCD'",
":",
"'true'",
",",
"'SwapRunFromNet'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'1'",
",",
"'TerminalServerAware'",
":",
"'1'",
",",
"'TurnOffAssemblyGeneration'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'f3'",
",",
"'TypeLibraryResourceID'",
":",
"'12'",
",",
"'UACExecutionLevel'",
":",
"'2'",
",",
"'UACUIAccess'",
":",
"'true'",
",",
"'UseLibraryDependencyInputs'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'false'",
",",
"'Version'",
":",
"'333'",
"}",
",",
"'VCResourceCompilerTool'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'f3'",
",",
"'AdditionalOptions'",
":",
"'/more3'",
",",
"'Culture'",
":",
"'3084'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'_UNICODE;UNICODE2'",
",",
"'ResourceOutputFileName'",
":",
"'$(IntDir)/$(InputName)3.res'",
",",
"'ShowProgress'",
":",
"'true'",
"}",
",",
"'VCManifestTool'",
":",
"{",
"'AdditionalManifestFiles'",
":",
"'sfsdfsd'",
",",
"'AdditionalOptions'",
":",
"'afdsdafsd'",
",",
"'AssemblyIdentity'",
":",
"'sddfdsadfsa'",
",",
"'ComponentFileName'",
":",
"'fsdfds'",
",",
"'DependencyInformationFile'",
":",
"'$(IntDir)\\\\mt.depdfd'",
",",
"'EmbedManifest'",
":",
"'false'",
",",
"'GenerateCatalogFiles'",
":",
"'true'",
",",
"'InputResourceManifests'",
":",
"'asfsfdafs'",
",",
"'ManifestResourceFile'",
":",
"'$(IntDir)\\\\$(TargetFileName).embed.manifest.resfdsf'",
",",
"'OutputManifestFile'",
":",
"'$(TargetPath).manifestdfs'",
",",
"'RegistrarScriptFile'",
":",
"'sdfsfd'",
",",
"'ReplacementsFile'",
":",
"'sdffsd'",
",",
"'SuppressStartupBanner'",
":",
"'false'",
",",
"'TypeLibraryFile'",
":",
"'sfsd'",
",",
"'UpdateFileHashes'",
":",
"'true'",
",",
"'UpdateFileHashesSearchPath'",
":",
"'sfsd'",
",",
"'UseFAT32Workaround'",
":",
"'true'",
",",
"'UseUnicodeResponseFiles'",
":",
"'false'",
",",
"'VerboseOutput'",
":",
"'true'",
"}",
"}",
"expected_msbuild_settings",
"=",
"{",
"'ClCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'dir1'",
",",
"'AdditionalOptions'",
":",
"'/more /J'",
",",
"'AdditionalUsingDirectories'",
":",
"'test'",
",",
"'AssemblerListingLocation'",
":",
"'$(IntDir)a'",
",",
"'AssemblerOutput'",
":",
"'AssemblyCode'",
",",
"'BasicRuntimeChecks'",
":",
"'EnableFastChecks'",
",",
"'BrowseInformation'",
":",
"'true'",
",",
"'BrowseInformationFile'",
":",
"'$(IntDir)e'",
",",
"'BufferSecurityCheck'",
":",
"'false'",
",",
"'CallingConvention'",
":",
"'FastCall'",
",",
"'CompileAs'",
":",
"'CompileAsC'",
",",
"'DebugInformationFormat'",
":",
"'EditAndContinue'",
",",
"'DisableLanguageExtensions'",
":",
"'true'",
",",
"'DisableSpecificWarnings'",
":",
"'abc'",
",",
"'EnableEnhancedInstructionSet'",
":",
"'StreamingSIMDExtensions'",
",",
"'EnableFiberSafeOptimizations'",
":",
"'true'",
",",
"'EnablePREfast'",
":",
"'true'",
",",
"'ErrorReporting'",
":",
"'Queue'",
",",
"'ExceptionHandling'",
":",
"'Async'",
",",
"'ExpandAttributedSource'",
":",
"'true'",
",",
"'FavorSizeOrSpeed'",
":",
"'Size'",
",",
"'FloatingPointExceptions'",
":",
"'true'",
",",
"'FloatingPointModel'",
":",
"'Strict'",
",",
"'ForceConformanceInForLoopScope'",
":",
"'false'",
",",
"'ForcedIncludeFiles'",
":",
"'def'",
",",
"'ForcedUsingFiles'",
":",
"'ge'",
",",
"'FunctionLevelLinking'",
":",
"'true'",
",",
"'GenerateXMLDocumentationFiles'",
":",
"'true'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'InlineFunctionExpansion'",
":",
"'OnlyExplicitInline'",
",",
"'IntrinsicFunctions'",
":",
"'true'",
",",
"'MinimalRebuild'",
":",
"'true'",
",",
"'ObjectFileName'",
":",
"'$(IntDir)b'",
",",
"'OmitDefaultLibName'",
":",
"'true'",
",",
"'OmitFramePointers'",
":",
"'true'",
",",
"'OpenMPSupport'",
":",
"'true'",
",",
"'Optimization'",
":",
"'Full'",
",",
"'PrecompiledHeader'",
":",
"'NotUsing'",
",",
"# Actual conversion gives ''",
"'PrecompiledHeaderFile'",
":",
"'StdAfx.hd'",
",",
"'PrecompiledHeaderOutputFile'",
":",
"'$(IntDir)$(TargetName).pche'",
",",
"'PreprocessKeepComments'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'WIN32;_DEBUG;_CONSOLE'",
",",
"'PreprocessSuppressLineNumbers'",
":",
"'true'",
",",
"'PreprocessToFile'",
":",
"'true'",
",",
"'ProgramDataBaseFileName'",
":",
"'$(IntDir)vc90b.pdb'",
",",
"'RuntimeLibrary'",
":",
"'MultiThreadedDebugDLL'",
",",
"'RuntimeTypeInfo'",
":",
"'false'",
",",
"'ShowIncludes'",
":",
"'true'",
",",
"'SmallerTypeCheck'",
":",
"'true'",
",",
"'StringPooling'",
":",
"'true'",
",",
"'StructMemberAlignment'",
":",
"'4Bytes'",
",",
"'SuppressStartupBanner'",
":",
"'false'",
",",
"'TreatWarningAsError'",
":",
"'true'",
",",
"'TreatWChar_tAsBuiltInType'",
":",
"'false'",
",",
"'UndefineAllPreprocessorDefinitions'",
":",
"'true'",
",",
"'UndefinePreprocessorDefinitions'",
":",
"'wer'",
",",
"'UseFullPaths'",
":",
"'true'",
",",
"'WarningLevel'",
":",
"'Level3'",
",",
"'WholeProgramOptimization'",
":",
"'true'",
",",
"'XMLDocumentationFileName'",
":",
"'$(IntDir)c'",
"}",
",",
"'Link'",
":",
"{",
"'AdditionalDependencies'",
":",
"'zx'",
",",
"'AdditionalLibraryDirectories'",
":",
"'asd'",
",",
"'AdditionalManifestDependencies'",
":",
"'s2'",
",",
"'AdditionalOptions'",
":",
"'/mor2'",
",",
"'AddModuleNamesToAssembly'",
":",
"'d1'",
",",
"'AllowIsolation'",
":",
"'false'",
",",
"'AssemblyDebug'",
":",
"'true'",
",",
"'AssemblyLinkResource'",
":",
"'d5'",
",",
"'BaseAddress'",
":",
"'23423'",
",",
"'CLRImageType'",
":",
"'ForceSafeILImage'",
",",
"'CLRThreadAttribute'",
":",
"'MTAThreadingAttribute'",
",",
"'CLRUnmanagedCodeCheck'",
":",
"'true'",
",",
"'DataExecutionPrevention'",
":",
"''",
",",
"'DelayLoadDLLs'",
":",
"'d4'",
",",
"'DelaySign'",
":",
"'true'",
",",
"'Driver'",
":",
"'UpOnly'",
",",
"'EmbedManagedResourceFile'",
":",
"'d2'",
",",
"'EnableCOMDATFolding'",
":",
"'false'",
",",
"'EnableUAC'",
":",
"'false'",
",",
"'EntryPointSymbol'",
":",
"'f5'",
",",
"'FixedBaseAddress'",
":",
"'false'",
",",
"'ForceSymbolReferences'",
":",
"'d3'",
",",
"'FunctionOrder'",
":",
"'fssdfsd'",
",",
"'GenerateDebugInformation'",
":",
"'true'",
",",
"'GenerateMapFile'",
":",
"'true'",
",",
"'HeapCommitSize'",
":",
"'13'",
",",
"'HeapReserveSize'",
":",
"'12'",
",",
"'IgnoreAllDefaultLibraries'",
":",
"'true'",
",",
"'IgnoreEmbeddedIDL'",
":",
"'true'",
",",
"'IgnoreSpecificDefaultLibraries'",
":",
"'flob;flok'",
",",
"'ImportLibrary'",
":",
"'f4'",
",",
"'KeyContainer'",
":",
"'f7'",
",",
"'KeyFile'",
":",
"'f6'",
",",
"'LargeAddressAware'",
":",
"'true'",
",",
"'LinkErrorReporting'",
":",
"'QueueForNextLogin'",
",",
"'LinkTimeCodeGeneration'",
":",
"'UseLinkTimeCodeGeneration'",
",",
"'ManifestFile'",
":",
"'$(IntDir)$(TargetFileName).2intermediate.manifest'",
",",
"'MapExports'",
":",
"'true'",
",",
"'MapFileName'",
":",
"'d5'",
",",
"'MergedIDLBaseFileName'",
":",
"'f2'",
",",
"'MergeSections'",
":",
"'f5'",
",",
"'MidlCommandFile'",
":",
"'f1'",
",",
"'ModuleDefinitionFile'",
":",
"'sdsd'",
",",
"'NoEntryPoint'",
":",
"'true'",
",",
"'OptimizeReferences'",
":",
"'true'",
",",
"'OutputFile'",
":",
"'$(OutDir)$(ProjectName)2.exe'",
",",
"'PerUserRedirection'",
":",
"'true'",
",",
"'Profile'",
":",
"'true'",
",",
"'ProfileGuidedDatabase'",
":",
"'$(TargetDir)$(TargetName).pgdd'",
",",
"'ProgramDatabaseFile'",
":",
"'Flob.pdb'",
",",
"'RandomizedBaseAddress'",
":",
"'false'",
",",
"'RegisterOutput'",
":",
"'true'",
",",
"'SetChecksum'",
":",
"'false'",
",",
"'ShowProgress'",
":",
"'LinkVerbose'",
",",
"'StackCommitSize'",
":",
"'15'",
",",
"'StackReserveSize'",
":",
"'14'",
",",
"'StripPrivateSymbols'",
":",
"'d3'",
",",
"'SubSystem'",
":",
"'Console'",
",",
"'SupportUnloadOfDelayLoadedDLL'",
":",
"'true'",
",",
"'SuppressStartupBanner'",
":",
"'false'",
",",
"'SwapRunFromCD'",
":",
"'true'",
",",
"'SwapRunFromNET'",
":",
"'true'",
",",
"'TargetMachine'",
":",
"'MachineX86'",
",",
"'TerminalServerAware'",
":",
"'false'",
",",
"'TurnOffAssemblyGeneration'",
":",
"'true'",
",",
"'TypeLibraryFile'",
":",
"'f3'",
",",
"'TypeLibraryResourceID'",
":",
"'12'",
",",
"'UACExecutionLevel'",
":",
"'RequireAdministrator'",
",",
"'UACUIAccess'",
":",
"'true'",
",",
"'Version'",
":",
"'333'",
"}",
",",
"'ResourceCompile'",
":",
"{",
"'AdditionalIncludeDirectories'",
":",
"'f3'",
",",
"'AdditionalOptions'",
":",
"'/more3'",
",",
"'Culture'",
":",
"'0x0c0c'",
",",
"'IgnoreStandardIncludePath'",
":",
"'true'",
",",
"'PreprocessorDefinitions'",
":",
"'_UNICODE;UNICODE2'",
",",
"'ResourceOutputFileName'",
":",
"'$(IntDir)%(Filename)3.res'",
",",
"'ShowProgress'",
":",
"'true'",
"}",
",",
"'Manifest'",
":",
"{",
"'AdditionalManifestFiles'",
":",
"'sfsdfsd'",
",",
"'AdditionalOptions'",
":",
"'afdsdafsd'",
",",
"'AssemblyIdentity'",
":",
"'sddfdsadfsa'",
",",
"'ComponentFileName'",
":",
"'fsdfds'",
",",
"'GenerateCatalogFiles'",
":",
"'true'",
",",
"'InputResourceManifests'",
":",
"'asfsfdafs'",
",",
"'OutputManifestFile'",
":",
"'$(TargetPath).manifestdfs'",
",",
"'RegistrarScriptFile'",
":",
"'sdfsfd'",
",",
"'ReplacementsFile'",
":",
"'sdffsd'",
",",
"'SuppressStartupBanner'",
":",
"'false'",
",",
"'TypeLibraryFile'",
":",
"'sfsd'",
",",
"'UpdateFileHashes'",
":",
"'true'",
",",
"'UpdateFileHashesSearchPath'",
":",
"'sfsd'",
",",
"'VerboseOutput'",
":",
"'true'",
"}",
",",
"'ProjectReference'",
":",
"{",
"'LinkLibraryDependencies'",
":",
"'false'",
",",
"'UseLibraryDependencyInputs'",
":",
"'true'",
"}",
",",
"''",
":",
"{",
"'EmbedManifest'",
":",
"'false'",
",",
"'GenerateManifest'",
":",
"'false'",
",",
"'IgnoreImportLibrary'",
":",
"'true'",
",",
"'LinkIncremental'",
":",
"''",
"}",
",",
"'ManifestResourceCompile'",
":",
"{",
"'ResourceOutputFileName'",
":",
"'$(IntDir)$(TargetFileName).embed.manifest.resfdsf'",
"}",
"}",
"actual_msbuild_settings",
"=",
"MSVSSettings",
".",
"ConvertToMSBuildSettings",
"(",
"msvs_settings",
",",
"self",
".",
"stderr",
")",
"self",
".",
"assertEqual",
"(",
"expected_msbuild_settings",
",",
"actual_msbuild_settings",
")",
"self",
".",
"_ExpectedWarnings",
"(",
"[",
"]",
")"
] | [
1089,
2
] | [
1478,
30
] | python | en | ['en', 'en', 'en'] | True |
EVI | (ds, G=2.5, C1=6, C2=7.5, L=1, normalize=True) |
Computes the 3-band Enhanced Vegetation Index for an `xarray.Dataset`.
The formula is G * (NIR - RED) / (NIR + C1*RED - C2*BLUE + L).
Usually, G = 2.5, C1 = 6, C2 = 7.5, and L = 1.
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1,2.5].
EVI is superior to NDVI in accuracy because it is less dependent on the solar
incidence angle, atmospheric conditions (e.g. particles and clouds), shadows, and
soil appearance.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', 'red', and 'blue' `DataArrays`.
G, C1, C2, L: float
G is the gain factor - a constant scaling factor.
C1 and C2 pertain to aerosols in clouds.
L adjusts for canopy background and soil appearance. It particularly pertains to
the nir and red bands, which are transmitted non-linearly through a canopy.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
evi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
|
Computes the 3-band Enhanced Vegetation Index for an `xarray.Dataset`.
The formula is G * (NIR - RED) / (NIR + C1*RED - C2*BLUE + L).
Usually, G = 2.5, C1 = 6, C2 = 7.5, and L = 1.
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1,2.5].
EVI is superior to NDVI in accuracy because it is less dependent on the solar
incidence angle, atmospheric conditions (e.g. particles and clouds), shadows, and
soil appearance.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', 'red', and 'blue' `DataArrays`.
G, C1, C2, L: float
G is the gain factor - a constant scaling factor.
C1 and C2 pertain to aerosols in clouds.
L adjusts for canopy background and soil appearance. It particularly pertains to
the nir and red bands, which are transmitted non-linearly through a canopy.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
evi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
| def EVI(ds, G=2.5, C1=6, C2=7.5, L=1, normalize=True):
"""
Computes the 3-band Enhanced Vegetation Index for an `xarray.Dataset`.
The formula is G * (NIR - RED) / (NIR + C1*RED - C2*BLUE + L).
Usually, G = 2.5, C1 = 6, C2 = 7.5, and L = 1.
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1,2.5].
EVI is superior to NDVI in accuracy because it is less dependent on the solar
incidence angle, atmospheric conditions (e.g. particles and clouds), shadows, and
soil appearance.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', 'red', and 'blue' `DataArrays`.
G, C1, C2, L: float
G is the gain factor - a constant scaling factor.
C1 and C2 pertain to aerosols in clouds.
L adjusts for canopy background and soil appearance. It particularly pertains to
the nir and red bands, which are transmitted non-linearly through a canopy.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
evi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
"""
evi = G * (ds.nir - ds.red) / (ds.nir + C1 * ds.red - C2 * ds.blue + L)
# Clamp values to the range [-1,2.5].
evi.values[evi.values < -1] = -1
evi.values[2.5 < evi.values] = 2.5
if normalize:
# Scale values in the range [0,2.5] to the range [0,1].
pos_vals_mask = 0 < evi.values
evi.values[pos_vals_mask] = np.interp(evi.values[pos_vals_mask], (0, 2.5), (0, 1))
return evi | [
"def",
"EVI",
"(",
"ds",
",",
"G",
"=",
"2.5",
",",
"C1",
"=",
"6",
",",
"C2",
"=",
"7.5",
",",
"L",
"=",
"1",
",",
"normalize",
"=",
"True",
")",
":",
"evi",
"=",
"G",
"*",
"(",
"ds",
".",
"nir",
"-",
"ds",
".",
"red",
")",
"/",
"(",
"ds",
".",
"nir",
"+",
"C1",
"*",
"ds",
".",
"red",
"-",
"C2",
"*",
"ds",
".",
"blue",
"+",
"L",
")",
"# Clamp values to the range [-1,2.5].\r",
"evi",
".",
"values",
"[",
"evi",
".",
"values",
"<",
"-",
"1",
"]",
"=",
"-",
"1",
"evi",
".",
"values",
"[",
"2.5",
"<",
"evi",
".",
"values",
"]",
"=",
"2.5",
"if",
"normalize",
":",
"# Scale values in the range [0,2.5] to the range [0,1].\r",
"pos_vals_mask",
"=",
"0",
"<",
"evi",
".",
"values",
"evi",
".",
"values",
"[",
"pos_vals_mask",
"]",
"=",
"np",
".",
"interp",
"(",
"evi",
".",
"values",
"[",
"pos_vals_mask",
"]",
",",
"(",
"0",
",",
"2.5",
")",
",",
"(",
"0",
",",
"1",
")",
")",
"return",
"evi"
] | [
2,
0
] | [
40,
14
] | python | en | ['en', 'ja', 'th'] | False |
EVI2 | (ds, G=2.5, C=2.4, L=1, normalize=True) |
Computes the 2-band Enhanced Vegetation Index for an `xarray.Dataset`.
The formula is G*((NIR-RED)/(NIR+C*Red+L)).
Usually, G = 2.5, C = 2.4, and L = 1.
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1,2.5].
EVI2 does not require a blue band like EVI, which means less data is required to use it.
Additionally, the blue band used in EVI can have a low signal-to-noise ratio
in earth observation imagery. When atmospheric effects are insignificant (e.g. on clear days),
EVI2 should closely match EVI.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', and 'red' `DataArrays`.
G, C, L: float
G is the gain factor - a constant scaling factor.
C pertains to aerosols in clouds.
L adjusts for canopy background and soil appearance. It particularly pertains to
the nir and red bands, which are transmitted non-linearly through a canopy.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
evi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
|
Computes the 2-band Enhanced Vegetation Index for an `xarray.Dataset`.
The formula is G*((NIR-RED)/(NIR+C*Red+L)).
Usually, G = 2.5, C = 2.4, and L = 1.
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1,2.5].
EVI2 does not require a blue band like EVI, which means less data is required to use it.
Additionally, the blue band used in EVI can have a low signal-to-noise ratio
in earth observation imagery. When atmospheric effects are insignificant (e.g. on clear days),
EVI2 should closely match EVI.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', and 'red' `DataArrays`.
G, C, L: float
G is the gain factor - a constant scaling factor.
C pertains to aerosols in clouds.
L adjusts for canopy background and soil appearance. It particularly pertains to
the nir and red bands, which are transmitted non-linearly through a canopy.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
evi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
| def EVI2(ds, G=2.5, C=2.4, L=1, normalize=True):
"""
Computes the 2-band Enhanced Vegetation Index for an `xarray.Dataset`.
The formula is G*((NIR-RED)/(NIR+C*Red+L)).
Usually, G = 2.5, C = 2.4, and L = 1.
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1,2.5].
EVI2 does not require a blue band like EVI, which means less data is required to use it.
Additionally, the blue band used in EVI can have a low signal-to-noise ratio
in earth observation imagery. When atmospheric effects are insignificant (e.g. on clear days),
EVI2 should closely match EVI.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', and 'red' `DataArrays`.
G, C, L: float
G is the gain factor - a constant scaling factor.
C pertains to aerosols in clouds.
L adjusts for canopy background and soil appearance. It particularly pertains to
the nir and red bands, which are transmitted non-linearly through a canopy.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
evi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
"""
evi = G * (ds.nir - ds.red) / (ds.nir + C * ds.red + L)
# Clamp values to the range [-1,2.5].
evi.values[evi.values < -1] = -1
evi.values[2.5 < evi.values] = 2.5
if normalize:
# Scale values in the range [0,2.5] to the range [0,1].
pos_vals_mask = 0 < evi.values
evi.values[pos_vals_mask] = np.interp(evi.values[pos_vals_mask], (0, 2.5), (0, 1))
return evi | [
"def",
"EVI2",
"(",
"ds",
",",
"G",
"=",
"2.5",
",",
"C",
"=",
"2.4",
",",
"L",
"=",
"1",
",",
"normalize",
"=",
"True",
")",
":",
"evi",
"=",
"G",
"*",
"(",
"ds",
".",
"nir",
"-",
"ds",
".",
"red",
")",
"/",
"(",
"ds",
".",
"nir",
"+",
"C",
"*",
"ds",
".",
"red",
"+",
"L",
")",
"# Clamp values to the range [-1,2.5].\r",
"evi",
".",
"values",
"[",
"evi",
".",
"values",
"<",
"-",
"1",
"]",
"=",
"-",
"1",
"evi",
".",
"values",
"[",
"2.5",
"<",
"evi",
".",
"values",
"]",
"=",
"2.5",
"if",
"normalize",
":",
"# Scale values in the range [0,2.5] to the range [0,1].\r",
"pos_vals_mask",
"=",
"0",
"<",
"evi",
".",
"values",
"evi",
".",
"values",
"[",
"pos_vals_mask",
"]",
"=",
"np",
".",
"interp",
"(",
"evi",
".",
"values",
"[",
"pos_vals_mask",
"]",
",",
"(",
"0",
",",
"2.5",
")",
",",
"(",
"0",
",",
"1",
")",
")",
"return",
"evi"
] | [
43,
0
] | [
82,
14
] | python | en | ['en', 'ja', 'th'] | False |
NBR | (ds) |
Computes the Normalized Burn Ratio for an `xarray.Dataset`.
The formula is (NIR - SWIR2) / (NIR + SWIR2).
Values should be in the range [-1,1] for valid LANDSAT data (nir and swir2 are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir' and 'swir2' `DataArrays`.
Returns
-------
nbr: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
|
Computes the Normalized Burn Ratio for an `xarray.Dataset`.
The formula is (NIR - SWIR2) / (NIR + SWIR2).
Values should be in the range [-1,1] for valid LANDSAT data (nir and swir2 are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir' and 'swir2' `DataArrays`.
Returns
-------
nbr: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
| def NBR(ds):
"""
Computes the Normalized Burn Ratio for an `xarray.Dataset`.
The formula is (NIR - SWIR2) / (NIR + SWIR2).
Values should be in the range [-1,1] for valid LANDSAT data (nir and swir2 are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir' and 'swir2' `DataArrays`.
Returns
-------
nbr: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
"""
return (ds.nir - ds.swir2) / (ds.nir + ds.swir2) | [
"def",
"NBR",
"(",
"ds",
")",
":",
"return",
"(",
"ds",
".",
"nir",
"-",
"ds",
".",
"swir2",
")",
"/",
"(",
"ds",
".",
"nir",
"+",
"ds",
".",
"swir2",
")"
] | [
84,
0
] | [
101,
52
] | python | en | ['en', 'ja', 'th'] | False |
NDVI | (ds) |
Computes the Normalized Difference Vegetation Index for an `xarray.Dataset`.
The formula is (NIR - RED) / (NIR + RED).
Values should be in the range [-1,1] for valid LANDSAT data (nir and red are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir' and 'red' `DataArrays`.
Returns
-------
ndvi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
|
Computes the Normalized Difference Vegetation Index for an `xarray.Dataset`.
The formula is (NIR - RED) / (NIR + RED).
Values should be in the range [-1,1] for valid LANDSAT data (nir and red are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir' and 'red' `DataArrays`.
Returns
-------
ndvi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
| def NDVI(ds):
"""
Computes the Normalized Difference Vegetation Index for an `xarray.Dataset`.
The formula is (NIR - RED) / (NIR + RED).
Values should be in the range [-1,1] for valid LANDSAT data (nir and red are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir' and 'red' `DataArrays`.
Returns
-------
ndvi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
"""
return (ds.nir - ds.red) / (ds.nir + ds.red) | [
"def",
"NDVI",
"(",
"ds",
")",
":",
"return",
"(",
"ds",
".",
"nir",
"-",
"ds",
".",
"red",
")",
"/",
"(",
"ds",
".",
"nir",
"+",
"ds",
".",
"red",
")"
] | [
103,
0
] | [
120,
48
] | python | en | ['en', 'ja', 'th'] | False |
SAVI | (ds, L=0.5, normalize=True) |
Computes the Soil-Adjusted Vegetation Index for an `xarray.Dataset`.
The formula is (NIR - RED) / (NIR + RED + L) * (1 + L).
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1-L,1+L].
In areas where vegetative cover is low (i.e., < 40%) and the soil surface
is exposed, the reflectance of light in the red and near-infrared spectra
can influence vegetation index values. This is especially problematic when
comparisons are being made across different soil types that may reflect different
amounts of light in the red and near infrared wavelengths (i.e. soils with
different brightness values). The soil-adjusted vegetation index was developed
as a modification of the Normalized Difference Vegetation Index to correct for
the influence of soil brightness when vegetative cover is low.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', and 'red' `DataArrays`.
L: float
L is the “soil brightness correction factor”, which should be varied based
on the greenness of vegetation in the scene. In very high vegetation regions,
`L=0`. In areas with no green vegetation, `L=1`. Generally, `L=0.5` works well
and is the default value. When `L=0`, `SAVI==NDVI`.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
savi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
|
Computes the Soil-Adjusted Vegetation Index for an `xarray.Dataset`.
The formula is (NIR - RED) / (NIR + RED + L) * (1 + L).
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1-L,1+L].
In areas where vegetative cover is low (i.e., < 40%) and the soil surface
is exposed, the reflectance of light in the red and near-infrared spectra
can influence vegetation index values. This is especially problematic when
comparisons are being made across different soil types that may reflect different
amounts of light in the red and near infrared wavelengths (i.e. soils with
different brightness values). The soil-adjusted vegetation index was developed
as a modification of the Normalized Difference Vegetation Index to correct for
the influence of soil brightness when vegetative cover is low.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', and 'red' `DataArrays`.
L: float
L is the “soil brightness correction factor”, which should be varied based
on the greenness of vegetation in the scene. In very high vegetation regions,
`L=0`. In areas with no green vegetation, `L=1`. Generally, `L=0.5` works well
and is the default value. When `L=0`, `SAVI==NDVI`.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
savi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
| def SAVI(ds, L=0.5, normalize=True):
"""
Computes the Soil-Adjusted Vegetation Index for an `xarray.Dataset`.
The formula is (NIR - RED) / (NIR + RED + L) * (1 + L).
For Landsat data, returned values should be in the range [-1,1] if `normalize == True`.
If `normalize == False`, returned values should be in the range [-1-L,1+L].
In areas where vegetative cover is low (i.e., < 40%) and the soil surface
is exposed, the reflectance of light in the red and near-infrared spectra
can influence vegetation index values. This is especially problematic when
comparisons are being made across different soil types that may reflect different
amounts of light in the red and near infrared wavelengths (i.e. soils with
different brightness values). The soil-adjusted vegetation index was developed
as a modification of the Normalized Difference Vegetation Index to correct for
the influence of soil brightness when vegetative cover is low.
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must contain 'nir', and 'red' `DataArrays`.
L: float
L is the “soil brightness correction factor”, which should be varied based
on the greenness of vegetation in the scene. In very high vegetation regions,
`L=0`. In areas with no green vegetation, `L=1`. Generally, `L=0.5` works well
and is the default value. When `L=0`, `SAVI==NDVI`.
normalize: boolean
Whether to normalize to the range [-1,1] - the range of most common spectral indices.
Returns
-------
savi: xarray.DataArray
An `xarray.DataArray` with the same shape as `ds` - the same coordinates in
the same order.
"""
savi = (ds.nir - ds.red) / (ds.nir + ds.red + L) * (1 + L)
if normalize:
savi.values = np.interp(savi.values, (-1-L, 1+L), (-1, 1))
return savi | [
"def",
"SAVI",
"(",
"ds",
",",
"L",
"=",
"0.5",
",",
"normalize",
"=",
"True",
")",
":",
"savi",
"=",
"(",
"ds",
".",
"nir",
"-",
"ds",
".",
"red",
")",
"/",
"(",
"ds",
".",
"nir",
"+",
"ds",
".",
"red",
"+",
"L",
")",
"*",
"(",
"1",
"+",
"L",
")",
"if",
"normalize",
":",
"savi",
".",
"values",
"=",
"np",
".",
"interp",
"(",
"savi",
".",
"values",
",",
"(",
"-",
"1",
"-",
"L",
",",
"1",
"+",
"L",
")",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"return",
"savi"
] | [
123,
0
] | [
160,
15
] | python | en | ['en', 'ja', 'th'] | False |
typedef_t.__init__ | (self, name='', decl_type=None) | creates class that describes C++ typedef | creates class that describes C++ typedef | def __init__(self, name='', decl_type=None):
"""creates class that describes C++ typedef"""
declaration.declaration_t.__init__(self, name)
byte_info.byte_info.__init__(self)
self._decl_type = decl_type
if not isinstance(decl_type, str):
self.byte_size = decl_type.byte_size
self.byte_align = decl_type.byte_align | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"''",
",",
"decl_type",
"=",
"None",
")",
":",
"declaration",
".",
"declaration_t",
".",
"__init__",
"(",
"self",
",",
"name",
")",
"byte_info",
".",
"byte_info",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_decl_type",
"=",
"decl_type",
"if",
"not",
"isinstance",
"(",
"decl_type",
",",
"str",
")",
":",
"self",
".",
"byte_size",
"=",
"decl_type",
".",
"byte_size",
"self",
".",
"byte_align",
"=",
"decl_type",
".",
"byte_align"
] | [
18,
4
] | [
25,
50
] | python | en | ['en', 'nl', 'en'] | True |
typedef_t._get__cmp__items | (self) | implementation details | implementation details | def _get__cmp__items(self):
"""implementation details"""
return [self.decl_type] | [
"def",
"_get__cmp__items",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"decl_type",
"]"
] | [
27,
4
] | [
29,
31
] | python | da | ['eo', 'da', 'en'] | False |
typedef_t.decl_type | (self) | reference to the original :class:`decl_type <type_t>` | reference to the original :class:`decl_type <type_t>` | def decl_type(self):
"""reference to the original :class:`decl_type <type_t>`"""
return self._decl_type | [
"def",
"decl_type",
"(",
"self",
")",
":",
"return",
"self",
".",
"_decl_type"
] | [
40,
4
] | [
42,
30
] | python | en | ['en', 'en', 'en'] | True |
score5 | (fa, matrix=None) |
Calculate 5' splice site strength
(exon)XXX|XXXXXX(intron)
**
>>> round(score5('cagGTAAGT'), 2)
10.86
>>> round(score5('gagGTAAGT'), 2)
11.08
>>> round(score5('taaATAAGT'), 2)
-0.12
>>> matrix = load_matrix(5)
>>> round(score5('cagGTAAGT', matrix=matrix), 2)
10.86
|
Calculate 5' splice site strength
(exon)XXX|XXXXXX(intron)
**
>>> round(score5('cagGTAAGT'), 2)
10.86
>>> round(score5('gagGTAAGT'), 2)
11.08
>>> round(score5('taaATAAGT'), 2)
-0.12
>>> matrix = load_matrix(5)
>>> round(score5('cagGTAAGT', matrix=matrix), 2)
10.86
| def score5(fa, matrix=None):
'''
Calculate 5' splice site strength
(exon)XXX|XXXXXX(intron)
**
>>> round(score5('cagGTAAGT'), 2)
10.86
>>> round(score5('gagGTAAGT'), 2)
11.08
>>> round(score5('taaATAAGT'), 2)
-0.12
>>> matrix = load_matrix(5)
>>> round(score5('cagGTAAGT', matrix=matrix), 2)
10.86
'''
# check length of fa
if len(fa) != 9:
sys.exit('Wrong length of fa!')
# check matrix
if not matrix:
matrix = load_matrix(5)
# for key elements
key = fa[3:5].upper()
score = cons1_5[key[0]] * cons2_5[key[1]] / (bgd_5[key[0]] * bgd_5[key[1]])
# for rest elements
rest = (fa[:3] + fa[5:]).upper()
rest_score = matrix[rest]
# final score
return math.log(score * rest_score, 2) | [
"def",
"score5",
"(",
"fa",
",",
"matrix",
"=",
"None",
")",
":",
"# check length of fa",
"if",
"len",
"(",
"fa",
")",
"!=",
"9",
":",
"sys",
".",
"exit",
"(",
"'Wrong length of fa!'",
")",
"# check matrix",
"if",
"not",
"matrix",
":",
"matrix",
"=",
"load_matrix",
"(",
"5",
")",
"# for key elements",
"key",
"=",
"fa",
"[",
"3",
":",
"5",
"]",
".",
"upper",
"(",
")",
"score",
"=",
"cons1_5",
"[",
"key",
"[",
"0",
"]",
"]",
"*",
"cons2_5",
"[",
"key",
"[",
"1",
"]",
"]",
"/",
"(",
"bgd_5",
"[",
"key",
"[",
"0",
"]",
"]",
"*",
"bgd_5",
"[",
"key",
"[",
"1",
"]",
"]",
")",
"# for rest elements",
"rest",
"=",
"(",
"fa",
"[",
":",
"3",
"]",
"+",
"fa",
"[",
"5",
":",
"]",
")",
".",
"upper",
"(",
")",
"rest_score",
"=",
"matrix",
"[",
"rest",
"]",
"# final score",
"return",
"math",
".",
"log",
"(",
"score",
"*",
"rest_score",
",",
"2",
")"
] | [
34,
0
] | [
62,
42
] | python | en | ['en', 'error', 'th'] | False |
score3 | (fa, matrix=None) |
Calculate 3' splice site strength
(intron)XXXXXXXXXXXXXXXXXXXX|XXX(exon)
**
>>> round(score3('ttccaaacgaacttttgtAGgga'), 2)
2.89
>>> round(score3('tgtctttttctgtgtggcAGtgg'), 2)
8.19
>>> round(score3('ttctctcttcagacttatAGcaa'), 2)
-0.08
>>> matrix = load_matrix(3)
>>> round(score3('ttccaaacgaacttttgtAGgga', matrix=matrix), 2)
2.89
|
Calculate 3' splice site strength
(intron)XXXXXXXXXXXXXXXXXXXX|XXX(exon)
**
>>> round(score3('ttccaaacgaacttttgtAGgga'), 2)
2.89
>>> round(score3('tgtctttttctgtgtggcAGtgg'), 2)
8.19
>>> round(score3('ttctctcttcagacttatAGcaa'), 2)
-0.08
>>> matrix = load_matrix(3)
>>> round(score3('ttccaaacgaacttttgtAGgga', matrix=matrix), 2)
2.89
| def score3(fa, matrix=None):
'''
Calculate 3' splice site strength
(intron)XXXXXXXXXXXXXXXXXXXX|XXX(exon)
**
>>> round(score3('ttccaaacgaacttttgtAGgga'), 2)
2.89
>>> round(score3('tgtctttttctgtgtggcAGtgg'), 2)
8.19
>>> round(score3('ttctctcttcagacttatAGcaa'), 2)
-0.08
>>> matrix = load_matrix(3)
>>> round(score3('ttccaaacgaacttttgtAGgga', matrix=matrix), 2)
2.89
'''
# check length of fa
if len(fa) != 23:
sys.exit('Wrong length of fa!')
# check matrix
if not matrix:
matrix = load_matrix(3)
# for key elements
key = fa[18:20].upper()
score = cons1_3[key[0]] * cons2_3[key[1]] / (bgd_3[key[0]] * bgd_3[key[1]])
# for rest elements
rest = (fa[:18] + fa[20:]).upper()
rest_score = 1
rest_score *= matrix[0][hashseq(rest[:7])]
rest_score *= matrix[1][hashseq(rest[7:14])]
rest_score *= matrix[2][hashseq(rest[14:])]
rest_score *= matrix[3][hashseq(rest[4:11])]
rest_score *= matrix[4][hashseq(rest[11:18])]
rest_score /= matrix[5][hashseq(rest[4:7])]
rest_score /= matrix[6][hashseq(rest[7:11])]
rest_score /= matrix[7][hashseq(rest[11:14])]
rest_score /= matrix[8][hashseq(rest[14:18])]
# final score
return math.log(score * rest_score, 2) | [
"def",
"score3",
"(",
"fa",
",",
"matrix",
"=",
"None",
")",
":",
"# check length of fa",
"if",
"len",
"(",
"fa",
")",
"!=",
"23",
":",
"sys",
".",
"exit",
"(",
"'Wrong length of fa!'",
")",
"# check matrix",
"if",
"not",
"matrix",
":",
"matrix",
"=",
"load_matrix",
"(",
"3",
")",
"# for key elements",
"key",
"=",
"fa",
"[",
"18",
":",
"20",
"]",
".",
"upper",
"(",
")",
"score",
"=",
"cons1_3",
"[",
"key",
"[",
"0",
"]",
"]",
"*",
"cons2_3",
"[",
"key",
"[",
"1",
"]",
"]",
"/",
"(",
"bgd_3",
"[",
"key",
"[",
"0",
"]",
"]",
"*",
"bgd_3",
"[",
"key",
"[",
"1",
"]",
"]",
")",
"# for rest elements",
"rest",
"=",
"(",
"fa",
"[",
":",
"18",
"]",
"+",
"fa",
"[",
"20",
":",
"]",
")",
".",
"upper",
"(",
")",
"rest_score",
"=",
"1",
"rest_score",
"*=",
"matrix",
"[",
"0",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
":",
"7",
"]",
")",
"]",
"rest_score",
"*=",
"matrix",
"[",
"1",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"7",
":",
"14",
"]",
")",
"]",
"rest_score",
"*=",
"matrix",
"[",
"2",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"14",
":",
"]",
")",
"]",
"rest_score",
"*=",
"matrix",
"[",
"3",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"4",
":",
"11",
"]",
")",
"]",
"rest_score",
"*=",
"matrix",
"[",
"4",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"11",
":",
"18",
"]",
")",
"]",
"rest_score",
"/=",
"matrix",
"[",
"5",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"4",
":",
"7",
"]",
")",
"]",
"rest_score",
"/=",
"matrix",
"[",
"6",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"7",
":",
"11",
"]",
")",
"]",
"rest_score",
"/=",
"matrix",
"[",
"7",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"11",
":",
"14",
"]",
")",
"]",
"rest_score",
"/=",
"matrix",
"[",
"8",
"]",
"[",
"hashseq",
"(",
"rest",
"[",
"14",
":",
"18",
"]",
")",
"]",
"# final score",
"return",
"math",
".",
"log",
"(",
"score",
"*",
"rest_score",
",",
"2",
")"
] | [
65,
0
] | [
102,
42
] | python | en | ['en', 'error', 'th'] | False |
install_ambassador | (namespace, single_namespace=True, envs=None) |
Install Ambassador into a given namespace. NOTE WELL that although there
is a 'single_namespace' parameter, this function probably needs work to do
the fully-correct thing with single_namespace False.
:param namespace: namespace to install Ambassador in
:param single_namespace: should we set AMBASSADOR_SINGLE_NAMESPACE? SEE NOTE ABOVE!
:param envs: [
{
'name': 'ENV_NAME',
'value': 'ENV_VALUE'
},
...
...
]
|
Install Ambassador into a given namespace. NOTE WELL that although there
is a 'single_namespace' parameter, this function probably needs work to do
the fully-correct thing with single_namespace False. | def install_ambassador(namespace, single_namespace=True, envs=None):
"""
Install Ambassador into a given namespace. NOTE WELL that although there
is a 'single_namespace' parameter, this function probably needs work to do
the fully-correct thing with single_namespace False.
:param namespace: namespace to install Ambassador in
:param single_namespace: should we set AMBASSADOR_SINGLE_NAMESPACE? SEE NOTE ABOVE!
:param envs: [
{
'name': 'ENV_NAME',
'value': 'ENV_VALUE'
},
...
...
]
"""
if envs is None:
envs = []
found_single_namespace = False
if single_namespace:
for e in envs:
if e['name'] == 'AMBASSADOR_SINGLE_NAMESPACE':
e['value'] = 'true'
found_single_namespace = True
break
if not found_single_namespace:
envs.append({
'name': 'AMBASSADOR_SINGLE_NAMESPACE',
'value': 'true'
})
# Create namespace to install Ambassador
create_namespace(namespace)
# Create Ambassador CRDs
apply_kube_artifacts(namespace=namespace, artifacts=load_manifest('crds'))
# Proceed to install Ambassador now
final_yaml = []
serviceAccountExtra = ''
if os.environ.get("DEV_USE_IMAGEPULLSECRET", False):
serviceAccountExtra = """
imagePullSecrets:
- name: dev-image-pull-secret
"""
rbac_manifest_name = 'rbac_namespace_scope' if single_namespace else 'rbac_cluster_scope'
# Hackish fakes of actual KAT structures -- it's _far_ too much work to synthesize
# actual KAT Nodes and Paths.
fakeNode = namedtuple('fakeNode', [ 'namespace', 'path', 'ambassador_id' ])
fakePath = namedtuple('fakePath', [ 'k8s' ])
ambassador_yaml = list(yaml.safe_load_all((
load_manifest(rbac_manifest_name) +
load_manifest('ambassador') +
(CLEARTEXT_HOST_YAML % namespace)
).format(
capabilities_block="",
envs="",
extra_ports="",
serviceAccountExtra=serviceAccountExtra,
image=os.environ["AMBASSADOR_DOCKER_IMAGE"],
self=fakeNode(
namespace=namespace,
ambassador_id='default',
path=fakePath(k8s='ambassador')
)
)))
for manifest in ambassador_yaml:
kind = manifest.get('kind', None)
metadata = manifest.get('metadata', {})
name = metadata.get('name', None)
if (kind == "Pod") and (name == "ambassador"):
# Force AMBASSADOR_ID to match ours.
#
# XXX This is not likely to work without single_namespace=True.
for envvar in manifest['spec']['containers'][0]['env']:
if envvar.get('name', '') == 'AMBASSADOR_ID':
envvar['value'] = 'default'
# add new envs, if any
manifest['spec']['containers'][0]['env'].extend(envs)
apply_kube_artifacts(namespace=namespace, artifacts=yaml.safe_dump_all(ambassador_yaml)) | [
"def",
"install_ambassador",
"(",
"namespace",
",",
"single_namespace",
"=",
"True",
",",
"envs",
"=",
"None",
")",
":",
"if",
"envs",
"is",
"None",
":",
"envs",
"=",
"[",
"]",
"found_single_namespace",
"=",
"False",
"if",
"single_namespace",
":",
"for",
"e",
"in",
"envs",
":",
"if",
"e",
"[",
"'name'",
"]",
"==",
"'AMBASSADOR_SINGLE_NAMESPACE'",
":",
"e",
"[",
"'value'",
"]",
"=",
"'true'",
"found_single_namespace",
"=",
"True",
"break",
"if",
"not",
"found_single_namespace",
":",
"envs",
".",
"append",
"(",
"{",
"'name'",
":",
"'AMBASSADOR_SINGLE_NAMESPACE'",
",",
"'value'",
":",
"'true'",
"}",
")",
"# Create namespace to install Ambassador",
"create_namespace",
"(",
"namespace",
")",
"# Create Ambassador CRDs",
"apply_kube_artifacts",
"(",
"namespace",
"=",
"namespace",
",",
"artifacts",
"=",
"load_manifest",
"(",
"'crds'",
")",
")",
"# Proceed to install Ambassador now",
"final_yaml",
"=",
"[",
"]",
"serviceAccountExtra",
"=",
"''",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"DEV_USE_IMAGEPULLSECRET\"",
",",
"False",
")",
":",
"serviceAccountExtra",
"=",
"\"\"\"\nimagePullSecrets:\n- name: dev-image-pull-secret\n\"\"\"",
"rbac_manifest_name",
"=",
"'rbac_namespace_scope'",
"if",
"single_namespace",
"else",
"'rbac_cluster_scope'",
"# Hackish fakes of actual KAT structures -- it's _far_ too much work to synthesize",
"# actual KAT Nodes and Paths.",
"fakeNode",
"=",
"namedtuple",
"(",
"'fakeNode'",
",",
"[",
"'namespace'",
",",
"'path'",
",",
"'ambassador_id'",
"]",
")",
"fakePath",
"=",
"namedtuple",
"(",
"'fakePath'",
",",
"[",
"'k8s'",
"]",
")",
"ambassador_yaml",
"=",
"list",
"(",
"yaml",
".",
"safe_load_all",
"(",
"(",
"load_manifest",
"(",
"rbac_manifest_name",
")",
"+",
"load_manifest",
"(",
"'ambassador'",
")",
"+",
"(",
"CLEARTEXT_HOST_YAML",
"%",
"namespace",
")",
")",
".",
"format",
"(",
"capabilities_block",
"=",
"\"\"",
",",
"envs",
"=",
"\"\"",
",",
"extra_ports",
"=",
"\"\"",
",",
"serviceAccountExtra",
"=",
"serviceAccountExtra",
",",
"image",
"=",
"os",
".",
"environ",
"[",
"\"AMBASSADOR_DOCKER_IMAGE\"",
"]",
",",
"self",
"=",
"fakeNode",
"(",
"namespace",
"=",
"namespace",
",",
"ambassador_id",
"=",
"'default'",
",",
"path",
"=",
"fakePath",
"(",
"k8s",
"=",
"'ambassador'",
")",
")",
")",
")",
")",
"for",
"manifest",
"in",
"ambassador_yaml",
":",
"kind",
"=",
"manifest",
".",
"get",
"(",
"'kind'",
",",
"None",
")",
"metadata",
"=",
"manifest",
".",
"get",
"(",
"'metadata'",
",",
"{",
"}",
")",
"name",
"=",
"metadata",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"if",
"(",
"kind",
"==",
"\"Pod\"",
")",
"and",
"(",
"name",
"==",
"\"ambassador\"",
")",
":",
"# Force AMBASSADOR_ID to match ours.",
"#",
"# XXX This is not likely to work without single_namespace=True.",
"for",
"envvar",
"in",
"manifest",
"[",
"'spec'",
"]",
"[",
"'containers'",
"]",
"[",
"0",
"]",
"[",
"'env'",
"]",
":",
"if",
"envvar",
".",
"get",
"(",
"'name'",
",",
"''",
")",
"==",
"'AMBASSADOR_ID'",
":",
"envvar",
"[",
"'value'",
"]",
"=",
"'default'",
"# add new envs, if any",
"manifest",
"[",
"'spec'",
"]",
"[",
"'containers'",
"]",
"[",
"0",
"]",
"[",
"'env'",
"]",
".",
"extend",
"(",
"envs",
")",
"apply_kube_artifacts",
"(",
"namespace",
"=",
"namespace",
",",
"artifacts",
"=",
"yaml",
".",
"safe_dump_all",
"(",
"ambassador_yaml",
")",
")"
] | [
54,
0
] | [
146,
92
] | python | en | ['en', 'error', 'th'] | False |
project | () | Project operations | Project operations | def project():
"""Project operations"""
pass | [
"def",
"project",
"(",
")",
":",
"pass"
] | [
14,
0
] | [
16,
8
] | python | en | ['en', 'en', 'en'] | False |
project_check_config | (directory) | Check a config for validity and help with migrations. | Check a config for validity and help with migrations. | def project_check_config(directory):
"""Check a config for validity and help with migrations."""
cli_message("Checking your config files for validity...\n")
is_config_ok, error_message, context = do_config_check(directory)
if context:
toolkit.send_usage_message(
data_context=context, event="cli.project.check_config", success=True
)
if not is_config_ok:
cli_message("Unfortunately, your config appears to be invalid:\n")
cli_message("<red>{}</red>".format(error_message))
sys.exit(1)
cli_message("<green>Your config file appears valid!</green>") | [
"def",
"project_check_config",
"(",
"directory",
")",
":",
"cli_message",
"(",
"\"Checking your config files for validity...\\n\"",
")",
"is_config_ok",
",",
"error_message",
",",
"context",
"=",
"do_config_check",
"(",
"directory",
")",
"if",
"context",
":",
"toolkit",
".",
"send_usage_message",
"(",
"data_context",
"=",
"context",
",",
"event",
"=",
"\"cli.project.check_config\"",
",",
"success",
"=",
"True",
")",
"if",
"not",
"is_config_ok",
":",
"cli_message",
"(",
"\"Unfortunately, your config appears to be invalid:\\n\"",
")",
"cli_message",
"(",
"\"<red>{}</red>\"",
".",
"format",
"(",
"error_message",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"cli_message",
"(",
"\"<green>Your config file appears valid!</green>\"",
")"
] | [
26,
0
] | [
39,
65
] | python | en | ['en', 'en', 'en'] | True |
project_upgrade | (directory) | Upgrade a project after installing the next Great Expectations major version. | Upgrade a project after installing the next Great Expectations major version. | def project_upgrade(directory):
"""Upgrade a project after installing the next Great Expectations major version."""
cli_message("\nChecking project...")
cli_message(SECTION_SEPARATOR)
if load_data_context_with_error_handling(
directory=directory, from_cli_upgrade_command=True
):
up_to_date_message = (
"Your project is up-to-date - no further upgrade is necessary.\n"
)
cli_message(f"<green>{up_to_date_message}</green>")
sys.exit(0) | [
"def",
"project_upgrade",
"(",
"directory",
")",
":",
"cli_message",
"(",
"\"\\nChecking project...\"",
")",
"cli_message",
"(",
"SECTION_SEPARATOR",
")",
"if",
"load_data_context_with_error_handling",
"(",
"directory",
"=",
"directory",
",",
"from_cli_upgrade_command",
"=",
"True",
")",
":",
"up_to_date_message",
"=",
"(",
"\"Your project is up-to-date - no further upgrade is necessary.\\n\"",
")",
"cli_message",
"(",
"f\"<green>{up_to_date_message}</green>\"",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | [
49,
0
] | [
60,
19
] | python | en | ['en', 'en', 'en'] | True |
Pipeline.add_node | (self, component, name: str, inputs: List[str]) |
Add a new node to the pipeline.
:param component: The object to be called when the data is passed to the node. It can be a Haystack component
(like Retriever, Reader, or Generator) or a user-defined object that implements a run()
method to process incoming data from predecessor node.
:param name: The name for the node. It must not contain any dots.
:param inputs: A list of inputs to the node. If the predecessor node has a single outgoing edge, just the name
of node is sufficient. For instance, a 'ElasticsearchRetriever' node would always output a single
edge with a list of documents. It can be represented as ["ElasticsearchRetriever"].
In cases when the predecessor node has multiple outputs, e.g., a "QueryClassifier", the output
must be specified explicitly as "QueryClassifier.output_2".
|
Add a new node to the pipeline. | def add_node(self, component, name: str, inputs: List[str]):
"""
Add a new node to the pipeline.
:param component: The object to be called when the data is passed to the node. It can be a Haystack component
(like Retriever, Reader, or Generator) or a user-defined object that implements a run()
method to process incoming data from predecessor node.
:param name: The name for the node. It must not contain any dots.
:param inputs: A list of inputs to the node. If the predecessor node has a single outgoing edge, just the name
of node is sufficient. For instance, a 'ElasticsearchRetriever' node would always output a single
edge with a list of documents. It can be represented as ["ElasticsearchRetriever"].
In cases when the predecessor node has multiple outputs, e.g., a "QueryClassifier", the output
must be specified explicitly as "QueryClassifier.output_2".
"""
self.graph.add_node(name, component=component, inputs=inputs)
if len(self.graph.nodes) == 2: # first node added; connect with Root
self.graph.add_edge(self.root_node_id, name, label="output_1")
return
for i in inputs:
if "." in i:
[input_node_name, input_edge_name] = i.split(".")
assert "output_" in input_edge_name, f"'{input_edge_name}' is not a valid edge name."
outgoing_edges_input_node = self.graph.nodes[input_node_name]["component"].outgoing_edges
assert int(input_edge_name.split("_")[1]) <= outgoing_edges_input_node, (
f"Cannot connect '{input_edge_name}' from '{input_node_name}' as it only has "
f"{outgoing_edges_input_node} outgoing edge(s)."
)
else:
outgoing_edges_input_node = self.graph.nodes[i]["component"].outgoing_edges
assert outgoing_edges_input_node == 1, (
f"Adding an edge from {i} to {name} is ambiguous as {i} has {outgoing_edges_input_node} edges. "
f"Please specify the output explicitly."
)
input_node_name = i
input_edge_name = "output_1"
self.graph.add_edge(input_node_name, name, label=input_edge_name) | [
"def",
"add_node",
"(",
"self",
",",
"component",
",",
"name",
":",
"str",
",",
"inputs",
":",
"List",
"[",
"str",
"]",
")",
":",
"self",
".",
"graph",
".",
"add_node",
"(",
"name",
",",
"component",
"=",
"component",
",",
"inputs",
"=",
"inputs",
")",
"if",
"len",
"(",
"self",
".",
"graph",
".",
"nodes",
")",
"==",
"2",
":",
"# first node added; connect with Root",
"self",
".",
"graph",
".",
"add_edge",
"(",
"self",
".",
"root_node_id",
",",
"name",
",",
"label",
"=",
"\"output_1\"",
")",
"return",
"for",
"i",
"in",
"inputs",
":",
"if",
"\".\"",
"in",
"i",
":",
"[",
"input_node_name",
",",
"input_edge_name",
"]",
"=",
"i",
".",
"split",
"(",
"\".\"",
")",
"assert",
"\"output_\"",
"in",
"input_edge_name",
",",
"f\"'{input_edge_name}' is not a valid edge name.\"",
"outgoing_edges_input_node",
"=",
"self",
".",
"graph",
".",
"nodes",
"[",
"input_node_name",
"]",
"[",
"\"component\"",
"]",
".",
"outgoing_edges",
"assert",
"int",
"(",
"input_edge_name",
".",
"split",
"(",
"\"_\"",
")",
"[",
"1",
"]",
")",
"<=",
"outgoing_edges_input_node",
",",
"(",
"f\"Cannot connect '{input_edge_name}' from '{input_node_name}' as it only has \"",
"f\"{outgoing_edges_input_node} outgoing edge(s).\"",
")",
"else",
":",
"outgoing_edges_input_node",
"=",
"self",
".",
"graph",
".",
"nodes",
"[",
"i",
"]",
"[",
"\"component\"",
"]",
".",
"outgoing_edges",
"assert",
"outgoing_edges_input_node",
"==",
"1",
",",
"(",
"f\"Adding an edge from {i} to {name} is ambiguous as {i} has {outgoing_edges_input_node} edges. \"",
"f\"Please specify the output explicitly.\"",
")",
"input_node_name",
"=",
"i",
"input_edge_name",
"=",
"\"output_1\"",
"self",
".",
"graph",
".",
"add_edge",
"(",
"input_node_name",
",",
"name",
",",
"label",
"=",
"input_edge_name",
")"
] | [
42,
4
] | [
80,
77
] | python | en | ['en', 'error', 'th'] | False |
Pipeline.get_node | (self, name: str) |
Get a node from the Pipeline.
:param name: The name of the node.
|
Get a node from the Pipeline. | def get_node(self, name: str):
"""
Get a node from the Pipeline.
:param name: The name of the node.
"""
component = self.graph.nodes[name]["component"]
return component | [
"def",
"get_node",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"component",
"=",
"self",
".",
"graph",
".",
"nodes",
"[",
"name",
"]",
"[",
"\"component\"",
"]",
"return",
"component"
] | [
82,
4
] | [
89,
24
] | python | en | ['en', 'error', 'th'] | False |
Pipeline.set_node | (self, name: str, component) |
Set the component for a node in the Pipeline.
:param name: The name of the node.
:param component: The component object to be set at the node.
|
Set the component for a node in the Pipeline. | def set_node(self, name: str, component):
"""
Set the component for a node in the Pipeline.
:param name: The name of the node.
:param component: The component object to be set at the node.
"""
self.graph.nodes[name]["component"] = component | [
"def",
"set_node",
"(",
"self",
",",
"name",
":",
"str",
",",
"component",
")",
":",
"self",
".",
"graph",
".",
"nodes",
"[",
"name",
"]",
"[",
"\"component\"",
"]",
"=",
"component"
] | [
91,
4
] | [
98,
55
] | python | en | ['en', 'error', 'th'] | False |
Pipeline.draw | (self, path: Path = Path("pipeline.png")) |
Create a Graphviz visualization of the pipeline.
:param path: the path to save the image.
|
Create a Graphviz visualization of the pipeline. | def draw(self, path: Path = Path("pipeline.png")):
"""
Create a Graphviz visualization of the pipeline.
:param path: the path to save the image.
"""
try:
import pygraphviz
except ImportError:
raise ImportError(f"Could not import `pygraphviz`. Please install via: \n"
f"pip install pygraphviz\n"
f"(You might need to run this first: apt install libgraphviz-dev graphviz )")
graphviz = to_agraph(self.graph)
graphviz.layout("dot")
graphviz.draw(path) | [
"def",
"draw",
"(",
"self",
",",
"path",
":",
"Path",
"=",
"Path",
"(",
"\"pipeline.png\"",
")",
")",
":",
"try",
":",
"import",
"pygraphviz",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"f\"Could not import `pygraphviz`. Please install via: \\n\"",
"f\"pip install pygraphviz\\n\"",
"f\"(You might need to run this first: apt install libgraphviz-dev graphviz )\"",
")",
"graphviz",
"=",
"to_agraph",
"(",
"self",
".",
"graph",
")",
"graphviz",
".",
"layout",
"(",
"\"dot\"",
")",
"graphviz",
".",
"draw",
"(",
"path",
")"
] | [
139,
4
] | [
154,
27
] | python | en | ['en', 'error', 'th'] | False |
Pipeline.load_from_yaml | (cls, path: Path, pipeline_name: Optional[str] = None, overwrite_with_env_variables: bool = True) |
Load Pipeline from a YAML file defining the individual components and how they're tied together to form
a Pipeline. A single YAML can declare multiple Pipelines, in which case an explicit `pipeline_name` must
be passed.
Here's a sample configuration:
```yaml
| version: '0.7'
|
| components: # define all the building-blocks for Pipeline
| - name: MyReader # custom-name for the component; helpful for visualization & debugging
| type: FARMReader # Haystack Class name for the component
| params:
| no_ans_boost: -10
| model_name_or_path: deepset/roberta-base-squad2
| - name: MyESRetriever
| type: ElasticsearchRetriever
| params:
| document_store: MyDocumentStore # params can reference other components defined in the YAML
| custom_query: null
| - name: MyDocumentStore
| type: ElasticsearchDocumentStore
| params:
| index: haystack_test
|
| pipelines: # multiple Pipelines can be defined using the components from above
| - name: my_query_pipeline # a simple extractive-qa Pipeline
| nodes:
| - name: MyESRetriever
| inputs: [Query]
| - name: MyReader
| inputs: [MyESRetriever]
```
:param path: path of the YAML file.
:param pipeline_name: if the YAML contains multiple pipelines, the pipeline_name to load must be set.
:param overwrite_with_env_variables: Overwrite the YAML configuration with environment variables. For example,
to change index name param for an ElasticsearchDocumentStore, an env
variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties.
|
Load Pipeline from a YAML file defining the individual components and how they're tied together to form
a Pipeline. A single YAML can declare multiple Pipelines, in which case an explicit `pipeline_name` must
be passed. | def load_from_yaml(cls, path: Path, pipeline_name: Optional[str] = None, overwrite_with_env_variables: bool = True):
"""
Load Pipeline from a YAML file defining the individual components and how they're tied together to form
a Pipeline. A single YAML can declare multiple Pipelines, in which case an explicit `pipeline_name` must
be passed.
Here's a sample configuration:
```yaml
| version: '0.7'
|
| components: # define all the building-blocks for Pipeline
| - name: MyReader # custom-name for the component; helpful for visualization & debugging
| type: FARMReader # Haystack Class name for the component
| params:
| no_ans_boost: -10
| model_name_or_path: deepset/roberta-base-squad2
| - name: MyESRetriever
| type: ElasticsearchRetriever
| params:
| document_store: MyDocumentStore # params can reference other components defined in the YAML
| custom_query: null
| - name: MyDocumentStore
| type: ElasticsearchDocumentStore
| params:
| index: haystack_test
|
| pipelines: # multiple Pipelines can be defined using the components from above
| - name: my_query_pipeline # a simple extractive-qa Pipeline
| nodes:
| - name: MyESRetriever
| inputs: [Query]
| - name: MyReader
| inputs: [MyESRetriever]
```
:param path: path of the YAML file.
:param pipeline_name: if the YAML contains multiple pipelines, the pipeline_name to load must be set.
:param overwrite_with_env_variables: Overwrite the YAML configuration with environment variables. For example,
to change index name param for an ElasticsearchDocumentStore, an env
variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties.
"""
with open(path, "r", encoding='utf-8') as stream:
data = yaml.safe_load(stream)
if pipeline_name is None:
if len(data["pipelines"]) == 1:
pipeline_config = data["pipelines"][0]
else:
raise Exception("The YAML contains multiple pipelines. Please specify the pipeline name to load.")
else:
pipelines_in_yaml = list(filter(lambda p: p["name"] == pipeline_name, data["pipelines"]))
if not pipelines_in_yaml:
raise Exception(f"Cannot find any pipeline with name '{pipeline_name}' declared in the YAML file.")
pipeline_config = pipelines_in_yaml[0]
definitions = {} # definitions of each component from the YAML.
for definition in data["components"]:
if overwrite_with_env_variables:
cls._overwrite_with_env_variables(definition)
name = definition.pop("name")
definitions[name] = definition
pipeline = cls(pipeline_type=pipeline_config["type"])
components: dict = {} # instances of component objects.
for node_config in pipeline_config["nodes"]:
name = node_config["name"]
component = cls._load_or_get_component(name=name, definitions=definitions, components=components)
pipeline.add_node(component=component, name=node_config["name"], inputs=node_config.get("inputs", []))
return pipeline | [
"def",
"load_from_yaml",
"(",
"cls",
",",
"path",
":",
"Path",
",",
"pipeline_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"overwrite_with_env_variables",
":",
"bool",
"=",
"True",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"stream",
":",
"data",
"=",
"yaml",
".",
"safe_load",
"(",
"stream",
")",
"if",
"pipeline_name",
"is",
"None",
":",
"if",
"len",
"(",
"data",
"[",
"\"pipelines\"",
"]",
")",
"==",
"1",
":",
"pipeline_config",
"=",
"data",
"[",
"\"pipelines\"",
"]",
"[",
"0",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"The YAML contains multiple pipelines. Please specify the pipeline name to load.\"",
")",
"else",
":",
"pipelines_in_yaml",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"p",
":",
"p",
"[",
"\"name\"",
"]",
"==",
"pipeline_name",
",",
"data",
"[",
"\"pipelines\"",
"]",
")",
")",
"if",
"not",
"pipelines_in_yaml",
":",
"raise",
"Exception",
"(",
"f\"Cannot find any pipeline with name '{pipeline_name}' declared in the YAML file.\"",
")",
"pipeline_config",
"=",
"pipelines_in_yaml",
"[",
"0",
"]",
"definitions",
"=",
"{",
"}",
"# definitions of each component from the YAML.",
"for",
"definition",
"in",
"data",
"[",
"\"components\"",
"]",
":",
"if",
"overwrite_with_env_variables",
":",
"cls",
".",
"_overwrite_with_env_variables",
"(",
"definition",
")",
"name",
"=",
"definition",
".",
"pop",
"(",
"\"name\"",
")",
"definitions",
"[",
"name",
"]",
"=",
"definition",
"pipeline",
"=",
"cls",
"(",
"pipeline_type",
"=",
"pipeline_config",
"[",
"\"type\"",
"]",
")",
"components",
":",
"dict",
"=",
"{",
"}",
"# instances of component objects.",
"for",
"node_config",
"in",
"pipeline_config",
"[",
"\"nodes\"",
"]",
":",
"name",
"=",
"node_config",
"[",
"\"name\"",
"]",
"component",
"=",
"cls",
".",
"_load_or_get_component",
"(",
"name",
"=",
"name",
",",
"definitions",
"=",
"definitions",
",",
"components",
"=",
"components",
")",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"component",
",",
"name",
"=",
"node_config",
"[",
"\"name\"",
"]",
",",
"inputs",
"=",
"node_config",
".",
"get",
"(",
"\"inputs\"",
",",
"[",
"]",
")",
")",
"return",
"pipeline"
] | [
157,
4
] | [
229,
23
] | python | en | ['en', 'error', 'th'] | False |
Pipeline._load_or_get_component | (cls, name: str, definitions: dict, components: dict) |
Load a component from the definition or return if component object already present in `components` dict.
:param name: name of the component to load or get.
:param definitions: dict containing definitions of all components retrieved from the YAML.
:param components: dict containing component objects.
|
Load a component from the definition or return if component object already present in `components` dict. | def _load_or_get_component(cls, name: str, definitions: dict, components: dict):
"""
Load a component from the definition or return if component object already present in `components` dict.
:param name: name of the component to load or get.
:param definitions: dict containing definitions of all components retrieved from the YAML.
:param components: dict containing component objects.
"""
if name in components.keys(): # check if component is already loaded.
return components[name]
component_params = definitions[name]["params"]
component_type = definitions[name]["type"]
for key, value in component_params.items():
# Component params can reference to other components. For instance, a Retriever can reference a
# DocumentStore defined in the YAML. All references should be recursively resolved.
if value in definitions.keys(): # check if the param value is a reference to another component.
if value not in components.keys(): # check if the referenced component is already loaded.
cls._load_or_get_component(name=value, definitions=definitions, components=components)
component_params[key] = components[value] # substitute reference (string) with the component object.
instance = BaseComponent.load_from_args(component_type=component_type, **component_params)
components[name] = instance
return instance | [
"def",
"_load_or_get_component",
"(",
"cls",
",",
"name",
":",
"str",
",",
"definitions",
":",
"dict",
",",
"components",
":",
"dict",
")",
":",
"if",
"name",
"in",
"components",
".",
"keys",
"(",
")",
":",
"# check if component is already loaded.",
"return",
"components",
"[",
"name",
"]",
"component_params",
"=",
"definitions",
"[",
"name",
"]",
"[",
"\"params\"",
"]",
"component_type",
"=",
"definitions",
"[",
"name",
"]",
"[",
"\"type\"",
"]",
"for",
"key",
",",
"value",
"in",
"component_params",
".",
"items",
"(",
")",
":",
"# Component params can reference to other components. For instance, a Retriever can reference a",
"# DocumentStore defined in the YAML. All references should be recursively resolved.",
"if",
"value",
"in",
"definitions",
".",
"keys",
"(",
")",
":",
"# check if the param value is a reference to another component.",
"if",
"value",
"not",
"in",
"components",
".",
"keys",
"(",
")",
":",
"# check if the referenced component is already loaded.",
"cls",
".",
"_load_or_get_component",
"(",
"name",
"=",
"value",
",",
"definitions",
"=",
"definitions",
",",
"components",
"=",
"components",
")",
"component_params",
"[",
"key",
"]",
"=",
"components",
"[",
"value",
"]",
"# substitute reference (string) with the component object.",
"instance",
"=",
"BaseComponent",
".",
"load_from_args",
"(",
"component_type",
"=",
"component_type",
",",
"*",
"*",
"component_params",
")",
"components",
"[",
"name",
"]",
"=",
"instance",
"return",
"instance"
] | [
232,
4
] | [
256,
23
] | python | en | ['en', 'error', 'th'] | False |
Pipeline._overwrite_with_env_variables | (cls, definition: dict) |
Overwrite the YAML configuration with environment variables. For example, to change index name param for an
ElasticsearchDocumentStore, an env variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties.
:param definition: a dictionary containing the YAML definition of a component.
|
Overwrite the YAML configuration with environment variables. For example, to change index name param for an
ElasticsearchDocumentStore, an env variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties. | def _overwrite_with_env_variables(cls, definition: dict):
"""
Overwrite the YAML configuration with environment variables. For example, to change index name param for an
ElasticsearchDocumentStore, an env variable 'MYDOCSTORE_PARAMS_INDEX=documents-2021' can be set. Note that an
`_` sign must be used to specify nested hierarchical properties.
:param definition: a dictionary containing the YAML definition of a component.
"""
env_prefix = f"{definition['name']}_params_".upper()
for key, value in os.environ.items():
if key.startswith(env_prefix):
param_name = key.replace(env_prefix, "").lower()
definition["params"][param_name] = value | [
"def",
"_overwrite_with_env_variables",
"(",
"cls",
",",
"definition",
":",
"dict",
")",
":",
"env_prefix",
"=",
"f\"{definition['name']}_params_\"",
".",
"upper",
"(",
")",
"for",
"key",
",",
"value",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"env_prefix",
")",
":",
"param_name",
"=",
"key",
".",
"replace",
"(",
"env_prefix",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"definition",
"[",
"\"params\"",
"]",
"[",
"param_name",
"]",
"=",
"value"
] | [
259,
4
] | [
271,
56
] | python | en | ['en', 'error', 'th'] | False |
BaseStandardPipeline.add_node | (self, component, name: str, inputs: List[str]) |
Add a new node to the pipeline.
:param component: The object to be called when the data is passed to the node. It can be a Haystack component
(like Retriever, Reader, or Generator) or a user-defined object that implements a run()
method to process incoming data from predecessor node.
:param name: The name for the node. It must not contain any dots.
:param inputs: A list of inputs to the node. If the predecessor node has a single outgoing edge, just the name
of node is sufficient. For instance, a 'ElasticsearchRetriever' node would always output a single
edge with a list of documents. It can be represented as ["ElasticsearchRetriever"].
In cases when the predecessor node has multiple outputs, e.g., a "QueryClassifier", the output
must be specified explicitly as "QueryClassifier.output_2".
|
Add a new node to the pipeline. | def add_node(self, component, name: str, inputs: List[str]):
"""
Add a new node to the pipeline.
:param component: The object to be called when the data is passed to the node. It can be a Haystack component
(like Retriever, Reader, or Generator) or a user-defined object that implements a run()
method to process incoming data from predecessor node.
:param name: The name for the node. It must not contain any dots.
:param inputs: A list of inputs to the node. If the predecessor node has a single outgoing edge, just the name
of node is sufficient. For instance, a 'ElasticsearchRetriever' node would always output a single
edge with a list of documents. It can be represented as ["ElasticsearchRetriever"].
In cases when the predecessor node has multiple outputs, e.g., a "QueryClassifier", the output
must be specified explicitly as "QueryClassifier.output_2".
"""
self.pipeline.add_node(component=component, name=name, inputs=inputs) | [
"def",
"add_node",
"(",
"self",
",",
"component",
",",
"name",
":",
"str",
",",
"inputs",
":",
"List",
"[",
"str",
"]",
")",
":",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"component",
",",
"name",
"=",
"name",
",",
"inputs",
"=",
"inputs",
")"
] | [
277,
4
] | [
293,
77
] | python | en | ['en', 'error', 'th'] | False |
BaseStandardPipeline.get_node | (self, name: str) |
Get a node from the Pipeline.
:param name: The name of the node.
|
Get a node from the Pipeline. | def get_node(self, name: str):
"""
Get a node from the Pipeline.
:param name: The name of the node.
"""
component = self.pipeline.get_node(name)
return component | [
"def",
"get_node",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"component",
"=",
"self",
".",
"pipeline",
".",
"get_node",
"(",
"name",
")",
"return",
"component"
] | [
295,
4
] | [
302,
24
] | python | en | ['en', 'error', 'th'] | False |
BaseStandardPipeline.set_node | (self, name: str, component) |
Set the component for a node in the Pipeline.
:param name: The name of the node.
:param component: The component object to be set at the node.
|
Set the component for a node in the Pipeline. | def set_node(self, name: str, component):
"""
Set the component for a node in the Pipeline.
:param name: The name of the node.
:param component: The component object to be set at the node.
"""
self.pipeline.set_node(name, component) | [
"def",
"set_node",
"(",
"self",
",",
"name",
":",
"str",
",",
"component",
")",
":",
"self",
".",
"pipeline",
".",
"set_node",
"(",
"name",
",",
"component",
")"
] | [
304,
4
] | [
311,
47
] | python | en | ['en', 'error', 'th'] | False |
BaseStandardPipeline.draw | (self, path: Path = Path("pipeline.png")) |
Create a Graphviz visualization of the pipeline.
:param path: the path to save the image.
|
Create a Graphviz visualization of the pipeline. | def draw(self, path: Path = Path("pipeline.png")):
"""
Create a Graphviz visualization of the pipeline.
:param path: the path to save the image.
"""
self.pipeline.draw(path) | [
"def",
"draw",
"(",
"self",
",",
"path",
":",
"Path",
"=",
"Path",
"(",
"\"pipeline.png\"",
")",
")",
":",
"self",
".",
"pipeline",
".",
"draw",
"(",
"path",
")"
] | [
313,
4
] | [
319,
32
] | python | en | ['en', 'error', 'th'] | False |
ExtractiveQAPipeline.__init__ | (self, reader: BaseReader, retriever: BaseRetriever) |
Initialize a Pipeline for Extractive Question Answering.
:param reader: Reader instance
:param retriever: Retriever instance
|
Initialize a Pipeline for Extractive Question Answering. | def __init__(self, reader: BaseReader, retriever: BaseRetriever):
"""
Initialize a Pipeline for Extractive Question Answering.
:param reader: Reader instance
:param retriever: Retriever instance
"""
self.pipeline = Pipeline()
self.pipeline.add_node(component=retriever, name="Retriever", inputs=["Query"])
self.pipeline.add_node(component=reader, name="Reader", inputs=["Retriever"]) | [
"def",
"__init__",
"(",
"self",
",",
"reader",
":",
"BaseReader",
",",
"retriever",
":",
"BaseRetriever",
")",
":",
"self",
".",
"pipeline",
"=",
"Pipeline",
"(",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"retriever",
",",
"name",
"=",
"\"Retriever\"",
",",
"inputs",
"=",
"[",
"\"Query\"",
"]",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"reader",
",",
"name",
"=",
"\"Reader\"",
",",
"inputs",
"=",
"[",
"\"Retriever\"",
"]",
")"
] | [
323,
4
] | [
332,
85
] | python | en | ['en', 'error', 'th'] | False |
DocumentSearchPipeline.__init__ | (self, retriever: BaseRetriever) |
Initialize a Pipeline for semantic document search.
:param retriever: Retriever instance
|
Initialize a Pipeline for semantic document search. | def __init__(self, retriever: BaseRetriever):
"""
Initialize a Pipeline for semantic document search.
:param retriever: Retriever instance
"""
self.pipeline = Pipeline()
self.pipeline.add_node(component=retriever, name="Retriever", inputs=["Query"]) | [
"def",
"__init__",
"(",
"self",
",",
"retriever",
":",
"BaseRetriever",
")",
":",
"self",
".",
"pipeline",
"=",
"Pipeline",
"(",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"retriever",
",",
"name",
"=",
"\"Retriever\"",
",",
"inputs",
"=",
"[",
"\"Query\"",
"]",
")"
] | [
342,
4
] | [
349,
87
] | python | en | ['en', 'error', 'th'] | False |
GenerativeQAPipeline.__init__ | (self, generator: BaseGenerator, retriever: BaseRetriever) |
Initialize a Pipeline for Generative Question Answering.
:param generator: Generator instance
:param retriever: Retriever instance
|
Initialize a Pipeline for Generative Question Answering. | def __init__(self, generator: BaseGenerator, retriever: BaseRetriever):
"""
Initialize a Pipeline for Generative Question Answering.
:param generator: Generator instance
:param retriever: Retriever instance
"""
self.pipeline = Pipeline()
self.pipeline.add_node(component=retriever, name="Retriever", inputs=["Query"])
self.pipeline.add_node(component=generator, name="Generator", inputs=["Retriever"]) | [
"def",
"__init__",
"(",
"self",
",",
"generator",
":",
"BaseGenerator",
",",
"retriever",
":",
"BaseRetriever",
")",
":",
"self",
".",
"pipeline",
"=",
"Pipeline",
"(",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"retriever",
",",
"name",
"=",
"\"Retriever\"",
",",
"inputs",
"=",
"[",
"\"Query\"",
"]",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"generator",
",",
"name",
"=",
"\"Generator\"",
",",
"inputs",
"=",
"[",
"\"Retriever\"",
"]",
")"
] | [
359,
4
] | [
368,
91
] | python | en | ['en', 'error', 'th'] | False |
SearchSummarizationPipeline.__init__ | (self, summarizer: BaseSummarizer, retriever: BaseRetriever) |
Initialize a Pipeline that retrieves documents for a query and then summarizes those documents.
:param summarizer: Summarizer instance
:param retriever: Retriever instance
|
Initialize a Pipeline that retrieves documents for a query and then summarizes those documents. | def __init__(self, summarizer: BaseSummarizer, retriever: BaseRetriever):
"""
Initialize a Pipeline that retrieves documents for a query and then summarizes those documents.
:param summarizer: Summarizer instance
:param retriever: Retriever instance
"""
self.pipeline = Pipeline()
self.pipeline.add_node(component=retriever, name="Retriever", inputs=["Query"])
self.pipeline.add_node(component=summarizer, name="Summarizer", inputs=["Retriever"]) | [
"def",
"__init__",
"(",
"self",
",",
"summarizer",
":",
"BaseSummarizer",
",",
"retriever",
":",
"BaseRetriever",
")",
":",
"self",
".",
"pipeline",
"=",
"Pipeline",
"(",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"retriever",
",",
"name",
"=",
"\"Retriever\"",
",",
"inputs",
"=",
"[",
"\"Query\"",
"]",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"summarizer",
",",
"name",
"=",
"\"Summarizer\"",
",",
"inputs",
"=",
"[",
"\"Retriever\"",
"]",
")"
] | [
378,
4
] | [
387,
93
] | python | en | ['en', 'error', 'th'] | False |
SearchSummarizationPipeline.run | (
self,
query: str,
filters: Optional[Dict] = None,
top_k_retriever: int = 10,
generate_single_summary: bool = False,
return_in_answer_format=False
) |
:param query: Your search query
:param filters:
:param top_k_retriever: Number of top docs the retriever should pass to the summarizer.
The higher this value, the slower your pipeline.
:param generate_single_summary: Whether to generate single summary from all retrieved docs (True) or one per doc (False).
:param return_in_answer_format: Whether the results should be returned as documents (False) or in the answer format used in other QA pipelines (True).
With the latter, you can use this pipeline as a "drop-in replacement" for other QA pipelines.
|
:param query: Your search query
:param filters:
:param top_k_retriever: Number of top docs the retriever should pass to the summarizer.
The higher this value, the slower your pipeline.
:param generate_single_summary: Whether to generate single summary from all retrieved docs (True) or one per doc (False).
:param return_in_answer_format: Whether the results should be returned as documents (False) or in the answer format used in other QA pipelines (True).
With the latter, you can use this pipeline as a "drop-in replacement" for other QA pipelines.
| def run(
self,
query: str,
filters: Optional[Dict] = None,
top_k_retriever: int = 10,
generate_single_summary: bool = False,
return_in_answer_format=False
):
"""
:param query: Your search query
:param filters:
:param top_k_retriever: Number of top docs the retriever should pass to the summarizer.
The higher this value, the slower your pipeline.
:param generate_single_summary: Whether to generate single summary from all retrieved docs (True) or one per doc (False).
:param return_in_answer_format: Whether the results should be returned as documents (False) or in the answer format used in other QA pipelines (True).
With the latter, you can use this pipeline as a "drop-in replacement" for other QA pipelines.
"""
output = self.pipeline.run(
query=query, filters=filters, top_k_retriever=top_k_retriever, generate_single_summary=generate_single_summary
)
# Convert to answer format to allow "drop-in replacement" for other QA pipelines
if return_in_answer_format:
results: Dict = {"query": query, "answers": []}
docs = deepcopy(output["documents"])
for doc in docs:
cur_answer = {
"query": query,
"answer": doc.text,
"document_id": doc.id,
"context": doc.meta.pop("context"),
"score": None,
"probability": None,
"offset_start": None,
"offset_end": None,
"meta": doc.meta,
}
results["answers"].append(cur_answer)
else:
results = output
return results | [
"def",
"run",
"(",
"self",
",",
"query",
":",
"str",
",",
"filters",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"top_k_retriever",
":",
"int",
"=",
"10",
",",
"generate_single_summary",
":",
"bool",
"=",
"False",
",",
"return_in_answer_format",
"=",
"False",
")",
":",
"output",
"=",
"self",
".",
"pipeline",
".",
"run",
"(",
"query",
"=",
"query",
",",
"filters",
"=",
"filters",
",",
"top_k_retriever",
"=",
"top_k_retriever",
",",
"generate_single_summary",
"=",
"generate_single_summary",
")",
"# Convert to answer format to allow \"drop-in replacement\" for other QA pipelines",
"if",
"return_in_answer_format",
":",
"results",
":",
"Dict",
"=",
"{",
"\"query\"",
":",
"query",
",",
"\"answers\"",
":",
"[",
"]",
"}",
"docs",
"=",
"deepcopy",
"(",
"output",
"[",
"\"documents\"",
"]",
")",
"for",
"doc",
"in",
"docs",
":",
"cur_answer",
"=",
"{",
"\"query\"",
":",
"query",
",",
"\"answer\"",
":",
"doc",
".",
"text",
",",
"\"document_id\"",
":",
"doc",
".",
"id",
",",
"\"context\"",
":",
"doc",
".",
"meta",
".",
"pop",
"(",
"\"context\"",
")",
",",
"\"score\"",
":",
"None",
",",
"\"probability\"",
":",
"None",
",",
"\"offset_start\"",
":",
"None",
",",
"\"offset_end\"",
":",
"None",
",",
"\"meta\"",
":",
"doc",
".",
"meta",
",",
"}",
"results",
"[",
"\"answers\"",
"]",
".",
"append",
"(",
"cur_answer",
")",
"else",
":",
"results",
"=",
"output",
"return",
"results"
] | [
389,
4
] | [
430,
22
] | python | en | ['en', 'error', 'th'] | False |
FAQPipeline.__init__ | (self, retriever: BaseRetriever) |
Initialize a Pipeline for finding similar FAQs using semantic document search.
:param retriever: Retriever instance
|
Initialize a Pipeline for finding similar FAQs using semantic document search. | def __init__(self, retriever: BaseRetriever):
"""
Initialize a Pipeline for finding similar FAQs using semantic document search.
:param retriever: Retriever instance
"""
self.pipeline = Pipeline()
self.pipeline.add_node(component=retriever, name="Retriever", inputs=["Query"]) | [
"def",
"__init__",
"(",
"self",
",",
"retriever",
":",
"BaseRetriever",
")",
":",
"self",
".",
"pipeline",
"=",
"Pipeline",
"(",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"retriever",
",",
"name",
"=",
"\"Retriever\"",
",",
"inputs",
"=",
"[",
"\"Query\"",
"]",
")"
] | [
434,
4
] | [
441,
87
] | python | en | ['en', 'error', 'th'] | False |
TranslationWrapperPipeline.__init__ | (
self,
input_translator: BaseTranslator,
output_translator: BaseTranslator,
pipeline: BaseStandardPipeline
) |
Wrap a given `pipeline` with the `input_translator` and `output_translator`.
:param input_translator: A Translator node that shall translate the input query from language A to B
:param output_translator: A Translator node that shall translate the pipeline results from language B to A
:param pipeline: The pipeline object (e.g. ExtractiveQAPipeline) you want to "wrap".
Note that pipelines with split or merge nodes are currently not supported.
|
Wrap a given `pipeline` with the `input_translator` and `output_translator`. | def __init__(
self,
input_translator: BaseTranslator,
output_translator: BaseTranslator,
pipeline: BaseStandardPipeline
):
"""
Wrap a given `pipeline` with the `input_translator` and `output_translator`.
:param input_translator: A Translator node that shall translate the input query from language A to B
:param output_translator: A Translator node that shall translate the pipeline results from language B to A
:param pipeline: The pipeline object (e.g. ExtractiveQAPipeline) you want to "wrap".
Note that pipelines with split or merge nodes are currently not supported.
"""
self.pipeline = Pipeline()
self.pipeline.add_node(component=input_translator, name="InputTranslator", inputs=["Query"])
graph = pipeline.pipeline.graph
previous_node_name = ["InputTranslator"]
# Traverse in BFS
for node in graph.nodes:
if node == "Query":
continue
# TODO: Do not work properly for Join Node and Answer format
if graph.nodes[node]["inputs"] and len(graph.nodes[node]["inputs"]) > 1:
raise AttributeError("Split and merge nodes are not supported currently")
self.pipeline.add_node(name=node, component=graph.nodes[node]["component"], inputs=previous_node_name)
previous_node_name = [node]
self.pipeline.add_node(component=output_translator, name="OutputTranslator", inputs=previous_node_name) | [
"def",
"__init__",
"(",
"self",
",",
"input_translator",
":",
"BaseTranslator",
",",
"output_translator",
":",
"BaseTranslator",
",",
"pipeline",
":",
"BaseStandardPipeline",
")",
":",
"self",
".",
"pipeline",
"=",
"Pipeline",
"(",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"input_translator",
",",
"name",
"=",
"\"InputTranslator\"",
",",
"inputs",
"=",
"[",
"\"Query\"",
"]",
")",
"graph",
"=",
"pipeline",
".",
"pipeline",
".",
"graph",
"previous_node_name",
"=",
"[",
"\"InputTranslator\"",
"]",
"# Traverse in BFS",
"for",
"node",
"in",
"graph",
".",
"nodes",
":",
"if",
"node",
"==",
"\"Query\"",
":",
"continue",
"# TODO: Do not work properly for Join Node and Answer format",
"if",
"graph",
".",
"nodes",
"[",
"node",
"]",
"[",
"\"inputs\"",
"]",
"and",
"len",
"(",
"graph",
".",
"nodes",
"[",
"node",
"]",
"[",
"\"inputs\"",
"]",
")",
">",
"1",
":",
"raise",
"AttributeError",
"(",
"\"Split and merge nodes are not supported currently\"",
")",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"name",
"=",
"node",
",",
"component",
"=",
"graph",
".",
"nodes",
"[",
"node",
"]",
"[",
"\"component\"",
"]",
",",
"inputs",
"=",
"previous_node_name",
")",
"previous_node_name",
"=",
"[",
"node",
"]",
"self",
".",
"pipeline",
".",
"add_node",
"(",
"component",
"=",
"output_translator",
",",
"name",
"=",
"\"OutputTranslator\"",
",",
"inputs",
"=",
"previous_node_name",
")"
] | [
473,
4
] | [
505,
111
] | python | en | ['en', 'error', 'th'] | False |
JoinDocuments.__init__ | (
self, join_mode: str = "concatenate", weights: Optional[List[float]] = None, top_k_join: Optional[int] = None
) |
:param join_mode: `concatenate` to combine documents from multiple retrievers or `merge` to aggregate scores of
individual documents.
:param weights: A node-wise list(length of list must be equal to the number of input nodes) of weights for
adjusting document scores when using the `merge` join_mode. By default, equal weight is given
to each retriever score. This param is not compatible with the `concatenate` join_mode.
:param top_k_join: Limit documents to top_k based on the resulting scores of the join.
|
:param join_mode: `concatenate` to combine documents from multiple retrievers or `merge` to aggregate scores of
individual documents.
:param weights: A node-wise list(length of list must be equal to the number of input nodes) of weights for
adjusting document scores when using the `merge` join_mode. By default, equal weight is given
to each retriever score. This param is not compatible with the `concatenate` join_mode.
:param top_k_join: Limit documents to top_k based on the resulting scores of the join.
| def __init__(
self, join_mode: str = "concatenate", weights: Optional[List[float]] = None, top_k_join: Optional[int] = None
):
"""
:param join_mode: `concatenate` to combine documents from multiple retrievers or `merge` to aggregate scores of
individual documents.
:param weights: A node-wise list(length of list must be equal to the number of input nodes) of weights for
adjusting document scores when using the `merge` join_mode. By default, equal weight is given
to each retriever score. This param is not compatible with the `concatenate` join_mode.
:param top_k_join: Limit documents to top_k based on the resulting scores of the join.
"""
assert join_mode in ["concatenate", "merge"], f"JoinDocuments node does not support '{join_mode}' join_mode."
assert not (
weights is not None and join_mode == "concatenate"
), "Weights are not compatible with 'concatenate' join_mode."
self.join_mode = join_mode
self.weights = weights
self.top_k = top_k_join | [
"def",
"__init__",
"(",
"self",
",",
"join_mode",
":",
"str",
"=",
"\"concatenate\"",
",",
"weights",
":",
"Optional",
"[",
"List",
"[",
"float",
"]",
"]",
"=",
"None",
",",
"top_k_join",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
":",
"assert",
"join_mode",
"in",
"[",
"\"concatenate\"",
",",
"\"merge\"",
"]",
",",
"f\"JoinDocuments node does not support '{join_mode}' join_mode.\"",
"assert",
"not",
"(",
"weights",
"is",
"not",
"None",
"and",
"join_mode",
"==",
"\"concatenate\"",
")",
",",
"\"Weights are not compatible with 'concatenate' join_mode.\"",
"self",
".",
"join_mode",
"=",
"join_mode",
"self",
".",
"weights",
"=",
"weights",
"self",
".",
"top_k",
"=",
"top_k_join"
] | [
531,
4
] | [
549,
31
] | python | en | ['en', 'error', 'th'] | False |
test_context_profiler | (filesystem_csv_data_context) |
This just validates that it's possible to profile using the datasource hook,
and have validation results available in the DataContext
|
This just validates that it's possible to profile using the datasource hook,
and have validation results available in the DataContext
| def test_context_profiler(filesystem_csv_data_context):
"""
This just validates that it's possible to profile using the datasource hook,
and have validation results available in the DataContext
"""
context = filesystem_csv_data_context
assert isinstance(context.datasources["rad_datasource"], PandasDatasource)
assert context.list_expectation_suites() == []
context.profile_datasource(
"rad_datasource",
profiler=BasicSuiteBuilderProfiler,
profiler_configuration="demo",
)
assert len(context.list_expectation_suites()) == 1
expected_suite_name = "rad_datasource.subdir_reader.f1.BasicSuiteBuilderProfiler"
expectation_suite = context.get_expectation_suite(expected_suite_name)
for exp in expectation_suite.expectations:
assert "BasicSuiteBuilderProfiler" in exp.meta
assert "confidence" in exp.meta["BasicSuiteBuilderProfiler"]
assert expectation_suite.expectation_suite_name == expected_suite_name
assert "batch_kwargs" in expectation_suite.meta["BasicSuiteBuilderProfiler"]
assert expectation_suite.meta["notes"] == {
"format": "markdown",
"content": [
"""#### This is an _example_ suite
- This suite was made by quickly glancing at 1000 rows of your data.
- This is **not a production suite**. It is meant to show examples of expectations.
- Because this suite was auto-generated using a very basic profiler that does not know your data like you do, many of the expectations may not be meaningful.
"""
],
}
expectation_types = [
expectation["expectation_type"]
for expectation in expectation_suite.expectations
]
expected_expectation_types = {
"expect_table_row_count_to_be_between",
"expect_table_column_count_to_equal",
"expect_table_columns_to_match_ordered_list",
"expect_column_values_to_not_be_null",
"expect_column_min_to_be_between",
"expect_column_max_to_be_between",
"expect_column_mean_to_be_between",
"expect_column_median_to_be_between",
"expect_column_quantile_values_to_be_between",
}
assert set(expectation_types) == expected_expectation_types | [
"def",
"test_context_profiler",
"(",
"filesystem_csv_data_context",
")",
":",
"context",
"=",
"filesystem_csv_data_context",
"assert",
"isinstance",
"(",
"context",
".",
"datasources",
"[",
"\"rad_datasource\"",
"]",
",",
"PandasDatasource",
")",
"assert",
"context",
".",
"list_expectation_suites",
"(",
")",
"==",
"[",
"]",
"context",
".",
"profile_datasource",
"(",
"\"rad_datasource\"",
",",
"profiler",
"=",
"BasicSuiteBuilderProfiler",
",",
"profiler_configuration",
"=",
"\"demo\"",
",",
")",
"assert",
"len",
"(",
"context",
".",
"list_expectation_suites",
"(",
")",
")",
"==",
"1",
"expected_suite_name",
"=",
"\"rad_datasource.subdir_reader.f1.BasicSuiteBuilderProfiler\"",
"expectation_suite",
"=",
"context",
".",
"get_expectation_suite",
"(",
"expected_suite_name",
")",
"for",
"exp",
"in",
"expectation_suite",
".",
"expectations",
":",
"assert",
"\"BasicSuiteBuilderProfiler\"",
"in",
"exp",
".",
"meta",
"assert",
"\"confidence\"",
"in",
"exp",
".",
"meta",
"[",
"\"BasicSuiteBuilderProfiler\"",
"]",
"assert",
"expectation_suite",
".",
"expectation_suite_name",
"==",
"expected_suite_name",
"assert",
"\"batch_kwargs\"",
"in",
"expectation_suite",
".",
"meta",
"[",
"\"BasicSuiteBuilderProfiler\"",
"]",
"assert",
"expectation_suite",
".",
"meta",
"[",
"\"notes\"",
"]",
"==",
"{",
"\"format\"",
":",
"\"markdown\"",
",",
"\"content\"",
":",
"[",
"\"\"\"#### This is an _example_ suite\n\n- This suite was made by quickly glancing at 1000 rows of your data.\n- This is **not a production suite**. It is meant to show examples of expectations.\n- Because this suite was auto-generated using a very basic profiler that does not know your data like you do, many of the expectations may not be meaningful.\n\"\"\"",
"]",
",",
"}",
"expectation_types",
"=",
"[",
"expectation",
"[",
"\"expectation_type\"",
"]",
"for",
"expectation",
"in",
"expectation_suite",
".",
"expectations",
"]",
"expected_expectation_types",
"=",
"{",
"\"expect_table_row_count_to_be_between\"",
",",
"\"expect_table_column_count_to_equal\"",
",",
"\"expect_table_columns_to_match_ordered_list\"",
",",
"\"expect_column_values_to_not_be_null\"",
",",
"\"expect_column_min_to_be_between\"",
",",
"\"expect_column_max_to_be_between\"",
",",
"\"expect_column_mean_to_be_between\"",
",",
"\"expect_column_median_to_be_between\"",
",",
"\"expect_column_quantile_values_to_be_between\"",
",",
"}",
"assert",
"set",
"(",
"expectation_types",
")",
"==",
"expected_expectation_types"
] | [
382,
0
] | [
438,
63
] | 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.