if self.get_resource_endpoint() is not None:<EOL><INDENT>return self.send(self.get_resource_endpoint(), "<STR_LIT>")<EOL><DEDENT>

Refreshes a resource by checking against the API
:return:


self.client = auth_client<EOL>

Initializes the instance
:param auth_client: Client to make (non)authorized requests
:return:


def send(self, relative_path, http_method, **requests_args):

url = urljoin(self.base_url, relative_path)<EOL>return self.session.request(http_method, url, **requests_args)<EOL>

Subclasses must implement this method, that will be used to send API requests with proper auth
:param relative_path: URL path relative to self.base_url
:param http_method: HTTP method
:param requests_args: kargs to be sent to requests
:return:


self.many = many<EOL>self.name = None<EOL>

Initialize the field
:param many: Set to True if this field will host a list of items


if instance is not None and self.name is not None:<EOL><INDENT>return instance.__dict__.get(self.name)<EOL><DEDENT>else:<EOL><INDENT>return self<EOL><DEDENT>

Normal descriptor get method
:param instance: Resource instance where the field lives
:param instance: Resource class where the field lives
:return: Value stored in instance.name (TODO: maybe change this in the future to instance.Cache.name)


if instance is not None and self.name is not None:<EOL><INDENT>instance.__dict__[self.name] = value<EOL><DEDENT>

Normal descriptor set method
:param instance: Resource instance where the field lives
:param value: Value to store in instance.name (TODO: maybe change this in the future to instance.Cache.name)


