Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> def flow(parameters: dict, stats: dict): out_path = parameters.pop('out-path', '.') stats.setdefault(STATS_DPP_KEY, {})[STATS_OUT_DP_URL_KEY] = os.path.join(out_path, 'datapackage.json') return Flow( dump_to_path( out_path, **parameters <|code_end|> , generate the next line using the imports in this file: import os from dataflows import Flow, dump_to_path from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' . Output only the next line.
)
Given snippet: <|code_start|> def flow(parameters: dict, stats: dict): out_path = parameters.pop('out-path', '.') stats.setdefault(STATS_DPP_KEY, {})[STATS_OUT_DP_URL_KEY] = os.path.join(out_path, 'datapackage.json') return Flow( dump_to_path( out_path, **parameters <|code_end|> , continue by predicting the next line. Consider current file imports: import os from dataflows import Flow, dump_to_path from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY and context: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' which might include code, classes, or functions. Output only the next line.
)
Here is a snippet: <|code_start|> def flow(parameters: dict, stats: dict): out_path = parameters.pop('out-path', '.') stats.setdefault(STATS_DPP_KEY, {})[STATS_OUT_DP_URL_KEY] = os.path.join(out_path, 'datapackage.json') return Flow( dump_to_path( out_path, <|code_end|> . Write the next line using the current file imports: import os from dataflows import Flow, dump_to_path from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' , which may include functions, classes, or code. Output only the next line.
**parameters
Given the following code snippet before the placeholder: <|code_start|> parameters, datapackage, resources, stats = tuple(ingest()) + ({},) if parameters.get('test-package'): assert DPP_DOCKER_TEST <|code_end|> , predict the next line using imports from the current file: from datapackage_pipelines.wrapper import ingest, spew from datapackage_pipelines.utilities.resources import PROP_STREAMING from dpp_docker_test import DPP_DOCKER_TEST import datetime and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' . Output only the next line.
datapackage['resources'] = [{'name': 'test', 'path': 'test.csv',
Next line prediction: <|code_start|> def flow(parameters: dict): out_file = parameters.pop('out-file') return Flow( dump_to_zip( out_file, **parameters ) <|code_end|> . Use current file imports: (from dataflows import Flow, dump_to_zip from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow) and context including class names, function names, or small code snippets from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) . Output only the next line.
)
Predict the next line for this snippet: <|code_start|> def flow(parameters: dict): out_file = parameters.pop('out-file') return Flow( dump_to_zip( out_file, **parameters <|code_end|> with the help of current file imports: from dataflows import Flow, dump_to_zip from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) , which may contain function names, class names, or code. Output only the next line.
)
Given snippet: <|code_start|> pipelines = list(filter(lambda x: len(x['id']) == 1, lvl)) children_ = list(filter(lambda x: len(x['id']) > 1, lvl)) groups_ = {} for child in children_: child_key = child['id'].pop(0) groups_.setdefault(child_key, []).append(child) children_ = dict( (k, group(v)) for k, v in groups_.items() ) for p in pipelines: p['id'] = p['id'][0] return { 'pipelines': pipelines, 'children': children_ } def flatten(children_): for k, v in children_.items(): v['children'] = flatten(v['children']) child_keys = list(v['children'].keys()) if len(child_keys) == 1 and len(v['pipelines']) == 0: child_key = child_keys[0] children_['/'.join([k, child_key])] = v['children'][child_key] del children_[k] return children_ statuses = [ { 'id': st['id'].split('/'), <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import os import logging import slugify import yaml import mistune import requests from io import BytesIO from functools import wraps from copy import deepcopy from collections import Counter from flask import \ Blueprint, Flask, render_template, abort, send_file, make_response from flask_cors import CORS from flask_jsonpify import jsonify from flask_basicauth import BasicAuth from datapackage_pipelines.status import status_mgr from datapackage_pipelines.utilities.stat_utils import user_facing_stats and context: # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # def user_facing_stats(stats): # if stats is not None and isinstance(stats, dict): # return dict((k, v) for k, v in stats.items() if k != STATS_DPP_KEY) # return None which might include code, classes, or functions. Output only the next line.
'title': st.get('title'),
Continue the code snippet: <|code_start|> def group(lvl): pipelines = list(filter(lambda x: len(x['id']) == 1, lvl)) children_ = list(filter(lambda x: len(x['id']) > 1, lvl)) groups_ = {} for child in children_: child_key = child['id'].pop(0) groups_.setdefault(child_key, []).append(child) children_ = dict( (k, group(v)) for k, v in groups_.items() ) for p in pipelines: p['id'] = p['id'][0] return { 'pipelines': pipelines, 'children': children_ } def flatten(children_): for k, v in children_.items(): v['children'] = flatten(v['children']) child_keys = list(v['children'].keys()) if len(child_keys) == 1 and len(v['pipelines']) == 0: child_key = child_keys[0] children_['/'.join([k, child_key])] = v['children'][child_key] del children_[k] return children_ statuses = [ { <|code_end|> . Use current file imports: import datetime import os import logging import slugify import yaml import mistune import requests from io import BytesIO from functools import wraps from copy import deepcopy from collections import Counter from flask import \ Blueprint, Flask, render_template, abort, send_file, make_response from flask_cors import CORS from flask_jsonpify import jsonify from flask_basicauth import BasicAuth from datapackage_pipelines.status import status_mgr from datapackage_pipelines.utilities.stat_utils import user_facing_stats and context (classes, functions, or code) from other files: # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # def user_facing_stats(stats): # if stats is not None and isinstance(stats, dict): # return dict((k, v) for k, v in stats.items() if k != STATS_DPP_KEY) # return None . Output only the next line.
'id': st['id'].split('/'),
Here is a snippet: <|code_start|> } DEFAULT_SERIALIZER = identity NULL_VALUE = None PYTHON_DIALECT = { 'date': { 'format': DATE_P_FORMAT }, 'time': { 'format': TIME_P_FORMAT }, 'datetime': { 'format': DATETIME_P_FORMAT }, } def prepare_resource(self, resource): resource['encoding'] = 'utf-8' basename, _ = os.path.splitext(get_path(resource)) resource['path'] = basename + '.json' resource['format'] = 'json' super(JSONFormat, self).prepare_resource(resource) def initialize_file(self, file, headers): writer = file writer.write('[') writer.__first = True return writer def write_transformed_row(self, writer, transformed_row, fields): <|code_end|> . Write the next line using the current file imports: import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path and context from other files: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None , which may include functions, classes, or code. Output only the next line.
if not writer.__first:
Next line prediction: <|code_start|> class JSONFormat(FileFormat): SERIALIZERS = { 'datetime': lambda d: d.strftime(DATETIME_F_FORMAT), 'date': lambda d: d.strftime(DATE_F_FORMAT), 'time': lambda d: d.strftime(TIME_F_FORMAT), 'number': float, 'duration': lambda d: isodate.duration_isoformat(d), 'geopoint': lambda d: list(map(float, d)), 'yearmonth': lambda d: '{:04d}-{:02d}'.format(*d), } DEFAULT_SERIALIZER = identity NULL_VALUE = None PYTHON_DIALECT = { 'date': { 'format': DATE_P_FORMAT }, 'time': { 'format': TIME_P_FORMAT }, 'datetime': { 'format': DATETIME_P_FORMAT }, } def prepare_resource(self, resource): resource['encoding'] = 'utf-8' basename, _ = os.path.splitext(get_path(resource)) <|code_end|> . Use current file imports: (import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path) and context including class names, function names, or small code snippets from other files: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None . Output only the next line.
resource['path'] = basename + '.json'
Given snippet: <|code_start|> 'geopoint': lambda d: '{}, {}'.format(*d), 'geojson': json.dumps, 'year': lambda d: '{:04d}'.format(d), 'yearmonth': lambda d: '{:04d}-{:02d}'.format(*d), } DEFAULT_SERIALIZER = str NULL_VALUE = '' PYTHON_DIALECT = { 'number': { 'decimalChar': '.', 'groupChar': '' }, 'date': { 'format': DATE_P_FORMAT }, 'time': { 'format': TIME_P_FORMAT }, 'datetime': { 'format': DATETIME_P_FORMAT }, } def prepare_resource(self, resource): resource['encoding'] = 'utf-8' basename, _ = os.path.splitext(get_path(resource)) resource['path'] = basename + '.csv' resource['format'] = 'csv' resource['dialect'] = dict( <|code_end|> , continue by predicting the next line. Consider current file imports: import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path and context: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None which might include code, classes, or functions. Output only the next line.
lineTerminator='\r\n',
Next line prediction: <|code_start|> 'groupChar': '' }, 'date': { 'format': DATE_P_FORMAT }, 'time': { 'format': TIME_P_FORMAT }, 'datetime': { 'format': DATETIME_P_FORMAT }, } def prepare_resource(self, resource): resource['encoding'] = 'utf-8' basename, _ = os.path.splitext(get_path(resource)) resource['path'] = basename + '.csv' resource['format'] = 'csv' resource['dialect'] = dict( lineTerminator='\r\n', delimiter=',', doubleQuote=True, quoteChar='"', skipInitialSpace=False ) super(CSVFormat, self).prepare_resource(resource) def initialize_file(self, file, headers): csv_writer = csv.DictWriter(file, headers) csv_writer.writeheader() <|code_end|> . Use current file imports: (import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path) and context including class names, function names, or small code snippets from other files: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None . Output only the next line.
return csv_writer
Here is a snippet: <|code_start|> def identity(x): return x def json_dumps(x): return json.dumps(x, ensure_ascii=False) class FileFormat(): def prepare_resource(self, resource): for field in resource.get('schema', {}).get('fields', []): field.update(self.PYTHON_DIALECT.get(field['type'], {})) def __transform_row(self, row, fields): try: return dict((k, self.__transform_value(v, fields[k]['type'])) for k, v in row.items()) except Exception: logging.exception('Failed to transform row %r', row) raise @classmethod def __transform_value(cls, value, field_type): if value is None: return cls.NULL_VALUE <|code_end|> . Write the next line using the current file imports: import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path and context from other files: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None , which may include functions, classes, or code. Output only the next line.
serializer = cls.SERIALIZERS.get(field_type, cls.DEFAULT_SERIALIZER)
Based on the snippet: <|code_start|> 'time': lambda d: d.strftime(TIME_F_FORMAT), 'duration': lambda d: isodate.duration_isoformat(d), 'geopoint': lambda d: '{}, {}'.format(*d), 'geojson': json.dumps, 'year': lambda d: '{:04d}'.format(d), 'yearmonth': lambda d: '{:04d}-{:02d}'.format(*d), } DEFAULT_SERIALIZER = str NULL_VALUE = '' PYTHON_DIALECT = { 'number': { 'decimalChar': '.', 'groupChar': '' }, 'date': { 'format': DATE_P_FORMAT }, 'time': { 'format': TIME_P_FORMAT }, 'datetime': { 'format': DATETIME_P_FORMAT }, } def prepare_resource(self, resource): resource['encoding'] = 'utf-8' basename, _ = os.path.splitext(get_path(resource)) resource['path'] = basename + '.csv' <|code_end|> , predict the immediate next line with the help of imports: import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path and context (classes, functions, sometimes code) from other files: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None . Output only the next line.
resource['format'] = 'csv'
Here is a snippet: <|code_start|> def initialize_file(self, file, headers): csv_writer = csv.DictWriter(file, headers) csv_writer.writeheader() return csv_writer def write_transformed_row(self, writer, transformed_row, fields): writer.writerow(transformed_row) def finalize_file(self, writer): pass class JSONFormat(FileFormat): SERIALIZERS = { 'datetime': lambda d: d.strftime(DATETIME_F_FORMAT), 'date': lambda d: d.strftime(DATE_F_FORMAT), 'time': lambda d: d.strftime(TIME_F_FORMAT), 'number': float, 'duration': lambda d: isodate.duration_isoformat(d), 'geopoint': lambda d: list(map(float, d)), 'yearmonth': lambda d: '{:04d}-{:02d}'.format(*d), } DEFAULT_SERIALIZER = identity NULL_VALUE = None PYTHON_DIALECT = { 'date': { 'format': DATE_P_FORMAT <|code_end|> . Write the next line using the current file imports: import csv import json import os import isodate import logging from datapackage_pipelines.utilities.extended_json import ( DATETIME_F_FORMAT, DATE_F_FORMAT, TIME_F_FORMAT, DATETIME_P_FORMAT, DATE_P_FORMAT, TIME_P_FORMAT, ) from datapackage_pipelines.utilities.resources import get_path and context from other files: # Path: datapackage_pipelines/utilities/extended_json.py # DATE_F_FORMAT = '%Y-%m-%d' # DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' # DATE_F_FORMAT = '%04Y-%m-%d' # DATETIME_F_FORMAT = '%04Y-%m-%d %H:%M:%S' # DATE_FORMAT = DATE_F_FORMAT # DATETIME_FORMAT = DATETIME_F_FORMAT # TIME_FORMAT = '%H:%M:%S' # DATE_P_FORMAT = '%Y-%m-%d' # DATETIME_P_FORMAT = '%Y-%m-%d %H:%M:%S' # TIME_P_FORMAT = TIME_F_FORMAT = TIME_FORMAT # class LazyJsonLine(LazyDict): # class CommonJSONDecoder(_json.JSONDecoder): # class CommonJSONEncoder(_json.JSONEncoder): # class json(object): # def __init__(self, args, kwargs): # def _evaluate(self): # def __str__(self): # def __repr__(self): # def object_hook(cls, obj): # def __init__(self, **kwargs): # def default(self, obj): # def _dumpl(*args, **kwargs): # def _loadl(*args, **kwargs): # def _dumps(*args, **kwargs): # def _loads(*args, **kwargs): # def _dump(*args, **kwargs): # def _load(*args, **kwargs): # # Path: datapackage_pipelines/utilities/resources.py # def get_path(descriptor): # path = descriptor.get('path') # if isinstance(path, str): # return path # if isinstance(path, list): # if len(path) > 0: # return path.pop(0) # else: # return None # assert path is None, '%r' % path # return None , which may include functions, classes, or code. Output only the next line.
},
Given the following code snippet before the placeholder: <|code_start|> params, datapackage, res_iter = ingest() key = params['key'] def process_resources(_res_iter): for res in _res_iter: def process_res(_res): for line in _res: <|code_end|> , predict the next line using imports from the current file: from datapackage_pipelines.wrapper import ingest, spew and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) . Output only the next line.
if key in line:
Given the code snippet: <|code_start|> params, datapackage, res_iter = ingest() key = params['key'] def process_resources(_res_iter): for res in _res_iter: def process_res(_res): for line in _res: if key in line: line[key] = line[key].title() <|code_end|> , generate the next line using the imports in this file: from datapackage_pipelines.wrapper import ingest, spew and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) . Output only the next line.
yield line
Based on the snippet: <|code_start|> class XLSXFormat(CSVFormat): def prepare_resource(self, resource): super(XLSXFormat, self).prepare_resource(resource) basename, _ = os.path.splitext(get_path(resource)) resource['path'] = basename + '.xlsx' resource['format'] = 'xlsx' def initialize_file(self, file, headers): self.file = file self.headers = headers <|code_end|> , predict the immediate next line with the help of imports: from datapackage_pipelines.lib.dump.file_formats import CSVFormat, get_path import os import openpyxl and context (classes, functions, sometimes code) from other files: # Path: datapackage_pipelines/lib/dump/file_formats.py # def identity(x): # def json_dumps(x): # def prepare_resource(self, resource): # def __transform_row(self, row, fields): # def __transform_value(cls, value, field_type): # def write_row(self, writer, row, fields): # def prepare_resource(self, resource): # def initialize_file(self, file, headers): # def write_transformed_row(self, writer, transformed_row, fields): # def finalize_file(self, writer): # def prepare_resource(self, resource): # def initialize_file(self, file, headers): # def write_transformed_row(self, writer, transformed_row, fields): # def finalize_file(self, writer): # class FileFormat(): # class CSVFormat(FileFormat): # class JSONFormat(FileFormat): # SERIALIZERS = { # 'array': json_dumps, # 'object': json_dumps, # 'datetime': lambda d: d.strftime(DATETIME_F_FORMAT), # 'date': lambda d: d.strftime(DATE_F_FORMAT), # 'time': lambda d: d.strftime(TIME_F_FORMAT), # 'duration': lambda d: isodate.duration_isoformat(d), # 'geopoint': lambda d: '{}, {}'.format(*d), # 'geojson': json.dumps, # 'year': lambda d: '{:04d}'.format(d), # 'yearmonth': lambda d: '{:04d}-{:02d}'.format(*d), # } # DEFAULT_SERIALIZER = str # NULL_VALUE = '' # PYTHON_DIALECT = { # 'number': { # 'decimalChar': '.', # 'groupChar': '' # }, # 'date': { # 'format': DATE_P_FORMAT # }, # 'time': { # 'format': TIME_P_FORMAT # }, # 'datetime': { # 'format': DATETIME_P_FORMAT # }, # } # SERIALIZERS = { # 'datetime': lambda d: d.strftime(DATETIME_F_FORMAT), # 'date': lambda d: d.strftime(DATE_F_FORMAT), # 'time': lambda d: d.strftime(TIME_F_FORMAT), # 'number': float, # 'duration': lambda d: isodate.duration_isoformat(d), # 'geopoint': lambda d: list(map(float, d)), # 'yearmonth': lambda d: '{:04d}-{:02d}'.format(*d), # } # DEFAULT_SERIALIZER = identity # NULL_VALUE = None # PYTHON_DIALECT = { # 'date': { # 'format': DATE_P_FORMAT # }, # 'time': { # 'format': TIME_P_FORMAT # }, # 'datetime': { # 'format': DATETIME_P_FORMAT # }, # } . Output only the next line.
wb = openpyxl.Workbook()
Predict the next line after this snippet: <|code_start|> def flow(parameters): return Flow( load_lazy_json(parameters.get('source')), <|code_end|> using the current file's imports: from dataflows import Flow, duplicate from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and any relevant context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
duplicate(
Using the snippet: <|code_start|> def flow(parameters): return Flow( load_lazy_json(parameters.get('source')), duplicate( parameters.get('source'), parameters.get('target-name'), parameters.get('target-path'), parameters.get('batch_size', 1000), parameters.get('duplicate_to_end', False) ) ) <|code_end|> , determine the next line of code. You have imports: from dataflows import Flow, duplicate from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and context (class names, function names, or code) available: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
if __name__ == '__main__':
Given the following code snippet before the placeholder: <|code_start|> params, dp, res_iter = ingest() big_string = 'z'*64*1024 logging.info('Look at me %s', big_string) dp['name'] = 'a' dp['resources'].append({ 'name': 'aa%f' % os.getpid(), 'path': 'data/bla.csv', 'schema': { 'fields': [ <|code_end|> , predict the next line using imports from the current file: import logging import itertools import os from datapackage_pipelines.wrapper import ingest, spew from datapackage_pipelines.utilities.resources import PROP_STREAMING and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' . Output only the next line.
{'name': 'a', 'type': 'string'}
Given the following code snippet before the placeholder: <|code_start|> params, dp, res_iter = ingest() big_string = 'z'*64*1024 logging.info('Look at me %s', big_string) dp['name'] = 'a' <|code_end|> , predict the next line using imports from the current file: import logging import itertools import os from datapackage_pipelines.wrapper import ingest, spew from datapackage_pipelines.utilities.resources import PROP_STREAMING and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' . Output only the next line.
dp['resources'].append({
Continue the code snippet: <|code_start|> params, dp, res_iter = ingest() big_string = 'z'*64*1024 logging.info('Look at me %s', big_string) dp['name'] = 'a' dp['resources'].append({ 'name': 'aa%f' % os.getpid(), 'path': 'data/bla.csv', 'schema': { 'fields': [ {'name': 'a', 'type': 'string'} ] }, 'very-large-prop': '*' * 100 * 1024, PROP_STREAMING: True <|code_end|> . Use current file imports: import logging import itertools import os from datapackage_pipelines.wrapper import ingest, spew from datapackage_pipelines.utilities.resources import PROP_STREAMING and context (classes, functions, or code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' . Output only the next line.
})
Predict the next line after this snippet: <|code_start|> spec, resource_index, parameters, stats) if row is not None: yield row def generic_process_resources(resource_iterator, parameters, stats, process_row): for resource_index, resource in enumerate(resource_iterator): rows = resource spec = resource.spec yield generic_process_resource(rows, spec, resource_index, parameters, stats, process_row) def process(modify_datapackage=None, process_row=None, debug=False): with ingest(debug=debug) as ctx: if modify_datapackage is not None: ctx.datapackage = modify_datapackage(ctx.datapackage, ctx.parameters, ctx.stats) if process_row is not None: ctx.resource_iterator = \ generic_process_resources(ctx.resource_iterator, <|code_end|> using the current file's imports: import gzip import sys import os import logging from contextlib import ExitStack, redirect_stderr, redirect_stdout from tableschema.exceptions import CastError from ..utilities.extended_json import json from .input_processor import process_input from ..utilities.resources import streaming and any relevant context from other files: # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/wrapper/input_processor.py # def process_input(infile, validate=False, debug=False): # dependency_dp = read_json(infile, True) # dp = read_json(infile) # resources = dp.get('resources', []) # original_resources = copy.deepcopy(resources) # # if len(dp.get('resources', [])) == 0: # # Currently datapackages with no resources are disallowed in the schema. # # Since this might happen in the early stages of a pipeline, # # we're adding this hack to avoid validation errors # dp_to_validate = copy.deepcopy(dp) # dp_to_validate['resources'] = [{ # 'name': '__placeholder__', # 'path': PATH_PLACEHOLDER # }] # else: # dp_to_validate = dp # try: # datapackage.validate(dp_to_validate) # except ValidationError as e: # logging.info('FAILED TO VALIDATE %r', dp_to_validate) # for e in e.errors: # try: # logging.error("Data Package validation error: %s at dp%s", # e.message, # "[%s]" % "][".join(repr(index) for index in e.path)) # except AttributeError: # logging.error("Data Package validation error: %s", e) # raise # # infile.readline().strip() # # def resources_iterator(_resources, _original_resources): # # we pass a resource instance that may be changed by the processing # # code, so we must keep a copy of the original resource (used to # # validate incoming data) # ret = [] # for resource, orig_resource in zip(_resources, _original_resources): # if not streaming(resource): # continue # # res_iter = ResourceIterator(infile, # resource, orig_resource, # validate, debug) # ret.append(res_iter) # return iter(ret) # # return dp, resources_iterator(resources, original_resources), dependency_dp # # Path: datapackage_pipelines/utilities/resources.py # def streaming(descriptor): # return descriptor.get(PROP_STREAMING) . Output only the next line.
ctx.parameters,
Based on the snippet: <|code_start|> row_count += 1 except CastError as e: for err in e.errors: logging.error('Failed to cast row: %s', err) raise if num_resources != expected_resources: logging.error('Expected to see %d resource(s) but spewed %d', expected_resources, num_resources) assert num_resources == expected_resources aggregated_stats = {} if not first: stats_line = sys.stdin.readline().strip() if len(stats_line) > 0: try: aggregated_stats = json.loads(stats_line) assert aggregated_stats is None or \ isinstance(aggregated_stats, dict) except json.JSONDecodeError: logging.error('Failed to parse stats: %r', stats_line) if stats is not None: aggregated_stats.update(stats) stats_json = json.dumps(aggregated_stats, sort_keys=True, ensure_ascii=True) for f in files: f.write('\n'+stats_json) except BrokenPipeError: logging.error('Output pipe disappeared!') <|code_end|> , predict the immediate next line with the help of imports: import gzip import sys import os import logging from contextlib import ExitStack, redirect_stderr, redirect_stdout from tableschema.exceptions import CastError from ..utilities.extended_json import json from .input_processor import process_input from ..utilities.resources import streaming and context (classes, functions, sometimes code) from other files: # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/wrapper/input_processor.py # def process_input(infile, validate=False, debug=False): # dependency_dp = read_json(infile, True) # dp = read_json(infile) # resources = dp.get('resources', []) # original_resources = copy.deepcopy(resources) # # if len(dp.get('resources', [])) == 0: # # Currently datapackages with no resources are disallowed in the schema. # # Since this might happen in the early stages of a pipeline, # # we're adding this hack to avoid validation errors # dp_to_validate = copy.deepcopy(dp) # dp_to_validate['resources'] = [{ # 'name': '__placeholder__', # 'path': PATH_PLACEHOLDER # }] # else: # dp_to_validate = dp # try: # datapackage.validate(dp_to_validate) # except ValidationError as e: # logging.info('FAILED TO VALIDATE %r', dp_to_validate) # for e in e.errors: # try: # logging.error("Data Package validation error: %s at dp%s", # e.message, # "[%s]" % "][".join(repr(index) for index in e.path)) # except AttributeError: # logging.error("Data Package validation error: %s", e) # raise # # infile.readline().strip() # # def resources_iterator(_resources, _original_resources): # # we pass a resource instance that may be changed by the processing # # code, so we must keep a copy of the original resource (used to # # validate incoming data) # ret = [] # for resource, orig_resource in zip(_resources, _original_resources): # if not streaming(resource): # continue # # res_iter = ResourceIterator(infile, # resource, orig_resource, # validate, debug) # ret.append(res_iter) # return iter(ret) # # return dp, resources_iterator(resources, original_resources), dependency_dp # # Path: datapackage_pipelines/utilities/resources.py # def streaming(descriptor): # return descriptor.get(PROP_STREAMING) . Output only the next line.
sys.stderr.flush()
Given the code snippet: <|code_start|> # ## LOW LEVEL INTERFACE def _ingest(debug=False): global cache global first params = None validate = False if len(sys.argv) > 4: first = sys.argv[1] == '0' params = json.loads(sys.argv[2]) validate = sys.argv[3] == 'True' cache = sys.argv[4] datapackage, resource_iterator, dependency_dp = process_input(sys.stdin, validate, debug) dependency_datapackage_urls.update(dependency_dp) return params, datapackage, resource_iterator def spew(dp, resources_iterator, stats=None, finalizer=None): files = [stdout] cache_filename = '' if len(cache) > 0: if not os.path.exists('.cache'): os.mkdir('.cache') cache_filename = os.path.join('.cache', cache) files.append(gzip.open(cache_filename+'.ongoing', 'wt')) <|code_end|> , generate the next line using the imports in this file: import gzip import sys import os import logging from contextlib import ExitStack, redirect_stderr, redirect_stdout from tableschema.exceptions import CastError from ..utilities.extended_json import json from .input_processor import process_input from ..utilities.resources import streaming and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/wrapper/input_processor.py # def process_input(infile, validate=False, debug=False): # dependency_dp = read_json(infile, True) # dp = read_json(infile) # resources = dp.get('resources', []) # original_resources = copy.deepcopy(resources) # # if len(dp.get('resources', [])) == 0: # # Currently datapackages with no resources are disallowed in the schema. # # Since this might happen in the early stages of a pipeline, # # we're adding this hack to avoid validation errors # dp_to_validate = copy.deepcopy(dp) # dp_to_validate['resources'] = [{ # 'name': '__placeholder__', # 'path': PATH_PLACEHOLDER # }] # else: # dp_to_validate = dp # try: # datapackage.validate(dp_to_validate) # except ValidationError as e: # logging.info('FAILED TO VALIDATE %r', dp_to_validate) # for e in e.errors: # try: # logging.error("Data Package validation error: %s at dp%s", # e.message, # "[%s]" % "][".join(repr(index) for index in e.path)) # except AttributeError: # logging.error("Data Package validation error: %s", e) # raise # # infile.readline().strip() # # def resources_iterator(_resources, _original_resources): # # we pass a resource instance that may be changed by the processing # # code, so we must keep a copy of the original resource (used to # # validate incoming data) # ret = [] # for resource, orig_resource in zip(_resources, _original_resources): # if not streaming(resource): # continue # # res_iter = ResourceIterator(infile, # resource, orig_resource, # validate, debug) # ret.append(res_iter) # return iter(ret) # # return dp, resources_iterator(resources, original_resources), dependency_dp # # Path: datapackage_pipelines/utilities/resources.py # def streaming(descriptor): # return descriptor.get(PROP_STREAMING) . Output only the next line.
expected_resources = \
Given the following code snippet before the placeholder: <|code_start|> cache_hash): self.pipeline_details = pipeline_details self.source_spec = source_spec self.validation_errors = validation_errors self.cache_hash = cache_hash def __load(self): data = self.backend.get_status('PipelineStatus:' + self.pipeline_id) if data is None: data = {} self.pipeline_details = data.get('pipeline_details', {}) self.source_spec = data.get('source_spec', {}) self.validation_errors = data.get('validation_errors', []) self.cache_hash = data.get('cache_hash', '') self._execution_ids = data.get('executions', []) self._executions = None self._last_execution = None def __iter__(self): yield 'pipeline_details', self.pipeline_details, yield 'source_spec', self.source_spec, yield 'validation_errors', self.validation_errors yield 'cache_hash', self.cache_hash yield 'executions', [ex.execution_id for ex in self.executions] def __save(self): # logging.debug('SAVING PipelineStatus %s -> %r' % (self.pipeline_id, self.executions)) self.backend.register_pipeline_id(self.pipeline_id) self.backend.set_status('PipelineStatus:' + self.pipeline_id, dict(self)) <|code_end|> , predict the next line using imports from the current file: from typing import Optional from .hook_sender import hook_sender from .pipeline_execution import PipelineExecution import logging and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/status/hook_sender.py # def _send(hook, payload): # def send(self, hook, payload, blocking=False): # class HookSender(): # # Path: datapackage_pipelines/status/pipeline_execution.py # class PipelineExecution(object): # # def __init__(self, backend, pipeline_id, pipeline_details, cache_hash, trigger, execution_id, # log='', queue_time=None, start_time=None, finish_time=None, success=None, # stats=None, error_log=None, # save=True): # self.backend = backend # self.pipeline_id = pipeline_id # self.pipeline_details = pipeline_details # self.cache_hash = cache_hash # self.trigger = trigger # self.execution_id = execution_id # self.log = log # self.queue_time = queue_time # self.start_time = start_time # self.finish_time = finish_time # self.success = success # self.stats = stats or {} # self.error_log = error_log or [] # if save: # self.__save() # # @staticmethod # def from_execution_id(backend, execution_id): # data = backend.get_status('PipelineExecution:' + execution_id) # return PipelineExecution( # backend, # data['pipeline_id'], # data['pipeline_details'], # data['cache_hash'], # data['trigger'], # data['execution_id'], # log=data['log'], # queue_time=data['queue_time'], # start_time=data['start_time'], # finish_time=data['finish_time'], # success=data['success'], # stats=data['stats'], # error_log=data['error_log'], # save=False # ) # # def __iter__(self): # yield 'pipeline_id', self.pipeline_id, # yield 'pipeline_details', self.pipeline_details, # yield 'cache_hash', self.cache_hash # yield 'trigger', self.trigger # yield 'execution_id', self.execution_id # yield 'log', self.log # yield 'queue_time', self.queue_time # yield 'start_time', self.start_time # yield 'finish_time', self.finish_time # yield 'success', self.success # yield 'stats', self.stats # yield 'error_log', self.error_log # # def __save(self): # # logging.debug('SAVING PipelineExecution %s/%s -> %r' % (self.pipeline_id, self.execution_id, dict(self))) # self.backend.set_status('PipelineExecution:' + self.execution_id, dict(self)) # # def queue_execution(self, trigger): # if self.queue_time is not None: # return False # self.queue_time = time.time() # self.trigger = trigger # self.__save() # return True # # def start_execution(self): # if self.queue_time is None or self.start_time is not None: # return False # self.start_time = time.time() # self.__save() # return True # # def finish_execution(self, success, stats, error_log): # if self.queue_time is None or self.start_time is None: # return False # self.finish_time = time.time() # self.success = success # self.stats = stats # self.error_log = error_log # self.__save() # return True # # def update_execution(self, log): # if self.queue_time is None or self.start_time is None or self.finish_time is not None: # return False # self.log = '\n'.join(log) # self.__save() # return True # # def invalidate(self): # now = time.time() # self.queue_time = self.queue_time or now # self.start_time = self.start_time or now # self.finish_time = self.finish_time or now # self.__save() # return True # # def delete(self): # self.backend.del_status(self.execution_id) # # def is_stale(self): # long_ago = time.time() - 86400 # a day ago # if self.start_time is not None and self.start_time < long_ago: # return True # if self.queue_time is not None and self.queue_time < long_ago: # return True . Output only the next line.
def save(self):
Predict the next line for this snippet: <|code_start|> def __iter__(self): yield 'pipeline_details', self.pipeline_details, yield 'source_spec', self.source_spec, yield 'validation_errors', self.validation_errors yield 'cache_hash', self.cache_hash yield 'executions', [ex.execution_id for ex in self.executions] def __save(self): # logging.debug('SAVING PipelineStatus %s -> %r' % (self.pipeline_id, self.executions)) self.backend.register_pipeline_id(self.pipeline_id) self.backend.set_status('PipelineStatus:' + self.pipeline_id, dict(self)) def save(self): self.__save() def dirty(self): return self.num_executions == 0 or self.cache_hash != self.last_execution.cache_hash @property def executions(self): if self._executions is None: self._executions = [PipelineExecution.from_execution_id(self.backend, ex) for ex in self._execution_ids] return self._executions @property def num_executions(self): if self._executions is not None: return len(self._executions) <|code_end|> with the help of current file imports: from typing import Optional from .hook_sender import hook_sender from .pipeline_execution import PipelineExecution import logging and context from other files: # Path: datapackage_pipelines/status/hook_sender.py # def _send(hook, payload): # def send(self, hook, payload, blocking=False): # class HookSender(): # # Path: datapackage_pipelines/status/pipeline_execution.py # class PipelineExecution(object): # # def __init__(self, backend, pipeline_id, pipeline_details, cache_hash, trigger, execution_id, # log='', queue_time=None, start_time=None, finish_time=None, success=None, # stats=None, error_log=None, # save=True): # self.backend = backend # self.pipeline_id = pipeline_id # self.pipeline_details = pipeline_details # self.cache_hash = cache_hash # self.trigger = trigger # self.execution_id = execution_id # self.log = log # self.queue_time = queue_time # self.start_time = start_time # self.finish_time = finish_time # self.success = success # self.stats = stats or {} # self.error_log = error_log or [] # if save: # self.__save() # # @staticmethod # def from_execution_id(backend, execution_id): # data = backend.get_status('PipelineExecution:' + execution_id) # return PipelineExecution( # backend, # data['pipeline_id'], # data['pipeline_details'], # data['cache_hash'], # data['trigger'], # data['execution_id'], # log=data['log'], # queue_time=data['queue_time'], # start_time=data['start_time'], # finish_time=data['finish_time'], # success=data['success'], # stats=data['stats'], # error_log=data['error_log'], # save=False # ) # # def __iter__(self): # yield 'pipeline_id', self.pipeline_id, # yield 'pipeline_details', self.pipeline_details, # yield 'cache_hash', self.cache_hash # yield 'trigger', self.trigger # yield 'execution_id', self.execution_id # yield 'log', self.log # yield 'queue_time', self.queue_time # yield 'start_time', self.start_time # yield 'finish_time', self.finish_time # yield 'success', self.success # yield 'stats', self.stats # yield 'error_log', self.error_log # # def __save(self): # # logging.debug('SAVING PipelineExecution %s/%s -> %r' % (self.pipeline_id, self.execution_id, dict(self))) # self.backend.set_status('PipelineExecution:' + self.execution_id, dict(self)) # # def queue_execution(self, trigger): # if self.queue_time is not None: # return False # self.queue_time = time.time() # self.trigger = trigger # self.__save() # return True # # def start_execution(self): # if self.queue_time is None or self.start_time is not None: # return False # self.start_time = time.time() # self.__save() # return True # # def finish_execution(self, success, stats, error_log): # if self.queue_time is None or self.start_time is None: # return False # self.finish_time = time.time() # self.success = success # self.stats = stats # self.error_log = error_log # self.__save() # return True # # def update_execution(self, log): # if self.queue_time is None or self.start_time is None or self.finish_time is not None: # return False # self.log = '\n'.join(log) # self.__save() # return True # # def invalidate(self): # now = time.time() # self.queue_time = self.queue_time or now # self.start_time = self.start_time or now # self.finish_time = self.finish_time or now # self.__save() # return True # # def delete(self): # self.backend.del_status(self.execution_id) # # def is_stale(self): # long_ago = time.time() - 86400 # a day ago # if self.start_time is not None and self.start_time < long_ago: # return True # if self.queue_time is not None and self.queue_time < long_ago: # return True , which may contain function names, class names, or code. Output only the next line.
return len(self._execution_ids)
Given the code snippet: <|code_start|> class RunnerConfiguration(object): ENV_VAR = 'DPP_RUNNER_CONFIG' DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' def __init__(self): config_fn = os.environ.get(self.ENV_VAR, self.DEFAULT_RUNNER_CONFIG) if os.path.exists(config_fn): self.config = yaml.load(open(config_fn), Loader=yaml.Loader) else: self.config = {} def get_runner_class(self, kind): return { 'local-python': LocalPythonRunner, 'wrapped-python': WrappedPythonRunner, }.get(kind, LocalPythonRunner) def get_runner(self, name): <|code_end|> , generate the next line using the imports in this file: import os import yaml from .local_python import LocalPythonRunner, WrappedPythonRunner and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/manager/runners/local_python.py # class LocalPythonRunner(BaseRunner): # # def get_execution_args(self, step, _, idx): # return [ # sys.executable, # step['executor'], # str(idx), # json.dumps(step.get('parameters', {})), # str(step.get('validate', False)), # step.get('_cache_hash') if step.get('cache') else '' # ] # # class WrappedPythonRunner(LocalPythonRunner): # # def get_execution_args(self, step, cwd, idx): # args = super(WrappedPythonRunner, self).get_execution_args(step, cwd, idx) # for i in range(len(args)): # args[i] = '\\\"' + args[i].replace('"', '\\\\\\\"') + '\\\"' # cmd = " ".join(args) # abspath = os.path.abspath(cwd) # cmd = self.parameters['wrapper'].format(path=cwd, # abspath=abspath, # cmd=cmd, # env=os.environ) # args = shlex.split(cmd) # return args . Output only the next line.
runner_config = self.config.get(name, {})
Predict the next line for this snippet: <|code_start|> class RunnerConfiguration(object): ENV_VAR = 'DPP_RUNNER_CONFIG' DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' def __init__(self): config_fn = os.environ.get(self.ENV_VAR, self.DEFAULT_RUNNER_CONFIG) if os.path.exists(config_fn): self.config = yaml.load(open(config_fn), Loader=yaml.Loader) else: self.config = {} def get_runner_class(self, kind): return { 'local-python': LocalPythonRunner, 'wrapped-python': WrappedPythonRunner, }.get(kind, LocalPythonRunner) def get_runner(self, name): runner_config = self.config.get(name, {}) <|code_end|> with the help of current file imports: import os import yaml from .local_python import LocalPythonRunner, WrappedPythonRunner and context from other files: # Path: datapackage_pipelines/manager/runners/local_python.py # class LocalPythonRunner(BaseRunner): # # def get_execution_args(self, step, _, idx): # return [ # sys.executable, # step['executor'], # str(idx), # json.dumps(step.get('parameters', {})), # str(step.get('validate', False)), # step.get('_cache_hash') if step.get('cache') else '' # ] # # class WrappedPythonRunner(LocalPythonRunner): # # def get_execution_args(self, step, cwd, idx): # args = super(WrappedPythonRunner, self).get_execution_args(step, cwd, idx) # for i in range(len(args)): # args[i] = '\\\"' + args[i].replace('"', '\\\\\\\"') + '\\\"' # cmd = " ".join(args) # abspath = os.path.abspath(cwd) # cmd = self.parameters['wrapper'].format(path=cwd, # abspath=abspath, # cmd=cmd, # env=os.environ) # args = shlex.split(cmd) # return args , which may contain function names, class names, or code. Output only the next line.
kind = runner_config.get('kind')
Using the snippet: <|code_start|> DPP_DB_FILENAME = os.environ.get('DPP_DB_FILENAME', '.dpp.db') class Sqlite3Dict(object): def __init__(self, filename): self.filename = filename conn = sqlite3.connect(self.filename) cursor = conn.cursor() <|code_end|> , determine the next line of code. You have imports: import os import sqlite3 from datapackage_pipelines.utilities.extended_json import json and context (class names, function names, or code) available: # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError . Output only the next line.
cursor.execute(
Predict the next line for this snippet: <|code_start|> for dep_err in ps.validation_errors: spec.validation_errors.append( SpecError('From {}'.format(pipeline_id), dep_err) ) pipeline_hash = all_pipeline_ids.get(pipeline_id).cache_hash assert pipeline_hash is not None cache_hash += pipeline_hash spec.dependencies.append(pipeline_id) elif 'datapackage' in dependency: dp_id = dependency['datapackage'] try: dp = datapackage.DataPackage(dp_id) if 'hash' in dp.descriptor: cache_hash += dp.descriptor['hash'] else: spec.validation_errors.append( SpecError('Missing dependency', "Couldn't get data from datapackage %s" % dp_id)) except DataPackageException: spec.validation_errors.append( SpecError('Missing dependency', "Couldn't open datapackage %s" % dp_id)) else: <|code_end|> with the help of current file imports: import datapackage from datapackage.exceptions import DataPackageException from ..parsers.base_parser import PipelineSpec from ..errors import SpecError and context from other files: # Path: datapackage_pipelines/specs/parsers/base_parser.py # class PipelineSpec(object): # def __init__(self, # path=None, # pipeline_id=None, # pipeline_details=None, # source_details=None, # validation_errors=None, # dependencies=None, # cache_hash='', # schedule=None, # environment=None): # self.path = path # self.pipeline_id = pipeline_id # self.pipeline_details = pipeline_details # self.source_details = source_details # self.validation_errors = [] if validation_errors is None else validation_errors # self.dependencies = [] if dependencies is None else dependencies # self.cache_hash = cache_hash # self.schedule = schedule # self.environment = environment # # def __str__(self): # return 'PipelineSpec({}, validation_errors={}, ' \ # 'dependencies={}, cache_hash={})'\ # .format(self.pipeline_id, self.validation_errors, # self.dependencies, self.cache_hash) # # def __repr__(self): # return str(self) # # Path: datapackage_pipelines/specs/errors.py # class SpecError(NamedTuple): # short_msg: str # long_msg: str # # def __str__(self): # return '{}: {}'.format(self.short_msg, self.long_msg) , which may contain function names, class names, or code. Output only the next line.
spec.validation_errors.append(
Based on the snippet: <|code_start|> dep_prefix = 'dependency://' parameters, dp, res_iter = ingest() url = parameters['url'] if url.startswith(dep_prefix): dependency = url[len(dep_prefix):].strip() url = get_dependency_datapackage_url(dependency) assert url is not None, "Failed to fetch output datapackage for dependency '%s'" % dependency datapackage = datapackage.DataPackage(url) <|code_end|> , predict the immediate next line with the help of imports: import datapackage from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url and context (classes, functions, sometimes code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # def get_dependency_datapackage_url(pipeline_id): # return dependency_datapackage_urls.get(pipeline_id) . Output only the next line.
for k, v in datapackage.descriptor.items():
Given the code snippet: <|code_start|> dep_prefix = 'dependency://' parameters, dp, res_iter = ingest() url = parameters['url'] if url.startswith(dep_prefix): dependency = url[len(dep_prefix):].strip() url = get_dependency_datapackage_url(dependency) assert url is not None, "Failed to fetch output datapackage for dependency '%s'" % dependency datapackage = datapackage.DataPackage(url) <|code_end|> , generate the next line using the imports in this file: import datapackage from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # def get_dependency_datapackage_url(pipeline_id): # return dependency_datapackage_urls.get(pipeline_id) . Output only the next line.
for k, v in datapackage.descriptor.items():
Using the snippet: <|code_start|> dep_prefix = 'dependency://' parameters, dp, res_iter = ingest() url = parameters['url'] if url.startswith(dep_prefix): dependency = url[len(dep_prefix):].strip() url = get_dependency_datapackage_url(dependency) assert url is not None, "Failed to fetch output datapackage for dependency '%s'" % dependency datapackage = datapackage.DataPackage(url) <|code_end|> , determine the next line of code. You have imports: import datapackage from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url and context (class names, function names, or code) available: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # def spew(dp, resources_iterator, stats=None, finalizer=None): # files = [stdout] # # cache_filename = '' # if len(cache) > 0: # if not os.path.exists('.cache'): # os.mkdir('.cache') # cache_filename = os.path.join('.cache', cache) # files.append(gzip.open(cache_filename+'.ongoing', 'wt')) # # expected_resources = \ # len(list(filter(streaming, dp.get('resources', [])))) # row_count = 0 # try: # for f in files: # f.write(json.dumps(dp, sort_keys=True, ensure_ascii=True)+'\n') # f.flush() # num_resources = 0 # for res in resources_iterator: # if hasattr(res, 'it') and res.it is None: # continue # num_resources += 1 # for f in files: # f.write('\n') # try: # for rec in res: # try: # line = json.dumpl(rec, # sort_keys=True, # ensure_ascii=True) # except TypeError as e: # logging.error('Failed to encode row to JSON: %s\nOffending row: %r', e, rec) # raise # # logging.error('SPEWING: {}'.format(line)) # for f in files: # f.write(line+'\n') # # logging.error('WROTE') # row_count += 1 # except CastError as e: # for err in e.errors: # logging.error('Failed to cast row: %s', err) # raise # if num_resources != expected_resources: # logging.error('Expected to see %d resource(s) but spewed %d', # expected_resources, num_resources) # assert num_resources == expected_resources # # aggregated_stats = {} # if not first: # stats_line = sys.stdin.readline().strip() # if len(stats_line) > 0: # try: # aggregated_stats = json.loads(stats_line) # assert aggregated_stats is None or \ # isinstance(aggregated_stats, dict) # except json.JSONDecodeError: # logging.error('Failed to parse stats: %r', stats_line) # if stats is not None: # aggregated_stats.update(stats) # stats_json = json.dumps(aggregated_stats, # sort_keys=True, # ensure_ascii=True) # for f in files: # f.write('\n'+stats_json) # # except BrokenPipeError: # logging.error('Output pipe disappeared!') # sys.stderr.flush() # sys.exit(1) # # stdout.flush() # if row_count > 0: # logging.info('Processed %d rows', row_count) # # if finalizer is not None: # finalizer() # # for f in files: # f.write('\n') # Signal to other processors that we're done # if f == stdout: # # Can't close sys.stdout, otherwise any subsequent # # call to print() will throw an exception # f.flush() # else: # f.close() # # if len(cache) > 0: # os.rename(cache_filename+'.ongoing', cache_filename) # # def get_dependency_datapackage_url(pipeline_id): # return dependency_datapackage_urls.get(pipeline_id) . Output only the next line.
for k, v in datapackage.descriptor.items():
Predict the next line after this snippet: <|code_start|> def flow(parameters): return Flow( load_lazy_json(parameters.get('resources')), sort_rows( parameters['sort-by'], <|code_end|> using the current file's imports: from dataflows import Flow, sort_rows from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and any relevant context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
resources=parameters.get('resources'),
Using the snippet: <|code_start|> def flow(parameters): return Flow( load_lazy_json(parameters.get('resources')), sort_rows( parameters['sort-by'], resources=parameters.get('resources'), reverse=parameters.get('reverse') ) ) <|code_end|> , determine the next line of code. You have imports: from dataflows import Flow, sort_rows from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and context (class names, function names, or code) available: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
if __name__ == '__main__':
Next line prediction: <|code_start|> def flow(parameters): return Flow( load_lazy_json(parameters.get('resources')), sort_rows( parameters['sort-by'], <|code_end|> . Use current file imports: (from dataflows import Flow, sort_rows from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json) and context including class names, function names, or small code snippets from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
resources=parameters.get('resources'),
Here is a snippet: <|code_start|> if debug: logging.info(line) await queue.put(line) return errors async def dequeue_errors(queue, out): while True: line = await queue.get() if line is None: break out.append(line) if len(out) > 1000: out.pop(0) async def collect_stats(infile): reader = asyncio.StreamReader() reader_protocol = asyncio.StreamReaderProtocol(reader) transport, _ = await asyncio.get_event_loop() \ .connect_read_pipe(lambda: reader_protocol, infile) count = 0 dp = None stats = None while True: try: line = await reader.readline() except ValueError: logging.exception('Too large stats object!') break <|code_end|> . Write the next line using the current file imports: import asyncio import gzip import logging import os from concurrent.futures import CancelledError from json.decoder import JSONDecodeError from ..specs.specs import resolve_executor from ..status import status_mgr from ..utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY from ..utilities.extended_json import json from .runners import runner_config and context from other files: # Path: datapackage_pipelines/specs/specs.py # SPEC_PARSERS = [ # BasicPipelineParser(), # SourceSpecPipelineParser() # ] # YAML_LOADER = yaml.CLoader if 'CLoader' in yaml.__dict__ else yaml.Loader # def resolve_processors(spec: PipelineSpec): # def process_schedules(spec: PipelineSpec): # def process_environment(spec: PipelineSpec): # def find_specs(root_dir='.') -> PipelineSpec: # def pipelines(prefixes=None, ignore_missing_deps=False, root_dir='.', status_manager=None): # def register_all_pipelines(root_dir='.'): # # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/manager/runners/runner_config.py # class RunnerConfiguration(object): # ENV_VAR = 'DPP_RUNNER_CONFIG' # DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' # def __init__(self): # def get_runner_class(self, kind): # def get_runner(self, name): , which may include functions, classes, or code. Output only the next line.
if line == b'':
Based on the snippet: <|code_start|> logging.info("%s Async task starting", execution_id[:8]) ps = status_mgr().get(pipeline_id) if not ps.start_execution(execution_id): logging.info("%s START EXECUTION FAILED %s, BAILING OUT", execution_id[:8], pipeline_id) return False, {}, [] ps.update_execution(execution_id, []) if use_cache: if debug: logging.info("%s Searching for existing caches", execution_id[:8]) pipeline_steps = find_caches(pipeline_steps, pipeline_cwd) execution_log = [] if debug: logging.info("%s Building process chain:", execution_id[:8]) processes, stop_error_collecting = \ await construct_process_pipeline(pipeline_steps, pipeline_cwd, execution_log, debug) processes[0].stdin.write(json.dumps(dependencies).encode('utf8') + b'\n') processes[0].stdin.write(b'{"name": "_", "resources": []}\n') processes[0].stdin.close() def kill_all_processes(): for to_kill in processes: try: to_kill.kill() except ProcessLookupError: pass <|code_end|> , predict the immediate next line with the help of imports: import asyncio import gzip import logging import os from concurrent.futures import CancelledError from json.decoder import JSONDecodeError from ..specs.specs import resolve_executor from ..status import status_mgr from ..utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY from ..utilities.extended_json import json from .runners import runner_config and context (classes, functions, sometimes code) from other files: # Path: datapackage_pipelines/specs/specs.py # SPEC_PARSERS = [ # BasicPipelineParser(), # SourceSpecPipelineParser() # ] # YAML_LOADER = yaml.CLoader if 'CLoader' in yaml.__dict__ else yaml.Loader # def resolve_processors(spec: PipelineSpec): # def process_schedules(spec: PipelineSpec): # def process_environment(spec: PipelineSpec): # def find_specs(root_dir='.') -> PipelineSpec: # def pipelines(prefixes=None, ignore_missing_deps=False, root_dir='.', status_manager=None): # def register_all_pipelines(root_dir='.'): # # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/manager/runners/runner_config.py # class RunnerConfiguration(object): # ENV_VAR = 'DPP_RUNNER_CONFIG' # DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' # def __init__(self): # def get_runner_class(self, kind): # def get_runner(self, name): . Output only the next line.
success = True
Given the code snippet: <|code_start|> loop = asyncio.get_event_loop() if debug: logging.info("%s Collecting dependencies", execution_id[:8]) dependencies = {} for dep in spec.pipeline_details.get('dependencies', []): if 'pipeline' in dep: dep_pipeline_id = dep['pipeline'] pipeline_execution = status_mgr().get(dep_pipeline_id).get_last_successful_execution() if pipeline_execution is not None: result_dp = pipeline_execution.stats.get(STATS_DPP_KEY, {}).get(STATS_OUT_DP_URL_KEY) if result_dp is not None: dependencies[dep_pipeline_id] = result_dp if debug: logging.info("%s Running async task", execution_id[:8]) pipeline_task = \ asyncio.ensure_future(async_execute_pipeline(spec.pipeline_id, spec.pipeline_details.get('pipeline', []), spec.path, trigger, execution_id, use_cache, dependencies, debug)) try: if debug: logging.info("%s Waiting for completion", execution_id[:8]) return loop.run_until_complete(pipeline_task) <|code_end|> , generate the next line using the imports in this file: import asyncio import gzip import logging import os from concurrent.futures import CancelledError from json.decoder import JSONDecodeError from ..specs.specs import resolve_executor from ..status import status_mgr from ..utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY from ..utilities.extended_json import json from .runners import runner_config and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/specs/specs.py # SPEC_PARSERS = [ # BasicPipelineParser(), # SourceSpecPipelineParser() # ] # YAML_LOADER = yaml.CLoader if 'CLoader' in yaml.__dict__ else yaml.Loader # def resolve_processors(spec: PipelineSpec): # def process_schedules(spec: PipelineSpec): # def process_environment(spec: PipelineSpec): # def find_specs(root_dir='.') -> PipelineSpec: # def pipelines(prefixes=None, ignore_missing_deps=False, root_dir='.', status_manager=None): # def register_all_pipelines(root_dir='.'): # # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/manager/runners/runner_config.py # class RunnerConfiguration(object): # ENV_VAR = 'DPP_RUNNER_CONFIG' # DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' # def __init__(self): # def get_runner_class(self, kind): # def get_runner(self, name): . Output only the next line.
except KeyboardInterrupt:
Next line prediction: <|code_start|> wfd = asyncio.subprocess.DEVNULL if wfd is None else wfd ret = asyncio.create_subprocess_exec(*args, stdin=rfd, stdout=wfd, stderr=asyncio.subprocess.PIPE, pass_fds=pass_fds, cwd=cwd) return ret async def process_death_waiter(process): return_code = await process.wait() return process, return_code def find_caches(pipeline_steps, pipeline_cwd): if not any(step.get('cache') for step in pipeline_steps): # If no step requires caching then bail return pipeline_steps for i, step in reversed(list(enumerate(pipeline_steps))): cache_filename = os.path.join(pipeline_cwd, '.cache', step['_cache_hash']) if os.path.exists(cache_filename): try: canary = gzip.open(cache_filename, "rt") canary.seek(1) canary.close() except Exception: #noqa <|code_end|> . Use current file imports: (import asyncio import gzip import logging import os from concurrent.futures import CancelledError from json.decoder import JSONDecodeError from ..specs.specs import resolve_executor from ..status import status_mgr from ..utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY from ..utilities.extended_json import json from .runners import runner_config) and context including class names, function names, or small code snippets from other files: # Path: datapackage_pipelines/specs/specs.py # SPEC_PARSERS = [ # BasicPipelineParser(), # SourceSpecPipelineParser() # ] # YAML_LOADER = yaml.CLoader if 'CLoader' in yaml.__dict__ else yaml.Loader # def resolve_processors(spec: PipelineSpec): # def process_schedules(spec: PipelineSpec): # def process_environment(spec: PipelineSpec): # def find_specs(root_dir='.') -> PipelineSpec: # def pipelines(prefixes=None, ignore_missing_deps=False, root_dir='.', status_manager=None): # def register_all_pipelines(root_dir='.'): # # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/manager/runners/runner_config.py # class RunnerConfiguration(object): # ENV_VAR = 'DPP_RUNNER_CONFIG' # DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' # def __init__(self): # def get_runner_class(self, kind): # def get_runner(self, name): . Output only the next line.
continue
Predict the next line after this snippet: <|code_start|> def kill_all_processes(): for to_kill in processes: try: to_kill.kill() except ProcessLookupError: pass success = True pending = [asyncio.ensure_future(process_death_waiter(process)) for process in processes] index_for_pid = dict( (p.pid, i) for i, p in enumerate(processes) ) failed_index = None while len(pending) > 0: done = [] try: done, pending = \ await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED, timeout=10) except CancelledError: success = False kill_all_processes() for waiter in done: process, return_code = waiter.result() if return_code == 0: if debug: <|code_end|> using the current file's imports: import asyncio import gzip import logging import os from concurrent.futures import CancelledError from json.decoder import JSONDecodeError from ..specs.specs import resolve_executor from ..status import status_mgr from ..utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY from ..utilities.extended_json import json from .runners import runner_config and any relevant context from other files: # Path: datapackage_pipelines/specs/specs.py # SPEC_PARSERS = [ # BasicPipelineParser(), # SourceSpecPipelineParser() # ] # YAML_LOADER = yaml.CLoader if 'CLoader' in yaml.__dict__ else yaml.Loader # def resolve_processors(spec: PipelineSpec): # def process_schedules(spec: PipelineSpec): # def process_environment(spec: PipelineSpec): # def find_specs(root_dir='.') -> PipelineSpec: # def pipelines(prefixes=None, ignore_missing_deps=False, root_dir='.', status_manager=None): # def register_all_pipelines(root_dir='.'): # # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/manager/runners/runner_config.py # class RunnerConfiguration(object): # ENV_VAR = 'DPP_RUNNER_CONFIG' # DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' # def __init__(self): # def get_runner_class(self, kind): # def get_runner(self, name): . Output only the next line.
logging.info("%s DONE %s", execution_id[:8], process.args)
Predict the next line after this snippet: <|code_start|> try: to_kill.kill() except ProcessLookupError: pass success = True pending = [asyncio.ensure_future(process_death_waiter(process)) for process in processes] index_for_pid = dict( (p.pid, i) for i, p in enumerate(processes) ) failed_index = None while len(pending) > 0: done = [] try: done, pending = \ await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED, timeout=10) except CancelledError: success = False kill_all_processes() for waiter in done: process, return_code = waiter.result() if return_code == 0: if debug: logging.info("%s DONE %s", execution_id[:8], process.args) processes = [p for p in processes if p.pid != process.pid] <|code_end|> using the current file's imports: import asyncio import gzip import logging import os from concurrent.futures import CancelledError from json.decoder import JSONDecodeError from ..specs.specs import resolve_executor from ..status import status_mgr from ..utilities.stat_utils import STATS_DPP_KEY, STATS_OUT_DP_URL_KEY from ..utilities.extended_json import json from .runners import runner_config and any relevant context from other files: # Path: datapackage_pipelines/specs/specs.py # SPEC_PARSERS = [ # BasicPipelineParser(), # SourceSpecPipelineParser() # ] # YAML_LOADER = yaml.CLoader if 'CLoader' in yaml.__dict__ else yaml.Loader # def resolve_processors(spec: PipelineSpec): # def process_schedules(spec: PipelineSpec): # def process_environment(spec: PipelineSpec): # def find_specs(root_dir='.') -> PipelineSpec: # def pipelines(prefixes=None, ignore_missing_deps=False, root_dir='.', status_manager=None): # def register_all_pipelines(root_dir='.'): # # Path: datapackage_pipelines/status/status_manager.py # def status_mgr(root_dir='.') -> StatusManager: # global _status # global _root_dir # # if _status is not None and _root_dir == root_dir: # return _status # _root_dir = root_dir # _status = StatusManager(host=os.environ.get('DPP_REDIS_HOST'), root_dir=root_dir) # return _status # # Path: datapackage_pipelines/utilities/stat_utils.py # STATS_DPP_KEY = '.dpp' # # STATS_OUT_DP_URL_KEY = 'out-datapackage-url' # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError # # Path: datapackage_pipelines/manager/runners/runner_config.py # class RunnerConfiguration(object): # ENV_VAR = 'DPP_RUNNER_CONFIG' # DEFAULT_RUNNER_CONFIG = 'dpp-runners.yaml' # def __init__(self): # def get_runner_class(self, kind): # def get_runner(self, name): . Output only the next line.
else:
Here is a snippet: <|code_start|> with ingest() as ctx: parameters, datapackage, resources = ctx stats = {} sys.path.append(parameters.pop('__path')) flow_module = import_module(parameters.pop('__flow')) <|code_end|> . Write the next line using the current file imports: import sys from importlib import import_module from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) , which may include functions, classes, or code. Output only the next line.
flow = flow_module.flow(parameters, datapackage, resources, ctx.stats)
Continue the code snippet: <|code_start|> with ingest() as ctx: parameters, datapackage, resources = ctx stats = {} <|code_end|> . Use current file imports: import sys from importlib import import_module from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context (classes, functions, or code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) . Output only the next line.
sys.path.append(parameters.pop('__path'))
Given the following code snippet before the placeholder: <|code_start|> def flow(parameters): return Flow( add_computed_field( <|code_end|> , predict the next line using imports from the current file: from dataflows import Flow, add_computed_field from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) . Output only the next line.
parameters.get('fields', []),
Predict the next line after this snippet: <|code_start|> def flow(parameters): return Flow( deduplicate( resources=parameters.get('resources'), <|code_end|> using the current file's imports: from dataflows import Flow, deduplicate from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and any relevant context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) . Output only the next line.
)
Predict the next line after this snippet: <|code_start|> def flow(parameters): _from = parameters.pop('from') num_resources = 0 def count_resources(): def func(package): global num_resources num_resources = len(package.pkg.resources) yield package.pkg yield from package return func def mark_streaming(_from): def func(package): for i in range(num_resources, len(package.pkg.resources)): package.pkg.descriptor['resources'][i].setdefault(PROP_STREAMING, True) package.pkg.descriptor['resources'][i].setdefault(PROP_STREAMED_FROM, _from) yield package.pkg yield from package return func return Flow( count_resources(), <|code_end|> using the current file's imports: from dataflows import Flow, load from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.utilities.resources import PROP_STREAMING, PROP_STREAMED_FROM and any relevant context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # PROP_STREAMED_FROM = 'dpp:streamedFrom' . Output only the next line.
load(_from, **parameters),
Using the snippet: <|code_start|> def flow(parameters): _from = parameters.pop('from') num_resources = 0 def count_resources(): def func(package): global num_resources num_resources = len(package.pkg.resources) yield package.pkg yield from package return func def mark_streaming(_from): def func(package): <|code_end|> , determine the next line of code. You have imports: from dataflows import Flow, load from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.utilities.resources import PROP_STREAMING, PROP_STREAMED_FROM and context (class names, function names, or code) available: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # PROP_STREAMED_FROM = 'dpp:streamedFrom' . Output only the next line.
for i in range(num_resources, len(package.pkg.resources)):
Predict the next line after this snippet: <|code_start|> def flow(parameters): _from = parameters.pop('from') num_resources = 0 def count_resources(): def func(package): global num_resources num_resources = len(package.pkg.resources) yield package.pkg yield from package return func def mark_streaming(_from): def func(package): for i in range(num_resources, len(package.pkg.resources)): package.pkg.descriptor['resources'][i].setdefault(PROP_STREAMING, True) package.pkg.descriptor['resources'][i].setdefault(PROP_STREAMED_FROM, _from) yield package.pkg yield from package <|code_end|> using the current file's imports: from dataflows import Flow, load from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.utilities.resources import PROP_STREAMING, PROP_STREAMED_FROM and any relevant context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # PROP_STREAMED_FROM = 'dpp:streamedFrom' . Output only the next line.
return func
Based on the snippet: <|code_start|> self.redis.set(pipeline_id, json.dumps(status, ensure_ascii=True)) def del_status(self, pipeline_id): if self.is_init(): self.redis.delete(pipeline_id) def register_pipeline_id(self, pipeline_id): if self.is_init(): self.redis.sadd('all-pipelines', pipeline_id.strip()) def deregister_pipeline_id(self, pipeline_id): if self.is_init(): self.redis.srem('all-pipelines', pipeline_id.strip()) def reset(self): if self.is_init(): self.redis.delete('all-pipelines') def all_pipeline_ids(self): if self.is_init(): return [x.decode('utf-8') for x in self.redis.smembers('all-pipelines')] return [] def all_statuses(self): if self.is_init(): all_ids = self.redis.smembers('all-pipelines') pipe = self.redis.pipeline() for _id in sorted(all_ids): pipe.get(_id) return [json.loads(sts.decode('ascii')) for sts in pipe.execute()] <|code_end|> , predict the immediate next line with the help of imports: import logging import redis from datapackage_pipelines.utilities.extended_json import json and context (classes, functions, sometimes code) from other files: # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError . Output only the next line.
return []
Given the code snippet: <|code_start|> def flow(parameters): resources = parameters.get('resources', None) metadata = parameters.pop('metadata', {}) return Flow( update_resource(resources, **metadata), <|code_end|> , generate the next line using the imports in this file: from dataflows import Flow, update_resource from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) . Output only the next line.
)
Predict the next line for this snippet: <|code_start|> def flow(parameters): resources = parameters.get('resources', None) metadata = parameters.pop('metadata', {}) return Flow( update_resource(resources, **metadata), ) <|code_end|> with the help of current file imports: from dataflows import Flow, update_resource from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) , which may contain function names, class names, or code. Output only the next line.
if __name__ == '__main__':
Predict the next line for this snippet: <|code_start|> class ResourceIterator(object): def __init__(self, infile, spec, orig_spec, validate=False, debug=False): <|code_end|> with the help of current file imports: import sys import copy import logging import datapackage from tableschema.exceptions import ValidationError, CastError from tableschema import Schema from ..utilities.resources import PATH_PLACEHOLDER, streaming from ..utilities.extended_json import json and context from other files: # Path: datapackage_pipelines/utilities/resources.py # PATH_PLACEHOLDER = '_' # # def streaming(descriptor): # return descriptor.get(PROP_STREAMING) # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError , which may contain function names, class names, or code. Output only the next line.
self.spec = spec
Using the snippet: <|code_start|> class ResourceIterator(object): def __init__(self, infile, spec, orig_spec, validate=False, debug=False): self.spec = spec self.table_schema = Schema(orig_spec['schema']) self.field_names = [f['name'] for f in orig_spec['schema']['fields']] self.validate = validate self.infile = infile self.debug = debug self.stopped = False def __iter__(self): return self def __next__(self): if self.stopped: raise StopIteration() if self.debug: logging.error('WAITING') line = self.infile.readline().strip() if self.debug: logging.error('INGESTING: %r', line) if line == '': self.stopped = True <|code_end|> , determine the next line of code. You have imports: import sys import copy import logging import datapackage from tableschema.exceptions import ValidationError, CastError from tableschema import Schema from ..utilities.resources import PATH_PLACEHOLDER, streaming from ..utilities.extended_json import json and context (class names, function names, or code) available: # Path: datapackage_pipelines/utilities/resources.py # PATH_PLACEHOLDER = '_' # # def streaming(descriptor): # return descriptor.get(PROP_STREAMING) # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError . Output only the next line.
raise StopIteration()
Predict the next line for this snippet: <|code_start|> return self.__next__() def read_json(infile, proxy=False): line_json = infile.readline().strip() if line_json == '': sys.exit(-3) if proxy: print(line_json) try: return json.loads(line_json) except json.JSONDecodeError: logging.exception("Failed to decode line %r\nPerhaps there's a rogue print statement somewhere?", line_json) def process_input(infile, validate=False, debug=False): dependency_dp = read_json(infile, True) dp = read_json(infile) resources = dp.get('resources', []) original_resources = copy.deepcopy(resources) if len(dp.get('resources', [])) == 0: # Currently datapackages with no resources are disallowed in the schema. # Since this might happen in the early stages of a pipeline, # we're adding this hack to avoid validation errors dp_to_validate = copy.deepcopy(dp) dp_to_validate['resources'] = [{ 'name': '__placeholder__', 'path': PATH_PLACEHOLDER }] <|code_end|> with the help of current file imports: import sys import copy import logging import datapackage from tableschema.exceptions import ValidationError, CastError from tableschema import Schema from ..utilities.resources import PATH_PLACEHOLDER, streaming from ..utilities.extended_json import json and context from other files: # Path: datapackage_pipelines/utilities/resources.py # PATH_PLACEHOLDER = '_' # # def streaming(descriptor): # return descriptor.get(PROP_STREAMING) # # Path: datapackage_pipelines/utilities/extended_json.py # class json(object): # dumps = _dumps # loads = _loads # dumpl = _dumpl # loadl = _loadl # dump = _dump # load = _load # JSONDecodeError = _json.JSONDecodeError , which may contain function names, class names, or code. Output only the next line.
else:
Predict the next line for this snippet: <|code_start|> def flow(parameters): return Flow( find_replace( parameters.get('fields', []), resources=parameters.get('resources') <|code_end|> with the help of current file imports: from dataflows import Flow, find_replace from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) , which may contain function names, class names, or code. Output only the next line.
)
Predict the next line for this snippet: <|code_start|> def flow(parameters): return Flow( dump_to_sql( parameters['tables'], engine=parameters.get('engine', 'env://DPP_DB_ENGINE'), <|code_end|> with the help of current file imports: from dataflows import Flow, dump_to_sql from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) , which may contain function names, class names, or code. Output only the next line.
updated_column=parameters.get("updated_column"),
Using the snippet: <|code_start|> def flow(parameters): return Flow( dump_to_sql( parameters['tables'], engine=parameters.get('engine', 'env://DPP_DB_ENGINE'), updated_column=parameters.get("updated_column"), updated_id_column=parameters.get("updated_id_column") ) ) <|code_end|> , determine the next line of code. You have imports: from dataflows import Flow, dump_to_sql from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow and context (class names, function names, or code) available: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) . Output only the next line.
if __name__ == '__main__':
Given the following code snippet before the placeholder: <|code_start|> def flow(parameters): source = parameters['source'] target = parameters['target'] return Flow( load_lazy_json(source['name']), join( source['name'], source['key'], target['name'], target['key'], parameters['fields'], parameters.get('full', None), parameters.get('mode', 'half-outer'), source.get('delete', False) ), update_resource( target['name'], <|code_end|> , predict the next line using imports from the current file: from dataflows import Flow, join, update_resource from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.resources import PROP_STREAMING from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
**{
Predict the next line for this snippet: <|code_start|> def flow(parameters): source = parameters['source'] target = parameters['target'] return Flow( load_lazy_json(source['name']), join( source['name'], source['key'], target['name'], target['key'], parameters['fields'], parameters.get('full', None), parameters.get('mode', 'half-outer'), <|code_end|> with the help of current file imports: from dataflows import Flow, join, update_resource from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.resources import PROP_STREAMING from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and context from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func , which may contain function names, class names, or code. Output only the next line.
source.get('delete', False)
Continue the code snippet: <|code_start|> def flow(parameters): source = parameters['source'] target = parameters['target'] return Flow( load_lazy_json(source['name']), join( source['name'], source['key'], target['name'], target['key'], parameters['fields'], <|code_end|> . Use current file imports: from dataflows import Flow, join, update_resource from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.resources import PROP_STREAMING from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and context (classes, functions, or code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
parameters.get('full', None),
Given the code snippet: <|code_start|> def flow(parameters): source = parameters['source'] target = parameters['target'] return Flow( load_lazy_json(source['name']), join( <|code_end|> , generate the next line using the imports in this file: from dataflows import Flow, join, update_resource from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.resources import PROP_STREAMING from datapackage_pipelines.utilities.flow_utils import spew_flow, load_lazy_json and context (functions, classes, or occasionally code) from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/resources.py # PROP_STREAMING = 'dpp:streaming' # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # def load_lazy_json(resources): # # def func(package): # matcher = ResourceMatcher(resources, package.pkg) # yield package.pkg # for rows in package: # if matcher.match(rows.res.name): # yield ( # row.inner # if isinstance(row, LazyJsonLine) # else row # for row in rows # ) # else: # yield rows # # return func . Output only the next line.
source['name'],
Here is a snippet: <|code_start|> for path_ in processor_path() ]) resolvers.append(find_file_in_path([os.path.dirname(__file__), '..', 'lib'])) for resolver in resolvers: location = resolver(parts) if location is not None: return location message = "Couldn't resolve {0} at {1}".format(executor, path) errors.append(SpecError('Unresolved processor', message)) resolved_generators = {} def resolve_generator(module_name): if module_name in resolved_generators: return resolved_generators[module_name] resolved_generators[module_name] = None module = load_module(module_name) if module is None: return None try: generator_class = module.Generator except AttributeError: logging.warning("Can't find 'Generator' identifier in %s", module_name) return None generator = generator_class() <|code_end|> . Write the next line using the current file imports: import logging import os import hashlib import sys from importlib.util import find_spec from importlib import import_module from .errors import SpecError and context from other files: # Path: datapackage_pipelines/specs/errors.py # class SpecError(NamedTuple): # short_msg: str # long_msg: str # # def __str__(self): # return '{}: {}'.format(self.short_msg, self.long_msg) , which may include functions, classes, or code. Output only the next line.
resolved_generators[module_name] = generator
Here is a snippet: <|code_start|> if datetime.date(1, 1, 1).strftime('%04Y') == '4Y': DATE_F_FORMAT = '%Y-%m-%d' DATETIME_F_FORMAT = '%Y-%m-%d %H:%M:%S' <|code_end|> . Write the next line using the current file imports: import datetime import json as _json import decimal import isodate from .lazy_dict import LazyDict and context from other files: # Path: datapackage_pipelines/utilities/lazy_dict.py # class LazyDict(collections.MutableMapping): # # def __init__(self): # self._inner = None # self._dirty = False # # @property # def dirty(self): # return self._dirty # # @property # def inner(self): # self.__ensure() # return self._inner # # def _evaluate(self): # raise NotImplementedError() # # def __ensure(self): # if self._inner is None: # self._inner = self._evaluate() # # def __len__(self): # self.__ensure() # return len(self._inner) # # def __getitem__(self, item): # self.__ensure() # return self._inner.__getitem__(item) # # def __setitem__(self, key, value): # self.__ensure() # self._inner.__setitem__(key, value) # self._dirty = True # # def __delitem__(self, key): # self.__ensure() # self._inner.__delitem__(key) # self._dirty = True # # def __iter__(self): # self.__ensure() # return self._inner.__iter__() , which may include functions, classes, or code. Output only the next line.
else:
Given the following code snippet before the placeholder: <|code_start|> if __name__ == '__main__': warnings.warn( 'add_metadata will be removed in the future, use "update_package" instead', DeprecationWarning <|code_end|> , predict the next line using imports from the current file: import warnings from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow from datapackage_pipelines.lib.update_package import flow and context including class names, function names, and sometimes code from other files: # Path: datapackage_pipelines/wrapper/wrapper.py # def ingest(debug=False): # params, datapackage, resource_iterator = _ingest(debug=debug) # return ProcessorContext(params, datapackage, resource_iterator) # # Path: datapackage_pipelines/utilities/flow_utils.py # def spew_flow(flow, ctx: ProcessorContext): # flow = Flow( # update_package(**ctx.datapackage), # load((ctx.datapackage, ctx.resource_iterator)), # flow, # ) # datastream = flow.datastream() # ctx.datapackage = datastream.dp.descriptor # ctx.resource_iterator = datastream.res_iter # ctx.stats = MergeableStats(datastream.stats, ctx.stats) # # Path: datapackage_pipelines/lib/update_package.py # def flow(parameters): # return Flow( # update_package(**parameters) # ) . Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> @abstractmethod def done_callbacks(self) -> CallbackCollection: raise NotImplementedError @property @abstractmethod def is_initialized(self) -> bool: return hasattr(self, "_channel") @property @abstractmethod def is_closed(self) -> bool: raise NotImplementedError @abstractmethod def close(self, exc: ExceptionType = None) -> Awaitable[None]: raise NotImplementedError @property @abstractmethod def channel(self) -> aiormq.abc.AbstractChannel: raise NotImplementedError @property @abstractmethod def number(self) -> Optional[int]: raise NotImplementedError @abstractmethod def __await__(self) -> Generator[Any, Any, "AbstractChannel"]: <|code_end|> , predict the next line using imports from the current file: import asyncio import aiormq from abc import ABC, abstractmethod from datetime import datetime, timedelta from enum import Enum, IntEnum, unique from types import TracebackType from typing import ( Any, AsyncContextManager, Awaitable, Callable, Dict, FrozenSet, Generator, Iterator, MutableMapping, NamedTuple, Optional, Set, Tuple, Type, TypeVar, Union, ) from aiormq.abc import ExceptionType from pamqp.common import Arguments from yarl import URL from .pool import PoolInstance from .tools import CallbackCollection, CallbackSetType, CallbackType and context including class names, function names, and sometimes code from other files: # Path: aio_pika/pool.py # class PoolInstance(abc.ABC): # @abc.abstractmethod # def close(self) -> Awaitable[None]: # raise NotImplementedError # # Path: aio_pika/tools.py # T = TypeVar("T") # def iscoroutinepartial(fn: Callable[..., Any]) -> bool: # def create_task( # func: Callable[..., Union[Coroutine[Any, Any, T], Awaitable[T]]], # *args: Any, # loop: Optional[asyncio.AbstractEventLoop] = None, # **kwargs: Any # ) -> Awaitable[T]: # def run(future: asyncio.Future) -> Optional[asyncio.Future]: # def task( # func: Callable[..., Coroutine[Any, Any, T]], # ) -> Callable[..., Awaitable[T]]: # def wrap(*args: Any, **kwargs: Any) -> Awaitable[T]: # def shield(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]: # def wrap(*args: Any, **kwargs: Any) -> Awaitable[T]: # def __init__(self, sender: Union[T, ReferenceType]): # def add( # self, callback: Callable[..., Any], weak: bool = False, # ) -> None: # def discard(self, callback: Callable[..., Any]) -> None: # def clear(self) -> None: # def is_frozen(self) -> bool: # def freeze(self) -> None: # def unfreeze(self) -> None: # def __contains__(self, x: object) -> bool: # def __len__(self) -> int: # def __iter__(self) -> Iterator[CallbackType]: # def __bool__(self) -> bool: # def __copy__(self) -> "CallbackCollection": # def __call__(self, *args: Any, **kwargs: Any) -> None: # def __hash__(self) -> int: # class CallbackCollection(MutableSet): . Output only the next line.
raise NotImplementedError
Given snippet: <|code_start|> auto_delete: bool = False, internal: bool = False, passive: bool = False, arguments: Arguments = None, timeout: TimeoutType = None, ) -> AbstractExchange: raise NotImplementedError @abstractmethod async def get_exchange( self, name: str, *, ensure: bool = True ) -> AbstractExchange: raise NotImplementedError @abstractmethod async def declare_queue( self, name: str = None, *, durable: bool = False, exclusive: bool = False, passive: bool = False, auto_delete: bool = False, arguments: Arguments = None, timeout: TimeoutType = None ) -> AbstractQueue: raise NotImplementedError @abstractmethod async def get_queue( <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio import aiormq from abc import ABC, abstractmethod from datetime import datetime, timedelta from enum import Enum, IntEnum, unique from types import TracebackType from typing import ( Any, AsyncContextManager, Awaitable, Callable, Dict, FrozenSet, Generator, Iterator, MutableMapping, NamedTuple, Optional, Set, Tuple, Type, TypeVar, Union, ) from aiormq.abc import ExceptionType from pamqp.common import Arguments from yarl import URL from .pool import PoolInstance from .tools import CallbackCollection, CallbackSetType, CallbackType and context: # Path: aio_pika/pool.py # class PoolInstance(abc.ABC): # @abc.abstractmethod # def close(self) -> Awaitable[None]: # raise NotImplementedError # # Path: aio_pika/tools.py # T = TypeVar("T") # def iscoroutinepartial(fn: Callable[..., Any]) -> bool: # def create_task( # func: Callable[..., Union[Coroutine[Any, Any, T], Awaitable[T]]], # *args: Any, # loop: Optional[asyncio.AbstractEventLoop] = None, # **kwargs: Any # ) -> Awaitable[T]: # def run(future: asyncio.Future) -> Optional[asyncio.Future]: # def task( # func: Callable[..., Coroutine[Any, Any, T]], # ) -> Callable[..., Awaitable[T]]: # def wrap(*args: Any, **kwargs: Any) -> Awaitable[T]: # def shield(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]: # def wrap(*args: Any, **kwargs: Any) -> Awaitable[T]: # def __init__(self, sender: Union[T, ReferenceType]): # def add( # self, callback: Callable[..., Any], weak: bool = False, # ) -> None: # def discard(self, callback: Callable[..., Any]) -> None: # def clear(self) -> None: # def is_frozen(self) -> bool: # def freeze(self) -> None: # def unfreeze(self) -> None: # def __contains__(self, x: object) -> bool: # def __len__(self) -> int: # def __iter__(self) -> Iterator[CallbackType]: # def __bool__(self) -> bool: # def __copy__(self) -> "CallbackCollection": # def __call__(self, *args: Any, **kwargs: Any) -> None: # def __hash__(self) -> int: # class CallbackCollection(MutableSet): which might include code, classes, or functions. Output only the next line.
self, name: str, *, ensure: bool = True
Given the code snippet: <|code_start|> log = logging.getLogger(__name__) class PoolInstance(abc.ABC): @abc.abstractmethod def close(self) -> Awaitable[None]: raise NotImplementedError T = TypeVar("T") ConstructorType = Callable[ ..., Union[ Awaitable[PoolInstance], PoolInstance, Coroutine[Any, Any, PoolInstance], ], ] class PoolInvalidStateError(RuntimeError): pass class Pool(Generic[T]): __slots__ = ( "loop", <|code_end|> , generate the next line using the imports in this file: import abc import asyncio import logging from types import TracebackType from typing import ( Any, AsyncContextManager, Awaitable, Callable, Coroutine, Generic, Optional, Set, Tuple, Type, TypeVar, Union, ) from aiormq.tools import awaitable from aio_pika.tools import create_task and context (functions, classes, or occasionally code) from other files: # Path: aio_pika/tools.py # def create_task( # func: Callable[..., Union[Coroutine[Any, Any, T], Awaitable[T]]], # *args: Any, # loop: Optional[asyncio.AbstractEventLoop] = None, # **kwargs: Any # ) -> Awaitable[T]: # loop = loop or asyncio.get_event_loop() # # if iscoroutinepartial(func): # return loop.create_task(func(*args, **kwargs)) # # def run(future: asyncio.Future) -> Optional[asyncio.Future]: # if future.done(): # return None # # try: # future.set_result(func(*args, **kwargs)) # except Exception as e: # future.set_exception(e) # # return future # # future = loop.create_future() # loop.call_soon(run, future) # return future . Output only the next line.
"__max_size",
Predict the next line for this snippet: <|code_start|> return mock.MagicMock() @pytest.fixture def collection(self, instance): return CallbackCollection(instance) def test_basic(self, collection): def func(sender, *args, **kwargs): pass collection.add(func) assert func in collection with pytest.raises(ValueError): collection.add(None) collection.remove(func) with pytest.raises(LookupError): collection.remove(func) for _ in range(10): collection.add(func) assert len(collection) == 1 collection.freeze() with pytest.raises(RuntimeError): <|code_end|> with the help of current file imports: import logging import pytest from copy import copy from unittest import mock from aio_pika.tools import CallbackCollection and context from other files: # Path: aio_pika/tools.py # class CallbackCollection(MutableSet): # __slots__ = "__sender", "__callbacks", "__weak_callbacks", "__lock" # # def __init__(self, sender: Union[T, ReferenceType]): # self.__sender: ReferenceType # if isinstance(sender, ReferenceType): # self.__sender = sender # else: # self.__sender = ref(sender) # # self.__callbacks: CallbackSetType = set() # self.__weak_callbacks: MutableSet[CallbackType] = WeakSet() # self.__lock: Lock = Lock() # # def add( # self, callback: Callable[..., Any], weak: bool = False, # ) -> None: # if self.is_frozen: # raise RuntimeError("Collection frozen") # if not callable(callback): # raise ValueError("Callback is not callable") # # with self.__lock: # if weak: # self.__weak_callbacks.add(callback) # else: # self.__callbacks.add(callback) # type: ignore # # def discard(self, callback: Callable[..., Any]) -> None: # if self.is_frozen: # raise RuntimeError("Collection frozen") # # with self.__lock: # if callback in self.__callbacks: # self.__callbacks.remove(callback) # type: ignore # elif callback in self.__weak_callbacks: # self.__weak_callbacks.remove(callback) # # def clear(self) -> None: # if self.is_frozen: # raise RuntimeError("Collection frozen") # # with self.__lock: # self.__callbacks.clear() # type: ignore # self.__weak_callbacks.clear() # # @property # def is_frozen(self) -> bool: # return isinstance(self.__callbacks, frozenset) # # def freeze(self) -> None: # if self.is_frozen: # raise RuntimeError("Collection already frozen") # # with self.__lock: # self.__callbacks = frozenset(self.__callbacks) # self.__weak_callbacks = WeakSet(self.__weak_callbacks) # # def unfreeze(self) -> None: # if not self.is_frozen: # raise RuntimeError("Collection is not frozen") # # with self.__lock: # self.__callbacks = set(self.__callbacks) # self.__weak_callbacks = WeakSet(self.__weak_callbacks) # # def __contains__(self, x: object) -> bool: # return x in self.__callbacks or x in self.__weak_callbacks # # def __len__(self) -> int: # return len(self.__callbacks) + len(self.__weak_callbacks) # # def __iter__(self) -> Iterator[CallbackType]: # return iter(chain(self.__callbacks, self.__weak_callbacks)) # # def __bool__(self) -> bool: # return bool(self.__callbacks) or bool(self.__weak_callbacks) # # def __copy__(self) -> "CallbackCollection": # instance = self.__class__(self.__sender) # # with self.__lock: # for cb in self.__callbacks: # instance.add(cb, weak=False) # # for cb in self.__weak_callbacks: # instance.add(cb, weak=True) # # if self.is_frozen: # instance.freeze() # # return instance # # def __call__(self, *args: Any, **kwargs: Any) -> None: # with self.__lock: # sender = self.__sender() # # for cb in self: # try: # cb(sender, *args, **kwargs) # except Exception: # log.exception("Callback %r error", cb) # # def __hash__(self) -> int: # return id(self) , which may contain function names, class names, or code. Output only the next line.
collection.freeze()
Based on the snippet: <|code_start|> @pytest.mark.parametrize("max_size", [50, 10, 5, 1]) async def test_simple(max_size, loop): counter = 0 async def create_instance(): nonlocal counter await asyncio.sleep(0) counter += 1 return counter pool = Pool(create_instance, max_size=max_size, loop=loop) <|code_end|> , predict the immediate next line with the help of imports: import asyncio import pytest from collections import Counter from aio_pika.pool import Pool, PoolInstance and context (classes, functions, sometimes code) from other files: # Path: aio_pika/pool.py # class Pool(Generic[T]): # __slots__ = ( # "loop", # "__max_size", # "__items", # "__constructor", # "__created", # "__lock", # "__constructor_args", # "__item_set", # "__closed", # ) # # def __init__( # self, # constructor: ConstructorType, # *args: Any, # max_size: int = None, # loop: Optional[asyncio.AbstractEventLoop] = None # ): # self.loop = loop or asyncio.get_event_loop() # self.__closed = False # self.__constructor: Callable[..., Awaitable[Any]] = awaitable( # constructor, # ) # self.__constructor_args: Tuple[Any, ...] = args or () # self.__created: int = 0 # self.__item_set: Set[PoolInstance] = set() # self.__items: asyncio.Queue = asyncio.Queue() # self.__lock: asyncio.Lock = asyncio.Lock() # self.__max_size: Optional[int] = max_size # # @property # def is_closed(self) -> bool: # return self.__closed # # def acquire(self) -> "PoolItemContextManager[T]": # if self.__closed: # raise PoolInvalidStateError("acquire operation on closed pool") # # return PoolItemContextManager[T](self) # # @property # def _has_released(self) -> bool: # return self.__items.qsize() > 0 # # @property # def _is_overflow(self) -> bool: # if self.__max_size: # return self.__created >= self.__max_size or self._has_released # return self._has_released # # async def _create_item(self) -> T: # if self.__closed: # raise PoolInvalidStateError("create item operation on closed pool") # # async with self.__lock: # if self._is_overflow: # return await self.__items.get() # # log.debug("Creating a new instance of %r", self.__constructor) # item = await self.__constructor(*self.__constructor_args) # self.__created += 1 # self.__item_set.add(item) # return item # # async def _get(self) -> T: # if self.__closed: # raise PoolInvalidStateError("get operation on closed pool") # # if self._is_overflow: # return await self.__items.get() # # return await self._create_item() # # def put(self, item: T) -> None: # if self.__closed: # raise PoolInvalidStateError("put operation on closed pool") # # self.__items.put_nowait(item) # # async def close(self) -> None: # async with self.__lock: # self.__closed = True # tasks = [] # # for item in self.__item_set: # tasks.append(create_task(item.close)) # # if tasks: # await asyncio.gather(*tasks, return_exceptions=True) # # async def __aenter__(self) -> "Pool": # return self # # async def __aexit__( # self, # exc_type: Optional[Type[BaseException]], # exc_val: Optional[BaseException], # exc_tb: Optional[TracebackType], # ) -> None: # if self.__closed: # return # # await asyncio.shield(self.close()) # # class PoolInstance(abc.ABC): # @abc.abstractmethod # def close(self) -> Awaitable[None]: # raise NotImplementedError . Output only the next line.
async def getter():
Given the code snippet: <|code_start|> class TestInstance(TestInstanceBase): async def test_close(self, pool, instances, loop, max_size): async def getter(): async with pool.acquire(): await asyncio.sleep(0.05) assert not pool.is_closed assert len(instances) == 0 await asyncio.gather(*[getter() for _ in range(200)]) assert len(instances) == max_size for instance in instances: assert not instance.closed await pool.close() for instance in instances: assert instance.closed assert pool.is_closed async def test_close_context_manager(self, pool, instances): async def getter(): async with pool.acquire(): await asyncio.sleep(0.05) async with pool: <|code_end|> , generate the next line using the imports in this file: import asyncio import pytest from collections import Counter from aio_pika.pool import Pool, PoolInstance and context (functions, classes, or occasionally code) from other files: # Path: aio_pika/pool.py # class Pool(Generic[T]): # __slots__ = ( # "loop", # "__max_size", # "__items", # "__constructor", # "__created", # "__lock", # "__constructor_args", # "__item_set", # "__closed", # ) # # def __init__( # self, # constructor: ConstructorType, # *args: Any, # max_size: int = None, # loop: Optional[asyncio.AbstractEventLoop] = None # ): # self.loop = loop or asyncio.get_event_loop() # self.__closed = False # self.__constructor: Callable[..., Awaitable[Any]] = awaitable( # constructor, # ) # self.__constructor_args: Tuple[Any, ...] = args or () # self.__created: int = 0 # self.__item_set: Set[PoolInstance] = set() # self.__items: asyncio.Queue = asyncio.Queue() # self.__lock: asyncio.Lock = asyncio.Lock() # self.__max_size: Optional[int] = max_size # # @property # def is_closed(self) -> bool: # return self.__closed # # def acquire(self) -> "PoolItemContextManager[T]": # if self.__closed: # raise PoolInvalidStateError("acquire operation on closed pool") # # return PoolItemContextManager[T](self) # # @property # def _has_released(self) -> bool: # return self.__items.qsize() > 0 # # @property # def _is_overflow(self) -> bool: # if self.__max_size: # return self.__created >= self.__max_size or self._has_released # return self._has_released # # async def _create_item(self) -> T: # if self.__closed: # raise PoolInvalidStateError("create item operation on closed pool") # # async with self.__lock: # if self._is_overflow: # return await self.__items.get() # # log.debug("Creating a new instance of %r", self.__constructor) # item = await self.__constructor(*self.__constructor_args) # self.__created += 1 # self.__item_set.add(item) # return item # # async def _get(self) -> T: # if self.__closed: # raise PoolInvalidStateError("get operation on closed pool") # # if self._is_overflow: # return await self.__items.get() # # return await self._create_item() # # def put(self, item: T) -> None: # if self.__closed: # raise PoolInvalidStateError("put operation on closed pool") # # self.__items.put_nowait(item) # # async def close(self) -> None: # async with self.__lock: # self.__closed = True # tasks = [] # # for item in self.__item_set: # tasks.append(create_task(item.close)) # # if tasks: # await asyncio.gather(*tasks, return_exceptions=True) # # async def __aenter__(self) -> "Pool": # return self # # async def __aexit__( # self, # exc_type: Optional[Type[BaseException]], # exc_val: Optional[BaseException], # exc_tb: Optional[TracebackType], # ) -> None: # if self.__closed: # return # # await asyncio.shield(self.close()) # # class PoolInstance(abc.ABC): # @abc.abstractmethod # def close(self) -> Awaitable[None]: # raise NotImplementedError . Output only the next line.
assert not pool.is_closed
Given snippet: <|code_start|> try: except ImportError, e: try: except ImportError, e: <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf import settings from django.db import models from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.forms import UserChangeForm from django.http import (HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseNotFound) from django.views.decorators.http import (require_GET, require_POST, require_http_methods) from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from .models import UserProfile from .forms import UserProfileEditForm, UserEditForm from commons.urlresolvers import reverse from django.core.urlresolvers import reverse from tower import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _ and context: # Path: apps/profiles/models.py # class UserProfile(models.Model): # # user = models.ForeignKey(User, unique=True) # # username_changes = models.IntegerField(default=0) # # is_confirmed = models.BooleanField(default=False) # # display_name = models.CharField(max_length=64, blank=True, null=True, # unique=False) # # avatar = models.ImageField(blank=True, null=True, # storage=PROFILE_UPLOADS_FS, # upload_to=mk_upload_to('avatar.png')) # # bio = models.TextField(blank=True) # organization = models.CharField(max_length=255, default='', blank=True) # location = models.CharField(max_length=255, default='', blank=True) # # created = models.DateTimeField(auto_now_add=True, blank=False) # modified = models.DateTimeField(auto_now=True, blank=False) # # class Meta: # pass # # def __unicode__(self): # return (self.display_name and # self.display_name or self.user.username) # # def get_absolute_url(self): # return reverse('profiles.views.profile_view', # kwargs={'username':self.user.username}) # # def get_upload_meta(self): # return ("profile", self.user.username) # # def allows_edit(self, user): # if user == self.user: # return True # if user.is_staff or user.is_superuser: # return True # return False # # @property # def bio_html(self): # return bleach.linkify(self.bio) # # def username_changes_remaining(self): # return MAX_USERNAME_CHANGES - self.username_changes # # def can_change_username(self, user=None): # if self.username_changes_remaining() > 0: # return True # return False # # def change_username(self, username, user=None): # if not self.can_change_username(user): # return False # if username != self.user.username: # self.user.username = username # self.user.save() # self.username_changes += 1 # self.save() # return True # # def clean(self): # if self.avatar: # scaled_file = scale_image(self.avatar.file, IMG_MAX_SIZE) # if not scaled_file: # raise ValidationError(_('Cannot process image')) # self.avatar.file = scaled_file # # Path: apps/profiles/forms.py # class UserProfileEditForm(MyModelForm): # # class Meta: # model = UserProfile # fields = ('display_name', 'avatar', 'location', 'bio', ) # # def __init__(self, *args, **kwargs): # super(UserProfileEditForm, self).__init__(*args, **kwargs) # # class UserEditForm(MyForm): # # username = forms.RegexField(label=_("Username"), max_length=30, # regex=r'^[\w.@+-]+$', # help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), # error_messages = {'invalid': # _("This value may contain only letters, numbers and @/./+/-/_ characters.")}) # # def __init__(self, *args, **kwargs): # # profile = kwargs['profile'] # del kwargs['profile'] # # super(UserEditForm, self).__init__(*args, **kwargs) # # remaining = profile.username_changes_remaining() # self.fields['username'].help_text = ( # _('Changes remaining: %s') % remaining) # self.initial['username'] = profile.user.username which might include code, classes, or functions. Output only the next line.
def home(request):
Given the following code snippet before the placeholder: <|code_start|> error_css_class = "error" def as_ul(self): "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>." return self._html_output( normal_row=(u'<li%(html_class_attr)s>%(label)s %(field)s' + '%(help_text)s%(errors)s</li>'), error_row=u'<li>%s</li>', row_ender='</li>', help_text_html=u' <p class="help">%s</p>', errors_on_separate_row=False) class UserEditForm(MyForm): username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")}) def __init__(self, *args, **kwargs): profile = kwargs['profile'] del kwargs['profile'] super(UserEditForm, self).__init__(*args, **kwargs) remaining = profile.username_changes_remaining() self.fields['username'].help_text = ( <|code_end|> , predict the next line using imports from the current file: from django import forms from django.db import models from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.forms import UserChangeForm from django.utils.translation import ugettext_lazy as _ from .models import UserProfile and context including class names, function names, and sometimes code from other files: # Path: apps/profiles/models.py # class UserProfile(models.Model): # # user = models.ForeignKey(User, unique=True) # # username_changes = models.IntegerField(default=0) # # is_confirmed = models.BooleanField(default=False) # # display_name = models.CharField(max_length=64, blank=True, null=True, # unique=False) # # avatar = models.ImageField(blank=True, null=True, # storage=PROFILE_UPLOADS_FS, # upload_to=mk_upload_to('avatar.png')) # # bio = models.TextField(blank=True) # organization = models.CharField(max_length=255, default='', blank=True) # location = models.CharField(max_length=255, default='', blank=True) # # created = models.DateTimeField(auto_now_add=True, blank=False) # modified = models.DateTimeField(auto_now=True, blank=False) # # class Meta: # pass # # def __unicode__(self): # return (self.display_name and # self.display_name or self.user.username) # # def get_absolute_url(self): # return reverse('profiles.views.profile_view', # kwargs={'username':self.user.username}) # # def get_upload_meta(self): # return ("profile", self.user.username) # # def allows_edit(self, user): # if user == self.user: # return True # if user.is_staff or user.is_superuser: # return True # return False # # @property # def bio_html(self): # return bleach.linkify(self.bio) # # def username_changes_remaining(self): # return MAX_USERNAME_CHANGES - self.username_changes # # def can_change_username(self, user=None): # if self.username_changes_remaining() > 0: # return True # return False # # def change_username(self, username, user=None): # if not self.can_change_username(user): # return False # if username != self.user.username: # self.user.username = username # self.user.save() # self.username_changes += 1 # self.save() # return True # # def clean(self): # if self.avatar: # scaled_file = scale_image(self.avatar.file, IMG_MAX_SIZE) # if not scaled_file: # raise ValidationError(_('Cannot process image')) # self.avatar.file = scaled_file . Output only the next line.
_('Changes remaining: %s') % remaining)
Predict the next line after this snippet: <|code_start|> @pytest.mark.django_db def test_filter_names_with_empty_query(rf, search_fixtures): request = rf.get('/') names = utils.filter_names(request) assert names.count() == search_fixtures.count() @pytest.mark.django_db def test_filter_names_with_query(rf, search_fixtures): request = rf.get('/', {'q': 1}) names = utils.filter_names(request) assert names.count() == 5 @pytest.mark.django_db @pytest.mark.parametrize('q_type,expected', [ ('Personal', 1), ('Personal,Organization', 2), ('Personal,Organization,Event', 3), ('Personal,Organization,Event,Software,Building', 5) ]) def test_filter_names_with_query_and_name_types(rf, q_type, expected, search_fixtures): request = rf.get('/', {'q': '1', 'q_type': q_type}) names = utils.filter_names(request) <|code_end|> using the current file's imports: import pytest from name import utils and any relevant context from other files: # Path: name/utils.py # def normalize_query(query_string): # def compose_query(query_string): # def resolve_type(q_type): # def filter_names(request): . Output only the next line.
assert names.count() == expected
Given snippet: <|code_start|> admin.autodiscover() urlpatterns = [ path('name/', include(urls)), path('admin/', admin.site.urls), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.urls import include, path from django.conf import settings from django.contrib import admin from name import urls import debug_toolbar and context: # Path: name/urls.py which might include code, classes, or functions. Output only the next line.
]
Based on the snippet: <|code_start|> response = self.app.get('/tenders/{}/contracts?acc_token={}'.format( self.tender_id, owner_token)) self.contract_id = response.json['data'][0]['id'] #### Set contract value tender = self.db.get(self.tender_id) for i in tender.get('awards', []): i['complaintPeriod']['endDate'] = i['complaintPeriod']['startDate'] self.db.save(tender) with open('docs/source/tutorial/tender-contract-set-contract-value.http', 'w') as self.app.file_obj: response = self.app.patch_json('/tenders/{}/contracts/{}?acc_token={}'.format( self.tender_id, self.contract_id, owner_token), {"data": {"value": {"amount": 238}}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']['value']['amount'], 238) #### Setting contract signature date # with open('docs/source/tutorial/tender-contract-sign-date.http', 'w') as self.app.file_obj: response = self.app.patch_json('/tenders/{}/contracts/{}?acc_token={}'.format( self.tender_id, self.contract_id, owner_token), {'data': {"dateSigned": get_now().isoformat()} }) self.assertEqual(response.status, '200 OK') #### Setting contract period period_dates = {"period": {"startDate": (get_now()).isoformat(), "endDate": (get_now() + timedelta(days=365)).isoformat()}} with open('docs/source/tutorial/tender-contract-period.http', 'w') as self.app.file_obj: <|code_end|> , predict the immediate next line with the help of imports: import json import os import openprocurement.tender.openua.tests.base as base_test from datetime import timedelta from openprocurement.api.models import get_now from openprocurement.api.tests.base import PrefixedRequestClass from openprocurement.tender.openua.tests.tender import BaseTenderUAWebTest from webtest import TestApp and context (classes, functions, sometimes code) from other files: # Path: openprocurement/tender/openua/tests/tender.py # class TenderUAResourceTestMixin(object): # class TenderUaProcessTestMixin(object): # class TenderUATest(BaseWebTest): # class TenderUAResourceTest(BaseTenderUAWebTest, TenderResourceTestMixin, TenderUAResourceTestMixin): # class TenderUAProcessTest(BaseTenderUAWebTest, TenderUaProcessTestMixin): # def suite(): . Output only the next line.
response = self.app.patch_json('/tenders/{}/contracts/{}?acc_token={}'.format(
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Cancellations', collection_path='/tenders/{tender_id}/cancellations', path='/tenders/{tender_id}/cancellations/{cancellation_id}', procurementMethodType='aboveThresholdUA', description="Tender cancellations") class TenderUaCancellationResource(TenderCancellationResource): def cancel_lot(self, cancellation=None): if not cancellation: cancellation = self.context tender = self.request.validated['tender'] [setattr(i, 'status', 'cancelled') for i in tender.lots if i.id == cancellation.relatedLot] <|code_end|> , determine the next line of code. You have imports: from openprocurement.api.utils import raise_operation_error from openprocurement.tender.core.utils import optendersresource from openprocurement.tender.belowthreshold.views.cancellation import TenderCancellationResource from openprocurement.tender.openua.utils import add_next_award and context (class names, function names, or code) available: # Path: openprocurement/tender/openua/utils.py # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # """Adding next award. # :param request: # The pyramid request object. # :param reverse: # Is used for sorting bids to generate award. # By default (reverse = False) awards are generated from lower to higher by value.amount # When reverse is set to True awards are generated from higher to lower by value.amount # """ # tender = request.validated['tender'] # now = get_now() # if not tender.awardPeriod: # tender.awardPeriod = type(tender).awardPeriod({}) # if not tender.awardPeriod.startDate: # tender.awardPeriod.startDate = now # if tender.lots: # statuses = set() # for lot in tender.lots: # if lot.status != 'active': # continue # lot_awards = [i for i in tender.awards if i.lotID == lot.id] # if lot_awards and lot_awards[-1].status in ['pending', 'active']: # statuses.add(lot_awards[-1].status if lot_awards else 'unsuccessful') # continue # lot_items = [i.id for i in tender.items if i.relatedLot == lot.id] # features = [ # i # for i in (tender.features or []) # if i.featureOf == 'tenderer' or i.featureOf == 'lot' and i.relatedItem == lot.id or i.featureOf == 'item' and i.relatedItem in lot_items # ] # codes = [i.code for i in features] # bids = [ # { # 'id': bid.id, # 'value': [i for i in bid.lotValues if lot.id == i.relatedLot][0].value.serialize(), # 'tenderers': bid.tenderers, # 'parameters': [i for i in bid.parameters if i.code in codes], # 'date': [i for i in bid.lotValues if lot.id == i.relatedLot][0].date # } # for bid in tender.bids # if bid.status == "active" and lot.id in [i.relatedLot for i in bid.lotValues if getattr(i, 'status', "active") == "active"] # ] # if not bids: # lot.status = 'unsuccessful' # statuses.add('unsuccessful') # continue # unsuccessful_awards = [i.bid_id for i in lot_awards if i.status == 'unsuccessful'] # bids = chef(bids, features, unsuccessful_awards, reverse, awarding_criteria_key) # if bids: # bid = bids[0] # award = tender.__class__.awards.model_class({ # 'bid_id': bid['id'], # 'lotID': lot.id, # 'status': 'pending', # 'date': get_now(), # 'value': bid['value'], # 'suppliers': bid['tenderers'], # 'complaintPeriod': { # 'startDate': now.isoformat() # } # }) # award.__parent__ = tender # tender.awards.append(award) # request.response.headers['Location'] = request.route_url('{}:Tender Awards'.format(tender.procurementMethodType), tender_id=tender.id, award_id=award['id']) # statuses.add('pending') # else: # statuses.add('unsuccessful') # if statuses.difference(set(['unsuccessful', 'active'])): # tender.awardPeriod.endDate = None # tender.status = 'active.qualification' # else: # tender.awardPeriod.endDate = now # tender.status = 'active.awarded' # else: # if not tender.awards or tender.awards[-1].status not in ['pending', 'active']: # unsuccessful_awards = [i.bid_id for i in tender.awards if i.status == 'unsuccessful'] # codes = [i.code for i in tender.features or []] # active_bids = [ # { # 'id': bid.id, # 'value': bid.value.serialize(), # 'tenderers': bid.tenderers, # 'parameters': [i for i in bid.parameters if i.code in codes], # 'date': bid.date # } # for bid in tender.bids # if bid.status == "active" # ] # bids = chef(active_bids, tender.features or [], unsuccessful_awards, reverse, awarding_criteria_key) # if bids: # bid = bids[0] # award = tender.__class__.awards.model_class({ # 'bid_id': bid['id'], # 'status': 'pending', # 'date': get_now(), # 'value': bid['value'], # 'suppliers': bid['tenderers'], # 'complaintPeriod': { # 'startDate': get_now().isoformat() # } # }) # award.__parent__ = tender # tender.awards.append(award) # request.response.headers['Location'] = request.route_url('{}:Tender Awards'.format(tender.procurementMethodType), tender_id=tender.id, award_id=award['id']) # if tender.awards[-1].status == 'pending': # tender.awardPeriod.endDate = None # tender.status = 'active.qualification' # else: # tender.awardPeriod.endDate = now # tender.status = 'active.awarded' . Output only the next line.
statuses = set([lot.status for lot in tender.lots])
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Auction', collection_path='/tenders/{tender_id}/auction', path='/tenders/{tender_id}/auction/{auction_lot_id}', <|code_end|> using the current file's imports: from openprocurement.api.utils import ( json_view, context_unpack, ) from openprocurement.tender.core.validation import ( validate_tender_auction_data, ) from openprocurement.tender.core.utils import ( apply_patch, save_tender, optendersresource ) from openprocurement.tender.belowthreshold.views.auction import TenderAuctionResource from openprocurement.tender.openua.utils import add_next_award and any relevant context from other files: # Path: openprocurement/tender/openua/utils.py # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # """Adding next award. # :param request: # The pyramid request object. # :param reverse: # Is used for sorting bids to generate award. # By default (reverse = False) awards are generated from lower to higher by value.amount # When reverse is set to True awards are generated from higher to lower by value.amount # """ # tender = request.validated['tender'] # now = get_now() # if not tender.awardPeriod: # tender.awardPeriod = type(tender).awardPeriod({}) # if not tender.awardPeriod.startDate: # tender.awardPeriod.startDate = now # if tender.lots: # statuses = set() # for lot in tender.lots: # if lot.status != 'active': # continue # lot_awards = [i for i in tender.awards if i.lotID == lot.id] # if lot_awards and lot_awards[-1].status in ['pending', 'active']: # statuses.add(lot_awards[-1].status if lot_awards else 'unsuccessful') # continue # lot_items = [i.id for i in tender.items if i.relatedLot == lot.id] # features = [ # i # for i in (tender.features or []) # if i.featureOf == 'tenderer' or i.featureOf == 'lot' and i.relatedItem == lot.id or i.featureOf == 'item' and i.relatedItem in lot_items # ] # codes = [i.code for i in features] # bids = [ # { # 'id': bid.id, # 'value': [i for i in bid.lotValues if lot.id == i.relatedLot][0].value.serialize(), # 'tenderers': bid.tenderers, # 'parameters': [i for i in bid.parameters if i.code in codes], # 'date': [i for i in bid.lotValues if lot.id == i.relatedLot][0].date # } # for bid in tender.bids # if bid.status == "active" and lot.id in [i.relatedLot for i in bid.lotValues if getattr(i, 'status', "active") == "active"] # ] # if not bids: # lot.status = 'unsuccessful' # statuses.add('unsuccessful') # continue # unsuccessful_awards = [i.bid_id for i in lot_awards if i.status == 'unsuccessful'] # bids = chef(bids, features, unsuccessful_awards, reverse, awarding_criteria_key) # if bids: # bid = bids[0] # award = tender.__class__.awards.model_class({ # 'bid_id': bid['id'], # 'lotID': lot.id, # 'status': 'pending', # 'date': get_now(), # 'value': bid['value'], # 'suppliers': bid['tenderers'], # 'complaintPeriod': { # 'startDate': now.isoformat() # } # }) # award.__parent__ = tender # tender.awards.append(award) # request.response.headers['Location'] = request.route_url('{}:Tender Awards'.format(tender.procurementMethodType), tender_id=tender.id, award_id=award['id']) # statuses.add('pending') # else: # statuses.add('unsuccessful') # if statuses.difference(set(['unsuccessful', 'active'])): # tender.awardPeriod.endDate = None # tender.status = 'active.qualification' # else: # tender.awardPeriod.endDate = now # tender.status = 'active.awarded' # else: # if not tender.awards or tender.awards[-1].status not in ['pending', 'active']: # unsuccessful_awards = [i.bid_id for i in tender.awards if i.status == 'unsuccessful'] # codes = [i.code for i in tender.features or []] # active_bids = [ # { # 'id': bid.id, # 'value': bid.value.serialize(), # 'tenderers': bid.tenderers, # 'parameters': [i for i in bid.parameters if i.code in codes], # 'date': bid.date # } # for bid in tender.bids # if bid.status == "active" # ] # bids = chef(active_bids, tender.features or [], unsuccessful_awards, reverse, awarding_criteria_key) # if bids: # bid = bids[0] # award = tender.__class__.awards.model_class({ # 'bid_id': bid['id'], # 'status': 'pending', # 'date': get_now(), # 'value': bid['value'], # 'suppliers': bid['tenderers'], # 'complaintPeriod': { # 'startDate': get_now().isoformat() # } # }) # award.__parent__ = tender # tender.awards.append(award) # request.response.headers['Location'] = request.route_url('{}:Tender Awards'.format(tender.procurementMethodType), tender_id=tender.id, award_id=award['id']) # if tender.awards[-1].status == 'pending': # tender.awardPeriod.endDate = None # tender.status = 'active.qualification' # else: # tender.awardPeriod.endDate = now # tender.status = 'active.awarded' . Output only the next line.
procurementMethodType='aboveThresholdUA',
Predict the next line for this snippet: <|code_start|> test_post_tender_auction_not_changed = snitch(post_tender_auction_not_changed) test_post_tender_auction_reversed = snitch(post_tender_auction_reversed) class TenderLotAuctionResourceTest(TenderLotAuctionResourceTestMixin, TenderAuctionResourceTest): initial_lots = test_lots initial_data = test_tender_data class TenderMultipleLotAuctionResourceTest(TenderMultipleLotAuctionResourceTestMixin, TenderAuctionResourceTest): initial_lots = 2 * test_lots test_patch_tender_auction = snitch(patch_tender_lots_auction) class TenderFeaturesAuctionResourceTest(BaseTenderUAContentWebTest): initial_data = test_features_tender_ua_data initial_status = 'active.tendering' initial_bids = [ { "parameters": [ { "code": i["code"], "value": 0.1, } for i in test_features_tender_data['features'] ], "tenderers": [ test_organization <|code_end|> with the help of current file imports: import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import ( test_features_tender_data, test_lots, test_organization ) from openprocurement.tender.belowthreshold.tests.auction import ( TenderAuctionResourceTestMixin, TenderLotAuctionResourceTestMixin, TenderMultipleLotAuctionResourceTestMixin ) from openprocurement.tender.belowthreshold.tests.auction_blanks import ( # TenderSameValueAuctionResourceTest post_tender_auction_not_changed, post_tender_auction_reversed, # TenderMultipleLotAuctionResourceTest patch_tender_lots_auction, # TenderFeaturesAuctionResourceTest get_tender_auction_feature, post_tender_auction_feature, # TenderFeaturesLotAuctionResourceTest get_tender_lot_auction_features, post_tender_lot_auction_features, # TenderFeaturesMultilotAuctionResourceTest get_tender_lots_auction_features, post_tender_lots_auction_features ) from openprocurement.tender.openua.tests.base import ( BaseTenderUAContentWebTest, test_tender_data, test_features_tender_ua_data, test_bids ) and context from other files: # Path: openprocurement/tender/openua/tests/base.py # class BaseTenderUAWebTest(BaseTenderWebTest): # class BaseTenderUAContentWebTest(BaseTenderUAWebTest): # def go_to_enquiryPeriod_end(self): # def set_status(self, status, extra=None): # def setUp(self): , which may contain function names, class names, or code. Output only the next line.
],
Continue the code snippet: <|code_start|> "code": i["code"], "value": 0.15, } for i in test_features_tender_data['features'] ], "tenderers": [ test_organization ], "value": { "amount": 479, "currency": "UAH", "valueAddedTaxIncluded": True }, 'selfEligible': True, 'selfQualified': True, } ] test_get_tender_auction = snitch(get_tender_auction_feature) test_post_tender_auction = snitch(post_tender_auction_feature) class TenderFeaturesLotAuctionResourceTest(TenderLotAuctionResourceTestMixin, TenderFeaturesAuctionResourceTest): initial_lots = test_lots test_get_tender_auction = snitch(get_tender_lot_auction_features) test_post_tender_auction = snitch(post_tender_lot_auction_features) class TenderFeaturesMultilotAuctionResourceTest(TenderMultipleLotAuctionResourceTestMixin, TenderFeaturesAuctionResourceTest): <|code_end|> . Use current file imports: import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import ( test_features_tender_data, test_lots, test_organization ) from openprocurement.tender.belowthreshold.tests.auction import ( TenderAuctionResourceTestMixin, TenderLotAuctionResourceTestMixin, TenderMultipleLotAuctionResourceTestMixin ) from openprocurement.tender.belowthreshold.tests.auction_blanks import ( # TenderSameValueAuctionResourceTest post_tender_auction_not_changed, post_tender_auction_reversed, # TenderMultipleLotAuctionResourceTest patch_tender_lots_auction, # TenderFeaturesAuctionResourceTest get_tender_auction_feature, post_tender_auction_feature, # TenderFeaturesLotAuctionResourceTest get_tender_lot_auction_features, post_tender_lot_auction_features, # TenderFeaturesMultilotAuctionResourceTest get_tender_lots_auction_features, post_tender_lots_auction_features ) from openprocurement.tender.openua.tests.base import ( BaseTenderUAContentWebTest, test_tender_data, test_features_tender_ua_data, test_bids ) and context (classes, functions, or code) from other files: # Path: openprocurement/tender/openua/tests/base.py # class BaseTenderUAWebTest(BaseTenderWebTest): # class BaseTenderUAContentWebTest(BaseTenderUAWebTest): # def go_to_enquiryPeriod_end(self): # def set_status(self, status, extra=None): # def setUp(self): . Output only the next line.
initial_lots = test_lots * 2
Given snippet: <|code_start|> }, 'selfEligible': True, 'selfQualified': True, } for i in range(3) ] test_post_tender_auction_not_changed = snitch(post_tender_auction_not_changed) test_post_tender_auction_reversed = snitch(post_tender_auction_reversed) class TenderLotAuctionResourceTest(TenderLotAuctionResourceTestMixin, TenderAuctionResourceTest): initial_lots = test_lots initial_data = test_tender_data class TenderMultipleLotAuctionResourceTest(TenderMultipleLotAuctionResourceTestMixin, TenderAuctionResourceTest): initial_lots = 2 * test_lots test_patch_tender_auction = snitch(patch_tender_lots_auction) class TenderFeaturesAuctionResourceTest(BaseTenderUAContentWebTest): initial_data = test_features_tender_ua_data initial_status = 'active.tendering' initial_bids = [ { "parameters": [ { "code": i["code"], "value": 0.1, <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import ( test_features_tender_data, test_lots, test_organization ) from openprocurement.tender.belowthreshold.tests.auction import ( TenderAuctionResourceTestMixin, TenderLotAuctionResourceTestMixin, TenderMultipleLotAuctionResourceTestMixin ) from openprocurement.tender.belowthreshold.tests.auction_blanks import ( # TenderSameValueAuctionResourceTest post_tender_auction_not_changed, post_tender_auction_reversed, # TenderMultipleLotAuctionResourceTest patch_tender_lots_auction, # TenderFeaturesAuctionResourceTest get_tender_auction_feature, post_tender_auction_feature, # TenderFeaturesLotAuctionResourceTest get_tender_lot_auction_features, post_tender_lot_auction_features, # TenderFeaturesMultilotAuctionResourceTest get_tender_lots_auction_features, post_tender_lots_auction_features ) from openprocurement.tender.openua.tests.base import ( BaseTenderUAContentWebTest, test_tender_data, test_features_tender_ua_data, test_bids ) and context: # Path: openprocurement/tender/openua/tests/base.py # class BaseTenderUAWebTest(BaseTenderWebTest): # class BaseTenderUAContentWebTest(BaseTenderUAWebTest): # def go_to_enquiryPeriod_end(self): # def set_status(self, status, extra=None): # def setUp(self): which might include code, classes, or functions. Output only the next line.
}
Given snippet: <|code_start|> "currency": "UAH", "valueAddedTaxIncluded": True }, 'selfEligible': True, 'selfQualified': True, } ] test_get_tender_auction = snitch(get_tender_auction_feature) test_post_tender_auction = snitch(post_tender_auction_feature) class TenderFeaturesLotAuctionResourceTest(TenderLotAuctionResourceTestMixin, TenderFeaturesAuctionResourceTest): initial_lots = test_lots test_get_tender_auction = snitch(get_tender_lot_auction_features) test_post_tender_auction = snitch(post_tender_lot_auction_features) class TenderFeaturesMultilotAuctionResourceTest(TenderMultipleLotAuctionResourceTestMixin, TenderFeaturesAuctionResourceTest): initial_lots = test_lots * 2 test_get_tender_auction = snitch(get_tender_lots_auction_features) test_post_tender_auction = snitch(post_tender_lots_auction_features) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TenderAuctionResourceTest)) suite.addTest(unittest.makeSuite(TenderSameValueAuctionResourceTest)) suite.addTest(unittest.makeSuite(TenderFeaturesAuctionResourceTest)) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import ( test_features_tender_data, test_lots, test_organization ) from openprocurement.tender.belowthreshold.tests.auction import ( TenderAuctionResourceTestMixin, TenderLotAuctionResourceTestMixin, TenderMultipleLotAuctionResourceTestMixin ) from openprocurement.tender.belowthreshold.tests.auction_blanks import ( # TenderSameValueAuctionResourceTest post_tender_auction_not_changed, post_tender_auction_reversed, # TenderMultipleLotAuctionResourceTest patch_tender_lots_auction, # TenderFeaturesAuctionResourceTest get_tender_auction_feature, post_tender_auction_feature, # TenderFeaturesLotAuctionResourceTest get_tender_lot_auction_features, post_tender_lot_auction_features, # TenderFeaturesMultilotAuctionResourceTest get_tender_lots_auction_features, post_tender_lots_auction_features ) from openprocurement.tender.openua.tests.base import ( BaseTenderUAContentWebTest, test_tender_data, test_features_tender_ua_data, test_bids ) and context: # Path: openprocurement/tender/openua/tests/base.py # class BaseTenderUAWebTest(BaseTenderWebTest): # class BaseTenderUAContentWebTest(BaseTenderUAWebTest): # def go_to_enquiryPeriod_end(self): # def set_status(self, status, extra=None): # def setUp(self): which might include code, classes, or functions. Output only the next line.
suite.addTest(unittest.makeSuite(TenderFeaturesLotAuctionResourceTest))
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Bids', collection_path='/tenders/{tender_id}/bids', path='/tenders/{tender_id}/bids/{bid_id}', <|code_end|> . Use current file imports: from openprocurement.tender.belowthreshold.views.bid import TenderBidResource from openprocurement.api.utils import ( set_ownership, json_view, context_unpack, get_now, raise_operation_error ) from openprocurement.tender.core.validation import ( validate_bid_data, validate_patch_bid_data, validate_update_deleted_bid, validate_bid_operation_period, validate_bid_operation_not_in_tendering ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource ) from openprocurement.tender.openua.validation import ( validate_update_bid_to_draft, validate_update_bid_to_active_status ) and context (classes, functions, or code) from other files: # Path: openprocurement/tender/openua/validation.py # def validate_update_bid_to_draft(request): # bid_status_to = request.validated['data'].get("status", request.context.status) # if request.context.status != 'draft' and bid_status_to == 'draft': # request.errors.add('body', 'bid', 'Can\'t update bid to ({}) status'.format(bid_status_to)) # request.errors.status = 403 # raise error_handler(request.errors) # # def validate_update_bid_to_active_status(request): # bid_status_to = request.validated['data'].get("status", request.context.status) # if bid_status_to != request.context.status and bid_status_to != 'active': # request.errors.add('body', 'bid', 'Can\'t update bid to ({}) status'.format(bid_status_to)) # request.errors.status = 403 # raise error_handler(request.errors) . Output only the next line.
procurementMethodType='aboveThresholdUA',
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Complaint Documents', collection_path='/tenders/{tender_id}/complaints/{complaint_id}/documents', path='/tenders/{tender_id}/complaints/{complaint_id}/documents/{document_id}', procurementMethodType='aboveThresholdUA', description="Tender complaint documents") class TenderUaComplaintDocumentResource(TenderComplaintDocumentResource): @json_view(validators=(validate_file_upload, validate_complaint_document_operation_not_in_allowed_status, validate_status_and_role_for_complaint_document_operation), permission='edit_complaint') <|code_end|> , generate the next line using the imports in this file: from openprocurement.api.utils import ( upload_file, update_file_content_type, json_view, context_unpack, ) from openprocurement.api.validation import ( validate_file_update, validate_file_upload, validate_patch_document_data, ) from openprocurement.tender.core.validation import ( validate_complaint_document_update_not_by_author, validate_status_and_role_for_complaint_document_operation ) from openprocurement.tender.core.utils import ( save_tender, optendersresource, apply_patch ) from openprocurement.tender.belowthreshold.views.complaint_document import TenderComplaintDocumentResource from openprocurement.tender.openua.validation import ( validate_complaint_document_operation_not_in_allowed_status ) and context (functions, classes, or occasionally code) from other files: # Path: openprocurement/tender/openua/validation.py # def validate_complaint_document_operation_not_in_allowed_status(request): # if request.validated['tender_status'] not in ['active.tendering']: # raise_operation_error(request, 'Can\'t {} document in current ({}) tender status'.format(OPERATIONS.get(request.method), request.validated['tender_status'])) . Output only the next line.
def collection_post(self):
Continue the code snippet: <|code_start|> response = self.app.post_json( request_path, {'not_data': {}}, status=422) self.assertEqual(response.status, '422 Unprocessable Entity') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['status'], 'error') self.assertEqual(response.json['errors'], [ {u'description': u'Data not available', u'location': u'body', u'name': u'data'} ]) response = self.app.post_json(request_path, {'data': { 'invalid_field': 'invalid_value'}}, status=422) self.assertEqual(response.status, '422 Unprocessable Entity') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['status'], 'error') self.assertEqual(response.json['errors'], [ {u'description': u'Rogue field', u'location': u'body', u'name': u'invalid_field'} ]) response = self.app.post_json(request_path, { 'data': {'selfEligible': True, 'selfQualified': True, 'tenderers': [{'identifier': 'invalid_value'}]}}, status=422) self.assertEqual(response.status, '422 Unprocessable Entity') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['status'], 'error') self.assertEqual(response.json['errors'], [ {u'description': {u'identifier': [ u'Please use a mapping for this field or Identifier instance instead of unicode.']}, u'location': u'body', u'name': u'tenderers'} <|code_end|> . Use current file imports: from copy import deepcopy from datetime import timedelta from openprocurement.tender.belowthreshold.tests.base import ( test_organization, now ) from openprocurement.tender.openua.tests.base import ( test_bids ) and context (classes, functions, or code) from other files: # Path: openprocurement/tender/openua/tests/base.py # class BaseTenderUAWebTest(BaseTenderWebTest): # class BaseTenderUAContentWebTest(BaseTenderUAWebTest): # def go_to_enquiryPeriod_end(self): # def set_status(self, status, extra=None): # def setUp(self): . Output only the next line.
])
Given the code snippet: <|code_start|> @optendersresource(name='aboveThresholdUA:Tender Documents', collection_path='/tenders/{tender_id}/documents', path='/tenders/{tender_id}/documents/{document_id}', <|code_end|> , generate the next line using the imports in this file: from openprocurement.api.utils import ( upload_file, context_unpack, json_view, update_file_content_type, get_now, error_handler, raise_operation_error ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource, calculate_business_date ) from openprocurement.api.validation import validate_file_upload, validate_file_update, validate_patch_document_data from openprocurement.tender.core.validation import ( validate_document_operation_in_not_allowed_period, validate_tender_document_update_not_by_author_or_tender_owner ) from openprocurement.tender.belowthreshold.views.tender_document import TenderDocumentResource from openprocurement.tender.openua.constants import TENDERING_EXTRA_PERIOD and context (functions, classes, or occasionally code) from other files: # Path: openprocurement/tender/openua/constants.py # TENDERING_EXTRA_PERIOD = timedelta(days=7) . Output only the next line.
procurementMethodType='aboveThresholdUA',
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Complaints', collection_path='/tenders/{tender_id}/complaints', path='/tenders/{tender_id}/complaints/{complaint_id}', procurementMethodType='aboveThresholdUA', <|code_end|> , predict the immediate next line with the help of imports: from openprocurement.tender.belowthreshold.views.complaint import TenderComplaintResource from openprocurement.api.utils import ( context_unpack, json_view, set_ownership, get_now, raise_operation_error ) from openprocurement.tender.openua.utils import ( check_tender_status, ) from openprocurement.tender.core.validation import ( validate_complaint_data, validate_submit_complaint_time, validate_patch_complaint_data, validate_complaint_operation_not_in_active_tendering, validate_update_complaint_not_in_allowed_complaint_status ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource, calculate_business_date ) from openprocurement.tender.openua.validation import validate_submit_claim_time from openprocurement.tender.openua.constants import ( CLAIM_SUBMIT_TIME, COMPLAINT_SUBMIT_TIME ) and context (classes, functions, sometimes code) from other files: # Path: openprocurement/tender/openua/utils.py # PKG = get_distribution(__package__) # LOGGER = getLogger(PKG.project_name) # def calculate_normalized_date(dt, tender, ceil=False): # def check_bids(request): # def check_complaint_status(request, complaint): # def check_status(request): # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # # Path: openprocurement/tender/openua/validation.py # def validate_submit_claim_time(request): # tender = request.context # claim_submit_time = request.content_configurator.tender_claim_submit_time # if get_now() > calculate_business_date(tender.tenderPeriod.endDate, -claim_submit_time, tender): # raise_operation_error(request, 'Can submit claim not later than {0.days} days before tenderPeriod end'.format(claim_submit_time)) # # Path: openprocurement/tender/openua/constants.py # CLAIM_SUBMIT_TIME = timedelta(days=10) # # COMPLAINT_SUBMIT_TIME = timedelta(days=4) . Output only the next line.
description="Tender complaints")
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Complaints', collection_path='/tenders/{tender_id}/complaints', path='/tenders/{tender_id}/complaints/{complaint_id}', procurementMethodType='aboveThresholdUA', <|code_end|> with the help of current file imports: from openprocurement.tender.belowthreshold.views.complaint import TenderComplaintResource from openprocurement.api.utils import ( context_unpack, json_view, set_ownership, get_now, raise_operation_error ) from openprocurement.tender.openua.utils import ( check_tender_status, ) from openprocurement.tender.core.validation import ( validate_complaint_data, validate_submit_complaint_time, validate_patch_complaint_data, validate_complaint_operation_not_in_active_tendering, validate_update_complaint_not_in_allowed_complaint_status ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource, calculate_business_date ) from openprocurement.tender.openua.validation import validate_submit_claim_time from openprocurement.tender.openua.constants import ( CLAIM_SUBMIT_TIME, COMPLAINT_SUBMIT_TIME ) and context from other files: # Path: openprocurement/tender/openua/utils.py # PKG = get_distribution(__package__) # LOGGER = getLogger(PKG.project_name) # def calculate_normalized_date(dt, tender, ceil=False): # def check_bids(request): # def check_complaint_status(request, complaint): # def check_status(request): # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # # Path: openprocurement/tender/openua/validation.py # def validate_submit_claim_time(request): # tender = request.context # claim_submit_time = request.content_configurator.tender_claim_submit_time # if get_now() > calculate_business_date(tender.tenderPeriod.endDate, -claim_submit_time, tender): # raise_operation_error(request, 'Can submit claim not later than {0.days} days before tenderPeriod end'.format(claim_submit_time)) # # Path: openprocurement/tender/openua/constants.py # CLAIM_SUBMIT_TIME = timedelta(days=10) # # COMPLAINT_SUBMIT_TIME = timedelta(days=4) , which may contain function names, class names, or code. Output only the next line.
description="Tender complaints")
Given snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Complaints', collection_path='/tenders/{tender_id}/complaints', path='/tenders/{tender_id}/complaints/{complaint_id}', procurementMethodType='aboveThresholdUA', description="Tender complaints") class TenderUaComplaintResource(TenderComplaintResource): def complaints_len(self, tender): return sum([len(i.complaints) for i in tender.awards], len(tender.complaints)) @json_view(content_type="application/json", validators=(validate_complaint_data, validate_complaint_operation_not_in_active_tendering), permission='create_complaint') <|code_end|> , continue by predicting the next line. Consider current file imports: from openprocurement.tender.belowthreshold.views.complaint import TenderComplaintResource from openprocurement.api.utils import ( context_unpack, json_view, set_ownership, get_now, raise_operation_error ) from openprocurement.tender.openua.utils import ( check_tender_status, ) from openprocurement.tender.core.validation import ( validate_complaint_data, validate_submit_complaint_time, validate_patch_complaint_data, validate_complaint_operation_not_in_active_tendering, validate_update_complaint_not_in_allowed_complaint_status ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource, calculate_business_date ) from openprocurement.tender.openua.validation import validate_submit_claim_time from openprocurement.tender.openua.constants import ( CLAIM_SUBMIT_TIME, COMPLAINT_SUBMIT_TIME ) and context: # Path: openprocurement/tender/openua/utils.py # PKG = get_distribution(__package__) # LOGGER = getLogger(PKG.project_name) # def calculate_normalized_date(dt, tender, ceil=False): # def check_bids(request): # def check_complaint_status(request, complaint): # def check_status(request): # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # # Path: openprocurement/tender/openua/validation.py # def validate_submit_claim_time(request): # tender = request.context # claim_submit_time = request.content_configurator.tender_claim_submit_time # if get_now() > calculate_business_date(tender.tenderPeriod.endDate, -claim_submit_time, tender): # raise_operation_error(request, 'Can submit claim not later than {0.days} days before tenderPeriod end'.format(claim_submit_time)) # # Path: openprocurement/tender/openua/constants.py # CLAIM_SUBMIT_TIME = timedelta(days=10) # # COMPLAINT_SUBMIT_TIME = timedelta(days=4) which might include code, classes, or functions. Output only the next line.
def collection_post(self):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class TenderDocumentResourceTest(BaseTenderUAContentWebTest, TenderDocumentResourceTestMixin): docservice = False class TenderDocumentWithDSResourceTest(TenderDocumentResourceTest, TenderDocumentWithDSResourceTestMixin): docservice = True def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TenderDocumentResourceTest)) suite.addTest(unittest.makeSuite(TenderDocumentWithDSResourceTest)) <|code_end|> , predict the next line using imports from the current file: import unittest from openprocurement.tender.openua.tests.base import BaseTenderUAContentWebTest from openprocurement.tender.belowthreshold.tests.document import ( TenderDocumentResourceTestMixin, TenderDocumentWithDSResourceTestMixin ) and context including class names, function names, and sometimes code from other files: # Path: openprocurement/tender/openua/tests/base.py # class BaseTenderUAContentWebTest(BaseTenderUAWebTest): # initial_data = test_tender_data # initial_status = None # initial_bids = None # initial_lots = None # # def setUp(self): # super(BaseTenderUAContentWebTest, self).setUp() # self.create_tender() . Output only the next line.
return suite
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Contracts', collection_path='/tenders/{tender_id}/contracts', path='/tenders/{tender_id}/contracts/{contract_id}', procurementMethodType='aboveThresholdUA', description="Tender contracts") <|code_end|> , predict the immediate next line with the help of imports: from openprocurement.tender.belowthreshold.views.contract import TenderAwardContractResource from openprocurement.api.utils import ( context_unpack, json_view, get_now, raise_operation_error ) from openprocurement.tender.openua.utils import check_tender_status from openprocurement.tender.core.validation import ( validate_contract_signing, validate_patch_contract_data, validate_update_contract_value, validate_update_contract_only_for_active_lots, validate_contract_operation_not_in_allowed_status ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource ) from openprocurement.tender.openua.validation import validate_contract_update_with_accepted_complaint and context (classes, functions, sometimes code) from other files: # Path: openprocurement/tender/openua/utils.py # PKG = get_distribution(__package__) # LOGGER = getLogger(PKG.project_name) # def calculate_normalized_date(dt, tender, ceil=False): # def check_bids(request): # def check_complaint_status(request, complaint): # def check_status(request): # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # # Path: openprocurement/tender/openua/validation.py # def validate_contract_update_with_accepted_complaint(request): # tender = request.validated['tender'] # if any([any([c.status == 'accepted' for c in i.complaints]) for i in tender.awards if i.lotID in [a.lotID for a in tender.awards if a.id == request.context.awardID]]): # raise_operation_error(request, 'Can\'t update contract with accepted complaint') . Output only the next line.
class TenderUaAwardContractResource(TenderAwardContractResource):
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @optendersresource(name='aboveThresholdUA:Tender Contracts', collection_path='/tenders/{tender_id}/contracts', path='/tenders/{tender_id}/contracts/{contract_id}', procurementMethodType='aboveThresholdUA', description="Tender contracts") class TenderUaAwardContractResource(TenderAwardContractResource): <|code_end|> . Write the next line using the current file imports: from openprocurement.tender.belowthreshold.views.contract import TenderAwardContractResource from openprocurement.api.utils import ( context_unpack, json_view, get_now, raise_operation_error ) from openprocurement.tender.openua.utils import check_tender_status from openprocurement.tender.core.validation import ( validate_contract_signing, validate_patch_contract_data, validate_update_contract_value, validate_update_contract_only_for_active_lots, validate_contract_operation_not_in_allowed_status ) from openprocurement.tender.core.utils import ( save_tender, apply_patch, optendersresource ) from openprocurement.tender.openua.validation import validate_contract_update_with_accepted_complaint and context from other files: # Path: openprocurement/tender/openua/utils.py # PKG = get_distribution(__package__) # LOGGER = getLogger(PKG.project_name) # def calculate_normalized_date(dt, tender, ceil=False): # def check_bids(request): # def check_complaint_status(request, complaint): # def check_status(request): # def add_next_award(request, reverse=False, awarding_criteria_key='amount'): # # Path: openprocurement/tender/openua/validation.py # def validate_contract_update_with_accepted_complaint(request): # tender = request.validated['tender'] # if any([any([c.status == 'accepted' for c in i.complaints]) for i in tender.awards if i.lotID in [a.lotID for a in tender.awards if a.id == request.context.awardID]]): # raise_operation_error(request, 'Can\'t update contract with accepted complaint') , which may include functions, classes, or code. Output only the next line.
@json_view(content_type="application/json", permission='edit_tender', validators=(validate_patch_contract_data, validate_contract_operation_not_in_allowed_status,
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- PKG = get_distribution(__package__) LOGGER = getLogger(PKG.project_name) def calculate_normalized_date(dt, tender, ceil=False): if (tender.revisions[0].date if tender.revisions else get_now()) > NORMALIZED_COMPLAINT_PERIOD_FROM and \ not (SANDBOX_MODE and tender.procurementMethodDetails): if ceil: return dt.astimezone(TZ).replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1) return dt.astimezone(TZ).replace(hour=0, minute=0, second=0, microsecond=0) return dt def check_bids(request): tender = request.validated['tender'] if tender.lots: [setattr(i.auctionPeriod, 'startDate', None) for i in tender.lots if i.numberOfBids < 2 and i.auctionPeriod and i.auctionPeriod.startDate] [setattr(i, 'status', 'unsuccessful') for i in tender.lots if i.numberOfBids < 2 and i.status == 'active'] if not set([i.status for i in tender.lots]).difference(set(['unsuccessful', 'cancelled'])): tender.status = 'unsuccessful' else: if tender.numberOfBids < 2: if tender.auctionPeriod and tender.auctionPeriod.startDate: tender.auctionPeriod.startDate = None tender.status = 'unsuccessful' def check_complaint_status(request, complaint): if complaint.status == 'answered': <|code_end|> , predict the immediate next line with the help of imports: from pkg_resources import get_distribution from datetime import timedelta from logging import getLogger from openprocurement.api.utils import get_now from openprocurement.api.constants import TZ, SANDBOX_MODE from openprocurement.tender.core.utils import ( has_unanswered_questions, has_unanswered_complaints, remove_draft_bids ) from openprocurement.tender.belowthreshold.utils import ( check_tender_status, context_unpack, ) from openprocurement.tender.openua.constants import ( NORMALIZED_COMPLAINT_PERIOD_FROM ) from barbecue import chef and context (classes, functions, sometimes code) from other files: # Path: openprocurement/tender/openua/constants.py # NORMALIZED_COMPLAINT_PERIOD_FROM = datetime(2016, 7, 14, tzinfo=TZ) . Output only the next line.
complaint.status = complaint.resolutionType
Predict the next line for this snippet: <|code_start|> ["Python", "scikit-learn", "scipy", "numpy", "statsmodels", "pandas"], ["R", "Python", "statistics", "regression", "probability"], ["machine learning", "regression", "decision trees", "libsvm"], ["Python", "R", "Java", "C++", "Haskell", "programming languages"], ["statistics", "probability", "mathematics", "theory"], ["machine learning", "scikit-learn", "Mahout", "neural networks"], ["neural networks", "deep learning", "Big Data", "artificial intelligence"], ["Hadoop", "Java", "MapReduce", "Big Data"], ["statistics", "R", "statsmodels"], ["C++", "deep learning", "artificial intelligence", "probability"], ["pandas", "R", "Python"], ["databases", "HBase", "Postgres", "MySQL", "MongoDB"], ["libsvm", "regression", "support vector machines"] ] popular_interests = Counter(interest for user_interests in users_interests for interest in user_interests) def most_popular_new_interests( user_interests: List[str], max_results: int = 5) -> List[Tuple[str, int]]: suggestions = [(interest, frequency) for interest, frequency in popular_interests.most_common() if interest not in user_interests] return suggestions[:max_results] unique_interests = sorted({interest <|code_end|> with the help of current file imports: from collections import Counter from typing import Dict, List, Tuple from scratch.nlp import cosine_similarity from collections import defaultdict from typing import NamedTuple from scratch.deep_learning import random_tensor from typing import List from scratch.linear_algebra import dot from scratch.working_with_data import pca, transform import csv import re import random import tqdm and context from other files: # Path: scratch/nlp.py # def cosine_similarity(v1: Vector, v2: Vector) -> float: # return dot(v1, v2) / math.sqrt(dot(v1, v1) * dot(v2, v2)) , which may contain function names, class names, or code. Output only the next line.
for user_interests in users_interests
Continue the code snippet: <|code_start|> def num_differences(v1: Vector, v2: Vector) -> int: assert len(v1) == len(v2) return len([x1 for x1, x2 in zip(v1, v2) if x1 != x2]) assert num_differences([1, 2, 3], [2, 1, 3]) == 2 assert num_differences([1, 2], [1, 2]) == 0 def cluster_means(k: int, inputs: List[Vector], assignments: List[int]) -> List[Vector]: # clusters[i] contains the inputs whose assignment is i <|code_end|> . Use current file imports: from scratch.linear_algebra import Vector from typing import List from scratch.linear_algebra import vector_mean from scratch.linear_algebra import squared_distance from typing import NamedTuple, Union from typing import Callable from scratch.linear_algebra import distance from typing import Tuple from matplotlib import pyplot as plt import itertools import random import tqdm import matplotlib.image as mpimg and context (classes, functions, or code) from other files: # Path: scratch/linear_algebra.py # def add(v: Vector, w: Vector) -> Vector: # def subtract(v: Vector, w: Vector) -> Vector: # def vector_sum(vectors: List[Vector]) -> Vector: # def scalar_multiply(c: float, v: Vector) -> Vector: # def vector_mean(vectors: List[Vector]) -> Vector: # def dot(v: Vector, w: Vector) -> float: # def sum_of_squares(v: Vector) -> float: # def magnitude(v: Vector) -> float: # def squared_distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # type: ignore # def shape(A: Matrix) -> Tuple[int, int]: # def get_row(A: Matrix, i: int) -> Vector: # def get_column(A: Matrix, j: int) -> Vector: # def make_matrix(num_rows: int, # num_cols: int, # entry_fn: Callable[[int, int], float]) -> Matrix: # def identity_matrix(n: int) -> Matrix: # A = [[1, 2, 3], # A has 2 rows and 3 columns # [4, 5, 6]] # B = [[1, 2], # B has 3 rows and 2 columns # [3, 4], # [5, 6]] # # Path: scratch/linear_algebra.py # def vector_mean(vectors: List[Vector]) -> Vector: # """Computes the element-wise average""" # n = len(vectors) # return scalar_multiply(1/n, vector_sum(vectors)) # # Path: scratch/linear_algebra.py # def squared_distance(v: Vector, w: Vector) -> float: # """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" # return sum_of_squares(subtract(v, w)) # # Path: scratch/linear_algebra.py # def distance(v: Vector, w: Vector) -> float: # """Computes the distance between v and w""" # return math.sqrt(squared_distance(v, w)) . Output only the next line.
clusters = [[] for i in range(k)]
Here is a snippet: <|code_start|> def num_differences(v1: Vector, v2: Vector) -> int: assert len(v1) == len(v2) return len([x1 for x1, x2 in zip(v1, v2) if x1 != x2]) assert num_differences([1, 2, 3], [2, 1, 3]) == 2 <|code_end|> . Write the next line using the current file imports: from scratch.linear_algebra import Vector from typing import List from scratch.linear_algebra import vector_mean from scratch.linear_algebra import squared_distance from typing import NamedTuple, Union from typing import Callable from scratch.linear_algebra import distance from typing import Tuple from matplotlib import pyplot as plt import itertools import random import tqdm import matplotlib.image as mpimg and context from other files: # Path: scratch/linear_algebra.py # def add(v: Vector, w: Vector) -> Vector: # def subtract(v: Vector, w: Vector) -> Vector: # def vector_sum(vectors: List[Vector]) -> Vector: # def scalar_multiply(c: float, v: Vector) -> Vector: # def vector_mean(vectors: List[Vector]) -> Vector: # def dot(v: Vector, w: Vector) -> float: # def sum_of_squares(v: Vector) -> float: # def magnitude(v: Vector) -> float: # def squared_distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # type: ignore # def shape(A: Matrix) -> Tuple[int, int]: # def get_row(A: Matrix, i: int) -> Vector: # def get_column(A: Matrix, j: int) -> Vector: # def make_matrix(num_rows: int, # num_cols: int, # entry_fn: Callable[[int, int], float]) -> Matrix: # def identity_matrix(n: int) -> Matrix: # A = [[1, 2, 3], # A has 2 rows and 3 columns # [4, 5, 6]] # B = [[1, 2], # B has 3 rows and 2 columns # [3, 4], # [5, 6]] # # Path: scratch/linear_algebra.py # def vector_mean(vectors: List[Vector]) -> Vector: # """Computes the element-wise average""" # n = len(vectors) # return scalar_multiply(1/n, vector_sum(vectors)) # # Path: scratch/linear_algebra.py # def squared_distance(v: Vector, w: Vector) -> float: # """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" # return sum_of_squares(subtract(v, w)) # # Path: scratch/linear_algebra.py # def distance(v: Vector, w: Vector) -> float: # """Computes the distance between v and w""" # return math.sqrt(squared_distance(v, w)) , which may include functions, classes, or code. Output only the next line.
assert num_differences([1, 2], [1, 2]) == 0
Given the following code snippet before the placeholder: <|code_start|> def num_differences(v1: Vector, v2: Vector) -> int: assert len(v1) == len(v2) return len([x1 for x1, x2 in zip(v1, v2) if x1 != x2]) assert num_differences([1, 2, 3], [2, 1, 3]) == 2 assert num_differences([1, 2], [1, 2]) == 0 def cluster_means(k: int, inputs: List[Vector], assignments: List[int]) -> List[Vector]: # clusters[i] contains the inputs whose assignment is i clusters = [[] for i in range(k)] for input, assignment in zip(inputs, assignments): clusters[assignment].append(input) # if a cluster is empty, just use a random point return [vector_mean(cluster) if cluster else random.choice(inputs) for cluster in clusters] class KMeans: def __init__(self, k: int) -> None: self.k = k # number of clusters <|code_end|> , predict the next line using imports from the current file: from scratch.linear_algebra import Vector from typing import List from scratch.linear_algebra import vector_mean from scratch.linear_algebra import squared_distance from typing import NamedTuple, Union from typing import Callable from scratch.linear_algebra import distance from typing import Tuple from matplotlib import pyplot as plt import itertools import random import tqdm import matplotlib.image as mpimg and context including class names, function names, and sometimes code from other files: # Path: scratch/linear_algebra.py # def add(v: Vector, w: Vector) -> Vector: # def subtract(v: Vector, w: Vector) -> Vector: # def vector_sum(vectors: List[Vector]) -> Vector: # def scalar_multiply(c: float, v: Vector) -> Vector: # def vector_mean(vectors: List[Vector]) -> Vector: # def dot(v: Vector, w: Vector) -> float: # def sum_of_squares(v: Vector) -> float: # def magnitude(v: Vector) -> float: # def squared_distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # type: ignore # def shape(A: Matrix) -> Tuple[int, int]: # def get_row(A: Matrix, i: int) -> Vector: # def get_column(A: Matrix, j: int) -> Vector: # def make_matrix(num_rows: int, # num_cols: int, # entry_fn: Callable[[int, int], float]) -> Matrix: # def identity_matrix(n: int) -> Matrix: # A = [[1, 2, 3], # A has 2 rows and 3 columns # [4, 5, 6]] # B = [[1, 2], # B has 3 rows and 2 columns # [3, 4], # [5, 6]] # # Path: scratch/linear_algebra.py # def vector_mean(vectors: List[Vector]) -> Vector: # """Computes the element-wise average""" # n = len(vectors) # return scalar_multiply(1/n, vector_sum(vectors)) # # Path: scratch/linear_algebra.py # def squared_distance(v: Vector, w: Vector) -> float: # """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" # return sum_of_squares(subtract(v, w)) # # Path: scratch/linear_algebra.py # def distance(v: Vector, w: Vector) -> float: # """Computes the distance between v and w""" # return math.sqrt(squared_distance(v, w)) . Output only the next line.
self.means = None
Given the following code snippet before the placeholder: <|code_start|> def num_differences(v1: Vector, v2: Vector) -> int: assert len(v1) == len(v2) return len([x1 for x1, x2 in zip(v1, v2) if x1 != x2]) <|code_end|> , predict the next line using imports from the current file: from scratch.linear_algebra import Vector from typing import List from scratch.linear_algebra import vector_mean from scratch.linear_algebra import squared_distance from typing import NamedTuple, Union from typing import Callable from scratch.linear_algebra import distance from typing import Tuple from matplotlib import pyplot as plt import itertools import random import tqdm import matplotlib.image as mpimg and context including class names, function names, and sometimes code from other files: # Path: scratch/linear_algebra.py # def add(v: Vector, w: Vector) -> Vector: # def subtract(v: Vector, w: Vector) -> Vector: # def vector_sum(vectors: List[Vector]) -> Vector: # def scalar_multiply(c: float, v: Vector) -> Vector: # def vector_mean(vectors: List[Vector]) -> Vector: # def dot(v: Vector, w: Vector) -> float: # def sum_of_squares(v: Vector) -> float: # def magnitude(v: Vector) -> float: # def squared_distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # def distance(v: Vector, w: Vector) -> float: # type: ignore # def shape(A: Matrix) -> Tuple[int, int]: # def get_row(A: Matrix, i: int) -> Vector: # def get_column(A: Matrix, j: int) -> Vector: # def make_matrix(num_rows: int, # num_cols: int, # entry_fn: Callable[[int, int], float]) -> Matrix: # def identity_matrix(n: int) -> Matrix: # A = [[1, 2, 3], # A has 2 rows and 3 columns # [4, 5, 6]] # B = [[1, 2], # B has 3 rows and 2 columns # [3, 4], # [5, 6]] # # Path: scratch/linear_algebra.py # def vector_mean(vectors: List[Vector]) -> Vector: # """Computes the element-wise average""" # n = len(vectors) # return scalar_multiply(1/n, vector_sum(vectors)) # # Path: scratch/linear_algebra.py # def squared_distance(v: Vector, w: Vector) -> float: # """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" # return sum_of_squares(subtract(v, w)) # # Path: scratch/linear_algebra.py # def distance(v: Vector, w: Vector) -> float: # """Computes the distance between v and w""" # return math.sqrt(squared_distance(v, w)) . Output only the next line.
assert num_differences([1, 2, 3], [2, 1, 3]) == 2