def parse(self, words, S='<STR_LIT:S>'):

self.chart = [[] for i in range(len(words)+<NUM_LIT:1>)]<EOL>self.add_edge([<NUM_LIT:0>, <NUM_LIT:0>, '<STR_LIT>', [], [S]])<EOL>for i in range(len(words)):<EOL><INDENT>self.scanner(i, words[i])<EOL><DEDENT>return self.chart<EOL>

Parse a list of words; according to the grammar.
        Leave results in the chart.


start, end, lhs, found, expects = edge<EOL>if edge not in self.chart[end]:<EOL><INDENT>self.chart[end].append(edge)<EOL>if self.trace:<EOL><INDENT>print('<STR_LIT>' % (caller(<NUM_LIT:2>), edge))<EOL><DEDENT>if not expects:<EOL><INDENT>self.extender(edge)<EOL><DEDENT>else:<EOL><INDENT>self.predictor(edge)<EOL><DEDENT><DEDENT>

Add edge to chart, and see if it extends or predicts another edge.


for (i, j, A, alpha, Bb) in self.chart[j]:<EOL><INDENT>if Bb and self.grammar.isa(word, Bb[<NUM_LIT:0>]):<EOL><INDENT>self.add_edge([i, j+<NUM_LIT:1>, A, alpha + [(Bb[<NUM_LIT:0>], word)], Bb[<NUM_LIT:1>:]])<EOL><DEDENT><DEDENT>

For each edge expecting a word of this category here, extend the edge.


(i, j, A, alpha, Bb) = xxx_todo_changeme<EOL>B = Bb[<NUM_LIT:0>]<EOL>if B in self.grammar.rules:<EOL><INDENT>for rhs in self.grammar.rewrites_for(B):<EOL><INDENT>self.add_edge([j, j, B, [], rhs])<EOL><DEDENT><DEDENT>

Add to chart any rules for B that could help extend this edge.


(j, k, B, _, _) = edge<EOL>for (i, j, A, alpha, B1b) in self.chart[j]:<EOL><INDENT>if B1b and B == B1b[<NUM_LIT:0>]:<EOL><INDENT>self.add_edge([i, k, A, alpha + [edge], B1b[<NUM_LIT:1>:]])<EOL><DEDENT><DEDENT>

See what edges can be extended by this edge.


player = game.to_move(state)<EOL>def max_value(state):<EOL><INDENT>if game.terminal_test(state):<EOL><INDENT>return game.utility(state, player)<EOL><DEDENT>v = -infinity<EOL>for a in game.actions(state):<EOL><INDENT>v = max(v, min_value(game.result(state, a)))<EOL><DEDENT>return v<EOL><DEDENT>def min_value(state):<EOL><INDENT>if game.terminal_test(state):<EOL><INDENT>return game.utility(state, player)<EOL><DEDENT>v = infinity<EOL>for a in game.actions(state):<EOL><INDENT>v = min(v, max_value(game.result(state, a)))<EOL><DEDENT>return v<EOL><DEDENT>return argmax(game.actions(state),<EOL>lambda a: min_value(game.result(state, a)))<EOL>

Given a state in a game, calculate the best move by searching
    forward all the way to the terminal states. [Fig. 5.3]


player = game.to_move(state)<EOL>def max_value(state, alpha, beta):<EOL><INDENT>if game.terminal_test(state):<EOL><INDENT>return game.utility(state, player)<EOL><DEDENT>v = -infinity<EOL>for a in game.actions(state):<EOL><INDENT>v = max(v, min_value(game.result(state, a), alpha, beta))<EOL>if v >= beta:<EOL><INDENT>return v<EOL><DEDENT>alpha = max(alpha, v)<EOL><DEDENT>return v<EOL><DEDENT>def min_value(state, alpha, beta):<EOL><INDENT>if game.terminal_test(state):<EOL><INDENT>return game.utility(state, player)<EOL><DEDENT>v = infinity<EOL>for a in game.actions(state):<EOL><INDENT>v = min(v, max_value(game.result(state, a), alpha, beta))<EOL>if v <= alpha:<EOL><INDENT>return v<EOL><DEDENT>beta = min(beta, v)<EOL><DEDENT>return v<EOL><DEDENT>return argmax(game.actions(state),<EOL>lambda a: min_value(game.result(state, a),<EOL>-infinity, infinity))<EOL>

Search game to determine best action; use alpha-beta pruning.
    As in [Fig. 5.7], this version searches all the way to the leaves.


game.display(state)<EOL>return num_or_str(input('<STR_LIT>'))<EOL>


return random.choice(game.actions(state))<EOL>

A player that chooses a legal move at random.


state = game.initial<EOL>while True:<EOL><INDENT>for player in players:<EOL><INDENT>move = player(game, state)<EOL>state = game.result(state, move)<EOL>if game.terminal_test(state):<EOL><INDENT>return game.utility(state, game.to_move(game.initial))<EOL><DEDENT><DEDENT><DEDENT>

Play an n-person, move-alternating game.
    >>> play_game(Fig52Game(), alphabeta_player, alphabeta_player)
    3


abstract<EOL>

Return a list of the allowable moves at this point.


abstract<EOL>

Return the state that results from making a move from a state.


abstract<EOL>

Return the value of this final state to player.


return state.to_move<EOL>

Return the player whose move it is in this state.


print(state)<EOL>


return state.moves<EOL>

Legal moves are any square not yet taken.


return if_(player == '<STR_LIT:X>', state.utility, -state.utility)<EOL>

Return the value to player; 1 for win, -1 for loss, 0 otherwise.


def compute_utility(self, board, move, player):

if (self.k_in_row(board, move, player, (<NUM_LIT:0>, <NUM_LIT:1>)) or<EOL>self.k_in_row(board, move, player, (<NUM_LIT:1>, <NUM_LIT:0>)) or<EOL>self.k_in_row(board, move, player, (<NUM_LIT:1>, -<NUM_LIT:1>)) or<EOL>self.k_in_row(board, move, player, (<NUM_LIT:1>, <NUM_LIT:1>))):<EOL><INDENT>return if_(player == '<STR_LIT:X>', +<NUM_LIT:1>, -<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

If X wins with this move, return 1; if O return -1; else return 0.


def k_in_row(self, board, move, player, xxx_todo_changeme):

(delta_x, delta_y) = xxx_todo_changeme<EOL>x, y = move<EOL>n = <NUM_LIT:0> <EOL>while board.get((x, y)) == player:<EOL><INDENT>n += <NUM_LIT:1><EOL>x, y = x + delta_x, y + delta_y<EOL><DEDENT>x, y = move<EOL>while board.get((x, y)) == player:<EOL><INDENT>n += <NUM_LIT:1><EOL>x, y = x - delta_x, y - delta_y<EOL><DEDENT>n -= <NUM_LIT:1> <EOL>return n >= self.k<EOL>

Return true if there is a line through move on board for player.


def program(percept):<EOL><INDENT>belief_state.observe(program.action, percept)<EOL>program.action = argmax(belief_state.actions(),<EOL>belief_state.expected_outcome_utility)<EOL>return program.action<EOL><DEDENT>program.action = None<EOL>return program<EOL>


if isinstance(event, tuple) and len(event) == len(vars):<EOL><INDENT>return event<EOL><DEDENT>else:<EOL><INDENT>return tuple([event[var] for var in vars])<EOL><DEDENT>

Return a tuple of the values of variables vars in event.
    >>> event_values ({'A': 10, 'B': 9, 'C': 8}, ['C', 'A'])
    (8, 10)
    >>> event_values ((1, 2), ['C', 'A'])
    (1, 2)


assert X not in e, "<STR_LIT>"<EOL>Q = ProbDist(X) <EOL>Y = [v for v in P.variables if v != X and v not in e] <EOL>for xi in P.values(X):<EOL><INDENT>Q[xi] = enumerate_joint(Y, extend(e, X, xi), P)<EOL><DEDENT>return Q.normalize()<EOL>

Return a probability distribution over the values of the variable X,
    given the {var:val} observations e, in the JointProbDist P. [Section 13.3]
    >>> P = JointProbDist(['X', 'Y'])
    >>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125
    >>> enumerate_joint_ask('X', dict(Y=1), P).show_approx()
    '0: 0.667, 1: 0.167, 2: 0.167'


if not vars:<EOL><INDENT>return P[e]<EOL><DEDENT>Y, rest = vars[<NUM_LIT:0>], vars[<NUM_LIT:1>:]<EOL>return sum([enumerate_joint(rest, extend(e, Y, y), P)<EOL>for y in P.values(Y)])<EOL>

Return the sum of those entries in P consistent with e,
    provided vars is P's remaining variables (the ones not in e).


assert X not in e, "<STR_LIT>"<EOL>Q = ProbDist(X)<EOL>for xi in bn.variable_values(X):<EOL><INDENT>Q[xi] = enumerate_all(bn.vars, extend(e, X, xi), bn)<EOL><DEDENT>return Q.normalize()<EOL>

Return the conditional probability distribution of variable X
    given evidence e, from BayesNet bn. [Fig. 14.9]
    >>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
    ...  ).show_approx()
    'False: 0.716, True: 0.284


if not vars:<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>Y, rest = vars[<NUM_LIT:0>], vars[<NUM_LIT:1>:]<EOL>Ynode = bn.variable_node(Y)<EOL>if Y in e:<EOL><INDENT>return Ynode.p(e[Y], e) * enumerate_all(rest, e, bn)<EOL><DEDENT>else:<EOL><INDENT>return sum(Ynode.p(y, e) * enumerate_all(rest, extend(e, Y, y), bn)<EOL>for y in bn.variable_values(Y))<EOL><DEDENT>

Return the sum of those entries in P(vars | e{others})
    consistent with e, where P is the joint distribution represented
    by bn, and e{others} means e restricted to bn's other variables
    (the ones other than vars). Parents must precede children in vars.


assert X not in e, "<STR_LIT>"<EOL>factors = []<EOL>for var in reversed(bn.vars):<EOL><INDENT>factors.append(make_factor(var, e, bn))<EOL>if is_hidden(var, X, e):<EOL><INDENT>factors = sum_out(var, factors, bn)<EOL><DEDENT><DEDENT>return pointwise_product(factors, bn).normalize()<EOL>

Compute bn's P(X|e) by variable elimination. [Fig. 14.11]
    >>> elimination_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
    ...  ).show_approx()
    'False: 0.716, True: 0.284


return var != X and var not in e<EOL>

Is var a hidden variable when querying P(X|e)?


node = bn.variable_node(var)<EOL>vars = [X for X in [var] + node.parents if X not in e]<EOL>cpt = dict((event_values(e1, vars), node.p(e1[var], e1))<EOL>for e1 in all_events(vars, bn, e))<EOL>return Factor(vars, cpt)<EOL>

Return the factor for var in bn's joint distribution given e.
    That is, bn's full joint distribution, projected to accord with e,
    is the pointwise product of these factors for bn's variables.


result, var_factors = [], []<EOL>for f in factors:<EOL><INDENT>(var_factors if var in f.vars else result).append(f)<EOL><DEDENT>result.append(pointwise_product(var_factors, bn).sum_out(var, bn))<EOL>return result<EOL>

Eliminate var from all factors by summing over its values.


if not vars:<EOL><INDENT>yield e<EOL><DEDENT>else:<EOL><INDENT>X, rest = vars[<NUM_LIT:0>], vars[<NUM_LIT:1>:]<EOL>for e1 in all_events(rest, bn, e):<EOL><INDENT>for x in bn.variable_values(X):<EOL><INDENT>yield extend(e1, X, x)<EOL><DEDENT><DEDENT><DEDENT>

Yield every way of extending e with values for all vars.


event = {}<EOL>for node in bn.nodes:<EOL><INDENT>event[node.variable] = node.sample(event)<EOL><DEDENT>return event<EOL>

Randomly sample from bn's full joint distribution. The result
    is a {variable: value} dict. [Fig. 14.13]


counts = dict((x, <NUM_LIT:0>) for x in bn.variable_values(X)) <EOL>for j in range(N):<EOL><INDENT>sample = prior_sample(bn) <EOL>if consistent_with(sample, e):<EOL><INDENT>counts[sample[X]] += <NUM_LIT:1><EOL><DEDENT><DEDENT>return ProbDist(X, counts)<EOL>

Estimate the probability distribution of variable X given
    evidence e in BayesNet bn, using N samples.  [Fig. 14.14]
    Raises a ZeroDivisionError if all the N samples are rejected,
    i.e., inconsistent with e.
    >>> seed(47)
    >>> rejection_sampling('Burglary', dict(JohnCalls=T, MaryCalls=T),
    ...   burglary, 10000).show_approx()
    'False: 0.7, True: 0.3'


return every(lambda k_v: evidence.get(k_v[<NUM_LIT:0>], k_v[<NUM_LIT:1>]) == k_v[<NUM_LIT:1>],<EOL>list(event.items()))<EOL>

Is event consistent with the given evidence?


W = dict((x, <NUM_LIT:0>) for x in bn.variable_values(X))<EOL>for j in range(N):<EOL><INDENT>sample, weight = weighted_sample(bn, e) <EOL>W[sample[X]] += weight<EOL><DEDENT>return ProbDist(X, W)<EOL>

Estimate the probability distribution of variable X given
    evidence e in BayesNet bn.  [Fig. 14.15]
    >>> seed(1017)
    >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T),
    ...   burglary, 10000).show_approx()
    'False: 0.702, True: 0.298'


w = <NUM_LIT:1><EOL>event = dict(e) <EOL>for node in bn.nodes:<EOL><INDENT>Xi = node.variable<EOL>if Xi in e:<EOL><INDENT>w *= node.p(e[Xi], event)<EOL><DEDENT>else:<EOL><INDENT>event[Xi] = node.sample(event)<EOL><DEDENT><DEDENT>return event, w<EOL>

