self._address_line1 = address_line1<EOL>

Sets the address_line1 of this Address.
Line 1 of Address

:param address_line1: The address_line1 of this Address.
:type: str


return self.to_str()<EOL>


result = {}<EOL>for attr, _ in iteritems(self.swagger_types):<EOL><INDENT>value = getattr(self, attr)<EOL>if isinstance(value, list):<EOL><INDENT>result[attr] = list(map(<EOL>lambda x: x.to_dict() if hasattr(x, "<STR_LIT>") else x,<EOL>value<EOL>))<EOL><DEDENT>elif hasattr(value, "<STR_LIT>"):<EOL><INDENT>result[attr] = value.to_dict()<EOL><DEDENT>else:<EOL><INDENT>result[attr] = value<EOL><DEDENT><DEDENT>return result<EOL>


return self._address<EOL>

Gets the address of this AuthorizedSignatoryWithCompanies.

:return: The address of this AuthorizedSignatoryWithCompanies.
:rtype: Address


return self._authorized_signatories<EOL>

Gets the authorized_signatories of this AuthorizedSignatories.
Array of Authorized Signatories

:return: The authorized_signatories of this AuthorizedSignatories.
:rtype: list[AuthorizedSignatoryWithCompanies]


return pformat(self.to_dict())<EOL>

Returns the string representation of the model


return pformat(self.to_dict())<EOL>


self._amount = amount<EOL>

Sets the amount of this Charge.
Amount of charges

:param amount: The amount of this Charge.
:type: int


return not self == other<EOL>

Returns true if both objects are not equal


return self.__dict__ == other.__dict__<EOL>


return self._companies<EOL>

Gets the companies of this Companies.
Array of Companies

:return: The companies of this Companies.
:rtype: list[CompanyBrief]


return self.__logger_file<EOL>


return {<EOL>'<STR_LIT>':<EOL>{<EOL>'<STR_LIT:type>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:key>': '<STR_LIT>',<EOL>'<STR_LIT:value>': self.get_api_key_with_prefix('<STR_LIT>')<EOL>},<EOL>}<EOL>

Gets Auth Settings dict for api client.

:return: The Auth Settings information dict.


return self.__debug<EOL>


def companies_cin_authorized_signatories_get(self, x_api_version, cin, **kwargs):

all_params = ['<STR_LIT>', '<STR_LIT>']<EOL>all_params.append('<STR_LIT>')<EOL>params = locals()<EOL>for key, val in iteritems(params['<STR_LIT>']):<EOL><INDENT>if key not in all_params:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % key<EOL>)<EOL><DEDENT>params[key] = val<EOL><DEDENT>del params['<STR_LIT>']<EOL>if ('<STR_LIT>' not in params) or (params['<STR_LIT>'] is None):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if ('<STR_LIT>' not in params) or (params['<STR_LIT>'] is None):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>resource_path = '<STR_LIT>'.replace('<STR_LIT>', '<STR_LIT>')<EOL>method = '<STR_LIT:GET>'<EOL>path_params = {}<EOL>if '<STR_LIT>' in params:<EOL><INDENT>path_params['<STR_LIT>'] = params['<STR_LIT>']<EOL><DEDENT>query_params = {}<EOL>header_params = {}<EOL>if '<STR_LIT>' in params:<EOL><INDENT>header_params['<STR_LIT>'] = params['<STR_LIT>']<EOL><DEDENT>form_params = {}<EOL>files = {}<EOL>body_params = None<EOL>header_params['<STR_LIT>'] = self.api_client.select_header_accept(['<STR_LIT:application/json>'])<EOL>if not header_params['<STR_LIT>']:<EOL><INDENT>del header_params['<STR_LIT>']<EOL><DEDENT>header_params['<STR_LIT:Content-Type>'] = self.api_client.select_header_content_type([])<EOL>auth_settings = ['<STR_LIT>']<EOL>response = self.api_client.call_api(resource_path, method,<EOL>path_params,<EOL>query_params,<EOL>header_params,<EOL>body=body_params,<EOL>post_params=form_params,<EOL>files=files,<EOL>response_type='<STR_LIT>',<EOL>auth_settings=auth_settings,<EOL>callback=params.get('<STR_LIT>'))<EOL>return response<EOL>

Authorized Signatories
Returns the Authorized Signatories which includes the Directors given a Company's CIN

This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>>     pprint(response)
>>>
>>> thread = api.companies_cin_authorized_signatories_get(x_api_version, cin, callback=callback_function)

:param callback function: The callback function
    for asynchronous request. (optional)
:param str x_api_version: api version (required)
:param str cin: cin of the company to fetch (required)
:return: InlineResponse2003
         If the method is called asynchronously,
         returns the request thread.


def companies_cin_charges_get(self, x_api_version, cin, **kwargs):

Charges
Returns the Charge details given a Company's CIN

This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>>     pprint(response)
>>>
>>> thread = api.companies_cin_charges_get(x_api_version, cin, callback=callback_function)

:param callback function: The callback function
    for asynchronous request. (optional)
:param str x_api_version: api version (required)
:param str cin: cin of the company to fetch (required)
:return: InlineResponse2004
         If the method is called asynchronously,
         returns the request thread.


def companies_cin_update_post(self, x_api_version, cin, **kwargs):

all_params = ['<STR_LIT>', '<STR_LIT>']<EOL>all_params.append('<STR_LIT>')<EOL>params = locals()<EOL>for key, val in iteritems(params['<STR_LIT>']):<EOL><INDENT>if key not in all_params:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % key<EOL>)<EOL><DEDENT>params[key] = val<EOL><DEDENT>del params['<STR_LIT>']<EOL>if ('<STR_LIT>' not in params) or (params['<STR_LIT>'] is None):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if ('<STR_LIT>' not in params) or (params['<STR_LIT>'] is None):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>resource_path = '<STR_LIT>'.replace('<STR_LIT>', '<STR_LIT>')<EOL>method = '<STR_LIT:POST>'<EOL>path_params = {}<EOL>if '<STR_LIT>' in params:<EOL><INDENT>path_params['<STR_LIT>'] = params['<STR_LIT>']<EOL><DEDENT>query_params = {}<EOL>header_params = {}<EOL>if '<STR_LIT>' in params:<EOL><INDENT>header_params['<STR_LIT>'] = params['<STR_LIT>']<EOL><DEDENT>form_params = {}<EOL>files = {}<EOL>body_params = None<EOL>header_params['<STR_LIT>'] = self.api_client.select_header_accept(['<STR_LIT:application/json>'])<EOL>if not header_params['<STR_LIT>']:<EOL><INDENT>del header_params['<STR_LIT>']<EOL><DEDENT>header_params['<STR_LIT:Content-Type>'] = self.api_client.select_header_content_type([])<EOL>auth_settings = ['<STR_LIT>']<EOL>response = self.api_client.call_api(resource_path, method,<EOL>path_params,<EOL>query_params,<EOL>header_params,<EOL>body=body_params,<EOL>post_params=form_params,<EOL>files=files,<EOL>response_type=None,<EOL>auth_settings=auth_settings,<EOL>callback=params.get('<STR_LIT>'))<EOL>return response<EOL>

Update Company data
This is an asynchronous call, where the request to update the company data is queued.\nYou will have to call the financial-datastatus to see if the update has happened.

This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>>     pprint(response)
>>>
>>> thread = api.companies_cin_update_post(x_api_version, cin, callback=callback_function)

:param callback function: The callback function
    for asynchronous request. (optional)
:param str x_api_version: api version (required)
:param str cin: cin of the company to update (required)
:return: None
         If the method is called asynchronously,
         returns the request thread.


def companies_cin_financial_datastatus_get(self, x_api_version, cin, **kwargs):

Financial Data Status
Returns the financial status of the company - years for which balancesheet is present

This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>>     pprint(response)
>>>
>>> thread = api.companies_cin_financial_datastatus_get(x_api_version, cin, callback=callback_function)

:param callback function: The callback function
    for asynchronous request. (optional)
:param str x_api_version: api version (required)
:param str cin: cin of the company to fetch (required)
:return: InlineResponse2005
         If the method is called asynchronously,
         returns the request thread.


if b < a:<EOL><INDENT>c = <NUM_LIT> - a<EOL>return (c + b) / float(delta)<EOL><DEDENT>return (b - a) / float(delta)<EOL>


yield wait(<NUM_LIT:0.1>)<EOL>yield service.stopService()<EOL>yield wait(<NUM_LIT:0.1>)<EOL>

Wait a little bit before and after stopping the service for things to
happen in the right order. :-(


self.td = self.t.start(self.inter)<EOL>if self.use_ssh and self.ssh_connector:<EOL><INDENT>self.ssh_client.connect()<EOL><DEDENT>


message = proto_pb2.Msg(<EOL>events=[self.encodeEvent(e) for e in events if e._type=='<STR_LIT>']<EOL>)<EOL>return message.SerializeToString()<EOL>

Encode a list of Tensor events with protobuf


def ping(dst, count, inter=<NUM_LIT>, maxwait=<NUM_LIT:1000>, size=<NUM_LIT:64>):

def _then(result, p):<EOL><INDENT>p.stopListening()<EOL>return result<EOL><DEDENT>d = defer.Deferred()<EOL>p = ICMPPort(<NUM_LIT:0>, ICMPPing(d, dst, count, inter, maxwait, size), "<STR_LIT>", <NUM_LIT>, reactor)<EOL>p.startListening()<EOL>return d.addCallback(_then, p)<EOL>

Sends ICMP echo requests to destination `dst` `count` times.
    Returns a deferred which fires when responses are finished.


rows = []<EOL>self.get_fn(lambda row: rows.append(row), max_lines=max_lines)<EOL>return rows<EOL>

Returns a big list of all log lines since the last run


if self._changed():<EOL><INDENT>self._read()<EOL><DEDENT>if k in self.store:<EOL><INDENT>return tuple(self.store[k])<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>


now = time.time()<EOL>cache = self._acquire_cache()<EOL>expired = [k for k, v in cache.items() if (now - v[<NUM_LIT:0>]) > age]<EOL>for k in expired:<EOL><INDENT>if k in cache:<EOL><INDENT>del cache[k]<EOL><DEDENT>if k in self.store:<EOL><INDENT>del self.store[k]<EOL><DEDENT><DEDENT>self._write_cache(cache)<EOL>

Expire any items in the cache older than `age` seconds


def fork(executable, args=(), env={}, path=None, timeout=<NUM_LIT>):

d = defer.Deferred()<EOL>p = ProcessProtocol(d, timeout)<EOL>reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path)<EOL>return d<EOL>

fork
    Provides a deferred wrapper function with a timeout function

    :param executable: Executable
    :type executable: str.
    :param args: Tupple of arguments
    :type args: tupple.
    :param env: Environment dictionary
    :type env: dict.
    :param timeout: Kill the child process if timeout is exceeded
    :type timeout: int.


def getBody(self, url, method='<STR_LIT:GET>', headers={}, data=None, socket=None):

if not '<STR_LIT>' in headers:<EOL><INDENT>headers['<STR_LIT>'] = ['<STR_LIT>']<EOL><DEDENT>return self.request(url, method, headers, data, socket)<EOL>

Make an HTTP request and return the body


@defer.inlineCallbacks<EOL><INDENT>def getJson(self, url, method='<STR_LIT:GET>', headers={}, data=None, socket=None):<DEDENT>

if not '<STR_LIT:Content-Type>' in headers:<EOL><INDENT>headers['<STR_LIT:Content-Type>'] = ['<STR_LIT:application/json>']<EOL><DEDENT>body = yield self.getBody(url, method, headers, data, socket)<EOL>defer.returnValue(json.loads(body))<EOL>


if self._changed():<EOL><INDENT>self._read()<EOL><DEDENT>return k in self.store.keys()<EOL>


server = self.config.get('<STR_LIT>', '<STR_LIT:127.0.0.1>')<EOL>port = self.config.get('<STR_LIT:port>', <NUM_LIT>)<EOL>def connect(ip):<EOL><INDENT>self.protocol = riemann.RiemannUDP(ip, port)<EOL>self.endpoint = reactor.listenUDP(<NUM_LIT:0>, self.protocol)<EOL><DEDENT>d = reactor.resolve(server)<EOL>d.addCallback(connect)<EOL>return d<EOL>


self.t.stop()<EOL>


if self.proto == '<STR_LIT>':<EOL><INDENT>defaultOutput = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': self.server,<EOL>'<STR_LIT:port>': self.port<EOL>}<EOL><DEDENT>else:<EOL><INDENT>defaultOutput = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': self.server,<EOL>'<STR_LIT:port>': self.port<EOL>}<EOL><DEDENT>outputs = config.get('<STR_LIT>', [defaultOutput])<EOL>for output in outputs:<EOL><INDENT>if not ('<STR_LIT>' in output):<EOL><INDENT>output['<STR_LIT>'] = self.debug<EOL><DEDENT>cl = output['<STR_LIT>'].split('<STR_LIT:.>')[-<NUM_LIT:1>]                <EOL>path = '<STR_LIT:.>'.join(output['<STR_LIT>'].split('<STR_LIT:.>')[:-<NUM_LIT:1>])   <EOL>outputObj = getattr(<EOL>importlib.import_module(path), cl)(output, self)<EOL>name = output.get('<STR_LIT:name>', None)<EOL>if name in self.outputs:<EOL><INDENT>self.outputs[name].append(outputObj)<EOL><DEDENT>else:<EOL><INDENT>self.outputs[name] = [outputObj]<EOL><DEDENT>reactor.callLater(<NUM_LIT:0>, outputObj.createClient)<EOL><DEDENT>