if self.many is False:<EOL><INDENT>if isinstance(value, str):<EOL><INDENT>value = parse(value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>datetime_list = []<EOL>for datetime_value in value:<EOL><INDENT>if isinstance(datetime_value, str):<EOL><INDENT>datetime_value = parse(datetime_value)<EOL><DEDENT>datetime_list.append(datetime_value)<EOL><DEDENT>value = datetime_list<EOL><DEDENT>super(DateTimeField, self).__set__(instance, value)<EOL>

Normal descriptor set method
:param instance: Resource instance where the field lives
:param value: Might be a datetime object or a string to be parsed


contents = read_file(os.path.join('<STR_LIT>', '<STR_LIT>'))<EOL>version = re.search('<STR_LIT>', contents)<EOL>version = version.group(<NUM_LIT:1>).replace('<STR_LIT:U+002CU+0020>', '<STR_LIT:.>').strip()<EOL>return version<EOL>

Returns version number, without module import (which can lead to ImportError
    if some dependencies are unavailable before install.


def __init__(<EOL>self, name, default, category=None, field=None, verbose_name=None, help_text='<STR_LIT>', static=True,<EOL>readonly=False):

self.name = name<EOL>self.category = category<EOL>self.default = default<EOL>self.static = static<EOL>self.help_text = help_text<EOL>if static:<EOL><INDENT>readonly = True<EOL><DEDENT>self.readonly = readonly<EOL>if verbose_name is None:<EOL><INDENT>verbose_name = name.replace('<STR_LIT:_>', '<STR_LIT:U+0020>').capitalize()<EOL><DEDENT>self.verbose_name = verbose_name<EOL>if field is None:<EOL><INDENT>self.field = get_field_for_proxy(self)<EOL><DEDENT>else:<EOL><INDENT>self.field = field<EOL>update_field_from_proxy(self.field, self)<EOL><DEDENT>

:param str|unicode name: Preference name.

:param default: Default (initial) value.

:param str|unicode category: Category name the preference belongs to.

:param Field field: Django model field to represent this preference.

:param str|unicode verbose_name: Field verbose name.

:param str|unicode help_text: Field help text.

:param bool static: Leave this preference static (do not store in DB).

:param bool readonly: Make this field read only.


attr_names = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:default>')<EOL>for attr_name in attr_names:<EOL><INDENT>setattr(field_obj, attr_name, getattr(pref_proxy, attr_name))<EOL><DEDENT>

Updates field object with data from a PrefProxy object.

    :param models.Field field_obj:

    :param PrefProxy pref_proxy:


locals_dict = get_frame_locals(stepback+<NUM_LIT:1>)<EOL>for k in locals_dict:<EOL><INDENT>if not k.startswith('<STR_LIT:_>') and k.upper() == k:<EOL><INDENT>yield k, locals_dict<EOL><DEDENT><DEDENT>

Generator to walk through variables considered as preferences
    in locals dict of a given frame.

    :param int stepback:

    :rtype: tuple


db_prefs = {<EOL>'<STR_LIT>' % (pref['<STR_LIT>'], pref['<STR_LIT:name>']): pref for pref in<EOL>cls.objects.values().order_by('<STR_LIT>', '<STR_LIT:name>')<EOL>}<EOL>new_prefs = []<EOL>for app, prefs in mem_prefs.items():<EOL><INDENT>for pref_name, pref_proxy in prefs.items():<EOL><INDENT>if not pref_proxy.static:  <EOL><INDENT>key = '<STR_LIT>' % (app, pref_name)<EOL>if key in db_prefs:<EOL><INDENT>pref_proxy.db_value = db_prefs[key]['<STR_LIT:text>']<EOL><DEDENT>else:<EOL><INDENT>new_prefs.append(cls(app=app, name=pref_name, text=pref_proxy.default))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if new_prefs:<EOL><INDENT>try:<EOL><INDENT>cls.objects.bulk_create(new_prefs)<EOL><DEDENT>except IntegrityError:  <EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Initializes preferences entries in DB according to currently discovered prefs.

        :param dict mem_prefs:


def bind_proxy(values, category=None, field=None, verbose_name=None, help_text='<STR_LIT>', static=True, readonly=False):

addrs = OrderedDict()<EOL>depth = <NUM_LIT:3><EOL>for local_name, locals_dict in traverse_local_prefs(depth):<EOL><INDENT>addrs[id(locals_dict[local_name])] = local_name<EOL><DEDENT>proxies = []<EOL>locals_dict = get_frame_locals(depth)<EOL>for value in values:  <EOL><INDENT>id_val = id(value)<EOL>if id_val in addrs:<EOL><INDENT>local_name = addrs[id_val]<EOL>local_val = locals_dict[local_name]<EOL>if isinstance(local_val, PatchedLocal) and not isinstance(local_val, PrefProxy):<EOL><INDENT>proxy = PrefProxy(<EOL>local_name, value.val,<EOL>category=category,<EOL>field=field,<EOL>verbose_name=verbose_name,<EOL>help_text=help_text,<EOL>static=static,<EOL>readonly=readonly,<EOL>)<EOL>app_name = locals_dict['<STR_LIT>'].split('<STR_LIT:.>')[-<NUM_LIT:2>]  <EOL>prefs = get_prefs()<EOL>if app_name not in prefs:<EOL><INDENT>prefs[app_name] = OrderedDict()<EOL><DEDENT>prefs[app_name][local_name.lower()] = proxy<EOL>locals_dict[local_name] = proxy<EOL>proxies.append(proxy)<EOL><DEDENT><DEDENT><DEDENT>return proxies<EOL>

Binds PrefProxy objects to module variables used by apps as preferences.

    :param list|tuple values: Preference values.

    :param str|unicode category: Category name the preference belongs to.

    :param Field field: Django model field to represent this preference.

    :param str|unicode verbose_name: Field verbose name.

    :param str|unicode help_text: Field help text.

    :param bool static: Leave this preference static (do not store in DB).

    :param bool readonly: Make this field read only.

    :rtype: list


swap_settings_module = bool(kwargs.get('<STR_LIT>', True))<EOL>if __PATCHED_LOCALS_SENTINEL not in get_frame_locals(<NUM_LIT:2>):<EOL><INDENT>raise SitePrefsException('<STR_LIT>')<EOL><DEDENT>bind_proxy(args, **kwargs)<EOL>unpatch_locals()<EOL>swap_settings_module and proxy_settings_module()<EOL>

Registers preferences that should be handled by siteprefs.

    Expects preferences as *args.

    Use keyword arguments to batch apply params supported by
    ``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.

    Batch kwargs:

        :param str|unicode help_text: Field help text.

        :param bool static: Leave this preference static (do not store in DB).

        :param bool readonly: Make this field read only.

    :param bool swap_settings_module: Whether to automatically replace settings module
        with a special ``ProxyModule`` object to access dynamic values of settings
        transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object).


if admin_site is None:<EOL><INDENT>admin_site = admin.site<EOL><DEDENT>if '<STR_LIT>' not in sys.argv[<NUM_LIT:0>] or (len(sys.argv) > <NUM_LIT:1> and sys.argv[<NUM_LIT:1>] in MANAGE_SAFE_COMMANDS):<EOL><INDENT>import_prefs()<EOL>Preference.read_prefs(get_prefs())<EOL>register_admin_models(admin_site)<EOL><DEDENT>

Automatically discovers and registers all preferences available in all apps.

    :param admin.AdminSite admin_site: Custom AdminSite object.


Preference.update_prefs(*args, **kwargs)<EOL>Preference.read_prefs(get_prefs())<EOL>

Triggered on dynamic preferences model save.
     Issues DB save and reread.


for name, locals_dict in traverse_local_prefs(depth):<EOL><INDENT>locals_dict[name] = PatchedLocal(name, locals_dict[name])<EOL><DEDENT>get_frame_locals(depth)[__PATCHED_LOCALS_SENTINEL] = True<EOL>

Temporarily (see unpatch_locals()) replaces all module variables
    considered preferences with PatchedLocal objects, so that every
    variable has different hash returned by id().


proxies = []<EOL>modules = sys.modules<EOL>module_name = get_frame_locals(depth)['<STR_LIT>']<EOL>module_real = modules[module_name]<EOL>for name, locals_dict in traverse_local_prefs(depth):<EOL><INDENT>value = locals_dict[name]<EOL>if isinstance(value, PrefProxy):<EOL><INDENT>proxies.append(name)<EOL><DEDENT><DEDENT>new_module = type(module_name, (ModuleType, ModuleProxy), {})(module_name)  <EOL>new_module.bind(module_real, proxies)<EOL>modules[module_name] = new_module<EOL>

Replaces a settings module with a Module proxy to intercept
    an access to settings.

    :param int depth: Frame count to go backward.


return sum([self.scores[len(w)] for w in self.words()])<EOL>

The total score for the words found, according to the rules.


return [self.child_node(problem, action)<EOL>for action in problem.actions(self.state)]<EOL>

List the nodes reachable in one step from this node.


h = memoize(h or problem.h, '<STR_LIT:h>')<EOL>def RBFS(problem, node, flimit):<EOL><INDENT>if problem.goal_test(node.state):<EOL><INDENT>return node, <NUM_LIT:0>   <EOL><DEDENT>successors = node.expand(problem)<EOL>if len(successors) == <NUM_LIT:0>:<EOL><INDENT>return None, infinity<EOL><DEDENT>for s in successors:<EOL><INDENT>s.f = max(s.path_cost + h(s), node.f)<EOL><DEDENT>while True:<EOL><INDENT>successors.sort(lambda x,y: cmp(x.f, y.f)) <EOL>best = successors[<NUM_LIT:0>]<EOL>if best.f > flimit:<EOL><INDENT>return None, best.f<EOL><DEDENT>if len(successors) > <NUM_LIT:1>:<EOL><INDENT>alternative = successors[<NUM_LIT:1>].f<EOL><DEDENT>else:<EOL><INDENT>alternative = infinity<EOL><DEDENT>result, best.f = RBFS(problem, best, min(flimit, alternative))<EOL>if result is not None:<EOL><INDENT>return result, best.f<EOL><DEDENT><DEDENT><DEDENT>node = Node(problem.initial)<EOL>node.f = h(node)<EOL>result, bestf = RBFS(problem, node, infinity)<EOL>return result<EOL>


def boggle_hill_climbing(board=None, ntimes=<NUM_LIT:100>, verbose=True):

finder = BoggleFinder()<EOL>if board is None:<EOL><INDENT>board = random_boggle()<EOL><DEDENT>best = len(finder.set_board(board))<EOL>for _ in range(ntimes):<EOL><INDENT>i, oldc = mutate_boggle(board)<EOL>new = len(finder.set_board(board))<EOL>if new > best:<EOL><INDENT>best = new<EOL>if verbose: print(best, _, board)<EOL><DEDENT>else:<EOL><INDENT>board[i] = oldc <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print_boggle(board)<EOL><DEDENT>return board, best<EOL>

Solve inverse Boggle by hill-climbing: find a high-scoring board by
    starting with a random one and changing it.


c = random.randrange(len(self.genes))<EOL>return self.__class__(self.genes[:c] + other.genes[c:])<EOL>

Return a new individual crossing self and other.


return list(self.dict.keys())<EOL>


unimplemented()<EOL>


def RandomGraph(nodes=list(range(<NUM_LIT:10>)), min_links=<NUM_LIT:2>, width=<NUM_LIT>, height=<NUM_LIT>,<EOL>curvature=lambda: random.uniform(<NUM_LIT>, <NUM_LIT>)):

g = UndirectedGraph()<EOL>g.locations = {}<EOL>for node in nodes:<EOL><INDENT>g.locations[node] = (random.randrange(width), random.randrange(height))<EOL><DEDENT>for i in range(min_links):<EOL><INDENT>for node in nodes:<EOL><INDENT>if len(g.get(node)) < min_links:<EOL><INDENT>here = g.locations[node]<EOL>def distance_to_node(n):<EOL><INDENT>if n is node or g.get(node,n): return infinity<EOL>return distance(g.locations[n], here)<EOL><DEDENT>neighbor = argmin(nodes, distance_to_node)<EOL>d = distance(g.locations[neighbor], here) * curvature()<EOL>g.connect(node, neighbor, int(d))<EOL><DEDENT><DEDENT><DEDENT>return g<EOL>

Construct a random graph, with the specified nodes, and random links.
    The nodes are laid out randomly on a (width x height) rectangle.
    Then each node is connected to the min_links nearest neighbors.
    Because inverse links are added, some nodes will have more connections.
    The distance between nodes is the hypotenuse times curvature(),
    where curvature() defaults to a random number between 1.1 and 1.5.


compare_searchers(problems=[GraphProblem('<STR_LIT:A>', '<STR_LIT:B>', romania),<EOL>GraphProblem('<STR_LIT:O>', '<STR_LIT:N>', romania),<EOL>GraphProblem('<STR_LIT>', '<STR_LIT>', australia)],<EOL>header=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>


if cache.get(n2):<EOL><INDENT>return cache.get(n2)<EOL><DEDENT>n = exact_sqrt(n2)<EOL>neighbors = [None] * n2<EOL>for i in range(n2):<EOL><INDENT>neighbors[i] = []<EOL>on_top = i < n<EOL>on_bottom = i >= n2 - n<EOL>on_left = i % n == <NUM_LIT:0><EOL>on_right = (i+<NUM_LIT:1>) % n == <NUM_LIT:0><EOL>if not on_top:<EOL><INDENT>neighbors[i].append(i - n)<EOL>if not on_left:  neighbors[i].append(i - n - <NUM_LIT:1>)<EOL>if not on_right: neighbors[i].append(i - n + <NUM_LIT:1>)<EOL><DEDENT>if not on_bottom:<EOL><INDENT>neighbors[i].append(i + n)<EOL>if not on_left:  neighbors[i].append(i + n - <NUM_LIT:1>)<EOL>if not on_right: neighbors[i].append(i + n + <NUM_LIT:1>)<EOL><DEDENT>if not on_left: neighbors[i].append(i - <NUM_LIT:1>)<EOL>if not on_right: neighbors[i].append(i + <NUM_LIT:1>)<EOL><DEDENT>cache[n2] = neighbors<EOL>return neighbors<EOL>

Return a list of lists, where the i-th element is the list of indexes
    for the neighbors of square i.


return tree_search(problem, Stack())<EOL>

Search the deepest nodes in the search tree first.


abstract<EOL>

For optimization problems, each state has a value.  Hill-climbing
        and related algorithms try to maximize this value.


current = Node(problem.initial)<EOL>while True:<EOL><INDENT>neighbors = current.expand(problem)<EOL>if not neighbors:<EOL><INDENT>break<EOL><DEDENT>neighbor = argmax_random_tie(neighbors,<EOL>lambda node: problem.value(node.state))<EOL>if problem.value(neighbor.state) <= problem.value(current.state):<EOL><INDENT>break<EOL><DEDENT>current = neighbor<EOL><DEDENT>return current.state<EOL>

From the initial node, keep choosing the neighbor with highest value,
    stopping when no neighbor is better. [Fig. 4.2]


self.initial = initial; self.goal = goal<EOL>

The constructor specifies the initial state, and possibly a goal
        state, if there is a unique goal.  Your subclass's constructor can add
        other arguments.


return len(self.found)<EOL>


return tree_search(problem, FIFOQueue())<EOL>

Search the shallowest nodes in the search tree first.


def connect(self, A, B, distance=<NUM_LIT:1>):

self.connect1(A, B, distance)<EOL>if not self.directed: self.connect1(B, A, distance)<EOL>

Add a link from A and B of given distance, and also add the inverse
        link if the graph is undirected.


col = state.index(None)<EOL>new = state[:]<EOL>new[col] = row<EOL>return new<EOL>


return Graph(dict=dict, directed=False)<EOL>

Build a Graph where every edge (including future ones) goes both ways.


frontier.append(Node(problem.initial))<EOL>explored = set()<EOL>while frontier:<EOL><INDENT>node = frontier.pop()<EOL>if problem.goal_test(node.state):<EOL><INDENT>return node<EOL><DEDENT>explored.add(node.state)<EOL>frontier.extend(child for child in node.expand(problem)<EOL>if child.state not in explored<EOL>and child not in frontier)<EOL><DEDENT>return None<EOL>

Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    If two paths reach a state, only use the first one. [Fig. 3.7]


def lookup(self, prefix, lo=<NUM_LIT:0>, hi=None):

words = self.words<EOL>if hi is None: hi = len(words)<EOL>i = bisect.bisect_left(words, prefix, lo, hi)<EOL>if i < len(words) and words[i].startswith(prefix):<EOL><INDENT>return i, (words[i] == prefix)<EOL><DEDENT>else:<EOL><INDENT>return None, False<EOL><DEDENT>

See if prefix is in dictionary, as a full word or as a prefix.
        Return two values: the first is the lowest i such that
        words[i].startswith(prefix), or is None; the second is
        True iff prefix itself is in the Wordlist.


abstract<EOL>


def genetic_search(problem, fitness_fn, ngen=<NUM_LIT:1000>, pmut=<NUM_LIT:0.1>, n=<NUM_LIT:20>):

s = problem.initial_state<EOL>states = [problem.result(s, a) for a in problem.actions(s)]<EOL>random.shuffle(states)<EOL>return genetic_algorithm(states[:n], problem.value, ngen, pmut)<EOL>

Call genetic_algorithm on the appropriate parts of a problem.
    This requires the problem to have states that can mate and mutate,
    plus a value method that scores states.


next = problem.result(self.state, action)<EOL>return Node(next, self, action,<EOL>problem.path_cost(self.path_cost, self.state, action, next))<EOL>


def recursive_dls(node, problem, limit):<EOL><INDENT>if problem.goal_test(node.state):<EOL><INDENT>return node<EOL><DEDENT>elif node.depth == limit:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>cutoff_occurred = False<EOL>for child in node.expand(problem):<EOL><INDENT>result = recursive_dls(child, problem, limit)<EOL>if result == '<STR_LIT>':<EOL><INDENT>cutoff_occurred = True<EOL><DEDENT>elif result is not None:<EOL><INDENT>return result<EOL><DEDENT><DEDENT>return if_(cutoff_occurred, '<STR_LIT>', None)<EOL><DEDENT><DEDENT>return recursive_dls(Node(problem.initial), problem, limit)<EOL>


def path_cost(self, c, state1, action, state2):

return c + <NUM_LIT:1><EOL>

Return the cost of a solution path that arrives at state2 from
        state1 via action, assuming cost c to get up to state1. If the problem
        is such that the path doesn't matter, this function will only look at
        state2.  If the path does matter, it will consider c and maybe state1
        and action. The default method costs 1 for every step in the path.


current = Node(problem.initial)<EOL>for t in range(sys.maxsize):<EOL><INDENT>T = schedule(t)<EOL>if T == <NUM_LIT:0>:<EOL><INDENT>return current<EOL><DEDENT>neighbors = current.expand(problem)<EOL>if not neighbors:<EOL><INDENT>return current<EOL><DEDENT>next = random.choice(neighbors)<EOL>delta_e = problem.value(next.state) - problem.value(current.state)<EOL>if delta_e > <NUM_LIT:0> or probability(math.exp(delta_e/T)):<EOL><INDENT>current = next<EOL><DEDENT><DEDENT>


def program(percept):<EOL><INDENT>program.state = update_state(program.state, program.action, percept)<EOL>rule = rule_match(program.state, rules)<EOL>action = rule.action<EOL>return action<EOL><DEDENT>program.state = program.action = None<EOL>return program<EOL>

This agent takes action based on the percept and state. [Fig. 2.12]


return (agent.location, self.status[agent.location])<EOL>

Returns the agent's location, and the location status (Dirty/Clean).


table = {((loc_A, '<STR_LIT>'),): '<STR_LIT>',<EOL>((loc_A, '<STR_LIT>'),): '<STR_LIT>',<EOL>((loc_B, '<STR_LIT>'),): '<STR_LIT>',<EOL>((loc_B, '<STR_LIT>'),): '<STR_LIT>',<EOL>((loc_A, '<STR_LIT>'), (loc_A, '<STR_LIT>')): '<STR_LIT>',<EOL>((loc_A, '<STR_LIT>'), (loc_A, '<STR_LIT>')): '<STR_LIT>',<EOL>((loc_A, '<STR_LIT>'), (loc_A, '<STR_LIT>'), (loc_A, '<STR_LIT>')): '<STR_LIT>',<EOL>((loc_A, '<STR_LIT>'), (loc_A, '<STR_LIT>'), (loc_A, '<STR_LIT>')): '<STR_LIT>',<EOL>}<EOL>return Agent(TableDrivenAgentProgram(table))<EOL>


try:<EOL><INDENT>self.things.remove(thing)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>print(e)<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>" % (thing, thing.location))<EOL>print("<STR_LIT>" % [(thing, thing.location)<EOL>for thing in self.things])<EOL><DEDENT>if thing in self.agents:<EOL><INDENT>self.agents.remove(thing)<EOL><DEDENT>


return lambda percept: random.choice(actions)<EOL>

An agent that chooses an action at random, ignoring all percepts.


def list_things_at(self, location, tclass=Thing):

return [thing for thing in self.things<EOL>if thing.location == location and isinstance(thing, tclass)]<EOL>

Return all things exactly at a given location.


for step in range(steps):<EOL><INDENT>if self.is_done(): return<EOL>self.step()<EOL><DEDENT>

Run the Environment for given number of time steps.


def execute_action(self, agent, action):

if action == '<STR_LIT>':<EOL><INDENT>agent.location = loc_B<EOL>agent.performance -= <NUM_LIT:1><EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>agent.location = loc_A<EOL>agent.performance -= <NUM_LIT:1><EOL><DEDENT>elif action == '<STR_LIT>':<EOL><INDENT>if self.status[agent.location] == '<STR_LIT>':<EOL><INDENT>agent.performance += <NUM_LIT:10><EOL><DEDENT>self.status[agent.location] = '<STR_LIT>'<EOL><DEDENT>

Change agent's location and/or location's status; track performance.
        Score 10 for each dirt cleaned; -1 for each move.


return turn_heading(heading, inc)<EOL>

Return the heading to the left (inc=+1) or right (inc=-1) of heading.


for rule in rules:<EOL><INDENT>if rule.matches(state):<EOL><INDENT>return rule<EOL><DEDENT><DEDENT>


return None<EOL>

Default location to place a new thing with unspecified location.


for x in range(self.width):<EOL><INDENT>self.add_thing(Wall(), (x, <NUM_LIT:0>))<EOL>self.add_thing(Wall(), (x, self.height-<NUM_LIT:1>))<EOL><DEDENT>for y in range(self.height):<EOL><INDENT>self.add_thing(Wall(), (<NUM_LIT:0>, y))<EOL>self.add_thing(Wall(), (self.width-<NUM_LIT:1>, y))<EOL><DEDENT>

Put walls around the entire perimeter of the grid.


def program(percept):<EOL><INDENT>state = interpret_input(percept)<EOL>rule = rule_match(state, rules)<EOL>action = rule.action<EOL>return action<EOL><DEDENT>return program<EOL>

This agent takes action based solely on the percept. [Fig. 2.10]


return Agent(RandomAgentProgram(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']))<EOL>

Randomly choose one of the actions from the vacuum environment.


thing.bump = self.some_things_at(destination, Obstacle)<EOL>if not thing.bump:<EOL><INDENT>thing.location = destination<EOL>for o in self.observers:<EOL><INDENT>o.thing_moved(thing)<EOL><DEDENT><DEDENT>


return False<EOL>

Returns True if this agent can grab this thing.
        Override for appropriate subclasses of Agent and Thing.


def add_thing(self, thing, location=None):

if not isinstance(thing, Thing):<EOL><INDENT>thing = Agent(thing)<EOL><DEDENT>assert thing not in self.things, "<STR_LIT>"<EOL>thing.location = location or self.default_location(thing)<EOL>self.things.append(thing)<EOL>if isinstance(thing, Agent):<EOL><INDENT>thing.performance = <NUM_LIT:0><EOL>self.agents.append(thing)<EOL><DEDENT>

Add a thing to the environment, setting its location. For
        convenience, if thing is an agent program we make a new agent
        for it. (Shouldn't need to override this.


for (score, d) in results:<EOL><INDENT>doc = self.documents[d]<EOL>print ("<STR_LIT>"<EOL>% (<NUM_LIT:100> * score, doc.url, doc.title[:<NUM_LIT>].expandtabs()))<EOL><DEDENT>


return [shift_encode(text, n) for n in range(len(alphabet))]<EOL>

Return a list of all 26 possible encodings of text by a shift cipher.


<EOL>return (math.log(<NUM_LIT:1> + self.index[word][docid])<EOL>/ math.log(<NUM_LIT:1> + self.documents[docid].nwords))<EOL>

Compute a score for this word on this docid.


s = <NUM_LIT:1.0><EOL>for bi in bigrams(plaintext):<EOL><INDENT>s = s * self.P2[bi]<EOL><DEDENT>return s<EOL>

Return a score for text based on how common letters pairs are.


for filename in filenames:<EOL><INDENT>self.index_document(open(filename).read(), filename)<EOL><DEDENT>


return reg.findall(text.lower())<EOL>

Return a list of the words in text, ignoring punctuation and
    converting everything to lowercase (to canonicalize).
    >>> words("``EGAD!'' Edgar cried.")
    ['egad', 'edgar', 'cried']


CountingProbDist.add(self, ngram)<EOL>self.cond_prob[ngram[:-<NUM_LIT:1>]].add(ngram[-<NUM_LIT:1>])<EOL>

Count 1 for P[(w1, ..., wn)] and for P(wn | (w1, ..., wn-1)


n = self.n<EOL>words = ['<STR_LIT>',] * (n-<NUM_LIT:1>) + words<EOL>for i in range(len(words)-n):<EOL><INDENT>self.add(tuple(words[i:i+n]))<EOL><DEDENT>

Add each of the tuple words[i:i+n], using a sliding window.
        Prefix some copies of the empty word, '', to make the start work.


<EOL>update(self, index=DefaultDict(DefaultDict(<NUM_LIT:0>)),<EOL>stopwords=set(words(stopwords)), documents=[])<EOL>

Create an IR System. Optionally specify stopwords.


<EOL>n = len(text)<EOL>words = ['<STR_LIT>'] + list(text)<EOL>best = [<NUM_LIT:1.0>] + [<NUM_LIT:0.0>] * n<EOL>for i in range(n+<NUM_LIT:1>):<EOL><INDENT>for j in range(<NUM_LIT:0>, i):<EOL><INDENT>w = text[j:i]<EOL>if P[w] * best[i - len(w)] >= best[i]:<EOL><INDENT>best[i] = P[w] * best[i - len(w)]<EOL>words[i] = w<EOL><DEDENT><DEDENT><DEDENT>sequence = []; i = len(words)-<NUM_LIT:1><EOL>while i > <NUM_LIT:0>:<EOL><INDENT>sequence[<NUM_LIT:0>:<NUM_LIT:0>] = [words[i]]<EOL>i = i - len(words[i])<EOL><DEDENT>return sequence, best[-<NUM_LIT:1>]<EOL>

Find the best segmentation of the string of characters, given the
    UnigramTextModel P.


pi = {}<EOL>for s in mdp.states:<EOL><INDENT>pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp))<EOL><DEDENT>return pi<EOL>

Given an MDP and a utility function U, determine the best policy,
    as a mapping from state to action. (Equation 17.4)


abstract<EOL>

Transition model.  From a state and an action, return a list
        of (probability, result-state) pairs.


U1 = dict([(s, <NUM_LIT:0>) for s in mdp.states])<EOL>R, T, gamma = mdp.R, mdp.T, mdp.gamma<EOL>while True:<EOL><INDENT>U = U1.copy()<EOL>delta = <NUM_LIT:0><EOL>for s in mdp.states:<EOL><INDENT>U1[s] = R(s) + gamma * max([sum([p * U[s1] for (p, s1) in T(s, a)])<EOL>for a in mdp.actions(s)])<EOL>delta = max(delta, abs(U1[s] - U[s]))<EOL><DEDENT>if delta < epsilon * (<NUM_LIT:1> - gamma) / gamma:<EOL><INDENT>return U<EOL><DEDENT><DEDENT>

Solving an MDP by value iteration. [Fig. 17.4]


def policy_evaluation(pi, U, mdp, k=<NUM_LIT:20>):

R, T, gamma = mdp.R, mdp.T, mdp.gamma<EOL>for i in range(k):<EOL><INDENT>for s in mdp.states:<EOL><INDENT>U[s] = R(s) + gamma * sum([p * U[s1] for (p, s1) in T(s, pi[s])])<EOL><DEDENT><DEDENT>return U<EOL>

Return an updated utility mapping U from each state in the MDP to its
    utility, using an approximation (modified policy iteration).


def predict(example):<EOL><INDENT>return weighted_mode((predictor(example) for predictor in predictors),<EOL>weights)<EOL><DEDENT>return predict<EOL>

Return a predictor that takes a weighted vote.


def setproblem(self, target, inputs=None, exclude=()):

self.target = self.attrnum(target)<EOL>exclude = list(map(self.attrnum, exclude))<EOL>if inputs:<EOL><INDENT>self.inputs = removeall(self.target, inputs)<EOL><DEDENT>else:<EOL><INDENT>self.inputs = [a for a in self.attrs<EOL>if a != self.target and a not in exclude]<EOL><DEDENT>if not self.values:<EOL><INDENT>self.values = list(map(unique, list(zip(*self.examples))))<EOL><DEDENT>self.check_me()<EOL>

Set (or change) the target and/or inputs.
        This way, one DataSet can be used multiple ways. inputs, if specified,
        is a list of attributes, or specify exclude as a list of attributes
        to not use in inputs. Attributes can be -n .. n, or an attrname.
        Also computes the list of possible values, if that wasn't done yet.


def replicated_dataset(dataset, weights, n=None):

n = n or len(dataset.examples)<EOL>result = copy.copy(dataset)<EOL>result.examples = weighted_replicate(dataset.examples, weights, n)<EOL>return result<EOL>

Copy dataset, replicating each example in proportion to its weight.


def decision_list_learning(examples):<EOL><INDENT>if not examples:<EOL><INDENT>return [(True, False)]<EOL><DEDENT>t, o, examples_t = find_examples(examples)<EOL>if not t:<EOL><INDENT>raise Failure<EOL><DEDENT>return [(t, o)] + decision_list_learning(examples - examples_t)<EOL><DEDENT>def find_examples(examples):<EOL><INDENT>"""<STR_LIT>"""<EOL>unimplemented()<EOL><DEDENT>def passes(example, test):<EOL><INDENT>"<STR_LIT>"<EOL>unimplemented()<EOL><DEDENT>def predict(example):<EOL><INDENT>"<STR_LIT>"<EOL>for test, outcome in predict.decision_list:<EOL><INDENT>if passes(example, test):<EOL><INDENT>return outcome<EOL><DEDENT><DEDENT><DEDENT>predict.decision_list = decision_list_learning(set(dataset.examples))<EOL>return predict<EOL>


def train(dataset):<EOL><INDENT>predictors = [learner(dataset) for learner in learners]<EOL>def predict(example):<EOL><INDENT>return mode(predictor(example) for predictor in predictors)<EOL><DEDENT>return predict<EOL><DEDENT>return train<EOL>

Given a list of learning algorithms, have them vote.


totals = defaultdict(int)<EOL>for v, w in zip(values, weights):<EOL><INDENT>totals[v] += w<EOL><DEDENT>return max(list(totals.keys()), key=totals.get)<EOL>

Return the value with the greatest total weight.
    >>> weighted_mode('abbaa', [1,2,3,1,2])
    'b


def train(dataset, weights):<EOL><INDENT>return unweighted_learner(replicated_dataset(dataset, weights))<EOL><DEDENT>return train<EOL>

Given a learner that takes just an unweighted dataset, return
    one that takes also a weight for each example. [p. 749 footnote 14]


targetvals = dataset.values[dataset.target]<EOL>target_dist = CountingProbDist(targetvals)<EOL>attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr]))<EOL>for gv in targetvals<EOL>for attr in dataset.inputs)<EOL>for example in dataset.examples:<EOL><INDENT>targetval = example[dataset.target]<EOL>target_dist.add(targetval)<EOL>for attr in dataset.inputs:<EOL><INDENT>attr_dists[targetval, attr].add(example[attr])<EOL><DEDENT><DEDENT>def predict(example):<EOL><INDENT>"""<STR_LIT>"""<EOL>def class_probability(targetval):<EOL><INDENT>return (target_dist[targetval]<EOL>* product(attr_dists[targetval, attr][example[attr]]<EOL>for attr in dataset.inputs))<EOL><DEDENT>return argmax(targetvals, class_probability)<EOL><DEDENT>return predict<EOL>