Sample an event from bn that's consistent with the evidence e;
    return the event and its weight, the likelihood that the event
    accords to the evidence.


assert X not in e, "<STR_LIT>"<EOL>counts = dict((x, <NUM_LIT:0>) for x in bn.variable_values(X)) <EOL>Z = [var for var in bn.vars if var not in e]<EOL>state = dict(e) <EOL>for Zi in Z:<EOL><INDENT>state[Zi] = choice(bn.variable_values(Zi))<EOL><DEDENT>for j in range(N):<EOL><INDENT>for Zi in Z:<EOL><INDENT>state[Zi] = markov_blanket_sample(Zi, state, bn)<EOL>counts[state[X]] += <NUM_LIT:1><EOL><DEDENT><DEDENT>return ProbDist(X, counts)<EOL>

[Fig. 14.16]
    >>> seed(1017)
    >>> gibbs_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary, 1000
    ...  ).show_approx()
    'False: 0.738, True: 0.262'


Xnode = bn.variable_node(X)<EOL>Q = ProbDist(X)<EOL>for xi in bn.variable_values(X):<EOL><INDENT>ei = extend(e, X, xi)<EOL>Q[xi] = Xnode.p(xi, e) * product(Yj.p(ei[Yj.variable], ei)<EOL>for Yj in Xnode.children)<EOL><DEDENT>return probability(Q.normalize()[True])<EOL>

Return a sample from P(X | mb) where mb denotes that the
    variables in the Markov blanket of X take their values from event
    e (which must assign a value to each). The Markov blanket of X is
    X's parents, children, and children's parents.


unimplemented()<EOL>


def __init__(self, varname='<STR_LIT:?>', freqs=None):

update(self, prob={}, varname=varname, values=[])<EOL>if freqs:<EOL><INDENT>for (v, p) in list(freqs.items()):<EOL><INDENT>self[v] = p<EOL><DEDENT>self.normalize()<EOL><DEDENT>

If freqs is given, it is a dictionary of value: frequency pairs,
        and the ProbDist then is normalized.


try: return self.prob[val]<EOL>except KeyError: return <NUM_LIT:0><EOL>


if val not in self.values:<EOL><INDENT>self.values.append(val)<EOL><DEDENT>self.prob[val] = p<EOL>


total = float(sum(self.prob.values()))<EOL>if not (<NUM_LIT:1.0>-epsilon < total < <NUM_LIT:1.0>+epsilon):<EOL><INDENT>for val in self.prob:<EOL><INDENT>self.prob[val] /= total<EOL><DEDENT><DEDENT>return self<EOL>

Make sure the probabilities of all values sum to 1.
        Returns the normalized distribution.
        Raises a ZeroDivisionError if the sum of the values is 0.
        >>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
        >>> P = P.normalize()
        >>> print '%5.3f %5.3f' % (P.prob['H'], P.prob['T'])
        0.350 0.650


return '<STR_LIT:U+002CU+0020>'.join([('<STR_LIT>' + numfmt) % (v, p)<EOL>for (v, p) in sorted(self.prob.items())])<EOL>

Show the probabilities rounded and sorted by key, for the
        sake of portable doctests.


values = event_values(values, self.variables)<EOL>return ProbDist.__getitem__(self, values)<EOL>

Given a tuple or dict of values, return P(values).


values = event_values(values, self.variables)<EOL>self.prob[values] = p<EOL>for var, val in zip(self.variables, values):<EOL><INDENT>if val not in self.vals[var]:<EOL><INDENT>self.vals[var].append(val)<EOL><DEDENT><DEDENT>

Set P(values) = p.  Values can be a tuple or a dict; it must
        have a value for each of the variables in the joint. Also keep track
        of the values we have seen so far for each variable.


return self.vals[var]<EOL>

Return the set of possible values for a variable.


update(self, nodes=[], vars=[])<EOL>for node_spec in node_specs:<EOL><INDENT>self.add(node_spec)<EOL><DEDENT>

nodes must be ordered with parents before children.


node = BayesNode(*node_spec)<EOL>assert node.variable not in self.vars<EOL>assert every(lambda parent: parent in self.vars, node.parents)<EOL>self.nodes.append(node)<EOL>self.vars.append(node.variable)<EOL>for parent in node.parents:<EOL><INDENT>self.variable_node(parent).children.append(node)<EOL><DEDENT>

Add a node to the net. Its parents must already be in the
        net, and its variable must not.


for n in self.nodes:<EOL><INDENT>if n.variable == var:<EOL><INDENT>return n<EOL><DEDENT><DEDENT>raise Exception("<STR_LIT>" % var)<EOL>

Return the node for the variable named var.
        >>> burglary.variable_node('Burglary').variable
        'Burglary


return [True, False]<EOL>


if isinstance(parents, str): parents = parents.split()<EOL>if isinstance(cpt, (float, int)): <EOL><INDENT>cpt = {(): cpt}<EOL><DEDENT>elif isinstance(cpt, dict):<EOL><INDENT>if cpt and isinstance(list(cpt.keys())[<NUM_LIT:0>], bool): <EOL><INDENT>cpt = dict(((v,), p) for v, p in list(cpt.items()))<EOL><DEDENT><DEDENT>assert isinstance(cpt, dict)<EOL>for vs, p in list(cpt.items()):<EOL><INDENT>assert isinstance(vs, tuple) and len(vs) == len(parents)<EOL>assert every(lambda v: isinstance(v, bool), vs)<EOL>assert <NUM_LIT:0> <= p <= <NUM_LIT:1><EOL><DEDENT>update(self, variable=X, parents=parents, cpt=cpt, children=[])<EOL>

X is a variable name, and parents a sequence of variable
        names or a space-separated string.  cpt, the conditional
        probability table, takes one of these forms:

        * A number, the unconditional probability P(X=true). You can
          use this form when there are no parents.

        * A dict {v: p, ...}, the conditional probability distribution
          P(X=true | parent=v) = p. When there's just one parent.

        * A dict {(v1, v2, ...): p, ...}, the distribution P(X=true |
          parent1=v1, parent2=v2, ...) = p. Each key must have as many
          values as there are parents. You can use this form always;
          the first two are just conveniences.

        In all cases the probability of X being false is left implicit,
        since it follows from P(X=true).

        >>> X = BayesNode('X', '', 0.2)
        >>> Y = BayesNode('Y', 'P', {T: 0.2, F: 0.7})
        >>> Z = BayesNode('Z', 'P Q',
        ...    {(T, T): 0.2, (T, F): 0.3, (F, T): 0.5, (F, F): 0.7})


assert isinstance(value, bool)<EOL>ptrue = self.cpt[event_values(event, self.parents)]<EOL>return if_(value, ptrue, <NUM_LIT:1> - ptrue)<EOL>

Return the conditional probability
        P(X=value | parents=parent_values), where parent_values
        are the values of parents in event. (event must assign each
        parent a value.)
        >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})
        >>> bn.p(False, {'Burglary': False, 'Earthquake': True})
        0.375


return probability(self.p(True, event))<EOL>

Sample from the distribution for this variable conditioned
        on event's values for parent_vars. That is, return True/False
        at random according with the conditional probability given the
        parents.


vars = list(set(self.vars) | set(other.vars))<EOL>cpt = dict((event_values(e, vars), self.p(e) * other.p(e))<EOL>for e in all_events(vars, bn, {}))<EOL>return Factor(vars, cpt)<EOL>

Multiply two factors, combining their variables.


vars = [X for X in self.vars if X != var]<EOL>cpt = dict((event_values(e, vars),<EOL>sum(self.p(extend(e, var, val))<EOL>for val in bn.variable_values(var)))<EOL>for e in all_events(vars, bn, {}))<EOL>return Factor(vars, cpt)<EOL>

Make a factor eliminating var by summing over its values.


assert len(self.vars) == <NUM_LIT:1><EOL>return ProbDist(self.vars[<NUM_LIT:0>],<EOL>dict((k, v) for ((k,), v) in list(self.cpt.items())))<EOL>

Return my probabilities; must be down to one variable.


return self.cpt[event_values(e, self.vars)]<EOL>


def assert_amnesty(self, input_code, errors, expected):

input_code = textwrap.dedent(input_code)<EOL>expected = textwrap.dedent(expected)<EOL>errors_by_line = defaultdict(list)<EOL>for error in errors:<EOL><INDENT>errors_by_line[error.linenum].append(error)<EOL><DEDENT>output_lines = itertools.chain.from_iterable(<EOL>fix_pylint(line, errors_by_line[lineno])<EOL>for lineno, line<EOL>in enumerate(StringIO(input_code), start=<NUM_LIT:1>)<EOL>)<EOL>self.assertEqual(expected.split(u'<STR_LIT:\n>'), "<STR_LIT>".join(output_lines).split(u'<STR_LIT:\n>'))<EOL>

Assert that fix_pylint produces ``expected`` when fed ``input_code`` and the
list of errors ``errors``.

Arguments:
    input_code: A string of python code. Will be textwrap.dedented.
    errors: A list of PylintErrors
    expected: A string of python code. Will be textwrap.dedented.


def assert_pylint_exception_match(self, expected, line):

self.assertEqual(<EOL>expected,<EOL>PYLINT_EXCEPTION_REGEX.search(line).group(<NUM_LIT:0>)<EOL>)<EOL>

Assert that PYLINT_EXCEPTION_REGEX mateches ``expected`` in ``line``.


markers = {}<EOL>for lineno, line in enumerate(source.splitlines(), start=<NUM_LIT:1>):<EOL><INDENT>m = re.search(r"<STR_LIT>", line)<EOL>if m:<EOL><INDENT>markers[lineno] = m.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>return markers<EOL>

Find line markers in program source.

    Returns a dict mapping line numbers to the marker on that line.


with open("<STR_LIT>", "<STR_LIT:w>") as f:<EOL><INDENT>f.write(textwrap.dedent(source))<EOL><DEDENT>reporter = SimpleReporter()<EOL>pylint_args = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>".format(msg_ids)]<EOL>if pylint_numversion >= (<NUM_LIT:2>, <NUM_LIT:0>):<EOL><INDENT>kwargs = dict(do_exit=False)<EOL><DEDENT>else:<EOL><INDENT>kwargs = dict(exit=False)<EOL><DEDENT>Run(pylint_args, reporter=reporter, **kwargs)       <EOL>markers = find_line_markers(source)<EOL>messages = {<EOL>"<STR_LIT>".format(m=m, line=markers.get(m.line, m.line))<EOL>for m in reporter.messages<EOL>}<EOL>return messages<EOL>

Run pylint on some source, collecting specific messages.

    `source` is the literal text of the program to check. It is
    dedented and written to a temp file for pylint to read.

    `msg_ids` is a comma-separated string of msgids we are interested
    in.  Use "all" to enable all messages.

    Returns a set of messages.  Each message is a string, formatted
    as "line:msg-id:message".  "line" will be the line number of the
    message, or if the source line has a comment like "#=Slug", then
    it will be "Slug" instead.  This makes it easier to write, read,
    and maintain the tests.


fdesc, filename = tempfile.mkstemp(suffix="<STR_LIT>", prefix="<STR_LIT>")<EOL>os.close(fdesc)<EOL>self.addCleanup(os.remove, filename)<EOL>return filename<EOL>

Make a temporary filename that will be deleted after the test.

Returns:
    The name of the temp file.


def write_tamper_evident(self, text, **kwargs):

filename = self.temp_filename()<EOL>TamperEvidentFile(filename).write(text, **kwargs)<EOL>return filename<EOL>

Helper to write a tamper-evident temp file.

Args:
    text (byte string): the content of the file.

    kwargs: any other arguments to `TamperEvidentFile.write`.

Returns:
    The name of the temp file.


return main.main(argv)<EOL>

Call an edx_lint script command.

        Arguments:
            argv (list) -- arguments to pass to the edx_lint script


def assert_file(self, filename, contains=None, not_contains=None):

self.assertTrue(os.path.isfile(filename))<EOL>if contains is not None or not_contains is not None:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>text = f.read()<EOL>if contains is not None:                    <EOL><INDENT>self.assertIn(contains, text)<EOL><DEDENT>if not_contains is not None:                <EOL><INDENT>self.assertNotIn(not_contains, text)<EOL><DEDENT><DEDENT><DEDENT>

Assert that a file exists, and optionally, contains some text.


self.assertFalse(os.path.isfile(filename))<EOL>


for section in tweaks.sections():<EOL><INDENT>for option in tweaks.options(section):<EOL><INDENT>value = tweaks.get(section, option)<EOL>if option.endswith("<STR_LIT:+>"):<EOL><INDENT>option = option[:-<NUM_LIT:1>]<EOL>value = main.get(section, option) + value<EOL><DEDENT>main.set(section, option, value)<EOL><DEDENT><DEDENT>


