How to use run_object method in Contexts

Best Python code snippet using Contexts

Run Contexts automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

45_word_doc.py

Source: 45_word_doc.py Github

copy
1#! usr/bin/env python3
2
3"""
4Working with word (.docx) documents
5"""
6
7# install the `python-docx` module
8# download the demo file from `http://autbor.com/demo.docx`
9
10# import the `docx` module
11import docx
12
13# create the `document object` with the demo document in `other` folder
14doc_object = docx.Document('other/demo.docx')
15
16# doc_object has paragraph member which contains the paragraph objects
17print(doc_object.paragraphs)
18par_object = doc_object.paragraphs
19
20# each paragraphs object has text member objects containing the strings.
21for text_object in par_object:
22    print(text_object.text)
23
24
25# each par_object has run member which contains the run `string` members.
26# `run` is when the format of the text in par_obj changes
27    run_object = text_object.runs
28    for i in range(len(run_object)):
29        print(run_object[i].text)
30
31# each run member has attribute variable (italic, bold, underline) which are
32# either set to True or False.
33        if run_object[i].bold:
34            print("This ^ is bold text.")
35            # changing the above to bold +italic + underline
36            run_object[i].italic = True
37            run_object[i].underline = True
38            run_object[i].text = 'bold + italic + underlined'
39
40# save the document
41doc_object.save('other/demo.docx')
42
Full Screen

experiment.py

Source: experiment.py Github