def to_child(self, append_message="<STR_LIT>", node_name="<STR_LIT>", **kwargs):

base_kwargs = {<EOL>attr: getattr(self, attr)<EOL>for attr in self.params<EOL>if attr not in ["<STR_LIT>"]<EOL>}<EOL>if not isinstance(append_message, dict):<EOL><INDENT>append_message = {"<STR_LIT>": append_message, "<STR_LIT>": {}}<EOL><DEDENT>kwargs["<STR_LIT>"] = [*self.messages, append_message]<EOL>kwargs["<STR_LIT>"] = self<EOL>for kwarg in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>if kwarg in kwargs and not kwargs[kwarg]:<EOL><INDENT>kwargs.pop(kwarg, None)<EOL><DEDENT><DEDENT>def update_kwarg(name, func):<EOL><INDENT>kwargs[name] = func(kwargs[name])<EOL><DEDENT>def update_context(name):<EOL><INDENT>update_kwarg(name, getattr(self, name).update_ctx)<EOL><DEDENT>if isinstance(kwargs.get("<STR_LIT>", None), list):<EOL><INDENT>update_kwarg("<STR_LIT>", wrap_in_module)<EOL><DEDENT>if isinstance(kwargs.get("<STR_LIT>", None), list):<EOL><INDENT>update_kwarg("<STR_LIT>", wrap_in_module)<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>kwargs["<STR_LIT>"] = self.student_ast_tokens.get_text(<EOL>kwargs["<STR_LIT>"]<EOL>)<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>kwargs["<STR_LIT>"] = self.solution_ast_tokens.get_text(<EOL>kwargs["<STR_LIT>"]<EOL>)<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>update_context("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>update_context("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>update_context("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in kwargs:<EOL><INDENT>update_context("<STR_LIT>")<EOL><DEDENT>klass = self.SUBCLASSES[node_name] if node_name else State<EOL>child = klass(**{**base_kwargs, **kwargs})<EOL>return child<EOL>

Dive into nested tree.

        Set the current state as a state with a subtree of this syntax tree as
        student tree and solution tree. This is necessary when testing if statements or
        for loops for example.


def check_object(<EOL>state, index, missing_msg=None, expand_msg=None, typestr="<STR_LIT>"<EOL>):

<EOL>if v2_only():<EOL><INDENT>extra_msg = "<STR_LIT>"<EOL>state.assert_root("<STR_LIT>", extra_msg=extra_msg)<EOL><DEDENT>if missing_msg is None:<EOL><INDENT>missing_msg = "<STR_LIT>"<EOL><DEDENT>if expand_msg is None:<EOL><INDENT>expand_msg = "<STR_LIT>"<EOL><DEDENT>if (<EOL>not isDefinedInProcess(index, state.solution_process)<EOL>and state.has_different_processes()<EOL>):<EOL><INDENT>raise InstructorError(<EOL>"<STR_LIT>"<EOL>% index<EOL>)<EOL><DEDENT>append_message = {"<STR_LIT>": expand_msg, "<STR_LIT>": {"<STR_LIT:index>": index, "<STR_LIT>": typestr}}<EOL>fallback = lambda: ObjectAssignmentParser.get_part(index)<EOL>stu_part = state.ast_dispatcher("<STR_LIT>", state.student_ast).get(index, fallback())<EOL>sol_part = state.ast_dispatcher("<STR_LIT>", state.solution_ast).get(index, fallback())<EOL>_msg = state.build_message(missing_msg, append_message["<STR_LIT>"])<EOL>state.do_test(DefinedProcessTest(index, state.student_process, Feedback(_msg)))<EOL>child = part_to_child(<EOL>stu_part, sol_part, append_message, state, node_name="<STR_LIT>"<EOL>)<EOL>return child<EOL>

Check object existence (and equality)

    Check whether an object is defined in the student's process, and zoom in on its value in both
    student and solution process to inspect quality (with has_equal_value().

    In ``pythonbackend``, both the student's submission as well as the solution code are executed, in separate processes.
    ``check_object()`` looks at these processes and checks if the referenced object is available in the student process.
    Next, you can use ``has_equal_value()`` to check whether the objects in the student and solution process correspond.

    Args:
        index (str): the name of the object which value has to be checked.
        missing_msg (str): feedback message when the object is not defined in the student process.
        expand_msg (str): If specified, this overrides any messages that are prepended by previous SCT chains.

    :Example:

        Suppose you want the student to create a variable ``x``, equal to 15: ::

            x = 15

        The following SCT will verify this: ::

            Ex().check_object("x").has_equal_value()

        - ``check_object()`` will check if the variable ``x`` is defined in the student process.
        - ``has_equal_value()`` will check whether the value of ``x`` in the solution process is the same as in the student process.

        Note that ``has_equal_value()`` only looks at **end result** of a variable in the student process.
        In the example, how the object ``x`` came about in the student's submission, does not matter.
        This means that all of the following submission will also pass the above SCT: ::

            x = 15
            x = 12 + 3
            x = 3; x += 12

    :Example:

        As the previous example mentioned, ``has_equal_value()`` only looks at the **end result**. If your exercise is
        first initializing and object and further down the script is updating the object, you can only look at the final value!

        Suppose you want the student to initialize and populate a list `my_list` as follows: ::

            my_list = []
            for i in range(20):
                if i % 3 == 0:
                    my_list.append(i)

        There is no robust way to verify whether `my_list = [0]` was coded correctly in a separate way.
        The best SCT would look something like this: ::

            msg = "Have you correctly initialized `my_list`?"
            Ex().check_correct(
                check_object('my_list').has_equal_value(),
                multi(
                    # check initialization: [] or list()
                    check_or(
                        has_equal_ast(code = "[]", incorrect_msg = msg),
                        check_function('list')
                    ),
                    check_for_loop().multi(
                        check_iter().has_equal_value(),
                        check_body().check_if_else().multi(
                            check_test().multi(
                                set_context(2).has_equal_value(),
                                set_context(3).has_equal_value()
                            ),
                            check_body().set_context(3).\\
                                set_env(my_list = [0]).\\
                                has_equal_value(name = 'my_list')
                        )
                    )
                )
            )

        - ``check_correct()`` is used to robustly check whether ``my_list`` was built correctly.
        - If ``my_list`` is not correct, **both** the initialization and the population code are checked.

    :Example:

        Because checking object correctness incorrectly is such a common misconception, we're adding another example: ::

            import pandas as pd
            df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
            df['c'] = [7, 8, 9]

        The following SCT would be **wrong**, as it does not factor in the possibility that the 'add column ``c``' step could've been wrong: ::

            Ex().check_correct(
                check_object('df').has_equal_value(),
                check_function('pandas.DataFrame').check_args(0).has_equal_value()
            )

        The following SCT would be better, as it is specific to the steps: ::

            # verify the df = pd.DataFrame(...) step
            Ex().check_correct(
                check_df('df').multi(
                    check_keys('a').has_equal_value(),
                    check_keys('b').has_equal_value()
                ),
                check_function('pandas.DataFrame').check_args(0).has_equal_value()
            )

            # verify the df['c'] = [...] step
            Ex().check_df('df').check_keys('c').has_equal_value()

    :Example:

        pythonwhat compares the objects in the student and solution process with the ``==`` operator.
        For basic objects, this ``==`` is operator is properly implemented, so that the objects can be effectively compared.
        For more complex objects that are produced by third-party packages, however, it's possible that this equality operator is not implemented in a way you'd expect.
        Often, for these object types the ``==`` will compare the actual object instances: ::

            # pre exercise code
            class Number():
                def __init__(self, n):
                    self.n = n

            # solution
            x = Number(1)

            # sct that won't work
            Ex().check_object().has_equal_value()

            # sct
            Ex().check_object().has_equal_value(expr_code = 'x.n')

            # submissions that will pass this sct
            x = Number(1)
            x = Number(2 - 1)

        The basic SCT like in the previous example will notwork here.
        Notice how we used the ``expr_code`` argument to _override_ which value `has_equal_value()` is checking.
        Instead of checking whether `x` corresponds between student and solution process, it's now executing the expression ``x.n``
        and seeing if the result of running this expression in both student and solution process match.


def has_output(state, text, pattern=True, no_output_msg=None):

if not no_output_msg:<EOL><INDENT>no_output_msg = "<STR_LIT>"<EOL><DEDENT>_msg = state.build_message(no_output_msg)<EOL>state.do_test(StringContainsTest(state.raw_student_output, text, pattern, _msg))<EOL>return state<EOL>

Search student output for a pattern.

    Among the student and solution process, the student submission and solution code as a string,
    the ``Ex()`` state also contains the output that a student generated with his or her submission.

    With ``has_output()``, you can access this output and match it against a regular or fixed expression.

    Args:
        text (str): the text that is searched for
        pattern (bool): if True (default), the text is treated as a pattern. If False, it is treated as plain text.
        no_output_msg (str): feedback message to be displayed if the output is not found.

    :Example:

        As an example, suppose we want a student to print out a sentence: ::

            # Print the "This is some ... stuff"
            print("This is some weird stuff")

        The following SCT tests whether the student prints out ``This is some weird stuff``: ::

            # Using exact string matching
            Ex().has_output("This is some weird stuff", pattern = False)

            # Using a regular expression (more robust)
            # pattern = True is the default
            msg = "Print out ``This is some ... stuff`` to the output, " + \\
                  "fill in ``...`` with a word you like."
            Ex().has_output(r"This is some \w* stuff", no_output_msg = msg)


student_imports = state.ast_dispatcher("<STR_LIT>", state.student_ast)<EOL>solution_imports = state.ast_dispatcher("<STR_LIT>", state.solution_ast)<EOL>if name not in solution_imports:<EOL><INDENT>raise InstructorError(<EOL>"<STR_LIT>"<EOL>% name<EOL>)<EOL><DEDENT>fmt_kwargs = {"<STR_LIT>": name, "<STR_LIT>": solution_imports[name]}<EOL>_msg = state.build_message(not_imported_msg, fmt_kwargs)<EOL>state.do_test(DefinedCollTest(name, student_imports, _msg))<EOL>if same_as:<EOL><INDENT>_msg = state.build_message(incorrect_as_msg, fmt_kwargs)<EOL>state.do_test(EqualTest(solution_imports[name], student_imports[name], _msg))<EOL><DEDENT>return state<EOL>

Checks whether student imported a package or function correctly.

    Python features many ways to import packages.
    All of these different methods revolve around the ``import``, ``from`` and ``as`` keywords.
    ``has_import()`` provides a robust way to check whether a student correctly imported a certain package.

    By default, ``has_import()`` allows for different ways of aliasing the imported package or function.
    If you want to make sure the correct alias was used to refer to the package or function that was imported,
    set ``same_as=True``.

    Args:
        name (str): the name of the package that has to be checked.
        same_as (bool): if True, the alias of the package or function has to be the same. Defaults to False.
        not_imported_msg (str): feedback message when the package is not imported.
        incorrect_as_msg (str): feedback message if the alias is wrong.

    :Example:

        Example 1, where aliases don't matter (defaut): ::

            # solution
            import matplotlib.pyplot as plt

            # sct
            Ex().has_import("matplotlib.pyplot")

            # passing submissions
            import matplotlib.pyplot as plt
            from matplotlib import pyplot as plt
            import matplotlib.pyplot as pltttt

            # failing submissions
            import matplotlib as mpl

        Example 2, where the SCT is coded so aliases do matter: ::

            # solution
            import matplotlib.pyplot as plt

            # sct
            Ex().has_import("matplotlib.pyplot", same_as=True)

            # passing submissions
            import matplotlib.pyplot as plt
            from matplotlib import pyplot as plt

            # failing submissions
            import matplotlib.pyplot as pltttt


def has_equal_part_len(state, name, unequal_msg):

d = dict(<EOL>stu_len=len(state.student_parts[name]), sol_len=len(state.solution_parts[name])<EOL>)<EOL>if d["<STR_LIT>"] != d["<STR_LIT>"]:<EOL><INDENT>_msg = state.build_message(unequal_msg, d)<EOL>state.report(Feedback(_msg, state))<EOL><DEDENT>return state<EOL>

Verify that a part that is zoomed in on has equal length.

    Typically used in the context of ``check_function_def()``

    Arguments:
        name (str): name of the part for which to check the length to the corresponding part in the solution.
        unequal_msg (str): Message in case the lengths do not match.
        state (State): state as passed by the SCT chain. Don't specify this explicitly.

    :Examples:

        Student and solution code::

            def shout(word):
                return word + '!!!'

        SCT that checks number of arguments::

            Ex().check_function_def('shout').has_equal_part_len('args', 'not enough args!')


append_missing = missing_msg is None<EOL>append_params_not_matched = params_not_matched_msg is None<EOL>if missing_msg is None:<EOL><INDENT>missing_msg = MISSING_MSG<EOL><DEDENT>if expand_msg is None:<EOL><INDENT>expand_msg = PREPEND_MSG<EOL><DEDENT>if params_not_matched_msg is None:<EOL><INDENT>params_not_matched_msg = SIG_ISSUE_MSG<EOL><DEDENT>stu_out = state.ast_dispatcher("<STR_LIT>", state.student_ast)<EOL>sol_out = state.ast_dispatcher("<STR_LIT>", state.solution_ast)<EOL>student_mappings = state.ast_dispatcher("<STR_LIT>", state.student_ast)<EOL>fmt_kwargs = {<EOL>"<STR_LIT>": get_times(index + <NUM_LIT:1>),<EOL>"<STR_LIT>": get_ord(index + <NUM_LIT:1>),<EOL>"<STR_LIT:index>": index,<EOL>"<STR_LIT>": get_mapped_name(name, student_mappings),<EOL>}<EOL>try:<EOL><INDENT>sol_parts = {**sol_out[name][index]}<EOL><DEDENT>except KeyError:<EOL><INDENT>raise InstructorError(<EOL>"<STR_LIT>"<EOL>% name<EOL>)<EOL><DEDENT>except IndexError:<EOL><INDENT>raise InstructorError(<EOL>"<STR_LIT>"<EOL>% (index + <NUM_LIT:1>, name)<EOL>)<EOL><DEDENT>try:<EOL><INDENT>stu_parts = {**stu_out[name][index]}<EOL><DEDENT>except (KeyError, IndexError):<EOL><INDENT>_msg = state.build_message(missing_msg, fmt_kwargs, append=append_missing)<EOL>state.report(Feedback(_msg, state))<EOL><DEDENT>if signature:<EOL><INDENT>signature = None if isinstance(signature, bool) else signature<EOL>get_sig = partial(<EOL>getSignatureInProcess,<EOL>name=name,<EOL>signature=signature,<EOL>manual_sigs=state.get_manual_sigs(),<EOL>)<EOL>try:<EOL><INDENT>sol_sig = get_sig(<EOL>mapped_name=sol_parts["<STR_LIT:name>"], process=state.solution_process<EOL>)<EOL>sol_parts["<STR_LIT:args>"] = bind_args(sol_sig, sol_parts["<STR_LIT:args>"])<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise InstructorError(<EOL>"<STR_LIT>"<EOL>% (get_ord(index + <NUM_LIT:1>), name, e)<EOL>)<EOL><DEDENT>try:<EOL><INDENT>stu_sig = get_sig(<EOL>mapped_name=stu_parts["<STR_LIT:name>"], process=state.student_process<EOL>)<EOL>stu_parts["<STR_LIT:args>"] = bind_args(stu_sig, stu_parts["<STR_LIT:args>"])<EOL><DEDENT>except Exception:<EOL><INDENT>_msg = state.build_message(<EOL>params_not_matched_msg, fmt_kwargs, append=append_params_not_matched<EOL>)<EOL>state.report(<EOL>Feedback(<EOL>_msg, StubState(stu_parts["<STR_LIT>"], state.highlighting_disabled)<EOL>)<EOL>)<EOL><DEDENT><DEDENT>append_message = {"<STR_LIT>": expand_msg, "<STR_LIT>": fmt_kwargs}<EOL>child = part_to_child(<EOL>stu_parts, sol_parts, append_message, state, node_name="<STR_LIT>"<EOL>)<EOL>return child<EOL>

Check whether a particular function is called.

    ``check_function()`` is typically followed by:

    - ``check_args()`` to check whether the arguments were specified.
      In turn, ``check_args()`` can be followed by ``has_equal_value()`` or ``has_equal_ast()``
      to assert that the arguments were correctly specified.
    - ``has_equal_value()`` to check whether rerunning the function call coded by the student
      gives the same result as calling the function call as in the solution.

    Checking function calls is a tricky topic. Please visit the
    `dedicated article <articles/checking_function_calls.html>`_ for more explanation,
    edge cases and best practices.

    Args:
        name (str): the name of the function to be tested. When checking functions in packages, always
            use the 'full path' of the function.
        index (int): index of the function call to be checked. Defaults to 0.
        missing_msg (str): If specified, this overrides an automatically generated feedback message in case
            the student did not call the function correctly.
        params_not_matched_msg (str): If specified, this overrides an automatically generated feedback message
            in case the function parameters were not successfully matched.
        expand_msg (str): If specified, this overrides any messages that are prepended by previous SCT chains.
        signature (Signature): Normally, check_function() can figure out what the function signature is,
            but it might be necessary to use ``sig_from_params()`` to manually build a signature and pass this along.
        state (State): State object that is passed from the SCT Chain (don't specify this).

    :Examples:

        Student code and solution code::

            import numpy as np
            arr = np.array([1, 2, 3, 4, 5])
            np.mean(arr)

        SCT::

            # Verify whether arr was correctly set in np.mean
            Ex().check_function('numpy.mean').check_args('a').has_equal_value()

            # Verify whether np.mean(arr) produced the same result
            Ex().check_function('numpy.mean').has_equal_value()


pass<EOL>

This function is called when all other nodes are encountered when traversing the tree.
When inheriting form this standard parser, this function will make the parser ignore
all nodes that are not relevant.

Args:
    node (ast.Node): The node which is visited.


def __init__(self, string, search_string, pattern, feedback):

super().__init__(feedback)<EOL>self.string = string<EOL>self.search_string = search_string<EOL>self.pattern = pattern<EOL>

Initialize with a string to look for, a string to search and whether or not to look for a pattern.

Args:
    string (regex/str):  The string to look for will be set to this.
    search_string (str): The string to search in will be set to this.
    pattern (bool): The pattern boolean will be set to this.
    feedback (str): The failure message will be set to this.


State.root_state.reporter.success_msg = message<EOL>

Set the succes message of the sct. This message will be the feedback if all tests pass.
Args:
        message (str): A string containing the feedback message.


if include_me:<EOL><INDENT>yield self<EOL><DEDENT>for child in self.child_list:<EOL><INDENT>yield child<EOL>yield from child.descend()<EOL><DEDENT>

Descend depth first into all child nodes


ba = self.data["<STR_LIT>"]<EOL>return state_partial(self.data["<STR_LIT>"], *ba.args[<NUM_LIT:1>:], **ba.kwargs)<EOL>

Return partial of original function call


if not self.api_key:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>response = _request('<STR_LIT>',<EOL>url=self.url_v1('<STR_LIT>' + pin_id),<EOL>user_agent=self.user_agent,<EOL>api_key=self.api_key,<EOL>)<EOL>_raise_for_status(response)<EOL>

Delete a shared pin.

:param str pin_id: The id of the pin to delete.
:raises `requests.exceptions.HTTPError`: If an HTTP error occurred.


def create_from_array(self, blockname, array, Nfile=None, memorylimit=<NUM_LIT> * <NUM_LIT> * <NUM_LIT>):

size = len(array)<EOL>sizeperfile = <NUM_LIT:32> * <NUM_LIT> * <NUM_LIT><EOL>if Nfile is None:<EOL><INDENT>Nfile = (size + sizeperfile - <NUM_LIT:1>) // sizeperfile<EOL><DEDENT>dtype = numpy.dtype((array.dtype, array.shape[<NUM_LIT:1>:]))<EOL>itemsize = dtype.itemsize<EOL>itemlimit = memorylimit // dtype.itemsize // <NUM_LIT> * <NUM_LIT><EOL>with self.create(blockname, dtype, size, Nfile) as b:<EOL><INDENT>for i in range(<NUM_LIT:0>, len(array), itemlimit):<EOL><INDENT>b.write(i, numpy.array(array[i:i+itemlimit]))<EOL><DEDENT><DEDENT>return self.open(blockname)<EOL>

create a block from array like objects
            The operation is well defined only if array is at most 2d.

            Parameters
            ----------
            array : array_like,
                array shall have a scalar dtype.
            blockname : string
                name of the block
            Nfile : int or None
                number of physical files. if None, 32M items per file
                is used.
            memorylimit : int
                number of bytes to use for the buffering. relevant only if
                indexing on array returns a copy (e.g. IO or dask array)


mols = [mol]<EOL>for n in six.moves.range(<NUM_LIT:20>):<EOL><INDENT>products = {}<EOL>for mol in mols:<EOL><INDENT>for product in [x[<NUM_LIT:0>] for x in rule.RunReactants((mol,))]:<EOL><INDENT>if Chem.SanitizeMol(product, catchErrors=True) == <NUM_LIT:0>:<EOL><INDENT>products[Chem.MolToSmiles(product, isomericSmiles=True)] = product<EOL><DEDENT><DEDENT><DEDENT>if products:<EOL><INDENT>mols = [products[s] for s in sorted(products)]<EOL><DEDENT>else:<EOL><INDENT>return mols[<NUM_LIT:0>] if n > <NUM_LIT:0> else None<EOL><DEDENT><DEDENT>

Repeatedly apply normalization transform to molecule until no changes occur.

        It is possible for multiple products to be produced when a rule is applied. The rule is applied repeatedly to
        each of the products, until no further changes occur or after 20 attempts. If there are multiple unique products
        after the final application, the first product (sorted alphabetically by SMILES) is chosen.


def __init__(self, normalizations=NORMALIZATIONS, max_restarts=MAX_RESTARTS):

log.debug('<STR_LIT>')<EOL>self.normalizations = normalizations<EOL>self.max_restarts = max_restarts<EOL>

Initialize a Normalizer with an optional custom list of :class:`~molvs.normalize.Normalization` transforms.

        :param normalizations: A list of  :class:`~molvs.normalize.Normalization` transforms to apply.
        :param int max_restarts: The maximum number of times to attempt to apply the series of normalizations (default
                                 200).


log.debug('<STR_LIT>')<EOL>fragments = []<EOL>for fragment in Chem.GetMolFrags(mol, asMols=True):<EOL><INDENT>fragments.append(self._normalize_fragment(fragment))<EOL><DEDENT>outmol = fragments.pop()<EOL>for fragment in fragments:<EOL><INDENT>outmol = Chem.CombineMols(outmol, fragment)<EOL><DEDENT>Chem.SanitizeMol(outmol)<EOL>return outmol<EOL>

Apply a series of Normalization transforms to correct functional groups and recombine charges.

        A series of transforms are applied to the molecule. For each Normalization, the transform is applied repeatedly
        until no further changes occur. If any changes occurred, we go back and start from the first Normalization
        again, in case the changes mean an earlier transform is now applicable. The molecule is returned once the entire
        series of Normalizations cause no further changes or if max_restarts (default 200) is reached.

        :param mol: The molecule to normalize.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The normalized fragment.
        :rtype: rdkit.Chem.rdchem.Mol


return MetalDisconnector()<EOL>

:returns: A callable :class:`~molvs.metal.MetalDisconnector` instance.


log.debug('<STR_LIT>')<EOL>self.normalizations = normalizations<EOL>self.acid_base_pairs = acid_base_pairs<EOL>self.charge_corrections = charge_corrections<EOL>self.tautomer_transforms = tautomer_transforms<EOL>self.tautomer_scores = tautomer_scores<EOL>self.max_restarts = max_restarts<EOL>self.max_tautomers = max_tautomers<EOL>self.prefer_organic = prefer_organic<EOL>

Initialize a Standardizer with optional custom parameters.

        :param normalizations: A list of Normalizations to apply (default: :data:`~molvs.normalize.NORMALIZATIONS`).
        :param acid_base_pairs: A list of AcidBasePairs for competitive reionization (default:
                                :data:`~molvs.charge.ACID_BASE_PAIRS`).
        :param charge_corrections: A list of ChargeCorrections to apply (default:
                                :data:`~molvs.charge.CHARGE_CORRECTIONS`).
        :param tautomer_transforms: A list of TautomerTransforms to apply (default:
                                    :data:`~molvs.tautomer.TAUTOMER_TRANSFORMS`).
        :param tautomer_scores: A list of TautomerScores used to determine canonical tautomer (default:
                                :data:`~molvs.tautomer.TAUTOMER_SCORES`).
        :param max_restarts: The maximum number of times to attempt to apply the series of normalizations (default 200).
        :param max_tautomers: The maximum number of tautomers to enumerate (default 1000).
        :param prefer_organic: Whether to prioritize organic fragments when choosing fragment parent (default False).


return Reionizer(acid_base_pairs=self.acid_base_pairs, charge_corrections=self.charge_corrections)<EOL>

:returns: A callable :class:`~molvs.charge.Reionizer` instance.


def fragment_parent(self, mol, skip_standardize=False):

if not skip_standardize:<EOL><INDENT>mol = self.standardize(mol)<EOL><DEDENT>fragment = self.largest_fragment(mol)<EOL>return fragment<EOL>

Return the fragment parent of a given molecule.

        The fragment parent is the largest organic covalent unit in the molecule.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :param bool skip_standardize: Set to True if mol has already been standardized.
        :returns: The fragment parent molecule.
        :rtype: rdkit.Chem.rdchem.Mol


return Uncharger(acid_base_pairs=self.acid_base_pairs)<EOL>

:returns: A callable :class:`~molvs.charge.Uncharger` instance.


mol = copy.deepcopy(mol)<EOL>Chem.SanitizeMol(mol)<EOL>mol = Chem.RemoveHs(mol)<EOL>mol = self.disconnect_metals(mol)<EOL>mol = self.normalize(mol)<EOL>mol = self.reionize(mol)<EOL>Chem.AssignStereochemistry(mol, force=True, cleanIt=True)<EOL>return mol<EOL>

Return a standardized version the given molecule.

        The standardization process consists of the following stages: RDKit
        :py:func:`~rdkit.Chem.rdmolops.RemoveHs`, RDKit :py:func:`~rdkit.Chem.rdmolops.SanitizeMol`,
        :class:`~molvs.metal.MetalDisconnector`, :class:`~molvs.normalize.Normalizer`,
        :class:`~molvs.charge.Reionizer`, RDKit :py:func:`~rdkit.Chem.rdmolops.AssignStereochemistry`.

        :param mol: The molecule to standardize.
        :type mol: rdkit.Chem.rdchem.Mol
        :returns: The standardized molecule.
        :rtype: rdkit.Chem.rdchem.Mol


def stereo_parent(self, mol, skip_standardize=False):

if not skip_standardize:<EOL><INDENT>mol = self.standardize(mol)<EOL><DEDENT>else:<EOL><INDENT>mol = copy.deepcopy(mol)<EOL><DEDENT>Chem.RemoveStereochemistry(mol)<EOL>return mol<EOL>

Return the stereo parent of a given molecule.

        The stereo parent has all stereochemistry information removed from tetrahedral centers and double bonds.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :param bool skip_standardize: Set to True if mol has already been standardized.
        :returns: The stereo parent molecule.
        :rtype: rdkit.Chem.rdchem.Mol


def isotope_parent(self, mol, skip_standardize=False):

if not skip_standardize:<EOL><INDENT>mol = self.standardize(mol)<EOL><DEDENT>else:<EOL><INDENT>mol = copy.deepcopy(mol)<EOL><DEDENT>for atom in mol.GetAtoms():<EOL><INDENT>atom.SetIsotope(<NUM_LIT:0>)<EOL><DEDENT>return mol<EOL>

Return the isotope parent of a given molecule.

        The isotope parent has all atoms replaced with the most abundant isotope for that element.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :param bool skip_standardize: Set to True if mol has already been standardized.
        :returns: The isotope parent molecule.
        :rtype: rdkit.Chem.rdchem.Mol


return self.remove(mol)<EOL>

Calling a FragmentRemover instance like a function is the same as calling its remove(mol) method.


log.debug('<STR_LIT>')<EOL>fragments = Chem.GetMolFrags(mol, asMols=True)<EOL>largest = None<EOL>for f in fragments:<EOL><INDENT>smiles = Chem.MolToSmiles(f, isomericSmiles=True)<EOL>log.debug('<STR_LIT>', smiles)<EOL>organic = is_organic(f)<EOL>if self.prefer_organic:<EOL><INDENT>if largest and largest['<STR_LIT>'] and not organic:<EOL><INDENT>continue<EOL><DEDENT>if largest and organic and not largest['<STR_LIT>']:<EOL><INDENT>largest = None<EOL><DEDENT><DEDENT>atoms = <NUM_LIT:0><EOL>for a in f.GetAtoms():<EOL><INDENT>atoms += <NUM_LIT:1> + a.GetTotalNumHs()<EOL><DEDENT>if largest and atoms < largest['<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>weight = rdMolDescriptors.CalcExactMolWt(f)<EOL>if largest and atoms == largest['<STR_LIT>'] and weight < largest['<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>if largest and atoms == largest['<STR_LIT>'] and weight == largest['<STR_LIT>'] and smiles > largest['<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>log.debug('<STR_LIT>', smiles, atoms)<EOL>largest = {'<STR_LIT>': smiles, '<STR_LIT>': f, '<STR_LIT>': atoms, '<STR_LIT>': weight, '<STR_LIT>': organic}<EOL><DEDENT>return largest['<STR_LIT>']<EOL>

Return the largest covalent unit.

        The largest fragment is determined by number of atoms (including hydrogens). Ties are broken by taking the
        fragment with the higher molecular weight, and then by taking the first alphabetically by SMILES if needed.

        :param mol: The molecule to choose the largest fragment from.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The largest fragment.
        :rtype: rdkit.Chem.rdchem.Mol


<EOL>for a in fragment.GetAtoms():<EOL><INDENT>if a.GetAtomicNum() == <NUM_LIT:6>:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return true if fragment contains at least one carbon atom.

    :param fragment: The fragment as an RDKit Mol object.


log.debug('<STR_LIT>')<EOL>for smarts in [self._metal_nof, self._metal_non]:<EOL><INDENT>pairs = mol.GetSubstructMatches(smarts)<EOL>rwmol = Chem.RWMol(mol)<EOL>orders = []<EOL>for i, j in pairs:<EOL><INDENT>orders.append(int(mol.GetBondBetweenAtoms(i, j).GetBondTypeAsDouble()))<EOL>rwmol.RemoveBond(i, j)<EOL><DEDENT>mol = rwmol.GetMol()<EOL>for n, (i, j) in enumerate(pairs):<EOL><INDENT>chg = orders[n]<EOL>atom1 = mol.GetAtomWithIdx(i)<EOL>atom1.SetFormalCharge(atom1.GetFormalCharge() + chg)<EOL>atom2 = mol.GetAtomWithIdx(j)<EOL>atom2.SetFormalCharge(atom2.GetFormalCharge() - chg)<EOL>log.info('<STR_LIT>', atom1.GetSymbol(), atom2.GetSymbol())<EOL><DEDENT><DEDENT>Chem.SanitizeMol(mol)<EOL>return mol<EOL>

Break covalent bonds between metals and organic atoms under certain conditions.

        The algorithm works as follows:

        - Disconnect N, O, F from any metal.
        - Disconnect other non-metals from transition metals + Al (but not Hg, Ga, Ge, In, Sn, As, Tl, Pb, Bi, Po).
        - For every bond broken, adjust the charges of the begin and end atoms accordingly.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The molecule with metals disconnected.
        :rtype: rdkit.Chem.rdchem.Mol


def __init__(self, validations=VALIDATIONS, log_format=SIMPLE_FORMAT, level=logging.INFO, stdout=False, raw=False):

self.raw = raw<EOL>self.log = logging.getLogger(type(self).__name__)<EOL>self.log.setLevel(level)<EOL>self.handler = LogHandler()<EOL>self.handler.setFormatter(logging.Formatter(log_format))<EOL>self.log.addHandler(self.handler)<EOL>if stdout:<EOL><INDENT>strhdlr = logging.StreamHandler(sys.stdout)<EOL>strhdlr.setFormatter(logging.Formatter(log_format))<EOL>self.log.addHandler(strhdlr)<EOL><DEDENT>self.validations = [validation(self.log) for validation in validations]<EOL>

Initialize a Validator with the following parameters:

        :param validations: A list of Validations to apply (default: :data:`~molvs.validations.VALIDATIONS`).
        :param string log_format: A string format (default: :data:`~molvs.validate.SIMPLE_FORMAT`).
        :param level: The minimum logging level to output.
        :param bool stdout: Whether to send log messages to standard output.
        :param bool raw: Whether to return raw :class:`~logging.LogRecord` objects instead of formatted log strings.


return self.validate(mol)<EOL>

Calling a Validator instance like a function is the same as calling its
        :meth:`~molvs.validate.Validator.validate` method.


attr_name = '<STR_LIT>'.format(fget.__name__)<EOL>@functools.wraps(fget)<EOL>def fget_memoized(self):<EOL><INDENT>if not hasattr(self, attr_name):<EOL><INDENT>setattr(self, attr_name, fget(self))<EOL><DEDENT>return getattr(self, attr_name)<EOL><DEDENT>return property(fget_memoized)<EOL>

Decorator to create memoized properties.


return self.canonicalize(mol)<EOL>

Calling a TautomerCanonicalizer instance like a function is the same as calling its canonicalize(mol) method.


smiles = Chem.MolToSmiles(mol, isomericSmiles=True)<EOL>tautomers = {smiles: copy.deepcopy(mol)}<EOL>kekulized = copy.deepcopy(mol)<EOL>Chem.Kekulize(kekulized)<EOL>kekulized = {smiles: kekulized}<EOL>done = set()<EOL>while len(tautomers) < self.max_tautomers:<EOL><INDENT>for tsmiles in sorted(tautomers):<EOL><INDENT>if tsmiles in done:<EOL><INDENT>continue<EOL><DEDENT>for transform in self.transforms:<EOL><INDENT>for match in kekulized[tsmiles].GetSubstructMatches(transform.tautomer):<EOL><INDENT>product = copy.deepcopy(kekulized[tsmiles])<EOL>first = product.GetAtomWithIdx(match[<NUM_LIT:0>])<EOL>last = product.GetAtomWithIdx(match[-<NUM_LIT:1>])<EOL>first.SetNumExplicitHs(max(<NUM_LIT:0>, first.GetTotalNumHs() - <NUM_LIT:1>))<EOL>last.SetNumExplicitHs(last.GetTotalNumHs() + <NUM_LIT:1>)<EOL>first.SetNoImplicit(True)<EOL>last.SetNoImplicit(True)<EOL>for bi, pair in enumerate(pairwise(match)):<EOL><INDENT>if transform.bonds:<EOL><INDENT>product.GetBondBetweenAtoms(*pair).SetBondType(transform.bonds[bi])<EOL><DEDENT>else:<EOL><INDENT>current_bond_type = product.GetBondBetweenAtoms(*pair).GetBondType()<EOL>product.GetBondBetweenAtoms(*pair).SetBondType(BondType.DOUBLE if current_bond_type == BondType.SINGLE else BondType.SINGLE)<EOL><DEDENT><DEDENT>if transform.charges:<EOL><INDENT>for ci, idx in enumerate(match):<EOL><INDENT>atom = product.GetAtomWithIdx(idx)<EOL>atom.SetFormalCharge(atom.GetFormalCharge() + transform.charges[ci])<EOL><DEDENT><DEDENT>try:<EOL><INDENT>Chem.SanitizeMol(product)<EOL>smiles = Chem.MolToSmiles(product, isomericSmiles=True)<EOL>log.debug('<STR_LIT>', transform.name, tsmiles)<EOL>if smiles not in tautomers:<EOL><INDENT>log.debug('<STR_LIT>' % smiles)<EOL>kekulized_product = copy.deepcopy(product)<EOL>Chem.Kekulize(kekulized_product)<EOL>tautomers[smiles] = product<EOL>kekulized[smiles] = kekulized_product<EOL><DEDENT>else:<EOL><INDENT>log.debug('<STR_LIT>' % smiles)<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>log.debug('<STR_LIT>', transform.name)<EOL><DEDENT><DEDENT><DEDENT>done.add(tsmiles)<EOL><DEDENT>if len(tautomers) == len(done):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.warning('<STR_LIT>', self.max_tautomers)<EOL><DEDENT>for tautomer in tautomers.values():<EOL><INDENT>Chem.AssignStereochemistry(tautomer, force=True, cleanIt=True)<EOL>for bond in tautomer.GetBonds():<EOL><INDENT>if bond.GetBondType() == BondType.DOUBLE and bond.GetStereo() > BondStereo.STEREOANY:<EOL><INDENT>begin = bond.GetBeginAtomIdx()<EOL>end = bond.GetEndAtomIdx()<EOL>for othertautomer in tautomers.values():<EOL><INDENT>if not othertautomer.GetBondBetweenAtoms(begin, end).GetBondType() == BondType.DOUBLE:<EOL><INDENT>neighbours = tautomer.GetAtomWithIdx(begin).GetBonds() + tautomer.GetAtomWithIdx(end).GetBonds()<EOL>for otherbond in neighbours:<EOL><INDENT>if otherbond.GetBondDir() in {BondDir.ENDUPRIGHT, BondDir.ENDDOWNRIGHT}:<EOL><INDENT>otherbond.SetBondDir(BondDir.NONE)<EOL><DEDENT><DEDENT>Chem.AssignStereochemistry(tautomer, force=True, cleanIt=True)<EOL>log.debug('<STR_LIT>')<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return list(tautomers.values())<EOL>

Enumerate all possible tautomers and return them as a list.

        :param mol: The input molecule.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: A list of all possible tautomers of the molecule.
        :rtype: list of rdkit.Chem.rdchem.Mol


return self.uncharge(mol)<EOL>

Calling an Uncharger instance like a function is the same as calling its uncharge(mol) method.


log.debug('<STR_LIT>', name)<EOL>self.name = name<EOL>self.acid_str = acid<EOL>self.base_str = base<EOL>

Initialize an AcidBasePair with the following parameters:

        :param string name: A name for this AcidBasePair.
        :param string acid: SMARTS pattern for the protonated acid.
        :param string base: SMARTS pattern for the conjugate ionized base.


log.debug('<STR_LIT>')<EOL>start_charge = Chem.GetFormalCharge(mol)<EOL>for cc in self.charge_corrections:<EOL><INDENT>for match in mol.GetSubstructMatches(cc.smarts):<EOL><INDENT>atom = mol.GetAtomWithIdx(match[<NUM_LIT:0>])<EOL>log.info('<STR_LIT>', cc.name, atom.GetSymbol(), cc.charge)<EOL>atom.SetFormalCharge(cc.charge)<EOL><DEDENT><DEDENT>current_charge = Chem.GetFormalCharge(mol)<EOL>charge_diff = Chem.GetFormalCharge(mol) - start_charge<EOL>if not current_charge == <NUM_LIT:0>:<EOL><INDENT>while charge_diff > <NUM_LIT:0>:<EOL><INDENT>ppos, poccur = self._strongest_protonated(mol)<EOL>if ppos is None:<EOL><INDENT>break<EOL><DEDENT>log.info('<STR_LIT>', self.acid_base_pairs[ppos].name)<EOL>patom = mol.GetAtomWithIdx(poccur[-<NUM_LIT:1>])<EOL>patom.SetFormalCharge(patom.GetFormalCharge() - <NUM_LIT:1>)<EOL>if patom.GetNumExplicitHs() > <NUM_LIT:0>:<EOL><INDENT>patom.SetNumExplicitHs(patom.GetNumExplicitHs() - <NUM_LIT:1>)<EOL><DEDENT>patom.UpdatePropertyCache()<EOL>charge_diff -= <NUM_LIT:1><EOL><DEDENT><DEDENT>already_moved = set()<EOL>while True:<EOL><INDENT>ppos, poccur = self._strongest_protonated(mol)<EOL>ipos, ioccur = self._weakest_ionized(mol)<EOL>if ioccur and poccur and ppos < ipos:<EOL><INDENT>if poccur[-<NUM_LIT:1>] == ioccur[-<NUM_LIT:1>]:<EOL><INDENT>log.warning('<STR_LIT>')<EOL>break<EOL><DEDENT>key = tuple(sorted([poccur[-<NUM_LIT:1>], ioccur[-<NUM_LIT:1>]]))<EOL>if key in already_moved:<EOL><INDENT>log.warning('<STR_LIT>')<EOL>break<EOL><DEDENT>already_moved.add(key)<EOL>log.info('<STR_LIT>', self.acid_base_pairs[ppos].name, self.acid_base_pairs[ipos].name)<EOL>patom = mol.GetAtomWithIdx(poccur[-<NUM_LIT:1>])<EOL>patom.SetFormalCharge(patom.GetFormalCharge() - <NUM_LIT:1>)<EOL>if patom.GetNumImplicitHs() == <NUM_LIT:0> and patom.GetNumExplicitHs() > <NUM_LIT:0>:<EOL><INDENT>patom.SetNumExplicitHs(patom.GetNumExplicitHs() - <NUM_LIT:1>)<EOL><DEDENT>patom.UpdatePropertyCache()<EOL>iatom = mol.GetAtomWithIdx(ioccur[-<NUM_LIT:1>])<EOL>iatom.SetFormalCharge(iatom.GetFormalCharge() + <NUM_LIT:1>)<EOL>if (iatom.GetNoImplicit() or<EOL>((patom.GetAtomicNum() == <NUM_LIT:7> or patom.GetAtomicNum() == <NUM_LIT:15>) and patom.GetIsAromatic()) or<EOL>iatom.GetTotalValence() not in list(Chem.GetPeriodicTable().GetValenceList(iatom.GetAtomicNum()))):<EOL><INDENT>iatom.SetNumExplicitHs(iatom.GetNumExplicitHs() + <NUM_LIT:1>)<EOL><DEDENT>iatom.UpdatePropertyCache()<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>Chem.SanitizeMol(mol)<EOL>return mol<EOL>

Enforce charges on certain atoms, then perform competitive reionization.

        First, charge corrections are applied to ensure, for example, that free metals are correctly ionized. Then, if
        a molecule with multiple acid groups is partially ionized, ensure the strongest acids ionize first.

        The algorithm works as follows:

        - Use SMARTS to find the strongest protonated acid and the weakest ionized acid.
        - If the ionized acid is weaker than the protonated acid, swap proton and repeat.

        :param mol: The molecule to reionize.
        :type mol: rdkit.Chem.rdchem.Mol
        :return: The reionized molecule.
        :rtype: rdkit.Chem.rdchem.Mol


def __init__(self, name, smarts, charge):

log.debug('<STR_LIT>', name)<EOL>self.name = name<EOL>self.smarts_str = smarts<EOL>self.charge = charge<EOL>

Initialize a ChargeCorrection with the following parameters:

        :param string name: A name for this ForcedAtomCharge.
        :param string smarts: SMARTS pattern to match. Charge is applied to the first atom.
        :param int charge: The charge to apply.


mol = Chem.MolFromSmiles(smiles, sanitize=False)<EOL>mol = Standardizer(prefer_organic=prefer_organic).fragment_parent(mol)<EOL>return Chem.MolToSmiles(mol, isomericSmiles=True)<EOL>

Utility function that returns the fragment parent SMILES for given a SMILES string.


mol = Chem.MolFromSmiles(smiles)<EOL>u = Uncharger()<EOL>mol = u.uncharge(mol)<EOL>if mol:<EOL><INDENT>return Chem.MolToSmiles(mol, isomericSmiles=True)<EOL><DEDENT>

Utility function that returns the uncharged SMILES for a given SMILES string.


if (word not in self.transmissions):<EOL><INDENT>raise NoMatchError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>trans = self.transmissions[word]<EOL>return sorted(((k, v) for k, v in trans.items() if v != <NUM_LIT:0>), <EOL>reverse=True)<EOL><DEDENT>

pass in a word string that you
would like to see probable matches for.


for iter in range(count):<EOL><INDENT>countef = {}<EOL>totalf = {}<EOL>for word in self.en_words:<EOL><INDENT>if(word not in self.probs):<EOL><INDENT>continue<EOL><DEDENT>word_probs = self.probs[word]<EOL>count = dict([(w, <NUM_LIT:0>) for w in word_probs])<EOL>countef[word] = count<EOL>totalf[word] = <NUM_LIT:0><EOL><DEDENT>self.countef = countef<EOL>self.totalf = totalf<EOL>for (es, ds) in self.sent_pairs:<EOL><INDENT>es_split = es.split()<EOL>ds_split = ds.split()<EOL>for d in ds_split:<EOL><INDENT>self.totals[d] = <NUM_LIT:0><EOL>for e in es_split:<EOL><INDENT>if (e not in self.transmissions):<EOL><INDENT>continue<EOL><DEDENT>e_trans = self.transmissions[e]<EOL>if (d not in e_trans):<EOL><INDENT>continue<EOL><DEDENT>self.totals[d] += e_trans[d]<EOL><DEDENT>for e in es_split:<EOL><INDENT>if(e not in self.transmissions):<EOL><INDENT>continue<EOL><DEDENT>if (d not in self.transmissions[e]):<EOL><INDENT>continue<EOL><DEDENT>self.countef[e][<EOL>d] += self.transmissions[e][d] / self.totals[d]<EOL>self.totalf[<EOL>e] += self.transmissions[e][d] / self.totals[d]<EOL><DEDENT><DEDENT><DEDENT>for e in self.en_words:<EOL><INDENT>if (e not in self.probs):<EOL><INDENT>continue<EOL><DEDENT>e_prob = self.probs[e]<EOL>for d in e_prob:<EOL><INDENT>self.transmissions[e][d] = self.countef[<EOL>e][d] / self.totalf[e]<EOL><DEDENT><DEDENT><DEDENT>

Iterate through all transmissions of english to
foreign words. keep count of repeated occurences
 do until convergence
   set count(e|f) to 0 for all e,f
   set total(f) to 0 for all f
   for all sentence pairs (e_s,f_s)
     set total_s(e) = 0 for all e
     for all words e in e_s
       for all words f in f_s
         total_s(e) += t(e|f)
     for all words e in e_s
       for all words f in f_s
         count(e|f) += t(e|f) / total_s(e)
         total(f)   += t(e|f) / total_s(e)
   for all f
     for all e
       t(e|f) = count(e|f) / total(f)


<EOL>while len(self._batches) > <NUM_LIT:0>:<EOL><INDENT>self._socket.sendall(self._batches[<NUM_LIT:0>])<EOL>self._batches.popleft()<EOL><DEDENT>return self<EOL>

Send buffered metrics in batch requests over TCP


client = TCPClient(self.host, self.port, self.prefix)<EOL>self._configure_client(client)<EOL>return client<EOL>

Return a TCPClient with same settings of the batch TCP client


def time_callable(self, name, target, rate=None, args=(), kwargs={}):<EOL>

assert callable(target)<EOL>if rate is None:<EOL><INDENT>rate = self._rate<EOL><DEDENT>else:<EOL><INDENT>assert_sample_rate(rate)<EOL><DEDENT>start_time = time()  <EOL>result = target(*args, **kwargs)<EOL>self.since(name, start_time, rate)<EOL>return result<EOL>

Send a Timer metric calculating duration of execution of the provided callable


batch_client = BatchClient(self.host, self.port, self.prefix, size)<EOL>self._configure_client(batch_client)<EOL>return batch_client<EOL>

Return a batch client with same settings of the client


def set(self, name, value, rate=<NUM_LIT:1>):<EOL>

if self._should_send_metric(name, rate):<EOL><INDENT>value = str(value)<EOL>self._request(<EOL>Set(<EOL>self._create_metric_name_for_request(name),<EOL>value,<EOL>rate<EOL>).to_request()<EOL>)<EOL><DEDENT>

Send a Set metric with the specified unique value


address = self.remote_address<EOL>while len(self._batches) > <NUM_LIT:0>:<EOL><INDENT>self._socket.sendto(self._batches[<NUM_LIT:0>], address)<EOL>self._batches.popleft()<EOL><DEDENT>return self<EOL>


raise NotImplementedError("<STR_LIT>")<EOL>


def hessian_f(*args, **kwargs):<EOL><INDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>x, = args<EOL>hessianf_x = (<EOL>f(x+delta) + f(x-delta) - <NUM_LIT:2>*f(x)<EOL>)/delta**<NUM_LIT:2><EOL>return hessianf_x<EOL><DEDENT>elif len(args) == <NUM_LIT:2>:<EOL><INDENT>x, y = args<EOL>if type(x) in [float, int] and type(y) in [float, int]:<EOL><INDENT>hess_xx = (<EOL>f(x + delta, y) + f(x - delta, y) - <NUM_LIT:2>*f(x, y)<EOL>)/delta**<NUM_LIT:2><EOL>hess_yy = (<EOL>f(x, y + delta) + f(x, y - delta) - <NUM_LIT:2>*f(x, y)<EOL>)/delta**<NUM_LIT:2><EOL>hess_xy = (<EOL>+ f(x+delta/<NUM_LIT:2>, y+delta/<NUM_LIT:2>)<EOL>+ f(x-delta/<NUM_LIT:2>, y-delta/<NUM_LIT:2>)<EOL>- f(x+delta/<NUM_LIT:2>, y-delta/<NUM_LIT:2>)<EOL>- f(x-delta/<NUM_LIT:2>, y+delta/<NUM_LIT:2>)<EOL>)/delta**<NUM_LIT:2><EOL>return hess_xx, hess_xy, hess_yy<EOL><DEDENT><DEDENT><DEDENT>return hessian_f<EOL>

Returns numerical hessian function of given input function
Input: f, scalar function of one or two variables
       delta(optional), finite difference step
Output: hessian function object


def clmixhess(obj, exe, arg1, arg2, delta=DELTA):

f, x = get_method_and_copy_of_attribute(obj, exe, arg1)<EOL>_, y = get_method_and_copy_of_attribute(obj, exe, arg2)<EOL>def hess_f(*args, **kwargs):<EOL><INDENT>hess_val = numpy.zeros(x.shape + y.shape)<EOL>it = numpy.nditer(x, op_flags=['<STR_LIT>'], flags=['<STR_LIT>'])<EOL>for xi in it:<EOL><INDENT>i = it.multi_index<EOL>jt = numpy.nditer(y, op_flags=['<STR_LIT>'], flags=['<STR_LIT>'])<EOL>for yj in jt:<EOL><INDENT>j = jt.multi_index<EOL>xi += delta/<NUM_LIT:2><EOL>yj += delta/<NUM_LIT:2><EOL>fpp = f(*args, **kwargs)<EOL>yj -= delta<EOL>fpm = f(*args, **kwargs)<EOL>xi -= delta<EOL>fmm = f(*args, **kwargs)<EOL>yj += delta<EOL>fmp = f(*args, **kwargs)<EOL>xi += delta/<NUM_LIT:2><EOL>yj -= delta/<NUM_LIT:2><EOL>hess_val[i + j] = (fpp + fmm - fpm - fmp)/delta**<NUM_LIT:2><EOL><DEDENT><DEDENT>return hess_val<EOL><DEDENT>return hess_f<EOL>

Returns numerical mixed Hessian function of given class method
with respect to two class attributes
Input: obj, general object
       exe (str), name of object method
       arg1(str), name of object attribute
       arg2(str), name of object attribute
       delta(float, optional), finite difference step
Output: Hessian function object


f, x = get_method_and_copy_of_attribute(obj, exe, arg)<EOL>def grad_f(*args, **kwargs):<EOL><INDENT>grad_val = numpy.zeros(x.shape)<EOL>it = numpy.nditer(x, op_flags=['<STR_LIT>'], flags=['<STR_LIT>'])<EOL>for xi in it:<EOL><INDENT>i = it.multi_index<EOL>xi += delta/<NUM_LIT:2><EOL>fp = f(*args, **kwargs)<EOL>xi -= delta<EOL>fm = f(*args, **kwargs)<EOL>xi += delta/<NUM_LIT:2><EOL>grad_val[i] = (fp - fm)/delta<EOL><DEDENT>return grad_val<EOL><DEDENT>return grad_f<EOL>

Returns numerical gradient function of given class method
with respect to a class attribute
Input: obj, general object
       exe (str), name of object method
       arg (str), name of object atribute
       delta(float, optional), finite difference step
Output: gradient function object


def grad_f(*args, **kwargs):<EOL><INDENT>x = args[<NUM_LIT:0>]<EOL>grad_val = numpy.zeros(x.shape)<EOL>it = numpy.nditer(x, op_flags=['<STR_LIT>'], flags=['<STR_LIT>'])<EOL>for xi in it:<EOL><INDENT>i = it.multi_index<EOL>xi += delta/<NUM_LIT:2><EOL>fp = f(*args, **kwargs)<EOL>xi -= delta<EOL>fm = f(*args, **kwargs)<EOL>xi += delta/<NUM_LIT:2><EOL>grad_val[i] = (fp - fm)/delta<EOL><DEDENT>return grad_val<EOL><DEDENT>return grad_f<EOL>

Returns numerical gradient function of given input function
Input: f, scalar function of an numpy array object
       delta(optional), finite difference step
Output: gradient function object


<EOL>if sys.platform == '<STR_LIT>':<EOL><INDENT>slash = '<STR_LIT:\\>'<EOL><DEDENT>elif sys.platform == '<STR_LIT>':<EOL><INDENT>slash = '<STR_LIT:/>'<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>print('<STR_LIT>')<EOL>for i in range(len(directory[<NUM_LIT:2>])):  <EOL><INDENT>full_path = directory[<NUM_LIT:0>]+slash+directory[<NUM_LIT:2>][i]<EOL>print(full_path)  <EOL>size(full_path)<EOL>print(md5(full_path))<EOL><DEDENT>

Split the tuple (obtained from scan) to separate files.
       Alternately send full paths to the files in md5 and call it.
       :param directory: tuple of files in the directory.


hasher = hashlib.md5()<EOL>with open(file_path, '<STR_LIT:rb>') as f:<EOL><INDENT>while True:<EOL><INDENT>buf = f.read(BLOCKSIZE)<EOL>if not buf:<EOL><INDENT>break<EOL><DEDENT>while len(buf) > <NUM_LIT:0>:<EOL><INDENT>hasher.update(buf)<EOL>buf = f.read(BLOCKSIZE)<EOL><DEDENT><DEDENT><DEDENT>md5_hash = hasher.hexdigest().upper()<EOL>return md5_hash<EOL>

Calculates the md5-hash of the file.
    :param file_path: full path to the file.


for p in self.processors():<EOL><INDENT>if p['<STR_LIT:name>'].startswith('<STR_LIT>'):<EOL><INDENT>print(p['<STR_LIT:name>'])<EOL><DEDENT><DEDENT>


if processor_name:<EOL><INDENT>return self.api.processor.get(name=processor_name)['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return self.api.processor.get()['<STR_LIT>']<EOL><DEDENT>

Return a list of Processor objects.

        :param project_id: ObjectId of Genesis project
        :type project_id: string
        :rtype: list of Processor objects


objects = self.cache['<STR_LIT>']<EOL>data = self.api.data.get(**query)['<STR_LIT>']<EOL>data_objects = []<EOL>for d in data:<EOL><INDENT>_id = d['<STR_LIT:id>']<EOL>if _id in objects:<EOL><INDENT>objects[_id].update(d)<EOL><DEDENT>else:<EOL><INDENT>objects[_id] = GenData(d, self)<EOL><DEDENT>data_objects.append(objects[_id])<EOL><DEDENT>for d in data_objects:<EOL><INDENT>count += <NUM_LIT:1><EOL>while True:<EOL><INDENT>ref_annotation = {}<EOL>remove_annotation = []<EOL>for path, ann in d.annotation.items():<EOL><INDENT>if ann['<STR_LIT:type>'].startswith('<STR_LIT>'):<EOL><INDENT>_id = ann['<STR_LIT:value>']<EOL>if _id not in objects:<EOL><INDENT>try:<EOL><INDENT>d_tmp = self.api.data(_id).get()<EOL><DEDENT>except slumber.exceptions.HttpClientError as ex:<EOL><INDENT>if ex.response.status_code == <NUM_LIT>:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>raise ex<EOL><DEDENT><DEDENT>objects[_id] = GenData(d_tmp, self)<EOL><DEDENT>annotation = objects[_id].annotation<EOL>ref_annotation.update({path + '<STR_LIT:.>' + k: v for k, v in annotation.items()})<EOL>remove_annotation.append(path)<EOL><DEDENT><DEDENT>if ref_annotation:<EOL><INDENT>d.annotation.update(ref_annotation)<EOL>for path in remove_annotation:<EOL><INDENT>del d.annotation[path]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return data_objects<EOL>


size = os.path.getsize(fn)<EOL>counter = <NUM_LIT:0><EOL>base_name = os.path.basename(fn)<EOL>session_id = str(uuid.uuid4())<EOL>with open(fn, '<STR_LIT:rb>') as f:<EOL><INDENT>while True:<EOL><INDENT>response = None<EOL>chunk = f.read(CHUNK_SIZE)<EOL>if not chunk:<EOL><INDENT>break<EOL><DEDENT>for i in range(<NUM_LIT:5>):<EOL><INDENT>content_range = '<STR_LIT>'.format(counter * CHUNK_SIZE,<EOL>counter * CHUNK_SIZE + len(chunk) - <NUM_LIT:1>, size)<EOL>if i > <NUM_LIT:0> and response is not None:<EOL><INDENT>print("<STR_LIT>"<EOL>.format(response.status_code, content_range))<EOL><DEDENT>response = requests.post(urlparse.urljoin(self.url, '<STR_LIT>'),<EOL>auth=self.auth,<EOL>data=chunk,<EOL>headers={<EOL>'<STR_LIT>': '<STR_LIT>'.format(base_name),<EOL>'<STR_LIT>': size,<EOL>'<STR_LIT>': content_range,<EOL>'<STR_LIT:Content-Type>': '<STR_LIT>',<EOL>'<STR_LIT>': session_id})<EOL>if response.status_code in [<NUM_LIT:200>, <NUM_LIT>]:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>progress = <NUM_LIT> * (counter * CHUNK_SIZE + len(chunk)) / size<EOL>sys.stdout.write("<STR_LIT>".format(progress, fn))<EOL>sys.stdout.flush()<EOL>counter += <NUM_LIT:1><EOL><DEDENT><DEDENT>print()<EOL>return session_id<EOL>

Upload a single file on the platform.

        File is uploaded in chunks of 1,024 bytes.

        :param fn: File path
        :type fn: string


for path, ann in self.annotation.items():<EOL><INDENT>if path.startswith('<STR_LIT>') and ann['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>print("<STR_LIT>".format(path, ann['<STR_LIT:value>']['<STR_LIT:file>']))<EOL><DEDENT><DEDENT>


data = self.gencloud.project_data(self.id)<EOL>return sorted(set(d.type for d in data))<EOL>


pass<EOL>


raise NotImplementedError()<EOL>


raise NotImplementedError()<EOL>

Move back a single entry in the browser's history.


@contextmanager<EOL><INDENT>def accept_modal(self, modal_type, text=None, response=None, wait=None):<DEDENT>

raise NotImplementedError()<EOL>

Accepts the modal that appears matching the given type and, optionally, text.

Args:
    modal_type (str): The type of modal that should be accepted.
    text (str | RegexObject, optional): Text that is expected to appear in the modal.
    response (str, optional): Text to enter for a response, if applicable.
    wait (int, optional): The number of seconds to wait for the modal to appear.


def evaluate_async_script(self, script, *args):

raise NotImplementedError()<EOL>

Evaluates the given JavaScript and obtains the result from a callback function.

Args:
    script (str): A string of JavaScript to evaluate.
    *args: Variable length argument list to pass to the executed JavaScript string.

Returns:
    object: The result of the evaluated JavaScript.


return ()<EOL>

Tuple[Exception]: A tuple of exceptions that indicate an element is invalid.


try:<EOL><INDENT>return self.evaluate_script("<STR_LIT>")<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>raise NotImplementedError()<EOL><DEDENT>


raise NotImplementedError()<EOL>

Move forward a single entry in the browser's history.


raise NotImplementedError()<EOL>

str: An XPath expression describing where on the page the node can be found.


def double_click(self, *keys, **offset):

raise NotImplementedError()<EOL>


raise NotImplementedError()<EOL>

Send keystrokes to the node.

Examples::

    from selenium.webdriver.common.keys import Keys

    element.send_keys("foo")                  # => value: "foo"
    element.send_keys("tet", Keys.LEFT, "s")  # => value: "test"

Args:
    *args: Variable length list of keys to send.


return "<STR_LIT>".join([describe(options) for describe in self.descriptions])<EOL>

Returns a description of the given filter options relevant to this selector.

Args:
    options (Dict[str, Any]): The filter options to describe.

Returns:
    str: A description of the filter options.


filter_set = filter_sets[name]<EOL>for name, filter in iter(filter_set.filters.items()):<EOL><INDENT>self.filters[name] = filter<EOL><DEDENT>self.descriptions += filter_set.descriptions<EOL>

Adds filters from a particular global :class:`FilterSet`.

Args:
    name (str): The name of the set whose filters should be added.


Returns a description of the given filter options relevant to this filter set.

Args:
    options (Dict[str, Any]): The filter options to describe.

Returns:
    str: A description of the filter options.


return FilterSet(self.name, self.descriptions, self.filters)<EOL>

FilterSet: Returns a new :class:`FilterSet` with the current factory config.


self.descriptions.append(func)<EOL>

Decorates a function that builds a description of some filter set options.

Args:
    func (Callable[[Dict[str, Any]], str]): The description builder function.


if not self.valid_values:<EOL><INDENT>return True<EOL><DEDENT>valid_values = (self.valid_values if isinstance(self.valid_values, list)<EOL>else list(self.valid_values))<EOL>return value in valid_values<EOL>


return self.skip_if is not None<EOL>

bool: Whether this rule has a value for which it should be skipped.


def assert_current_path(self, path, **kwargs):

query = CurrentPathQuery(path, **kwargs)<EOL>@self.document.synchronize<EOL>def assert_current_path():<EOL><INDENT>if not query.resolves_for(self):<EOL><INDENT>raise ExpectationNotMet(query.failure_message)<EOL><DEDENT><DEDENT>assert_current_path()<EOL>return True<EOL>

Asserts that the page has the given path. By default this will compare against the
path+query portion of the full URL.

Args:
    path (str | RegexObject): The string or regex that the current "path" should match.
    **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.

Returns:
    True

Raises:
    ExpectationNotMet: If the assertion hasn't succeeded during the wait time.


<EOL>for rootdir in path.parts(reverse=True):<EOL><INDENT>if rootdir.join("<STR_LIT>").exists():<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rootdir = path<EOL><DEDENT>pluginmanager = PytestPluginManager()<EOL>for spec in default_plugins:<EOL><INDENT>pluginmanager.import_plugin(spec)<EOL><DEDENT>config = Config(pluginmanager)<EOL>args = [rootdir]<EOL>config.parse(args)<EOL>return config<EOL>

Builds and returns a basic test configuration rooted at the given path.

Args:
    path (LocalPath): The path to the files under test.

Returns:
    Config: The generated test configuration.


return ismarionette(session) and int(session.driver.browser.capabilities['<STR_LIT>'].split("<STR_LIT:.>")[<NUM_LIT:0>]) < version<EOL>

Whether the session is using Marionette with Firefox less than the given version.

Args:
    version (int): The Firefox version to test.
    session (Session): The Capybara session.

Returns:
    bool: Whether the session is using Marionette with Firefox less than the given version.


try:<EOL><INDENT>from capybara.selenium.driver import Driver<EOL><DEDENT>except ImportError:<EOL><INDENT>return False<EOL><DEDENT>return isinstance(session.driver, Driver)<EOL>

bool: Whether the session is using Selenium.


return self._build_message("<STR_LIT>")<EOL>

str: A message describing the negative query failure.


self.node = node<EOL>self.actual_styles = node.style(*self.expected_styles.keys())<EOL>return all(<EOL>toregex(value).search(self.actual_styles[style])<EOL>for style, value in iter(self.expected_styles.items()))<EOL>

Resolves this query relative to the given node.

Args:
    node (node.Base): The node to be evaluated.

Returns:
    int: The number of matches found.


return (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>").format(<EOL>expected=desc(self.expected_styles),<EOL>actual=desc(self.actual_styles))<EOL>

str: A message describing the query failure.


if self.options["<STR_LIT>"] is not None:<EOL><INDENT>return self.options["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>return capybara.exact<EOL><DEDENT>

bool: Whether to exactly match the locator string.


description = self.label<EOL>if self.locator:<EOL><INDENT>description += "<STR_LIT>".format(desc(self.locator))<EOL><DEDENT>if self.options["<STR_LIT:text>"] is not None:<EOL><INDENT>description += "<STR_LIT>".format(desc(self.options["<STR_LIT:text>"]))<EOL><DEDENT>description += self.selector.description(self.filter_options)<EOL>return description<EOL>


visible = self.visible<EOL>if self.options["<STR_LIT:text>"]:<EOL><INDENT>if isregex(self.options["<STR_LIT:text>"]):<EOL><INDENT>regex = self.options["<STR_LIT:text>"]<EOL><DEDENT>elif self.exact_text is True:<EOL><INDENT>regex = re.compile(r"<STR_LIT>".format(re.escape(self.options["<STR_LIT:text>"])))<EOL><DEDENT>else:<EOL><INDENT>regex = toregex(self.options["<STR_LIT:text>"])<EOL><DEDENT>text = normalize_text(<EOL>node.all_text if visible == "<STR_LIT:all>" else node.visible_text)<EOL>if not regex.search(text):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if isinstance(self.exact_text, (bytes_, str_)):<EOL><INDENT>regex = re.compile(r"<STR_LIT>".format(re.escape(self.exact_text)))<EOL>text = normalize_text(<EOL>node.all_text if visible == "<STR_LIT:all>" else node.visible_text)<EOL>if not regex.search(text):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if visible == "<STR_LIT>":<EOL><INDENT>if not node.visible:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif visible == "<STR_LIT>":<EOL><INDENT>if node.visible:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>for name, node_filter in iter(self._node_filters.items()):<EOL><INDENT>if name in self.filter_options:<EOL><INDENT>if not node_filter.matches(node, self.filter_options[name]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif node_filter.has_default:<EOL><INDENT>if not node_filter.matches(node, node_filter.default):<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>if self.options["<STR_LIT>"] and not self.options["<STR_LIT>"](node):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Returns whether the given node matches all filters.

Args:
    node (Element): The node to evaluate.

Returns:
    bool: Whether the given node matches.


return self._build_message()<EOL>

str: A description of this query's failure.


str: A description of this query's negative failure.


if self.url:<EOL><INDENT>self.actual_path = session.current_url<EOL><DEDENT>else:<EOL><INDENT>result = urlparse(session.current_url)<EOL>if self.only_path:<EOL><INDENT>self.actual_path = result.path<EOL><DEDENT>else:<EOL><INDENT>request_uri = result.path<EOL>if result.query:<EOL><INDENT>request_uri += "<STR_LIT>".format(result.query)<EOL><DEDENT>self.actual_path = request_uri<EOL><DEDENT><DEDENT>if isregex(self.expected_path):<EOL><INDENT>return self.expected_path.search(self.actual_path)<EOL><DEDENT>else:<EOL><INDENT>return normalize_url(self.actual_path) == normalize_url(self.expected_path)<EOL><DEDENT>

Returns whether this query resolves for the given session.

Args:
    session (Session): The session for which this query should be executed.

Returns:
    bool: Whether this query resolves.


self.node = node<EOL>self.actual_text = normalize_text(<EOL>node.visible_text if self.query_type == "<STR_LIT>" else node.all_text)<EOL>self.count = len(re.findall(self.search_regexp, self.actual_text))<EOL>return self.count<EOL>


try:<EOL><INDENT>return self.driver.current_window_handle == self.handle<EOL><DEDENT>except self.driver.no_such_window_error:<EOL><INDENT>return False<EOL><DEDENT>

bool: Whether this window is the window in which commands are being executed.


self.driver.close_window(self.handle)<EOL>

Close window.

If this method was called for the window that is current, then after calling this method
future invocations of other Capybara methods should raise
``session.driver.no_such_window_error`` until another window is switched to.

If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.


if not self.responsive:<EOL><INDENT>type(self)._ports[self.port_key] = self.port<EOL>init_func = capybara.servers[capybara.server_name]<EOL>init_args = (self.middleware, self.port, self.host)<EOL>self.server_thread = Thread(target=init_func, args=init_args)<EOL>self.server_thread.daemon = True<EOL>self.server_thread.start()<EOL>timer = Timer(<NUM_LIT>)<EOL>while not self.responsive:<EOL><INDENT>if timer.expired:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.server_thread.join(<NUM_LIT:0.1>)<EOL><DEDENT><DEDENT>return self<EOL>

Boots a server for the app, if it isn't already booted.

Returns:
    Server: This server.


global current_driver<EOL>current_driver = None<EOL>

Use the default driver as the current driver.


def normalize_strings(value):<EOL><INDENT>if isinstance(value, list):<EOL><INDENT>value = [normalize_strings(e) for e in value]<EOL><DEDENT>if isinstance(value, dict):<EOL><INDENT>value = {normalize_strings(k): normalize_strings(v) for k, v in iter(value.items())}<EOL><DEDENT>if isregex(value):<EOL><INDENT>value = value.pattern<EOL><DEDENT>if isbytes(value):<EOL><INDENT>value = decode_bytes(value)<EOL><DEDENT>if PY2:<EOL><INDENT>if isstring(value):<EOL><INDENT>value = encode_string(value)<EOL><DEDENT><DEDENT>return value<EOL><DEDENT>value = normalize_strings(value)<EOL>return repr(value)<EOL>

str: A normalized representation for a user-provided value.


if any(options.get(key) is not None for key in ["<STR_LIT:count>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]):<EOL><INDENT>return matches_count(<NUM_LIT:0>, options)<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Returns whether the given query options expect a possible count of zero.

Args:
    options (Dict[str, int | Iterable[int]]): A dictionary of query options.

Returns:
    bool: Whether a possible count of zero is expected.


return monotonic() - self._start >= self._expire_in<EOL>


return self.find("<STR_LIT>", "<STR_LIT>").text<EOL>


return "<STR_LIT>" in self.native.attrib<EOL>

bool: Whether or not the element is checked.


bool: Whether or not the element is disabled.


return self._visible()<EOL>

bool: Whether or not the element is visible.


return self.native.text<EOL>


bool: Whether or not the element is selected.


raise NotImplementedError()<EOL>


def has_unchecked_field(self, locator, **kwargs):

kwargs["<STR_LIT>"] = False<EOL>return self.has_selector("<STR_LIT>", locator, **kwargs)<EOL>

Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.

Args:
    locator (str): The label, name, or id of an unchecked field.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Returns:
    bool: Whether it exists.


@predicate<EOL><INDENT>def has_text(self, *args, **kwargs):<DEDENT>

return self.assert_text(*args, **kwargs)<EOL>

Checks if the page or current node has the given text content, ignoring any HTML tags.

Whitespaces are normalized in both the node's text and the passed text parameter. Note that
whitespace isn't normalized in a passed regular expression as normalizing whitespace in a
regular expression isn't easy and doesn't seem to be worth it.

By default it will check if the text occurs at least once, but a different number can be
specified. ::

    page.has_text("lorem ipsum", between=range(2, 5))

Args:
    *args: Variable length argument list for :class:`TextQuery`.
    **kwargs: Arbitrary keyword arguments for :class:`TextQuery`.

Returns:
    bool: Whether it exists.


def assert_matches_selector(self, *args, **kwargs):

query = SelectorQuery(*args, **kwargs)<EOL>@self.synchronize(wait=query.wait)<EOL>def assert_matches_selector():<EOL><INDENT>result = query.resolve_for(self.find_first("<STR_LIT>", "<STR_LIT>", minimum=<NUM_LIT:0>) or self.query_scope)<EOL>if self not in result:<EOL><INDENT>raise ExpectationNotMet("<STR_LIT>")<EOL><DEDENT>return True<EOL><DEDENT>return assert_matches_selector()<EOL>

Asserts that the current node matches a given selector. ::

    node.assert_matches_selector("p#foo")
    node.assert_matches_selector("xpath", "//p[@id='foo']")

It also accepts all options that :meth:`find_all` accepts, such as ``text`` and
``visible``. ::

    node.assert_matches_selector("li", text="Horse", visible=True)

Args:
    *args: Variable length argument list for :class:`SelectorQuery`.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Returns:
    True

Raises:
    ExpectationNotMet: If the selector does not match.


return self.matches_selector("<STR_LIT>", css, **kwargs)<EOL>

Checks if the current node matches the given CSS selector.

Args:
    css (str): The CSS selector to match against the current node.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Return:
    bool: Whether it matches.


return self.has_selector("<STR_LIT>", query, **kwargs)<EOL>

Checks if a given XPath expression is on the page or a descendant of the current node. ::

    session.has_xpath(".//p[@id='foo']")

``has_xpath`` can also accept XPath expressions generated by the ``xpath-py`` package::

    from xpath import dsl as x

    session.has_xpath(x.descendant("p"))

Args:
    query (str): An XPath expression.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Return:
    bool: If the expression exists.


query = TextQuery(*args, **kwargs)<EOL>@self.synchronize(wait=query.wait)<EOL>def assert_text():<EOL><INDENT>count = query.resolve_for(self)<EOL>if not (matches_count(count, query.options) and<EOL>(count > <NUM_LIT:0> or expects_none(query.options))):<EOL><INDENT>raise ExpectationNotMet(query.failure_message)<EOL><DEDENT>return True<EOL><DEDENT>return assert_text()<EOL>

Asserts that the page or current node has the given text content, ignoring any HTML tags.

Args:
    *args: Variable length argument list for :class:`TextQuery`.
    **kwargs: Arbitrary keyword arguments for :class:`TextQuery`.

Returns:
    True

Raises:
    ExpectationNotMet: If the assertion hasn't succeeded during the wait time.


@predicate<EOL><INDENT>def matches_selector(self, *args, **kwargs):<DEDENT>

return self.assert_matches_selector(*args, **kwargs)<EOL>

Checks if the current node matches the given selector.

Args:
    *args: Variable length argument list for :class:`SelectorQuery`.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Returns:
    bool: Whether it matches.


return self._synchronized_resolve(SelectorQuery(*args, **kwargs))<EOL>

Find an :class:`Element` based on the given arguments. ``find`` will raise an error if the
element is not found.

``find`` takes the same options as :meth:`find_all`. ::

    page.find("#foo").find(".bar")
    page.find("xpath", "//div[contains(., 'bar')]")
    page.find("li", text="Quox").click_link("Delete")

Args:
    *args: Variable length argument list for :class:`SelectorQuery`.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

Returns:
    Element: The found element.

Raises:
    Ambiguous: If more than one element matching element is found.
    ElementNotFound: If the element can't be found before time expires.


def check(self, locator=None, allow_label_click=None, **kwargs):

self._check_with_label(<EOL>"<STR_LIT>", True, locator=locator, allow_label_click=allow_label_click, **kwargs)<EOL>

Find a check box and mark it as checked. The check box can be found via name, id, or label
text. ::

    page.check("German")

Args:
    locator (str, optional): Which check box to check.
    allow_label_click (bool, optional): Attempt to click the label to toggle state if
        element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.


def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None,<EOL>**kwargs):

if allow_label_click is None:<EOL><INDENT>allow_label_click = capybara.automatic_label_click<EOL><DEDENT>@self.synchronize(wait=BaseQuery.normalize_wait(wait))<EOL>def check_with_label():<EOL><INDENT>element = None<EOL>try:<EOL><INDENT>element = self.find(selector, locator, visible=visible, **kwargs)<EOL>element.set(checked)<EOL><DEDENT>except Exception as e:<EOL><INDENT>if not allow_label_click or not self._should_catch_error(e):<EOL><INDENT>raise<EOL><DEDENT>try:<EOL><INDENT>if not element:<EOL><INDENT>element = self.find(selector, locator, visible="<STR_LIT:all>", **kwargs)<EOL><DEDENT>label = self.find("<STR_LIT:label>", field=element, visible=True)<EOL>if element.checked != checked:<EOL><INDENT>label.click()<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT><DEDENT>check_with_label()<EOL>

Args:
    selector (str): The selector for the type of element that should be checked/unchecked.
    checked (bool): Whether the element should be checked.
    locator (str, optional): Which element to check.
    allow_label_click (bool, optional): Attempt to click the label to toggle state if
        element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
    visible (bool | str, optional): The desired element visibility. Defaults to
        :data:`capybara.ignore_hidden_elements`.
    wait (int | float, optional): The number of seconds to wait to check the element.
        Defaults to :data:`capybara.default_max_wait_time`.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.


def click_link(self, locator=None, **kwargs):

return self.find("<STR_LIT>", locator, **kwargs).click()<EOL>

Finds a link by id, text, or title and clicks it. Also looks at image alt text inside the
link.

Args:
    locator (str, optional): Text, id, title, or nested image's alt attribute.
    **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.


def has_no_title(self, title, **kwargs):

try:<EOL><INDENT>self.assert_no_title(title, **kwargs)<EOL>return True<EOL><DEDENT>except ExpectationNotMet:<EOL><INDENT>return False<EOL><DEDENT>

Checks if the page doesn't have the given title.

Args:
    title (str | RegexObject): The string that the title should include.
    **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.

Returns:
    bool: Whether it doesn't match.


def assert_title(self, title, **kwargs):

query = TitleQuery(title, **kwargs)<EOL>@self.synchronize(wait=query.wait)<EOL>def assert_title():<EOL><INDENT>if not query.resolves_for(self):<EOL><INDENT>raise ExpectationNotMet(query.failure_message)<EOL><DEDENT>return True<EOL><DEDENT>return assert_title()<EOL>

Asserts that the page has the given title.

Args:
    title (str | RegexObject): The string or regex that the title should match.
    **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.

Returns:
    True

Raises:
    ExpectationNotMet: If the assertion hasn't succeeded during the wait time.


Drag the element to the given other element. ::

    source = page.find("#foo")
    target = page.find("#bar")
    source.drag_to(target)

Args:
    node (Element): The element to drag to.


return self.base.readonly<EOL>

bool: Whether or not the element is readonly.


return self.base.multiple<EOL>

bool: Whether or not the element supports multiple results.


@synchronize<EOL><INDENT>def click(self, *keys, **offset):<DEDENT>

self.base.click(*keys, **offset)<EOL>

Click the element.

Both ``x`` and ``y`` must be specified if an offset is wanted. If not specified, the click
will occur at the middle of the element.

Args:
    keys (List[Keys], optional): Keys to be held down when clicking.
    offset (Dict[str, int], optional): X- and Y-coordinates to offset the click location
        from the toop left corner of the element.


@synchronize<EOL><INDENT>def right_click(self, *keys, **offset):<DEDENT>

self.base.right_click(*keys, **offset)<EOL>

Right-click the element.

Both ``x`` and ``y`` must be specified if an offset is wanted. If not specified, the click
will occur at the middle of the element.

Args:
    keys (List[Keys], optional): Keys to be held down when clicking.
    offset (Dict[str, int], optional): X- and Y-coordinates to offset the click location
        from the toop left corner of the element.


Send keystrokes to the element.

Examples::

    from selenium.webdriver.common.keys import Keys

    element.send_keys("foo")                  # => value: "foo"
    element.send_keys("tet", Keys.LEFT, "s")  # => value: "test"

Args:
    *args: Variable length list of keys to send.


@synchronize<EOL><INDENT>def set(self, value, **options):<DEDENT>

self.base.set(value, **options)<EOL>

Set the value of the form element to the given value.

Args:
    value (bool | str): The new value.
    **options: Driver-specific options for how to set the value.


return self.base.selected<EOL>

bool: Whether or not the element is selected.


Unselect this node if it is an option element inside a multiple select tag.


return self.compare_count == <NUM_LIT:0><EOL>

bool: Whether the result count matches the query options.


if self.query.options["<STR_LIT:count>"] is not None:<EOL><INDENT>count_opt = int(self.query.options["<STR_LIT:count>"])<EOL>self._cache_at_least(count_opt + <NUM_LIT:1>)<EOL>return cmp(len(self._result_cache), count_opt)<EOL><DEDENT>if self.query.options["<STR_LIT>"] is not None:<EOL><INDENT>min_opt = int(self.query.options["<STR_LIT>"])<EOL>if not self._cache_at_least(min_opt):<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT><DEDENT>if self.query.options["<STR_LIT>"] is not None:<EOL><INDENT>max_opt = int(self.query.options["<STR_LIT>"])<EOL>if self._cache_at_least(max_opt + <NUM_LIT:1>):<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT><DEDENT>if self.query.options["<STR_LIT>"] is not None:<EOL><INDENT>between = self.query.options["<STR_LIT>"]<EOL>min_opt, max_opt = between[<NUM_LIT:0>], between[-<NUM_LIT:1>]<EOL>if not self._cache_at_least(min_opt):<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>if self._cache_at_least(max_opt + <NUM_LIT:1>):<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>return <NUM_LIT:0><EOL><DEDENT>return <NUM_LIT:0><EOL>

Returns how the result count compares to the query options.

The return value is negative if too few results were found, zero if enough were found, and
positive if too many were found.

Returns:
    int: -1, 0, or 1.


return hasattr(possible_regex, "<STR_LIT>") and callable(possible_regex.search)<EOL>

Returns whether the given object is (probably) a regular expression object.

Args:
    possible_regex (object): An object which may or may not be a regular expression.

Returns:
    bool: Whether the given object is (probably) a regular expression object.


return value.decode("<STR_LIT:utf-8>") if isbytes(value) else value<EOL>


return self._value<EOL>


def get_browser(browser_name, capabilities=None, **options):

if browser_name == "<STR_LIT>":<EOL><INDENT>return webdriver.Chrome(desired_capabilities=capabilities, **options)<EOL><DEDENT>if browser_name == "<STR_LIT>":<EOL><INDENT>return webdriver.Edge(capabilities=capabilities, **options)<EOL><DEDENT>if browser_name in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>return webdriver.Firefox(capabilities=capabilities, **options)<EOL><DEDENT>if browser_name in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>return webdriver.Ie(capabilities=capabilities, **options)<EOL><DEDENT>if browser_name == "<STR_LIT>":<EOL><INDENT>return webdriver.PhantomJS(desired_capabilities=capabilities, **options)<EOL><DEDENT>if browser_name == "<STR_LIT>":<EOL><INDENT>return webdriver.Remote(desired_capabilities=capabilities, **options)<EOL><DEDENT>if browser_name == "<STR_LIT>":<EOL><INDENT>return webdriver.Safari(desired_capabilities=capabilities, **options)<EOL><DEDENT>raise ValueError("<STR_LIT>".format(repr(browser_name)))<EOL>

Returns an instance of the given browser with the given capabilities.

Args:
    browser_name (str): The name of the desired browser.
    capabilities (Dict[str, str | bool], optional): The desired capabilities of the browser.
        Defaults to None.
    options: Arbitrary keyword arguments for the browser-specific subclass of
        :class:`webdriver.Remote`.

Returns:
    WebDriver: An instance of the desired browser.


self.raise_server_error()<EOL>visit_uri = urlparse(visit_uri)<EOL>if capybara.app_host:<EOL><INDENT>uri_base = urlparse(capybara.app_host)<EOL><DEDENT>elif self.server:<EOL><INDENT>uri_base = urlparse("<STR_LIT>".format(self.server.host, self.server.port))<EOL><DEDENT>else:<EOL><INDENT>uri_base = None<EOL><DEDENT>visit_uri = ParseResult(<EOL>scheme=visit_uri.scheme or (uri_base.scheme if uri_base else "<STR_LIT>"),<EOL>netloc=visit_uri.netloc or (uri_base.netloc if uri_base else "<STR_LIT>"),<EOL>path=visit_uri.path,<EOL>params=visit_uri.params,<EOL>query=visit_uri.query,<EOL>fragment=visit_uri.fragment)<EOL>self.driver.visit(visit_uri.geturl())<EOL>

Navigate to the given URL. The URL can either be a relative URL or an absolute URL. The
behavior of either depends on the driver. ::

    session.visit("/foo")
    session.visit("http://google.com")

For drivers which can run against an external application, such as the Selenium driver,
giving an absolute URL will navigate to that page. This allows testing applications running
on remote servers. For these drivers, setting :data:`capybara.app_host` will make the
remote server the default. For example::

    capybara.app_host = "http://google.com"
    session.visit("/")  # visits the Google homepage

Args:
    visit_uri (str): The URL to navigate to.


@contextmanager<EOL><INDENT>def frame(self, locator=None, *args, **kwargs):<DEDENT>

self.switch_to_frame(self._find_frame(locator, *args, **kwargs))<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>self.switch_to_frame("<STR_LIT>")<EOL><DEDENT>

Execute the wrapped code within the given iframe using the given frame or frame name/id.
May not be supported by all drivers.

Args:
    locator (str | Element, optional): The name/id of the frame or the frame's element.
        Defaults to the only frame in the document.


return self.driver.html<EOL>

str: A snapshot of the DOM of the current document, as it looks right now.


def switch_to_window(self, window, wait=None):

if len(self._scopes) > <NUM_LIT:1>:<EOL><INDENT>raise ScopeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if isinstance(window, Window):<EOL><INDENT>self.driver.switch_to_window(window.handle)<EOL>return window<EOL><DEDENT>else:<EOL><INDENT>@self.document.synchronize(errors=(WindowError,), wait=wait)<EOL>def switch_and_get_matching_window():<EOL><INDENT>original_window_handle = self.driver.current_window_handle<EOL>try:<EOL><INDENT>for handle in self.driver.window_handles:<EOL><INDENT>self.driver.switch_to_window(handle)<EOL>result = window()<EOL>if result:<EOL><INDENT>return Window(self, handle)<EOL><DEDENT><DEDENT><DEDENT>except Exception:<EOL><INDENT>self.driver.switch_to_window(original_window_handle)<EOL>raise<EOL><DEDENT>self.driver.switch_to_window(original_window_handle)<EOL>raise WindowError("<STR_LIT>")<EOL><DEDENT>return switch_and_get_matching_window()<EOL><DEDENT>

If ``window`` is a lambda, it switches to the first window for which ``window`` returns a
value other than False or None. If a window that matches can't be found, the window will be
switched back and :exc:`WindowError` will be raised.

Args:
    window (Window | lambda): The window that should be switched to, or a filtering lambda.
    wait (int | float, optional): The number of seconds to wait to find the window.

Returns:
    Window: The new current window.

Raises:
    ScopeError: If this method is invoked inside :meth:`scope, :meth:`frame`, or
        :meth:`window`.
    WindowError: If no window matches the given lambda.


@contextmanager<EOL><INDENT>def accept_confirm(self, text=None, wait=None):<DEDENT>

with self.driver.accept_modal("<STR_LIT>", text=text, wait=wait):<EOL><INDENT>yield<EOL><DEDENT>

Execute the wrapped code, accepting a confirm.

Args:
    text (str | RegexObject, optional): Text to match against the text in the modal.
    wait (int | float, optional): Maximum time to wait for the modal to appear after
        executing the wrapped code.

Raises:
    ModalNotFound: If a modal dialog hasn't been found.


path = _prepare_path(path, "<STR_LIT:html>")<EOL>with open(path, "<STR_LIT:wb>") as f:<EOL><INDENT>f.write(encode_string(self.body))<EOL><DEDENT>return path<EOL>

Save a snapshot of the page.

If invoked without arguments, it will save a file to :data:`capybara.save_path` and the
file will be given a randomly generated filename. If invoked with a relative path, the path
will be relative to :data:`capybara.save_path`.

Args:
    path (str, optional): The path to where it should be saved.

Returns:
    str: The path to which the file was saved.


with self.scope("<STR_LIT>", locator):<EOL><INDENT>yield<EOL><DEDENT>

Execute the wrapped code within a specific fieldset given the id or legend of that
fieldset.

Args:
    locator (str): The id or legend of the fieldset.


if not self.current_url:<EOL><INDENT>return<EOL><DEDENT>result = urlparse(self.current_url)<EOL>scheme, netloc = result.scheme, result.netloc<EOL>host = netloc.split("<STR_LIT::>")[<NUM_LIT:0>] if netloc else None<EOL>return "<STR_LIT>".format(scheme, host) if host else None<EOL>


@contextmanager<EOL><INDENT>def dismiss_prompt(self, text=None, wait=None):<DEDENT>

with self.driver.dismiss_modal("<STR_LIT>", text=text, wait=wait):<EOL><INDENT>yield<EOL><DEDENT>

Execute the wrapped code, dismissing a prompt.

Args:
    text (str | RegexObject, optional): Text to match against the text in the modal.
    wait (int | float, optional): Maximum time to wait for the modal to appear after
        executing the wrapped code.

Raises:
    ModalNotFound: If a modal dialog hasn't been found.