print("<STR_LIT>")<EOL>for filename in pkg_resources.resource_listdir("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>print(filename)<EOL><DEDENT>return <NUM_LIT:0><EOL>

list
    List the FILENAMEs that edx_lint can provide.


for line in pylint_output:<EOL><INDENT>if not line.strip():<EOL><INDENT>continue<EOL><DEDENT>if line[<NUM_LIT:0>:<NUM_LIT:5>] in ("<STR_LIT:->"*<NUM_LIT:5>, "<STR_LIT:*>"*<NUM_LIT:5>):<EOL><INDENT>continue<EOL><DEDENT>parsed = PYLINT_PARSEABLE_REGEX.search(line)<EOL>if parsed is None:<EOL><INDENT>LOG.warning(<EOL>u"<STR_LIT>"<EOL>u"<STR_LIT>",<EOL>line<EOL>)<EOL>continue<EOL><DEDENT>parsed_dict = parsed.groupdict()<EOL>parsed_dict['<STR_LIT>'] = int(parsed_dict['<STR_LIT>'])<EOL>yield PylintError(**parsed_dict)<EOL><DEDENT>

Parse the pylint output-format=parseable lines into PylintError tuples.


tag_str = "<STR_LIT>" if tag else "<STR_LIT>"<EOL>if error_names:<EOL><INDENT>return u"<STR_LIT>".format(<EOL>disabled="<STR_LIT:U+002CU+0020>".join(sorted(error_names)),<EOL>tag=tag_str,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>

Format a list of error_names into a 'pylint: disable=' line.


if not errors:<EOL><INDENT>yield line<EOL>return<EOL><DEDENT>current = PYLINT_EXCEPTION_REGEX.search(line)<EOL>if current:<EOL><INDENT>original_errors = {disable.strip() for disable in current.group('<STR_LIT>').split('<STR_LIT:U+002C>')}<EOL><DEDENT>else:<EOL><INDENT>original_errors = set()<EOL><DEDENT>disabled_errors = set(original_errors)<EOL>for error in errors:<EOL><INDENT>if error.error_name == '<STR_LIT>':<EOL><INDENT>parsed = re.search("""<STR_LIT>""", error.error_msg)<EOL>disabled_errors.discard(parsed.group('<STR_LIT>'))<EOL><DEDENT>elif error.error_name == '<STR_LIT>' and error.error_msg == '<STR_LIT>':<EOL><INDENT>yield format_pylint_disables({error.error_name}).strip() + '<STR_LIT:\n>'<EOL><DEDENT>else:<EOL><INDENT>disabled_errors.add(error.error_name)<EOL><DEDENT><DEDENT>disable_string = format_pylint_disables(disabled_errors, not disabled_errors <= original_errors)<EOL>if current:<EOL><INDENT>yield PYLINT_EXCEPTION_REGEX.sub(disable_string, line)<EOL><DEDENT>else:<EOL><INDENT>yield re.sub(r'<STR_LIT>', disable_string + r'<STR_LIT>', line, count=<NUM_LIT:1>)<EOL><DEDENT>

Yield any modified versions of ``line`` needed to address the errors in ``errors``.


errors = defaultdict(lambda: defaultdict(set))<EOL>for pylint_error in parse_pylint_output(pylint_output):<EOL><INDENT>errors[pylint_error.filename][pylint_error.linenum].add(pylint_error)<EOL><DEDENT>for file_with_errors in sorted(errors):<EOL><INDENT>try:<EOL><INDENT>opened_file = open(file_with_errors)<EOL><DEDENT>except IOError:<EOL><INDENT>LOG.warning(u"<STR_LIT>", file_with_errors, exc_info=True)<EOL><DEDENT>else:<EOL><INDENT>with opened_file as input_file:<EOL><INDENT>output_lines = []<EOL>for line_num, line in enumerate(input_file, start=<NUM_LIT:1>):<EOL><INDENT>output_lines.extend(<EOL>fix_pylint(<EOL>line,<EOL>errors[file_with_errors][line_num]<EOL>)<EOL>)<EOL><DEDENT><DEDENT>with open(file_with_errors, '<STR_LIT:w>') as output_file:<EOL><INDENT>output_file.writelines(output_lines)<EOL><DEDENT><DEDENT><DEDENT>

Add ``# pylint: disable`` clauses to add exceptions to all existing pylint errors in a codebase.


if argv is None:<EOL><INDENT>argv = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>if not argv or argv[<NUM_LIT:0>] == "<STR_LIT>":<EOL><INDENT>show_help()<EOL>return <NUM_LIT:0><EOL><DEDENT>elif argv[<NUM_LIT:0>] == "<STR_LIT>":<EOL><INDENT>return check_main(argv[<NUM_LIT:1>:])<EOL><DEDENT>elif argv[<NUM_LIT:0>] == "<STR_LIT:list>":<EOL><INDENT>return list_main(argv[<NUM_LIT:1>:])<EOL><DEDENT>elif argv[<NUM_LIT:0>] == "<STR_LIT>":<EOL><INDENT>return write_main(argv[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>print(u"<STR_LIT>".format("<STR_LIT:U+0020>".join(argv)))<EOL>show_help()<EOL>return <NUM_LIT:1><EOL><DEDENT>


print(

Print the help string for the edx_lint command.


if len(argv) != <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL>return <NUM_LIT:1><EOL><DEDENT>filename = argv[<NUM_LIT:0>]<EOL>if os.path.exists(filename):<EOL><INDENT>print(u"<STR_LIT>" % filename)<EOL>tef = TamperEvidentFile(filename)<EOL>if tef.validate():<EOL><INDENT>print(u"<STR_LIT>" % filename)<EOL><DEDENT>else:<EOL><INDENT>print(u"<STR_LIT>" % filename)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print(u"<STR_LIT>" % filename)<EOL><DEDENT>return <NUM_LIT:0><EOL>

check FILENAME
    Check that FILENAME has not been edited since writing.


if len(argv) != <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>")<EOL>return <NUM_LIT:1><EOL><DEDENT>filename = argv[<NUM_LIT:0>]<EOL>resource_name = "<STR_LIT>" + filename<EOL>tweaks_name = amend_filename(filename, "<STR_LIT>")<EOL>if not pkg_resources.resource_exists("<STR_LIT>", resource_name):<EOL><INDENT>print(u"<STR_LIT>" % filename)<EOL>return <NUM_LIT:2><EOL><DEDENT>if os.path.exists(filename):<EOL><INDENT>print(u"<STR_LIT>" % filename)<EOL>tef = TamperEvidentFile(filename)<EOL>if not tef.validate():<EOL><INDENT>bak_name = amend_filename(filename, "<STR_LIT>")<EOL>print(u"<STR_LIT>" % (filename, bak_name))<EOL>if os.path.exists(bak_name):<EOL><INDENT>print(u"<STR_LIT>" % bak_name)<EOL>os.remove(bak_name)<EOL><DEDENT>os.rename(filename, bak_name)<EOL><DEDENT><DEDENT>print(u"<STR_LIT>" % filename)<EOL>cfg = configparser.RawConfigParser()<EOL>resource_string = pkg_resources.resource_string("<STR_LIT>", resource_name).decode("<STR_LIT:utf8>")<EOL>if six.PY2:<EOL><INDENT>cfg.readfp(cStringIO(resource_string), resource_name)<EOL><DEDENT>else:<EOL><INDENT>cfg.read_string(resource_string, resource_name)     <EOL><DEDENT>if os.path.exists(tweaks_name):<EOL><INDENT>print(u"<STR_LIT>" % tweaks_name)<EOL>cfg_tweaks = configparser.RawConfigParser()<EOL>cfg_tweaks.read([tweaks_name])<EOL>merge_configs(cfg, cfg_tweaks)<EOL><DEDENT>print(u"<STR_LIT>" % filename)<EOL>output_text = cStringIO()<EOL>output_text.write(WARNING_HEADER.format(filename=filename, tweaks_name=tweaks_name))<EOL>cfg.write(output_text)<EOL>out_tef = TamperEvidentFile(filename)<EOL>if six.PY2:<EOL><INDENT>output_bytes = output_text.getvalue()<EOL><DEDENT>else:<EOL><INDENT>output_bytes = output_text.getvalue().encode("<STR_LIT:utf8>")<EOL><DEDENT>out_tef.write(output_bytes)<EOL>return <NUM_LIT:0><EOL>

write FILENAME
    Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.


base, ext = os.path.splitext(filename)<EOL>amended_name = base + amend + ext<EOL>return amended_name<EOL>

Amend a filename with a suffix.

    amend_filename("foo.txt", "_tweak") --> "foo_tweak.txt"


linter.register_checker(YamlLoadChecker(linter))<EOL>


if FILENAME:<EOL><INDENT>linter.register_checker(ModuleTracingChecker(linter))<EOL><DEDENT>


with open(FILENAME, "<STR_LIT:a>") as f:<EOL><INDENT>f.write(node.file)<EOL>f.write("<STR_LIT:\n>")<EOL><DEDENT>


linter.register_checker(TranslationStringConstantsChecker(linter))<EOL>


if not isinstance(node.func, astroid.Name):<EOL><INDENT>return<EOL><DEDENT>if node.func.name not in self.TRANSLATION_FUNCTIONS:<EOL><INDENT>return<EOL><DEDENT>first = node.args[<NUM_LIT:0>]<EOL>if isinstance(first, astroid.Const):<EOL><INDENT>if isinstance(first.value, six.string_types):<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.add_message(self.MESSAGE_ID, args=node.func.name, node=node)<EOL>

Called for every function call in the source code.


linter.register_checker(GetSetAttrLiteralChecker(linter))<EOL>


if not isinstance(node.func, astroid.Name):<EOL><INDENT>return<EOL><DEDENT>if node.func.name == "<STR_LIT>":<EOL><INDENT>if len(node.args) != <NUM_LIT:2>:<EOL><INDENT>return<EOL><DEDENT><DEDENT>elif node.func.name in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>second = node.args[<NUM_LIT:1>]<EOL>if isinstance(second, astroid.Const):<EOL><INDENT>if isinstance(second.value, six.string_types):<EOL><INDENT>if re.search(r"<STR_LIT>", second.value):<EOL><INDENT>self.add_message(self.MESSAGE_ID, args=node.func.name, node=node)<EOL><DEDENT><DEDENT><DEDENT>


linter.register_checker(AssertChecker(linter))<EOL>


if not isinstance(node.func, astroid.Attribute):<EOL><INDENT>return<EOL><DEDENT>if node.func.attrname not in self.AFFECTED_ASSERTS:<EOL><INDENT>return<EOL><DEDENT>first_arg = node.args[<NUM_LIT:0>]<EOL>existing_code = "<STR_LIT>" % (node.func.attrname, first_arg.as_string())<EOL>if isinstance(first_arg, astroid.Compare):<EOL><INDENT>if len(first_arg.ops) > <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>compare = first_arg.ops[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>right = first_arg.ops[<NUM_LIT:0>][<NUM_LIT:1>]<EOL>if isinstance(right, astroid.Const) and right.value is None:<EOL><INDENT>better = self.BETTER_NONE_COMPARES[compare]<EOL><DEDENT>else:<EOL><INDENT>better = self.BETTER_COMPARES[compare]<EOL><DEDENT>if node.func.attrname == "<STR_LIT>":<EOL><INDENT>better = self.INVERTED[better]<EOL><DEDENT>self.add_message(<EOL>self.MESSAGE_ID,<EOL>args=u"<STR_LIT>" % (existing_code, better),<EOL>node=node,<EOL>)<EOL><DEDENT>

Check that various assertTrue/False functions are not misused.


linter.register_checker(RangeChecker(linter))<EOL>


if not isinstance(node.func, astroid.Name):<EOL><INDENT>return<EOL><DEDENT>if node.func.name not in self.RANGE_FUNCTIONS:<EOL><INDENT>return<EOL><DEDENT>first = node.args[<NUM_LIT:0>]<EOL>if not isinstance(first, astroid.Const):<EOL><INDENT>return<EOL><DEDENT>if not isinstance(first.value, int):<EOL><INDENT>return<EOL><DEDENT>three1 = False<EOL>if len(node.args) == <NUM_LIT:3>:<EOL><INDENT>third = node.args[<NUM_LIT:2>]<EOL>if isinstance(third, astroid.Const):<EOL><INDENT>if isinstance(third.value, int) and third.value == <NUM_LIT:1>:<EOL><INDENT>three1 = True<EOL><DEDENT><DEDENT><DEDENT>if first.value == <NUM_LIT:0>:<EOL><INDENT>if len(node.args) == <NUM_LIT:2>:<EOL><INDENT>self.add_message(self.MESSAGE_ID, args=(node.func.name, "<STR_LIT>"), node=node)<EOL><DEDENT>elif three1:<EOL><INDENT>self.add_message(self.MESSAGE_ID, args=(node.func.name, "<STR_LIT>"), node=node)<EOL><DEDENT><DEDENT>elif three1:<EOL><INDENT>self.add_message(self.MESSAGE_ID, args=(node.func.name, "<STR_LIT>"), node=node)<EOL><DEDENT>


linter.register_checker(UnitTestSetupSuperChecker(linter))<EOL>


<EOL>if not node.is_method():<EOL><INDENT>return<EOL><DEDENT>method_name = node.name<EOL>if method_name not in self.METHOD_NAMES:<EOL><INDENT>return<EOL><DEDENT>klass_node = node.parent.frame()<EOL>to_call = _ancestors_to_call(klass_node, method_name)<EOL>not_called_yet = dict(to_call)<EOL>for stmt in node.nodes_of_class(astroid.Call):<EOL><INDENT>expr = stmt.func<EOL>if not isinstance(expr, astroid.Attribute):<EOL><INDENT>continue<EOL><DEDENT>if expr.attrname != method_name:<EOL><INDENT>continue<EOL><DEDENT>if (isinstance(expr.expr, astroid.Call) and<EOL>isinstance(expr.expr.func, astroid.Name) and<EOL>expr.expr.func.name == '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>klass = next(expr.expr.infer())<EOL>if klass is astroid.Uninferable:<EOL><INDENT>continue<EOL><DEDENT>if (isinstance(klass, astroid.Instance) and<EOL>isinstance(klass._proxied, astroid.ClassDef) and<EOL>utils.is_builtin_object(klass._proxied) and<EOL>klass._proxied.name == '<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>if isinstance(klass, astroid.objects.Super):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>del not_called_yet[klass]<EOL><DEDENT>except KeyError:<EOL><INDENT>if klass not in to_call:<EOL><INDENT>self.add_message(<EOL>self.NON_PARENT_MESSAGE_ID,<EOL>node=expr,<EOL>args=(method_name, usable_class_name(klass)),<EOL>)<EOL><DEDENT><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>for klass, method in six.iteritems(not_called_yet):<EOL><INDENT>if klass.name == '<STR_LIT:object>' or method.parent.name == '<STR_LIT:object>':<EOL><INDENT>continue<EOL><DEDENT>self.add_message(<EOL>self.NOT_CALLED_MESSAGE_ID,<EOL>args=(method_name, usable_class_name(klass)),<EOL>node=node,<EOL>)<EOL><DEDENT>

Called for every function definition in the source code.


for name in dir(cls):<EOL><INDENT>if name.startswith("<STR_LIT>"):<EOL><INDENT>if name[<NUM_LIT:6>:] not in CLASS_NAMES:<EOL><INDENT>raise Exception(u"<STR_LIT>".format(name))<EOL><DEDENT><DEDENT><DEDENT>return cls<EOL>

Check that a checker's visitors are correctly named.

    A checker has methods named visit_NODETYPE, but it's easy to mis-name
    a visit method, and it will never be called.  This decorator checks
    the class to see that all of its visitors are named after an existing
    node class.


name = node.qname()<EOL>for prefix in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT:.>"]:<EOL><INDENT>if name.startswith(prefix):<EOL><INDENT>name = name[len(prefix):]<EOL><DEDENT><DEDENT>return name<EOL>

Make a reasonable class name for a class node.


linter.register_checker(UnicodeFormatStringChecker(linter))<EOL>


self._unicode_literals = "<STR_LIT>" in node.future_imports<EOL>


<EOL>for mod in MODS:<EOL><INDENT>mod.register_checkers(linter)<EOL><DEDENT>

Registering additional checkers.
    However, we will also use it to amend existing checker config.


linter.register_checker(LayeredTestClassChecker(linter))<EOL>


if not is_test_case_class(node):<EOL><INDENT>return<EOL><DEDENT>for anc in node.ancestors():<EOL><INDENT>if not is_test_case_class(anc):<EOL><INDENT>continue<EOL><DEDENT>for meth in anc.mymethods():<EOL><INDENT>if meth.name.startswith("<STR_LIT>"):<EOL><INDENT>self.add_message(self.MESSAGE_ID, args=(node.name, anc.name), node=node)<EOL>return<EOL><DEDENT><DEDENT><DEDENT>


def write(self, text, hashline=b"<STR_LIT>"):

if not text.endswith(b"<STR_LIT:\n>"):<EOL><INDENT>text += b"<STR_LIT:\n>"<EOL><DEDENT>actual_hash = hashlib.sha1(text).hexdigest()<EOL>with open(self.filename, "<STR_LIT:wb>") as f:<EOL><INDENT>f.write(text)<EOL>f.write(hashline.decode("<STR_LIT:utf8>").format(actual_hash).encode("<STR_LIT:utf8>"))<EOL>f.write(b"<STR_LIT:\n>")<EOL><DEDENT>

u"""
        Write `text` to the file.

        Writes the text to the file, with a final line checksumming the
        contents.  The entire file must be written with one `.write()` call.

        The last line is written with the `hashline` format string, which can
        be changed to accommodate different file syntaxes.

        Both arguments are UTF8 byte strings.

        Arguments:
            text (UTF8 byte string): the contents of the file to write.

            hashline (UTF8 byte string): the format of the last line to append
                to the file, with "{}" replaced with the hash.


with open(self.filename, "<STR_LIT:rb>") as f:<EOL><INDENT>text = f.read()<EOL><DEDENT>start_last_line = text.rfind(b"<STR_LIT:\n>", <NUM_LIT:0>, -<NUM_LIT:1>)<EOL>if start_last_line == -<NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>original_text = text[:start_last_line+<NUM_LIT:1>]<EOL>last_line = text[start_last_line+<NUM_LIT:1>:]<EOL>expected_hash = hashlib.sha1(original_text).hexdigest().encode('<STR_LIT:utf8>')<EOL>match = re.search(b"<STR_LIT>", last_line)<EOL>if not match:<EOL><INDENT>return False<EOL><DEDENT>actual_hash = match.group(<NUM_LIT:0>)<EOL>return actual_hash == expected_hash<EOL>

Check if the file still has its original contents.

Returns True if the file is unchanged, False if it has been tampered
with.


return isinstance( value, INTEGER_TYPES )<EOL>

Check if value is a valid unsigned int, int, or long


def guess_array_memory_usage( bam_readers, dtype, use_strand=False ):

ARRAY_COUNT = <NUM_LIT:5><EOL>if not isinstance( bam_readers, list ):<EOL><INDENT>bam_readers = [ bam_readers ]<EOL><DEDENT>if isinstance( dtype, basestring ):<EOL><INDENT>dtype = NUMPY_DTYPES.get( dtype, None )<EOL><DEDENT>use_strand = use_strand + <NUM_LIT:1> <EOL>dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=None, force_dtype=False )<EOL>if not [ dt for dt in dtypes if dt is not None ]:<EOL><INDENT>dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=dtype or numpy.uint64, force_dtype=True )<EOL><DEDENT>elif dtype:<EOL><INDENT>dtypes = [ dtype if dt else None for dt in dtypes ]<EOL><DEDENT>read_groups = []<EOL>no_read_group = False<EOL>for bam in bam_readers:<EOL><INDENT>rgs = bam.get_read_groups()<EOL>if rgs:<EOL><INDENT>for rg in rgs:<EOL><INDENT>if rg not in read_groups:<EOL><INDENT>read_groups.append( rg )<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>no_read_group = True<EOL><DEDENT><DEDENT>read_groups = len( read_groups ) + no_read_group<EOL>max_ref_size = <NUM_LIT:0><EOL>array_byte_overhead = sys.getsizeof( numpy.zeros( ( <NUM_LIT:0> ), dtype=numpy.uint64 ) )<EOL>array_count = ARRAY_COUNT * use_strand * read_groups<EOL>for bam in bam_readers:<EOL><INDENT>for i, ( name, length ) in enumerate( bam.get_references() ):<EOL><INDENT>if dtypes[i] is not None:<EOL><INDENT>max_ref_size = max( max_ref_size, ( length + length * dtypes[i]().nbytes * array_count + ( array_byte_overhead * ( array_count + <NUM_LIT:1> ) ) ) )<EOL><DEDENT><DEDENT><DEDENT>return max_ref_size<EOL>

Returns an estimate for the maximum amount of memory to be consumed by numpy arrays.


def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,<EOL>to_dir=os.curdir, delay=<NUM_LIT:15>):

<EOL>to_dir = os.path.abspath(to_dir)<EOL>try:<EOL><INDENT>from urllib.request import urlopen<EOL><DEDENT>except ImportError:<EOL><INDENT>from urllib2 import urlopen<EOL><DEDENT>tgz_name = "<STR_LIT>" % version<EOL>url = download_base + tgz_name<EOL>saveto = os.path.join(to_dir, tgz_name)<EOL>src = dst = None<EOL>if not os.path.exists(saveto):  <EOL><INDENT>try:<EOL><INDENT>log.warn("<STR_LIT>", url)<EOL>src = urlopen(url)<EOL>data = src.read()<EOL>dst = open(saveto, "<STR_LIT:wb>")<EOL>dst.write(data)<EOL><DEDENT>finally:<EOL><INDENT>if src:<EOL><INDENT>src.close()<EOL><DEDENT>if dst:<EOL><INDENT>dst.close()<EOL><DEDENT><DEDENT><DEDENT>return os.path.realpath(saveto)<EOL>

Download distribute from a specified location and return its filename

    `version` should be a valid distribute version number that is available
    as an egg for download under the `download_base` URL (which should end
    with a '/'). `to_dir` is the directory where the egg will be downloaded.
    `delay` is the number of seconds to pause before an actual download
    attempt.


f = open(path)<EOL>existing_content = f.read()<EOL>f.close()<EOL>if existing_content == content:<EOL><INDENT>log.warn('<STR_LIT>')<EOL>return False<EOL><DEDENT>log.warn('<STR_LIT>')<EOL>_rename_path(path)<EOL>f = open(path, '<STR_LIT:w>')<EOL>try:<EOL><INDENT>f.write(content)<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT>return True<EOL>


def _extractall(self, path="<STR_LIT:.>", members=None):

import copy<EOL>import operator<EOL>from tarfile import ExtractError<EOL>directories = []<EOL>if members is None:<EOL><INDENT>members = self<EOL><DEDENT>for tarinfo in members:<EOL><INDENT>if tarinfo.isdir():<EOL><INDENT>directories.append(tarinfo)<EOL>tarinfo = copy.copy(tarinfo)<EOL>tarinfo.mode = <NUM_LIT>  <EOL><DEDENT>self.extract(tarinfo, path)<EOL><DEDENT>if sys.version_info < (<NUM_LIT:2>, <NUM_LIT:4>):<EOL><INDENT>def sorter(dir1, dir2):<EOL><INDENT>return cmp(dir1.name, dir2.name)<EOL><DEDENT>directories.sort(sorter)<EOL>directories.reverse()<EOL><DEDENT>else:<EOL><INDENT>directories.sort(key=operator.attrgetter('<STR_LIT:name>'), reverse=True)<EOL><DEDENT>for tarinfo in directories:<EOL><INDENT>dirpath = os.path.join(path, tarinfo.name)<EOL>try:<EOL><INDENT>self.chown(tarinfo, dirpath)<EOL>self.utime(tarinfo, dirpath)<EOL>self.chmod(tarinfo, dirpath)<EOL><DEDENT>except ExtractError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if self.errorlevel > <NUM_LIT:1>:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>self._dbg(<NUM_LIT:1>, "<STR_LIT>" % e)<EOL><DEDENT><DEDENT><DEDENT>

Extract all members from the archive to the current working
       directory and set owner, modification time and permissions on
       directories afterwards. `path' specifies a different directory
       to extract to. `members' is optional and must be a subset of the
       list returned by getmembers().


install_args = []<EOL>if options.user_install:<EOL><INDENT>if sys.version_info < (<NUM_LIT:2>, <NUM_LIT:6>):<EOL><INDENT>log.warn("<STR_LIT>")<EOL>raise SystemExit(<NUM_LIT:1>)<EOL><DEDENT>install_args.append('<STR_LIT>')<EOL><DEDENT>return install_args<EOL>

Build the arguments to 'python setup.py install' on the distribute package


parser = optparse.OptionParser()<EOL>parser.add_option(<EOL>'<STR_LIT>', dest='<STR_LIT>', action='<STR_LIT:store_true>', default=False,<EOL>help='<STR_LIT>')<EOL>parser.add_option(<EOL>'<STR_LIT>', dest='<STR_LIT>', metavar="<STR_LIT>",<EOL>default=DEFAULT_URL,<EOL>help='<STR_LIT>')<EOL>options, args = parser.parse_args()<EOL>return options<EOL>


options = _parse_args()<EOL>tarball = download_setuptools(download_base=options.download_base)<EOL>return _install(tarball, _build_install_args(options))<EOL>

Install or upgrade setuptools and EasyInstall


with colorful.with_style('<STR_LIT>') as c:<EOL><INDENT>sys.stdout.write(c.bold('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.dimmed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.italic('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.underlined('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.inversed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.concealed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.struckthrough('<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.write(c.orange('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.purple('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.blue('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.seaGreen('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.green('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.yellow('<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.write(c.on_orange('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_purple('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_blue('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_seaGreen('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.gray_on_green('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.gray_on_yellow('<STR_LIT>') + '<STR_LIT:\n>')<EOL><DEDENT>


with colorful.with_style('<STR_LIT>') as c:<EOL><INDENT>sys.stdout.write(c.bold('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.dimmed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.italic('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.underlined('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.inversed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.concealed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.struckthrough('<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.write(c.yellow('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.red('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.red('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.blue('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.cyan('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.green('<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.write(c.on_yellow('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_red('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_red('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_blue('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_cyan('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(c.on_green('<STR_LIT>') + '<STR_LIT:\n>')<EOL><DEDENT>


<EOL>sys.stdout.write(colorful.bold('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.dimmed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.italic('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.underlined('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.inversed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.concealed('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.struckthrough('<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.write(colorful.red('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.green('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.yellow('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.blue('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.cyan('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.white('<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.write(colorful.on_red('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.on_green('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.on_yellow('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.on_blue('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.on_magenta('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.on_cyan('<STR_LIT>') + '<STR_LIT:U+0020>')<EOL>sys.stdout.write(colorful.on_white('<STR_LIT>') + '<STR_LIT:\n>')<EOL>


finder = VersionFinder()<EOL>path = os.path.join(PROJECT_ROOT, '<STR_LIT>', '<STR_LIT>')<EOL>with codecs.open(path, '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as fp:<EOL><INDENT>file_data = fp.read().encode('<STR_LIT:utf-8>')<EOL>finder.visit(ast.parse(file_data))<EOL><DEDENT>return finder.version<EOL>

Read version from __init__.py without loading any files


if env.get('<STR_LIT>', '<STR_LIT:0>') == '<STR_LIT:1>':<EOL><INDENT>return NO_COLORS<EOL><DEDENT>if env.get('<STR_LIT>', '<STR_LIT:0>') == '<STR_LIT:1>':<EOL><INDENT>return ANSI_8_COLORS<EOL><DEDENT>if env.get('<STR_LIT>', '<STR_LIT:0>') == '<STR_LIT:1>':<EOL><INDENT>return ANSI_16_COLORS<EOL><DEDENT>if env.get('<STR_LIT>', '<STR_LIT:0>') == '<STR_LIT:1>':<EOL><INDENT>return ANSI_256_COLORS<EOL><DEDENT>if env.get('<STR_LIT>', '<STR_LIT:0>') == '<STR_LIT:1>':<EOL><INDENT>return TRUE_COLORS<EOL><DEDENT>if not sys.stdout.isatty():<EOL><INDENT>return NO_COLORS<EOL><DEDENT>colorterm_env = env.get('<STR_LIT>')<EOL>if colorterm_env:<EOL><INDENT>if colorterm_env in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>return TRUE_COLORS<EOL><DEDENT>if colorterm_env in {'<STR_LIT>'}:<EOL><INDENT>return ANSI_256_COLORS<EOL><DEDENT><DEDENT>termprog_env = env.get('<STR_LIT>')<EOL>if termprog_env:<EOL><INDENT>if termprog_env in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>return TRUE_COLORS<EOL><DEDENT>if termprog_env in {'<STR_LIT>'}:<EOL><INDENT>return ANSI_256_COLORS<EOL><DEDENT><DEDENT>term_env = env.get('<STR_LIT>')<EOL>if term_env:<EOL><INDENT>if term_env in {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>return ANSI_256_COLORS<EOL><DEDENT>if term_env in {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>return ANSI_16_COLORS<EOL><DEDENT><DEDENT>if colorterm_env:<EOL><INDENT>return ANSI_16_COLORS<EOL><DEDENT>return ANSI_8_COLORS<EOL>

Detect what color palettes are supported.
It'll return a valid color mode to use
with colorful.

:param dict env: the environment dict like returned by ``os.envion``


if r == g and g == b:<EOL><INDENT>if r < <NUM_LIT:8>:<EOL><INDENT>return <NUM_LIT:16><EOL><DEDENT>if r > <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>return round(((r - <NUM_LIT:8>) / <NUM_LIT>) * <NUM_LIT>) + <NUM_LIT><EOL><DEDENT>ansi_r = <NUM_LIT> * round(r / <NUM_LIT> * <NUM_LIT>)<EOL>ansi_g = <NUM_LIT:6> * round(g / <NUM_LIT> * <NUM_LIT>)<EOL>ansi_b = round(b / <NUM_LIT> * <NUM_LIT>)<EOL>ansi = <NUM_LIT:16> + ansi_r + ansi_g + ansi_b<EOL>return ansi<EOL>


def rgb_to_ansi16(r, g, b, use_bright=False):

ansi_b = round(b / <NUM_LIT>) << <NUM_LIT:2><EOL>ansi_g = round(g / <NUM_LIT>) << <NUM_LIT:1><EOL>ansi_r = round(r / <NUM_LIT>)<EOL>ansi = (<NUM_LIT> if use_bright else <NUM_LIT:30>) + (ansi_b | ansi_g | ansi_r)<EOL>return ansi<EOL>


@contextmanager<EOL><INDENT>def with_setup(self, colormode=None, colorpalette=None, extend_colors=False):<DEDENT>

colorful = Colorful(<EOL>colormode=self.colorful.colormode,<EOL>colorpalette=copy.copy(self.colorful.colorpalette)<EOL>)<EOL>colorful.setup(<EOL>colormode=colormode, colorpalette=colorpalette, extend_colors=extend_colors<EOL>)<EOL>yield colorful<EOL>

Return a new Colorful object with the given color config.


<EOL>orig_module = __name__ + '<STR_LIT>'<EOL>if orig_module in sys.modules:<EOL><INDENT>try:<EOL><INDENT>return getattr(sys.modules[orig_module], name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass  <EOL><DEDENT><DEDENT>return getattr(self.colorful, name)<EOL>

Dynamically get methods from Colorful object.


def translate_rgb_to_ansi_code(red, green, blue, offset, colormode):

if colormode == terminal.NO_COLORS:  <EOL><INDENT>return '<STR_LIT>', '<STR_LIT>'<EOL><DEDENT>if colormode == terminal.ANSI_8_COLORS or colormode == terminal.ANSI_16_COLORS:<EOL><INDENT>color_code = ansi.rgb_to_ansi16(red, green, blue)<EOL>start_code = ansi.ANSI_ESCAPE_CODE.format(<EOL>code=color_code + offset - ansi.FOREGROUND_COLOR_OFFSET)<EOL>end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)<EOL>return start_code, end_code<EOL><DEDENT>if colormode == terminal.ANSI_256_COLORS:<EOL><INDENT>color_code = ansi.rgb_to_ansi256(red, green, blue)<EOL>start_code = ansi.ANSI_ESCAPE_CODE.format(code='<STR_LIT>'.format(<EOL>base=<NUM_LIT:8> + offset, code=color_code))<EOL>end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)<EOL>return start_code, end_code<EOL><DEDENT>if colormode == terminal.TRUE_COLORS:<EOL><INDENT>start_code = ansi.ANSI_ESCAPE_CODE.format(code='<STR_LIT>'.format(<EOL>base=<NUM_LIT:8> + offset, red=red, green=green, blue=blue))<EOL>end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)<EOL>return start_code, end_code<EOL><DEDENT>raise ColorfulError('<STR_LIT>'.format(colormode))<EOL>

Translate the given RGB color into the appropriate ANSI escape code
for the given color mode.
The offset is used for the base color which is used.

The ``colormode`` has to be one of:
    * 0: no colors / disabled
    * 8: use ANSI 8 colors
    * 16: use ANSI 16 colors (same as 8 but with brightness)
    * 256: use ANSI 256 colors
    * 0xFFFFFF / 16777215: use 16 Million true colors

:param int red: the red channel value
:param int green: the green channel value
:param int blue: the blue channel value
:param int offset: the offset to use for the base color
:param int colormode: the color mode to use. See explanation above


def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette):

try:<EOL><INDENT>red, green, blue = colorpalette[colorname]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ColorfulError('<STR_LIT>'.format(  <EOL>colorname))<EOL><DEDENT>else:<EOL><INDENT>return translate_rgb_to_ansi_code(red, green, blue, offset, colormode)<EOL><DEDENT>

Translate the given color name to a valid
ANSI escape code.

:parma str colorname: the name of the color to resolve
:parma str offset: the offset for the color code
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:parma dict colorpalette: the color palette to use for the color name mapping

:returns str: the color as ANSI escape code

:raises ColorfulError: if the given color name is invalid


if colormode == terminal.NO_COLORS:  <EOL><INDENT>return '<STR_LIT>', '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>start_code, end_code = ansi.MODIFIERS[modifiername]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ColorfulError('<STR_LIT>'.format(<EOL>modifiername, ansi.MODIFIERS.keys()))<EOL><DEDENT>else:<EOL><INDENT>return ansi.ANSI_ESCAPE_CODE.format(<EOL>code=start_code), ansi.ANSI_ESCAPE_CODE.format(<EOL>code=end_code)<EOL><DEDENT>

Resolve the given modifier name to a valid
ANSI escape code.

:param str modifiername: the name of the modifier to resolve
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``

:returns str: the ANSI escape code for the modifier

:raises ColorfulError: if the given modifier name is invalid


def translate_style(style, colormode, colorpalette):

style_parts = iter(style.split('<STR_LIT:_>'))<EOL>ansi_start_sequence = []<EOL>ansi_end_sequence = []<EOL>try:<EOL><INDENT>part = None<EOL>for mod_part in style_parts:<EOL><INDENT>part = mod_part<EOL>if part not in ansi.MODIFIERS:<EOL><INDENT>break  <EOL><DEDENT>mod_start_code, mod_end_code = resolve_modifier_to_ansi_code(part, colormode)<EOL>ansi_start_sequence.append(mod_start_code)<EOL>ansi_end_sequence.append(mod_end_code)<EOL><DEDENT>else:  <EOL><INDENT>raise StopIteration()<EOL><DEDENT>if part != '<STR_LIT>':<EOL><INDENT>ansi_start_code, ansi_end_code = translate_colorname_to_ansi_code(<EOL>part, ansi.FOREGROUND_COLOR_OFFSET, colormode, colorpalette)<EOL>ansi_start_sequence.append(ansi_start_code)<EOL>ansi_end_sequence.append(ansi_end_code)<EOL>next(style_parts)<EOL><DEDENT>part = next(style_parts)<EOL>ansi_start_code, ansi_end_code = translate_colorname_to_ansi_code(<EOL>part, ansi.BACKGROUND_COLOR_OFFSET, colormode, colorpalette)<EOL>ansi_start_sequence.append(ansi_start_code)<EOL>ansi_end_sequence.append(ansi_end_code)<EOL><DEDENT>except StopIteration:  <EOL><INDENT>pass<EOL><DEDENT>return '<STR_LIT>'.join(ansi_start_sequence), '<STR_LIT>'.join(ansi_end_sequence)<EOL>

Translate the given style to an ANSI escape code
sequence.

``style`` examples are:

* green
* bold
* red_on_black
* bold_green
* italic_yellow_on_cyan

:param str style: the style to translate
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:parma dict colorpalette: the color palette to use for the color name mapping


def style_string(string, ansi_style, colormode, nested=False):

ansi_start_code, ansi_end_code = ansi_style<EOL>if PY2:<EOL><INDENT>if isinstance(string, str):<EOL><INDENT>string = string.decode(DEFAULT_ENCODING)<EOL><DEDENT><DEDENT>string = UNICODE(string).replace(ansi.NEST_PLACEHOLDER, ansi_start_code)<EOL>return '<STR_LIT>'.format(<EOL>start_code=ansi_start_code,<EOL>string=string,<EOL>end_code=ansi_end_code,<EOL>nest_ph=ansi.NEST_PLACEHOLDER if nested else '<STR_LIT>')<EOL>

Style the given string according to the given
ANSI style string.

:param str string: the string to style
:param tuple ansi_style: the styling string returned by ``translate_style``
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``

:returns: a string containing proper ANSI sequence


return self._colorpalette<EOL>


if isinstance(colorpalette, str):  <EOL><INDENT>colorpalette = colors.parse_colors(colorpalette)<EOL><DEDENT>self._colorpalette = colors.sanitize_color_palette(colorpalette)<EOL>

Set the colorpalette which should be used


def setup(self, colormode=None, colorpalette=None, extend_colors=False):

if colormode:<EOL><INDENT>self.colormode = colormode<EOL><DEDENT>if colorpalette:<EOL><INDENT>if extend_colors:<EOL><INDENT>self.update_palette(colorpalette)<EOL><DEDENT>else:<EOL><INDENT>self.colorpalette = colorpalette<EOL><DEDENT><DEDENT>

Setup this colorful object by setting a ``colormode`` and
the ``colorpalette`. The ``extend_colors`` flag is used
to extend the currently active color palette instead of
replacing it.

:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:parma dict colorpalette: the colorpalette to use. This ``dict`` should map
                          color names to it's corresponding RGB value
:param bool extend_colors: extend the active color palette instead of replacing it


self.colormode = terminal.NO_COLORS<EOL>


self.colormode = terminal.ANSI_8_COLORS<EOL>

Use 8 ANSI colors for this colorful object


self.colormode = terminal.ANSI_16_COLORS<EOL>

Use 16 ANSI colors for this colorful object


self.colormode = terminal.ANSI_256_COLORS<EOL>

Use 256 ANSI colors for this colorful object


self.colormode = terminal.TRUE_COLORS<EOL>

Use true colors for this colorful object


self.colorpalette = colorpalette<EOL>


self.colorpalette.update(colors.sanitize_color_palette(colorpalette))<EOL>

Update the currently active color palette
with the given color palette


try:<EOL><INDENT>style = getattr(styles, style_name.upper())<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ColorfulError('<STR_LIT>'.format(<EOL>style_name))<EOL><DEDENT>else:<EOL><INDENT>self.colorpalette = style<EOL><DEDENT>

Use a predefined style as color palette

:param str style_name: the name of the style


def format(self, string, *args, **kwargs):

return string.format(c=self, *args, **kwargs)<EOL>

Format the given string with the given ``args`` and ``kwargs``.
The string can contain references to ``c`` which is provided by
this colorful object.

:param str string: the string to format


return ColorfulString(string, string)<EOL>

Create a new ColorfulString instance of the given
unstyled string.

This method should be used to create a ColorfulString
which is actually not styled yet but can safely be concatinated
with other ColorfulStrings like:

>>> s = colorful.str('Hello ')
>>> s =+ colorful.black('World')
>>> str(s)
'Hello \033[30mWorld\033[39m'

:param str string: the string to use for the ColorfulString


<EOL>allowed_options = {'<STR_LIT>', '<STR_LIT:end>', '<STR_LIT:file>', '<STR_LIT>'}<EOL>given_options = set(options.keys())<EOL>if not given_options.issubset(allowed_options):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(<EOL>'<STR_LIT:U+002CU+0020>'.join(given_options.difference(allowed_options))))<EOL><DEDENT>sep = options.get('<STR_LIT>', '<STR_LIT:U+0020>')<EOL>end = options.get('<STR_LIT:end>', '<STR_LIT:\n>')<EOL>file = options.get('<STR_LIT:file>', sys.stdout)<EOL>flush = options.get('<STR_LIT>', False)<EOL>styled_objects = [self.format(o) for o in objects]<EOL>print(*styled_objects, sep=sep, end=end, file=file)<EOL>if flush:<EOL><INDENT>file.flush()<EOL><DEDENT>

Print the given objects to the given file stream.
See https://docs.python.org/3/library/functions.html#print

The only difference to the ``print()`` built-in is that
``Colorful.print()`` formats the string with ``c=self``.
With that stylings are possible

:param str sep: the seperater between the objects
:param str end: the ending delimiter after all objects
:param file: the file stream to write to
:param bool flush: if the stream should be flushed


value = value.lstrip('<STR_LIT:#>')<EOL>check_hex(value)<EOL>length = len(value)<EOL>step = int(length / <NUM_LIT:3>)<EOL>return tuple(int(value[i:i+step], <NUM_LIT:16>) for i in range(<NUM_LIT:0>, length, step))<EOL>

Convert the given hex string to a
valid RGB channel triplet.


length = len(value)<EOL>if length not in (<NUM_LIT:3>, <NUM_LIT:6>):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(value))<EOL><DEDENT>regex = r'<STR_LIT>'.format(length=length)<EOL>if not re.search(regex, value, re.I):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(value))<EOL><DEDENT>

Check if the given hex value is a valid RGB color

It should match the format: [0-9a-fA-F]
and be of length 3 or 6.


if path.endswith("<STR_LIT>"):<EOL><INDENT>return parse_rgb_txt_file(path)<EOL><DEDENT>elif path.endswith("<STR_LIT>"):<EOL><INDENT>return parse_json_color_file(path)<EOL><DEDENT>raise TypeError("<STR_LIT>")<EOL>

Parse the given color files.

    Supported are:
        * .txt for X11 colors
        * .json for colornames


<EOL>color_dict = {}<EOL>with open(path, '<STR_LIT:r>') as rgb_txt:<EOL><INDENT>for line in rgb_txt:<EOL><INDENT>line = line.strip()<EOL>if not line or line.startswith('<STR_LIT:!>'):<EOL><INDENT>continue  <EOL><DEDENT>parts = line.split()<EOL>color_dict["<STR_LIT:U+0020>".join(parts[<NUM_LIT:3>:])] = (int(parts[<NUM_LIT:0>]), int(parts[<NUM_LIT:1>]), int(parts[<NUM_LIT:2>]))<EOL><DEDENT><DEDENT>return color_dict<EOL>

Parse the given rgb.txt file into a Python dict.

See https://en.wikipedia.org/wiki/X11_color_names for more information

:param str path: the path to the X11 rgb.txt file


with open(path, "<STR_LIT:r>") as color_file:<EOL><INDENT>color_list = json.load(color_file)<EOL><DEDENT>color_dict = {c["<STR_LIT:name>"]: c["<STR_LIT>"] for c in color_list}<EOL>return color_dict<EOL>

Parse a JSON color file.

    The JSON has to be in the following format:

    .. code:: json

       [{"name": "COLOR_NAME", "hex": "#HEX"}, ...]

    :param str path: the path to the JSON color file


new_palette = {}<EOL>def __make_valid_color_name(name):<EOL><INDENT>"""<STR_LIT>"""<EOL>if len(name) == <NUM_LIT:1>:<EOL><INDENT>name = name[<NUM_LIT:0>]<EOL>return name[:<NUM_LIT:1>].lower() + name[<NUM_LIT:1>:]<EOL><DEDENT>return name[<NUM_LIT:0>].lower() + '<STR_LIT>'.join(word.capitalize() for word in name[<NUM_LIT:1>:])<EOL><DEDENT>for key, value in colorpalette.items():<EOL><INDENT>if isinstance(value, str):<EOL><INDENT>value = utils.hex_to_rgb(value)<EOL><DEDENT>new_palette[__make_valid_color_name(key.split())] = value<EOL><DEDENT>return new_palette<EOL>

Sanitze the given color palette so it can
be safely used by Colorful.

It will convert colors specified in hex RGB to
a RGB channel triplet.


<EOL>if len(args) == <NUM_LIT:1>:<EOL><INDENT>args = args[<NUM_LIT:0>]<EOL><DEDENT>if len(args) == <NUM_LIT:2>:<EOL><INDENT>args += (CODAS[<NUM_LIT:0>],)<EOL><DEDENT>try:<EOL><INDENT>onset, nucleus, coda = args<EOL><DEDENT>except ValueError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>offset = (<EOL>(ONSETS.index(onset) * NUM_NUCLEUSES + NUCLEUSES.index(nucleus)) *<EOL>NUM_CODAS + CODAS.index(coda)<EOL>)<EOL>return unichr(FIRST_HANGUL_OFFSET + offset)<EOL>

Joins a Hangul letter from Korean phonemes.


def split_phonemes(letter, onset=True, nucleus=True, coda=True):

if len(letter) != <NUM_LIT:1> or not is_hangul(letter):<EOL><INDENT>raise ValueError('<STR_LIT>' % letter)<EOL><DEDENT>offset = ord(letter) - FIRST_HANGUL_OFFSET<EOL>phonemes = [None] * <NUM_LIT:3><EOL>if onset:<EOL><INDENT>phonemes[<NUM_LIT:0>] = ONSETS[offset // (NUM_NUCLEUSES * NUM_CODAS)]<EOL><DEDENT>if nucleus:<EOL><INDENT>phonemes[<NUM_LIT:1>] = NUCLEUSES[(offset // NUM_CODAS) % NUM_NUCLEUSES]<EOL><DEDENT>if coda:<EOL><INDENT>phonemes[<NUM_LIT:2>] = CODAS[offset % NUM_CODAS]<EOL><DEDENT>return tuple(phonemes)<EOL>

Splits Korean phonemes as known as "자소" from a Hangul letter.

    :returns: (onset, nucleus, coda)
    :raises ValueError: `letter` is not a Hangul single letter.


if word1 and word2 and is_consonant(word2[<NUM_LIT:0>]):<EOL><INDENT>onset, nucleus, coda = split_phonemes(word1[-<NUM_LIT:1>])<EOL>if not coda:<EOL><INDENT>glue = join_phonemes(onset, nucleus, word2[<NUM_LIT:0>])<EOL>return word1[:-<NUM_LIT:1>] + glue + word2[<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>return word1 + word2<EOL>

Combines two words.  If the first word ends with a vowel and the initial
    letter of the second word is only consonant, it merges them into one
    letter::

    >>> combine_words(u'다', u'ㄺ')
    닭
    >>> combine_words(u'가오', u'ㄴ누리')
    가온누리


patterns, indices = [], {}<EOL>for x, p in enumerate(particles):<EOL><INDENT>group = u'<STR_LIT>' % x<EOL>indices[group] = x<EOL>patterns.append(u'<STR_LIT>' % (group, p.regex_pattern()))<EOL><DEDENT>pattern = re.compile(u'<STR_LIT:|>'.join(patterns))<EOL>return pattern, indices<EOL>

Indexes :class:`Particle` objects.  It returns a regex pattern which
    matches to any particle morphs and a dictionary indexes the given particles
    by regex groups.


return registry.parse(morph)<EOL>

Shortcut for :class:`ParticleRegistry.parse` of the default registry.


return registry.pick(word, morph, **kwargs)<EOL>

Shortcut for :class:`ParticleRegistry.pick` of the default registry.


return registry.postfix(word, morph, **kwargs)<EOL>

Shortcut for :class:`ParticleRegistry.postfix` of the default registry.


return formatter.vformat(message, args, kwargs)<EOL>

Shortcut for :class:`tossi.Formatter.format` of the default registry.


if morph1 == morph2:<EOL><INDENT>return<EOL><DEDENT>if not (morph1 and morph2):<EOL><INDENT>yield u'<STR_LIT>' % (morph1 or morph2)<EOL>return<EOL><DEDENT>len1, len2 = len(morph1), len(morph2)<EOL>if len1 != len2:<EOL><INDENT>longer, shorter = (morph1, morph2) if len1 > len2 else (morph2, morph1)<EOL>if longer.endswith(shorter):<EOL><INDENT>yield u'<STR_LIT>' % (longer[:-len(shorter)], shorter)<EOL>return<EOL><DEDENT><DEDENT>for x, (let1, let2) in enumerate(zip(reversed(morph1), reversed(morph2))):<EOL><INDENT>if let1 != let2:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if x:<EOL><INDENT>x1, x2 = len(morph1) - x, len(morph2) - x<EOL>common_suffix = morph1[x1:]<EOL>morph1, morph2 = morph1[:x1], morph2[:x2]<EOL><DEDENT>else:<EOL><INDENT>common_suffix = '<STR_LIT>'<EOL><DEDENT>for morph1, morph2 in [(morph1, morph2), (morph2, morph1)]:<EOL><INDENT>yield u'<STR_LIT>' % (morph1, morph2, common_suffix)<EOL>yield u'<STR_LIT>' % (morph1, morph2, common_suffix)<EOL><DEDENT>

Generates all reasonable tolerant particle morphs::

    >>> set(generate_tolerances(u'이', u'가'))
    set([u'이(가)', u'(이)가', u'가(이)', u'(가)이'])
    >>> set(generate_tolerances(u'이면', u'면'))
    set([u'(이)면'])


if isinstance(style, integer_types):<EOL><INDENT>return style<EOL><DEDENT>if registry is None:<EOL><INDENT>from . import registry<EOL><DEDENT>particle = registry.parse(style)<EOL>if len(particle.tolerances) != <NUM_LIT:4>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return particle.tolerances.index(style)<EOL>

Resolves a tolerance style of the given tolerant particle morph::

    >>> parse_tolerance_style(u'은(는)')
    0
    >>> parse_tolerance_style(u'(은)는')
    1
    >>> parse_tolerance_style(OPTIONAL_MORPH2_AND_MORPH1)
    3


word = filter_only_significant(word)<EOL>return guess_coda_from_significant_word(word)<EOL>

Guesses the coda of the given word as correct as possible.  If it fails
    to guess the coda, returns ``None``.


if not word:<EOL><INDENT>return word<EOL><DEDENT>if word.startswith(u'<STR_LIT:(>') and word.endswith(u'<STR_LIT:)>'):<EOL><INDENT>return filter_only_significant(word[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL><DEDENT>x = len(word)<EOL>while x > <NUM_LIT:0>:<EOL><INDENT>x -= <NUM_LIT:1><EOL>c = word[x]<EOL>if c == u'<STR_LIT:)>':<EOL><INDENT>m = INSIGNIFICANT_PARENTHESIS_PATTERN.search(word[:x + <NUM_LIT:1>])<EOL>if m is not None:<EOL><INDENT>x = m.start()<EOL><DEDENT>continue<EOL><DEDENT>unicode_category = unicodedata.category(c)<EOL>if not SIGNIFICANT_UNICODE_CATEGORY_PATTERN.match(unicode_category):<EOL><INDENT>continue<EOL><DEDENT>break<EOL><DEDENT>return word[:x + <NUM_LIT:1>]<EOL>

Gets a word which removes insignificant letters at the end of the given
    word::

    >>> pick_significant(u'넥슨(코리아)')
    넥슨
    >>> pick_significant(u'메이플스토리...')
    메이플스토리


try:<EOL><INDENT>__, __, coda =split_phonemes(letter, onset=False, nucleus=False, coda=True)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return coda<EOL><DEDENT>

Picks only a coda from a Hangul letter.  It returns ``None`` if the
    given letter is not Hangul.


decimal = Decimal(decimal)<EOL>__, digits, exp = decimal.as_tuple()<EOL>if exp < <NUM_LIT:0>:<EOL><INDENT>return DIGIT_CODAS[digits[-<NUM_LIT:1>]]<EOL><DEDENT>__, digits, exp = decimal.normalize().as_tuple()<EOL>index = bisect_right(EXP_INDICES, exp) - <NUM_LIT:1><EOL>if index < <NUM_LIT:0>:<EOL><INDENT>return DIGIT_CODAS[digits[-<NUM_LIT:1>]]<EOL><DEDENT>else:<EOL><INDENT>return EXP_CODAS[EXP_INDICES[index]]<EOL><DEDENT>


@property<EOL>@functools.wraps(f)<EOL>def wrapped(self, name=f.__name__):<EOL><INDENT>try:<EOL><INDENT>cache = self.__cache__<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.__cache__ = cache = {}<EOL><DEDENT>try:<EOL><INDENT>return cache[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>cache[name] = rv = f(self)<EOL>return rv<EOL><DEDENT><DEDENT>return wrapped<EOL>

Similar to `@property` but it calls the function just once and caches
    the result.  The object has to can have ``__cache__`` attribute.

    If you define `__slots__` for optimization, the metaclass should be a
    :class:`CacheMeta`.


return with_metaclass(SingletonParticleMeta, SingletonParticle, *bases)<EOL>

Defines a singleton instance immediately when defining the class.  The
    name of the class will refer the instance instead.


return tuple(generate_tolerances(self.morph1, self.morph2))<EOL>

The tuple containing all the possible tolerant morphs.


return get_tolerance(self.tolerances, style)<EOL>


if coda:<EOL><INDENT>return self.morph1<EOL><DEDENT>else:<EOL><INDENT>return self.morph2<EOL><DEDENT>

Determines one of allomorphic morphs based on a coda.


def allomorph(self, word, morph, tolerance_style=DEFAULT_TOLERANCE_STYLE,<EOL>guess_coda=DEFAULT_GUESS_CODA):

suffix = self.match(morph)<EOL>if suffix is None:<EOL><INDENT>return None<EOL><DEDENT>coda = guess_coda(word)<EOL>if coda is not None:<EOL><INDENT>morph = self.rule(coda)<EOL><DEDENT>elif isinstance(tolerance_style, text_type):<EOL><INDENT>morph = tolerance_style<EOL><DEDENT>elif not suffix or not is_consonant(suffix[<NUM_LIT:0>]):<EOL><INDENT>morph = self.tolerance(tolerance_style)<EOL><DEDENT>else:<EOL><INDENT>morph1 = (combine_words(self.morph1, suffix)<EOL>if self.morph1 else suffix[<NUM_LIT:1>:])<EOL>morph2 = (combine_words(self.morph2, suffix)<EOL>if self.morph2 else suffix[<NUM_LIT:1>:])<EOL>tolerances = generate_tolerances(morph1, morph2)<EOL>return get_tolerance_from_iterator(tolerances, tolerance_style)<EOL><DEDENT>return combine_words(morph, suffix)<EOL>

Determines one of allomorphic morphs based on a word.

        .. see also:: :meth:`allomorph`.


if isinstance(key, slice):<EOL><INDENT>word = key.start<EOL>morph = key.stop or self.morph1<EOL>tolerance_style = key.step or DEFAULT_TOLERANCE_STYLE<EOL><DEDENT>else:<EOL><INDENT>word, morph = key, self.morph1<EOL>tolerance_style = DEFAULT_TOLERANCE_STYLE<EOL><DEDENT>return self.allomorph(word, morph, tolerance_style)<EOL>

The syntax sugar to determine one of allomorphic morphs based on a
        word::

           eun = Particle(u'은', u'는')
           assert eun[u'나오'] == u'는'
           assert eun[u'모리안'] == u'은'


seen = set()<EOL>saw = seen.add<EOL>morphs = chain([self.morph1, self.morph2], self.tolerances)<EOL>unique_morphs = (x for x in morphs if x and not (x in seen or saw(x)))<EOL>return tuple(sorted(unique_morphs, key=len, reverse=True))<EOL>

The tuple containing the given morphs and all the possible tolerant
        morphs.  Longer is first.


self.signature_passphrases = self._update_dict(signature_passphrases,<EOL>{}, replace_data=True)<EOL>


return self.signature_passphrases<EOL>


self.encryption_passphrases = self._update_dict(encryption_passphrases,<EOL>{}, replace_data=True)<EOL>


return self.encryption_passphrases<EOL>


def set_algorithms(self, signature=None, encryption=None,<EOL>serialization=None, compression=None):

self.signature_algorithms =self._update_dict(signature, self.DEFAULT_SIGNATURE)<EOL>self.encryption_algorithms =self._update_dict(encryption, self.DEFAULT_ENCRYPTION)<EOL>self.serialization_algorithms =self._update_dict(serialization, self.DEFAULT_SERIALIZATION)<EOL>self.compression_algorithms =self._update_dict(compression, self.DEFAULT_COMPRESSION)<EOL>

Set algorithms used for sealing. Defaults can not be overridden.


return {<EOL>'<STR_LIT>': self.signature_algorithms,<EOL>'<STR_LIT>': self.encryption_algorithms,<EOL>'<STR_LIT>': self.serialization_algorithms,<EOL>'<STR_LIT>': self.compression_algorithms,<EOL>}<EOL>


self.options = self._set_options(options)<EOL>


if not options:<EOL><INDENT>return self.options.copy()<EOL><DEDENT>options = options.copy()<EOL>if '<STR_LIT>' in options:<EOL><INDENT>self.set_magic(options['<STR_LIT>'])<EOL>del(options['<STR_LIT>'])<EOL><DEDENT>if '<STR_LIT>' in options:<EOL><INDENT>flags = options['<STR_LIT>']<EOL>del(options['<STR_LIT>'])<EOL>for key, value in flags.iteritems():<EOL><INDENT>if not isinstance(value, bool):<EOL><INDENT>raise TypeError('<STR_LIT>' % key)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>flags = self.options['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT:info>' in options:<EOL><INDENT>del(options['<STR_LIT:info>'])<EOL><DEDENT>for key, value in options.iteritems():<EOL><INDENT>if not isinstance(value, int):<EOL><INDENT>raise TypeError('<STR_LIT>' % key)<EOL><DEDENT>if value < <NUM_LIT:0> or value > <NUM_LIT:255>:<EOL><INDENT>raise ValueError('<STR_LIT>' % key)<EOL><DEDENT><DEDENT>new_options = self.options.copy()<EOL>new_options.update(options)<EOL>new_options['<STR_LIT>'].update(flags)<EOL>return new_options<EOL>

Private function for setting options used for sealing


return self.options<EOL>


if magic is None or isinstance(magic, str):<EOL><INDENT>self.magic = magic<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>


return self.magic<EOL>


options = self._set_options(options)<EOL>data = self._serialize_data(data, options)<EOL>data = self._compress_data(data, options)<EOL>data = self._encrypt_data(data, options)<EOL>data = self._add_header(data, options)<EOL>data = self._add_magic(data)<EOL>data = self._sign_data(data, options)<EOL>data = self._remove_magic(data)<EOL>data = urlsafe_nopadding_b64encode(data)<EOL>data = self._add_magic(data)<EOL>return data<EOL>


def unseal(self, data, return_options=False):

data = self._remove_magic(data)<EOL>data = urlsafe_nopadding_b64decode(data)<EOL>options = self._read_header(data)<EOL>data = self._add_magic(data)<EOL>data = self._unsign_data(data, options)<EOL>data = self._remove_magic(data)<EOL>data = self._remove_header(data, options)<EOL>data = self._decrypt_data(data, options)<EOL>data = self._decompress_data(data, options)<EOL>data = self._unserialize_data(data, options)<EOL>if return_options:<EOL><INDENT>return data, options<EOL><DEDENT>else:<EOL><INDENT>return data<EOL><DEDENT>


data = self._remove_magic(data)<EOL>data = urlsafe_nopadding_b64decode(data)<EOL>options = self._read_header(data)<EOL>data = self._add_magic(data)<EOL>self._unsign_data(data, options)<EOL>


def get_data_options(self, data, verify_signature=True):

data = self._remove_magic(data)<EOL>data = urlsafe_nopadding_b64decode(data)<EOL>options = self._read_header(data)<EOL>data = self._add_magic(data)<EOL>if verify_signature:<EOL><INDENT>data = self._unsign_data(data, options)<EOL><DEDENT>return options<EOL>


def _encode(self, data, algorithm, key=None):

if algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return data + self._hmac_generate(data, algorithm, key)<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return self._aes_encrypt(data, algorithm, key)<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return data<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return json.dumps(data)<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return data<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return self._zlib_compress(data, algorithm)<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>' % algorithm['<STR_LIT:type>'])<EOL><DEDENT>


def _decode(self, data, algorithm, key=None):

if algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>verify_signature = data[-algorithm['<STR_LIT>']:]<EOL>data = data[:-algorithm['<STR_LIT>']]<EOL>signature = self._hmac_generate(data, algorithm, key)<EOL>if not const_equal(verify_signature, signature):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>return data<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return self._aes_decrypt(data, algorithm, key)<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return data<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return json.loads(data)<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return data<EOL><DEDENT>elif algorithm['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return self._zlib_decompress(data, algorithm)<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>' % algorithm['<STR_LIT:type>'])<EOL><DEDENT>


if options['<STR_LIT>'] not in self.signature_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% options['<STR_LIT>'])<EOL><DEDENT>signature_algorithm =self.signature_algorithms[options['<STR_LIT>']]<EOL>algorithm = self._get_algorithm_info(signature_algorithm)<EOL>key_salt = get_random_bytes(algorithm['<STR_LIT>'])<EOL>key = self._generate_key(options['<STR_LIT>'],<EOL>self.signature_passphrases, key_salt, algorithm)<EOL>data = self._encode(data, algorithm, key)<EOL>return data + key_salt<EOL>


if options['<STR_LIT>'] not in self.signature_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% options['<STR_LIT>'])<EOL><DEDENT>signature_algorithm =self.signature_algorithms[options['<STR_LIT>']]<EOL>algorithm = self._get_algorithm_info(signature_algorithm)<EOL>key_salt = '<STR_LIT>'<EOL>if algorithm['<STR_LIT>']:<EOL><INDENT>key_salt = data[-algorithm['<STR_LIT>']:]<EOL>data = data[:-algorithm['<STR_LIT>']]<EOL><DEDENT>key = self._generate_key(options['<STR_LIT>'],<EOL>self.signature_passphrases, key_salt, algorithm)<EOL>data = self._decode(data, algorithm, key)<EOL>return data<EOL>


if options['<STR_LIT>'] not in self.encryption_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% options['<STR_LIT>'])<EOL><DEDENT>encryption_algorithm =self.encryption_algorithms[options['<STR_LIT>']]<EOL>algorithm = self._get_algorithm_info(encryption_algorithm)<EOL>key_salt = get_random_bytes(algorithm['<STR_LIT>'])<EOL>key = self._generate_key(options['<STR_LIT>'],<EOL>self.encryption_passphrases, key_salt, algorithm)<EOL>data = self._encode(data, algorithm, key)<EOL>return data + key_salt<EOL>


if options['<STR_LIT>'] not in self.encryption_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% options['<STR_LIT>'])<EOL><DEDENT>encryption_algorithm =self.encryption_algorithms[options['<STR_LIT>']]<EOL>algorithm = self._get_algorithm_info(encryption_algorithm)<EOL>key_salt = '<STR_LIT>'<EOL>if algorithm['<STR_LIT>']:<EOL><INDENT>key_salt = data[-algorithm['<STR_LIT>']:]<EOL>data = data[:-algorithm['<STR_LIT>']]<EOL><DEDENT>key = self._generate_key(options['<STR_LIT>'],<EOL>self.encryption_passphrases, key_salt, algorithm)<EOL>data = self._decode(data, algorithm, key)<EOL>return data<EOL>


def _serialize_data(self, data, options):

serialization_algorithm_id = options['<STR_LIT>']<EOL>if serialization_algorithm_id not in self.serialization_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% serialization_algorithm_id)<EOL><DEDENT>serialization_algorithm =self.serialization_algorithms[serialization_algorithm_id]<EOL>algorithm = self._get_algorithm_info(serialization_algorithm)<EOL>data = self._encode(data, algorithm)<EOL>return data<EOL>


def _unserialize_data(self, data, options):

serialization_algorithm_id = options['<STR_LIT>']<EOL>if serialization_algorithm_id not in self.serialization_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% serialization_algorithm_id)<EOL><DEDENT>serialization_algorithm =self.serialization_algorithms[serialization_algorithm_id]<EOL>algorithm = self._get_algorithm_info(serialization_algorithm)<EOL>data = self._decode(data, algorithm)<EOL>return data<EOL>


def _compress_data(self, data, options):

compression_algorithm_id = options['<STR_LIT>']<EOL>if compression_algorithm_id not in self.compression_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% compression_algorithm_id)<EOL><DEDENT>compression_algorithm =self.compression_algorithms[compression_algorithm_id]<EOL>algorithm = self._get_algorithm_info(compression_algorithm)<EOL>compressed = self._encode(data, algorithm)<EOL>if len(compressed) < len(data):<EOL><INDENT>data = compressed<EOL><DEDENT>else:<EOL><INDENT>options['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return data<EOL>


def _decompress_data(self, data, options):

compression_algorithm_id = options['<STR_LIT>']<EOL>if compression_algorithm_id not in self.compression_algorithms:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% compression_algorithm_id)<EOL><DEDENT>compression_algorithm =self.compression_algorithms[compression_algorithm_id]<EOL>algorithm = self._get_algorithm_info(compression_algorithm)<EOL>data = self._decode(data, algorithm)<EOL>return data<EOL>


if not self.magic:<EOL><INDENT>return data<EOL><DEDENT>magic_size = len(self.magic)<EOL>magic = data[:magic_size]<EOL>if magic != self.magic:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>data = data[magic_size:]<EOL>return data<EOL>


if self.magic:<EOL><INDENT>return self.magic + data<EOL><DEDENT>return data<EOL>


<EOL>version_info = self._get_version_info(options['<STR_LIT:version>'])<EOL>flags = options['<STR_LIT>']<EOL>header_flags = dict(<EOL>(i, str(int(j))) for i, j in options['<STR_LIT>'].iteritems())<EOL>header_flags = '<STR_LIT>'.join(version_info['<STR_LIT>'](**header_flags))<EOL>header_flags = int(header_flags, <NUM_LIT:2>)<EOL>options['<STR_LIT>'] = header_flags<EOL>header = version_info['<STR_LIT>']<EOL>header = header(**options)<EOL>header = pack(version_info['<STR_LIT>'], *header)<EOL>if '<STR_LIT>' in flags and flags['<STR_LIT>']:<EOL><INDENT>timestamp = long(time())<EOL>timestamp = pack(version_info['<STR_LIT>'], timestamp)<EOL>header = header + timestamp<EOL><DEDENT>return header + data<EOL>


<EOL>version = self._read_version(data)<EOL>version_info = self._get_version_info(version)<EOL>header_data = data[:version_info['<STR_LIT>']]<EOL>header = version_info['<STR_LIT>']<EOL>header = header._make(<EOL>unpack(version_info['<STR_LIT>'], header_data))<EOL>header = dict(header._asdict())<EOL>flags = list("<STR_LIT>".format(header['<STR_LIT>']))<EOL>flags = dict(version_info['<STR_LIT>']._make(flags)._asdict())<EOL>flags = dict((i, bool(int(j))) for i, j in flags.iteritems())<EOL>header['<STR_LIT>'] = flags<EOL>timestamp = None<EOL>if flags['<STR_LIT>']:<EOL><INDENT>ts_start = version_info['<STR_LIT>']<EOL>ts_end = ts_start + version_info['<STR_LIT>']<EOL>timestamp_data = data[ts_start:ts_end]<EOL>timestamp = unpack(<EOL>version_info['<STR_LIT>'], timestamp_data)[<NUM_LIT:0>]<EOL><DEDENT>header['<STR_LIT:info>'] = {'<STR_LIT>': timestamp}<EOL>return header<EOL>


def _remove_header(self, data, options):

version_info = self._get_version_info(options['<STR_LIT:version>'])<EOL>header_size = version_info['<STR_LIT>']<EOL>if options['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>header_size += version_info['<STR_LIT>']<EOL><DEDENT>data = data[header_size:]<EOL>return data<EOL>


version = ord(data[<NUM_LIT:0>])<EOL>if version not in self.VERSIONS:<EOL><INDENT>raise Exception('<STR_LIT>' % version)<EOL><DEDENT>return version<EOL>


return self.VERSIONS[version]<EOL>


if algorithm_info['<STR_LIT>'] not in self.ALGORITHMS:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% algorithm_info['<STR_LIT>'])<EOL><DEDENT>algorithm = self.ALGORITHMS[algorithm_info['<STR_LIT>']]<EOL>algorithm_info.update(algorithm)<EOL>return algorithm_info<EOL>


@staticmethod<EOL><INDENT>def _generate_key(pass_id, passphrases, salt, algorithm):<DEDENT>

if pass_id not in passphrases:<EOL><INDENT>raise Exception('<STR_LIT>' % pass_id)<EOL><DEDENT>passphrase = passphrases[pass_id]<EOL>if len(passphrase) < <NUM_LIT:32>:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>digestmod = EncryptedPickle._get_hashlib(algorithm['<STR_LIT>'])<EOL>encoder = PBKDF2(passphrase, salt,<EOL>iterations=algorithm['<STR_LIT>'],<EOL>digestmodule=digestmod)<EOL>return encoder.read(algorithm['<STR_LIT>'])<EOL>


@staticmethod<EOL><INDENT>def _update_dict(data, default_data, replace_data=False):<DEDENT>

if not data:<EOL><INDENT>data = default_data.copy()<EOL>return data<EOL><DEDENT>if not isinstance(data, dict):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if len(data) > <NUM_LIT:255>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for i in data.keys():<EOL><INDENT>if not isinstance(i, int):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if i < <NUM_LIT:0> or i > <NUM_LIT:255>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if not replace_data:<EOL><INDENT>data.update(default_data)<EOL><DEDENT>return data<EOL>

Update algorithm definition type dictionaries


if digestmode == '<STR_LIT>':<EOL><INDENT>return SHA<EOL><DEDENT>if digestmode == '<STR_LIT>':<EOL><INDENT>return SHA256<EOL><DEDENT>elif digestmode  == '<STR_LIT>':<EOL><INDENT>return SHA384<EOL><DEDENT>elif digestmode == '<STR_LIT>':<EOL><INDENT>return SHA512<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% digestmode)<EOL><DEDENT>


@staticmethod<EOL><INDENT>def _hmac_generate(data, algorithm, key):<DEDENT>

digestmod = EncryptedPickle._get_hashlib(algorithm['<STR_LIT>'])<EOL>return HMAC.new(key, data, digestmod).digest()<EOL>


@staticmethod<EOL><INDENT>def _aes_encrypt(data, algorithm, key):<DEDENT>

if algorithm['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>mode = AES.MODE_CBC<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% algorithm['<STR_LIT>'])<EOL><DEDENT>iv_size = algorithm['<STR_LIT>']<EOL>block_size = iv_size<EOL>include_iv = True<EOL>if '<STR_LIT>'in algorithm and algorithm['<STR_LIT>']:<EOL><INDENT>if len(algorithm['<STR_LIT>']) != algorithm['<STR_LIT>']:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>iv_value = algorithm['<STR_LIT>']<EOL>include_iv = False<EOL><DEDENT>else:<EOL><INDENT>iv_value = get_random_bytes(iv_size)<EOL><DEDENT>numpad = block_size - (len(data) % block_size)<EOL>data = data + numpad * chr(numpad)<EOL>enc = AES.new(key, mode, iv_value).encrypt(data)<EOL>if include_iv:<EOL><INDENT>enc = iv_value + enc<EOL><DEDENT>return enc<EOL>


@staticmethod<EOL><INDENT>def _aes_decrypt(data, algorithm, key):<DEDENT>

if algorithm['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>mode = AES.MODE_CBC<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% algorithm['<STR_LIT>'])<EOL><DEDENT>iv_size = algorithm['<STR_LIT>']<EOL>if '<STR_LIT>' in algorithm and algorithm['<STR_LIT>']:<EOL><INDENT>if len(algorithm['<STR_LIT>']) != algorithm['<STR_LIT>']:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>iv_value = algorithm['<STR_LIT>']<EOL>enc = data<EOL><DEDENT>else:<EOL><INDENT>iv_value = data[:iv_size]<EOL>enc = data[iv_size:]<EOL><DEDENT>dec = AES.new(key, mode, iv_value).decrypt(enc)<EOL>numpad = ord(dec[-<NUM_LIT:1>])<EOL>dec = dec[<NUM_LIT:0>:-numpad]<EOL>return dec<EOL>


if algorithm['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>encoder = zlib.compressobj(algorithm['<STR_LIT>'], zlib.DEFLATED, -<NUM_LIT:15>)<EOL>compressed = encoder.compress(data)<EOL>compressed += encoder.flush()<EOL>return compressed<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% algorithm['<STR_LIT>'])<EOL><DEDENT>


if algorithm['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return zlib.decompress(data, -<NUM_LIT:15>)<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>% algorithm['<STR_LIT>'])<EOL><DEDENT>


return urlsafe_b64encode(data).rstrip('<STR_LIT:=>')<EOL>

URL safe Base64 encode without padding (=)


padding = len(data) % <NUM_LIT:4><EOL>if padding != <NUM_LIT:0>:<EOL><INDENT>padding = <NUM_LIT:4> - padding<EOL><DEDENT>padding = '<STR_LIT:=>' * padding<EOL>data = data + padding<EOL>return urlsafe_b64decode(data)<EOL>

URL safe Base64 decode without padding (=)


if len(str_a) != len(str_b):<EOL><INDENT>return False<EOL><DEDENT>result = True<EOL>for i in range(len(str_a)):<EOL><INDENT>result &= (str_a[i] == str_b[i])<EOL><DEDENT>return result<EOL>


thisWindow = auto.GetConsoleWindow()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>auto.SendKeys('<STR_LIT>')<EOL>while not isinstance(auto.GetFocusedControl(), auto.EditControl):<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>auto.SendKeys('<STR_LIT>')<EOL>cmdWindow = auto.WindowControl(RegexName = '<STR_LIT>')<EOL>cmdWindow.TitleBarControl().RightClick()<EOL>auto.SendKey(auto.Keys.VK_P)<EOL>optionWindow = cmdWindow.WindowControl(SubName = '<STR_LIT>')<EOL>optionWindow.TabItemControl(SubName = '<STR_LIT>').Click()<EOL>optionTab = optionWindow.PaneControl(SubName = '<STR_LIT>')<EOL>checkBox = optionTab.CheckBoxControl(AutomationId = '<STR_LIT>')<EOL>if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On:<EOL><INDENT>checkBox.Click()<EOL><DEDENT>checkBox = optionTab.CheckBoxControl(AutomationId = '<STR_LIT>')<EOL>if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On:<EOL><INDENT>checkBox.Click()<EOL><DEDENT>optionWindow.TabItemControl(SubName = '<STR_LIT>').Click()<EOL>layoutTab = optionWindow.PaneControl(SubName = '<STR_LIT>')<EOL>layoutTab.EditControl(AutomationId='<STR_LIT>').GetValuePattern().SetValue('<STR_LIT>')<EOL>layoutTab.EditControl(AutomationId='<STR_LIT>').GetValuePattern().SetValue('<STR_LIT>')<EOL>layoutTab.EditControl(AutomationId='<STR_LIT>').GetValuePattern().SetValue('<STR_LIT>')<EOL>layoutTab.EditControl(AutomationId='<STR_LIT>').GetValuePattern().SetValue('<STR_LIT>')<EOL>optionWindow.ButtonControl(AutomationId = '<STR_LIT:1>').Click()<EOL>cmdWindow.SetActive()<EOL>rect = cmdWindow.BoundingRectangle<EOL>auto.DragDrop(rect.left + <NUM_LIT:50>, rect.top + <NUM_LIT:10>, <NUM_LIT:50>, <NUM_LIT:30>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>subprocess.Popen('<STR_LIT>')<EOL>notepadWindow = auto.WindowControl(searchDepth = <NUM_LIT:1>, ClassName = '<STR_LIT>')<EOL>cx, cy = auto.GetScreenSize()<EOL>notepadWindow.MoveWindow(cx // <NUM_LIT:2>, <NUM_LIT:20>, cx // <NUM_LIT:2>, cy // <NUM_LIT:2>)<EOL>time.sleep(<NUM_LIT:0.5>)<EOL>notepadWindow.EditControl().SendKeys('<STR_LIT>', <NUM_LIT>)<EOL>time.sleep(<NUM_LIT:1>)<EOL>dir = os.path.dirname(__file__)<EOL>scriptPath = os.path.abspath(os.path.join(dir, '<STR_LIT>'))<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>time.sleep(<NUM_LIT:3>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>time.sleep(<NUM_LIT:3>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>notepadWindow.SetActive()<EOL>notepadWindow.MoveCursorToMyCenter()<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SetActive(waitTime = <NUM_LIT:2>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>notepadWindow.SetActive()<EOL>notepadWindow.MoveCursorToMyCenter()<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SetActive(waitTime = <NUM_LIT:2>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>notepadWindow.SetActive()<EOL>notepadWindow.EditControl().Click()<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SetActive(waitTime = <NUM_LIT:2>)<EOL>time.sleep(<NUM_LIT:3>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.WriteLine('<STR_LIT>', auto.ConsoleColor.Green)<EOL>input()<EOL>


thisWindow = auto.GetConsoleWindow()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>auto.SendKeys('<STR_LIT>')<EOL>while not isinstance(auto.GetFocusedControl(), auto.EditControl):<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>auto.SendKeys('<STR_LIT>')<EOL>cmdWindow = auto.WindowControl(SubName = '<STR_LIT>')<EOL>rect = cmdWindow.BoundingRectangle<EOL>auto.DragDrop(rect.left + <NUM_LIT:50>, rect.top + <NUM_LIT:10>, <NUM_LIT:50>, <NUM_LIT:10>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>subprocess.Popen('<STR_LIT>')<EOL>notepadWindow = auto.WindowControl(searchDepth = <NUM_LIT:1>, ClassName = '<STR_LIT>')<EOL>cx, cy = auto.GetScreenSize()<EOL>notepadWindow.MoveWindow(cx // <NUM_LIT:2>, <NUM_LIT:20>, cx // <NUM_LIT:2>, cy // <NUM_LIT:2>)<EOL>time.sleep(<NUM_LIT:0.5>)<EOL>notepadWindow.EditControl().SendKeys('<STR_LIT>', <NUM_LIT>)<EOL>time.sleep(<NUM_LIT:1>)<EOL>dir = os.path.dirname(__file__)<EOL>scriptPath = os.path.abspath(os.path.join(dir, '<STR_LIT>'))<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>time.sleep(<NUM_LIT:3>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>time.sleep(<NUM_LIT:3>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>notepadWindow.SetActive()<EOL>notepadWindow.MoveCursorToMyCenter()<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SetActive(waitTime = <NUM_LIT:2>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>notepadWindow.SetActive()<EOL>notepadWindow.MoveCursorToMyCenter()<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SetActive(waitTime = <NUM_LIT:2>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.ColorfullyWrite('<STR_LIT>')<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SendKeys('<STR_LIT>'.format(scriptPath) + '<STR_LIT>', <NUM_LIT>)<EOL>notepadWindow.SetActive()<EOL>notepadWindow.EditControl().Click()<EOL>time.sleep(<NUM_LIT:3>)<EOL>cmdWindow.SetActive(waitTime = <NUM_LIT:2>)<EOL>time.sleep(<NUM_LIT:3>)<EOL>thisWindow.SetActive()<EOL>auto.Logger.WriteLine('<STR_LIT>', auto.ConsoleColor.Green)<EOL>input()<EOL>


<EOL>th = threading.currentThread()<EOL>auto.Logger.WriteLine('<STR_LIT>'.format(th.ident, th.name), auto.ConsoleColor.Cyan)<EOL>time.sleep(<NUM_LIT:2>)<EOL>auto.InitializeUIAutomationInCurrentThread()<EOL>auto.GetConsoleWindow().CaptureToImage('<STR_LIT>')<EOL>newRoot = auto.GetRootControl()    <EOL>auto.EnumAndLogControl(newRoot, <NUM_LIT:1>)<EOL>auto.UninitializeUIAutomationInCurrentThread()<EOL>auto.Logger.WriteLine('<STR_LIT>'.format(th.ident, th.name), auto.ConsoleColor.Cyan)<EOL>

If you want to use functionalities related to Controls and Patterns in a new thread.
You must call InitializeUIAutomationInCurrentThread first in the thread
    and call UninitializeUIAutomationInCurrentThread when the thread exits.
But you can't use use a Control or a Pattern created in a different thread.
So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it.


def SetClipboardText(text: str) -> bool:

if ctypes.windll.user32.OpenClipboard(<NUM_LIT:0>):<EOL><INDENT>ctypes.windll.user32.EmptyClipboard()<EOL>textByteLen = (len(text) + <NUM_LIT:1>) * <NUM_LIT:2><EOL>hClipboardData = ctypes.windll.kernel32.GlobalAlloc(<NUM_LIT:0>, textByteLen)  <EOL>hDestText = ctypes.windll.kernel32.GlobalLock(hClipboardData)<EOL>ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), textByteLen // <NUM_LIT:2>)<EOL>ctypes.windll.kernel32.GlobalUnlock(hClipboardData)<EOL>ctypes.windll.user32.SetClipboardData(<NUM_LIT>, hClipboardData)  <EOL>ctypes.windll.user32.CloseClipboard()<EOL>return True<EOL><DEDENT>return False<EOL>

Return bool, True if succeed otherwise False.


def SetConsoleColor(color: int) -> bool:

global _ConsoleOutputHandle<EOL>global _DefaultConsoleColor<EOL>if not _DefaultConsoleColor:<EOL><INDENT>if not _ConsoleOutputHandle:<EOL><INDENT>_ConsoleOutputHandle = ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle)<EOL><DEDENT>bufferInfo = ConsoleScreenBufferInfo()<EOL>ctypes.windll.kernel32.GetConsoleScreenBufferInfo(_ConsoleOutputHandle, ctypes.byref(bufferInfo))<EOL>_DefaultConsoleColor = int(bufferInfo.wAttributes & <NUM_LIT>)<EOL><DEDENT>if sys.stdout:<EOL><INDENT>sys.stdout.flush()<EOL><DEDENT>bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, color))<EOL>

Change the text color on console window.
color: int, a value in class `ConsoleColor`.
Return bool, True if succeed otherwise False.


if sys.stdout:<EOL><INDENT>sys.stdout.flush()<EOL><DEDENT>bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))<EOL>

Reset to the default text color on console window.
Return bool, True if succeed otherwise False.