copy
1from __future__ import absolute_import
2from __future__ import division
3from __future__ import print_function
4
5import copy
6import logging
7import six
8import types
9
10from ray.tune.result import DEFAULT_RESULTS_DIR
11from ray.tune.error import TuneError
12from ray.tune.registry import register_trainable
13
14logger = logging.getLogger(__name__)
15
16
17class Experiment(object):
18    """Tracks experiment specifications.
19
20    Parameters:
21        name (str): Name of experiment.
22        run (function|class|str): The algorithm or model to train.
23            This may refer to the name of a built-on algorithm
24            (e.g. RLLib's DQN or PPO), a user-defined trainable
25            function or class, or the string identifier of a
26            trainable function or class registered in the tune registry.
27        stop (dict): The stopping criteria. The keys may be any field in
28            the return result of 'train()', whichever is reached first.
29            Defaults to empty dict.
30        config (dict): Algorithm-specific configuration for Tune variant
31            generation (e.g. env, hyperparams). Defaults to empty dict.
32            Custom search algorithms may ignore this.
33        trial_resources (dict): Machine resources to allocate per trial,
34            e.g. ``{"cpu": 64, "gpu": 8}``. Note that GPUs will not be
35            assigned unless you specify them here. Defaults to 1 CPU and 0
36            GPUs in ``Trainable.default_resource_request()``.
37        repeat (int): Deprecated and will be removed in future versions of
38            Ray. Use `num_samples` instead.
39        num_samples (int): Number of times to sample from the
40            hyperparameter space. Defaults to 1. If `grid_search` is
41            provided as an argument, the grid will be repeated
42            `num_samples` of times.
43        local_dir (str): Local dir to save training results to.
44            Defaults to ``~/ray_results``.
45        upload_dir (str): Optional URI to sync training results
46            to (e.g. ``s3://bucket``).
47        checkpoint_freq (int): How many training iterations between
48            checkpoints. A value of 0 (default) disables checkpointing.
49        checkpoint_at_end (bool): Whether to checkpoint at the end of the
50            experiment regardless of the checkpoint_freq. Default is False.
51        max_failures (int): Try to recover a trial from its last
52            checkpoint at least this many times. Only applies if
53            checkpointing is enabled. Defaults to 3.
54        restore (str): Path to checkpoint. Only makes sense to set if
55            running 1 trial. Defaults to None.
56
57
58    Examples:
59        >>> experiment_spec = Experiment(
60        >>>     "my_experiment_name",
61        >>>     my_func,
62        >>>     stop={"mean_accuracy": 100},
63        >>>     config={
64        >>>         "alpha": tune.grid_search([0.2, 0.4, 0.6]),
65        >>>         "beta": tune.grid_search([1, 2]),
66        >>>     },
67        >>>     trial_resources={
68        >>>         "cpu": 1,
69        >>>         "gpu": 0
70        >>>     },
71        >>>     num_samples=10,
72        >>>     local_dir="~/ray_results",
73        >>>     upload_dir="s3://your_bucket/path",
74        >>>     checkpoint_freq=10,
75        >>>     max_failures=2)
76
77    """
78
79    def __init__(self,
80                 name,
81                 run,
82                 stop=None,
83                 config=None,
84                 trial_resources=None,
85                 repeat=1,
86                 num_samples=1,
87                 local_dir=None,
88                 upload_dir="",
89                 checkpoint_freq=0,
90                 checkpoint_at_end=False,
91                 max_failures=3,
92                 restore=None):
93        spec = {
94            "run": self._register_if_needed(run),
95            "stop": stop or {},
96            "config": config or {},
97            "trial_resources": trial_resources,
98            "num_samples": num_samples,
99            "local_dir": local_dir or DEFAULT_RESULTS_DIR,
100            "upload_dir": upload_dir,
101            "checkpoint_freq": checkpoint_freq,
102            "checkpoint_at_end": checkpoint_at_end,
103            "max_failures": max_failures,
104            "restore": restore
105        }
106
107        self.name = name
108        self.spec = spec
109
110    @classmethod
111    def from_json(cls, name, spec):
112        """Generates an Experiment object from JSON.
113
114        Args:
115            name (str): Name of Experiment.
116            spec (dict): JSON configuration of experiment.
117        """
118        if "run" not in spec:
119            raise TuneError("No trainable specified!")
120
121        if "repeat" in spec:
122            raise DeprecationWarning("The parameter `repeat` is deprecated; \
123                converting to `num_samples`. `repeat` will be removed in \
124                future versions of Ray.")
125            spec["num_samples"] = spec["repeat"]
126            del spec["repeat"]
127
128        # Special case the `env` param for RLlib by automatically
129        # moving it into the `config` section.
130        if "env" in spec:
131            spec["config"] = spec.get("config", {})
132            spec["config"]["env"] = spec["env"]
133            del spec["env"]
134
135        spec = copy.deepcopy(spec)
136
137        run_value = spec.pop("run")
138        try:
139            exp = cls(name, run_value, **spec)
140        except TypeError:
141            raise TuneError("Improper argument from JSON: {}.".format(spec))
142        return exp
143
144    def _register_if_needed(self, run_object):
145        """Registers Trainable or Function at runtime.
146
147        Assumes already registered if run_object is a string. Does not
148        register lambdas because they could be part of variant generation.
149        Also, does not inspect interface of given run_object.
150
151        Arguments:
152            run_object (str|function|class): Trainable to run. If string,
153                assumes it is an ID and does not modify it. Otherwise,
154                returns a string corresponding to the run_object name.
155
156        Returns:
157            A string representing the trainable identifier.
158        """
159
160        if isinstance(run_object, six.string_types):
161            return run_object
162        elif isinstance(run_object, types.FunctionType):
163            if run_object.__name__ == "<lambda>":
164                logger.warning(
165                    "Not auto-registering lambdas - resolving as variant.")
166                return run_object
167            else:
168                name = run_object.__name__
169                register_trainable(name, run_object)
170                return name
171        elif isinstance(run_object, type):
172            name = run_object.__name__
173            register_trainable(name, run_object)
174            return name
175        else:
176            raise TuneError("Improper 'run' - not string nor trainable.")
177
178
179def convert_to_experiment_list(experiments):
180    """Produces a list of Experiment objects.
181
182    Converts input from dict, single experiment, or list of
183    experiments to list of experiments. If input is None,
184    will return an empty list.
185
186    Arguments:
187        experiments (Experiment | list | dict): Experiments to run.
188
189    Returns:
190        List of experiments.
191    """
192    exp_list = experiments
193
194    # Transform list if necessary
195    if experiments is None:
196        exp_list = []
197    elif isinstance(experiments, Experiment):
198        exp_list = [experiments]
199    elif type(experiments) is dict:
200        exp_list = [
201            Experiment.from_json(name, spec)
202            for name, spec in experiments.items()
203        ]
204
205    # Validate exp_list
206    if (type(exp_list) is list
207            and all(isinstance(exp, Experiment) for exp in exp_list)):
208        if len(exp_list) > 1:
209            logger.warning("All experiments will be "
210                           "using the same SearchAlgorithm.")
211    else:
212        raise TuneError("Invalid argument: {}".format(experiments))
213
214    return exp_list
215
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Contexts on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)