Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> # if global_mapnik_lock.acquire(): try: if self.mapnik is None: self.mapnik = get_mapnikMap(self.mapfile) logging.debug('TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax)) if self.layer_id_key is not None: grids = [] for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource if isinstance(fields, list): fields = [str(f) for f in fields] else: fields = datasource.fields() grid = mapnik.Grid(width, height) mapnik.render_layer(self.mapnik, grid, layer=index, fields=fields) grid = grid.encode('utf', resolution=self.scale, features=True) for key in grid['data']: grid['data'][key][self.layer_id_key] = self.mapnik.layers[index].name grids.append(grid) # global_mapnik_lock.release() <|code_end|> , continue by predicting the next line. Consider current file imports: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and context: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass which might include code, classes, or functions. Output only the next line.
outgrid = reduce(merge_grids, grids)
Here is a snippet: <|code_start|> return dict(keys=outkeys, data=outdata, grid=outgrid) def encode_id(id): id += 32 if id >= 34: id = id + 1 if id >= 92: id = id + 1 if id > 127: return unichr(id) return chr(id) def decode_char(char): id = ord(char) if id >= 93: id = id - 1 if id >= 35: id = id - 1 return id - 32 def get_mapnikMap(mapfile): """ Get a new mapnik.Map instance for a mapfile """ mmap = mapnik.Map(0, 0) if exists(mapfile): mapnik.load_map(mmap, str(mapfile)) else: handle, filename = mkstemp() <|code_end|> . Write the next line using the current file imports: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass , which may include functions, classes, or code. Output only the next line.
os.write(handle, urlopen(mapfile).read())
Predict the next line for this snippet: <|code_start|> This provider is identified by the name "mapnik" in the TileStache config. Arguments: - mapfile (required) Local file path to Mapnik XML file. - fonts (optional) Local directory path to *.ttf font files. - "scale factor" (optional) Scale multiplier used for Mapnik rendering pipeline. Used for supporting retina resolution. For more information about the scale factor, see: https://github.com/mapnik/mapnik/wiki/Scale-factor More information on Mapnik and Mapnik XML: - http://mapnik.org - http://trac.mapnik.org/wiki/XMLGettingStarted - http://trac.mapnik.org/wiki/XMLConfigReference """ def __init__(self, layer, mapfile, fonts=None, scale_factor=None): """ Initialize Mapnik provider with layer and mapfile. XML mapfile keyword arg comes from TileStache config, and is an absolute path by the time it gets here. """ <|code_end|> with the help of current file imports: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass , which may contain function names, class names, or code. Output only the next line.
maphref = urljoin(layer.config.dirpath, mapfile)
Predict the next line for this snippet: <|code_start|> This provider is identified by the name "mapnik" in the TileStache config. Arguments: - mapfile (required) Local file path to Mapnik XML file. - fonts (optional) Local directory path to *.ttf font files. - "scale factor" (optional) Scale multiplier used for Mapnik rendering pipeline. Used for supporting retina resolution. For more information about the scale factor, see: https://github.com/mapnik/mapnik/wiki/Scale-factor More information on Mapnik and Mapnik XML: - http://mapnik.org - http://trac.mapnik.org/wiki/XMLGettingStarted - http://trac.mapnik.org/wiki/XMLConfigReference """ def __init__(self, layer, mapfile, fonts=None, scale_factor=None): """ Initialize Mapnik provider with layer and mapfile. XML mapfile keyword arg comes from TileStache config, and is an absolute path by the time it gets here. """ maphref = urljoin(layer.config.dirpath, mapfile) <|code_end|> with the help of current file imports: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass , which may contain function names, class names, or code. Output only the next line.
scheme, h, path, q, p, f = urlparse(maphref)
Predict the next line after this snippet: <|code_start|>known as "mapnik grid". Both require Mapnik to be installed; Grid requires Mapnik 2.0.0 and above. """ from __future__ import absolute_import # We enabled absolute_import because case insensitive filesystems # cause this file to be loaded twice (the name of this file # conflicts with the name of the module we want to import). # Forcing absolute imports fixes the issue. try: except ImportError: # can still build documentation pass try: except ImportError: # On some systems, PIL.Image is known as Image. if 'mapnik' in locals(): _version = hasattr(mapnik, 'mapnik_version') and mapnik.mapnik_version() or 701 if _version >= 20000: Box2d = mapnik.Box2d else: Box2d = mapnik.Envelope <|code_end|> using the current file's imports: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and any relevant context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass . Output only the next line.
global_mapnik_lock = allocate_lock()
Given the following code snippet before the placeholder: <|code_start|> # offset, outgrid = len(grid1['keys']), [] def newchar(char1, char2): """ Return a new encoded character based on two inputs. """ id1, id2 = decode_char(char1), decode_char(char2) if grid2['keys'][id2] == '': # transparent pixel, use the bottom character return encode_id(id1) else: # opaque pixel, use the top character return encode_id(id2 + offset) for (row1, row2) in zip(grid1['grid'], grid2['grid']): outrow = [newchar(c1, c2) for (c1, c2) in zip(row1, row2)] outgrid.append(''.join(outrow)) return dict(keys=outkeys, data=outdata, grid=outgrid) def encode_id(id): id += 32 if id >= 34: id = id + 1 if id >= 92: id = id + 1 if id > 127: <|code_end|> , predict the next line using imports from the current file: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and context including class names, function names, and sometimes code from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass . Output only the next line.
return unichr(id)
Continue the code snippet: <|code_start|> # global_mapnik_lock.release() outgrid = reduce(merge_grids, grids) else: grid = mapnik.Grid(width, height) for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map(str, fields) or datasource.fields() mapnik.render_layer(self.mapnik, grid, layer=index, fields=fields) # global_mapnik_lock.release() outgrid = grid.encode('utf', resolution=self.scale, features=True) except: self.mapnik = None raise finally: global_mapnik_lock.release() logging.debug('TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile) return SaveableResponse(outgrid, self.scale) def getTypeByExtension(self, extension): """ Get mime-type and format by file extension. This only accepts "json". """ if extension.lower() != 'json': <|code_end|> . Use current file imports: from time import time from os.path import exists from itertools import count from glob import glob from tempfile import mkstemp from .py3_compat import reduce, urlopen, urljoin, urlparse, allocate_lock from .py3_compat import unichr from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from PIL import Image import os import logging import json import mapnik import Image and context (classes, functions, or code) from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass . Output only the next line.
raise KnownUnknown('MapnikGrid only makes .json tiles, not "%s"' % extension)
Here is a snippet: <|code_start|> "osm": { "provider": {"name": "proxy", "provider": "OPENSTREETMAP"}, "png options": {"palette": "http://tilestache.org/example-palette-openstreetmap-mapnik.act"} } The example OSM palette above is a real file with a 32 color (5 bit) selection of colors appropriate for use with OpenStreetMap's default Mapnik cartography. To generate an .act file, convert an existing image in Photoshop to indexed color, and access the color table under Image -> Mode -> Color Table. Saving the color table results in a usable .act file, internally structured as a fixed-size 772-byte table with 256 3-byte RGB triplets, followed by a two-byte unsigned int with the number of defined colors (may be less than 256) and a finaly two-byte unsigned int with the optional index of a transparent color in the lookup table. If the final byte is 0xFFFF, there is no transparency. """ try: except ImportError: # On some systems, PIL.Image is known as Image. def load_palette(file_href): """ Load colors from a Photoshop .act file, return palette info. Return tuple is an array of [ (r, g, b), (r, g, b), ... ], bit depth of the palette, and a numeric transparency index or None if not defined. """ <|code_end|> . Write the next line using the current file imports: from struct import unpack, pack from math import sqrt, ceil, log from .py3_compat import urlopen, reduce from operator import add from PIL import Image import Image and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): , which may include functions, classes, or code. Output only the next line.
bytes_ = urlopen(file_href).read()
Predict the next line after this snippet: <|code_start|> for offset in range(0, len(pixels), 4): r, g, b, a = unpack('!BBBB', pixels[offset:offset+4]) if a < 0x80 and t_value is not None: # Sufficiently transparent indexes.append(t_value) continue try: indexes.append(mapping[(r, g, b)]) except KeyError: # Never seen this color mapping[(r, g, b)] = pack('!B', palette_color(r, g, b, palette, t_index)) else: continue indexes.append(mapping[(r, g, b)]) if hasattr(Image, 'frombytes'): # Image.fromstring is deprecated past Pillow 2.0 output = Image.frombytes('P', image.size, b''.join(indexes)) else: # PIL still uses Image.fromstring output = Image.fromstring('P', image.size, b''.join(indexes)) bits = int(ceil(log(len(palette)) / log(2))) palette += [(0, 0, 0)] * (256 - len(palette)) <|code_end|> using the current file's imports: from struct import unpack, pack from math import sqrt, ceil, log from .py3_compat import urlopen, reduce from operator import add from PIL import Image import Image and any relevant context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): . Output only the next line.
palette = reduce(add, palette)
Given the following code snippet before the placeholder: <|code_start|>def trans_coord(srid_source, srid_dest, x, y): srs_source = osr.SpatialReference() srs_source.ImportFromEPSG(srid_source) srs_dest = osr.SpatialReference() srs_dest.ImportFromEPSG(srid_dest) transform = osr.CoordinateTransformation(srs_source, srs_dest) point = ogr.CreateGeometryFromWkt("POINT ({} {})".format(x, y)) point.Transform(transform) return point.GetX(), point.GetY() def tile_bounds_mercator(x, y, z): #bds = mercantile.bounds(x, y, z) #ll = mercantile.xy(bds.west, bds.south) #ur = mercantile.xy(bds.east, bds.north) bds = TILE_BOUNDS.get((x, y, z)) ll = trans_coord(4326, 3857, bds.west, bds.south) ur = trans_coord(4326, 3857, bds.east, bds.north) return (ll[0], ll[1], ur[0], ur[1]) def coord2merc(x, y, extent): (x0, y0, x_max, y_max) = extent x_span = x_max - x0 y_span = y_max - y0 <|code_end|> , predict the next line using imports from the current file: import os import json import mapbox_vector_tile from unittest import TestCase, skipIf from collections import namedtuple from math import hypot from osgeo import ogr, osr from shapely.geometry import Point, LineString, Polygon, MultiPolygon, asShape from TileStache.Goodies.VecTiles import pbf from . import utils and context including class names, function names, and sometimes code from other files: # Path: TileStache/Goodies/VecTiles/pbf.py # def decode(file): # def encode(file, features, coord, layer_name=''): # def merge(file, feature_layers, coord): # def get_feature_layer(name, features): . Output only the next line.
x_merc = ((x * x_span) / float(pbf.extents)) + x0
Given the following code snippet before the placeholder: <|code_start|> """ db = _connect(filename) db.text_factory = bytes tile_row = (2**coord.zoom - 1) - coord.row # Hello, Paul Ramsey. q = 'DELETE FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?' db.execute(q, (coord.zoom, coord.column, tile_row)) def put_tile(filename, coord, content): """ """ db = _connect(filename) db.text_factory = bytes tile_row = (2**coord.zoom - 1) - coord.row # Hello, Paul Ramsey. q = 'REPLACE INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?, ?, ?, ?)' db.execute(q, (coord.zoom, coord.column, tile_row, buffer(content))) db.commit() db.close() class Provider: """ MBTiles provider. See module documentation for explanation of constructor arguments. """ def __init__(self, layer, tileset): """ """ sethref = urljoin(layer.config.dirpath, tileset) <|code_end|> , predict the next line using imports from the current file: from .py3_compat import urlparse, urljoin from os.path import exists from sqlite3 import connect as _connect from ModestMaps.Core import Coordinate and context including class names, function names, and sometimes code from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): . Output only the next line.
scheme, h, path, q, p, f = urlparse(sethref)
Here is a snippet: <|code_start|> """ Delete a tile by coordinate. """ db = _connect(filename) db.text_factory = bytes tile_row = (2**coord.zoom - 1) - coord.row # Hello, Paul Ramsey. q = 'DELETE FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?' db.execute(q, (coord.zoom, coord.column, tile_row)) def put_tile(filename, coord, content): """ """ db = _connect(filename) db.text_factory = bytes tile_row = (2**coord.zoom - 1) - coord.row # Hello, Paul Ramsey. q = 'REPLACE INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?, ?, ?, ?)' db.execute(q, (coord.zoom, coord.column, tile_row, buffer(content))) db.commit() db.close() class Provider: """ MBTiles provider. See module documentation for explanation of constructor arguments. """ def __init__(self, layer, tileset): """ """ <|code_end|> . Write the next line using the current file imports: from .py3_compat import urlparse, urljoin from os.path import exists from sqlite3 import connect as _connect from ModestMaps.Core import Coordinate and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): , which may include functions, classes, or code. Output only the next line.
sethref = urljoin(layer.config.dirpath, tileset)
Continue the code snippet: <|code_start|> class DynamicLayers: def __init__(self, config, url_root, cache_responses, dirpath): self.config = config self.url_root = url_root self.dirpath = dirpath self.cache_responses = cache_responses; self.seen_layers = {} self.lookup_failures = set() def keys(self): return self.seen_layers.keys() def items(self): return self.seen_layers.items() def parse_layer(self, layer_json): layer_dict = json_load(layer_json) return TileStache.Config._parseConfigLayer(layer_dict, self.config, self.dirpath) def __contains__(self, key): # If caching is enabled and we've seen a request for this layer before, return True unless # the prior lookup failed to find this layer. if self.cache_responses: if key in self.seen_layers: return True elif key in self.lookup_failures: return False <|code_end|> . Use current file imports: import logging import TileStache from json import load as json_load from simplejson import load as json_load from TileStache.py3_compat import urlopen and context (classes, functions, or code) from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): . Output only the next line.
res = urlopen(self.url_root + "/layer/" + key)
Continue the code snippet: <|code_start|> ''' Decode an MVT file into a list of (WKB, property dict) features. Result can be passed directly to mapnik.PythonDatasource.wkb_features(). ''' head = file.read(4) if head != '\x89MVT': raise Exception('Bad head: "%s"' % head) body = BytesIO(_decompress(file.read(_next_int(file)))) features = [] for i in range(_next_int(body)): wkb = body.read(_next_int(body)) raw = body.read(_next_int(body)) props = json.loads(raw) features.append((wkb, props)) return features def encode(file, features): ''' Encode a list of (WKB, property dict) features into an MVT stream. Geometries in the features list are assumed to be in spherical mercator. Floating point precision in the output is approximated to 26 bits. ''' parts = [] for feature in features: <|code_end|> . Use current file imports: from io import BytesIO from zlib import decompress as _decompress, compress as _compress from struct import unpack as _unpack, pack as _pack from .wkb import approximate_wkb import json and context (classes, functions, or code) from other files: # Path: TileStache/Goodies/VecTiles/wkb.py # def approximate_wkb(wkb_in): # ''' Return an approximation of the input WKB with lower-precision geometry. # ''' # input, output = BytesIO(wkb_in), BytesIO() # approx_geometry(input, output) # wkb_out = output.getvalue() # # assert len(wkb_in) == input.tell(), 'The whole WKB was not processed' # assert len(wkb_in) == len(wkb_out), 'The output WKB is the wrong length' # # return wkb_out . Output only the next line.
wkb = approximate_wkb(feature[0])
Predict the next line for this snippet: <|code_start|> nw = self.layer.projection.coordinateLocation(coord.left(buffer).up(buffer)) se = self.layer.projection.coordinateLocation(coord.right(1 + buffer).down(1 + buffer)) ul = self.mercator.locationProj(nw) lr = self.mercator.locationProj(se) self.mapnik.width = width + 2 * self.buffer self.mapnik.height = height + 2 * self.buffer self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y)) # create grid as same size as map/image grid = mapnik.Grid(width + 2 * self.buffer, height + 2 * self.buffer) # render a layer to that grid array mapnik.render_layer(self.mapnik, grid, layer=self.layer_index, fields=self.fields) # extract a gridview excluding the buffer grid_view = grid.view(self.buffer, self.buffer, width, height) # then encode the grid array as utf, resample to 1/scale the size, and dump features grid_utf = grid_view.encode('utf', resolution=self.scale, add_features=True) if self.wrapper is None: return SaveableResponse(json.dumps(grid_utf)) else: return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) + ')') def getTypeByExtension(self, extension): """ Get mime-type and format by file extension. This only accepts "json". """ if extension.lower() != 'json': <|code_end|> with the help of current file imports: import json import os import mapnik from os.path import exists from TileStache.Core import KnownUnknown from TileStache.Geography import getProjectionByName from urllib.parse import urljoin, urlparse from urlparse import urljoin, urlparse from tempfile import mkstemp from urllib import urlopen and context from other files: # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass , which may contain function names, class names, or code. Output only the next line.
raise KnownUnknown('MapnikGrid only makes .json tiles, not "%s"' % extension)
Given snippet: <|code_start|> best_route = None best_dist = 100000000000000 #routes are sorted by length, because we want to use the shortest #route that matches the points. for route in sorted(candidate_routes, key=lambda route:route.the_geom.length): total_dist = 0 for stop in stops: total_dist += route.the_geom.distance(Point(stop.stop_lon, stop.stop_lat)) if total_dist < best_dist: best_dist = total_dist best_route = route if candidate_routes[0].route == 'S55': print "The MTA's route shape for S55 is from 2007. So we're skipping it." return None if candidate_routes[0].route == 'Q48': #this is a total hack; the Q48 is in general a total hack if len(stops) == 22: for route in candidate_routes: if route.gid == 10707: best_route = route #figure out if the set of stops is shorter than the best route #(the bus stops or ends in the middle of the route) and if so, #cut the route down. <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.gis.geos import LineString, Point from django.core.management.base import BaseCommand from mta_data_parser import parse_schedule_dir from mta_data.models import * from mta_data.utils import st_line_locate_point from subway_stop_to_gid import stop_id_to_gid, end_of_line from zipfile import ZipFile import os import re import transitfeed import zipfile import pdb;pdb.set_trace() import traceback import pdb;pdb.set_trace() and context: # Path: mta_data/utils.py # def st_line_locate_point(linestring, p): # # coords = linestring.coords # before_length = after_length = seg_length = 0 # best_dist = 1000000000 # # found = None # for i in range(len(coords) - 1): # p0, p1 = coords[i:i+2] # this_length = sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) **2) # # next four lines from comp.graphics.algorithms Frequently # # Asked Questions via GEOS # # dx=p1[0]-p0[0] # dy=p1[1]-p0[1] # len2=dx*dx+dy*dy # r=((p[0]-p0[0])*dx+(p[1]-p0[1])*dy)/len2 # # if r < 0: # r = 0 # dist = (p0[0] - p[0]) ** 2 + (p0[1] - p[1]) ** 2 # elif r > 1: # r = 1 # dist = (p1[0] - p[0]) ** 2 + (p1[1] - p[1]) ** 2 # # else: # dist = dist_line_point(p0, p1, p) # # if dist < best_dist: # best_dist = dist # # found = r # before_length += after_length + seg_length # after_length = 0 # seg_length = this_length # else: # if found is None: # before_length += this_length # else: # after_length += this_length # # total_length = before_length + seg_length + after_length # before_r = before_length / total_length # seg_r = seg_length / total_length # # return before_r + found * seg_r which might include code, classes, or functions. Output only the next line.
start_location = st_line_locate_point(best_route.the_geom, (stops[0].stop_lon, stops[0].stop_lat))
Here is a snippet: <|code_start|> class Command(BaseCommand): help = "Geocode an address" def handle(self, address, **kw): <|code_end|> . Write the next line using the current file imports: from tracker.views import geocode from django.contrib.gis.geos.geometries import Point from django.core.management.base import BaseCommand import sys and context from other files: # Path: tracker/views.py # def geocode(location): # key = settings.GOOGLE_API_KEY # output = "csv" # location = urllib.quote_plus(location) # request = "http://maps.google.com/maps/geo?q=%s&output=%s&key=%s" % (location, output, key) # data = urllib.urlopen(request).read() # dlist = data.split(',') # if dlist[0] == '200': # return (float(dlist[2]), float(dlist[3])) # else: # return None , which may include functions, classes, or code. Output only the next line.
print geocode(address)
Here is a snippet: <|code_start|># ============================ class LoginForm(FlaskForm): """Sign in form """ email = StringField( 'Email address', validators=[ InputRequired('Please enter your email address'), Email() ]) password = PasswordField( 'Password', widget=PasswordInput(hide_value=False), validators=[ InputRequired('Please enter your password') ]) remember_me = BooleanField( 'Remember me', widget=CheckboxInput(), default=True) def validate_password(form, field): """Verify password """ if not form.email.data: raise StopValidation() # get user and verify password <|code_end|> . Write the next line using the current file imports: from flask import g from flask_wtf import FlaskForm from wtforms import (StringField, PasswordField, BooleanField, TextAreaField, FileField) from wtforms.validators import (InputRequired, Email, URL, EqualTo, ValidationError, StopValidation) from wtforms.widgets import PasswordInput, CheckboxInput from flaskapp.models import User from flaskapp.lib.util import verify_password_hash and context from other files: # Path: flaskapp/models.py # class User(db.Model): # """User object # """ # id = db.Column(db.Integer, primary_key=True) # email = db.Column(db.String(120), index=True, unique=True, nullable=False) # password = db.Column(db.String(60), index=True, nullable=False) # is_verified = db.Column(db.Boolean(), default=False, nullable=False) # password_reset_requests = db.relationship( # 'PasswordResetRequest', # backref=db.backref('user')) # email_verification_requests = db.relationship( # 'EmailVerificationRequest', # backref=db.backref('user')) # # def __repr__(self): # return '<User %r>' % self.email # # # =========================== # # Flask-Login methods # # =========================== # def is_authenticated(self): # return True # # def is_active(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.id # # Path: flaskapp/lib/util.py # def verify_password_hash(password, password_hash): # """Method to centralize the verification of password hash # """ # password = password.encode('utf-8') # return bcrypt.hashpw(password, password_hash) == password_hash , which may include functions, classes, or code. Output only the next line.
u = User.query.filter(User.email == form.email.data).first()
Using the snippet: <|code_start|>class LoginForm(FlaskForm): """Sign in form """ email = StringField( 'Email address', validators=[ InputRequired('Please enter your email address'), Email() ]) password = PasswordField( 'Password', widget=PasswordInput(hide_value=False), validators=[ InputRequired('Please enter your password') ]) remember_me = BooleanField( 'Remember me', widget=CheckboxInput(), default=True) def validate_password(form, field): """Verify password """ if not form.email.data: raise StopValidation() # get user and verify password u = User.query.filter(User.email == form.email.data).first() <|code_end|> , determine the next line of code. You have imports: from flask import g from flask_wtf import FlaskForm from wtforms import (StringField, PasswordField, BooleanField, TextAreaField, FileField) from wtforms.validators import (InputRequired, Email, URL, EqualTo, ValidationError, StopValidation) from wtforms.widgets import PasswordInput, CheckboxInput from flaskapp.models import User from flaskapp.lib.util import verify_password_hash and context (class names, function names, or code) available: # Path: flaskapp/models.py # class User(db.Model): # """User object # """ # id = db.Column(db.Integer, primary_key=True) # email = db.Column(db.String(120), index=True, unique=True, nullable=False) # password = db.Column(db.String(60), index=True, nullable=False) # is_verified = db.Column(db.Boolean(), default=False, nullable=False) # password_reset_requests = db.relationship( # 'PasswordResetRequest', # backref=db.backref('user')) # email_verification_requests = db.relationship( # 'EmailVerificationRequest', # backref=db.backref('user')) # # def __repr__(self): # return '<User %r>' % self.email # # # =========================== # # Flask-Login methods # # =========================== # def is_authenticated(self): # return True # # def is_active(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.id # # Path: flaskapp/lib/util.py # def verify_password_hash(password, password_hash): # """Method to centralize the verification of password hash # """ # password = password.encode('utf-8') # return bcrypt.hashpw(password, password_hash) == password_hash . Output only the next line.
if not u or not verify_password_hash(field.data, u.password):
Using the snippet: <|code_start|> bp = Blueprint('auth', __name__) @bp.route('/login', methods=['GET', 'POST']) def login(): """GET|POST /login: login form handler """ <|code_end|> , determine the next line of code. You have imports: import os import datetime from flask import (Blueprint, render_template, url_for, redirect, request, current_app, g) from flask_login import login_user, logout_user, login_required from flask_principal import identity_changed, Identity, AnonymousIdentity from flask_mail import Message from flask_wtf import FlaskForm from premailer import transform from flaskapp.meta import db, mail from flaskapp.forms import (LoginForm, CreateAccountForm, ForgotPasswordForm, ResetPasswordForm) from flaskapp.models import (User, EmailVerificationRequest, PasswordResetRequest) from flaskapp.lib.util import generate_password_hash and context (class names, function names, or code) available: # Path: flaskapp/forms.py # class LoginForm(FlaskForm): # """Sign in form # """ # email = StringField( # 'Email address', # validators=[ # InputRequired('Please enter your email address'), # Email() # ]) # # password = PasswordField( # 'Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please enter your password') # ]) # # remember_me = BooleanField( # 'Remember me', # widget=CheckboxInput(), # default=True) # # def validate_password(form, field): # """Verify password # """ # if not form.email.data: # raise StopValidation() # # # get user and verify password # u = User.query.filter(User.email == form.email.data).first() # if not u or not verify_password_hash(field.data, u.password): # raise ValidationError('Email and password must match') # # class CreateAccountForm(FlaskForm): # """Create account form # """ # email = StringField( # 'Email address', # validators=[ # InputRequired('Please enter an email address'), # Email() # ]) # # password = PasswordField( # 'Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please choose a password'), # EqualTo('password_confirm', message='Passwords must match') # ]) # # password_confirm = PasswordField( # 'Confirm Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please confirm your password') # ]) # # newsletter = BooleanField( # 'Please send me product updates', # widget=CheckboxInput(), # default=True # ) # # def validate_email(form, field): # """Check if email already exists # """ # u = User.query.filter(User.email == field.data).first() # if u != None: # raise ValidationError('Did your forget your password?') # # class ForgotPasswordForm(FlaskForm): # email = StringField( # 'Email address', # validators=[ # InputRequired('Please enter an email address'), # Email() # ]) # # def validate_email(form, field): # """Check if email exists # """ # u = User.query.filter(User.email == field.data).first() # if u == None: # raise ValidationError('Sorry, %s is not registered' % field.data) # # class ResetPasswordForm(FlaskForm): # password = PasswordField( # 'New Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please choose a password'), # EqualTo('password_confirm', message='Passwords must match') # ]) # # password_confirm = PasswordField( # 'Confirm Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please confirm your password') # ]) # # Path: flaskapp/models.py # class User(db.Model): # """User object # """ # id = db.Column(db.Integer, primary_key=True) # email = db.Column(db.String(120), index=True, unique=True, nullable=False) # password = db.Column(db.String(60), index=True, nullable=False) # is_verified = db.Column(db.Boolean(), default=False, nullable=False) # password_reset_requests = db.relationship( # 'PasswordResetRequest', # backref=db.backref('user')) # email_verification_requests = db.relationship( # 'EmailVerificationRequest', # backref=db.backref('user')) # # def __repr__(self): # return '<User %r>' % self.email # # # =========================== # # Flask-Login methods # # =========================== # def is_authenticated(self): # return True # # def is_active(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.id # # class EmailVerificationRequest(db.Model): # """EmailVerificationRequest object # """ # key = db.Column(db.String(64), primary_key=True) # fk_user = db.Column(db.Integer, db.ForeignKey('user.id')) # create_ts = db.Column(db.DateTime, default=datetime.datetime.utcnow, \ # nullable=False) # # class PasswordResetRequest(db.Model): # """PasswordResetRequest object # """ # key = db.Column(db.String(64), primary_key=True) # fk_user = db.Column(db.Integer, db.ForeignKey('user.id')) # create_ts = db.Column(db.DateTime, default=datetime.datetime.utcnow, \ # nullable=False) # # Path: flaskapp/lib/util.py # def generate_password_hash(password): # """Method to centralize the hashing of passwords # """ # password = password.encode('utf-8') # return bcrypt.hashpw(password, bcrypt.gensalt(12)) . Output only the next line.
form = LoginForm()
Next line prediction: <|code_start|> bp = Blueprint('auth', __name__) @bp.route('/login', methods=['GET', 'POST']) def login(): """GET|POST /login: login form handler """ form = LoginForm() if form.validate_on_submit(): # login user <|code_end|> . Use current file imports: (import os import datetime from flask import (Blueprint, render_template, url_for, redirect, request, current_app, g) from flask_login import login_user, logout_user, login_required from flask_principal import identity_changed, Identity, AnonymousIdentity from flask_mail import Message from flask_wtf import FlaskForm from premailer import transform from flaskapp.meta import db, mail from flaskapp.forms import (LoginForm, CreateAccountForm, ForgotPasswordForm, ResetPasswordForm) from flaskapp.models import (User, EmailVerificationRequest, PasswordResetRequest) from flaskapp.lib.util import generate_password_hash) and context including class names, function names, or small code snippets from other files: # Path: flaskapp/forms.py # class LoginForm(FlaskForm): # """Sign in form # """ # email = StringField( # 'Email address', # validators=[ # InputRequired('Please enter your email address'), # Email() # ]) # # password = PasswordField( # 'Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please enter your password') # ]) # # remember_me = BooleanField( # 'Remember me', # widget=CheckboxInput(), # default=True) # # def validate_password(form, field): # """Verify password # """ # if not form.email.data: # raise StopValidation() # # # get user and verify password # u = User.query.filter(User.email == form.email.data).first() # if not u or not verify_password_hash(field.data, u.password): # raise ValidationError('Email and password must match') # # class CreateAccountForm(FlaskForm): # """Create account form # """ # email = StringField( # 'Email address', # validators=[ # InputRequired('Please enter an email address'), # Email() # ]) # # password = PasswordField( # 'Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please choose a password'), # EqualTo('password_confirm', message='Passwords must match') # ]) # # password_confirm = PasswordField( # 'Confirm Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please confirm your password') # ]) # # newsletter = BooleanField( # 'Please send me product updates', # widget=CheckboxInput(), # default=True # ) # # def validate_email(form, field): # """Check if email already exists # """ # u = User.query.filter(User.email == field.data).first() # if u != None: # raise ValidationError('Did your forget your password?') # # class ForgotPasswordForm(FlaskForm): # email = StringField( # 'Email address', # validators=[ # InputRequired('Please enter an email address'), # Email() # ]) # # def validate_email(form, field): # """Check if email exists # """ # u = User.query.filter(User.email == field.data).first() # if u == None: # raise ValidationError('Sorry, %s is not registered' % field.data) # # class ResetPasswordForm(FlaskForm): # password = PasswordField( # 'New Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please choose a password'), # EqualTo('password_confirm', message='Passwords must match') # ]) # # password_confirm = PasswordField( # 'Confirm Password', # widget=PasswordInput(hide_value=False), # validators=[ # InputRequired('Please confirm your password') # ]) # # Path: flaskapp/models.py # class User(db.Model): # """User object # """ # id = db.Column(db.Integer, primary_key=True) # email = db.Column(db.String(120), index=True, unique=True, nullable=False) # password = db.Column(db.String(60), index=True, nullable=False) # is_verified = db.Column(db.Boolean(), default=False, nullable=False) # password_reset_requests = db.relationship( # 'PasswordResetRequest', # backref=db.backref('user')) # email_verification_requests = db.relationship( # 'EmailVerificationRequest', # backref=db.backref('user')) # # def __repr__(self): # return '<User %r>' % self.email # # # =========================== # # Flask-Login methods # # =========================== # def is_authenticated(self): # return True # # def is_active(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.id # # class EmailVerificationRequest(db.Model): # """EmailVerificationRequest object # """ # key = db.Column(db.String(64), primary_key=True) # fk_user = db.Column(db.Integer, db.ForeignKey('user.id')) # create_ts = db.Column(db.DateTime, default=datetime.datetime.utcnow, \ # nullable=False) # # class PasswordResetRequest(db.Model): # """PasswordResetRequest object # """ # key = db.Column(db.String(64), primary_key=True) # fk_user = db.Column(db.Integer, db.ForeignKey('user.id')) # create_ts = db.Column(db.DateTime, default=datetime.datetime.utcnow, \ # nullable=False) # # Path: flaskapp/lib/util.py # def generate_password_hash(password): # """Method to centralize the hashing of passwords # """ # password = password.encode('utf-8') # return bcrypt.hashpw(password, bcrypt.gensalt(12)) . Output only the next line.
u = User.query.filter(User.email == form.email.data).first()
Given the code snippet: <|code_start|> label_class = Label def __init__(self, description, out_vars=None): super().__init__() if not isinstance(description, str): description = 'c{}'.format( Label(description, None, None).label_value) self.description = description self.out_vars = out_vars self.lmap = _label_context_maps.setdefault(self.description, {}) def Label(self, statement, bound, invariant): label_value = fresh_int(statement, _lmap=self.lmap) return self.label_class( statement, bound=bound, invariant=invariant, context_id=self.description, _label_value=label_value) def __eq__(self, other): if not isinstance(other, self.__class__): return False return self.description == other.description def __repr__(self): return '<{cls}:{description}>'.format( cls=self.__class__, description=self.description) _label_semantics_tuple_type = namedtuple('LabelSemantics', ['label', 'env']) <|code_end|> , generate the next line using the imports in this file: from collections import namedtuple from soap.common import Comparable, Flyweight from soap.datatype import type_of from soap.expression import expression_factory, is_expression from soap.semantics.state import MetaState from soap.semantics.resource import resource_count and context (functions, classes, or occasionally code) from other files: # Path: soap/common/base.py # class Comparable(object): # __slots__ = () # # def __ne__(self, other): # return not self.__eq__(other) # # def __ge__(self, other): # return not self.__lt__(other) # # def __gt__(self, other): # return not self.__eq__(other) and not self.__lt__(other) # # def __le__(self, other): # return not self.__gt__(other) # # Path: soap/common/cache.py # class Flyweight(object): # # _cache = weakref.WeakValueDictionary() # # def __new__(cls, *args, **kwargs): # if not args and not kwargs: # return object.__new__(cls) # key = pickle.dumps((cls, args, list(kwargs.items()))) # v = cls._cache.get(key, None) # if v is not None: # return v # v = object.__new__(cls) # cls._cache[key] = v # return v # # Path: soap/datatype.py # def type_of(value): # if value is None: # return # if isinstance(value, IntegerInterval): # return int_type # if isinstance(value, ErrorSemantics): # return float_type # if isinstance(value, IntegerIntervalArray): # return IntegerArrayType(value.shape) # if isinstance(value, ErrorSemanticsArray): # return FloatArrayType(value.shape) # raise TypeError('Unrecognized type {}'.format(type(value))) # # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True . Output only the next line.
class LabelSemantics(_label_semantics_tuple_type, Flyweight, Comparable):
Continue the code snippet: <|code_start|> _label_map = {} _label_context_maps = {} _label_size = 0 def fresh_int(hashable, _lmap=_label_map): """ Generates a fresh int for the label of `statement`, within the known label mapping `lmap`. """ label_value = _lmap.get(hashable) if label_value is not None: return label_value global _label_size _label_size += 1 _lmap[hashable] = _label_size _lmap[_label_size] = hashable return _label_size label_namedtuple_type = namedtuple( 'Label', ['label_value', 'bound', 'invariant', 'context_id']) <|code_end|> . Use current file imports: from collections import namedtuple from soap.common import Comparable, Flyweight from soap.datatype import type_of from soap.expression import expression_factory, is_expression from soap.semantics.state import MetaState from soap.semantics.resource import resource_count and context (classes, functions, or code) from other files: # Path: soap/common/base.py # class Comparable(object): # __slots__ = () # # def __ne__(self, other): # return not self.__eq__(other) # # def __ge__(self, other): # return not self.__lt__(other) # # def __gt__(self, other): # return not self.__eq__(other) and not self.__lt__(other) # # def __le__(self, other): # return not self.__gt__(other) # # Path: soap/common/cache.py # class Flyweight(object): # # _cache = weakref.WeakValueDictionary() # # def __new__(cls, *args, **kwargs): # if not args and not kwargs: # return object.__new__(cls) # key = pickle.dumps((cls, args, list(kwargs.items()))) # v = cls._cache.get(key, None) # if v is not None: # return v # v = object.__new__(cls) # cls._cache[key] = v # return v # # Path: soap/datatype.py # def type_of(value): # if value is None: # return # if isinstance(value, IntegerInterval): # return int_type # if isinstance(value, ErrorSemantics): # return float_type # if isinstance(value, IntegerIntervalArray): # return IntegerArrayType(value.shape) # if isinstance(value, ErrorSemanticsArray): # return FloatArrayType(value.shape) # raise TypeError('Unrecognized type {}'.format(type(value))) # # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True . Output only the next line.
class Label(label_namedtuple_type, Flyweight):
Given the code snippet: <|code_start|> label_namedtuple_type = namedtuple( 'Label', ['label_value', 'bound', 'invariant', 'context_id']) class Label(label_namedtuple_type, Flyweight): """Constructs a label for expression or statement `statement`""" __slots__ = () _str_brackets = False def __new__(cls, statement, bound, invariant, context_id=None, _label_value=None): label_value = _label_value or fresh_int(statement) return super().__new__(cls, label_value, bound, invariant, context_id) def immu_update(self, bound=None, invariant=None): label = self.label_value bound = bound or self.bound invariant = invariant or self.invariant context_id = self.context_id return self.__class__(label, bound, invariant, context_id) def __getnewargs__(self): return ( None, self.bound, self.invariant, self.context_id, self.label_value) @property def dtype(self): <|code_end|> , generate the next line using the imports in this file: from collections import namedtuple from soap.common import Comparable, Flyweight from soap.datatype import type_of from soap.expression import expression_factory, is_expression from soap.semantics.state import MetaState from soap.semantics.resource import resource_count and context (functions, classes, or occasionally code) from other files: # Path: soap/common/base.py # class Comparable(object): # __slots__ = () # # def __ne__(self, other): # return not self.__eq__(other) # # def __ge__(self, other): # return not self.__lt__(other) # # def __gt__(self, other): # return not self.__eq__(other) and not self.__lt__(other) # # def __le__(self, other): # return not self.__gt__(other) # # Path: soap/common/cache.py # class Flyweight(object): # # _cache = weakref.WeakValueDictionary() # # def __new__(cls, *args, **kwargs): # if not args and not kwargs: # return object.__new__(cls) # key = pickle.dumps((cls, args, list(kwargs.items()))) # v = cls._cache.get(key, None) # if v is not None: # return v # v = object.__new__(cls) # cls._cache[key] = v # return v # # Path: soap/datatype.py # def type_of(value): # if value is None: # return # if isinstance(value, IntegerInterval): # return int_type # if isinstance(value, ErrorSemantics): # return float_type # if isinstance(value, IntegerIntervalArray): # return IntegerArrayType(value.shape) # if isinstance(value, ErrorSemanticsArray): # return FloatArrayType(value.shape) # raise TypeError('Unrecognized type {}'.format(type(value))) # # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True . Output only the next line.
return type_of(self.bound)
Using the snippet: <|code_start|> if not isinstance(env, MetaState): env = MetaState(env) return super().__new__(cls, label, env) def resources(self): return resource_count(self) def expr(self): return self.label.expr() def __iter__(self): return iter((self.label, self.env)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return self.label == other.label and self.env == other.env def __hash__(self): return hash((self.label, self.env)) def __str__(self): return '({}, {})'.format(self.label, self.env) def label_to_expr(node): if isinstance(node, Label): node = node.expr() if is_expression(node): args = (label_to_expr(arg) for arg in node.args) <|code_end|> , determine the next line of code. You have imports: from collections import namedtuple from soap.common import Comparable, Flyweight from soap.datatype import type_of from soap.expression import expression_factory, is_expression from soap.semantics.state import MetaState from soap.semantics.resource import resource_count and context (class names, function names, or code) available: # Path: soap/common/base.py # class Comparable(object): # __slots__ = () # # def __ne__(self, other): # return not self.__eq__(other) # # def __ge__(self, other): # return not self.__lt__(other) # # def __gt__(self, other): # return not self.__eq__(other) and not self.__lt__(other) # # def __le__(self, other): # return not self.__gt__(other) # # Path: soap/common/cache.py # class Flyweight(object): # # _cache = weakref.WeakValueDictionary() # # def __new__(cls, *args, **kwargs): # if not args and not kwargs: # return object.__new__(cls) # key = pickle.dumps((cls, args, list(kwargs.items()))) # v = cls._cache.get(key, None) # if v is not None: # return v # v = object.__new__(cls) # cls._cache[key] = v # return v # # Path: soap/datatype.py # def type_of(value): # if value is None: # return # if isinstance(value, IntegerInterval): # return int_type # if isinstance(value, ErrorSemantics): # return float_type # if isinstance(value, IntegerIntervalArray): # return IntegerArrayType(value.shape) # if isinstance(value, ErrorSemanticsArray): # return FloatArrayType(value.shape) # raise TypeError('Unrecognized type {}'.format(type(value))) # # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True . Output only the next line.
return expression_factory(node.op, *args)
Given the following code snippet before the placeholder: <|code_start|> """The semantics that captures the area of an expression.""" def __new__(cls, label, env): if not isinstance(env, MetaState): env = MetaState(env) return super().__new__(cls, label, env) def resources(self): return resource_count(self) def expr(self): return self.label.expr() def __iter__(self): return iter((self.label, self.env)) def __eq__(self, other): if not isinstance(other, self.__class__): return False return self.label == other.label and self.env == other.env def __hash__(self): return hash((self.label, self.env)) def __str__(self): return '({}, {})'.format(self.label, self.env) def label_to_expr(node): if isinstance(node, Label): node = node.expr() <|code_end|> , predict the next line using imports from the current file: from collections import namedtuple from soap.common import Comparable, Flyweight from soap.datatype import type_of from soap.expression import expression_factory, is_expression from soap.semantics.state import MetaState from soap.semantics.resource import resource_count and context including class names, function names, and sometimes code from other files: # Path: soap/common/base.py # class Comparable(object): # __slots__ = () # # def __ne__(self, other): # return not self.__eq__(other) # # def __ge__(self, other): # return not self.__lt__(other) # # def __gt__(self, other): # return not self.__eq__(other) and not self.__lt__(other) # # def __le__(self, other): # return not self.__gt__(other) # # Path: soap/common/cache.py # class Flyweight(object): # # _cache = weakref.WeakValueDictionary() # # def __new__(cls, *args, **kwargs): # if not args and not kwargs: # return object.__new__(cls) # key = pickle.dumps((cls, args, list(kwargs.items()))) # v = cls._cache.get(key, None) # if v is not None: # return v # v = object.__new__(cls) # cls._cache[key] = v # return v # # Path: soap/datatype.py # def type_of(value): # if value is None: # return # if isinstance(value, IntegerInterval): # return int_type # if isinstance(value, ErrorSemantics): # return float_type # if isinstance(value, IntegerIntervalArray): # return IntegerArrayType(value.shape) # if isinstance(value, ErrorSemanticsArray): # return FloatArrayType(value.shape) # raise TypeError('Unrecognized type {}'.format(type(value))) # # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True . Output only the next line.
if is_expression(node):
Given the code snippet: <|code_start|> class BaseState(base_dispatcher('visit')): """Base state for all program states.""" __slots__ = () @classmethod def empty(cls): return cls(bottom=True) def generic_visit(self, flow): raise TypeError('No method to visit {!r}'.format(flow)) def visit_SkipFlow(self, flow): return self visit_InputFlow = visit_OutputFlow = visit_SkipFlow def visit_AssignFlow(self, flow): <|code_end|> , generate the next line using the imports in this file: from soap.common import base_dispatcher from soap.semantics.functions import arith_eval, bool_eval from soap.program.flow import CompositionalFlow, WhileFlow and context (functions, classes, or occasionally code) from other files: # Path: soap/common/base.py # def base_dispatcher(dispatch_name='execute'): # class Dispatcher(BaseDispatcher): # pass # Dispatcher.dispatch_name = dispatch_name # return Dispatcher # # Path: soap/semantics/functions/arithmetic.py # class ArithmeticEvaluator(base_dispatcher()): # def generic_execute(self, expr, state): # def execute_numeral(self, expr, state): # def execute_PartitionLabel(self, expr, state): # def _execute_args(self, expr, state): # def execute_Variable(self, expr, state): # def execute_UnaryArithExpr(self, expr, state): # def execute_BinaryArithExpr(self, expr, state): # def execute_Subscript(self, expr, state): # def execute_AccessExpr(self, expr, state): # def execute_UpdateExpr(self, expr, state): # def execute_SelectExpr(self, expr, state): # def execute_FixExpr(self, expr, state): # def execute_PreUnrollExpr(self, expr, state): # def execute_MetaState(self, meta_state, state): # def __call__(self, expr, state): # def __eq__(self, other): # def __hash__(self): # def _to_norm(value): # def error_eval(expr, state, to_norm=True): # # Path: soap/semantics/functions/boolean.py # @cached # def bool_eval(expr, state): # if state.is_bottom(): # return state, state # constraints = construct(expr) # true_list, false_list = [], [] # for cstr in constraints: # cstr_list = [] # for cmp_expr in cstr: # cmp_eval_list = [ # _comparison_eval(cmp_expr, state) # for cmp_expr in _bool_transform(cmp_expr)] # cstr_list += cmp_eval_list # if not cstr_list: # # empty, don't know how to constraint values # return state, state # true, false = zip(*cstr_list) # true_list.append(meet(true)) # false_list.append(join(false)) # return join(true_list), meet(false_list) # # Path: soap/program/flow.py # class CompositionalFlow(Flow): # """Flow for program composition. # # Combines multiple flow objects into a unified flow. # """ # def __init__(self, flows=None): # super().__init__() # new_flows = [] # for flow in (flows or []): # if isinstance(flow, CompositionalFlow): # new_flows += flow.flows # else: # new_flows.append(flow) # self.flows = tuple(new_flows) # # def transition(self, state): # for flow in self.flows: # state = flow.transition(state) # return state # # def __bool__(self): # return any(self.flows) # # def format(self): # return '\n'.join(flow.format() for flow in self.flows) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return self.flows == other.flows # # def __repr__(self): # return '{cls}(flows={flows!r})'.format( # cls=self.__class__.__name__, flows=self.flows) # # def __hash__(self): # return hash(self.flows) # # class WhileFlow(Flow): # """Program flow for conditional while loops. """ # # def __init__(self, conditional_expr, loop_flow): # super().__init__() # self.conditional_expr = conditional_expr # self.loop_flow = loop_flow # # def format(self): # loop_format = indent(self.loop_flow.format()) # template = 'while ({conditional_expr}) {{\n{loop_format}}} ' # return template.format( # conditional_expr=self.conditional_expr, loop_format=loop_format) # # def __repr__(self): # return '{cls}(conditional_expr={expr!r}, loop_flow={flow!r})'.format( # cls=self.__class__.__name__, expr=self.conditional_expr, # flow=self.loop_flow) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return (self.conditional_expr == other.conditional_expr and # self.loop_flow == other.loop_flow) # # def __hash__(self): # return hash((self.conditional_expr, self.loop_flow)) . Output only the next line.
return self.immu_update(flow.var, arith_eval(flow.expr, self))
Predict the next line for this snippet: <|code_start|> class BaseState(base_dispatcher('visit')): """Base state for all program states.""" __slots__ = () @classmethod def empty(cls): return cls(bottom=True) def generic_visit(self, flow): raise TypeError('No method to visit {!r}'.format(flow)) def visit_SkipFlow(self, flow): return self visit_InputFlow = visit_OutputFlow = visit_SkipFlow def visit_AssignFlow(self, flow): return self.immu_update(flow.var, arith_eval(flow.expr, self)) def visit_IfFlow(self, flow): bool_expr = flow.conditional_expr <|code_end|> with the help of current file imports: from soap.common import base_dispatcher from soap.semantics.functions import arith_eval, bool_eval from soap.program.flow import CompositionalFlow, WhileFlow and context from other files: # Path: soap/common/base.py # def base_dispatcher(dispatch_name='execute'): # class Dispatcher(BaseDispatcher): # pass # Dispatcher.dispatch_name = dispatch_name # return Dispatcher # # Path: soap/semantics/functions/arithmetic.py # class ArithmeticEvaluator(base_dispatcher()): # def generic_execute(self, expr, state): # def execute_numeral(self, expr, state): # def execute_PartitionLabel(self, expr, state): # def _execute_args(self, expr, state): # def execute_Variable(self, expr, state): # def execute_UnaryArithExpr(self, expr, state): # def execute_BinaryArithExpr(self, expr, state): # def execute_Subscript(self, expr, state): # def execute_AccessExpr(self, expr, state): # def execute_UpdateExpr(self, expr, state): # def execute_SelectExpr(self, expr, state): # def execute_FixExpr(self, expr, state): # def execute_PreUnrollExpr(self, expr, state): # def execute_MetaState(self, meta_state, state): # def __call__(self, expr, state): # def __eq__(self, other): # def __hash__(self): # def _to_norm(value): # def error_eval(expr, state, to_norm=True): # # Path: soap/semantics/functions/boolean.py # @cached # def bool_eval(expr, state): # if state.is_bottom(): # return state, state # constraints = construct(expr) # true_list, false_list = [], [] # for cstr in constraints: # cstr_list = [] # for cmp_expr in cstr: # cmp_eval_list = [ # _comparison_eval(cmp_expr, state) # for cmp_expr in _bool_transform(cmp_expr)] # cstr_list += cmp_eval_list # if not cstr_list: # # empty, don't know how to constraint values # return state, state # true, false = zip(*cstr_list) # true_list.append(meet(true)) # false_list.append(join(false)) # return join(true_list), meet(false_list) # # Path: soap/program/flow.py # class CompositionalFlow(Flow): # """Flow for program composition. # # Combines multiple flow objects into a unified flow. # """ # def __init__(self, flows=None): # super().__init__() # new_flows = [] # for flow in (flows or []): # if isinstance(flow, CompositionalFlow): # new_flows += flow.flows # else: # new_flows.append(flow) # self.flows = tuple(new_flows) # # def transition(self, state): # for flow in self.flows: # state = flow.transition(state) # return state # # def __bool__(self): # return any(self.flows) # # def format(self): # return '\n'.join(flow.format() for flow in self.flows) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return self.flows == other.flows # # def __repr__(self): # return '{cls}(flows={flows!r})'.format( # cls=self.__class__.__name__, flows=self.flows) # # def __hash__(self): # return hash(self.flows) # # class WhileFlow(Flow): # """Program flow for conditional while loops. """ # # def __init__(self, conditional_expr, loop_flow): # super().__init__() # self.conditional_expr = conditional_expr # self.loop_flow = loop_flow # # def format(self): # loop_format = indent(self.loop_flow.format()) # template = 'while ({conditional_expr}) {{\n{loop_format}}} ' # return template.format( # conditional_expr=self.conditional_expr, loop_format=loop_format) # # def __repr__(self): # return '{cls}(conditional_expr={expr!r}, loop_flow={flow!r})'.format( # cls=self.__class__.__name__, expr=self.conditional_expr, # flow=self.loop_flow) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return (self.conditional_expr == other.conditional_expr and # self.loop_flow == other.loop_flow) # # def __hash__(self): # return hash((self.conditional_expr, self.loop_flow)) , which may contain function names, class names, or code. Output only the next line.
true_split, false_split = bool_eval(bool_expr, self)
Based on the snippet: <|code_start|> __slots__ = () @classmethod def empty(cls): return cls(bottom=True) def generic_visit(self, flow): raise TypeError('No method to visit {!r}'.format(flow)) def visit_SkipFlow(self, flow): return self visit_InputFlow = visit_OutputFlow = visit_SkipFlow def visit_AssignFlow(self, flow): return self.immu_update(flow.var, arith_eval(flow.expr, self)) def visit_IfFlow(self, flow): bool_expr = flow.conditional_expr true_split, false_split = bool_eval(bool_expr, self) true_split = true_split.transition(flow.true_flow) false_split = false_split.transition(flow.false_flow) return true_split | false_split def visit_WhileFlow(self, flow): raise NotImplementedError('Override this method.') def visit_ForFlow(self, flow): state = self.transition(flow.init_flow) loop_flows = flow.loop_flow <|code_end|> , predict the immediate next line with the help of imports: from soap.common import base_dispatcher from soap.semantics.functions import arith_eval, bool_eval from soap.program.flow import CompositionalFlow, WhileFlow and context (classes, functions, sometimes code) from other files: # Path: soap/common/base.py # def base_dispatcher(dispatch_name='execute'): # class Dispatcher(BaseDispatcher): # pass # Dispatcher.dispatch_name = dispatch_name # return Dispatcher # # Path: soap/semantics/functions/arithmetic.py # class ArithmeticEvaluator(base_dispatcher()): # def generic_execute(self, expr, state): # def execute_numeral(self, expr, state): # def execute_PartitionLabel(self, expr, state): # def _execute_args(self, expr, state): # def execute_Variable(self, expr, state): # def execute_UnaryArithExpr(self, expr, state): # def execute_BinaryArithExpr(self, expr, state): # def execute_Subscript(self, expr, state): # def execute_AccessExpr(self, expr, state): # def execute_UpdateExpr(self, expr, state): # def execute_SelectExpr(self, expr, state): # def execute_FixExpr(self, expr, state): # def execute_PreUnrollExpr(self, expr, state): # def execute_MetaState(self, meta_state, state): # def __call__(self, expr, state): # def __eq__(self, other): # def __hash__(self): # def _to_norm(value): # def error_eval(expr, state, to_norm=True): # # Path: soap/semantics/functions/boolean.py # @cached # def bool_eval(expr, state): # if state.is_bottom(): # return state, state # constraints = construct(expr) # true_list, false_list = [], [] # for cstr in constraints: # cstr_list = [] # for cmp_expr in cstr: # cmp_eval_list = [ # _comparison_eval(cmp_expr, state) # for cmp_expr in _bool_transform(cmp_expr)] # cstr_list += cmp_eval_list # if not cstr_list: # # empty, don't know how to constraint values # return state, state # true, false = zip(*cstr_list) # true_list.append(meet(true)) # false_list.append(join(false)) # return join(true_list), meet(false_list) # # Path: soap/program/flow.py # class CompositionalFlow(Flow): # """Flow for program composition. # # Combines multiple flow objects into a unified flow. # """ # def __init__(self, flows=None): # super().__init__() # new_flows = [] # for flow in (flows or []): # if isinstance(flow, CompositionalFlow): # new_flows += flow.flows # else: # new_flows.append(flow) # self.flows = tuple(new_flows) # # def transition(self, state): # for flow in self.flows: # state = flow.transition(state) # return state # # def __bool__(self): # return any(self.flows) # # def format(self): # return '\n'.join(flow.format() for flow in self.flows) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return self.flows == other.flows # # def __repr__(self): # return '{cls}(flows={flows!r})'.format( # cls=self.__class__.__name__, flows=self.flows) # # def __hash__(self): # return hash(self.flows) # # class WhileFlow(Flow): # """Program flow for conditional while loops. """ # # def __init__(self, conditional_expr, loop_flow): # super().__init__() # self.conditional_expr = conditional_expr # self.loop_flow = loop_flow # # def format(self): # loop_format = indent(self.loop_flow.format()) # template = 'while ({conditional_expr}) {{\n{loop_format}}} ' # return template.format( # conditional_expr=self.conditional_expr, loop_format=loop_format) # # def __repr__(self): # return '{cls}(conditional_expr={expr!r}, loop_flow={flow!r})'.format( # cls=self.__class__.__name__, expr=self.conditional_expr, # flow=self.loop_flow) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return (self.conditional_expr == other.conditional_expr and # self.loop_flow == other.loop_flow) # # def __hash__(self): # return hash((self.conditional_expr, self.loop_flow)) . Output only the next line.
if isinstance(loop_flows, CompositionalFlow):
Predict the next line for this snippet: <|code_start|> def generic_visit(self, flow): raise TypeError('No method to visit {!r}'.format(flow)) def visit_SkipFlow(self, flow): return self visit_InputFlow = visit_OutputFlow = visit_SkipFlow def visit_AssignFlow(self, flow): return self.immu_update(flow.var, arith_eval(flow.expr, self)) def visit_IfFlow(self, flow): bool_expr = flow.conditional_expr true_split, false_split = bool_eval(bool_expr, self) true_split = true_split.transition(flow.true_flow) false_split = false_split.transition(flow.false_flow) return true_split | false_split def visit_WhileFlow(self, flow): raise NotImplementedError('Override this method.') def visit_ForFlow(self, flow): state = self.transition(flow.init_flow) loop_flows = flow.loop_flow if isinstance(loop_flows, CompositionalFlow): loop_flows = loop_flows.flows else: loop_flows = [loop_flows] loop_flow = CompositionalFlow(loop_flows + [flow.incr_flow]) <|code_end|> with the help of current file imports: from soap.common import base_dispatcher from soap.semantics.functions import arith_eval, bool_eval from soap.program.flow import CompositionalFlow, WhileFlow and context from other files: # Path: soap/common/base.py # def base_dispatcher(dispatch_name='execute'): # class Dispatcher(BaseDispatcher): # pass # Dispatcher.dispatch_name = dispatch_name # return Dispatcher # # Path: soap/semantics/functions/arithmetic.py # class ArithmeticEvaluator(base_dispatcher()): # def generic_execute(self, expr, state): # def execute_numeral(self, expr, state): # def execute_PartitionLabel(self, expr, state): # def _execute_args(self, expr, state): # def execute_Variable(self, expr, state): # def execute_UnaryArithExpr(self, expr, state): # def execute_BinaryArithExpr(self, expr, state): # def execute_Subscript(self, expr, state): # def execute_AccessExpr(self, expr, state): # def execute_UpdateExpr(self, expr, state): # def execute_SelectExpr(self, expr, state): # def execute_FixExpr(self, expr, state): # def execute_PreUnrollExpr(self, expr, state): # def execute_MetaState(self, meta_state, state): # def __call__(self, expr, state): # def __eq__(self, other): # def __hash__(self): # def _to_norm(value): # def error_eval(expr, state, to_norm=True): # # Path: soap/semantics/functions/boolean.py # @cached # def bool_eval(expr, state): # if state.is_bottom(): # return state, state # constraints = construct(expr) # true_list, false_list = [], [] # for cstr in constraints: # cstr_list = [] # for cmp_expr in cstr: # cmp_eval_list = [ # _comparison_eval(cmp_expr, state) # for cmp_expr in _bool_transform(cmp_expr)] # cstr_list += cmp_eval_list # if not cstr_list: # # empty, don't know how to constraint values # return state, state # true, false = zip(*cstr_list) # true_list.append(meet(true)) # false_list.append(join(false)) # return join(true_list), meet(false_list) # # Path: soap/program/flow.py # class CompositionalFlow(Flow): # """Flow for program composition. # # Combines multiple flow objects into a unified flow. # """ # def __init__(self, flows=None): # super().__init__() # new_flows = [] # for flow in (flows or []): # if isinstance(flow, CompositionalFlow): # new_flows += flow.flows # else: # new_flows.append(flow) # self.flows = tuple(new_flows) # # def transition(self, state): # for flow in self.flows: # state = flow.transition(state) # return state # # def __bool__(self): # return any(self.flows) # # def format(self): # return '\n'.join(flow.format() for flow in self.flows) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return self.flows == other.flows # # def __repr__(self): # return '{cls}(flows={flows!r})'.format( # cls=self.__class__.__name__, flows=self.flows) # # def __hash__(self): # return hash(self.flows) # # class WhileFlow(Flow): # """Program flow for conditional while loops. """ # # def __init__(self, conditional_expr, loop_flow): # super().__init__() # self.conditional_expr = conditional_expr # self.loop_flow = loop_flow # # def format(self): # loop_format = indent(self.loop_flow.format()) # template = 'while ({conditional_expr}) {{\n{loop_format}}} ' # return template.format( # conditional_expr=self.conditional_expr, loop_format=loop_format) # # def __repr__(self): # return '{cls}(conditional_expr={expr!r}, loop_flow={flow!r})'.format( # cls=self.__class__.__name__, expr=self.conditional_expr, # flow=self.loop_flow) # # def __eq__(self, other): # if type(self) is not type(other): # return False # return (self.conditional_expr == other.conditional_expr and # self.loop_flow == other.loop_flow) # # def __hash__(self): # return hash((self.conditional_expr, self.loop_flow)) , which may contain function names, class names, or code. Output only the next line.
while_flow = WhileFlow(flow.conditional_expr, loop_flow)
Using the snippet: <|code_start|> self._add_projection_lines(xmin, ymin, zmin) ax3d.set_xlim(xmin, xmax) ax3d.set_ylim(ymin, ymax) ax3d.set_zlim(zmin, zmax) def _set_labels(self): """Set names for axes. """ ax3d = self.ax3d ax3d.set_xlabel('Resources (LUTs)') ax3d.xaxis.get_major_formatter().set_scientific(True) ax3d.xaxis.get_major_formatter().set_powerlimits((-3, 3)) ax3d.set_ylabel('Error') ax3d.yaxis.get_major_formatter().set_scientific(True) ax3d.yaxis.get_major_formatter().set_powerlimits((-3, 4)) ax3d.set_zlabel('Latency') def _add_legend(self): legends = [] proxies = [] for color, marker, legend in self.legends: proxy = matplotlib.lines.Line2D( [0], [0], linestyle="none", color=color, marker=marker) proxies.append(proxy) legends.append(legend) self.ax3d.legend(proxies, legends, numpoints=1) def finalize(self): if self.is_finalized: return self.is_finalized = True <|code_end|> , determine the next line of code. You have imports: import itertools import matplotlib from matplotlib import rc, pyplot from mpl_toolkits.mplot3d import Axes3D from soap import logger from soap.analysis.core import pareto_frontier and context (class names, function names, or code) available: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/analysis/core.py # def pareto_frontier(points, ignore_last=True): # frontier = _pareto_frontier(points, ignore_last)[0] # return frontier . Output only the next line.
logger.debug('Finalizing plot...')
Given the following code snippet before the placeholder: <|code_start|> figure = self.figure = pyplot.figure() self.ax3d = Axes3D(figure) self.colors = itertools.cycle('rgbkcmy') self.markers = itertools.cycle('+ox.sv^<>') self.legends = [] self.projection_results = [] self.is_finalized = False def values(self, result): return result.lut, result.error, result.latency, result.expression def add_original(self, original_point): self.add([original_point], 'Original') def add(self, optimized_results, legend=None): if self.is_finalized: raise PlotFinalizedError values = [self.values(r) for r in optimized_results] luts, errors, lats, exprs = zip(*values) color = next(self.colors) marker = next(self.markers) self.ax3d.scatter( luts, errors, lats, s=100, color=color, marker=marker) # add legend text to add later self.legends.append((color, marker, legend)) # add results to plot projections later self.projection_results.append((color, values)) def _add_projection_frontiers(self, xmin, xmax, ymin, ymax, zmin, zmax): def frontier(x, y, start, stop): <|code_end|> , predict the next line using imports from the current file: import itertools import matplotlib from matplotlib import rc, pyplot from mpl_toolkits.mplot3d import Axes3D from soap import logger from soap.analysis.core import pareto_frontier and context including class names, function names, and sometimes code from other files: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/analysis/core.py # def pareto_frontier(points, ignore_last=True): # frontier = _pareto_frontier(points, ignore_last)[0] # return frontier . Output only the next line.
points = pareto_frontier(zip(x, y), ignore_last=False)
Using the snippet: <|code_start|>""" .. module:: soap.expression.variable :synopsis: The class of variables. """ class Variable(ArithmeticMixin, BooleanMixin, BinaryExpression): """The variable class.""" __slots__ = () _str_brackets = False <|code_end|> , determine the next line of code. You have imports: import collections from soap.datatype import auto_type from soap.expression.arithmetic import ArithmeticMixin from soap.expression.base import Expression, BinaryExpression from soap.expression.boolean import BooleanMixin from soap.expression.operators import EXTERNAL_OP, VARIABLE_OP and context (class names, function names, or code) available: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/expression/arithmetic.py # class ArithmeticMixin(object): # # def __add__(self, other): # return BinaryArithExpr(ADD_OP, self, other) # # def __sub__(self, other): # return BinaryArithExpr(SUBTRACT_OP, self, other) # # def __mul__(self, other): # return BinaryArithExpr(MULTIPLY_OP, self, other) # # def __div__(self, other): # return BinaryArithExpr(DIVIDE_OP, self, other) # # def __neg__(self): # return UnaryArithExpr(UNARY_SUBTRACT_OP, self) # # Path: soap/expression/base.py # class Expression(Flyweight): # """A base class for expressions.""" # # __slots__ = ('_op', '_args', '_hash') # _str_brackets = True # # def __init__(self, op, *args): # super().__init__() # if not args and not all(args): # raise ValueError('There is no arguments.') # self._op = op # self._args = args # self._hash = None # # def __setstate__(self, state): # self._hash = None # state = state[1] # self._op = state['_op'] # self._args = state['_args'] # # @property # def op(self): # return self._op # # @property # def args(self): # return self._args # # @property # def arity(self): # return len(self.args) # # def vars(self): # return expression_variables(self) # # def _args_to_str(self): # def format(expr): # if is_numeral(expr): # brackets = False # else: # brackets = getattr(expr, '_str_brackets', True) # if is_expression(expr): # expr = expr.format() # text = '({})' if brackets else '{}' # return text.format(expr) # return [format(a) for a in self.args] # # def __repr__(self): # args = ', '.join('a{}={!r}'.format(i + 1, a) # for i, a in enumerate(self.args)) # return "{name}(op={op!r}, {args})".format( # name=self.__class__.__name__, op=self.op, args=args) # # def format(self): # raise NotImplementedError( # 'Override this method for {}'.format(self.__class__)) # # def __str__(self): # return self.format().replace(' ', '').replace('\n', '').strip() # # def _attr(self): # return (self.op, self.args) # # def __eq__(self, other): # if not isinstance(other, Expression): # return False # if id(self) == id(other): # return True # if type(self) is not type(other) or hash(self) != hash(other): # return False # return self._attr() == other._attr() # # def __ne__(self, other): # return not self == other # # def __hash__(self): # if self._hash: # return self._hash # self._hash = hash(self._attr()) # return self._hash # # class BinaryExpression(Expression): # """A binary expression class. Instance has two arguments.""" # # __slots__ = () # # def __init__(self, op, a1, a2): # super().__init__(op, a1, a2) # # @property # def a1(self): # return self.args[0] # # @property # def a2(self): # return self.args[1] # # def format(self): # a1, a2 = self._args_to_str() # return '{a1} {op} {a2}'.format(op=self.op, a1=a1, a2=a2) # # Path: soap/expression/boolean.py # class BooleanMixin(object): # # def __invert__(self): # return UnaryBoolExpr(operators.UNARY_NEGATION_OP, self) # # def __and__(self, other): # return BinaryBoolExpr(operators.AND_OP, self, other) # # def __or__(self, other): # return BinaryBoolExpr(operators.OR_OP, self, other) # # Path: soap/expression/operators.py # EXTERNAL_OP = 'extern' # # VARIABLE_OP = 'v' . Output only the next line.
def __init__(self, name, dtype=auto_type):
Next line prediction: <|code_start|>""" .. module:: soap.expression.variable :synopsis: The class of variables. """ class Variable(ArithmeticMixin, BooleanMixin, BinaryExpression): """The variable class.""" __slots__ = () _str_brackets = False def __init__(self, name, dtype=auto_type): <|code_end|> . Use current file imports: (import collections from soap.datatype import auto_type from soap.expression.arithmetic import ArithmeticMixin from soap.expression.base import Expression, BinaryExpression from soap.expression.boolean import BooleanMixin from soap.expression.operators import EXTERNAL_OP, VARIABLE_OP) and context including class names, function names, or small code snippets from other files: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/expression/arithmetic.py # class ArithmeticMixin(object): # # def __add__(self, other): # return BinaryArithExpr(ADD_OP, self, other) # # def __sub__(self, other): # return BinaryArithExpr(SUBTRACT_OP, self, other) # # def __mul__(self, other): # return BinaryArithExpr(MULTIPLY_OP, self, other) # # def __div__(self, other): # return BinaryArithExpr(DIVIDE_OP, self, other) # # def __neg__(self): # return UnaryArithExpr(UNARY_SUBTRACT_OP, self) # # Path: soap/expression/base.py # class Expression(Flyweight): # """A base class for expressions.""" # # __slots__ = ('_op', '_args', '_hash') # _str_brackets = True # # def __init__(self, op, *args): # super().__init__() # if not args and not all(args): # raise ValueError('There is no arguments.') # self._op = op # self._args = args # self._hash = None # # def __setstate__(self, state): # self._hash = None # state = state[1] # self._op = state['_op'] # self._args = state['_args'] # # @property # def op(self): # return self._op # # @property # def args(self): # return self._args # # @property # def arity(self): # return len(self.args) # # def vars(self): # return expression_variables(self) # # def _args_to_str(self): # def format(expr): # if is_numeral(expr): # brackets = False # else: # brackets = getattr(expr, '_str_brackets', True) # if is_expression(expr): # expr = expr.format() # text = '({})' if brackets else '{}' # return text.format(expr) # return [format(a) for a in self.args] # # def __repr__(self): # args = ', '.join('a{}={!r}'.format(i + 1, a) # for i, a in enumerate(self.args)) # return "{name}(op={op!r}, {args})".format( # name=self.__class__.__name__, op=self.op, args=args) # # def format(self): # raise NotImplementedError( # 'Override this method for {}'.format(self.__class__)) # # def __str__(self): # return self.format().replace(' ', '').replace('\n', '').strip() # # def _attr(self): # return (self.op, self.args) # # def __eq__(self, other): # if not isinstance(other, Expression): # return False # if id(self) == id(other): # return True # if type(self) is not type(other) or hash(self) != hash(other): # return False # return self._attr() == other._attr() # # def __ne__(self, other): # return not self == other # # def __hash__(self): # if self._hash: # return self._hash # self._hash = hash(self._attr()) # return self._hash # # class BinaryExpression(Expression): # """A binary expression class. Instance has two arguments.""" # # __slots__ = () # # def __init__(self, op, a1, a2): # super().__init__(op, a1, a2) # # @property # def a1(self): # return self.args[0] # # @property # def a2(self): # return self.args[1] # # def format(self): # a1, a2 = self._args_to_str() # return '{a1} {op} {a2}'.format(op=self.op, a1=a1, a2=a2) # # Path: soap/expression/boolean.py # class BooleanMixin(object): # # def __invert__(self): # return UnaryBoolExpr(operators.UNARY_NEGATION_OP, self) # # def __and__(self, other): # return BinaryBoolExpr(operators.AND_OP, self, other) # # def __or__(self, other): # return BinaryBoolExpr(operators.OR_OP, self, other) # # Path: soap/expression/operators.py # EXTERNAL_OP = 'extern' # # VARIABLE_OP = 'v' . Output only the next line.
super().__init__(VARIABLE_OP, name, dtype)
Next line prediction: <|code_start|> continue except (TypeError, ValueError): pass # a range is a port try: a, b = i.e float(a), float(b) in_ports.add(i) continue except (TypeError, ValueError): pass # an expression, need a signal for its output try: i.e.op if i != out_port: signals.add(i) except AttributeError: pass wires.add((op, wire_name(in1), wire_name(in2), wire_name(out))) for out, e in ls.items(): try: op, in1, in2 = e.op, e.a1, e.a2 wire(op, in1, in2, out) ops.add(e.op) except AttributeError: pass in_ports = [i.port_name() for i in in_ports] out_port = 'p_out' signals = [i.signal_name() for i in signals] <|code_end|> . Use current file imports: (import itertools import pickle import shutil import tempfile import sh import sh from soap import logger from soap.flopoco.common import cd, template_file, flopoco, xilinx from soap.expression import Expr from akpytemp import Template from multiprocessing import Pool from matplotlib import rc from matplotlib import pyplot, pylab from matplotlib import pyplot from soap.transformer.utils import greedy_trace from soap.flopoco.common import wf_range) and context including class names, function names, or small code snippets from other files: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/flopoco/common.py # def cd(d): # def flopoco_key(fop, we=-1, wf=-1, wi=-1): # def flopoco(key, file_name=None, dir_name=None): # def get_luts(file_name): # def xilinx(file_name, dir_name=None): # def _datatype_exponent(op, label): # _FILTER_OPERATORS = operators.TRADITIONAL_OPERATORS + [ # operators.TERNARY_SELECT_OP # ] . Output only the next line.
logger.debug(in_ports, signals, wires)
Given snippet: <|code_start|> class _RTLGenerator(object): def __init__(self, expr, var_env, prec, file_name=None, dir=None): self.expr = Expr(expr) self.var_env = var_env self.wf = prec self.we = self.expr.exponent_width(var_env, prec) self.dir = dir or tempfile.mktemp(suffix='/') <|code_end|> , continue by predicting the next line. Consider current file imports: import itertools import pickle import shutil import tempfile import sh import sh from soap import logger from soap.flopoco.common import cd, template_file, flopoco, xilinx from soap.expression import Expr from akpytemp import Template from multiprocessing import Pool from matplotlib import rc from matplotlib import pyplot, pylab from matplotlib import pyplot from soap.transformer.utils import greedy_trace from soap.flopoco.common import wf_range and context: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/flopoco/common.py # def cd(d): # def flopoco_key(fop, we=-1, wf=-1, wi=-1): # def flopoco(key, file_name=None, dir_name=None): # def get_luts(file_name): # def xilinx(file_name, dir_name=None): # def _datatype_exponent(op, label): # _FILTER_OPERATORS = operators.TRADITIONAL_OPERATORS + [ # operators.TERNARY_SELECT_OP # ] which might include code, classes, or functions. Output only the next line.
with cd(self.dir):
Predict the next line after this snippet: <|code_start|> except (TypeError, ValueError): pass # a range is a port try: a, b = i.e float(a), float(b) in_ports.add(i) continue except (TypeError, ValueError): pass # an expression, need a signal for its output try: i.e.op if i != out_port: signals.add(i) except AttributeError: pass wires.add((op, wire_name(in1), wire_name(in2), wire_name(out))) for out, e in ls.items(): try: op, in1, in2 = e.op, e.a1, e.a2 wire(op, in1, in2, out) ops.add(e.op) except AttributeError: pass in_ports = [i.port_name() for i in in_ports] out_port = 'p_out' signals = [i.signal_name() for i in signals] logger.debug(in_ports, signals, wires) <|code_end|> using the current file's imports: import itertools import pickle import shutil import tempfile import sh import sh from soap import logger from soap.flopoco.common import cd, template_file, flopoco, xilinx from soap.expression import Expr from akpytemp import Template from multiprocessing import Pool from matplotlib import rc from matplotlib import pyplot, pylab from matplotlib import pyplot from soap.transformer.utils import greedy_trace from soap.flopoco.common import wf_range and any relevant context from other files: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/flopoco/common.py # def cd(d): # def flopoco_key(fop, we=-1, wf=-1, wi=-1): # def flopoco(key, file_name=None, dir_name=None): # def get_luts(file_name): # def xilinx(file_name, dir_name=None): # def _datatype_exponent(op, label): # _FILTER_OPERATORS = operators.TRADITIONAL_OPERATORS + [ # operators.TERNARY_SELECT_OP # ] . Output only the next line.
Template(path=template_file).save(
Given the following code snippet before the placeholder: <|code_start|> pass # a range is a port try: a, b = i.e float(a), float(b) in_ports.add(i) continue except (TypeError, ValueError): pass # an expression, need a signal for its output try: i.e.op if i != out_port: signals.add(i) except AttributeError: pass wires.add((op, wire_name(in1), wire_name(in2), wire_name(out))) for out, e in ls.items(): try: op, in1, in2 = e.op, e.a1, e.a2 wire(op, in1, in2, out) ops.add(e.op) except AttributeError: pass in_ports = [i.port_name() for i in in_ports] out_port = 'p_out' signals = [i.signal_name() for i in signals] logger.debug(in_ports, signals, wires) Template(path=template_file).save( <|code_end|> , predict the next line using imports from the current file: import itertools import pickle import shutil import tempfile import sh import sh from soap import logger from soap.flopoco.common import cd, template_file, flopoco, xilinx from soap.expression import Expr from akpytemp import Template from multiprocessing import Pool from matplotlib import rc from matplotlib import pyplot, pylab from matplotlib import pyplot from soap.transformer.utils import greedy_trace from soap.flopoco.common import wf_range and context including class names, function names, and sometimes code from other files: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/flopoco/common.py # def cd(d): # def flopoco_key(fop, we=-1, wf=-1, wi=-1): # def flopoco(key, file_name=None, dir_name=None): # def get_luts(file_name): # def xilinx(file_name, dir_name=None): # def _datatype_exponent(op, label): # _FILTER_OPERATORS = operators.TRADITIONAL_OPERATORS + [ # operators.TERNARY_SELECT_OP # ] . Output only the next line.
path=self.f, directory=self.dir, flopoco=flopoco,
Based on the snippet: <|code_start|> signals.add(i) except AttributeError: pass wires.add((op, wire_name(in1), wire_name(in2), wire_name(out))) for out, e in ls.items(): try: op, in1, in2 = e.op, e.a1, e.a2 wire(op, in1, in2, out) ops.add(e.op) except AttributeError: pass in_ports = [i.port_name() for i in in_ports] out_port = 'p_out' signals = [i.signal_name() for i in signals] logger.debug(in_ports, signals, wires) Template(path=template_file).save( path=self.f, directory=self.dir, flopoco=flopoco, ops=ops, e=self.expr, we=self.we, wf=self.wf, in_ports=in_ports, out_port=out_port, signals=signals, wires=wires) return self.f def actual_luts(expr, var_env, prec): dir = tempfile.mktemp(suffix='/') f = _RTLGenerator(expr, var_env, prec, dir=dir).generate() logger.debug('Synthesising', str(expr), 'with precision', prec, 'in', f) try: <|code_end|> , predict the immediate next line with the help of imports: import itertools import pickle import shutil import tempfile import sh import sh from soap import logger from soap.flopoco.common import cd, template_file, flopoco, xilinx from soap.expression import Expr from akpytemp import Template from multiprocessing import Pool from matplotlib import rc from matplotlib import pyplot, pylab from matplotlib import pyplot from soap.transformer.utils import greedy_trace from soap.flopoco.common import wf_range and context (classes, functions, sometimes code) from other files: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): # # Path: soap/flopoco/common.py # def cd(d): # def flopoco_key(fop, we=-1, wf=-1, wi=-1): # def flopoco(key, file_name=None, dir_name=None): # def get_luts(file_name): # def xilinx(file_name, dir_name=None): # def _datatype_exponent(op, label): # _FILTER_OPERATORS = operators.TRADITIONAL_OPERATORS + [ # operators.TERNARY_SELECT_OP # ] . Output only the next line.
return xilinx(f, dir=dir)
Here is a snippet: <|code_start|> gmpy2.set_context(gmpy2.ieee(64)) _repr = builtins.repr _str = builtins.str _soap_classes = [c for c in dir(soap) if inspect.isclass(c)] def _run_line_magic(magic, value): with open(os.devnull, 'w') as null: with contextlib.redirect_stdout(null): shell.run_line_magic(magic, value) <|code_end|> . Write the next line using the current file imports: import builtins import contextlib import inspect import os import gmpy2 import soap from soap.context.base import _Context, ConfigError from soap.shell import shell and context from other files: # Path: soap/context/base.py # class _Context(dict): # """ # _Context, a dictionary subclass with dot syntax and snapshot support. # """ # def __init__(self, dictionary=None, **kwargs): # super().__init__() # if dictionary: # kwargs.update(dictionary) # kwargs = {k: self._cast_dict(v) for k, v in kwargs.items()} # with self.no_invalidate_cache(): # for k, v in kwargs.items(): # self.__setattr__(k, v) # # @contextmanager # def no_invalidate_cache(self): # super().__setattr__('_invalidate_cache', False) # yield # super().__delattr__('_invalidate_cache') # # def __setattr__(self, key, value): # hook = getattr(self, key + '_hook', lambda v: v) # value = hook(value) # if key != '_snapshot': # value = self._cast_dict(value) # old_value = self.get(key) # self[key] = value # if getattr(self, '_invalidate_cache', True): # if old_value != value: # invalidate_cache() # # def __getattr__(self, key): # try: # return self[key] # except KeyError as e: # raise AttributeError(str(e)) # # def __delattr__(self, key): # try: # del self[key] # except KeyError as e: # raise AttributeError(str(e)) # # def _cast_dict(self, dictionary): # if not isinstance(dictionary, dict): # return dictionary # dictionary = {k: self._cast_dict(v) for k, v in dictionary.items()} # return self.__class__(dictionary) # # def update(self, dictionary=None, **kwargs): # dictionary = dict(dictionary or {}, **kwargs) # for k, v in dictionary.items(): # setattr(self, k, v) # # def take_snapshot(self): # with self.no_invalidate_cache(): # self._snapshot = copy.deepcopy(dict(self)) # # def restore_snapshot(self): # if '_snapshot' not in self: # raise RestoreSnapshotError( # 'Cannot restore snapshot: no snapshot exists.') # snapshot = self._snapshot # self.update(snapshot) # for k in list(self.keys()): # if k not in snapshot: # del self[k] # # @contextmanager # def local(self, dictionary=None, **kwargs): # """Withable local context. """ # self.take_snapshot() # self.update(dictionary, **kwargs) # yield # self.restore_snapshot() # # class ConfigError(ValueError): # """Malformed configuration value. """ , which may include functions, classes, or code. Output only the next line.
class SoapContext(_Context):
Here is a snippet: <|code_start|> c._repr = c.__repr__ def precision_hook(self, value): fp_format = {'single': 32, 'double': 64}.get(value, None) if fp_format is not None: value = gmpy2.ieee(fp_format).precision - 1 if isinstance(value, str): value = int(value) gmpy2.get_context().precision = value + 1 return value def repr_hook(self, value): str_to_func = {'repr': _repr, 'str': _str} value = str_to_func.get(value, value) if value == _repr: builtins.repr = _repr for c in _soap_classes: c.__repr__ = c._repr elif value == _str: builtins.repr = str for c in _soap_classes: c.__repr__ = c.__str__ else: raise ValueError( 'Attribute repr cannot accept value {}'.format(value)) return value def xmode_hook(self, value): allowed = ['plain', 'verbose', 'context'] if value not in allowed: <|code_end|> . Write the next line using the current file imports: import builtins import contextlib import inspect import os import gmpy2 import soap from soap.context.base import _Context, ConfigError from soap.shell import shell and context from other files: # Path: soap/context/base.py # class _Context(dict): # """ # _Context, a dictionary subclass with dot syntax and snapshot support. # """ # def __init__(self, dictionary=None, **kwargs): # super().__init__() # if dictionary: # kwargs.update(dictionary) # kwargs = {k: self._cast_dict(v) for k, v in kwargs.items()} # with self.no_invalidate_cache(): # for k, v in kwargs.items(): # self.__setattr__(k, v) # # @contextmanager # def no_invalidate_cache(self): # super().__setattr__('_invalidate_cache', False) # yield # super().__delattr__('_invalidate_cache') # # def __setattr__(self, key, value): # hook = getattr(self, key + '_hook', lambda v: v) # value = hook(value) # if key != '_snapshot': # value = self._cast_dict(value) # old_value = self.get(key) # self[key] = value # if getattr(self, '_invalidate_cache', True): # if old_value != value: # invalidate_cache() # # def __getattr__(self, key): # try: # return self[key] # except KeyError as e: # raise AttributeError(str(e)) # # def __delattr__(self, key): # try: # del self[key] # except KeyError as e: # raise AttributeError(str(e)) # # def _cast_dict(self, dictionary): # if not isinstance(dictionary, dict): # return dictionary # dictionary = {k: self._cast_dict(v) for k, v in dictionary.items()} # return self.__class__(dictionary) # # def update(self, dictionary=None, **kwargs): # dictionary = dict(dictionary or {}, **kwargs) # for k, v in dictionary.items(): # setattr(self, k, v) # # def take_snapshot(self): # with self.no_invalidate_cache(): # self._snapshot = copy.deepcopy(dict(self)) # # def restore_snapshot(self): # if '_snapshot' not in self: # raise RestoreSnapshotError( # 'Cannot restore snapshot: no snapshot exists.') # snapshot = self._snapshot # self.update(snapshot) # for k in list(self.keys()): # if k not in snapshot: # del self[k] # # @contextmanager # def local(self, dictionary=None, **kwargs): # """Withable local context. """ # self.take_snapshot() # self.update(dictionary, **kwargs) # yield # self.restore_snapshot() # # class ConfigError(ValueError): # """Malformed configuration value. """ , which may include functions, classes, or code. Output only the next line.
raise ConfigError(
Given the following code snippet before the placeholder: <|code_start|> class FixExprIsNotForLoopException(Exception): """FixExpr object is not a for loop. """ class FixExpr(QuaternaryArithExpr): """Fixpoint expression.""" def __init__(self, a1, a2, a3, a4): super().__init__(FIXPOINT_OP, a1, a2, a3, a4) @property def bool_expr(self): return self.a1 @property def loop_state(self): return self.a2 @property def loop_var(self): return self.a3 @property def init_state(self): return self.a4 def format(self): <|code_end|> , predict the next line using imports from the current file: from soap.common.formatting import underline from soap.expression.operators import FIXPOINT_OP from soap.expression.arithmetic import QuaternaryArithExpr and context including class names, function names, and sometimes code from other files: # Path: soap/common/formatting.py # def underline(text): # combining_low_line = '\u0332' # return combining_low_line.join(list(text)) + combining_low_line # # Path: soap/expression/operators.py # FIXPOINT_OP = 'fix' # # Path: soap/expression/arithmetic.py # class QuaternaryArithExpr(QuaternaryExpression, ArithExpr): # # __slots__ = () . Output only the next line.
fixpoint_var = underline('e')
Given snippet: <|code_start|> class FixExprIsNotForLoopException(Exception): """FixExpr object is not a for loop. """ class FixExpr(QuaternaryArithExpr): """Fixpoint expression.""" def __init__(self, a1, a2, a3, a4): <|code_end|> , continue by predicting the next line. Consider current file imports: from soap.common.formatting import underline from soap.expression.operators import FIXPOINT_OP from soap.expression.arithmetic import QuaternaryArithExpr and context: # Path: soap/common/formatting.py # def underline(text): # combining_low_line = '\u0332' # return combining_low_line.join(list(text)) + combining_low_line # # Path: soap/expression/operators.py # FIXPOINT_OP = 'fix' # # Path: soap/expression/arithmetic.py # class QuaternaryArithExpr(QuaternaryExpression, ArithExpr): # # __slots__ = () which might include code, classes, or functions. Output only the next line.
super().__init__(FIXPOINT_OP, a1, a2, a3, a4)
Using the snippet: <|code_start|> def _extract_from_program(program): flow = parse(program) meta_state = flow_to_meta_state(flow) fix_expr = meta_state[flow.outputs[0]] return ForLoopNestExtractor(fix_expr) class TestExtractor(unittest.TestCase): def compare(self, extractor, expect_for_loop): for key, expect_val in expect_for_loop.items(): self.assertEqual(getattr(extractor, key), expect_val) def test_simple_loop(self): program = """ #pragma soap input float a[30] #pragma soap output a for (int i = 1; i < 10; i++) a[i] = a[i - 1] + 1; """ expect_for_loop = { <|code_end|> , determine the next line of code. You have imports: import unittest from soap.datatype import int_type, FloatArrayType from soap.expression import Variable from soap.parser import parse from soap.semantics.schedule.extract import ForLoopNestExtractor from soap.semantics.state import flow_to_meta_state and context (class names, function names, or code) available: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/expression/variable.py # class Variable(ArithmeticMixin, BooleanMixin, BinaryExpression): # """The variable class.""" # __slots__ = () # _str_brackets = False # # def __init__(self, name, dtype=auto_type): # super().__init__(VARIABLE_OP, name, dtype) # # @property # def name(self): # return self.args[0] # # @property # def dtype(self): # return self.args[1] # # def format(self): # return '{}'.format(self.name) # # def __repr__(self): # return '{cls}({name!r}, {dtype!r})'.format( # cls=self.__class__.__name__, name=self.name, dtype=self.dtype) # # Path: soap/parser/program.py # def parse(program, decl=None): # decl = decl or {} # visitor = _ProgramVisitor(decl) # program = _preprocess(program) # flow = visitor.parse(program) # return ProgramFlow(flow) # # Path: soap/semantics/schedule/extract.py # class ForLoopNestExtractor(ForLoopExtractor): # def __init__(self, fix_expr): # super().__init__(fix_expr) # try: # self.iter_vars, self.iter_slices, self._kernel = \ # self._extract_for_loop_nest(fix_expr) # self.is_for_loop_nest = True # except ForLoopNestExtractionFailureException as exception: # self.iter_vars = self.iter_slices = None # self._kernel = fix_expr.loop_state # self.is_for_loop_nest = False # self.exception = exception # # @property # def kernel(self): # return self._kernel # # def _check_init_sandwich(self, fix_expr): # for var, expr in fix_expr.init_state.items(): # if is_expression(expr): # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich because its init_state ' # 'has logic.') # # def _find_inner_fix_expr(self, fix_expr, iter_var): # found_inner_loop = False # for var, expr in fix_expr.loop_state.items(): # if var == iter_var: # pass # iter_var is already checked by ForLoopExtractor # elif var == fix_expr.loop_var: # if isinstance(expr, FixExpr): # # has SIMPLE inner loop # inner_fix_expr = expr # found_inner_loop = True # else: # # has sandwich # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich somewhere.') # elif var == expr: # pass # no logic # else: # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich on variables other than the ' # 'iteration variable and the loop variable.') # if not found_inner_loop: # raise ForLoopNestExtractionFailureException( # 'Did not find loop var in loop.') # return inner_fix_expr # # def _extract_for_loop_nest(self, fix_expr): # extractor = ForLoopExtractor(fix_expr) # if not extractor.is_for_loop: # raise ForLoopNestExtractionFailureException( # 'Loop is not for loop, reason: ' + str(extractor.exception)) # # iter_var = extractor.iter_var # iter_vars = [iter_var] # iter_slices = [extractor.iter_slice] # # if not extractor.has_inner_loops: # return iter_vars, iter_slices, fix_expr.loop_state # # # nested loops # inner_fix_expr = self._find_inner_fix_expr(fix_expr, iter_var) # # # and check inner loop init_state is simple # self._check_init_sandwich(inner_fix_expr) # # inner_iter_vars, inner_iter_slices, inner_kernel = \ # self._extract_for_loop_nest(inner_fix_expr) # iter_vars += inner_iter_vars # iter_slices += inner_iter_slices # return iter_vars, iter_slices, inner_kernel # # Path: soap/semantics/state/meta.py # def flow_to_meta_state(flow): # id_state = MetaState({v: v for v in flow.vars(output=False)}) # return id_state.transition(flow) . Output only the next line.
'iter_var': Variable('i', int_type),
Given snippet: <|code_start|> def _extract_from_program(program): flow = parse(program) meta_state = flow_to_meta_state(flow) fix_expr = meta_state[flow.outputs[0]] return ForLoopNestExtractor(fix_expr) class TestExtractor(unittest.TestCase): def compare(self, extractor, expect_for_loop): for key, expect_val in expect_for_loop.items(): self.assertEqual(getattr(extractor, key), expect_val) def test_simple_loop(self): program = """ #pragma soap input float a[30] #pragma soap output a for (int i = 1; i < 10; i++) a[i] = a[i - 1] + 1; """ expect_for_loop = { <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from soap.datatype import int_type, FloatArrayType from soap.expression import Variable from soap.parser import parse from soap.semantics.schedule.extract import ForLoopNestExtractor from soap.semantics.state import flow_to_meta_state and context: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/expression/variable.py # class Variable(ArithmeticMixin, BooleanMixin, BinaryExpression): # """The variable class.""" # __slots__ = () # _str_brackets = False # # def __init__(self, name, dtype=auto_type): # super().__init__(VARIABLE_OP, name, dtype) # # @property # def name(self): # return self.args[0] # # @property # def dtype(self): # return self.args[1] # # def format(self): # return '{}'.format(self.name) # # def __repr__(self): # return '{cls}({name!r}, {dtype!r})'.format( # cls=self.__class__.__name__, name=self.name, dtype=self.dtype) # # Path: soap/parser/program.py # def parse(program, decl=None): # decl = decl or {} # visitor = _ProgramVisitor(decl) # program = _preprocess(program) # flow = visitor.parse(program) # return ProgramFlow(flow) # # Path: soap/semantics/schedule/extract.py # class ForLoopNestExtractor(ForLoopExtractor): # def __init__(self, fix_expr): # super().__init__(fix_expr) # try: # self.iter_vars, self.iter_slices, self._kernel = \ # self._extract_for_loop_nest(fix_expr) # self.is_for_loop_nest = True # except ForLoopNestExtractionFailureException as exception: # self.iter_vars = self.iter_slices = None # self._kernel = fix_expr.loop_state # self.is_for_loop_nest = False # self.exception = exception # # @property # def kernel(self): # return self._kernel # # def _check_init_sandwich(self, fix_expr): # for var, expr in fix_expr.init_state.items(): # if is_expression(expr): # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich because its init_state ' # 'has logic.') # # def _find_inner_fix_expr(self, fix_expr, iter_var): # found_inner_loop = False # for var, expr in fix_expr.loop_state.items(): # if var == iter_var: # pass # iter_var is already checked by ForLoopExtractor # elif var == fix_expr.loop_var: # if isinstance(expr, FixExpr): # # has SIMPLE inner loop # inner_fix_expr = expr # found_inner_loop = True # else: # # has sandwich # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich somewhere.') # elif var == expr: # pass # no logic # else: # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich on variables other than the ' # 'iteration variable and the loop variable.') # if not found_inner_loop: # raise ForLoopNestExtractionFailureException( # 'Did not find loop var in loop.') # return inner_fix_expr # # def _extract_for_loop_nest(self, fix_expr): # extractor = ForLoopExtractor(fix_expr) # if not extractor.is_for_loop: # raise ForLoopNestExtractionFailureException( # 'Loop is not for loop, reason: ' + str(extractor.exception)) # # iter_var = extractor.iter_var # iter_vars = [iter_var] # iter_slices = [extractor.iter_slice] # # if not extractor.has_inner_loops: # return iter_vars, iter_slices, fix_expr.loop_state # # # nested loops # inner_fix_expr = self._find_inner_fix_expr(fix_expr, iter_var) # # # and check inner loop init_state is simple # self._check_init_sandwich(inner_fix_expr) # # inner_iter_vars, inner_iter_slices, inner_kernel = \ # self._extract_for_loop_nest(inner_fix_expr) # iter_vars += inner_iter_vars # iter_slices += inner_iter_slices # return iter_vars, iter_slices, inner_kernel # # Path: soap/semantics/state/meta.py # def flow_to_meta_state(flow): # id_state = MetaState({v: v for v in flow.vars(output=False)}) # return id_state.transition(flow) which might include code, classes, or functions. Output only the next line.
'iter_var': Variable('i', int_type),
Predict the next line for this snippet: <|code_start|> def _extract_from_program(program): flow = parse(program) meta_state = flow_to_meta_state(flow) fix_expr = meta_state[flow.outputs[0]] <|code_end|> with the help of current file imports: import unittest from soap.datatype import int_type, FloatArrayType from soap.expression import Variable from soap.parser import parse from soap.semantics.schedule.extract import ForLoopNestExtractor from soap.semantics.state import flow_to_meta_state and context from other files: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/expression/variable.py # class Variable(ArithmeticMixin, BooleanMixin, BinaryExpression): # """The variable class.""" # __slots__ = () # _str_brackets = False # # def __init__(self, name, dtype=auto_type): # super().__init__(VARIABLE_OP, name, dtype) # # @property # def name(self): # return self.args[0] # # @property # def dtype(self): # return self.args[1] # # def format(self): # return '{}'.format(self.name) # # def __repr__(self): # return '{cls}({name!r}, {dtype!r})'.format( # cls=self.__class__.__name__, name=self.name, dtype=self.dtype) # # Path: soap/parser/program.py # def parse(program, decl=None): # decl = decl or {} # visitor = _ProgramVisitor(decl) # program = _preprocess(program) # flow = visitor.parse(program) # return ProgramFlow(flow) # # Path: soap/semantics/schedule/extract.py # class ForLoopNestExtractor(ForLoopExtractor): # def __init__(self, fix_expr): # super().__init__(fix_expr) # try: # self.iter_vars, self.iter_slices, self._kernel = \ # self._extract_for_loop_nest(fix_expr) # self.is_for_loop_nest = True # except ForLoopNestExtractionFailureException as exception: # self.iter_vars = self.iter_slices = None # self._kernel = fix_expr.loop_state # self.is_for_loop_nest = False # self.exception = exception # # @property # def kernel(self): # return self._kernel # # def _check_init_sandwich(self, fix_expr): # for var, expr in fix_expr.init_state.items(): # if is_expression(expr): # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich because its init_state ' # 'has logic.') # # def _find_inner_fix_expr(self, fix_expr, iter_var): # found_inner_loop = False # for var, expr in fix_expr.loop_state.items(): # if var == iter_var: # pass # iter_var is already checked by ForLoopExtractor # elif var == fix_expr.loop_var: # if isinstance(expr, FixExpr): # # has SIMPLE inner loop # inner_fix_expr = expr # found_inner_loop = True # else: # # has sandwich # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich somewhere.') # elif var == expr: # pass # no logic # else: # raise ForLoopNestExtractionFailureException( # 'Loop has logic sandwich on variables other than the ' # 'iteration variable and the loop variable.') # if not found_inner_loop: # raise ForLoopNestExtractionFailureException( # 'Did not find loop var in loop.') # return inner_fix_expr # # def _extract_for_loop_nest(self, fix_expr): # extractor = ForLoopExtractor(fix_expr) # if not extractor.is_for_loop: # raise ForLoopNestExtractionFailureException( # 'Loop is not for loop, reason: ' + str(extractor.exception)) # # iter_var = extractor.iter_var # iter_vars = [iter_var] # iter_slices = [extractor.iter_slice] # # if not extractor.has_inner_loops: # return iter_vars, iter_slices, fix_expr.loop_state # # # nested loops # inner_fix_expr = self._find_inner_fix_expr(fix_expr, iter_var) # # # and check inner loop init_state is simple # self._check_init_sandwich(inner_fix_expr) # # inner_iter_vars, inner_iter_slices, inner_kernel = \ # self._extract_for_loop_nest(inner_fix_expr) # iter_vars += inner_iter_vars # iter_slices += inner_iter_slices # return iter_vars, iter_slices, inner_kernel # # Path: soap/semantics/state/meta.py # def flow_to_meta_state(flow): # id_state = MetaState({v: v for v in flow.vars(output=False)}) # return id_state.transition(flow) , which may contain function names, class names, or code. Output only the next line.
return ForLoopNestExtractor(fix_expr)
Based on the snippet: <|code_start|> @functools.wraps(decd_func) def wrapper(self, other): t = base_func(self, other) if t is not None: return t return decd_func(self, other) return wrapper cls.__str__ = decorate_self(Lattice.__str__, cls.__str__) cls.__repr__ = decorate_self(Lattice.__repr__, cls.__repr__) cls.__hash__ = decorate_self(Lattice.__hash__, cls.__hash__) cls.is_top = decorate_self(Lattice.is_top, cls.is_top) cls.is_bottom = decorate_self(Lattice.is_bottom, cls.is_bottom) cls.join = decorate_self_other(Lattice.join, cls.join) cls.meet = decorate_self_other(Lattice.meet, cls.meet) cls.le = decorate_self_other(Lattice.le, cls.le) cls._decorated.add(cls) return cls def _compare(func): def wrapped_func(self, other): try: return func(self, other) except AttributeError: return False return wrapped_func <|code_end|> , predict the immediate next line with the help of imports: import functools from soap.common.cache import Flyweight and context (classes, functions, sometimes code) from other files: # Path: soap/common/cache.py # class Flyweight(object): # # _cache = weakref.WeakValueDictionary() # # def __new__(cls, *args, **kwargs): # if not args and not kwargs: # return object.__new__(cls) # key = pickle.dumps((cls, args, list(kwargs.items()))) # v = cls._cache.get(key, None) # if v is not None: # return v # v = object.__new__(cls) # cls._cache[key] = v # return v . Output only the next line.
class Lattice(Flyweight):
Based on the snippet: <|code_start|>""" .. module:: soap.expression.arithmetic :synopsis: The class of expressions. """ class ArithmeticMixin(object): def __add__(self, other): <|code_end|> , predict the immediate next line with the help of imports: from soap.expression.operators import ( ADD_OP, SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, UNARY_SUBTRACT_OP, TERNARY_SELECT_OP, ARITHMETIC_OPERATORS, COMMUTATIVITY_OPERATORS ) from soap.expression.base import ( Expression, UnaryExpression, BinaryExpression, TernaryExpression, QuaternaryExpression ) and context (classes, functions, sometimes code) from other files: # Path: soap/expression/operators.py # ADD_OP = '+' # # SUBTRACT_OP = '-' # # MULTIPLY_OP = '*' # # DIVIDE_OP = '/' # # UNARY_SUBTRACT_OP = '_' # # TERNARY_SELECT_OP = '?' # # ARITHMETIC_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EXPONENTIATE_OP, TERNARY_SELECT_OP, FIXPOINT_OP, FOR_OP, BARRIER_OP, # ] # # COMMUTATIVITY_OPERATORS = ASSOCIATIVITY_OPERATORS # # Path: soap/expression/base.py # class Expression(Flyweight): # """A base class for expressions.""" # # __slots__ = ('_op', '_args', '_hash') # _str_brackets = True # # def __init__(self, op, *args): # super().__init__() # if not args and not all(args): # raise ValueError('There is no arguments.') # self._op = op # self._args = args # self._hash = None # # def __setstate__(self, state): # self._hash = None # state = state[1] # self._op = state['_op'] # self._args = state['_args'] # # @property # def op(self): # return self._op # # @property # def args(self): # return self._args # # @property # def arity(self): # return len(self.args) # # def vars(self): # return expression_variables(self) # # def _args_to_str(self): # def format(expr): # if is_numeral(expr): # brackets = False # else: # brackets = getattr(expr, '_str_brackets', True) # if is_expression(expr): # expr = expr.format() # text = '({})' if brackets else '{}' # return text.format(expr) # return [format(a) for a in self.args] # # def __repr__(self): # args = ', '.join('a{}={!r}'.format(i + 1, a) # for i, a in enumerate(self.args)) # return "{name}(op={op!r}, {args})".format( # name=self.__class__.__name__, op=self.op, args=args) # # def format(self): # raise NotImplementedError( # 'Override this method for {}'.format(self.__class__)) # # def __str__(self): # return self.format().replace(' ', '').replace('\n', '').strip() # # def _attr(self): # return (self.op, self.args) # # def __eq__(self, other): # if not isinstance(other, Expression): # return False # if id(self) == id(other): # return True # if type(self) is not type(other) or hash(self) != hash(other): # return False # return self._attr() == other._attr() # # def __ne__(self, other): # return not self == other # # def __hash__(self): # if self._hash: # return self._hash # self._hash = hash(self._attr()) # return self._hash # # class UnaryExpression(Expression): # """A unary expression class. Instance has only one argument.""" # # __slots__ = () # # def __init__(self, op, a): # super().__init__(op, a) # # @property # def a(self): # return self.args[0] # # @property # def a1(self): # return self.args[0] # # def format(self): # return '{op}{a}'.format(op=self.op, a=self._args_to_str().pop()) # # class BinaryExpression(Expression): # """A binary expression class. Instance has two arguments.""" # # __slots__ = () # # def __init__(self, op, a1, a2): # super().__init__(op, a1, a2) # # @property # def a1(self): # return self.args[0] # # @property # def a2(self): # return self.args[1] # # def format(self): # a1, a2 = self._args_to_str() # return '{a1} {op} {a2}'.format(op=self.op, a1=a1, a2=a2) # # class TernaryExpression(Expression): # """A ternary expression class. Instance has three arguments.""" # # __slots__ = () # # def __init__(self, op, a1, a2, a3): # super().__init__(op, a1, a2, a3) # # @property # def a1(self): # return self.args[0] # # @property # def a2(self): # return self.args[1] # # @property # def a3(self): # return self.args[2] # # class QuaternaryExpression(Expression): # """A quaternary expression class. Instance has four arguments.""" # # __slots__ = () # # def __init__(self, op, a1, a2, a3, a4): # super().__init__(op, a1, a2, a3, a4) # # @property # def a1(self): # return self.args[0] # # @property # def a2(self): # return self.args[1] # # @property # def a3(self): # return self.args[2] # # @property # def a4(self): # return self.args[3] . Output only the next line.
return BinaryArithExpr(ADD_OP, self, other)
Given the code snippet: <|code_start|> """ nodes = graph.nodes() len_nodes = len(nodes) dist_shape = [len_nodes] * 2 dist = numpy.full(dist_shape, neg_inf) iterer = itertools.product(enumerate(nodes), repeat=2) for (from_idx, from_node), (to_idx, to_node) in iterer: try: edge = graph[from_node][to_node] except KeyError: continue dist[from_idx, to_idx] = edge['latency'] - ii * edge['distance'] iterer = itertools.product(range(len_nodes), repeat=3) for mid_idx, from_idx, to_idx in iterer: dist_val = dist[from_idx, mid_idx] + dist[mid_idx, to_idx] if dist_val > dist[from_idx, to_idx]: if from_idx == to_idx and dist_val > 0: return False dist[from_idx, to_idx] = dist_val return True def rec_init_int_search(graph, init_ii=1, prec=None, round_values=False): """ Performs a binary search of the recurrence-based minimum initiation interval (RecMII). """ <|code_end|> , generate the next line using the imports in this file: import itertools import math import numpy from soap.context import context and context (functions, classes, or occasionally code) from other files: # Path: soap/context/default.py . Output only the next line.
prec = prec or context.ii_precision
Given the code snippet: <|code_start|> DEVICE_LATENCY_TABLE = { ('Virtex7', 333): { int_type: { 'comparison': 1, 'boolean': 0, operators.UNARY_SUBTRACT_OP: 0, operators.ADD_OP: 1, operators.SUBTRACT_OP: 1, operators.MULTIPLY_OP: 7, operators.DIVIDE_OP: 36, operators.TERNARY_SELECT_OP: 0, operators.INDEX_ACCESS_OP: 2, }, <|code_end|> , generate the next line using the imports in this file: from collections import namedtuple from soap.datatype import int_type, float_type, ArrayType from soap.context import context from soap.expression import operators and context (functions, classes, or occasionally code) from other files: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/context/default.py # # Path: soap/expression/operators.py # ADD_OP = '+' # SUBTRACT_OP = '-' # UNARY_SUBTRACT_OP = '_' # MULTIPLY_OP = '*' # DIVIDE_OP = '/' # EXPONENTIATE_OP = 'exp' # EQUAL_OP = '==' # NOT_EQUAL_OP = '!=' # GREATER_OP = '>' # GREATER_EQUAL_OP = '>=' # LESS_OP = '<' # LESS_EQUAL_OP = '<=' # UNARY_NEGATION_OP = '!' # AND_OP = '&&' # OR_OP = '||' # VARIABLE_OP = 'v' # EXTERNAL_OP = 'extern' # TERNARY_SELECT_OP = '?' # FIXPOINT_OP = 'fix' # FOR_OP = 'for' # STATE_GETTER_OP = '()' # BARRIER_OP = ',' # INDEX_ACCESS_OP = 'access' # INDEX_UPDATE_OP = 'update' # SUBSCRIPT_OP = 'subscript' # ARITHMETIC_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EXPONENTIATE_OP, TERNARY_SELECT_OP, FIXPOINT_OP, FOR_OP, BARRIER_OP, # ] # COMPARISON_OPERATORS = [ # EQUAL_OP, NOT_EQUAL_OP, GREATER_OP, LESS_OP, GREATER_EQUAL_OP, # LESS_EQUAL_OP, # ] # BOOLEAN_OPERATORS = COMPARISON_OPERATORS + [ # UNARY_NEGATION_OP, AND_OP, OR_OP # ] # TRADITIONAL_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EQUAL_OP, NOT_EQUAL_OP, GREATER_OP, LESS_OP, GREATER_EQUAL_OP, # LESS_EQUAL_OP, UNARY_NEGATION_OP, AND_OP, OR_OP # ] # SPECIAL_OPERATORS = [ # TERNARY_SELECT_OP, FIXPOINT_OP # ] # OPERATORS = BOOLEAN_OPERATORS + ARITHMETIC_OPERATORS + SPECIAL_OPERATORS # UNARY_OPERATORS = [UNARY_SUBTRACT_OP, UNARY_NEGATION_OP] # BINARY_OPERATORS = list(set(OPERATORS) - set(UNARY_OPERATORS)) # ASSOCIATIVITY_OPERATORS = [ADD_OP, MULTIPLY_OP, EQUAL_OP, AND_OP, OR_OP] # COMMUTATIVITY_OPERATORS = ASSOCIATIVITY_OPERATORS # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS = [(MULTIPLY_OP, ADD_OP)] # LEFT_DISTRIBUTIVITY_OPERATOR_PAIRS = \ # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS # RIGHT_DISTRIBUTIVITY_OPERATOR_PAIRS = \ # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS # LEFT_DISTRIBUTIVITY_OPERATORS, LEFT_DISTRIBUTION_OVER_OPERATORS = \ # list(zip(*LEFT_DISTRIBUTIVITY_OPERATOR_PAIRS)) # RIGHT_DISTRIBUTIVITY_OPERATORS, RIGHT_DISTRIBUTION_OVER_OPERATORS = \ # list(zip(*RIGHT_DISTRIBUTIVITY_OPERATOR_PAIRS)) # COMPARISON_NEGATE_DICT = { # LESS_OP: GREATER_EQUAL_OP, # LESS_EQUAL_OP: GREATER_OP, # GREATER_OP: LESS_EQUAL_OP, # GREATER_EQUAL_OP: LESS_OP, # EQUAL_OP: NOT_EQUAL_OP, # NOT_EQUAL_OP: EQUAL_OP, # } # COMPARISON_MIRROR_DICT = { # LESS_OP: GREATER_OP, # LESS_EQUAL_OP: GREATER_EQUAL_OP, # GREATER_OP: LESS_OP, # GREATER_EQUAL_OP: LESS_EQUAL_OP, # EQUAL_OP: EQUAL_OP, # NOT_EQUAL_OP: NOT_EQUAL_OP, # } . Output only the next line.
float_type: {
Continue the code snippet: <|code_start|> DEVICE_LATENCY_TABLE = { ('Virtex7', 333): { int_type: { 'comparison': 1, 'boolean': 0, operators.UNARY_SUBTRACT_OP: 0, operators.ADD_OP: 1, operators.SUBTRACT_OP: 1, operators.MULTIPLY_OP: 7, operators.DIVIDE_OP: 36, operators.TERNARY_SELECT_OP: 0, operators.INDEX_ACCESS_OP: 2, }, float_type: { 'comparison': 3, 'boolean': 0, 'conversion': 8, operators.UNARY_SUBTRACT_OP: 0, operators.ADD_OP: 10, operators.SUBTRACT_OP: 10, operators.MULTIPLY_OP: 7, operators.DIVIDE_OP: 30, operators.EXPONENTIATE_OP: 20, operators.TERNARY_SELECT_OP: 0, operators.INDEX_ACCESS_OP: 2, }, <|code_end|> . Use current file imports: from collections import namedtuple from soap.datatype import int_type, float_type, ArrayType from soap.context import context from soap.expression import operators and context (classes, functions, or code) from other files: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/context/default.py # # Path: soap/expression/operators.py # ADD_OP = '+' # SUBTRACT_OP = '-' # UNARY_SUBTRACT_OP = '_' # MULTIPLY_OP = '*' # DIVIDE_OP = '/' # EXPONENTIATE_OP = 'exp' # EQUAL_OP = '==' # NOT_EQUAL_OP = '!=' # GREATER_OP = '>' # GREATER_EQUAL_OP = '>=' # LESS_OP = '<' # LESS_EQUAL_OP = '<=' # UNARY_NEGATION_OP = '!' # AND_OP = '&&' # OR_OP = '||' # VARIABLE_OP = 'v' # EXTERNAL_OP = 'extern' # TERNARY_SELECT_OP = '?' # FIXPOINT_OP = 'fix' # FOR_OP = 'for' # STATE_GETTER_OP = '()' # BARRIER_OP = ',' # INDEX_ACCESS_OP = 'access' # INDEX_UPDATE_OP = 'update' # SUBSCRIPT_OP = 'subscript' # ARITHMETIC_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EXPONENTIATE_OP, TERNARY_SELECT_OP, FIXPOINT_OP, FOR_OP, BARRIER_OP, # ] # COMPARISON_OPERATORS = [ # EQUAL_OP, NOT_EQUAL_OP, GREATER_OP, LESS_OP, GREATER_EQUAL_OP, # LESS_EQUAL_OP, # ] # BOOLEAN_OPERATORS = COMPARISON_OPERATORS + [ # UNARY_NEGATION_OP, AND_OP, OR_OP # ] # TRADITIONAL_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EQUAL_OP, NOT_EQUAL_OP, GREATER_OP, LESS_OP, GREATER_EQUAL_OP, # LESS_EQUAL_OP, UNARY_NEGATION_OP, AND_OP, OR_OP # ] # SPECIAL_OPERATORS = [ # TERNARY_SELECT_OP, FIXPOINT_OP # ] # OPERATORS = BOOLEAN_OPERATORS + ARITHMETIC_OPERATORS + SPECIAL_OPERATORS # UNARY_OPERATORS = [UNARY_SUBTRACT_OP, UNARY_NEGATION_OP] # BINARY_OPERATORS = list(set(OPERATORS) - set(UNARY_OPERATORS)) # ASSOCIATIVITY_OPERATORS = [ADD_OP, MULTIPLY_OP, EQUAL_OP, AND_OP, OR_OP] # COMMUTATIVITY_OPERATORS = ASSOCIATIVITY_OPERATORS # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS = [(MULTIPLY_OP, ADD_OP)] # LEFT_DISTRIBUTIVITY_OPERATOR_PAIRS = \ # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS # RIGHT_DISTRIBUTIVITY_OPERATOR_PAIRS = \ # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS # LEFT_DISTRIBUTIVITY_OPERATORS, LEFT_DISTRIBUTION_OVER_OPERATORS = \ # list(zip(*LEFT_DISTRIBUTIVITY_OPERATOR_PAIRS)) # RIGHT_DISTRIBUTIVITY_OPERATORS, RIGHT_DISTRIBUTION_OVER_OPERATORS = \ # list(zip(*RIGHT_DISTRIBUTIVITY_OPERATOR_PAIRS)) # COMPARISON_NEGATE_DICT = { # LESS_OP: GREATER_EQUAL_OP, # LESS_EQUAL_OP: GREATER_OP, # GREATER_OP: LESS_EQUAL_OP, # GREATER_EQUAL_OP: LESS_OP, # EQUAL_OP: NOT_EQUAL_OP, # NOT_EQUAL_OP: EQUAL_OP, # } # COMPARISON_MIRROR_DICT = { # LESS_OP: GREATER_OP, # LESS_EQUAL_OP: GREATER_EQUAL_OP, # GREATER_OP: LESS_OP, # GREATER_EQUAL_OP: LESS_EQUAL_OP, # EQUAL_OP: EQUAL_OP, # NOT_EQUAL_OP: NOT_EQUAL_OP, # } . Output only the next line.
ArrayType: {
Here is a snippet: <|code_start|> DEVICE_LATENCY_TABLE = { ('Virtex7', 333): { int_type: { 'comparison': 1, 'boolean': 0, <|code_end|> . Write the next line using the current file imports: from collections import namedtuple from soap.datatype import int_type, float_type, ArrayType from soap.context import context from soap.expression import operators and context from other files: # Path: soap/datatype.py # class TypeBase(object): # class AutoType(TypeBase): # class BoolType(TypeBase): # class IntType(TypeBase): # class FloatingPointType(TypeBase): # class FloatType(FloatingPointType): # class DoubleType(FloatingPointType): # class FunctionType(TypeBase): # class ArrayType(TypeBase): # class IntegerArrayType(ArrayType): # class FloatArrayType(ArrayType): # def __repr__(self): # def __eq__(self, other): # def __hash__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __init__(self, shape): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def type_of(value): # def type_cast(dtype, value=None, top=False, bottom=False): # # Path: soap/context/default.py # # Path: soap/expression/operators.py # ADD_OP = '+' # SUBTRACT_OP = '-' # UNARY_SUBTRACT_OP = '_' # MULTIPLY_OP = '*' # DIVIDE_OP = '/' # EXPONENTIATE_OP = 'exp' # EQUAL_OP = '==' # NOT_EQUAL_OP = '!=' # GREATER_OP = '>' # GREATER_EQUAL_OP = '>=' # LESS_OP = '<' # LESS_EQUAL_OP = '<=' # UNARY_NEGATION_OP = '!' # AND_OP = '&&' # OR_OP = '||' # VARIABLE_OP = 'v' # EXTERNAL_OP = 'extern' # TERNARY_SELECT_OP = '?' # FIXPOINT_OP = 'fix' # FOR_OP = 'for' # STATE_GETTER_OP = '()' # BARRIER_OP = ',' # INDEX_ACCESS_OP = 'access' # INDEX_UPDATE_OP = 'update' # SUBSCRIPT_OP = 'subscript' # ARITHMETIC_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EXPONENTIATE_OP, TERNARY_SELECT_OP, FIXPOINT_OP, FOR_OP, BARRIER_OP, # ] # COMPARISON_OPERATORS = [ # EQUAL_OP, NOT_EQUAL_OP, GREATER_OP, LESS_OP, GREATER_EQUAL_OP, # LESS_EQUAL_OP, # ] # BOOLEAN_OPERATORS = COMPARISON_OPERATORS + [ # UNARY_NEGATION_OP, AND_OP, OR_OP # ] # TRADITIONAL_OPERATORS = [ # ADD_OP, SUBTRACT_OP, UNARY_SUBTRACT_OP, MULTIPLY_OP, DIVIDE_OP, # EQUAL_OP, NOT_EQUAL_OP, GREATER_OP, LESS_OP, GREATER_EQUAL_OP, # LESS_EQUAL_OP, UNARY_NEGATION_OP, AND_OP, OR_OP # ] # SPECIAL_OPERATORS = [ # TERNARY_SELECT_OP, FIXPOINT_OP # ] # OPERATORS = BOOLEAN_OPERATORS + ARITHMETIC_OPERATORS + SPECIAL_OPERATORS # UNARY_OPERATORS = [UNARY_SUBTRACT_OP, UNARY_NEGATION_OP] # BINARY_OPERATORS = list(set(OPERATORS) - set(UNARY_OPERATORS)) # ASSOCIATIVITY_OPERATORS = [ADD_OP, MULTIPLY_OP, EQUAL_OP, AND_OP, OR_OP] # COMMUTATIVITY_OPERATORS = ASSOCIATIVITY_OPERATORS # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS = [(MULTIPLY_OP, ADD_OP)] # LEFT_DISTRIBUTIVITY_OPERATOR_PAIRS = \ # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS # RIGHT_DISTRIBUTIVITY_OPERATOR_PAIRS = \ # COMMUTATIVE_DISTRIBUTIVITY_OPERATOR_PAIRS # LEFT_DISTRIBUTIVITY_OPERATORS, LEFT_DISTRIBUTION_OVER_OPERATORS = \ # list(zip(*LEFT_DISTRIBUTIVITY_OPERATOR_PAIRS)) # RIGHT_DISTRIBUTIVITY_OPERATORS, RIGHT_DISTRIBUTION_OVER_OPERATORS = \ # list(zip(*RIGHT_DISTRIBUTIVITY_OPERATOR_PAIRS)) # COMPARISON_NEGATE_DICT = { # LESS_OP: GREATER_EQUAL_OP, # LESS_EQUAL_OP: GREATER_OP, # GREATER_OP: LESS_EQUAL_OP, # GREATER_EQUAL_OP: LESS_OP, # EQUAL_OP: NOT_EQUAL_OP, # NOT_EQUAL_OP: EQUAL_OP, # } # COMPARISON_MIRROR_DICT = { # LESS_OP: GREATER_OP, # LESS_EQUAL_OP: GREATER_EQUAL_OP, # GREATER_OP: LESS_OP, # GREATER_EQUAL_OP: LESS_EQUAL_OP, # EQUAL_OP: EQUAL_OP, # NOT_EQUAL_OP: NOT_EQUAL_OP, # } , which may include functions, classes, or code. Output only the next line.
operators.UNARY_SUBTRACT_OP: 0,
Given the code snippet: <|code_start|>from __future__ import print_function class levels(): name = {} levels = levels() for i, l in enumerate(['debug', 'info', 'warning', 'error', 'off']): levels.__dict__[l] = i levels.name[i] = l <|code_end|> , generate the next line using the imports in this file: import os import sys import time import ipdb import traceback from pprint import pformat from contextlib import contextmanager from soap.context import context as _global_context and context (functions, classes, or occasionally code) from other files: # Path: soap/context/default.py . Output only the next line.
with _global_context.no_invalidate_cache():
Given the following code snippet before the placeholder: <|code_start|> if len(value_list) == 1: return value_list[0] return value_list class FunctionNotMatched(Exception): """Function is unmatched. """ class _DotDict(dict): def __init__(self, dictionary, **kwargs): dictionary = dict(dictionary, **kwargs) super(_DotDict, self).__init__(dictionary) self.__dict__.update(dictionary) class Dispatcher(object): def __init__(self): self.func_map = {} def __call__(self, func): arg_defaults = func.__defaults__ or tuple() arg_names = func.__code__.co_varnames[1:] if len(arg_names) != len(arg_defaults): raise SyntaxError('Each argument must have a default value.') if not arg_names: # no arguments return func arg_sig = {k: v for k, v in zip(arg_names, arg_defaults)} func_name = func.__code__.co_name func_list = self.func_map.setdefault(func_name, []) <|code_end|> , predict the next line using imports from the current file: from itertools import zip_longest from itertools import izip_longest as zip_longest from patmat.mimic import Mimic and context including class names, function names, and sometimes code from other files: # Path: patmat/mimic.py # def Mimic(*args, **kwargs): # """Lazy programmer's stuff. # # Automatically determines the correct mimic instances from definition. # """ # if kwargs: # if args: # raise ValueError('Attribute matching should not take a sequence.') # for k, v in kwargs.items(): # kwargs[k] = Mimic(v) # return Attr(**kwargs) # if len(args) > 1: # return Seq(args) # value = args[0] # if isinstance(value, type): # return Type(value) # if isinstance(value, list): # return List(Mimic(v) for v in value) # if isinstance(value, tuple): # return Tuple(Mimic(v) for v in value) # if isinstance(value, dict): # return Dict({Mimic(k): Mimic(v) for k, v in value.items()}) # if callable(value): # return Pred(value) # return value . Output only the next line.
func_list.append((func, Mimic(arg_sig)))
Using the snippet: <|code_start|> def expand_expr(expr, meta_state): if isinstance(expr, FixExpr): return expression_factory( expr.op, expr.bool_expr, expr.loop_state, expr.loop_var, expand_meta_state(expr.init_state, meta_state)) <|code_end|> , determine the next line of code. You have imports: from soap.expression import ( expression_factory, is_expression, is_variable, FixExpr ) from soap.semantics.common import is_numeral and context (class names, function names, or code) available: # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True # # def is_variable(e): # from soap.expression.variable import Variable # return isinstance(e, Variable) # # Path: soap/expression/fixpoint.py # class FixExpr(QuaternaryArithExpr): # """Fixpoint expression.""" # # def __init__(self, a1, a2, a3, a4): # super().__init__(FIXPOINT_OP, a1, a2, a3, a4) # # @property # def bool_expr(self): # return self.a1 # # @property # def loop_state(self): # return self.a2 # # @property # def loop_var(self): # return self.a3 # # @property # def init_state(self): # return self.a4 # # def format(self): # fixpoint_var = underline('e') # s = ('{op}(λ{fvar}.({bool_expr} ? {fvar} % {loop_state} : {var}))' # ' % {init_state}') # return s.format( # fvar=fixpoint_var, op=self.op, bool_expr=self.bool_expr, # loop_state=self.loop_state.format(), var=self.loop_var, # init_state=self.init_state.format()) # # Path: soap/semantics/common.py # def is_numeral(e): # from soap.semantics.error import ( # mpz_type, mpfr_type, Interval, ErrorSemantics # ) # from soap.semantics.linalg import MultiDimensionalArray # return isinstance(e, ( # mpz_type, mpfr_type, Interval, ErrorSemantics, MultiDimensionalArray)) . Output only the next line.
if is_expression(expr):
Here is a snippet: <|code_start|> def expand_expr(expr, meta_state): if isinstance(expr, FixExpr): return expression_factory( expr.op, expr.bool_expr, expr.loop_state, expr.loop_var, expand_meta_state(expr.init_state, meta_state)) if is_expression(expr): args = [expand_expr(a, meta_state) for a in expr.args] return expression_factory(expr.op, *args) <|code_end|> . Write the next line using the current file imports: from soap.expression import ( expression_factory, is_expression, is_variable, FixExpr ) from soap.semantics.common import is_numeral and context from other files: # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True # # def is_variable(e): # from soap.expression.variable import Variable # return isinstance(e, Variable) # # Path: soap/expression/fixpoint.py # class FixExpr(QuaternaryArithExpr): # """Fixpoint expression.""" # # def __init__(self, a1, a2, a3, a4): # super().__init__(FIXPOINT_OP, a1, a2, a3, a4) # # @property # def bool_expr(self): # return self.a1 # # @property # def loop_state(self): # return self.a2 # # @property # def loop_var(self): # return self.a3 # # @property # def init_state(self): # return self.a4 # # def format(self): # fixpoint_var = underline('e') # s = ('{op}(λ{fvar}.({bool_expr} ? {fvar} % {loop_state} : {var}))' # ' % {init_state}') # return s.format( # fvar=fixpoint_var, op=self.op, bool_expr=self.bool_expr, # loop_state=self.loop_state.format(), var=self.loop_var, # init_state=self.init_state.format()) # # Path: soap/semantics/common.py # def is_numeral(e): # from soap.semantics.error import ( # mpz_type, mpfr_type, Interval, ErrorSemantics # ) # from soap.semantics.linalg import MultiDimensionalArray # return isinstance(e, ( # mpz_type, mpfr_type, Interval, ErrorSemantics, MultiDimensionalArray)) , which may include functions, classes, or code. Output only the next line.
if is_variable(expr):
Next line prediction: <|code_start|> def expand_expr(expr, meta_state): if isinstance(expr, FixExpr): return expression_factory( expr.op, expr.bool_expr, expr.loop_state, expr.loop_var, expand_meta_state(expr.init_state, meta_state)) if is_expression(expr): args = [expand_expr(a, meta_state) for a in expr.args] return expression_factory(expr.op, *args) if is_variable(expr): try: new_expr = meta_state[expr] except KeyError: raise KeyError( 'Cannot expand the expression {expr}, missing variable in ' '{state}'.format(expr=expr, state=meta_state)) return new_expr <|code_end|> . Use current file imports: (from soap.expression import ( expression_factory, is_expression, is_variable, FixExpr ) from soap.semantics.common import is_numeral) and context including class names, function names, or small code snippets from other files: # Path: soap/expression/common.py # @cached # def expression_factory(op, *args): # from soap.expression import operators # from soap.expression.arithmetic import ( # UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr # ) # from soap.expression.boolean import ( # UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr # ) # from soap.expression.fixpoint import FixExpr # from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr # # global op_expr_cls_map # if not op_expr_cls_map: # op_expr_cls_map = { # operators.SUBSCRIPT_OP: Subscript, # operators.INDEX_ACCESS_OP: AccessExpr, # operators.INDEX_UPDATE_OP: UpdateExpr, # operators.FIXPOINT_OP: FixExpr, # operators.TERNARY_SELECT_OP: SelectExpr, # } # cls = op_expr_cls_map.get(op) # if cls: # return cls(*args) # # if op in operators.ARITHMETIC_OPERATORS: # class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] # elif op in operators.BOOLEAN_OPERATORS: # class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] # else: # raise ValueError('Unknown operator {}.'.format(op)) # try: # cls = class_list[len(args) - 1] # except IndexError: # raise ValueError('Too many arguments.') # return cls(op, *args) # # def is_expression(e): # from soap.expression.base import Expression # from soap.expression.variable import Variable, VariableTuple # if not isinstance(e, Expression): # return False # if isinstance(e, Variable): # return False # if isinstance(e, VariableTuple): # return False # return True # # def is_variable(e): # from soap.expression.variable import Variable # return isinstance(e, Variable) # # Path: soap/expression/fixpoint.py # class FixExpr(QuaternaryArithExpr): # """Fixpoint expression.""" # # def __init__(self, a1, a2, a3, a4): # super().__init__(FIXPOINT_OP, a1, a2, a3, a4) # # @property # def bool_expr(self): # return self.a1 # # @property # def loop_state(self): # return self.a2 # # @property # def loop_var(self): # return self.a3 # # @property # def init_state(self): # return self.a4 # # def format(self): # fixpoint_var = underline('e') # s = ('{op}(λ{fvar}.({bool_expr} ? {fvar} % {loop_state} : {var}))' # ' % {init_state}') # return s.format( # fvar=fixpoint_var, op=self.op, bool_expr=self.bool_expr, # loop_state=self.loop_state.format(), var=self.loop_var, # init_state=self.init_state.format()) # # Path: soap/semantics/common.py # def is_numeral(e): # from soap.semantics.error import ( # mpz_type, mpfr_type, Interval, ErrorSemantics # ) # from soap.semantics.linalg import MultiDimensionalArray # return isinstance(e, ( # mpz_type, mpfr_type, Interval, ErrorSemantics, MultiDimensionalArray)) . Output only the next line.
if is_numeral(expr):
Given the code snippet: <|code_start|> device='Virtex7', frequency=333, port_count=2, # analysis related fast_outer=True, # analyze only innermost loop for error fast_factor=0.05, # accelerate error analysis by computing a fraction # of iterations and extrapolate scalar_array=True, unroll_factor=0, # steps before no unrolling in static analysis widen_factor=0, # steps before widening in static analysis precision='single', norm='mse_error', # function for computing multiple variable avg error ii_precision=5, # how precise are IIs computed round_values=True, scheduler='alap', # the scheduler used for sequential nodes # transform related rand_seed=42, sample_unique=True, reduce_limit=2000, size_limit=500, loop_size_limit=0, algorithm='partition', max_steps=10, # max no of steps for equivalent expr discovery plugin_every=1, # no of steps before plugins are executed thickness=0, # no of iterations of pareto suboptimal inclusion small_steps=5, # transition steps for finding equivalent small exprs small_depth=3, # transition depth for finding equivalent small exprs window_depth=3, # depth limit window for equivalent expr discovery unroll_depth=7, # partial unroll depth limit ) <|code_end|> , generate the next line using the imports in this file: from soap.context.soap import SoapContext and context (functions, classes, or occasionally code) from other files: # Path: soap/context/soap.py # class SoapContext(_Context): # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # for c in _soap_classes: # c._repr = c.__repr__ # # def precision_hook(self, value): # fp_format = {'single': 32, 'double': 64}.get(value, None) # if fp_format is not None: # value = gmpy2.ieee(fp_format).precision - 1 # if isinstance(value, str): # value = int(value) # gmpy2.get_context().precision = value + 1 # return value # # def repr_hook(self, value): # str_to_func = {'repr': _repr, 'str': _str} # value = str_to_func.get(value, value) # if value == _repr: # builtins.repr = _repr # for c in _soap_classes: # c.__repr__ = c._repr # elif value == _str: # builtins.repr = str # for c in _soap_classes: # c.__repr__ = c.__str__ # else: # raise ValueError( # 'Attribute repr cannot accept value {}'.format(value)) # return value # # def xmode_hook(self, value): # allowed = ['plain', 'verbose', 'context'] # if value not in allowed: # raise ConfigError( # 'Config xmode must take values in {allowed}' # .format(allowed=allowed)) # _run_line_magic('xmode', value) # return value # # def autocall_hook(self, value): # value = bool(value) # _run_line_magic('autocall', str(int(value))) # return value . Output only the next line.
context = SoapContext(context)
Given the following code snippet before the placeholder: <|code_start|> def linear_expressions_never_equal(*args): try: return _basic_set_from_linear_expressions(*args).is_empty() except ExpressionNotLinearException: return False def subscripts_always_equal(*subscripts): return all( linear_expressions_always_equal(*indices) for indices in zip(*(a.args for a in subscripts))) def subscripts_never_equal(*subscripts): return any( linear_expressions_never_equal(*indices) for indices in zip(*(a.args for a in subscripts))) class AccessUpdateSimplifier(GenericExecuter): def _execute_atom(self, expr): return expr execute_PartitionLabel = execute_PreUnrollExpr = _execute_atom def _execute_args(self, expr): return (self(arg) for arg in expr.args) def _execute_expression(self, expr): <|code_end|> , predict the next line using imports from the current file: import itertools import islpy from soap.expression import ( expression_factory, expression_variables, AccessExpr, UpdateExpr, Subscript, GenericExecuter ) and context including class names, function names, and sometimes code from other files: # Path: soap/expression/common.py # def is_variable(e): # def is_variable_tuple(e): # def is_expression(e): # def is_arith_expr(e): # def is_bool_expr(e): # def concat_multi_expr(*expr_args): # def split_multi_expr(e): # def expression_factory(op, *args): # def __init__(self, *arg, **kwargs): # def _set_default_method(self, name, value): # def generic_execute(self, expr, *args, **kwargs): # def _execute_atom(self, expr, *args, **kwargs): # def _execute_expression(self, expr, *args, **kwargs): # def _execute_mapping(self, meta_state, *args, **kwargs): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_tuple(self, expr): # def execute_numeral(self, expr): # def execute_FixExpr(self, expr): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_FixExpr(self, expr): # def _execute_mapping(self, expr): # def fix_expr_has_inner_loop(expr): # class GenericExecuter(base_dispatcher()): # class VariableSetGenerator(GenericExecuter): # class HasInnerLoop(GenericExecuter): # # Path: soap/expression/linalg.py # class Subscript(Expression): # __slots__ = () # _str_brackets = False # # def __init__(self, *subscript): # super().__init__(SUBSCRIPT_OP, *subscript) # # def __iter__(self): # return iter(self.args) # # def format(self): # return ''.join('[' + a.format() + ']' for a in self.args) # # def __repr__(self): # return '{}({!r})'.format(self.__class__.__name__, self.args) # # class AccessExpr( # ArithmeticMixin, BooleanMixin, BinaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_ACCESS_OP, var, subscript) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # def format(self): # var, subscript = self._args_to_str() # return '{}{}'.format(var, subscript) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript) # # class UpdateExpr( # ArithmeticMixin, BooleanMixin, TernaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript, expr): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_UPDATE_OP, var, subscript, expr) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # @property # def expr(self): # return self.a3 # # def format(self): # var, subscript, expr = (a.format() for a in self.args) # args = '{}, \n{}, \n{}'.format(var, subscript, expr) # return 'update(\n{})'.format(indent(args)) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r}, {expr!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript, expr=self.expr) . Output only the next line.
return expression_factory(expr.op, *self._execute_args(expr))
Given the code snippet: <|code_start|> class ExpressionNotLinearException(Exception): pass def _basic_set_from_linear_expressions(*expr_set): var_set = set() for expr in expr_set: <|code_end|> , generate the next line using the imports in this file: import itertools import islpy from soap.expression import ( expression_factory, expression_variables, AccessExpr, UpdateExpr, Subscript, GenericExecuter ) and context (functions, classes, or occasionally code) from other files: # Path: soap/expression/common.py # def is_variable(e): # def is_variable_tuple(e): # def is_expression(e): # def is_arith_expr(e): # def is_bool_expr(e): # def concat_multi_expr(*expr_args): # def split_multi_expr(e): # def expression_factory(op, *args): # def __init__(self, *arg, **kwargs): # def _set_default_method(self, name, value): # def generic_execute(self, expr, *args, **kwargs): # def _execute_atom(self, expr, *args, **kwargs): # def _execute_expression(self, expr, *args, **kwargs): # def _execute_mapping(self, meta_state, *args, **kwargs): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_tuple(self, expr): # def execute_numeral(self, expr): # def execute_FixExpr(self, expr): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_FixExpr(self, expr): # def _execute_mapping(self, expr): # def fix_expr_has_inner_loop(expr): # class GenericExecuter(base_dispatcher()): # class VariableSetGenerator(GenericExecuter): # class HasInnerLoop(GenericExecuter): # # Path: soap/expression/linalg.py # class Subscript(Expression): # __slots__ = () # _str_brackets = False # # def __init__(self, *subscript): # super().__init__(SUBSCRIPT_OP, *subscript) # # def __iter__(self): # return iter(self.args) # # def format(self): # return ''.join('[' + a.format() + ']' for a in self.args) # # def __repr__(self): # return '{}({!r})'.format(self.__class__.__name__, self.args) # # class AccessExpr( # ArithmeticMixin, BooleanMixin, BinaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_ACCESS_OP, var, subscript) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # def format(self): # var, subscript = self._args_to_str() # return '{}{}'.format(var, subscript) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript) # # class UpdateExpr( # ArithmeticMixin, BooleanMixin, TernaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript, expr): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_UPDATE_OP, var, subscript, expr) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # @property # def expr(self): # return self.a3 # # def format(self): # var, subscript, expr = (a.format() for a in self.args) # args = '{}, \n{}, \n{}'.format(var, subscript, expr) # return 'update(\n{})'.format(indent(args)) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r}, {expr!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript, expr=self.expr) . Output only the next line.
var_set |= expression_variables(expr)
Next line prediction: <|code_start|> raise ExpressionNotLinearException return basic_set def linear_expressions_always_equal(*args): try: return _basic_set_from_linear_expressions(*args).is_universe() except ExpressionNotLinearException: return False def linear_expressions_never_equal(*args): try: return _basic_set_from_linear_expressions(*args).is_empty() except ExpressionNotLinearException: return False def subscripts_always_equal(*subscripts): return all( linear_expressions_always_equal(*indices) for indices in zip(*(a.args for a in subscripts))) def subscripts_never_equal(*subscripts): return any( linear_expressions_never_equal(*indices) for indices in zip(*(a.args for a in subscripts))) <|code_end|> . Use current file imports: (import itertools import islpy from soap.expression import ( expression_factory, expression_variables, AccessExpr, UpdateExpr, Subscript, GenericExecuter )) and context including class names, function names, or small code snippets from other files: # Path: soap/expression/common.py # def is_variable(e): # def is_variable_tuple(e): # def is_expression(e): # def is_arith_expr(e): # def is_bool_expr(e): # def concat_multi_expr(*expr_args): # def split_multi_expr(e): # def expression_factory(op, *args): # def __init__(self, *arg, **kwargs): # def _set_default_method(self, name, value): # def generic_execute(self, expr, *args, **kwargs): # def _execute_atom(self, expr, *args, **kwargs): # def _execute_expression(self, expr, *args, **kwargs): # def _execute_mapping(self, meta_state, *args, **kwargs): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_tuple(self, expr): # def execute_numeral(self, expr): # def execute_FixExpr(self, expr): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_FixExpr(self, expr): # def _execute_mapping(self, expr): # def fix_expr_has_inner_loop(expr): # class GenericExecuter(base_dispatcher()): # class VariableSetGenerator(GenericExecuter): # class HasInnerLoop(GenericExecuter): # # Path: soap/expression/linalg.py # class Subscript(Expression): # __slots__ = () # _str_brackets = False # # def __init__(self, *subscript): # super().__init__(SUBSCRIPT_OP, *subscript) # # def __iter__(self): # return iter(self.args) # # def format(self): # return ''.join('[' + a.format() + ']' for a in self.args) # # def __repr__(self): # return '{}({!r})'.format(self.__class__.__name__, self.args) # # class AccessExpr( # ArithmeticMixin, BooleanMixin, BinaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_ACCESS_OP, var, subscript) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # def format(self): # var, subscript = self._args_to_str() # return '{}{}'.format(var, subscript) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript) # # class UpdateExpr( # ArithmeticMixin, BooleanMixin, TernaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript, expr): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_UPDATE_OP, var, subscript, expr) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # @property # def expr(self): # return self.a3 # # def format(self): # var, subscript, expr = (a.format() for a in self.args) # args = '{}, \n{}, \n{}'.format(var, subscript, expr) # return 'update(\n{})'.format(indent(args)) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r}, {expr!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript, expr=self.expr) . Output only the next line.
class AccessUpdateSimplifier(GenericExecuter):
Here is a snippet: <|code_start|> def __call__(self, expr, indices=None): indices = indices or set() return super().__call__(expr, indices) class SubscriptSimplifier(GenericExecuter): def _execute_atom(self, expr, indices): return expr execute_PartitionLabel = execute_PreUnrollExpr = _execute_atom def _execute_expression(self, expr, indices): args = (self(arg, indices) for arg in expr.args) return expression_factory(expr.op, *args) def execute_Subscript(self, expr, indices): args = (indices.get(index, index) for index in expr.args) return expression_factory(expr.op, *args) def _execute_mapping(self, expr, indices): return expr.__class__({ var: self(var_expr, indices) for var, var_expr in expr.items()}) def _smallest_indices(indices): equiv_map = {} iterer = itertools.product(indices, repeat=2) for index_1, index_2 in iterer: if not subscripts_always_equal( <|code_end|> . Write the next line using the current file imports: import itertools import islpy from soap.expression import ( expression_factory, expression_variables, AccessExpr, UpdateExpr, Subscript, GenericExecuter ) and context from other files: # Path: soap/expression/common.py # def is_variable(e): # def is_variable_tuple(e): # def is_expression(e): # def is_arith_expr(e): # def is_bool_expr(e): # def concat_multi_expr(*expr_args): # def split_multi_expr(e): # def expression_factory(op, *args): # def __init__(self, *arg, **kwargs): # def _set_default_method(self, name, value): # def generic_execute(self, expr, *args, **kwargs): # def _execute_atom(self, expr, *args, **kwargs): # def _execute_expression(self, expr, *args, **kwargs): # def _execute_mapping(self, meta_state, *args, **kwargs): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_tuple(self, expr): # def execute_numeral(self, expr): # def execute_FixExpr(self, expr): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_FixExpr(self, expr): # def _execute_mapping(self, expr): # def fix_expr_has_inner_loop(expr): # class GenericExecuter(base_dispatcher()): # class VariableSetGenerator(GenericExecuter): # class HasInnerLoop(GenericExecuter): # # Path: soap/expression/linalg.py # class Subscript(Expression): # __slots__ = () # _str_brackets = False # # def __init__(self, *subscript): # super().__init__(SUBSCRIPT_OP, *subscript) # # def __iter__(self): # return iter(self.args) # # def format(self): # return ''.join('[' + a.format() + ']' for a in self.args) # # def __repr__(self): # return '{}({!r})'.format(self.__class__.__name__, self.args) # # class AccessExpr( # ArithmeticMixin, BooleanMixin, BinaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_ACCESS_OP, var, subscript) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # def format(self): # var, subscript = self._args_to_str() # return '{}{}'.format(var, subscript) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript) # # class UpdateExpr( # ArithmeticMixin, BooleanMixin, TernaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript, expr): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_UPDATE_OP, var, subscript, expr) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # @property # def expr(self): # return self.a3 # # def format(self): # var, subscript, expr = (a.format() for a in self.args) # args = '{}, \n{}, \n{}'.format(var, subscript, expr) # return 'update(\n{})'.format(indent(args)) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r}, {expr!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript, expr=self.expr) , which may include functions, classes, or code. Output only the next line.
Subscript(index_1), Subscript(index_2)):
Here is a snippet: <|code_start|> def subscripts_never_equal(*subscripts): return any( linear_expressions_never_equal(*indices) for indices in zip(*(a.args for a in subscripts))) class AccessUpdateSimplifier(GenericExecuter): def _execute_atom(self, expr): return expr execute_PartitionLabel = execute_PreUnrollExpr = _execute_atom def _execute_args(self, expr): return (self(arg) for arg in expr.args) def _execute_expression(self, expr): return expression_factory(expr.op, *self._execute_args(expr)) def execute_AccessExpr(self, expr): expr = self._execute_expression(expr) var, access_subscript = expr.args if not isinstance(var, UpdateExpr): return expr var, update_subscript, update_expr = self._execute_args(var) if subscripts_always_equal(update_subscript, access_subscript): # access(update(a, i, e), i) ==> e return update_expr if subscripts_never_equal(update_subscript, access_subscript): # access(update(a, i, _), j) ==> access(a, j) [i != j] <|code_end|> . Write the next line using the current file imports: import itertools import islpy from soap.expression import ( expression_factory, expression_variables, AccessExpr, UpdateExpr, Subscript, GenericExecuter ) and context from other files: # Path: soap/expression/common.py # def is_variable(e): # def is_variable_tuple(e): # def is_expression(e): # def is_arith_expr(e): # def is_bool_expr(e): # def concat_multi_expr(*expr_args): # def split_multi_expr(e): # def expression_factory(op, *args): # def __init__(self, *arg, **kwargs): # def _set_default_method(self, name, value): # def generic_execute(self, expr, *args, **kwargs): # def _execute_atom(self, expr, *args, **kwargs): # def _execute_expression(self, expr, *args, **kwargs): # def _execute_mapping(self, meta_state, *args, **kwargs): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_tuple(self, expr): # def execute_numeral(self, expr): # def execute_FixExpr(self, expr): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_FixExpr(self, expr): # def _execute_mapping(self, expr): # def fix_expr_has_inner_loop(expr): # class GenericExecuter(base_dispatcher()): # class VariableSetGenerator(GenericExecuter): # class HasInnerLoop(GenericExecuter): # # Path: soap/expression/linalg.py # class Subscript(Expression): # __slots__ = () # _str_brackets = False # # def __init__(self, *subscript): # super().__init__(SUBSCRIPT_OP, *subscript) # # def __iter__(self): # return iter(self.args) # # def format(self): # return ''.join('[' + a.format() + ']' for a in self.args) # # def __repr__(self): # return '{}({!r})'.format(self.__class__.__name__, self.args) # # class AccessExpr( # ArithmeticMixin, BooleanMixin, BinaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_ACCESS_OP, var, subscript) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # def format(self): # var, subscript = self._args_to_str() # return '{}{}'.format(var, subscript) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript) # # class UpdateExpr( # ArithmeticMixin, BooleanMixin, TernaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript, expr): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_UPDATE_OP, var, subscript, expr) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # @property # def expr(self): # return self.a3 # # def format(self): # var, subscript, expr = (a.format() for a in self.args) # args = '{}, \n{}, \n{}'.format(var, subscript, expr) # return 'update(\n{})'.format(indent(args)) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r}, {expr!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript, expr=self.expr) , which may include functions, classes, or code. Output only the next line.
return self(AccessExpr(var, access_subscript))
Given snippet: <|code_start|> return False def subscripts_always_equal(*subscripts): return all( linear_expressions_always_equal(*indices) for indices in zip(*(a.args for a in subscripts))) def subscripts_never_equal(*subscripts): return any( linear_expressions_never_equal(*indices) for indices in zip(*(a.args for a in subscripts))) class AccessUpdateSimplifier(GenericExecuter): def _execute_atom(self, expr): return expr execute_PartitionLabel = execute_PreUnrollExpr = _execute_atom def _execute_args(self, expr): return (self(arg) for arg in expr.args) def _execute_expression(self, expr): return expression_factory(expr.op, *self._execute_args(expr)) def execute_AccessExpr(self, expr): expr = self._execute_expression(expr) var, access_subscript = expr.args <|code_end|> , continue by predicting the next line. Consider current file imports: import itertools import islpy from soap.expression import ( expression_factory, expression_variables, AccessExpr, UpdateExpr, Subscript, GenericExecuter ) and context: # Path: soap/expression/common.py # def is_variable(e): # def is_variable_tuple(e): # def is_expression(e): # def is_arith_expr(e): # def is_bool_expr(e): # def concat_multi_expr(*expr_args): # def split_multi_expr(e): # def expression_factory(op, *args): # def __init__(self, *arg, **kwargs): # def _set_default_method(self, name, value): # def generic_execute(self, expr, *args, **kwargs): # def _execute_atom(self, expr, *args, **kwargs): # def _execute_expression(self, expr, *args, **kwargs): # def _execute_mapping(self, meta_state, *args, **kwargs): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_tuple(self, expr): # def execute_numeral(self, expr): # def execute_FixExpr(self, expr): # def generic_execute(self, expr): # def _execute_atom(self, expr): # def _execute_expression(self, expr): # def execute_FixExpr(self, expr): # def _execute_mapping(self, expr): # def fix_expr_has_inner_loop(expr): # class GenericExecuter(base_dispatcher()): # class VariableSetGenerator(GenericExecuter): # class HasInnerLoop(GenericExecuter): # # Path: soap/expression/linalg.py # class Subscript(Expression): # __slots__ = () # _str_brackets = False # # def __init__(self, *subscript): # super().__init__(SUBSCRIPT_OP, *subscript) # # def __iter__(self): # return iter(self.args) # # def format(self): # return ''.join('[' + a.format() + ']' for a in self.args) # # def __repr__(self): # return '{}({!r})'.format(self.__class__.__name__, self.args) # # class AccessExpr( # ArithmeticMixin, BooleanMixin, BinaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_ACCESS_OP, var, subscript) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # def format(self): # var, subscript = self._args_to_str() # return '{}{}'.format(var, subscript) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript) # # class UpdateExpr( # ArithmeticMixin, BooleanMixin, TernaryExpression, _TrueVarMixin): # __slots__ = () # _str_brackets = False # # def __init__(self, var, subscript, expr): # from soap.semantics.label import Label # if not isinstance(subscript, Label): # subscript = Subscript(*subscript) # super().__init__(INDEX_UPDATE_OP, var, subscript, expr) # # @property # def var(self): # return self.a1 # # @property # def subscript(self): # return self.a2 # # @property # def expr(self): # return self.a3 # # def format(self): # var, subscript, expr = (a.format() for a in self.args) # args = '{}, \n{}, \n{}'.format(var, subscript, expr) # return 'update(\n{})'.format(indent(args)) # # def __repr__(self): # return '{cls}({var!r}, {subscript!r}, {expr!r})'.format( # cls=self.__class__.__name__, var=self.var, # subscript=self.subscript, expr=self.expr) which might include code, classes, or functions. Output only the next line.
if not isinstance(var, UpdateExpr):
Given snippet: <|code_start|> class _Context(dict): """ _Context, a dictionary subclass with dot syntax and snapshot support. """ def __init__(self, dictionary=None, **kwargs): super().__init__() if dictionary: kwargs.update(dictionary) kwargs = {k: self._cast_dict(v) for k, v in kwargs.items()} with self.no_invalidate_cache(): for k, v in kwargs.items(): self.__setattr__(k, v) @contextmanager def no_invalidate_cache(self): super().__setattr__('_invalidate_cache', False) yield super().__delattr__('_invalidate_cache') def __setattr__(self, key, value): hook = getattr(self, key + '_hook', lambda v: v) value = hook(value) if key != '_snapshot': value = self._cast_dict(value) old_value = self.get(key) self[key] = value if getattr(self, '_invalidate_cache', True): if old_value != value: <|code_end|> , continue by predicting the next line. Consider current file imports: import copy from contextlib import contextmanager from soap.common.cache import invalidate_cache and context: # Path: soap/common/cache.py # def invalidate_cache(): # from soap import logger # from soap.common.parallel import pool # process_invalidate_cache() # pool.invalidate_cache() # logger.info('Cache invalidated.') which might include code, classes, or functions. Output only the next line.
invalidate_cache()
Given the following code snippet before the placeholder: <|code_start|> @cached def expression_factory(op, *args): global op_expr_cls_map if not op_expr_cls_map: op_expr_cls_map = { operators.SUBSCRIPT_OP: Subscript, operators.INDEX_ACCESS_OP: AccessExpr, operators.INDEX_UPDATE_OP: UpdateExpr, operators.FIXPOINT_OP: FixExpr, operators.TERNARY_SELECT_OP: SelectExpr, } cls = op_expr_cls_map.get(op) if cls: return cls(*args) if op in operators.ARITHMETIC_OPERATORS: class_list = [UnaryArithExpr, BinaryArithExpr, TernaryArithExpr] elif op in operators.BOOLEAN_OPERATORS: class_list = [UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr] else: raise ValueError('Unknown operator {}.'.format(op)) try: cls = class_list[len(args) - 1] except IndexError: raise ValueError('Too many arguments.') return cls(op, *args) <|code_end|> , predict the next line using imports from the current file: from soap.common.base import base_dispatcher from soap.common.cache import cached from soap.expression.variable import Variable from soap.expression.variable import VariableTuple from soap.expression.base import Expression from soap.expression.variable import Variable, VariableTuple from soap.expression.arithmetic import ArithExpr from soap.expression.boolean import BoolExpr from soap.expression.operators import BARRIER_OP from soap.expression import operators from soap.expression.arithmetic import ( UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr ) from soap.expression.boolean import ( UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr ) from soap.expression.fixpoint import FixExpr from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr from soap.expression.fixpoint import FixExpr and context including class names, function names, and sometimes code from other files: # Path: soap/common/base.py # def base_dispatcher(dispatch_name='execute'): # class Dispatcher(BaseDispatcher): # pass # Dispatcher.dispatch_name = dispatch_name # return Dispatcher # # Path: soap/common/cache.py # def cached(f): # class NonLocals(object): # pass # CACHE_CAPACITY = 1000000 # cache = {} # NonLocals.full = False # NonLocals.hits = NonLocals.misses = NonLocals.currsize = 0 # NonLocals.root = [] # NonLocals.root[:] = [NonLocals.root, NonLocals.root, None, None] # PREV, NEXT, KEY, RESULT = range(4) # # def decorated(*args, **kwargs): # if not kwargs: # key_tuple = args # else: # key_tuple = (args, tuple(sorted(kwargs.items(), key=hash))) # key = pickle.dumps(key_tuple) # link = cache.get(key) # if link is not None: # p, n, k, r = link # p[NEXT] = n # n[PREV] = p # last = NonLocals.root[PREV] # last[NEXT] = NonLocals.root[PREV] = link # link[PREV] = last # link[NEXT] = NonLocals.root # NonLocals.hits += 1 # return r # r = f(*args, **kwargs) # if NonLocals.full: # NonLocals.root[KEY] = key # NonLocals.root[RESULT] = r # cache[key] = NonLocals.root # NonLocals.root = NonLocals.root[NEXT] # del cache[NonLocals.root[KEY]] # NonLocals.root[KEY] = NonLocals.root[RESULT] = None # else: # last = NonLocals.root[PREV] # link = [last, NonLocals.root, key, r] # cache[key] = last[NEXT] = NonLocals.root[PREV] = link # NonLocals.currsize += 1 # NonLocals.full = (NonLocals.currsize == CACHE_CAPACITY) # NonLocals.misses += 1 # return r # # def cache_info(): # return NonLocals.hits, NonLocals.misses, NonLocals.currsize # # def cache_clear(): # cache.clear() # NonLocals.root[:] = [NonLocals.root, NonLocals.root, None, None] # NonLocals.hits = NonLocals.misses = NonLocals.currsize = 0 # NonLocals.full = False # # d = functools.wraps(f)(decorated) # d.cache_info = cache_info # d.cache_clear = cache_clear # d.wrapped_func = f # # global _cached_funcs # _cached_funcs.append(d) # # return d . Output only the next line.
class GenericExecuter(base_dispatcher()):
Given snippet: <|code_start|>def is_arith_expr(e): """Check if `e` is an expression.""" return isinstance(e, ArithExpr) def is_bool_expr(e): """Check if `e` is a boolean expression.""" return isinstance(e, BoolExpr) def concat_multi_expr(*expr_args): """Concatenates multiple expressions into a single expression by using the barrier operator. """ me = None for e in expr_args: me = me | e if me else e return me def split_multi_expr(e): """Splits the single expression into multiple expressions.""" if e.op != BARRIER_OP: return [e] return split_multi_expr(e.a1) + split_multi_expr(e.a2) op_expr_cls_map = None <|code_end|> , continue by predicting the next line. Consider current file imports: from soap.common.base import base_dispatcher from soap.common.cache import cached from soap.expression.variable import Variable from soap.expression.variable import VariableTuple from soap.expression.base import Expression from soap.expression.variable import Variable, VariableTuple from soap.expression.arithmetic import ArithExpr from soap.expression.boolean import BoolExpr from soap.expression.operators import BARRIER_OP from soap.expression import operators from soap.expression.arithmetic import ( UnaryArithExpr, BinaryArithExpr, TernaryArithExpr, SelectExpr ) from soap.expression.boolean import ( UnaryBoolExpr, BinaryBoolExpr, TernaryBoolExpr ) from soap.expression.fixpoint import FixExpr from soap.expression.linalg import Subscript, AccessExpr, UpdateExpr from soap.expression.fixpoint import FixExpr and context: # Path: soap/common/base.py # def base_dispatcher(dispatch_name='execute'): # class Dispatcher(BaseDispatcher): # pass # Dispatcher.dispatch_name = dispatch_name # return Dispatcher # # Path: soap/common/cache.py # def cached(f): # class NonLocals(object): # pass # CACHE_CAPACITY = 1000000 # cache = {} # NonLocals.full = False # NonLocals.hits = NonLocals.misses = NonLocals.currsize = 0 # NonLocals.root = [] # NonLocals.root[:] = [NonLocals.root, NonLocals.root, None, None] # PREV, NEXT, KEY, RESULT = range(4) # # def decorated(*args, **kwargs): # if not kwargs: # key_tuple = args # else: # key_tuple = (args, tuple(sorted(kwargs.items(), key=hash))) # key = pickle.dumps(key_tuple) # link = cache.get(key) # if link is not None: # p, n, k, r = link # p[NEXT] = n # n[PREV] = p # last = NonLocals.root[PREV] # last[NEXT] = NonLocals.root[PREV] = link # link[PREV] = last # link[NEXT] = NonLocals.root # NonLocals.hits += 1 # return r # r = f(*args, **kwargs) # if NonLocals.full: # NonLocals.root[KEY] = key # NonLocals.root[RESULT] = r # cache[key] = NonLocals.root # NonLocals.root = NonLocals.root[NEXT] # del cache[NonLocals.root[KEY]] # NonLocals.root[KEY] = NonLocals.root[RESULT] = None # else: # last = NonLocals.root[PREV] # link = [last, NonLocals.root, key, r] # cache[key] = last[NEXT] = NonLocals.root[PREV] = link # NonLocals.currsize += 1 # NonLocals.full = (NonLocals.currsize == CACHE_CAPACITY) # NonLocals.misses += 1 # return r # # def cache_info(): # return NonLocals.hits, NonLocals.misses, NonLocals.currsize # # def cache_clear(): # cache.clear() # NonLocals.root[:] = [NonLocals.root, NonLocals.root, None, None] # NonLocals.hits = NonLocals.misses = NonLocals.currsize = 0 # NonLocals.full = False # # d = functools.wraps(f)(decorated) # d.cache_info = cache_info # d.cache_clear = cache_clear # d.wrapped_func = f # # global _cached_funcs # _cached_funcs.append(d) # # return d which might include code, classes, or functions. Output only the next line.
@cached
Given the following code snippet before the placeholder: <|code_start|>""" .. module:: soap.analysis.utils :synopsis: Provides utility functions for analysis and plotting. """ def analyze(expr_set, state, out_vars=None, **kwargs): """Provides area and error analysis of expressions with input ranges and precisions. :param expr_set: A set of expressions. :type expr_set: set or list :param state: The ranges of input variables. :type state: dictionary containing mappings from variables to :class:`soap.semantics.error.Interval` :param out_vars: The output variables of the metastate :type out_vars: :class:`collections.Sequence` """ <|code_end|> , predict the next line using imports from the current file: from soap.analysis.core import Analysis and context including class names, function names, and sometimes code from other files: # Path: soap/analysis/core.py # class Analysis(object): # # def __init__( # self, expr_set, state, out_vars=None, recurrences=None, # size_limit=None, round_values=None, multiprocessing=None): # """Analysis class initialisation. # # :param expr_set: A set of expressions or a single expression. # :type expr_set: `set` or :class:`soap.expression.Expression` # :param state: The ranges of input variables. # :type state: dictionary containing mappings from variables to # :class:`soap.semantics.error.Interval` # """ # super().__init__() # self.expr_set = expr_set # self.state = state # self.out_vars = out_vars # self.recurrences = recurrences # self.size_limit = size_limit or context.size_limit # self.round_values = round_values # if multiprocessing is not None: # self.multiprocessing = multiprocessing # else: # self.multiprocessing = context.multiprocessing # self._results = None # # def analyze(self): # """Analyzes the set of expressions with input ranges and precisions # provided in initialisation. # # :returns: a list of dictionaries each containing results and the # expression. # """ # results = self._results # if results: # return results # # expr_set = self.expr_set # state = self.state # out_vars = self.out_vars # recurrences = self.recurrences # round_values = self.round_values # # size = len(expr_set) # limit = self.size_limit # if limit >= 0 and size > limit: # logger.debug( # 'Number of equivalent structures over limit {} > {}, ' # 'reduces population size by sampling.'.format(size, limit)) # random.seed(context.rand_seed) # expr_set = random.sample(expr_set, limit) # size = len(expr_set) # # if self.multiprocessing: # map = pool.map # else: # map = lambda func, args_list: (func(args) for args in args_list) # args_list = [ # (expr, state, out_vars, recurrences, round_values) # for expr in expr_set] # # try: # results = set() # for i, result in enumerate(map(_analyze_expression, args_list)): # logger.persistent('Analysing', '{}/{}'.format(i, size)) # results.add(result) # except KeyboardInterrupt: # logger.warning( # 'Analysis interrupted, completed: {}.'.format(len(results))) # logger.unpersistent('Analysing') # # self._results = results # return results # # def frontier(self): # """Computes the Pareto frontier from analyzed results.""" # return sample_unique(pareto_frontier(self.analyze())) # # def thick_frontier(self): # return thick_frontier(self.analyze()) . Output only the next line.
return Analysis(expr_set, state, out_vars, **kwargs).analyze()
Predict the next line for this snippet: <|code_start|> class TestIntArray(unittest.TestCase): def _list_elements_to_interval(self, values): return [[IntegerInterval(e) for e in l] for l in values] def setUp(self): self.vector_values = [1, 2, 3] <|code_end|> with the help of current file imports: import itertools import unittest from soap.semantics.error import IntegerInterval from soap.semantics.linalg import IntegerIntervalArray as IntArray and context from other files: # Path: soap/semantics/error.py # class IntegerInterval(Interval): # """The interval containing integer values.""" # def __init__(self, v=None, top=False, bottom=False): # super().__init__(v, top=top, bottom=bottom) # try: # if self.min not in (-inf, inf): # self.min = mpz(self.min) # if self.max not in (-inf, inf): # self.max = mpz(self.max) # except AttributeError: # 'The interval is a top or bottom.' # # def __truediv__(self, other): # return FloatInterval(self) / other # # Path: soap/semantics/linalg.py # class IntegerIntervalArray(MultiDimensionalArray): # value_class = IntegerInterval , which may contain function names, class names, or code. Output only the next line.
self.vector = IntArray(self.vector_values)
Given the following code snippet before the placeholder: <|code_start|> Process = NoDaemonProcess class _Pool(object): def __init__(self, cpu=None): super().__init__() self._cpu = cpu or multiprocessing.cpu_count() self._pool = None self.map = self._map_func_wrapper('imap') self.map_unordered = self._map_func_wrapper('imap_unordered') @property def pool(self): if not self._pool: cpu = self._cpu self._pool = _NoDaemonPool(cpu, initializer=self._initializer) return self._pool @staticmethod def _initializer(): signal.signal(signal.SIGINT, signal.SIG_IGN) def _map_func_wrapper(self, func_name): def wrapped(map_func, items, chunksize=None): if chunksize is None: chunksize = int(len(items) / self._cpu) + 1 try: func = getattr(self.pool, func_name) return func(map_func, items, chunksize) except KeyboardInterrupt: <|code_end|> , predict the next line using imports from the current file: import signal import multiprocessing from multiprocessing.pool import Pool from soap import logger from soap.common.cache import process_invalidate_cache and context including class names, function names, and sometimes code from other files: # Path: soap/logger.py # class levels(): # def set_context(**kwargs): # def get_context(): # def header(s, l=levels.info): # def format(*args): # def log(*args, **kwargs): # def line(*args, **kwargs): # def rewrite(*args, **kwargs): # def persistent(name, *args, **kwargs): # def unpersistent(*args): # def local_context(**kwargs): # def log_level(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_enable(l): # def wrapper(f): # def wrapped(*args, **kwargs): # def log_context(l): # def wrapper(): # def _init_level(): . Output only the next line.
logger.warning(
Continue the code snippet: <|code_start|> # @see http://ccbv.co.uk/projects/Django/1.6/django.views.generic.list/ListView/ # @see http://ccbv.co.uk/projects/Django/1.6/django.views.generic.detail/DetailView/ # @see https://docs.djangoproject.com/en/1.4/topics/class-based-views/#dynamic-filtering def get_queryset(self): self.object = get_object_or_404(Section, parent_id=None, slug=self.kwargs.get('slug', None)) self.notices_present = False section_ids = [] for section in self.object._get_descendants(include_self=True): if section.title == 'NOTICES OF MOTION UNDER RULE 32(3)': self.notices_present = True if self.notices: section_ids.append(section.id) elif not self.notices: section_ids.append(section.id) return Speech.objects.filter(section__in=section_ids).prefetch_related('speaker', 'speaker__memberships', 'speaker__memberships__organization', 'section', 'section__parent') def get_context_data(self, **kwargs): context = super(DebateDetailView, self).get_context_data(**kwargs) context['section'] = self.object context['notices'] = self.notices context['notices_present'] = self.notices_present return context debate = DebateDetailView.as_view() notices = DebateDetailView.as_view(notices=True) debate_single_page = DebateDetailView.as_view(paginate_by=None) notices_single_page = DebateDetailView.as_view(paginate_by=None, notices=True) class BillListView(ListView): <|code_end|> . Use current file imports: import calendar import json import re from collections import defaultdict from heapq import nlargest from operator import itemgetter from django import forms from django.db.models import Count from django.shortcuts import get_object_or_404, render_to_response from django.utils.html import strip_tags from django.views.generic import ListView, DetailView from django.views.generic.dates import ArchiveIndexView, YearArchiveView, MonthArchiveView from haystack.forms import SearchForm from haystack.query import RelatedSearchQuerySet from haystack.views import SearchView from popolo.models import Organization from speeches.models import Section, Speaker, Speech from speeches.search import SpeakerForm from legislature.models import Action, Bill and context (classes, functions, or code) from other files: # Path: legislature/models.py # class Action(models.Model): # description = models.TextField() # date = models.DateField(blank=True, null=True) # text = models.TextField(blank=True, null=True) # bill = models.ForeignKey(Bill, blank=True, null=True) # had to be NULL for migration # # class Meta: # ordering = ['date'] # unique_together = ('bill', 'description') # # def __str__(self): # return self.description # # class Bill(models.Model): # STATUS_CHOICES = ( # ('1st', 'First Reading'), # ('2nd', 'Second Reading'), # ('LA', 'Law Amendments Committee'), # ('PL', 'Private & Local Bills Committee'), # ('WH', 'Committee of the Whole House'), # ('3rd', 'Third Reading'), # ('RA', 'Royal Assent'), # ) # # identifier = models.PositiveIntegerField() # title = models.TextField() # description = models.TextField() # classification = models.TextField() # creator = models.ForeignKey(Speaker, blank=True, null=True, on_delete=models.SET_NULL) # modified = models.DateField() # status = models.CharField(max_length=3, choices=STATUS_CHOICES) # slug = models.TextField() # url = models.URLField() # law_amendments_committee_submissions_url = models.URLField() # # def __str__(self): # return self.title # # @models.permalink # def get_absolute_url(self): # return ('legislature:bill-view', (), {'slug': self.slug}) . Output only the next line.
model = Bill
Predict the next line for this snippet: <|code_start|> bill.law_amendments_committee_submissions_url = div.xpath('string(.//@href[contains(.,"/committees/submissions/")])') # @see http://nslegislature.ca/index.php/proceedings/bills/liquor_control_act_-_bill_52 matches = div.xpath('./p[not(@class)]//@href') if matches: bill.creator = Speaker.objects.get(sources__url=matches[0].rstrip('/')) # Some descriptions are identical to titles. description = div.xpath('./h3//text()')[1].rstrip('*\n ') if bill.title != description: bill.description = description if div.xpath('.//text()[contains(.,"Law Amendments Committee")]'): bill.classification = 'Public Bills' elif div.xpath('.//text()[contains(.,"Private and Local Bills")]'): bill.classification = 'Private and Local Bills' if not bill.pk or as_dict != model_to_dict(bill): bill.save() for tr in div.xpath('.//tr'): matches = tr.xpath('./td//text()') if matches and matches[0] != 'View': # Skip link to statute description = tr.xpath('./th//text()')[0].strip() if description == 'Second Reading Passed': description = 'Second Reading' # Avoids importing duplicates. try: <|code_end|> with the help of current file imports: import datetime import re import requests from django.core.management.base import BaseCommand from django.forms.models import model_to_dict from lxml import html from speeches.models import Speaker from legislature.models import Action, Bill and context from other files: # Path: legislature/models.py # class Action(models.Model): # description = models.TextField() # date = models.DateField(blank=True, null=True) # text = models.TextField(blank=True, null=True) # bill = models.ForeignKey(Bill, blank=True, null=True) # had to be NULL for migration # # class Meta: # ordering = ['date'] # unique_together = ('bill', 'description') # # def __str__(self): # return self.description # # class Bill(models.Model): # STATUS_CHOICES = ( # ('1st', 'First Reading'), # ('2nd', 'Second Reading'), # ('LA', 'Law Amendments Committee'), # ('PL', 'Private & Local Bills Committee'), # ('WH', 'Committee of the Whole House'), # ('3rd', 'Third Reading'), # ('RA', 'Royal Assent'), # ) # # identifier = models.PositiveIntegerField() # title = models.TextField() # description = models.TextField() # classification = models.TextField() # creator = models.ForeignKey(Speaker, blank=True, null=True, on_delete=models.SET_NULL) # modified = models.DateField() # status = models.CharField(max_length=3, choices=STATUS_CHOICES) # slug = models.TextField() # url = models.URLField() # law_amendments_committee_submissions_url = models.URLField() # # def __str__(self): # return self.title # # @models.permalink # def get_absolute_url(self): # return ('legislature:bill-view', (), {'slug': self.slug}) , which may contain function names, class names, or code. Output only the next line.
Action.objects.get(description=description, bill=bill)
Predict the next line for this snippet: <|code_start|> class Command(BaseCommand): help = 'Imports bills from the NS Legislature website.' def get(self, path): return requests.get(self.base_url + path).json() def handle(self, *args, **options): url = 'http://nslegislature.ca/index.php/proceedings/status-of-bills/sort/status' page = requests.get(url) tree = html.fromstring(page.text) tree.make_links_absolute(url) for tr in tree.xpath('//tr[@valign="top"]'): identifier = int(tr.xpath('./td[2]//text()')[0]) try: <|code_end|> with the help of current file imports: import datetime import re import requests from django.core.management.base import BaseCommand from django.forms.models import model_to_dict from lxml import html from speeches.models import Speaker from legislature.models import Action, Bill and context from other files: # Path: legislature/models.py # class Action(models.Model): # description = models.TextField() # date = models.DateField(blank=True, null=True) # text = models.TextField(blank=True, null=True) # bill = models.ForeignKey(Bill, blank=True, null=True) # had to be NULL for migration # # class Meta: # ordering = ['date'] # unique_together = ('bill', 'description') # # def __str__(self): # return self.description # # class Bill(models.Model): # STATUS_CHOICES = ( # ('1st', 'First Reading'), # ('2nd', 'Second Reading'), # ('LA', 'Law Amendments Committee'), # ('PL', 'Private & Local Bills Committee'), # ('WH', 'Committee of the Whole House'), # ('3rd', 'Third Reading'), # ('RA', 'Royal Assent'), # ) # # identifier = models.PositiveIntegerField() # title = models.TextField() # description = models.TextField() # classification = models.TextField() # creator = models.ForeignKey(Speaker, blank=True, null=True, on_delete=models.SET_NULL) # modified = models.DateField() # status = models.CharField(max_length=3, choices=STATUS_CHOICES) # slug = models.TextField() # url = models.URLField() # law_amendments_committee_submissions_url = models.URLField() # # def __str__(self): # return self.title # # @models.permalink # def get_absolute_url(self): # return ('legislature:bill-view', (), {'slug': self.slug}) , which may contain function names, class names, or code. Output only the next line.
bill = Bill.objects.get(identifier=identifier)
Given snippet: <|code_start|>""" Aggregate event avro schema validation """ schemas = {} def load_all_event_schemas(): """ Initializes aggregate event schemas lookup cache. """ errors = [] for aggregate in list_concrete_aggregates(): for event in list_aggregate_events(aggregate_cls=aggregate): try: schemas[event] = load_event_schema(aggregate, event) except EventSchemaError as e: errors.append(str(e)) # Serve all schema errors at once not iteratively. if errors: raise EventSchemaError("\n".join(errors)) return schemas def set_event_version(aggregate_cls, event_cls, avro_dir=None): <|code_end|> , continue by predicting the next line. Consider current file imports: import avro.schema import itertools import os import stringcase from avro.io import Validate as avro_validate from .settings import get_avro_dir from .utils import list_concrete_aggregates from .utils import list_aggregate_events from .utils import event_to_json from .exceptions import EventSchemaError and context: # Path: djangoevents/settings.py # def get_avro_dir(): # config = get_config() # # try: # avro_folder = config.get('EVENT_SCHEMA_VALIDATION', {})['SCHEMA_DIR'] # except KeyError: # raise ImproperlyConfigured("Please define `SCHEMA_DIR`") # # avro_dir = os.path.abspath(os.path.join(settings.BASE_DIR, '..', avro_folder)) # return avro_dir # # Path: djangoevents/utils.py # def list_concrete_aggregates(): # """ # Lists all non abstract aggregates defined within the application. # """ # aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) # return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] # # Path: djangoevents/utils.py # def list_aggregate_events(aggregate_cls): # """ # Lists all aggregate_cls events defined within the application. # Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. # """ # events = _list_internal_classes(aggregate_cls, DomainEvent) # return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)] # # Path: djangoevents/utils.py # def event_to_json(event): # """ # Converts an event class to its dictionary representation. # Underlying eventsourcing library does not provide a proper event->dict conversion function. # # Note: Similarly to event journal persistence flow, this method supports native JSON types only. # """ # return vars(event) # # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass which might include code, classes, or functions. Output only the next line.
avro_dir = avro_dir or get_avro_dir()
Based on the snippet: <|code_start|>""" Aggregate event avro schema validation """ schemas = {} def load_all_event_schemas(): """ Initializes aggregate event schemas lookup cache. """ errors = [] <|code_end|> , predict the immediate next line with the help of imports: import avro.schema import itertools import os import stringcase from avro.io import Validate as avro_validate from .settings import get_avro_dir from .utils import list_concrete_aggregates from .utils import list_aggregate_events from .utils import event_to_json from .exceptions import EventSchemaError and context (classes, functions, sometimes code) from other files: # Path: djangoevents/settings.py # def get_avro_dir(): # config = get_config() # # try: # avro_folder = config.get('EVENT_SCHEMA_VALIDATION', {})['SCHEMA_DIR'] # except KeyError: # raise ImproperlyConfigured("Please define `SCHEMA_DIR`") # # avro_dir = os.path.abspath(os.path.join(settings.BASE_DIR, '..', avro_folder)) # return avro_dir # # Path: djangoevents/utils.py # def list_concrete_aggregates(): # """ # Lists all non abstract aggregates defined within the application. # """ # aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) # return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] # # Path: djangoevents/utils.py # def list_aggregate_events(aggregate_cls): # """ # Lists all aggregate_cls events defined within the application. # Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. # """ # events = _list_internal_classes(aggregate_cls, DomainEvent) # return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)] # # Path: djangoevents/utils.py # def event_to_json(event): # """ # Converts an event class to its dictionary representation. # Underlying eventsourcing library does not provide a proper event->dict conversion function. # # Note: Similarly to event journal persistence flow, this method supports native JSON types only. # """ # return vars(event) # # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass . Output only the next line.
for aggregate in list_concrete_aggregates():
Given the code snippet: <|code_start|>""" Aggregate event avro schema validation """ schemas = {} def load_all_event_schemas(): """ Initializes aggregate event schemas lookup cache. """ errors = [] for aggregate in list_concrete_aggregates(): <|code_end|> , generate the next line using the imports in this file: import avro.schema import itertools import os import stringcase from avro.io import Validate as avro_validate from .settings import get_avro_dir from .utils import list_concrete_aggregates from .utils import list_aggregate_events from .utils import event_to_json from .exceptions import EventSchemaError and context (functions, classes, or occasionally code) from other files: # Path: djangoevents/settings.py # def get_avro_dir(): # config = get_config() # # try: # avro_folder = config.get('EVENT_SCHEMA_VALIDATION', {})['SCHEMA_DIR'] # except KeyError: # raise ImproperlyConfigured("Please define `SCHEMA_DIR`") # # avro_dir = os.path.abspath(os.path.join(settings.BASE_DIR, '..', avro_folder)) # return avro_dir # # Path: djangoevents/utils.py # def list_concrete_aggregates(): # """ # Lists all non abstract aggregates defined within the application. # """ # aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) # return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] # # Path: djangoevents/utils.py # def list_aggregate_events(aggregate_cls): # """ # Lists all aggregate_cls events defined within the application. # Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. # """ # events = _list_internal_classes(aggregate_cls, DomainEvent) # return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)] # # Path: djangoevents/utils.py # def event_to_json(event): # """ # Converts an event class to its dictionary representation. # Underlying eventsourcing library does not provide a proper event->dict conversion function. # # Note: Similarly to event journal persistence flow, this method supports native JSON types only. # """ # return vars(event) # # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass . Output only the next line.
for event in list_aggregate_events(aggregate_cls=aggregate):
Given the code snippet: <|code_start|>def _event_to_schema_path(aggregate_cls, event_cls, avro_dir, version): aggregate_name = decode_cls_name(aggregate_cls) event_name = decode_cls_name(event_cls) filename = "v{version}_{aggregate_name}_{event_name}.json".format( aggregate_name=aggregate_name, event_name=event_name, version=version) return os.path.join(avro_dir, aggregate_name, filename) def decode_cls_name(cls): """ Convert camel case class name to snake case names used in event documentation. """ return stringcase.snakecase(cls.__name__) def parse_event_schema(spec_body): schema = avro.schema.Parse(spec_body) return schema def get_schema_for_event(event_cls): if event_cls not in schemas: raise EventSchemaError("Cached Schema not found for: {}".format(event_cls)) return schemas[event_cls] def validate_event(event, schema=None): schema = schema or get_schema_for_event(event.__class__) <|code_end|> , generate the next line using the imports in this file: import avro.schema import itertools import os import stringcase from avro.io import Validate as avro_validate from .settings import get_avro_dir from .utils import list_concrete_aggregates from .utils import list_aggregate_events from .utils import event_to_json from .exceptions import EventSchemaError and context (functions, classes, or occasionally code) from other files: # Path: djangoevents/settings.py # def get_avro_dir(): # config = get_config() # # try: # avro_folder = config.get('EVENT_SCHEMA_VALIDATION', {})['SCHEMA_DIR'] # except KeyError: # raise ImproperlyConfigured("Please define `SCHEMA_DIR`") # # avro_dir = os.path.abspath(os.path.join(settings.BASE_DIR, '..', avro_folder)) # return avro_dir # # Path: djangoevents/utils.py # def list_concrete_aggregates(): # """ # Lists all non abstract aggregates defined within the application. # """ # aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) # return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] # # Path: djangoevents/utils.py # def list_aggregate_events(aggregate_cls): # """ # Lists all aggregate_cls events defined within the application. # Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. # """ # events = _list_internal_classes(aggregate_cls, DomainEvent) # return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)] # # Path: djangoevents/utils.py # def event_to_json(event): # """ # Converts an event class to its dictionary representation. # Underlying eventsourcing library does not provide a proper event->dict conversion function. # # Note: Similarly to event journal persistence flow, this method supports native JSON types only. # """ # return vars(event) # # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass . Output only the next line.
return avro_validate(schema, event_to_json(event))
Based on the snippet: <|code_start|>""" Aggregate event avro schema validation """ schemas = {} def load_all_event_schemas(): """ Initializes aggregate event schemas lookup cache. """ errors = [] for aggregate in list_concrete_aggregates(): for event in list_aggregate_events(aggregate_cls=aggregate): try: schemas[event] = load_event_schema(aggregate, event) <|code_end|> , predict the immediate next line with the help of imports: import avro.schema import itertools import os import stringcase from avro.io import Validate as avro_validate from .settings import get_avro_dir from .utils import list_concrete_aggregates from .utils import list_aggregate_events from .utils import event_to_json from .exceptions import EventSchemaError and context (classes, functions, sometimes code) from other files: # Path: djangoevents/settings.py # def get_avro_dir(): # config = get_config() # # try: # avro_folder = config.get('EVENT_SCHEMA_VALIDATION', {})['SCHEMA_DIR'] # except KeyError: # raise ImproperlyConfigured("Please define `SCHEMA_DIR`") # # avro_dir = os.path.abspath(os.path.join(settings.BASE_DIR, '..', avro_folder)) # return avro_dir # # Path: djangoevents/utils.py # def list_concrete_aggregates(): # """ # Lists all non abstract aggregates defined within the application. # """ # aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) # return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] # # Path: djangoevents/utils.py # def list_aggregate_events(aggregate_cls): # """ # Lists all aggregate_cls events defined within the application. # Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. # """ # events = _list_internal_classes(aggregate_cls, DomainEvent) # return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)] # # Path: djangoevents/utils.py # def event_to_json(event): # """ # Converts an event class to its dictionary representation. # Underlying eventsourcing library does not provide a proper event->dict conversion function. # # Note: Similarly to event journal persistence flow, this method supports native JSON types only. # """ # return vars(event) # # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass . Output only the next line.
except EventSchemaError as e:
Predict the next line for this snippet: <|code_start|> UnifiedStoredEvent = namedtuple('UnifiedStoredEvent', [ 'event_id', 'event_type', 'event_version', 'event_data', 'aggregate_id', 'aggregate_type', 'aggregate_version', 'create_date', 'metadata', 'module_name', 'class_name', 'stored_entity_id', ]) class UnifiedTranscoder(AbstractTranscoder): def __init__(self, json_encoder_cls=None): self.json_encoder_cls = json_encoder_cls # encrypt not implemented def serialize(self, domain_event): """ Serializes a domain event into a stored event. """ <|code_end|> with the help of current file imports: from .domain import DomainEvent from .schema import get_event_version from .settings import adds_schema_version_to_event_data from .utils import camel_case_to_snake_case from collections import namedtuple from datetime import datetime from eventsourcing.domain.model.events import resolve_attr from eventsourcing.domain.services.transcoding import AbstractTranscoder from eventsourcing.domain.services.transcoding import ObjectJSONDecoder from eventsourcing.domain.services.transcoding import id_prefix_from_event from eventsourcing.domain.services.transcoding import make_stored_entity_id from eventsourcing.utils.time import timestamp_from_uuid from inspect import isclass import importlib import json and context from other files: # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/schema.py # def get_event_version(event_cls): # return getattr(event_cls, 'version', None) or 1 # # Path: djangoevents/settings.py # def adds_schema_version_to_event_data(): # config = get_config() # return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False) # # Path: djangoevents/utils.py # def camel_case_to_snake_case(text): # # def repl(match): # sep = match.group().lower() # if match.start() > 0: # sep = '_%s' % sep # return sep # # return re.sub(r'[A-Z][a-z]', repl, text).lower() , which may contain function names, class names, or code. Output only the next line.
assert isinstance(domain_event, DomainEvent)
Next line prediction: <|code_start|> 'aggregate_id', 'aggregate_type', 'aggregate_version', 'create_date', 'metadata', 'module_name', 'class_name', 'stored_entity_id', ]) class UnifiedTranscoder(AbstractTranscoder): def __init__(self, json_encoder_cls=None): self.json_encoder_cls = json_encoder_cls # encrypt not implemented def serialize(self, domain_event): """ Serializes a domain event into a stored event. """ assert isinstance(domain_event, DomainEvent) event_data = {key: value for key, value in domain_event.__dict__.items() if key not in { 'domain_event_id', 'entity_id', 'entity_version', 'metadata', }} domain_event_class = type(domain_event) <|code_end|> . Use current file imports: (from .domain import DomainEvent from .schema import get_event_version from .settings import adds_schema_version_to_event_data from .utils import camel_case_to_snake_case from collections import namedtuple from datetime import datetime from eventsourcing.domain.model.events import resolve_attr from eventsourcing.domain.services.transcoding import AbstractTranscoder from eventsourcing.domain.services.transcoding import ObjectJSONDecoder from eventsourcing.domain.services.transcoding import id_prefix_from_event from eventsourcing.domain.services.transcoding import make_stored_entity_id from eventsourcing.utils.time import timestamp_from_uuid from inspect import isclass import importlib import json) and context including class names, function names, or small code snippets from other files: # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/schema.py # def get_event_version(event_cls): # return getattr(event_cls, 'version', None) or 1 # # Path: djangoevents/settings.py # def adds_schema_version_to_event_data(): # config = get_config() # return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False) # # Path: djangoevents/utils.py # def camel_case_to_snake_case(text): # # def repl(match): # sep = match.group().lower() # if match.start() > 0: # sep = '_%s' % sep # return sep # # return re.sub(r'[A-Z][a-z]', repl, text).lower() . Output only the next line.
event_version = get_event_version(domain_event_class)
Using the snippet: <|code_start|> event_data=self._json_encode(event_data), aggregate_id=domain_event.entity_id, aggregate_type=get_aggregate_type(domain_event), aggregate_version=domain_event.entity_version, create_date=datetime.fromtimestamp(timestamp_from_uuid(domain_event.domain_event_id)), metadata=self._json_encode(getattr(domain_event, 'metadata', None)), module_name=domain_event_class.__module__, class_name=domain_event_class.__qualname__, # have to have stored_entity_id because of the lib stored_entity_id=make_stored_entity_id(id_prefix_from_event(domain_event), domain_event.entity_id), ) def deserialize(self, stored_event): """ Recreates original domain event from stored event topic and event attrs. """ assert isinstance(stored_event, UnifiedStoredEvent) # Get the domain event class from the topic. domain_event_class = self._get_domain_event_class(stored_event.module_name, stored_event.class_name) # Deserialize event attributes from JSON event_attrs = self._json_decode(stored_event.event_data) # Reinstantiate and return the domain event object. defaults = { 'entity_id': stored_event.aggregate_id, 'entity_version': stored_event.aggregate_version, 'domain_event_id': stored_event.event_id, } <|code_end|> , determine the next line of code. You have imports: from .domain import DomainEvent from .schema import get_event_version from .settings import adds_schema_version_to_event_data from .utils import camel_case_to_snake_case from collections import namedtuple from datetime import datetime from eventsourcing.domain.model.events import resolve_attr from eventsourcing.domain.services.transcoding import AbstractTranscoder from eventsourcing.domain.services.transcoding import ObjectJSONDecoder from eventsourcing.domain.services.transcoding import id_prefix_from_event from eventsourcing.domain.services.transcoding import make_stored_entity_id from eventsourcing.utils.time import timestamp_from_uuid from inspect import isclass import importlib import json and context (class names, function names, or code) available: # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/schema.py # def get_event_version(event_cls): # return getattr(event_cls, 'version', None) or 1 # # Path: djangoevents/settings.py # def adds_schema_version_to_event_data(): # config = get_config() # return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False) # # Path: djangoevents/utils.py # def camel_case_to_snake_case(text): # # def repl(match): # sep = match.group().lower() # if match.start() > 0: # sep = '_%s' % sep # return sep # # return re.sub(r'[A-Z][a-z]', repl, text).lower() . Output only the next line.
if adds_schema_version_to_event_data():
Predict the next line for this snippet: <|code_start|> if not issubclass(domain_event_class, DomainEvent): raise ValueError("Event class is not a DomainEvent: {}".format(domain_event_class)) return domain_event_class def _json_encode(self, data): return json.dumps(data, separators=(',', ':'), sort_keys=True, cls=self.json_encoder_cls) def _json_decode(self, json_str): return json.loads(json_str, cls=ObjectJSONDecoder) class ResolveDomainFailed(Exception): pass def get_aggregate_type(domain_event): assert isinstance(domain_event, DomainEvent) domain_event_class = type(domain_event) return domain_event_class.__qualname__.split('.')[0] def get_event_type(domain_event): if hasattr(domain_event, 'event_type'): return getattr(domain_event, 'event_type') else: aggregate_type = get_aggregate_type(domain_event) event_name = domain_event.__class__.__name__ event_type_name = '%s%s' % (aggregate_type, event_name) <|code_end|> with the help of current file imports: from .domain import DomainEvent from .schema import get_event_version from .settings import adds_schema_version_to_event_data from .utils import camel_case_to_snake_case from collections import namedtuple from datetime import datetime from eventsourcing.domain.model.events import resolve_attr from eventsourcing.domain.services.transcoding import AbstractTranscoder from eventsourcing.domain.services.transcoding import ObjectJSONDecoder from eventsourcing.domain.services.transcoding import id_prefix_from_event from eventsourcing.domain.services.transcoding import make_stored_entity_id from eventsourcing.utils.time import timestamp_from_uuid from inspect import isclass import importlib import json and context from other files: # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/schema.py # def get_event_version(event_cls): # return getattr(event_cls, 'version', None) or 1 # # Path: djangoevents/settings.py # def adds_schema_version_to_event_data(): # config = get_config() # return config.get('ADDS_SCHEMA_VERSION_TO_EVENT_DATA', False) # # Path: djangoevents/utils.py # def camel_case_to_snake_case(text): # # def repl(match): # sep = match.group().lower() # if match.start() > 0: # sep = '_%s' % sep # return sep # # return re.sub(r'[A-Z][a-z]', repl, text).lower() , which may contain function names, class names, or code. Output only the next line.
return camel_case_to_snake_case(event_type_name)
Predict the next line after this snippet: <|code_start|> @abstract class BaseAggregate(EventSourcedEntity): """ `EventSourcedEntity` with saner mutator routing & naming: >>> class Asset(BaseAggregate): >>> class Created(BaseAggregate.Created): >>> def mutate(event, klass): >>> return klass(...) >>> >>> class Updated(DomainEvent): >>> def mutate(event, instance): >>> instance.connect = True >>> return instance """ @classmethod def is_abstract_class(cls): <|code_end|> using the current file's imports: import warnings from djangoevents.utils_abstract import abstract from djangoevents.utils_abstract import is_abstract from eventsourcing.domain.model.entity import DomainEvent from eventsourcing.domain.model.entity import EventSourcedEntity and any relevant context from other files: # Path: djangoevents/utils_abstract.py # def abstract(cls): # """ # Decorator marking classes as abstract. # # The "abstract" mark is an internal tag. Classes can be checked for # being abstract with the `is_abstract` function. The tag is non # inheritable: every class or subclass has to be explicitly marked # with the decorator to be considered abstract. # """ # # _abstract_classes.add(cls) # return cls # # Path: djangoevents/utils_abstract.py # def is_abstract(cls): # return cls in _abstract_classes . Output only the next line.
return is_abstract(cls)
Given the following code snippet before the placeholder: <|code_start|> class DjangoStoredEventRepository(AbstractStoredEventRepository): def __init__(self, *args, **kwargs): self.EventModel = Event super(DjangoStoredEventRepository, self).__init__(*args, **kwargs) def append(self, new_stored_event, new_version_number=None, max_retries=3, artificial_failure_rate=0): """ Saves given stored event in this repository. """ # Check the new event is a stored event instance. <|code_end|> , predict the next line using imports from the current file: from .unifiedtranscoder import UnifiedStoredEvent from django.conf import settings from django.db.utils import IntegrityError from django.utils import timezone from djangoevents.exceptions import AlreadyExists from eventsourcing.domain.services.eventstore import AbstractStoredEventRepository from eventsourcing.domain.services.eventstore import EntityVersionDoesNotExist from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from .models import Event # import model at runtime for making top level import possible import datetime and context including class names, function names, and sometimes code from other files: # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass . Output only the next line.
assert isinstance(new_stored_event, UnifiedStoredEvent)
Continue the code snippet: <|code_start|> .filter(aggregate_version=version_number) if not events_query.exists(): raise EntityVersionDoesNotExist() return EntityVersion( entity_version_id=self.make_entity_version_id(stored_entity_id, version_number), event_id=events_query[0].event_id, ) def write_version_and_event(self, new_stored_event, new_version_number=None, max_retries=3, artificial_failure_rate=0): try: self.EventModel.objects.create( event_id=new_stored_event.event_id, event_type=new_stored_event.event_type, event_version=new_stored_event.event_version, event_data=new_stored_event.event_data, aggregate_id=new_stored_event.aggregate_id, aggregate_type=new_stored_event.aggregate_type, aggregate_version=new_stored_event.aggregate_version, create_date=make_aware_if_needed(new_stored_event.create_date), metadata=new_stored_event.metadata, module_name=new_stored_event.module_name, class_name=new_stored_event.class_name, stored_entity_id=new_stored_event.stored_entity_id, ) except IntegrityError as err: create_attempt = not new_version_number if create_attempt: msg = "Aggregate with id %r already exists" % new_stored_event.aggregate_id <|code_end|> . Use current file imports: from .unifiedtranscoder import UnifiedStoredEvent from django.conf import settings from django.db.utils import IntegrityError from django.utils import timezone from djangoevents.exceptions import AlreadyExists from eventsourcing.domain.services.eventstore import AbstractStoredEventRepository from eventsourcing.domain.services.eventstore import EntityVersionDoesNotExist from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from .models import Event # import model at runtime for making top level import possible import datetime and context (classes, functions, or code) from other files: # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass . Output only the next line.
raise AlreadyExists(msg)
Predict the next line for this snippet: <|code_start|> class SampleAggregate(EventSourcedEntity): class Created(EventSourcedEntity.Created): pass <|code_end|> with the help of current file imports: from ..app import EventSourcingWithDjango from ..models import Event from ..repository import from_model_instance from ..unifiedtranscoder import UnifiedStoredEvent from eventsourcing.domain.model.entity import EventSourcedEntity from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from datetime import datetime from django.db import transaction from djangoevents.exceptions import AlreadyExists import json import pytest and context from other files: # Path: djangoevents/app.py # class EventSourcingWithDjango(EventSourcingApplication): # def __init__(self, **kwargs): # kwargs.setdefault('json_encoder_cls', DjangoJSONEncoder) # super().__init__(**kwargs) # self.on_init() # # def on_init(self): # """ # Override at subclass. For example, initialize repositories that this # app would use. # """ # # def create_stored_event_repo(self, **kwargs): # return DjangoStoredEventRepository(**kwargs) # # def create_transcoder(self, always_encrypt, cipher, json_decoder_cls, json_encoder_cls): # return UnifiedTranscoder(json_encoder_cls=json_encoder_cls) # # def get_repo_for_aggregate(self, aggregate_cls): # """ # Returns EventSourcedRepository class for a given aggregate. # """ # clsname = '%sRepository' % aggregate_cls.__name__ # repo_cls = type(clsname, (EventSourcedRepository,), {'domain_class': aggregate_cls}) # return repo_cls(event_store=self.event_store) # # def get_repo_for_entity(self, entity_cls): # """ # Returns EventSourcedRepository class for given entity. # """ # msg = "`get_repo_for_entity` is depreciated. Please switch to: `get_repo_for_aggregate`" # warnings.warn(msg, DeprecationWarning) # return self.get_repo_for_aggregate(aggregate_cls=entity_cls) # # Path: djangoevents/models.py # class Event(models.Model): # event_id = models.CharField(max_length=255, db_index=True) # event_type = models.CharField(max_length=255) # event_version = models.IntegerField(null=True) # event_data = models.TextField() # aggregate_id = models.CharField(max_length=255, db_index=True) # aggregate_type = models.CharField(max_length=255) # aggregate_version = models.IntegerField() # create_date = models.DateTimeField() # metadata = models.TextField() # module_name = models.CharField(max_length=255, db_column='_module_name') # class_name = models.CharField(max_length=255, db_column='_class_name') # stored_entity_id = models.CharField(max_length=255, db_column='_stored_entity_id', db_index=True) # # class Meta: # unique_together = (("aggregate_id", "aggregate_type", "aggregate_version"),) # db_table = 'event_journal' # # def __str__(self): # return '%s.%s | %s | %s' % (self.aggregate_type, self.event_type, self.event_id, self.create_date) # # Path: djangoevents/repository.py # def from_model_instance(event): # return UnifiedStoredEvent( # event_id=event.event_id, # event_type=event.event_type, # event_version=event.event_version, # event_data=event.event_data, # aggregate_id=event.aggregate_id, # aggregate_type=event.aggregate_type, # aggregate_version=event.aggregate_version, # create_date=event.create_date, # metadata=event.metadata, # module_name=event.module_name, # class_name=event.class_name, # stored_entity_id=event.stored_entity_id # ) # # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass , which may contain function names, class names, or code. Output only the next line.
class SampleApp(EventSourcingWithDjango):
Using the snippet: <|code_start|> create_date=datetime.fromtimestamp(timestamp_from_uuid(event_id)), stored_entity_id='SampleAggregate::' + aggregate_id, metadata='', module_name='', class_name='', ) def save_events(repo, stored_events): for e in stored_events: repo.append(e) @pytest.fixture def repo(): app = SampleApp() return app.stored_event_repo @pytest.fixture def stored_events(): return [new_stored_event(uuids[i], 'Created', {'title': 'test'}, uuids[0], i) for i, uuid in enumerate(uuids)] @pytest.mark.django_db def test_repo_append(repo): test_stored_event = new_stored_event(uuids[0], 'Created', {'title': 'test'}, uuids[1], 1) # test basic save and get repo.append(test_stored_event) <|code_end|> , determine the next line of code. You have imports: from ..app import EventSourcingWithDjango from ..models import Event from ..repository import from_model_instance from ..unifiedtranscoder import UnifiedStoredEvent from eventsourcing.domain.model.entity import EventSourcedEntity from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from datetime import datetime from django.db import transaction from djangoevents.exceptions import AlreadyExists import json import pytest and context (class names, function names, or code) available: # Path: djangoevents/app.py # class EventSourcingWithDjango(EventSourcingApplication): # def __init__(self, **kwargs): # kwargs.setdefault('json_encoder_cls', DjangoJSONEncoder) # super().__init__(**kwargs) # self.on_init() # # def on_init(self): # """ # Override at subclass. For example, initialize repositories that this # app would use. # """ # # def create_stored_event_repo(self, **kwargs): # return DjangoStoredEventRepository(**kwargs) # # def create_transcoder(self, always_encrypt, cipher, json_decoder_cls, json_encoder_cls): # return UnifiedTranscoder(json_encoder_cls=json_encoder_cls) # # def get_repo_for_aggregate(self, aggregate_cls): # """ # Returns EventSourcedRepository class for a given aggregate. # """ # clsname = '%sRepository' % aggregate_cls.__name__ # repo_cls = type(clsname, (EventSourcedRepository,), {'domain_class': aggregate_cls}) # return repo_cls(event_store=self.event_store) # # def get_repo_for_entity(self, entity_cls): # """ # Returns EventSourcedRepository class for given entity. # """ # msg = "`get_repo_for_entity` is depreciated. Please switch to: `get_repo_for_aggregate`" # warnings.warn(msg, DeprecationWarning) # return self.get_repo_for_aggregate(aggregate_cls=entity_cls) # # Path: djangoevents/models.py # class Event(models.Model): # event_id = models.CharField(max_length=255, db_index=True) # event_type = models.CharField(max_length=255) # event_version = models.IntegerField(null=True) # event_data = models.TextField() # aggregate_id = models.CharField(max_length=255, db_index=True) # aggregate_type = models.CharField(max_length=255) # aggregate_version = models.IntegerField() # create_date = models.DateTimeField() # metadata = models.TextField() # module_name = models.CharField(max_length=255, db_column='_module_name') # class_name = models.CharField(max_length=255, db_column='_class_name') # stored_entity_id = models.CharField(max_length=255, db_column='_stored_entity_id', db_index=True) # # class Meta: # unique_together = (("aggregate_id", "aggregate_type", "aggregate_version"),) # db_table = 'event_journal' # # def __str__(self): # return '%s.%s | %s | %s' % (self.aggregate_type, self.event_type, self.event_id, self.create_date) # # Path: djangoevents/repository.py # def from_model_instance(event): # return UnifiedStoredEvent( # event_id=event.event_id, # event_type=event.event_type, # event_version=event.event_version, # event_data=event.event_data, # aggregate_id=event.aggregate_id, # aggregate_type=event.aggregate_type, # aggregate_version=event.aggregate_version, # create_date=event.create_date, # metadata=event.metadata, # module_name=event.module_name, # class_name=event.class_name, # stored_entity_id=event.stored_entity_id # ) # # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass . Output only the next line.
events = Event.objects.filter(stored_entity_id=test_stored_event.stored_entity_id)
Using the snippet: <|code_start|> metadata='', module_name='', class_name='', ) def save_events(repo, stored_events): for e in stored_events: repo.append(e) @pytest.fixture def repo(): app = SampleApp() return app.stored_event_repo @pytest.fixture def stored_events(): return [new_stored_event(uuids[i], 'Created', {'title': 'test'}, uuids[0], i) for i, uuid in enumerate(uuids)] @pytest.mark.django_db def test_repo_append(repo): test_stored_event = new_stored_event(uuids[0], 'Created', {'title': 'test'}, uuids[1], 1) # test basic save and get repo.append(test_stored_event) events = Event.objects.filter(stored_entity_id=test_stored_event.stored_entity_id) assert len(events) == 1 <|code_end|> , determine the next line of code. You have imports: from ..app import EventSourcingWithDjango from ..models import Event from ..repository import from_model_instance from ..unifiedtranscoder import UnifiedStoredEvent from eventsourcing.domain.model.entity import EventSourcedEntity from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from datetime import datetime from django.db import transaction from djangoevents.exceptions import AlreadyExists import json import pytest and context (class names, function names, or code) available: # Path: djangoevents/app.py # class EventSourcingWithDjango(EventSourcingApplication): # def __init__(self, **kwargs): # kwargs.setdefault('json_encoder_cls', DjangoJSONEncoder) # super().__init__(**kwargs) # self.on_init() # # def on_init(self): # """ # Override at subclass. For example, initialize repositories that this # app would use. # """ # # def create_stored_event_repo(self, **kwargs): # return DjangoStoredEventRepository(**kwargs) # # def create_transcoder(self, always_encrypt, cipher, json_decoder_cls, json_encoder_cls): # return UnifiedTranscoder(json_encoder_cls=json_encoder_cls) # # def get_repo_for_aggregate(self, aggregate_cls): # """ # Returns EventSourcedRepository class for a given aggregate. # """ # clsname = '%sRepository' % aggregate_cls.__name__ # repo_cls = type(clsname, (EventSourcedRepository,), {'domain_class': aggregate_cls}) # return repo_cls(event_store=self.event_store) # # def get_repo_for_entity(self, entity_cls): # """ # Returns EventSourcedRepository class for given entity. # """ # msg = "`get_repo_for_entity` is depreciated. Please switch to: `get_repo_for_aggregate`" # warnings.warn(msg, DeprecationWarning) # return self.get_repo_for_aggregate(aggregate_cls=entity_cls) # # Path: djangoevents/models.py # class Event(models.Model): # event_id = models.CharField(max_length=255, db_index=True) # event_type = models.CharField(max_length=255) # event_version = models.IntegerField(null=True) # event_data = models.TextField() # aggregate_id = models.CharField(max_length=255, db_index=True) # aggregate_type = models.CharField(max_length=255) # aggregate_version = models.IntegerField() # create_date = models.DateTimeField() # metadata = models.TextField() # module_name = models.CharField(max_length=255, db_column='_module_name') # class_name = models.CharField(max_length=255, db_column='_class_name') # stored_entity_id = models.CharField(max_length=255, db_column='_stored_entity_id', db_index=True) # # class Meta: # unique_together = (("aggregate_id", "aggregate_type", "aggregate_version"),) # db_table = 'event_journal' # # def __str__(self): # return '%s.%s | %s | %s' % (self.aggregate_type, self.event_type, self.event_id, self.create_date) # # Path: djangoevents/repository.py # def from_model_instance(event): # return UnifiedStoredEvent( # event_id=event.event_id, # event_type=event.event_type, # event_version=event.event_version, # event_data=event.event_data, # aggregate_id=event.aggregate_id, # aggregate_type=event.aggregate_type, # aggregate_version=event.aggregate_version, # create_date=event.create_date, # metadata=event.metadata, # module_name=event.module_name, # class_name=event.class_name, # stored_entity_id=event.stored_entity_id # ) # # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass . Output only the next line.
assert test_stored_event == from_model_instance(events[0])
Predict the next line after this snippet: <|code_start|> class SampleAggregate(EventSourcedEntity): class Created(EventSourcedEntity.Created): pass class SampleApp(EventSourcingWithDjango): def on_init(self): self.repo = self.get_repo_for_entity(SampleAggregate) # uuid1 contains time uuids = ['7ab23d4c-a520-11e6-80f5-76304dec7eb7', '846713a8-a520-11e6-80f5-76304dec7eb7', '917e42a0-a520-11e6-80f5-76304dec7eb7', '98ef1faa-a520-11e6-80f5-76304dec7eb7', '9e89b9de-a520-11e6-80f5-76304dec7eb7', 'a678b7a8-a520-11e6-80f5-76304dec7eb7'] def new_stored_event(event_id, event_type, event_data, aggregate_id, aggregate_version): <|code_end|> using the current file's imports: from ..app import EventSourcingWithDjango from ..models import Event from ..repository import from_model_instance from ..unifiedtranscoder import UnifiedStoredEvent from eventsourcing.domain.model.entity import EventSourcedEntity from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from datetime import datetime from django.db import transaction from djangoevents.exceptions import AlreadyExists import json import pytest and any relevant context from other files: # Path: djangoevents/app.py # class EventSourcingWithDjango(EventSourcingApplication): # def __init__(self, **kwargs): # kwargs.setdefault('json_encoder_cls', DjangoJSONEncoder) # super().__init__(**kwargs) # self.on_init() # # def on_init(self): # """ # Override at subclass. For example, initialize repositories that this # app would use. # """ # # def create_stored_event_repo(self, **kwargs): # return DjangoStoredEventRepository(**kwargs) # # def create_transcoder(self, always_encrypt, cipher, json_decoder_cls, json_encoder_cls): # return UnifiedTranscoder(json_encoder_cls=json_encoder_cls) # # def get_repo_for_aggregate(self, aggregate_cls): # """ # Returns EventSourcedRepository class for a given aggregate. # """ # clsname = '%sRepository' % aggregate_cls.__name__ # repo_cls = type(clsname, (EventSourcedRepository,), {'domain_class': aggregate_cls}) # return repo_cls(event_store=self.event_store) # # def get_repo_for_entity(self, entity_cls): # """ # Returns EventSourcedRepository class for given entity. # """ # msg = "`get_repo_for_entity` is depreciated. Please switch to: `get_repo_for_aggregate`" # warnings.warn(msg, DeprecationWarning) # return self.get_repo_for_aggregate(aggregate_cls=entity_cls) # # Path: djangoevents/models.py # class Event(models.Model): # event_id = models.CharField(max_length=255, db_index=True) # event_type = models.CharField(max_length=255) # event_version = models.IntegerField(null=True) # event_data = models.TextField() # aggregate_id = models.CharField(max_length=255, db_index=True) # aggregate_type = models.CharField(max_length=255) # aggregate_version = models.IntegerField() # create_date = models.DateTimeField() # metadata = models.TextField() # module_name = models.CharField(max_length=255, db_column='_module_name') # class_name = models.CharField(max_length=255, db_column='_class_name') # stored_entity_id = models.CharField(max_length=255, db_column='_stored_entity_id', db_index=True) # # class Meta: # unique_together = (("aggregate_id", "aggregate_type", "aggregate_version"),) # db_table = 'event_journal' # # def __str__(self): # return '%s.%s | %s | %s' % (self.aggregate_type, self.event_type, self.event_id, self.create_date) # # Path: djangoevents/repository.py # def from_model_instance(event): # return UnifiedStoredEvent( # event_id=event.event_id, # event_type=event.event_type, # event_version=event.event_version, # event_data=event.event_data, # aggregate_id=event.aggregate_id, # aggregate_type=event.aggregate_type, # aggregate_version=event.aggregate_version, # create_date=event.create_date, # metadata=event.metadata, # module_name=event.module_name, # class_name=event.class_name, # stored_entity_id=event.stored_entity_id # ) # # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass . Output only the next line.
return UnifiedStoredEvent(
Predict the next line for this snippet: <|code_start|> def save_events(repo, stored_events): for e in stored_events: repo.append(e) @pytest.fixture def repo(): app = SampleApp() return app.stored_event_repo @pytest.fixture def stored_events(): return [new_stored_event(uuids[i], 'Created', {'title': 'test'}, uuids[0], i) for i, uuid in enumerate(uuids)] @pytest.mark.django_db def test_repo_append(repo): test_stored_event = new_stored_event(uuids[0], 'Created', {'title': 'test'}, uuids[1], 1) # test basic save and get repo.append(test_stored_event) events = Event.objects.filter(stored_entity_id=test_stored_event.stored_entity_id) assert len(events) == 1 assert test_stored_event == from_model_instance(events[0]) # test unique constraint with transaction.atomic(): test_stored_event2 = new_stored_event(uuids[2], 'Updated', {'title': 'updated test'}, uuids[1], 1) <|code_end|> with the help of current file imports: from ..app import EventSourcingWithDjango from ..models import Event from ..repository import from_model_instance from ..unifiedtranscoder import UnifiedStoredEvent from eventsourcing.domain.model.entity import EventSourcedEntity from eventsourcing.domain.services.transcoding import EntityVersion from eventsourcing.utils.time import timestamp_from_uuid from datetime import datetime from django.db import transaction from djangoevents.exceptions import AlreadyExists import json import pytest and context from other files: # Path: djangoevents/app.py # class EventSourcingWithDjango(EventSourcingApplication): # def __init__(self, **kwargs): # kwargs.setdefault('json_encoder_cls', DjangoJSONEncoder) # super().__init__(**kwargs) # self.on_init() # # def on_init(self): # """ # Override at subclass. For example, initialize repositories that this # app would use. # """ # # def create_stored_event_repo(self, **kwargs): # return DjangoStoredEventRepository(**kwargs) # # def create_transcoder(self, always_encrypt, cipher, json_decoder_cls, json_encoder_cls): # return UnifiedTranscoder(json_encoder_cls=json_encoder_cls) # # def get_repo_for_aggregate(self, aggregate_cls): # """ # Returns EventSourcedRepository class for a given aggregate. # """ # clsname = '%sRepository' % aggregate_cls.__name__ # repo_cls = type(clsname, (EventSourcedRepository,), {'domain_class': aggregate_cls}) # return repo_cls(event_store=self.event_store) # # def get_repo_for_entity(self, entity_cls): # """ # Returns EventSourcedRepository class for given entity. # """ # msg = "`get_repo_for_entity` is depreciated. Please switch to: `get_repo_for_aggregate`" # warnings.warn(msg, DeprecationWarning) # return self.get_repo_for_aggregate(aggregate_cls=entity_cls) # # Path: djangoevents/models.py # class Event(models.Model): # event_id = models.CharField(max_length=255, db_index=True) # event_type = models.CharField(max_length=255) # event_version = models.IntegerField(null=True) # event_data = models.TextField() # aggregate_id = models.CharField(max_length=255, db_index=True) # aggregate_type = models.CharField(max_length=255) # aggregate_version = models.IntegerField() # create_date = models.DateTimeField() # metadata = models.TextField() # module_name = models.CharField(max_length=255, db_column='_module_name') # class_name = models.CharField(max_length=255, db_column='_class_name') # stored_entity_id = models.CharField(max_length=255, db_column='_stored_entity_id', db_index=True) # # class Meta: # unique_together = (("aggregate_id", "aggregate_type", "aggregate_version"),) # db_table = 'event_journal' # # def __str__(self): # return '%s.%s | %s | %s' % (self.aggregate_type, self.event_type, self.event_id, self.create_date) # # Path: djangoevents/repository.py # def from_model_instance(event): # return UnifiedStoredEvent( # event_id=event.event_id, # event_type=event.event_type, # event_version=event.event_version, # event_data=event.event_data, # aggregate_id=event.aggregate_id, # aggregate_type=event.aggregate_type, # aggregate_version=event.aggregate_version, # create_date=event.create_date, # metadata=event.metadata, # module_name=event.module_name, # class_name=event.class_name, # stored_entity_id=event.stored_entity_id # ) # # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # class ResolveDomainFailed(Exception): # def __init__(self, json_encoder_cls=None): # def serialize(self, domain_event): # def deserialize(self, stored_event): # def _get_domain_event_class(module_name, class_name): # def _json_encode(self, data): # def _json_decode(self, json_str): # def get_aggregate_type(domain_event): # def get_event_type(domain_event): # # Path: djangoevents/exceptions.py # class AlreadyExists(DjangoeventsError): # pass , which may contain function names, class names, or code. Output only the next line.
with pytest.raises(AlreadyExists):
Using the snippet: <|code_start|> def list_concrete_aggregates(): """ Lists all non abstract aggregates defined within the application. """ aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] def is_event_mutating(event): return hasattr(event, 'mutate_event') def list_aggregate_events(aggregate_cls): """ Lists all aggregate_cls events defined within the application. Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. """ <|code_end|> , determine the next line of code. You have imports: import inspect import re from .domain import BaseEntity from .domain import BaseAggregate from .domain import DomainEvent from djangoevents.utils_abstract import is_abstract and context (class names, function names, or code) available: # Path: djangoevents/domain.py # class BaseEntity(BaseAggregate): # """ # `EventSourcedEntity` with saner mutator routing: # # OBSOLETE! Interface kept for backward compatibility. # """ # @classmethod # def is_abstract_class(cls): # return super().is_abstract_class() or cls is BaseEntity # # @classmethod # def mutate(cls, entity=None, event=None): # warnings.warn("`BaseEntity` is depreciated. Please switch to: `BaseAggregate`", DeprecationWarning) # return super().mutate(aggregate=entity, event=event) # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # """ # `EventSourcedEntity` with saner mutator routing & naming: # # >>> class Asset(BaseAggregate): # >>> class Created(BaseAggregate.Created): # >>> def mutate(event, klass): # >>> return klass(...) # >>> # >>> class Updated(DomainEvent): # >>> def mutate(event, instance): # >>> instance.connect = True # >>> return instance # """ # # @classmethod # def is_abstract_class(cls): # return is_abstract(cls) # # @classmethod # def mutate(cls, aggregate=None, event=None): # if aggregate: # aggregate._validate_originator(event) # # if not hasattr(event, 'mutate_event'): # msg = "{} does not provide a mutate_event() method.".format(event.__class__) # raise NotImplementedError(msg) # # aggregate = event.mutate_event(event, aggregate or cls) # aggregate._increment_version() # return aggregate # # @classmethod # def create_for_event(cls, event): # aggregate = cls( # entity_id=event.entity_id, # domain_event_id=event.domain_event_id, # entity_version=event.entity_version, # ) # return aggregate # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/utils_abstract.py # def is_abstract(cls): # return cls in _abstract_classes . Output only the next line.
events = _list_internal_classes(aggregate_cls, DomainEvent)
Given snippet: <|code_start|> def list_concrete_aggregates(): """ Lists all non abstract aggregates defined within the application. """ aggregates = set(_list_subclasses(BaseAggregate) + _list_subclasses(BaseEntity)) return [aggregate for aggregate in aggregates if not aggregate.is_abstract_class()] def is_event_mutating(event): return hasattr(event, 'mutate_event') def list_aggregate_events(aggregate_cls): """ Lists all aggregate_cls events defined within the application. Note: Only events with a defined `mutate_event` flow and are not marked as abstract will be returned. """ events = _list_internal_classes(aggregate_cls, DomainEvent) <|code_end|> , continue by predicting the next line. Consider current file imports: import inspect import re from .domain import BaseEntity from .domain import BaseAggregate from .domain import DomainEvent from djangoevents.utils_abstract import is_abstract and context: # Path: djangoevents/domain.py # class BaseEntity(BaseAggregate): # """ # `EventSourcedEntity` with saner mutator routing: # # OBSOLETE! Interface kept for backward compatibility. # """ # @classmethod # def is_abstract_class(cls): # return super().is_abstract_class() or cls is BaseEntity # # @classmethod # def mutate(cls, entity=None, event=None): # warnings.warn("`BaseEntity` is depreciated. Please switch to: `BaseAggregate`", DeprecationWarning) # return super().mutate(aggregate=entity, event=event) # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # """ # `EventSourcedEntity` with saner mutator routing & naming: # # >>> class Asset(BaseAggregate): # >>> class Created(BaseAggregate.Created): # >>> def mutate(event, klass): # >>> return klass(...) # >>> # >>> class Updated(DomainEvent): # >>> def mutate(event, instance): # >>> instance.connect = True # >>> return instance # """ # # @classmethod # def is_abstract_class(cls): # return is_abstract(cls) # # @classmethod # def mutate(cls, aggregate=None, event=None): # if aggregate: # aggregate._validate_originator(event) # # if not hasattr(event, 'mutate_event'): # msg = "{} does not provide a mutate_event() method.".format(event.__class__) # raise NotImplementedError(msg) # # aggregate = event.mutate_event(event, aggregate or cls) # aggregate._increment_version() # return aggregate # # @classmethod # def create_for_event(cls, event): # aggregate = cls( # entity_id=event.entity_id, # domain_event_id=event.domain_event_id, # entity_version=event.entity_version, # ) # return aggregate # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/utils_abstract.py # def is_abstract(cls): # return cls in _abstract_classes which might include code, classes, or functions. Output only the next line.
return [event_cls for event_cls in events if is_event_mutating(event_cls) and not is_abstract(event_cls)]
Continue the code snippet: <|code_start|> class SampleAggregate(EventSourcedEntity): class Created(EventSourcedEntity.Created): pass class Updated(EventSourcedEntity.AttributeChanged): event_type = 'overridden_event_type' def override_schema_version_setting(adds): return override_settings(DJANGOEVENTS_CONFIG={ 'ADDS_SCHEMA_VERSION_TO_EVENT_DATA': adds, }) def test_serialize_and_deserialize_1(): <|code_end|> . Use current file imports: import pytest from ..unifiedtranscoder import UnifiedTranscoder from eventsourcing.domain.model.entity import EventSourcedEntity from django.core.serializers.json import DjangoJSONEncoder from django.test.utils import override_settings from unittest import mock and context (classes, functions, or code) from other files: # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # def __init__(self, json_encoder_cls=None): # self.json_encoder_cls = json_encoder_cls # # encrypt not implemented # # def serialize(self, domain_event): # """ # Serializes a domain event into a stored event. # """ # assert isinstance(domain_event, DomainEvent) # # event_data = {key: value for key, value in domain_event.__dict__.items() if key not in { # 'domain_event_id', # 'entity_id', # 'entity_version', # 'metadata', # }} # # domain_event_class = type(domain_event) # event_version = get_event_version(domain_event_class) # # return UnifiedStoredEvent( # event_id=domain_event.domain_event_id, # event_type=get_event_type(domain_event), # event_version=event_version, # event_data=self._json_encode(event_data), # aggregate_id=domain_event.entity_id, # aggregate_type=get_aggregate_type(domain_event), # aggregate_version=domain_event.entity_version, # create_date=datetime.fromtimestamp(timestamp_from_uuid(domain_event.domain_event_id)), # metadata=self._json_encode(getattr(domain_event, 'metadata', None)), # module_name=domain_event_class.__module__, # class_name=domain_event_class.__qualname__, # # have to have stored_entity_id because of the lib # stored_entity_id=make_stored_entity_id(id_prefix_from_event(domain_event), domain_event.entity_id), # ) # # def deserialize(self, stored_event): # """ # Recreates original domain event from stored event topic and event attrs. # """ # assert isinstance(stored_event, UnifiedStoredEvent) # # Get the domain event class from the topic. # domain_event_class = self._get_domain_event_class(stored_event.module_name, stored_event.class_name) # # # Deserialize event attributes from JSON # event_attrs = self._json_decode(stored_event.event_data) # # # Reinstantiate and return the domain event object. # defaults = { # 'entity_id': stored_event.aggregate_id, # 'entity_version': stored_event.aggregate_version, # 'domain_event_id': stored_event.event_id, # } # # if adds_schema_version_to_event_data(): # defaults['schema_version'] = None # # kwargs = {**defaults, **event_attrs} # # try: # domain_event = domain_event_class(**kwargs) # except TypeError: # raise ValueError("Unable to instantiate class '{}' with data '{}'" # "".format(stored_event.class_name, event_attrs)) # # return domain_event # # @staticmethod # def _get_domain_event_class(module_name, class_name): # """Return domain class described by given topic. # # Args: # module_name: string of module_name # class_name: string of class_name # Returns: # A domain class. # # Raises: # ResolveDomainFailed: If there is no such domain class. # """ # try: # module = importlib.import_module(module_name) # except ImportError as e: # raise ResolveDomainFailed("{}#{}: {}".format(module_name, class_name, e)) # try: # domain_event_class = resolve_attr(module, class_name) # except AttributeError as e: # raise ResolveDomainFailed("{}#{}: {}".format(module_name, class_name, e)) # # if not isclass(domain_event_class): # raise ValueError("Event class is not a type: {}".format(domain_event_class)) # # if not issubclass(domain_event_class, DomainEvent): # raise ValueError("Event class is not a DomainEvent: {}".format(domain_event_class)) # # return domain_event_class # # def _json_encode(self, data): # return json.dumps(data, separators=(',', ':'), sort_keys=True, cls=self.json_encoder_cls) # # def _json_decode(self, json_str): # return json.loads(json_str, cls=ObjectJSONDecoder) . Output only the next line.
transcoder = UnifiedTranscoder(json_encoder_cls=DjangoJSONEncoder)
Given the code snippet: <|code_start|> { "name": "entity_version", "type": "string", "doc": "Aggregate revision" }, { "name": "domain_event_id", "type": "string", "doc": "ID of the last modifying event" }, { "name": "name", "type": "string", "doc": "name of the project" } ] }) @override_settings(BASE_DIR='/path/to/proj/src/') @mock.patch.object(schema, 'list_concrete_aggregates', return_value=[Project]) @mock.patch.object(schema, 'load_event_schema') def test_load_all_event_schemas(load_schema, load_aggs): schema.load_all_event_schemas() load_schema.assert_called_once_with(Project, Project.Created) @override_settings(BASE_DIR='/path/to/proj/src/') @mock.patch.object(schema, 'list_concrete_aggregates', return_value=[Project]) def test_load_all_event_schemas_missing_specs(list_aggs): <|code_end|> , generate the next line using the imports in this file: import avro.schema import djangoevents.schema as schema import json import os import pytest import shutil import tempfile from djangoevents.exceptions import EventSchemaError from djangoevents.domain import BaseAggregate from djangoevents.domain import DomainEvent from io import StringIO from django.test import override_settings from unittest import mock from .test_domain import SampleEntity from ..schema import set_event_version and context (functions, classes, or occasionally code) from other files: # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # """ # `EventSourcedEntity` with saner mutator routing & naming: # # >>> class Asset(BaseAggregate): # >>> class Created(BaseAggregate.Created): # >>> def mutate(event, klass): # >>> return klass(...) # >>> # >>> class Updated(DomainEvent): # >>> def mutate(event, instance): # >>> instance.connect = True # >>> return instance # """ # # @classmethod # def is_abstract_class(cls): # return is_abstract(cls) # # @classmethod # def mutate(cls, aggregate=None, event=None): # if aggregate: # aggregate._validate_originator(event) # # if not hasattr(event, 'mutate_event'): # msg = "{} does not provide a mutate_event() method.".format(event.__class__) # raise NotImplementedError(msg) # # aggregate = event.mutate_event(event, aggregate or cls) # aggregate._increment_version() # return aggregate # # @classmethod # def create_for_event(cls, event): # aggregate = cls( # entity_id=event.entity_id, # domain_event_id=event.domain_event_id, # entity_version=event.entity_version, # ) # return aggregate # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/tests/test_domain.py # class SampleEntity(BaseEntity): # class Created(BaseEntity.Created): # def mutate_event(self, event, klass): # return klass(entity_id=event.entity_id, # entity_version=event.entity_version, # domain_event_id=event.domain_event_id) # # class Updated(DomainEvent): # def mutate_event(self, event, entity): # entity.is_dirty = True # return entity # # class Closed(DomainEvent): # # no mutate_event # pass # # def __init__(self, is_dirty=False, **kwargs): # super().__init__(**kwargs) # self.is_dirty = is_dirty # # Path: djangoevents/schema.py # def set_event_version(aggregate_cls, event_cls, avro_dir=None): # avro_dir = avro_dir or get_avro_dir() # event_cls.version = _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir) . Output only the next line.
with pytest.raises(EventSchemaError) as e:
Based on the snippet: <|code_start|> class Project(BaseAggregate): class Created(BaseAggregate.Created): def mutate_event(self, event, klass): return klass( entity_id=event.entity_id, entity_version=event.entity_version, domain_event_id=event.domain_event_id, name=event.name, ) <|code_end|> , predict the immediate next line with the help of imports: import avro.schema import djangoevents.schema as schema import json import os import pytest import shutil import tempfile from djangoevents.exceptions import EventSchemaError from djangoevents.domain import BaseAggregate from djangoevents.domain import DomainEvent from io import StringIO from django.test import override_settings from unittest import mock from .test_domain import SampleEntity from ..schema import set_event_version and context (classes, functions, sometimes code) from other files: # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # """ # `EventSourcedEntity` with saner mutator routing & naming: # # >>> class Asset(BaseAggregate): # >>> class Created(BaseAggregate.Created): # >>> def mutate(event, klass): # >>> return klass(...) # >>> # >>> class Updated(DomainEvent): # >>> def mutate(event, instance): # >>> instance.connect = True # >>> return instance # """ # # @classmethod # def is_abstract_class(cls): # return is_abstract(cls) # # @classmethod # def mutate(cls, aggregate=None, event=None): # if aggregate: # aggregate._validate_originator(event) # # if not hasattr(event, 'mutate_event'): # msg = "{} does not provide a mutate_event() method.".format(event.__class__) # raise NotImplementedError(msg) # # aggregate = event.mutate_event(event, aggregate or cls) # aggregate._increment_version() # return aggregate # # @classmethod # def create_for_event(cls, event): # aggregate = cls( # entity_id=event.entity_id, # domain_event_id=event.domain_event_id, # entity_version=event.entity_version, # ) # return aggregate # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/tests/test_domain.py # class SampleEntity(BaseEntity): # class Created(BaseEntity.Created): # def mutate_event(self, event, klass): # return klass(entity_id=event.entity_id, # entity_version=event.entity_version, # domain_event_id=event.domain_event_id) # # class Updated(DomainEvent): # def mutate_event(self, event, entity): # entity.is_dirty = True # return entity # # class Closed(DomainEvent): # # no mutate_event # pass # # def __init__(self, is_dirty=False, **kwargs): # super().__init__(**kwargs) # self.is_dirty = is_dirty # # Path: djangoevents/schema.py # def set_event_version(aggregate_cls, event_cls, avro_dir=None): # avro_dir = avro_dir or get_avro_dir() # event_cls.version = _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir) . Output only the next line.
class Closed(DomainEvent):
Based on the snippet: <|code_start|> { "name": "name", "type": "string", "doc": "name of the project" } ] }) @override_settings(BASE_DIR='/path/to/proj/src/') @mock.patch.object(schema, 'list_concrete_aggregates', return_value=[Project]) @mock.patch.object(schema, 'load_event_schema') def test_load_all_event_schemas(load_schema, load_aggs): schema.load_all_event_schemas() load_schema.assert_called_once_with(Project, Project.Created) @override_settings(BASE_DIR='/path/to/proj/src/') @mock.patch.object(schema, 'list_concrete_aggregates', return_value=[Project]) def test_load_all_event_schemas_missing_specs(list_aggs): with pytest.raises(EventSchemaError) as e: schema.load_all_event_schemas() path = "/path/to/proj/avro/project/v1_project_created.json" msg = "No event schema found for: {cls} (expecting file at:{path}).".format(cls=Project.Created, path=path) assert msg in str(e.value) @override_settings(BASE_DIR='/path/to/proj/src/') def test_valid_event_to_schema_path(): <|code_end|> , predict the immediate next line with the help of imports: import avro.schema import djangoevents.schema as schema import json import os import pytest import shutil import tempfile from djangoevents.exceptions import EventSchemaError from djangoevents.domain import BaseAggregate from djangoevents.domain import DomainEvent from io import StringIO from django.test import override_settings from unittest import mock from .test_domain import SampleEntity from ..schema import set_event_version and context (classes, functions, sometimes code) from other files: # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # """ # `EventSourcedEntity` with saner mutator routing & naming: # # >>> class Asset(BaseAggregate): # >>> class Created(BaseAggregate.Created): # >>> def mutate(event, klass): # >>> return klass(...) # >>> # >>> class Updated(DomainEvent): # >>> def mutate(event, instance): # >>> instance.connect = True # >>> return instance # """ # # @classmethod # def is_abstract_class(cls): # return is_abstract(cls) # # @classmethod # def mutate(cls, aggregate=None, event=None): # if aggregate: # aggregate._validate_originator(event) # # if not hasattr(event, 'mutate_event'): # msg = "{} does not provide a mutate_event() method.".format(event.__class__) # raise NotImplementedError(msg) # # aggregate = event.mutate_event(event, aggregate or cls) # aggregate._increment_version() # return aggregate # # @classmethod # def create_for_event(cls, event): # aggregate = cls( # entity_id=event.entity_id, # domain_event_id=event.domain_event_id, # entity_version=event.entity_version, # ) # return aggregate # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/tests/test_domain.py # class SampleEntity(BaseEntity): # class Created(BaseEntity.Created): # def mutate_event(self, event, klass): # return klass(entity_id=event.entity_id, # entity_version=event.entity_version, # domain_event_id=event.domain_event_id) # # class Updated(DomainEvent): # def mutate_event(self, event, entity): # entity.is_dirty = True # return entity # # class Closed(DomainEvent): # # no mutate_event # pass # # def __init__(self, is_dirty=False, **kwargs): # super().__init__(**kwargs) # self.is_dirty = is_dirty # # Path: djangoevents/schema.py # def set_event_version(aggregate_cls, event_cls, avro_dir=None): # avro_dir = avro_dir or get_avro_dir() # event_cls.version = _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir) . Output only the next line.
SampleEntity.Created.version = None
Continue the code snippet: <|code_start|> with pytest.raises(EventSchemaError) as e: schema.load_all_event_schemas() path = "/path/to/proj/avro/project/v1_project_created.json" msg = "No event schema found for: {cls} (expecting file at:{path}).".format(cls=Project.Created, path=path) assert msg in str(e.value) @override_settings(BASE_DIR='/path/to/proj/src/') def test_valid_event_to_schema_path(): SampleEntity.Created.version = None avro_path = schema.event_to_schema_path(aggregate_cls=SampleEntity, event_cls=SampleEntity.Created) assert avro_path == "/path/to/proj/avro/sample_entity/v1_sample_entity_created.json" @override_settings(BASE_DIR='/path/to/proj/src/') def test_event_to_schema_path_chooses_file_with_the_highest_version(): try: # make temporary directory structure temp_dir = tempfile.mkdtemp() entity_dir = os.path.join(temp_dir, 'sample_entity') os.mkdir(entity_dir) for version in range(1, 4): # make empty schema file expected_schema_path = os.path.join(entity_dir, 'v{}_sample_entity_created.json'.format(version)) with open(expected_schema_path, 'w'): pass # refresh version <|code_end|> . Use current file imports: import avro.schema import djangoevents.schema as schema import json import os import pytest import shutil import tempfile from djangoevents.exceptions import EventSchemaError from djangoevents.domain import BaseAggregate from djangoevents.domain import DomainEvent from io import StringIO from django.test import override_settings from unittest import mock from .test_domain import SampleEntity from ..schema import set_event_version and context (classes, functions, or code) from other files: # Path: djangoevents/exceptions.py # class EventSchemaError(DjangoeventsError): # pass # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # """ # `EventSourcedEntity` with saner mutator routing & naming: # # >>> class Asset(BaseAggregate): # >>> class Created(BaseAggregate.Created): # >>> def mutate(event, klass): # >>> return klass(...) # >>> # >>> class Updated(DomainEvent): # >>> def mutate(event, instance): # >>> instance.connect = True # >>> return instance # """ # # @classmethod # def is_abstract_class(cls): # return is_abstract(cls) # # @classmethod # def mutate(cls, aggregate=None, event=None): # if aggregate: # aggregate._validate_originator(event) # # if not hasattr(event, 'mutate_event'): # msg = "{} does not provide a mutate_event() method.".format(event.__class__) # raise NotImplementedError(msg) # # aggregate = event.mutate_event(event, aggregate or cls) # aggregate._increment_version() # return aggregate # # @classmethod # def create_for_event(cls, event): # aggregate = cls( # entity_id=event.entity_id, # domain_event_id=event.domain_event_id, # entity_version=event.entity_version, # ) # return aggregate # # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/tests/test_domain.py # class SampleEntity(BaseEntity): # class Created(BaseEntity.Created): # def mutate_event(self, event, klass): # return klass(entity_id=event.entity_id, # entity_version=event.entity_version, # domain_event_id=event.domain_event_id) # # class Updated(DomainEvent): # def mutate_event(self, event, entity): # entity.is_dirty = True # return entity # # class Closed(DomainEvent): # # no mutate_event # pass # # def __init__(self, is_dirty=False, **kwargs): # super().__init__(**kwargs) # self.is_dirty = is_dirty # # Path: djangoevents/schema.py # def set_event_version(aggregate_cls, event_cls, avro_dir=None): # avro_dir = avro_dir or get_avro_dir() # event_cls.version = _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir) . Output only the next line.
set_event_version(SampleEntity, SampleEntity.Created, avro_dir=temp_dir)
Given the code snippet: <|code_start|> class SampleEntity(BaseEntity): class Created(BaseEntity.Created): def mutate_event(self, event, klass): return klass(entity_id=event.entity_id, entity_version=event.entity_version, domain_event_id=event.domain_event_id) <|code_end|> , generate the next line using the imports in this file: from ..domain import BaseEntity, DomainEvent from ..schema import get_event_version from ..schema import set_event_version from ..unifiedtranscoder import UnifiedTranscoder from django.core.serializers.json import DjangoJSONEncoder from django.test import override_settings from unittest import mock import os import pytest and context (functions, classes, or occasionally code) from other files: # Path: djangoevents/domain.py # class BaseAggregate(EventSourcedEntity): # class BaseEntity(BaseAggregate): # def is_abstract_class(cls): # def mutate(cls, aggregate=None, event=None): # def create_for_event(cls, event): # def is_abstract_class(cls): # def mutate(cls, entity=None, event=None): # # Path: djangoevents/schema.py # def get_event_version(event_cls): # return getattr(event_cls, 'version', None) or 1 # # Path: djangoevents/schema.py # def set_event_version(aggregate_cls, event_cls, avro_dir=None): # avro_dir = avro_dir or get_avro_dir() # event_cls.version = _find_highest_event_version_based_on_schemas(aggregate_cls, event_cls, avro_dir) # # Path: djangoevents/unifiedtranscoder.py # class UnifiedTranscoder(AbstractTranscoder): # def __init__(self, json_encoder_cls=None): # self.json_encoder_cls = json_encoder_cls # # encrypt not implemented # # def serialize(self, domain_event): # """ # Serializes a domain event into a stored event. # """ # assert isinstance(domain_event, DomainEvent) # # event_data = {key: value for key, value in domain_event.__dict__.items() if key not in { # 'domain_event_id', # 'entity_id', # 'entity_version', # 'metadata', # }} # # domain_event_class = type(domain_event) # event_version = get_event_version(domain_event_class) # # return UnifiedStoredEvent( # event_id=domain_event.domain_event_id, # event_type=get_event_type(domain_event), # event_version=event_version, # event_data=self._json_encode(event_data), # aggregate_id=domain_event.entity_id, # aggregate_type=get_aggregate_type(domain_event), # aggregate_version=domain_event.entity_version, # create_date=datetime.fromtimestamp(timestamp_from_uuid(domain_event.domain_event_id)), # metadata=self._json_encode(getattr(domain_event, 'metadata', None)), # module_name=domain_event_class.__module__, # class_name=domain_event_class.__qualname__, # # have to have stored_entity_id because of the lib # stored_entity_id=make_stored_entity_id(id_prefix_from_event(domain_event), domain_event.entity_id), # ) # # def deserialize(self, stored_event): # """ # Recreates original domain event from stored event topic and event attrs. # """ # assert isinstance(stored_event, UnifiedStoredEvent) # # Get the domain event class from the topic. # domain_event_class = self._get_domain_event_class(stored_event.module_name, stored_event.class_name) # # # Deserialize event attributes from JSON # event_attrs = self._json_decode(stored_event.event_data) # # # Reinstantiate and return the domain event object. # defaults = { # 'entity_id': stored_event.aggregate_id, # 'entity_version': stored_event.aggregate_version, # 'domain_event_id': stored_event.event_id, # } # # if adds_schema_version_to_event_data(): # defaults['schema_version'] = None # # kwargs = {**defaults, **event_attrs} # # try: # domain_event = domain_event_class(**kwargs) # except TypeError: # raise ValueError("Unable to instantiate class '{}' with data '{}'" # "".format(stored_event.class_name, event_attrs)) # # return domain_event # # @staticmethod # def _get_domain_event_class(module_name, class_name): # """Return domain class described by given topic. # # Args: # module_name: string of module_name # class_name: string of class_name # Returns: # A domain class. # # Raises: # ResolveDomainFailed: If there is no such domain class. # """ # try: # module = importlib.import_module(module_name) # except ImportError as e: # raise ResolveDomainFailed("{}#{}: {}".format(module_name, class_name, e)) # try: # domain_event_class = resolve_attr(module, class_name) # except AttributeError as e: # raise ResolveDomainFailed("{}#{}: {}".format(module_name, class_name, e)) # # if not isclass(domain_event_class): # raise ValueError("Event class is not a type: {}".format(domain_event_class)) # # if not issubclass(domain_event_class, DomainEvent): # raise ValueError("Event class is not a DomainEvent: {}".format(domain_event_class)) # # return domain_event_class # # def _json_encode(self, data): # return json.dumps(data, separators=(',', ':'), sort_keys=True, cls=self.json_encoder_cls) # # def _json_decode(self, json_str): # return json.loads(json_str, cls=ObjectJSONDecoder) . Output only the next line.
class Updated(DomainEvent):
Given the code snippet: <|code_start|> def test_get_entity_or_404_item_exists(): """ ES store provides a dictionary style item verification. """ repo = {'id': 'entity'} <|code_end|> , generate the next line using the imports in this file: from ..shortcuts import get_entity_or_404, get_aggregate_or_404 from django.http import Http404 import pytest and context (functions, classes, or occasionally code) from other files: # Path: djangoevents/shortcuts.py # def get_entity_or_404(repo, entity_id): # warnings.warn("`get_entity_or_404` is depreciated. Please switch to: `get_aggregate_or_404`", DeprecationWarning) # return get_aggregate_or_404(repo, entity_id) # # def get_aggregate_or_404(repo, aggregate_id): # """ # Uses `repo` to return most recent state of the aggregate. Raises a Http404 exception if the # `aggregate_id` does not exist. # # `repo` has to be a EventSourcedRepository object. # """ # if aggregate_id not in repo: # raise Http404 # return repo[aggregate_id] . Output only the next line.
assert get_entity_or_404(repo, 'id') == 'entity'
Predict the next line after this snippet: <|code_start|> def test_get_entity_or_404_item_exists(): """ ES store provides a dictionary style item verification. """ repo = {'id': 'entity'} assert get_entity_or_404(repo, 'id') == 'entity' def test_get_entity_or_404_item_does_not_exists(): repo = {} with pytest.raises(Http404) as exc_info: get_entity_or_404(repo, 'id') def test_get_aggregate_or_404_item_exists(): repo = {'id': 'aggregate'} <|code_end|> using the current file's imports: from ..shortcuts import get_entity_or_404, get_aggregate_or_404 from django.http import Http404 import pytest and any relevant context from other files: # Path: djangoevents/shortcuts.py # def get_entity_or_404(repo, entity_id): # warnings.warn("`get_entity_or_404` is depreciated. Please switch to: `get_aggregate_or_404`", DeprecationWarning) # return get_aggregate_or_404(repo, entity_id) # # def get_aggregate_or_404(repo, aggregate_id): # """ # Uses `repo` to return most recent state of the aggregate. Raises a Http404 exception if the # `aggregate_id` does not exist. # # `repo` has to be a EventSourcedRepository object. # """ # if aggregate_id not in repo: # raise Http404 # return repo[aggregate_id] . Output only the next line.
assert get_aggregate_or_404(repo, 'id') == 'aggregate'