Just count how many times each value of each input attribute
    occurs, conditional on the target value. Count the different
    target values too.


self.smooth_for(o)<EOL>self.dictionary[o] += <NUM_LIT:1><EOL>self.n_obs += <NUM_LIT:1><EOL>self.sampler = None<EOL>

Add an observation o to the distribution.


def train(dataset):<EOL><INDENT>examples, target = dataset.examples, dataset.target<EOL>N = len(examples)<EOL>epsilon = <NUM_LIT:1.>/(<NUM_LIT:2>*N)<EOL>w = [<NUM_LIT:1.>/N] * N<EOL>h, z = [], []<EOL>for k in range(K):<EOL><INDENT>h_k = L(dataset, w)<EOL>h.append(h_k)<EOL>error = sum(weight for example, weight in zip(examples, w)<EOL>if example[target] != h_k(example))<EOL>error = clip(error, epsilon, <NUM_LIT:1>-epsilon)<EOL>for j, example in enumerate(examples):<EOL><INDENT>if example[target] == h_k(example):<EOL><INDENT>w[j] *= error / (<NUM_LIT:1.> - error)<EOL><DEDENT><DEDENT>w = normalize(w)<EOL>z.append(math.log((<NUM_LIT:1.> - error) / error))<EOL><DEDENT>return WeightedMajority(h, z)<EOL><DEDENT>return train<EOL>


if attr < <NUM_LIT:0>:<EOL><INDENT>return len(self.attrs) + attr<EOL><DEDENT>elif isinstance(attr, str):<EOL><INDENT>return self.attrnames.index(attr)<EOL><DEDENT>else:<EOL><INDENT>return attr<EOL><DEDENT>

Returns the number used for attr, which can be a name, or -n .. n-1.


self.check_example(example)<EOL>self.examples.append(example)<EOL>

Add an example to the list of examples, checking it first.


lines = [line for line in input.splitlines() if line.strip()]<EOL>return [list(map(num_or_str, line.split(delim))) for line in lines]<EOL>

r"""Input is a string consisting of lines, each line has comma-delimited
    fields.  Convert this into a list of lists.  Blank lines are skipped.
    Fields that look like numbers are converted to numbers.
    The delim defaults to ',' but '\t' and None are also reasonable values.
    >>> parse_csv('1, 2, 3 \n 0, 2, na')
    [[1, 2, 3], [0, 2, 'na']]


return Parity(<NUM_LIT:2>, n, name="<STR_LIT>")<EOL>

Return a DataSet with n examples of 2-input xor.


activations = [[<NUM_LIT:0.0> for i in range(n)] for n in sizes]<EOL>weights = []<EOL>def predict(example):<EOL><INDENT>unimplemented()<EOL><DEDENT>return predict<EOL>


def weighted_replicate(seq, weights, n):

assert len(seq) == len(weights)<EOL>weights = normalize(weights)<EOL>wholes = [int(w*n) for w in weights]<EOL>fractions = [(w*n) % <NUM_LIT:1> for w in weights]<EOL>return (flatten([x] * nx for x, nx in zip(seq, wholes))<EOL>+ weighted_sample_with_replacement(seq, fractions, n - sum(wholes)))<EOL>

Return n selections from seq, with the count of each element of
    seq proportional to the corresponding weight (filling in fractions
    randomly).
    >>> weighted_replicate('ABC', [1,2,1], 4)
    ['A', 'B', 'B', 'C']


def __init__(self, examples=None, attrs=None, attrnames=None, target=-<NUM_LIT:1>,<EOL>inputs=None, values=None, distance=mean_boolean_error,<EOL>name='<STR_LIT>', source='<STR_LIT>', exclude=()):

update(self, name=name, source=source, values=values, distance=distance)<EOL>if isinstance(examples, str):<EOL><INDENT>self.examples = parse_csv(examples)<EOL><DEDENT>elif examples is None:<EOL><INDENT>self.examples = parse_csv(DataFile(name+'<STR_LIT>').read())<EOL><DEDENT>else:<EOL><INDENT>self.examples = examples<EOL><DEDENT>if not attrs and self.examples:<EOL><INDENT>attrs = list(range(len(self.examples[<NUM_LIT:0>])))<EOL><DEDENT>self.attrs = attrs<EOL>if isinstance(attrnames, str):<EOL><INDENT>self.attrnames = attrnames.split()<EOL><DEDENT>else:<EOL><INDENT>self.attrnames = attrnames or attrs<EOL><DEDENT>self.setproblem(target, inputs=inputs, exclude=exclude)<EOL>

Accepts any of DataSet's fields.  Examples can also be a
        string or file from which to parse examples using parse_csv.
        Optional parameter: exclude, as documented in .setproblem().
        >>> DataSet(examples='1, 2, 3')
        <DataSet(): 1 examples, 3 attributes>


self.branches[val] = subtree<EOL>

Add a branch.  If self.attr = val, go to the given subtree.


return cross_validation(learner, dataset, k=len(dataset.examples))<EOL>

Leave one out cross-validation over the dataset.


<EOL>csp.current = current = {}<EOL>for var in csp.vars:<EOL><INDENT>val = min_conflicts_value(csp, var, current)<EOL>csp.assign(var, val, current)<EOL><DEDENT>for i in range(max_steps):<EOL><INDENT>conflicted = csp.conflicted_vars(current)<EOL>if not conflicted:<EOL><INDENT>return current<EOL><DEDENT>var = random.choice(conflicted)<EOL>val = min_conflicts_value(csp, var, current)<EOL>csp.assign(var, val, current)<EOL><DEDENT>return None<EOL>

Solve a CSP by stochastic hillclimbing on the number of conflicts.


return [var for var in self.vars<EOL>if self.nconflicts(var, current[var], current) > <NUM_LIT:0>]<EOL>

Return a list of variables in current assignment that are in conflict


def nconflicts(self, var, val, assignment):

n = len(self.vars)<EOL>c = self.rows[val] + self.downs[var+val] + self.ups[var-val+n-<NUM_LIT:1>]<EOL>if assignment.get(var, None) == val:<EOL><INDENT>c -= <NUM_LIT:3><EOL><DEDENT>return c<EOL>

The number of conflicts, as recorded with each assignment.
        Count conflicts in row and in up, down diagonals. If there
        is a queen there, it can't conflict with itself, so subtract 3.


return (self.curr_domains or self.domains)[var]<EOL>

Return all values for var that aren't currently ruled out.


if isinstance(neighbors, str):<EOL><INDENT>neighbors = parse_neighbors(neighbors)<EOL><DEDENT>return CSP(list(neighbors.keys()), UniversalDict(colors), neighbors,<EOL>different_values_constraint)<EOL>

Make a CSP for the problem of coloring a map with different colors
    for any two adjacent regions.  Arguments are a list of colors, and a
    dict of {region: [neighbor,...]} entries.  This dict may also be
    specified as a string of the form defined by parse_neighbors.


revised = False<EOL>for x in csp.curr_domains[Xi][:]:<EOL><INDENT>if every(lambda y: not csp.constraints(Xi, x, Xj, y),<EOL>csp.curr_domains[Xj]):<EOL><INDENT>csp.prune(Xi, x, removals)<EOL>revised = True<EOL><DEDENT><DEDENT>return revised<EOL>


def min_conflicts_value(csp, var, current):

return argmin_random_tie(csp.domains[var],<EOL>lambda val: csp.nconflicts(var, val, current))<EOL>

Return the value that will give var the least number of conflicts.
    If there is a tie, choose at random.


n = len(csp.vars)<EOL>assignment = {}<EOL>root = csp.vars[<NUM_LIT:0>]<EOL>X, parent = topological_sort(csp.vars, root)<EOL>for Xj in reversed(X):<EOL><INDENT>if not make_arc_consistent(parent[Xj], Xj, csp):<EOL><INDENT>return None<EOL><DEDENT><DEDENT>for Xi in X:<EOL><INDENT>if not csp.curr_domains[Xi]:<EOL><INDENT>return None<EOL><DEDENT>assignment[Xi] = csp.curr_domains[Xi][<NUM_LIT:0>]<EOL><DEDENT>return assignment<EOL>


def unordered_domain_values(var, assignment, csp):

return csp.choices(var)<EOL>


if self.curr_domains is None:<EOL><INDENT>self.curr_domains = dict((v, list(self.domains[v]))<EOL>for v in self.vars)<EOL><DEDENT>

Make sure we can prune values from domains. (We want to pay
        for this only if we use it.)


return argmin_random_tie(<EOL>[v for v in csp.vars if v not in assignment],<EOL>lambda var: num_legal_values(csp, var, assignment))<EOL>


def result(self, state, xxx_todo_changeme):

(var, val) = xxx_todo_changeme<EOL>return state + ((var, val),)<EOL>

Perform an action and return the new state.


def forward_checking(csp, var, value, assignment, removals):

for B in csp.neighbors[var]:<EOL><INDENT>if B not in assignment:<EOL><INDENT>for b in csp.curr_domains[B][:]:<EOL><INDENT>if not csp.constraints(var, value, B, b):<EOL><INDENT>csp.prune(B, b, removals)<EOL><DEDENT><DEDENT>if not csp.curr_domains[B]:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>

Prune neighbor values inconsistent with var=value.


<EOL>print('<STR_LIT>', self, '<STR_LIT>', assignment)<EOL>

Show a human-readable representation of the CSP.


Colors = '<STR_LIT>'.split()<EOL>Pets = '<STR_LIT>'.split()<EOL>Drinks = '<STR_LIT>'.split()<EOL>Countries = '<STR_LIT>'.split()<EOL>Smokes = '<STR_LIT>'.split()<EOL>vars = Colors + Pets + Drinks + Countries + Smokes<EOL>domains = {}<EOL>for var in vars:<EOL><INDENT>domains[var] = list(range(<NUM_LIT:1>, <NUM_LIT:6>))<EOL><DEDENT>domains['<STR_LIT>'] = [<NUM_LIT:1>]<EOL>domains['<STR_LIT>'] = [<NUM_LIT:3>]<EOL>neighbors = parse_neighbors("""<STR_LIT>""", vars)<EOL>for type in [Colors, Pets, Drinks, Countries, Smokes]:<EOL><INDENT>for A in type:<EOL><INDENT>for B in type:<EOL><INDENT>if A != B:<EOL><INDENT>if B not in neighbors[A]: neighbors[A].append(B)<EOL>if A not in neighbors[B]: neighbors[B].append(A)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>def zebra_constraint(A, a, B, b, recurse=<NUM_LIT:0>):<EOL><INDENT>same = (a == b)<EOL>next_to = abs(a - b) == <NUM_LIT:1><EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return next_to<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return next_to<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return next_to<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return same<EOL>if A == '<STR_LIT>' and B == '<STR_LIT>': return (a - <NUM_LIT:1>) == b<EOL>if recurse == <NUM_LIT:0>: return zebra_constraint(B, b, A, a, <NUM_LIT:1>)<EOL>if ((A in Colors and B in Colors) or<EOL>(A in Pets and B in Pets) or<EOL>(A in Drinks and B in Drinks) or<EOL>(A in Countries and B in Countries) or<EOL>(A in Smokes and B in Smokes)): return not same<EOL>raise '<STR_LIT:error>'<EOL><DEDENT>return CSP(vars, domains, neighbors, zebra_constraint)<EOL>


return sorted(csp.choices(var),<EOL>key=lambda val: csp.nconflicts(var, val, assignment))<EOL>


<EOL>def conflict(var2):<EOL><INDENT>return (var2 in assignment<EOL>and not self.constraints(var, val, var2, assignment[var2]))<EOL><DEDENT>return count_if(conflict, self.neighbors[var])<EOL>

Return the number of conflicts var=val has with other variables.


def AC3(csp, queue=None, removals=None):

if queue is None:<EOL><INDENT>queue = [(Xi, Xk) for Xi in csp.vars for Xk in csp.neighbors[Xi]]<EOL><DEDENT>csp.support_pruning()<EOL>while queue:<EOL><INDENT>(Xi, Xj) = queue.pop()<EOL>if revise(csp, Xi, Xj, removals):<EOL><INDENT>if not csp.curr_domains[Xi]:<EOL><INDENT>return False<EOL><DEDENT>for Xk in csp.neighbors[Xi]:<EOL><INDENT>if Xk != Xi:<EOL><INDENT>queue.append((Xk, Xi))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return True<EOL>


dict = DefaultDict([])<EOL>for var in vars:<EOL><INDENT>dict[var] = []<EOL><DEDENT>specs = [spec.split('<STR_LIT::>') for spec in neighbors.split('<STR_LIT:;>')]<EOL>for (A, Aneighbors) in specs:<EOL><INDENT>A = A.strip()<EOL>dict.setdefault(A, [])<EOL>for B in Aneighbors.split():<EOL><INDENT>dict[A].append(B)<EOL>dict[B].append(A)<EOL><DEDENT><DEDENT>return dict<EOL>

Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping
    regions to neighbors.  The syntax is a region name followed by a ':'
    followed by zero or more region names, followed by ';', repeated for
    each region name.  If you say 'X: Y' you don't need 'Y: X'.
    >>> parse_neighbors('X: Y Z; Y: Z')
    {'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']}


if len(state) == len(self.vars):<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>assignment = dict(state)<EOL>var = find_if(lambda v: v not in assignment, self.vars)<EOL>return [(var, val) for val in self.domains[var]<EOL>if self.nconflicts(var, val, assignment) == <NUM_LIT:0>]<EOL><DEDENT>

Return a list of applicable actions: nonconflicting
        assignments to an unassigned variable.


return find_if(lambda var: var not in assignment, csp.vars)<EOL>


oldval = assignment.get(var, None)<EOL>if val != oldval:<EOL><INDENT>if oldval is not None: <EOL><INDENT>self.record_conflict(assignment, var, oldval, -<NUM_LIT:1>)<EOL><DEDENT>self.record_conflict(assignment, var, val, +<NUM_LIT:1>)<EOL>CSP.assign(self, var, val, assignment)<EOL><DEDENT>

Assign var, and keep track of conflicts.


n = len(self.vars)<EOL>for val in range(n):<EOL><INDENT>for var in range(n):<EOL><INDENT>if assignment.get(var,'<STR_LIT>') == val: ch = '<STR_LIT>'<EOL>elif (var+val) % <NUM_LIT:2> == <NUM_LIT:0>: ch = '<STR_LIT:.>'<EOL>else: ch = '<STR_LIT:->'<EOL>print(ch, end='<STR_LIT:U+0020>')<EOL><DEDENT>print('<STR_LIT:U+0020>', end='<STR_LIT:U+0020>')<EOL>for var in range(n):<EOL><INDENT>if assignment.get(var,'<STR_LIT>') == val: ch = '<STR_LIT:*>'<EOL>else: ch = '<STR_LIT:U+0020>'<EOL>print(str(self.nconflicts(var, val, assignment))+ch, end='<STR_LIT:U+0020>')<EOL><DEDENT>print()<EOL><DEDENT>

Print the queens and the nconflicts values (for debugging).


def __init__(self, vars, domains, neighbors, constraints):

vars = vars or list(domains.keys())<EOL>update(self, vars=vars, domains=domains,<EOL>neighbors=neighbors, constraints=constraints,<EOL>initial=(), curr_domains=None, nassigns=<NUM_LIT:0>)<EOL>

Construct a CSP problem. If vars is empty, it becomes domains.keys().


count = dict([(c, len(conjuncts(c.args[<NUM_LIT:0>]))) for c in KB.clauses<EOL>if c.op == '<STR_LIT>'])<EOL>inferred = DefaultDict(False)<EOL>agenda = [s for s in KB.clauses if is_prop_symbol(s.op)]<EOL>while agenda:<EOL><INDENT>p = agenda.pop()<EOL>if p == q: return True<EOL>if not inferred[p]:<EOL><INDENT>inferred[p] = True<EOL>for c in KB.clauses_with_premise(p):<EOL><INDENT>count[c] -= <NUM_LIT:1><EOL>if count[c] == <NUM_LIT:0>:<EOL><INDENT>agenda.append(c.args[<NUM_LIT:1>])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return False<EOL>

Use forward chaining to see if a PropDefiniteKB entails symbol q.
    [Fig. 7.15]
    >>> pl_fc_entails(Fig[7,15], expr('Q'))
    True


if isinstance(s, Expr): return s<EOL>if isnumber(s): return Expr(s)<EOL>s = s.replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>s = s.replace('<STR_LIT>', '<STR_LIT:%>').replace('<STR_LIT>', '<STR_LIT>')<EOL>s = re.sub(r'<STR_LIT>', r'<STR_LIT>', s)<EOL>return eval(s, {'<STR_LIT>':Expr})<EOL>

Create an Expr representing a logic expression by parsing the input
    string. Symbols and numbers are automatically converted to Exprs.
    In addition you can use alternative spellings of these operators:
      'x ==> y'   parses as   (x >> y)    # Implication
      'x <== y'   parses as   (x << y)    # Reverse implication
      'x <=> y'   parses as   (x % y)     # Logical equivalence
      'x =/= y'   parses as   (x ^ y)     # Logical disequality (xor)
    But BE CAREFUL; precedence of implication is wrong. expr('P & Q ==> R & S')
    is ((P & (Q >> R)) & S); so you must use expr('(P & Q) ==> (R & S)').
    >>> expr('P <=> Q(1)')
    (P <=> Q(1))
    >>> expr('P & Q | ~R(x, F(x))')
    ((P & Q) | ~R(x, F(x)))


if pl_fc_entails(self.clauses, query):<EOL><INDENT>yield {}<EOL><DEDENT>

Yield the empty substitution if KB implies query; else nothing.


result = set([])<EOL>def walk(s):<EOL><INDENT>if is_variable(s):<EOL><INDENT>result.add(s)<EOL><DEDENT>else:<EOL><INDENT>for arg in s.args:<EOL><INDENT>walk(arg)<EOL><DEDENT><DEDENT><DEDENT>walk(s)<EOL>return result<EOL>

Return a set of the variables in expression s.
    >>> ppset(variables(F(x, A, y)))
    set([x, y])
    >>> ppset(variables(F(G(x), z)))
    set([x, z])
    >>> ppset(variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, z)')))
    set([x, y, z])


if s.op == '<STR_LIT>':<EOL><INDENT>NOT = lambda b: move_not_inwards(~b)<EOL>a = s.args[<NUM_LIT:0>]<EOL>if a.op == '<STR_LIT>': return move_not_inwards(a.args[<NUM_LIT:0>]) <EOL>if a.op =='<STR_LIT:&>': return associate('<STR_LIT:|>', list(map(NOT, a.args)))<EOL>if a.op =='<STR_LIT:|>': return associate('<STR_LIT:&>', list(map(NOT, a.args)))<EOL>return s<EOL><DEDENT>elif is_symbol(s.op) or not s.args:<EOL><INDENT>return s<EOL><DEDENT>else:<EOL><INDENT>return Expr(s.op, *list(map(move_not_inwards, s.args)))<EOL><DEDENT>

Rewrite sentence s by moving negation sign inward.
    >>> move_not_inwards(~(A | B))
    (~A & ~B)
    >>> move_not_inwards(~(A & B))
    (~A | ~B)
    >>> move_not_inwards(~(~(A | ~B) | ~~C))
    ((A | ~B) & ~C)


if isinstance(x, list):<EOL><INDENT>return [subst(s, xi) for xi in x]<EOL><DEDENT>elif isinstance(x, tuple):<EOL><INDENT>return tuple([subst(s, xi) for xi in x])<EOL><DEDENT>elif not isinstance(x, Expr):<EOL><INDENT>return x<EOL><DEDENT>elif is_var_symbol(x.op):<EOL><INDENT>return s.get(x, x)<EOL><DEDENT>else:<EOL><INDENT>return Expr(x.op, *[subst(s, arg) for arg in x.args])<EOL><DEDENT>

Substitute the substitution s into the expression x.
    >>> subst({x: 42, y:0}, F(x) + y)
    (F(42) + 0)


if is_symbol(s.op):<EOL><INDENT>return True<EOL><DEDENT>elif s.op == '<STR_LIT>':<EOL><INDENT>antecedent, consequent = s.args<EOL>return (is_symbol(consequent.op)<EOL>and every(lambda arg: is_symbol(arg.op), conjuncts(antecedent)))<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

returns True for exprs s of the form A & B & ... & C ==> D,
    where all literals are positive.  In clause form, this is
    ~A | ~B | ... | ~C | D, where exactly one clause is positive.
    >>> is_definite_clause(expr('Farmer(Mac)'))
    True
    >>> is_definite_clause(expr('~Farmer(Mac)'))
    False
    >>> is_definite_clause(expr('(Farmer(f) & Rabbit(r)) ==> Hates(f, r)'))
    True
    >>> is_definite_clause(expr('(Farmer(f) & ~Rabbit(r)) ==> Hates(f, r)'))
    False
    >>> is_definite_clause(expr('(Farmer(f) | Rabbit(r)) ==> Hates(f, r)'))
    False


for result in self.ask_generator(query):<EOL><INDENT>return result<EOL><DEDENT>return False<EOL>

Return a substitution that makes the query true, or,
        failing that, return False.


abstract<EOL>


if dic is None: dic = {}<EOL>if not isinstance(sentence, Expr):<EOL><INDENT>return sentence<EOL><DEDENT>elif is_var_symbol(sentence.op):<EOL><INDENT>if sentence in dic:<EOL><INDENT>return dic[sentence]<EOL><DEDENT>else:<EOL><INDENT>v = Expr('<STR_LIT>' % next(standardize_variables.counter))<EOL>dic[sentence] = v<EOL>return v<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return Expr(sentence.op,<EOL>*[standardize_variables(a, dic) for a in sentence.args])<EOL><DEDENT>

Replace all the variables in sentence with new variables.
    >>> e = expr('F(a, b, c) & G(c, A, 23)')
    >>> len(variables(standardize_variables(e)))
    3
    >>> variables(e).intersection(variables(standardize_variables(e)))
    set([])
    >>> is_variable(standardize_variables(expr('x')))
    True


if y == x: return ONE<EOL>elif not y.args: return ZERO<EOL>else:<EOL><INDENT>u, op, v = y.args[<NUM_LIT:0>], y.op, y.args[-<NUM_LIT:1>]<EOL>if op == '<STR_LIT:+>': return diff(u, x) + diff(v, x)<EOL>elif op == '<STR_LIT:->' and len(args) == <NUM_LIT:1>: return -diff(u, x)<EOL>elif op == '<STR_LIT:->': return diff(u, x) - diff(v, x)<EOL>elif op == '<STR_LIT:*>': return u * diff(v, x) + v * diff(u, x)<EOL>elif op == '<STR_LIT:/>': return (v*diff(u, x) - u*diff(v, x)) / (v * v)<EOL>elif op == '<STR_LIT>' and isnumber(x.op):<EOL><INDENT>return (v * u ** (v - <NUM_LIT:1>) * diff(u, x))<EOL><DEDENT>elif op == '<STR_LIT>': return (v * u ** (v - <NUM_LIT:1>) * diff(u, x)<EOL>+ u ** v * Expr('<STR_LIT>')(u) * diff(v, x))<EOL>elif op == '<STR_LIT>': return diff(u, x) / u<EOL>else: raise ValueError("<STR_LIT>" % (op, y, x))<EOL><DEDENT>

Return the symbolic derivative, dy/dx, as an Expr.
    However, you probably want to simplify the results with simp.
    >>> diff(x * x, x)
    ((x * 1) + (x * 1))
    >>> simp(diff(x * x, x))
    (2 * x)


return is_symbol(s) and s[<NUM_LIT:0>].islower()<EOL>

A logic variable symbol is an initial-lowercase string.


if isinstance(s, str): s = expr(s)<EOL>s = eliminate_implications(s) <EOL>s = move_not_inwards(s) <EOL>return distribute_and_over_or(s)<EOL>


unknown_clauses = [] <EOL>for c in clauses:<EOL><INDENT>val =  pl_true(c, model)<EOL>if val == False:<EOL><INDENT>return False<EOL><DEDENT>if val != True:<EOL><INDENT>unknown_clauses.append(c)<EOL><DEDENT><DEDENT>if not unknown_clauses:<EOL><INDENT>return model<EOL><DEDENT>P, value = find_pure_symbol(symbols, unknown_clauses)<EOL>if P:<EOL><INDENT>return dpll(clauses, removeall(P, symbols), extend(model, P, value))<EOL><DEDENT>P, value = find_unit_clause(clauses, model)<EOL>if P:<EOL><INDENT>return dpll(clauses, removeall(P, symbols), extend(model, P, value))<EOL><DEDENT>P, symbols = symbols[<NUM_LIT:0>], symbols[<NUM_LIT:1>:]<EOL>return (dpll(clauses, symbols, extend(model, P, True)) or<EOL>dpll(clauses, symbols, extend(model, P, False)))<EOL>

See if the clauses are true in a partial model.


return hash(self.op) ^ hash(tuple(self.args))<EOL>

Need a hash method so Exprs can live in dicts.


assert is_definite_clause(sentence), "<STR_LIT>"<EOL>self.clauses.append(sentence)<EOL>


if not s.args or is_symbol(s.op): return s     <EOL>args = list(map(eliminate_implications, s.args))<EOL>a, b = args[<NUM_LIT:0>], args[-<NUM_LIT:1>]<EOL>if s.op == '<STR_LIT>':<EOL><INDENT>return (b | ~a)<EOL><DEDENT>elif s.op == '<STR_LIT>':<EOL><INDENT>return (a | ~b)<EOL><DEDENT>elif s.op == '<STR_LIT>':<EOL><INDENT>return (a | ~b) & (b | ~a)<EOL><DEDENT>elif s.op == '<STR_LIT>':<EOL><INDENT>assert len(args) == <NUM_LIT:2>   <EOL>return (a & ~b) | (~a & b)<EOL><DEDENT>else:<EOL><INDENT>assert s.op in ('<STR_LIT:&>', '<STR_LIT:|>', '<STR_LIT>')<EOL>return Expr(s.op, *args)<EOL><DEDENT>

Change >>, <<, and <=> into &, |, and ~. That is, return an Expr
    that is equivalent to s, but has only &, |, and ~ as logical operators.
    >>> eliminate_implications(A >> (~B << C))
    ((~B | ~C) | ~A)
    >>> eliminate_implications(A ^ B)
    ((A & ~B) | (~A & B))


op, args = exp.op, exp.args<EOL>if exp == TRUE:<EOL><INDENT>return True<EOL><DEDENT>elif exp == FALSE:<EOL><INDENT>return False<EOL><DEDENT>elif is_prop_symbol(op):<EOL><INDENT>return model.get(exp)<EOL><DEDENT>elif op == '<STR_LIT>':<EOL><INDENT>p = pl_true(args[<NUM_LIT:0>], model)<EOL>if p is None: return None<EOL>else: return not p<EOL><DEDENT>elif op == '<STR_LIT:|>':<EOL><INDENT>result = False<EOL>for arg in args:<EOL><INDENT>p = pl_true(arg, model)<EOL>if p is True: return True<EOL>if p is None: result = None<EOL><DEDENT>return result<EOL><DEDENT>elif op == '<STR_LIT:&>':<EOL><INDENT>result = True<EOL>for arg in args:<EOL><INDENT>p = pl_true(arg, model)<EOL>if p is False: return False<EOL>if p is None: result = None<EOL><DEDENT>return result<EOL><DEDENT>p, q = args<EOL>if op == '<STR_LIT>':<EOL><INDENT>return pl_true(~p | q, model)<EOL><DEDENT>elif op == '<STR_LIT>':<EOL><INDENT>return pl_true(p | ~q, model)<EOL><DEDENT>pt = pl_true(p, model)<EOL>if pt is None: return None<EOL>qt = pl_true(q, model)<EOL>if qt is None: return None<EOL>if op == '<STR_LIT>':<EOL><INDENT>return pt == qt<EOL><DEDENT>elif op == '<STR_LIT>':<EOL><INDENT>return pt != qt<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" + str(exp))<EOL><DEDENT>

Return True if the propositional logic expression is true in the model,
    and False if it is false. If the model does not specify the value for
    every proposition, this may return None to indicate 'not obvious';
    this may happen even when the expression is tautological.


def tt_check_all(kb, alpha, symbols, model):

if not symbols:<EOL><INDENT>if pl_true(kb, model):<EOL><INDENT>result = pl_true(alpha, model)<EOL>assert result in (True, False)<EOL>return result<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>P, rest = symbols[<NUM_LIT:0>], symbols[<NUM_LIT:1>:]<EOL>return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and<EOL>tt_check_all(kb, alpha, rest, extend(model, P, False)))<EOL><DEDENT>

Auxiliary routine to implement tt_entails.


steps = itertools.count()<EOL>def program(percept):<EOL><INDENT>t = next(steps)<EOL>KB.tell(make_percept_sentence(percept, t))<EOL>action = KB.ask(make_action_query(t))<EOL>KB.tell(make_action_sentence(action, t))<EOL>return action<EOL><DEDENT>def make_percept_sentence(self, percept, t):<EOL><INDENT>return Expr("<STR_LIT>")(percept, t)<EOL><DEDENT>def make_action_query(self, t):<EOL><INDENT>return expr("<STR_LIT>" % t)<EOL><DEDENT>def make_action_sentence(self, action, t):<EOL><INDENT>return Expr("<STR_LIT>")(action[expr('<STR_LIT:action>')], t)<EOL><DEDENT>return program<EOL>

A generic logical knowledge-based agent program. [Fig. 7.1]


abstract<EOL>

Yield all the substitutions that make query true.


assert is_definite_clause(s)<EOL>if is_symbol(s.op):<EOL><INDENT>return [], s<EOL><DEDENT>else:<EOL><INDENT>antecedent, consequent = s.args<EOL>return conjuncts(antecedent), consequent<EOL><DEDENT>

Return the antecedents and the consequent of a definite clause.


return dissociate('<STR_LIT:|>', [s])<EOL>

Return a list of the disjuncts in the sentence s.
    >>> disjuncts(A | B)
    [A, B]
    >>> disjuncts(A & B)
    [(A & B)]


ppdict(s)<EOL>


P, value = None, None<EOL>for literal in disjuncts(clause):<EOL><INDENT>sym, positive = inspect_literal(literal)<EOL>if sym in model:<EOL><INDENT>if model[sym] == positive:<EOL><INDENT>return None, None  <EOL><DEDENT><DEDENT>elif P:<EOL><INDENT>return None, None      <EOL><DEDENT>else:<EOL><INDENT>P, value = sym, positive<EOL><DEDENT><DEDENT>return P, value<EOL>

Return a single variable/value pair that makes clause true in
    the model, if possible.
    >>> unit_clause_assign(A|B|C, {A:True})
    (None, None)
    >>> unit_clause_assign(B|~C, {A:True})
    (None, None)
    >>> unit_clause_assign(~A|~B, {A:True})
    (B, False)


if s is None:<EOL><INDENT>return None<EOL><DEDENT>elif x == y:<EOL><INDENT>return s<EOL><DEDENT>elif is_variable(x):<EOL><INDENT>return unify_var(x, y, s)<EOL><DEDENT>elif is_variable(y):<EOL><INDENT>return unify_var(y, x, s)<EOL><DEDENT>elif isinstance(x, Expr) and isinstance(y, Expr):<EOL><INDENT>return unify(x.args, y.args, unify(x.op, y.op, s))<EOL><DEDENT>elif isinstance(x, str) or isinstance(y, str):<EOL><INDENT>return None<EOL><DEDENT>elif issequence(x) and issequence(y) and len(x) == len(y):<EOL><INDENT>if not x: return s<EOL>return unify(x[<NUM_LIT:1>:], y[<NUM_LIT:1>:], unify(x[<NUM_LIT:0>], y[<NUM_LIT:0>], s))<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Unify expressions x,y with substitution s; return a substitution that
    would make x,y equal, or None if x,y can not unify. x and y can be
    variables (e.g. Expr('x')), constants, lists, or Exprs. [Fig. 9.1]
    >>> ppsubst(unify(x + y, y + C, {}))
    {x: y, y: C}


def __init__(self, name, rules, lexicon):

update(self, name=name, rules=rules, lexicon=lexicon)<EOL>self.categories = DefaultDict([])<EOL>for lhs in lexicon:<EOL><INDENT>for word in lexicon[lhs]:<EOL><INDENT>self.categories[word].append(lhs)<EOL><DEDENT><DEDENT>

A grammar has a set of rules and a lexicon.


(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.


return cat in self.categories[word]<EOL>


import random<EOL>def rewrite(tokens, into):<EOL><INDENT>for token in tokens:<EOL><INDENT>if token in grammar.rules:<EOL><INDENT>rewrite(random.choice(grammar.rules[token]), into)<EOL><DEDENT>elif token in grammar.lexicon:<EOL><INDENT>into.append(random.choice(grammar.lexicon[token]))<EOL><DEDENT>else:<EOL><INDENT>into.append(token)<EOL><DEDENT><DEDENT>return into<EOL><DEDENT>return '<STR_LIT:U+0020>'.join(rewrite(s.split(), []))<EOL>

Replace each token in s by a random entry in grammar (recursively).
    This is useful for testing a grammar, e.g. generate_random(E_)


return self.rules.get(cat, ())<EOL>

Return a sequence of possible rhs's that cat can be rewritten as.


for (lhs, rhs) in list(rules.items()):<EOL><INDENT>rules[lhs] = [word.strip() for word in rhs.split('<STR_LIT:|>')]<EOL><DEDENT>return rules<EOL>

Create a dictionary mapping symbols to alternative words.
    >>> Lexicon(Art = "the | a | an")
    {'Art': ['the', 'a', 'an']}


def __init__(self, grammar, trace=False):

update(self, grammar=grammar, trace=trace)<EOL>

A datastructure for parsing a string; and methods to do the parse.
        self.chart[i] holds the edges that end just before the i'th word.
        Edges are 5-element lists of [start, end, lhs, [found], [expects]].


for (lhs, rhs) in list(rules.items()):<EOL><INDENT>rules[lhs] = [alt.strip().split() for alt in rhs.split('<STR_LIT:|>')]<EOL><DEDENT>return rules<EOL>

Create a dictionary mapping symbols to alternative sequences.
    >>> Rules(A = "B C | D E")
    {'A': [['B', 'C'], ['D', 'E']]}


abstract<EOL>

Return a list of the allowable moves at this point.


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.


abstract<EOL>

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


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

A player that chooses a legal move at random.


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]


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.


return state.to_move<EOL>

Return the player whose move it is in this state.


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


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.


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.


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.


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.


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


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]


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


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


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


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'


unimplemented()<EOL>


return self.vals[var]<EOL>

Return the set of possible values for a variable.


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).


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'


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.


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.


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.


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.


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.


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


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


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>

Called for every function call 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.


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.


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.


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 _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().


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


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.


<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>


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


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

Update the currently active color palette
with the given color palette


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


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


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.ANSI_256_COLORS<EOL>

Use 256 ANSI colors for this 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


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


self.colormode = terminal.TRUE_COLORS<EOL>

Use true colors for this colorful object


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 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


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.


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.


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``.


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.


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.


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'은'


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.


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.


if self.magic:<EOL><INDENT>return self.magic + data<EOL><DEDENT>return data<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>


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>


return self.options<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>


@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>


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>


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>


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


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 _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.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>


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


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>


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.


<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.


@property<EOL><INDENT>def RowSpan(self) -> int:<DEDENT>

return self.pattern.CurrentRowSpan<EOL>

Property RowSpan.
Call IUIAutomationGridItemPattern::get_CurrentRowSpan.
Return int, the number of rows spanned by the grid item.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationgriditempattern-get_currentrowspan


self.pattern = pattern<EOL>


def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:

SetCursorPos(x, y)<EOL>screenWidth, screenHeight = GetScreenSize()<EOL>mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(<NUM_LIT>)<EOL>mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * <NUM_LIT> // screenWidth, y * <NUM_LIT> // screenHeight, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>time.sleep(waitTime)<EOL>

Simulate mouse right click at point x, y.
x: int.
y: int.
waitTime: float.


@property<EOL><INDENT>def CurrentView(self) -> int:<DEDENT>

return self.pattern.CurrentCurrentView<EOL>

Property CurrentView.
Call IUIAutomationMultipleViewPattern::get_CurrentCurrentView.
Return int, the control-specific identifier of the current view of the control.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationmultipleviewpattern-get_currentcurrentview


def SetValue(self, value: str, waitTime: float = OPERATION_WAIT_TIME) -> bool:

ret = self.pattern.SetValue(value) == S_OK<EOL>time.sleep(waitTime)<EOL>return ret<EOL>

Call IUIAutomationTransformPattern2::IUIAutomationValuePattern::SetValue.
Set the value of the element.
value: str.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationvaluepattern-setvalue


@property<EOL><INDENT>def Orientation(self) -> int:<DEDENT>

return self.Element.CurrentOrientation<EOL>

Property Orientation.
Return int, a value in class `OrientationType`.
Call IUIAutomationElement::get_CurrentOrientation.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentorientation


def SetCursorPos(x: int, y: int) -> bool:

return bool(ctypes.windll.user32.SetCursorPos(x, y))<EOL>

SetCursorPos from Win32.
Set mouse cursor to point x, y.
x: int.
y: int.
Return bool, True if succeed otherwise False.