Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger('make.py') def main(): print(' **make.py** ', sys.argv[1]) dumpname = sys.argv[1] fn = open('/dev/null') app = './%s' % (dumpname[:dumpname.rindex('.')]) print(' **make.py** app', app) try: print(' **cleantree** dumpname', dumpname) shutil.rmtree(dumpname) print(' **cleantree done** dumpname', dumpname) except: pass print(' **open stdout w** ', app + ".stdout") out = open(app + ".stdout", 'w') # pid1 = subprocess.Popen([app], stdout=fn.fileno()) print(' **popen process** ', app) pid1 = subprocess.Popen([app], bufsize=-1, stdout=out.fileno()) print("process", pid1.pid, "was launched") time.sleep(0.9) print(" **end sleep**", pid1.pid) if not os.access(app + ".stdout", os.F_OK): print(" ** preDUMP ** file %s was not written" % app + ".stdout") print(' **DUMP** ', pid1.pid) <|code_end|> . Use current file imports: (import logging import os import subprocess import sys import shutil import time from haystack import memory_dumper) and context including class names, function names, or small code snippets from other files: # Path: haystack/memory_dumper.py # class MemoryDumper: # ARCHIVE_TYPES = ["dir", "tar", "gztar"] # def __init__(self, pid, dest): # def make_mappings(self): # def dump(self, dest=None): # def _dump_all_mappings_winapp(self, destdir): # def _dump_all_mappings(self, destdir): # def _free_process(self): # def _dump_mapping(self, m, tmpdir): # def dump(pid, outfile): # def _dump(opt): # def argparser(): # def main(): . Output only the next line.
memory_dumper.dump(pid1.pid, dumpname)
Using the snippet: <|code_start|>log = logging.getLogger('test_vol') #@unittest.skip('not ready') class TestMapper(unittest.TestCase): """ load zeus.vmem from https://code.google.com/p/volatility/wiki/MemorySamples The malware analysis cookbook """ def setUp(self): try: except ImportError as e: self.skipTest('Volatility not installed') pass def tearDown(self): pass def test_number_of_mappings(self): """ check the number of mappings on 3 processes """ #check vad numbers with #vol.py -f /home/jal/outputs/vol/zeus.vmem -p 856 vadwalk |wc -l #5 headers lines to be removed from count # #analysis here: #https://malwarereversing.wordpress.com/2011/09/23/zeus-analysis-in-volatility-2-0/ f = '/home/jal/outputs/vol/zeus.vmem' pid = 856 # PID 856 has 176 _memory_handler <|code_end|> , determine the next line of code. You have imports: import logging import unittest import volatility from haystack.mappings.vol import VolatilityProcessMapper from test.testfiles import zeus_1668_vmtoolsd_exe from test.testfiles import zeus_856_svchost_exe from haystack.allocators.win32 import winxp_32 and context (class names, function names, or code) available: # Path: haystack/mappings/vol.py # class VolatilityProcessMapper(interfaces.IMemoryLoader): # # def __init__(self, imgname, profile, pid): # self.pid = pid # self.imgname = imgname # # FIXME for some reason volatility is able to autodetect. # # but not with this piece of code. # self.profile = profile # #self.profile = None # self._memory_handler = None # self._unload_volatility() # self._init_volatility() # # def _unload_volatility(self): # '''we cannot have volatility already loaded. # we need to remove it''' # for mod in sys.modules.keys(): # if 'volatility' in mod: # del sys.modules[mod] # # def _init_volatility(self): # #import sys # # for mod in sys.modules.keys(): # # if 'parse' in mod: # # del sys.modules[mod] # # print "deleted",mod # #import sys # # if len(sys.argv) > 3: # # #sys.args=[sys.args[3]] # # sys.argv=[sys.argv[0],'-f',sys.argv[3]] # # print 'after modif',sys.argv # import volatility.conf as conf # import volatility.registry as registry # registry.PluginImporter() # config = conf.ConfObject() # import volatility.commands as commands # import volatility.addrspace as addrspace # import volatility.utils as volutils # registry.register_global_options(config, commands.Command) # registry.register_global_options(config, addrspace.BaseAddressSpace) # # Dying because it cannot parse argv options # # apparently, it was not required to parse options. hey. # # config.parse_options() # #addr_space = volutils.load_as(config,astype = 'any') # #print config.PROFILE # #import code # #code.interact(local=locals()) # config.PROFILE = self.profile # #_target_platform.LOCATION = "file:///media/memory/private/image.dmp" # config.LOCATION = "file://%s" % self.imgname # config.PID = str(self.pid) # # self.config = config # # import volatility.plugins.vadinfo as vadinfo # # command = vadinfo.VADWalk(config) # command.render_text = partial(my_render_text, self, command) # command.execute() # # works now. # #for x in self._memory_handler.get_mappings(): # # print x # #import code # #code.interact(local=locals()) # # def make_memory_handler(self): # return self._memory_handler . Output only the next line.
mapper = VolatilityProcessMapper(f, "WinXPSP2x86", pid)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger('api') class HaystackError(Exception): pass def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): """ Search a record in the memory dump of a process represented by memory_handler. The record type must have been imported using haystack functions. If constraints exists, they will be considered during the search. :param memory_handler: IMemoryHandler :param record_type: a ctypes.Structure or ctypes.Union from a module imported by haystack :param search_constraints: IModuleConstraints to be considered during the search :param extended_search: boolean, use allocated chunks only per default (False) :rtype a list of (ctypes records, memory offset) """ if extended_search: <|code_end|> with the help of current file imports: from past.builtins import long from haystack.search import searcher from haystack.outputters import text from haystack.outputters import python from haystack import listmodel import logging import pickle import json and context from other files: # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/listmodel.py # class ListModel(basicmodel.CTypesRecordConstraintValidator): # def is_single_linked_list_type(self, record_type): # def is_double_linked_list_type(self, record_type): # def get_single_linked_list_type(self, record_type): # def get_double_linked_list_type(self, record_type): # def register_single_linked_list_record_type(self, record_type, forward, sentinels=None): # def register_double_linked_list_record_type(self, record_type, forward, backward, sentinels=None): # def register_linked_list_field_and_type(self, record_type, field_name, list_entry_type, list_entry_field_name): # def _get_list_info_for_field_for(self, record_type, fieldname): # def _get_list_fields(self, record_type): # def iterate_list_from_field(self, record, fieldname, sentinels=None, ignore_head=True): # def iterate_list_from_pointer_field(self, pointer_field, target_fieldname, sentinels=None): # def _iterate_list_from_field_with_link_info(self, record, link_info, sentinels=None, ignore_head=True): # def _iterate_list_from_field_inner(self, iterator_fn, head, pointee_record_type, offset, sentinels): # def _iterate_double_linked_list(self, record, sentinels=None): # def _iterate_single_linked_list(self, record, sentinels=None): # def is_valid(self, record): # def load_members(self, record, max_depth): # def _load_list_entries(self, record, link_iterator, max_depth): , which may contain function names, class names, or code. Output only the next line.
my_searcher = searcher.AnyOffsetRecordSearcher(memory_handler, search_constraints)
Based on the snippet: <|code_start|> If constraints exists, they will be considered during the search. :param memory_handler: IMemoryHandler :param record_type: a ctypes.Structure or ctypes.Union from a module imported by haystack :param search_constraints: IModuleConstraints to be considered during the search :param extended_search: boolean, use allocated chunks only per default (False) :rtype a list of (ctypes records, memory offset) """ hint_mapping = memory_handler.get_mapping_for_address(hint) if extended_search: my_searcher = searcher.AnyOffsetRecordSearcher(memory_handler, my_constraints=search_constraints, target_mappings=[hint_mapping]) return my_searcher.search(record_type) my_searcher = searcher.RecordSearcher(memory_handler, my_constraints=search_constraints, target_mappings=[hint_mapping]) return my_searcher.search(record_type) # FIXME TODO change for results == ctypes def output_to_string(memory_handler, results): """ Transform ctypes results in a string format :param memory_handler: IMemoryHandler :param results: results from the search_record :return: """ if not isinstance(results, list): raise TypeError('Feed me a list of results') <|code_end|> , predict the immediate next line with the help of imports: from past.builtins import long from haystack.search import searcher from haystack.outputters import text from haystack.outputters import python from haystack import listmodel import logging import pickle import json and context (classes, functions, sometimes code) from other files: # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/listmodel.py # class ListModel(basicmodel.CTypesRecordConstraintValidator): # def is_single_linked_list_type(self, record_type): # def is_double_linked_list_type(self, record_type): # def get_single_linked_list_type(self, record_type): # def get_double_linked_list_type(self, record_type): # def register_single_linked_list_record_type(self, record_type, forward, sentinels=None): # def register_double_linked_list_record_type(self, record_type, forward, backward, sentinels=None): # def register_linked_list_field_and_type(self, record_type, field_name, list_entry_type, list_entry_field_name): # def _get_list_info_for_field_for(self, record_type, fieldname): # def _get_list_fields(self, record_type): # def iterate_list_from_field(self, record, fieldname, sentinels=None, ignore_head=True): # def iterate_list_from_pointer_field(self, pointer_field, target_fieldname, sentinels=None): # def _iterate_list_from_field_with_link_info(self, record, link_info, sentinels=None, ignore_head=True): # def _iterate_list_from_field_inner(self, iterator_fn, head, pointee_record_type, offset, sentinels): # def _iterate_double_linked_list(self, record, sentinels=None): # def _iterate_single_linked_list(self, record, sentinels=None): # def is_valid(self, record): # def load_members(self, record, max_depth): # def _load_list_entries(self, record, link_iterator, max_depth): . Output only the next line.
parser = text.RecursiveTextOutputter(memory_handler)
Given the code snippet: <|code_start|> :param results: results from the search_record :return: """ if not isinstance(results, list): raise TypeError('Feed me a list of results') parser = text.RecursiveTextOutputter(memory_handler) ret = '[' for ss, addr in results: ret += "# --------------- 0x%lx \n%s" % (addr, parser.parse(ss)) pass ret += ']' return ret def output_to_python(memory_handler, results): """ Transform ctypes results in a non-ctypes python object format :param memory_handler: IMemoryHandler :param results: results from the search_record :return: """ if not isinstance(results, list): raise TypeError('Feed me a list of results') # also generate POPOs my_model = memory_handler.get_model() pythoned_modules = my_model.get_pythoned_modules().keys() for module_name, module in my_model.get_imported_modules().items(): if module_name not in pythoned_modules: my_model.build_python_class_clones(module) # parse and generate instances <|code_end|> , generate the next line using the imports in this file: from past.builtins import long from haystack.search import searcher from haystack.outputters import text from haystack.outputters import python from haystack import listmodel import logging import pickle import json and context (functions, classes, or occasionally code) from other files: # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/listmodel.py # class ListModel(basicmodel.CTypesRecordConstraintValidator): # def is_single_linked_list_type(self, record_type): # def is_double_linked_list_type(self, record_type): # def get_single_linked_list_type(self, record_type): # def get_double_linked_list_type(self, record_type): # def register_single_linked_list_record_type(self, record_type, forward, sentinels=None): # def register_double_linked_list_record_type(self, record_type, forward, backward, sentinels=None): # def register_linked_list_field_and_type(self, record_type, field_name, list_entry_type, list_entry_field_name): # def _get_list_info_for_field_for(self, record_type, fieldname): # def _get_list_fields(self, record_type): # def iterate_list_from_field(self, record, fieldname, sentinels=None, ignore_head=True): # def iterate_list_from_pointer_field(self, pointer_field, target_fieldname, sentinels=None): # def _iterate_list_from_field_with_link_info(self, record, link_info, sentinels=None, ignore_head=True): # def _iterate_list_from_field_inner(self, iterator_fn, head, pointee_record_type, offset, sentinels): # def _iterate_double_linked_list(self, record, sentinels=None): # def _iterate_single_linked_list(self, record, sentinels=None): # def is_valid(self, record): # def load_members(self, record, max_depth): # def _load_list_entries(self, record, link_iterator, max_depth): . Output only the next line.
parser = python.PythonOutputter(memory_handler)
Based on the snippet: <|code_start|> def load_record(memory_handler, struct_type, memory_address, load_constraints=None): """ Load a record from a specific address in memory. You could use that function to monitor a specific record from memory after a refresh. :param memory_handler: IMemoryHandler :param struct_type: a ctypes.Structure or ctypes.Union :param memory_address: long :param load_constraints: IModuleConstraints to be considered during loading :return: (ctypes record instance, validated_boolean) """ # FIXME, is number maybe ? if not isinstance(memory_address, long) and not isinstance(memory_address, int): raise TypeError('Feed me a long memory_address') # we need to give target_mappings so not to trigger a heap resolution my_loader = searcher.RecordLoader(memory_handler, load_constraints, target_mappings=memory_handler.get_mappings()) return my_loader.load(struct_type, memory_address) def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): """ Validate a loaded record against constraints. :param memory_handler: IMemoryHandler :param instance: a ctypes record :param record_constraints: IModuleConstraints to be considered during validation :return: """ <|code_end|> , predict the immediate next line with the help of imports: from past.builtins import long from haystack.search import searcher from haystack.outputters import text from haystack.outputters import python from haystack import listmodel import logging import pickle import json and context (classes, functions, sometimes code) from other files: # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/listmodel.py # class ListModel(basicmodel.CTypesRecordConstraintValidator): # def is_single_linked_list_type(self, record_type): # def is_double_linked_list_type(self, record_type): # def get_single_linked_list_type(self, record_type): # def get_double_linked_list_type(self, record_type): # def register_single_linked_list_record_type(self, record_type, forward, sentinels=None): # def register_double_linked_list_record_type(self, record_type, forward, backward, sentinels=None): # def register_linked_list_field_and_type(self, record_type, field_name, list_entry_type, list_entry_field_name): # def _get_list_info_for_field_for(self, record_type, fieldname): # def _get_list_fields(self, record_type): # def iterate_list_from_field(self, record, fieldname, sentinels=None, ignore_head=True): # def iterate_list_from_pointer_field(self, pointer_field, target_fieldname, sentinels=None): # def _iterate_list_from_field_with_link_info(self, record, link_info, sentinels=None, ignore_head=True): # def _iterate_list_from_field_inner(self, iterator_fn, head, pointee_record_type, offset, sentinels): # def _iterate_double_linked_list(self, record, sentinels=None): # def _iterate_single_linked_list(self, record, sentinels=None): # def is_valid(self, record): # def load_members(self, record, max_depth): # def _load_list_entries(self, record, link_iterator, max_depth): . Output only the next line.
validator = listmodel.ListModel(memory_handler, record_constraints)
Given snippet: <|code_start|> def test_freelists(self): """ List all free blocks """ self.assertNotEqual(self._memory_handler, None) # test the heaps walkers = self._heap_finder.list_heap_walkers() heap_sums = dict([(heap_walker.get_heap_mapping(), list()) for heap_walker in walkers]) child_heaps = dict() for heap_walker in walkers: heap = heap_walker.get_heap_mapping() heap_addr = heap_walker.get_heap_address() log.debug( '==== walking heap num: %0.2d @ %0.8x' % (heap_walker.get_heap().ProcessHeapsListIndex, heap_addr)) walker = self._heap_finder.get_heap_walker(heap) for x, s in walker._get_freelists(): m = self._memory_handler.get_mapping_for_address(x) # Found new mmap outside of heaps mmaps if m not in heap_sums: heap_sums[m] = [] heap_sums[m].append((x, s)) #self.assertEqual( free_size, walker.HEAP().TotalFreeSize) # save mmap hierarchy child_heaps[heap] = walker.list_used_mappings() # calcul cumulates for heap, children in child_heaps.items(): # for each heap, look at all children freeblocks = list(map(lambda x: x[0], heap_sums[heap])) free_size = sum(map(lambda x: x[1], heap_sums[heap])) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import unittest from builtins import map from haystack.allocators.win32 import winxpheapwalker from haystack.outputters import python from haystack.outputters import text from haystack.mappings import folder from test.testfiles import zeus_1668_vmtoolsd_exe and context: # Path: haystack/allocators/win32/winxpheapwalker.py # class WinXPHeapWalker(winheapwalker.WinHeapWalker): # class WinXPHeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): which might include code, classes, or functions. Output only the next line.
finder = winxpheapwalker.WinXPHeapFinder(self._memory_handler)
Predict the next line for this snippet: <|code_start|> return @classmethod def tearDownClass(cls): cls._memory_handler.reset_mappings() cls._memory_handler = None return def setUp(self): self._heap_finder = self._memory_handler.get_heap_finder() return def tearDown(self): self._heap_finder = None return def test_is_heap(self): finder = winxpheapwalker.WinXPHeapFinder(self._memory_handler) for addr, size in zeus_1668_vmtoolsd_exe.known_heaps: m = self._memory_handler.get_mapping_for_address(addr) # heap = m.read_struct(addr, win7heap.HEAP) # FIXME self.assertTrue(self._heap_finder._is_heap(m)) def test_print_heap_alignmask(self): finder = winxpheapwalker.WinXPHeapFinder(self._memory_handler) for addr, size in zeus_1668_vmtoolsd_exe.known_heaps: m = self._memory_handler.get_mapping_for_address(addr) walker = finder.get_heap_walker(m) win7heap = walker._heap_module heap = m.read_struct(addr, win7heap.HEAP) <|code_end|> with the help of current file imports: import logging import unittest from builtins import map from haystack.allocators.win32 import winxpheapwalker from haystack.outputters import python from haystack.outputters import text from haystack.mappings import folder from test.testfiles import zeus_1668_vmtoolsd_exe and context from other files: # Path: haystack/allocators/win32/winxpheapwalker.py # class WinXPHeapWalker(winheapwalker.WinHeapWalker): # class WinXPHeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): , which may contain function names, class names, or code. Output only the next line.
parser = python.PythonOutputter(self._memory_handler)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for haystack.reverse.structure.""" log = logging.getLogger('testwinxpwalker') """ for f in `ls /home/jal/outputs/vol/zeus.vmem.1668.dump` ; do echo $f; xxd /home/jal/outputs/vol/zeus.vmem.1668.dump/$f | head | grep -c "ffee ffee" ; done | grep -B1 "1$" """ class TestWinXPHeapWalker(unittest.TestCase): @classmethod def setUpClass(cls): cls._memory_handler = folder.load(zeus_1668_vmtoolsd_exe.dumpname) return @classmethod def tearDownClass(cls): cls._memory_handler.reset_mappings() cls._memory_handler = None return def setUp(self): self._heap_finder = self._memory_handler.get_heap_finder() <|code_end|> , predict the immediate next line with the help of imports: import logging import unittest from builtins import map from haystack.allocators.win32 import winxpheapwalker from haystack.outputters import python from haystack.outputters import text from haystack.mappings import folder from test.testfiles import zeus_1668_vmtoolsd_exe and context (classes, functions, sometimes code) from other files: # Path: haystack/allocators/win32/winxpheapwalker.py # class WinXPHeapWalker(winheapwalker.WinHeapWalker): # class WinXPHeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
self.parser = text.RecursiveTextOutputter(self._memory_handler)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for haystack.reverse.structure.""" log = logging.getLogger('testwinxpwalker') """ for f in `ls /home/jal/outputs/vol/zeus.vmem.1668.dump` ; do echo $f; xxd /home/jal/outputs/vol/zeus.vmem.1668.dump/$f | head | grep -c "ffee ffee" ; done | grep -B1 "1$" """ class TestWinXPHeapWalker(unittest.TestCase): @classmethod def setUpClass(cls): <|code_end|> , predict the next line using imports from the current file: import logging import unittest from builtins import map from haystack.allocators.win32 import winxpheapwalker from haystack.outputters import python from haystack.outputters import text from haystack.mappings import folder from test.testfiles import zeus_1668_vmtoolsd_exe and context including class names, function names, and sometimes code from other files: # Path: haystack/allocators/win32/winxpheapwalker.py # class WinXPHeapWalker(winheapwalker.WinHeapWalker): # class WinXPHeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/outputters/python.py # class PythonOutputter(Outputter): # class pyObj(object): # class _pyObjBuilder: # def parse(self, obj, prefix='', depth=50): # def _attrToPyObject(self, attr, field, attrtype): # def json_encode_pyobj(obj): # def toString(self, prefix='', maxDepth=10): # def _attrToString(self, attr, attrname, typ, prefix, maxDepth): # def __len__(self): # def findCtypes(self, cache=None): # def _attrFindCtypes(self, attr, attrname, typ, cache): # def __iter__(self): # def __getstate__(self): # def __reduce__(self): # def __call__(self, modulename, classname): # def findCtypesInPyObj(memory_handler, obj): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
cls._memory_handler = folder.load(zeus_1668_vmtoolsd_exe.dumpname)
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Dumps a process memory _memory_handler to a haystack dump format.""" __author__ = "Loic Jaquemet" __copyright__ = "Copyright (C) 2012 Loic Jaquemet" __email__ = "loic.jaquemet+python@gmail.com" __license__ = "GPL" __maintainer__ = "Loic Jaquemet" __status__ = "Production" log = logging.getLogger('dumper') class MemoryDumper: """ Dumps a process memory maps to a tgz """ ARCHIVE_TYPES = ["dir", "tar", "gztar"] def __init__(self, pid, dest): self._pid = pid self._dest = os.path.normpath(dest) <|code_end|> . Use current file imports: (import logging import argparse import shutil import sys import tempfile import os from haystack import dbg from haystack.mappings.process import make_process_memory_handler) and context including class names, function names, or small code snippets from other files: # Path: haystack/dbg.py # class IProcessDebugger(object): # class IProcess(object): # class MyPTraceDebugger(IProcessDebugger): # class MyWinAppDebugger(IProcessDebugger): # class MyPTraceProcess(IProcess): # class MyWinAppDbgProcess(IProcess): # def get_process(self): # def quit(self): # def get_pid(self): # def get_mappings_line(self): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, struct): # def read_array(self, address, basetype, count): # def __init__(self, pid): # def get_process(self): # def quit(self): # def __init__(self, pid): # def get_process(self): # def quit(self): # def __init__(self, pid, ptrace_process): # def get_pid(self): # def resume(self): # def get_mappings_line(self): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, struct): # def read_array(self, address, basetype, count): # def __init__(self, pid, winapp_process): # def get_pid(self): # def resume(self): # def get_mappings_line(self): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, struct): # def read_array(self, address, basetype, count): # def get_debugger(pid): # def make_local_process_memory_handler(pid, use_mmap=True): # # Path: haystack/mappings/process.py # def make_process_memory_handler(process): # """ # Read all memory mappings of the specified process. # # Return a list of MemoryMapping objects, or empty list if it's not possible # to read the memory mappings. # # May raise a ProcessError. # """ # if not isinstance(process, dbg.IProcess): # raise TypeError('dbg.IProcess expected') # mapsfile = process.get_mappings_line() # # mappings = [] # is_64 = False # # read the mappings # for line in mapsfile: # line = line.rstrip() # match = PROC_MAP_REGEX.match(line) # if not match: # raise IOError(process, "Unable to parse memory mapping: %r" % line) # if not is_64 and len(match.group(1)) > 8: # is_64 = True # # # log.debug('readProcessMappings %s' % (str(match.groups()))) # _map = ProcessMemoryMapping(process, int(match.group(1), 16), int(match.group(2), 16), # match.group(3), int(match.group(4), 16), int(match.group(5), 16), # int(match.group(6), 16), int(match.group(7)), match.group(8)) # mappings.append(_map) # # create the memory_handler for self # import sys # if 'linux' in sys.platform: # os_name = target.TargetPlatform.LINUX # else: # sys.platform.startswith('win'): # os_name = target.TargetPlatform.WIN7 # _target_platform = None # if is_64: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_64(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_64() # else: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_32(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_32() # _memory_handler = MemoryHandler(mappings, _target_platform, 'localhost-%d' % process.get_pid()) # return _memory_handler . Output only the next line.
self.dbg = None
Using the snippet: <|code_start|>"""Dumps a process memory _memory_handler to a haystack dump format.""" __author__ = "Loic Jaquemet" __copyright__ = "Copyright (C) 2012 Loic Jaquemet" __email__ = "loic.jaquemet+python@gmail.com" __license__ = "GPL" __maintainer__ = "Loic Jaquemet" __status__ = "Production" log = logging.getLogger('dumper') class MemoryDumper: """ Dumps a process memory maps to a tgz """ ARCHIVE_TYPES = ["dir", "tar", "gztar"] def __init__(self, pid, dest): self._pid = pid self._dest = os.path.normpath(dest) self.dbg = None self._memory_handler = None def make_mappings(self): """Connect the debugguer to the process and gets the memory mappings metadata.""" self.dbg = dbg.get_debugger(self._pid) <|code_end|> , determine the next line of code. You have imports: import logging import argparse import shutil import sys import tempfile import os from haystack import dbg from haystack.mappings.process import make_process_memory_handler and context (class names, function names, or code) available: # Path: haystack/dbg.py # class IProcessDebugger(object): # class IProcess(object): # class MyPTraceDebugger(IProcessDebugger): # class MyWinAppDebugger(IProcessDebugger): # class MyPTraceProcess(IProcess): # class MyWinAppDbgProcess(IProcess): # def get_process(self): # def quit(self): # def get_pid(self): # def get_mappings_line(self): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, struct): # def read_array(self, address, basetype, count): # def __init__(self, pid): # def get_process(self): # def quit(self): # def __init__(self, pid): # def get_process(self): # def quit(self): # def __init__(self, pid, ptrace_process): # def get_pid(self): # def resume(self): # def get_mappings_line(self): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, struct): # def read_array(self, address, basetype, count): # def __init__(self, pid, winapp_process): # def get_pid(self): # def resume(self): # def get_mappings_line(self): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, struct): # def read_array(self, address, basetype, count): # def get_debugger(pid): # def make_local_process_memory_handler(pid, use_mmap=True): # # Path: haystack/mappings/process.py # def make_process_memory_handler(process): # """ # Read all memory mappings of the specified process. # # Return a list of MemoryMapping objects, or empty list if it's not possible # to read the memory mappings. # # May raise a ProcessError. # """ # if not isinstance(process, dbg.IProcess): # raise TypeError('dbg.IProcess expected') # mapsfile = process.get_mappings_line() # # mappings = [] # is_64 = False # # read the mappings # for line in mapsfile: # line = line.rstrip() # match = PROC_MAP_REGEX.match(line) # if not match: # raise IOError(process, "Unable to parse memory mapping: %r" % line) # if not is_64 and len(match.group(1)) > 8: # is_64 = True # # # log.debug('readProcessMappings %s' % (str(match.groups()))) # _map = ProcessMemoryMapping(process, int(match.group(1), 16), int(match.group(2), 16), # match.group(3), int(match.group(4), 16), int(match.group(5), 16), # int(match.group(6), 16), int(match.group(7)), match.group(8)) # mappings.append(_map) # # create the memory_handler for self # import sys # if 'linux' in sys.platform: # os_name = target.TargetPlatform.LINUX # else: # sys.platform.startswith('win'): # os_name = target.TargetPlatform.WIN7 # _target_platform = None # if is_64: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_64(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_64() # else: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_32(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_32() # _memory_handler = MemoryHandler(mappings, _target_platform, 'localhost-%d' % process.get_pid()) # return _memory_handler . Output only the next line.
self._memory_handler = make_process_memory_handler(self.dbg.get_process())
Here is a snippet: <|code_start|> (0x03360000, 604), (0x04030000, 632), (0x04110000, 1334), (0x041c0000, 644), # from free stuf (0x0061a000, 1200), ] self.memory_handler = folder.load(self.memdumpname) def tearDown(self): self.memory_handler.reset_mappings() self.memory_handler = None self.memdumpname = None self.classname = None self.known_heaps = None def test_load(self): # this is kinda stupid, given we are using a heapwalker to # find the heap, and testing the heap. finder = self.memory_handler.get_heap_finder() walkers = finder.list_heap_walkers() heaps = [walker.get_heap_mapping() for walker in walkers] my_heap = [x for x in heaps if x.start == self.known_heaps[0][0]][0] heap_mapping = self.memory_handler.get_mapping_for_address(self.known_heaps[0][0]) # we want the 32 bits heap record type on 32 bits heap mappings heapwalker = finder.get_heap_walker(heap_mapping) ## Thats a 64 bits heap heapwalker = finder.get_heap_walker(heaps[0]) my_loader = searcher.RecordLoader(self.memory_handler) res = my_loader.load(heapwalker._heap_module.HEAP, self.known_heaps[0][0]) <|code_end|> . Write the next line using the current file imports: import logging import unittest from haystack.search import api from haystack.search import searcher from haystack.mappings import folder and context from other files: # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): # # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): , which may include functions, classes, or code. Output only the next line.
res_p = api.output_to_python(self.memory_handler, [res])
Continue the code snippet: <|code_start|> (0x01ef0000, 604), (0x02010000, 61348), (0x02080000, 474949), (0x021f0000, 18762), (0x03360000, 604), (0x04030000, 632), (0x04110000, 1334), (0x041c0000, 644), # from free stuf (0x0061a000, 1200), ] self.memory_handler = folder.load(self.memdumpname) def tearDown(self): self.memory_handler.reset_mappings() self.memory_handler = None self.memdumpname = None self.classname = None self.known_heaps = None def test_load(self): # this is kinda stupid, given we are using a heapwalker to # find the heap, and testing the heap. finder = self.memory_handler.get_heap_finder() walkers = finder.list_heap_walkers() heaps = [walker.get_heap_mapping() for walker in walkers] my_heap = [x for x in heaps if x.start == self.known_heaps[0][0]][0] heap_mapping = self.memory_handler.get_mapping_for_address(self.known_heaps[0][0]) # we want the 32 bits heap record type on 32 bits heap mappings heapwalker = finder.get_heap_walker(heap_mapping) ## Thats a 64 bits heap heapwalker = finder.get_heap_walker(heaps[0]) <|code_end|> . Use current file imports: import logging import unittest from haystack.search import api from haystack.search import searcher from haystack.mappings import folder and context (classes, functions, or code) from other files: # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): # # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
my_loader = searcher.RecordLoader(self.memory_handler)
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class TestApiWin32Dump(unittest.TestCase): """ test if the API works for windows """ memdumpname = 'test/dumps/putty/putty.1.dump' #modulename = "test/src/putty.py" def setUp(self): self.classname = 'haystack.allocators.win32.win7heap.HEAP' self.known_heaps = [(0x00390000, 8956), (0x00540000, 868), (0x00580000, 111933), (0x005c0000, 1704080), (0x01ef0000, 604), (0x02010000, 61348), (0x02080000, 474949), (0x021f0000, 18762), (0x03360000, 604), (0x04030000, 632), (0x04110000, 1334), (0x041c0000, 644), # from free stuf (0x0061a000, 1200), ] <|code_end|> , determine the next line of code. You have imports: import logging import unittest from haystack.search import api from haystack.search import searcher from haystack.mappings import folder and context (class names, function names, or code) available: # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): # # Path: haystack/search/searcher.py # class RecordSearcher(object): # class RecordLoader(RecordSearcher): # class AnyOffsetRecordSearcher(RecordSearcher): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def search(self, struct_type, max_res=10, max_depth=10): # def _search_in(self, mem_map, struct_type, nb=10, depth=99): # def _load_at(self, mem_map, address, struct_type, depth=99): # def load(self, struct_type, memory_address): # def __init__(self, memory_handler, my_constraints=None, target_mappings=None, update_cb=None): # def _search_in(self, mem_map, struct_type, nb=10, depth=99, align=None): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
self.memory_handler = folder.load(self.memdumpname)
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function # from haystack.outputters import python """ Search for HEAP. """ log = logging.getLogger('cliwin') def find_heap(): argv = sys.argv[1:] <|code_end|> , determine the next line of code. You have imports: import argparse import logging import struct import sys from haystack import cli from haystack import argparse_utils from haystack.outputters import text from haystack.mappings import folder and context (class names, function names, or code) available: # Path: haystack/cli.py # SEARCH_DESC = 'Search for instance of a record_type in the allocated memory of a process. ' # SHOW_DESC = 'Cast the bytes at this address into a record_type. ' # WATCH_DESC = 'Cast the bytes at this address into a record_type and refresh regularly. ' # DUMP_DESC = 'Extract the process dump from the OS memory dump in haystack format. ' # DUMPTYPE_BASE = 'haystack' # DUMPTYPE_VOLATILITY = 'volatility' # DUMPTYPE_REKALL = 'rekall' # DUMPTYPE_LIVE = 'live' # DUMPTYPE_MINIDUMP = 'minidump' # DUMPTYPE_FRIDA = 'frida' # SUPPORTED_DUMP_URI = {} # DUMPTYPE_BASE_DESC = 'The process dump is a folder produced by a haystack-dump script.' # DUMPTYPE_VOL_DESC = 'The process dump is a volatility OS dump. The PID is the targeted process.' # DUMPTYPE_REKALL_DESC = 'The process dump is a rekall OS dump. The PID is the targeted process.' # DUMPTYPE_LIVE_DESC = 'The PID must be a running process.' # DUMPTYPE_MINIDUMP_DESC = 'The process dump is a Minidump (MDMP) process dump.' # def url(u): # def make_memory_handler(opts): # def get_output(memory_handler, results, rtype): # def dump_process(opts): # def search_cmdline(args): # def show_cmdline(args): # def check_varname_for_type(memory_handler, varname, struct_type): # def get_varname_value(varname, instance): # def watch(args): # def base_argparser(program_name, description): # def search_argparser(search_parser): # def show_argparser(show_parser): # def watch_argparser(watch_parser): # def dump_argparser(dump_parser): # def output_argparser(rootparser): # def set_logging_level(opts): # def live_watch(): # def volatility_dump(): # def rekall_dump(): # def search(): # def show(): # class HaystackError(Exception): # # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
parser = cli.base_argparser('haystack-find-heap', "Find heaps in a dumpfile")
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function # from haystack.outputters import python """ Search for HEAP. """ log = logging.getLogger('cliwin') def find_heap(): argv = sys.argv[1:] parser = cli.base_argparser('haystack-find-heap', "Find heaps in a dumpfile") parser.add_argument('--verbose', '-v', action='store_true', help='Verbose') parser.add_argument('--mappings', '-m', action='store_true', help='Show mappings') # only if address is present group = parser.add_argument_group('For a specific HEAP') <|code_end|> using the current file's imports: import argparse import logging import struct import sys from haystack import cli from haystack import argparse_utils from haystack.outputters import text from haystack.mappings import folder and any relevant context from other files: # Path: haystack/cli.py # SEARCH_DESC = 'Search for instance of a record_type in the allocated memory of a process. ' # SHOW_DESC = 'Cast the bytes at this address into a record_type. ' # WATCH_DESC = 'Cast the bytes at this address into a record_type and refresh regularly. ' # DUMP_DESC = 'Extract the process dump from the OS memory dump in haystack format. ' # DUMPTYPE_BASE = 'haystack' # DUMPTYPE_VOLATILITY = 'volatility' # DUMPTYPE_REKALL = 'rekall' # DUMPTYPE_LIVE = 'live' # DUMPTYPE_MINIDUMP = 'minidump' # DUMPTYPE_FRIDA = 'frida' # SUPPORTED_DUMP_URI = {} # DUMPTYPE_BASE_DESC = 'The process dump is a folder produced by a haystack-dump script.' # DUMPTYPE_VOL_DESC = 'The process dump is a volatility OS dump. The PID is the targeted process.' # DUMPTYPE_REKALL_DESC = 'The process dump is a rekall OS dump. The PID is the targeted process.' # DUMPTYPE_LIVE_DESC = 'The PID must be a running process.' # DUMPTYPE_MINIDUMP_DESC = 'The process dump is a Minidump (MDMP) process dump.' # def url(u): # def make_memory_handler(opts): # def get_output(memory_handler, results, rtype): # def dump_process(opts): # def search_cmdline(args): # def show_cmdline(args): # def check_varname_for_type(memory_handler, varname, struct_type): # def get_varname_value(varname, instance): # def watch(args): # def base_argparser(program_name, description): # def search_argparser(search_parser): # def show_argparser(show_parser): # def watch_argparser(watch_parser): # def dump_argparser(dump_parser): # def output_argparser(rootparser): # def set_logging_level(opts): # def live_watch(): # def volatility_dump(): # def rekall_dump(): # def search(): # def show(): # class HaystackError(Exception): # # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
group.add_argument('address', nargs='?', type=argparse_utils.int16, default=None, help='Load Heap from address (hex)')
Here is a snippet: <|code_start|> one_heap(opts, finder) return print('Probable Process HEAPS:') for m in memory_handler.get_mappings(): for addr in range(m.start, m.end, 0x1000): special = '' for os, bits, offset in [('winxp', 32, 8), ('winxp', 64, 16), ('win7', 32, 100), ('win7', 64, 160)]: signature = struct.unpack('I', m.read_bytes(addr+offset, 4))[0] if signature == 0xeeffeeff: if addr != m.start: special = ' (!) ' print('[+] %s %dbits %s 0x%0.8x' % (os, bits, special, addr), m) # Then show heap analysis print('Found Heaps:') for walker in finder.list_heap_walkers(): validator = walker.get_heap_validator() validator.print_heap_analysis(walker.get_heap(), opts.verbose) return def one_heap(opts, finder): address = opts.address memory_handler = finder._memory_handler # just return the heap ctypes_heap, valid = finder.search_heap_direct(address) <|code_end|> . Write the next line using the current file imports: import argparse import logging import struct import sys from haystack import cli from haystack import argparse_utils from haystack.outputters import text from haystack.mappings import folder and context from other files: # Path: haystack/cli.py # SEARCH_DESC = 'Search for instance of a record_type in the allocated memory of a process. ' # SHOW_DESC = 'Cast the bytes at this address into a record_type. ' # WATCH_DESC = 'Cast the bytes at this address into a record_type and refresh regularly. ' # DUMP_DESC = 'Extract the process dump from the OS memory dump in haystack format. ' # DUMPTYPE_BASE = 'haystack' # DUMPTYPE_VOLATILITY = 'volatility' # DUMPTYPE_REKALL = 'rekall' # DUMPTYPE_LIVE = 'live' # DUMPTYPE_MINIDUMP = 'minidump' # DUMPTYPE_FRIDA = 'frida' # SUPPORTED_DUMP_URI = {} # DUMPTYPE_BASE_DESC = 'The process dump is a folder produced by a haystack-dump script.' # DUMPTYPE_VOL_DESC = 'The process dump is a volatility OS dump. The PID is the targeted process.' # DUMPTYPE_REKALL_DESC = 'The process dump is a rekall OS dump. The PID is the targeted process.' # DUMPTYPE_LIVE_DESC = 'The PID must be a running process.' # DUMPTYPE_MINIDUMP_DESC = 'The process dump is a Minidump (MDMP) process dump.' # def url(u): # def make_memory_handler(opts): # def get_output(memory_handler, results, rtype): # def dump_process(opts): # def search_cmdline(args): # def show_cmdline(args): # def check_varname_for_type(memory_handler, varname, struct_type): # def get_varname_value(varname, instance): # def watch(args): # def base_argparser(program_name, description): # def search_argparser(search_parser): # def show_argparser(show_parser): # def watch_argparser(watch_parser): # def dump_argparser(dump_parser): # def output_argparser(rootparser): # def set_logging_level(opts): # def live_watch(): # def volatility_dump(): # def rekall_dump(): # def search(): # def show(): # class HaystackError(Exception): # # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): , which may include functions, classes, or code. Output only the next line.
out = text.RecursiveTextOutputter(finder._memory_handler)
Continue the code snippet: <|code_start|> # FIXME: the sum calculation is per segment, not per mapping. self.assertNotEqual(self._memory_handler, None) # test the heaps walkers = self._heap_finder.list_heap_walkers() heap_sums = dict([(walker.get_heap_mapping(), list()) for walker in walkers]) child_heaps = dict() for heap_walker in walkers: heap_addr = heap_walker.get_heap_address() heap = heap_walker.get_heap_mapping() log.debug( '==== walking heap num: %0.2d @ %0.8x', heap_walker.get_heap().ProcessHeapsListIndex, heap_addr) walker = self._heap_finder.get_heap_walker(heap) for x, s in walker._get_freelists(): m = self._memory_handler.get_mapping_for_address(x) # Found new mmap outside of heaps mmaps if m not in heap_sums: heap_sums[m] = [] heap_sums[m].append((x, s)) #self.assertEqual( free_size, walker.HEAP().TotalFreeSize) # save mmap hierarchy child_heaps[heap] = walker.list_used_mappings() # calcul cumulates for heap, children in child_heaps.items(): # for each heap, look at all children freeblocks = map(lambda x: x[0], heap_sums[heap]) free_size = sum(map(lambda x: x[1], heap_sums[heap])) <|code_end|> . Use current file imports: import logging import sys import unittest from haystack.allocators.win32 import win7heapwalker from haystack.mappings import folder from test.testfiles import putty_1_win7 and context (classes, functions, or code) from other files: # Path: haystack/allocators/win32/win7heapwalker.py # class Win7HeapWalker(winheapwalker.WinHeapWalker): # class Win7HeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
finder = win7heapwalker.Win7HeapFinder(self._memory_handler)
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for haystack.reverse.structure.""" from __future__ import print_function log = logging.getLogger('testwin7walker') class TestWin7HeapWalker(unittest.TestCase): @classmethod def setUpClass(cls): # putty 1 was done under win7 32 bits ? <|code_end|> . Use current file imports: import logging import sys import unittest from haystack.allocators.win32 import win7heapwalker from haystack.mappings import folder from test.testfiles import putty_1_win7 and context (classes, functions, or code) from other files: # Path: haystack/allocators/win32/win7heapwalker.py # class Win7HeapWalker(winheapwalker.WinHeapWalker): # class Win7HeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
cls._memory_handler = folder.load(putty_1_win7.dumpname)
Predict the next line after this snippet: <|code_start|> cache type enum """ BROC_UNKNOW = 0 BROC_HEADER = 1 # head file BROC_SOURCE = 2 # souce file BROC_LIB = 3 # .a BROC_APP = 4 # exe class BrocObject(object): """ base cache class """ TYPE = BrocObjectType.BROC_UNKNOW def __init__(self, pathname, initialized=True): """ Args: pathname : the cvs path of object file initialized : to mark whether BrocObject need initialized, default is True, if initialized is False, create a empty BrocObject object """ self.pathname = pathname self.initialized = initialized # initialized flag self.deps = set() # dependent BrocObject self.reverse_deps = set() # reversed dependent BrocObject self.hash = None # hash value of content self.modify_time = 0 # the last modify time of BrocObject file self.build_cmd = "" # the commond of BrocObject to build if self.initialized: try: <|code_end|> using the current file's imports: import os import sys from util import Function from util import Log and any relevant context from other files: # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): # # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) . Output only the next line.
self.hash = Function.GetFileHash(pathname)
Given the following code snippet before the placeholder: <|code_start|> result['msg'] = self.build_cmd + '\n' + msg return result def NotifyReverseDeps(self): """ to notify all reversed dependent BrocObject objects to build """ for obj in self.reverse_deps: #Log.Log().LevPrint("MSG", "%s nofity reverse cache dep(%s) build" % (self.pathname, obj.Pathname())) obj.EnableBuild() def IsChanged(self, target=None): """ to check whether cache is changed Args: target : the target that compared to Returns: if file is modified, return True if file is not modified, return False """ # if build flag is True, means it has changed if self.build: #Log.Log().LevPrint('MSG', 'cache %s build mark is true' % self.pathname) return True # check mtime modify_time = None try: modify_time = os.stat(self.pathname).st_mtime except BaseException: <|code_end|> , predict the next line using imports from the current file: import os import sys from util import Function from util import Log and context including class names, function names, and sometimes code from other files: # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): # # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) . Output only the next line.
Log.Log().LevPrint('MSG', 'get %s modify_time failed' % self.pathname)
Predict the next line for this snippet: <|code_start|> broc_path = os.path.realpath(os.path.join(os.path.realpath(__file__), '..', '..')) sys.path.insert(0, broc_path) class TestUTMaster(unittest.TestCase): """ unit test for UTMaster """ def setUp(self): """ """ pass def tearDown(self): """ """ pass def test_UTMaster(self): """ test UTMaster """ queue = Queue.Queue() queue.put("ls -al") queue.put("whoami") queue.put("gcc --version") queue.put("gcc --watch out") queue.put("echo 'broc is great'") log = Log.Log() <|code_end|> with the help of current file imports: import os import sys import Queue import unittest from dependency import UTMaster from util import Log and context from other files: # Path: dependency/UTMaster.py # class UTMaster(object): # """ # UTMaster dispatches ut command to ut threads # """ # def __init__(self, queue, logger): # """ # Args: # queue : the ut command queue # logger : the Log.Log() object # """ # self._queue = queue # self._logger = logger # self._errors = list() # # def Run(self): # """ # thread entrence function # """ # while not self._queue.empty(): # try: # cmd = self._queue.get(True, 1) # except Queue.Empty: # break # ret, msg = Function.RunCommand(cmd, True) # if ret != 0: # self._logger.LevPrint("ERROR", "run ut cmd(%s) failed: %s" % (cmd, msg)) # self._errors.append(msg) # else: # self._logger.LevPrint("MSG", "run ut cmd(%s) OK\n%s" % (cmd, msg)) # self._queue.task_done() # # def Start(self): # """ # run all ut threads # """ # num = 4 # # if self._queue.qsize() < 4: # num = self._queue.qsize() # # workers = list() # for i in xrange(0, num): # t = threading.Thread(target=self.Run) # workers.append(t) # t.start() # # wait all ut comands done # self._queue.join() # # wait all ut threads exit # for worker in workers: # worker.join() # # def Errors(self): # """ # return all error msg # """ # return self._errors # # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) , which may contain function names, class names, or code. Output only the next line.
master = UTMaster.UTMaster(queue, log)
Continue the code snippet: <|code_start|>""" broc_path = os.path.realpath(os.path.join(os.path.realpath(__file__), '..', '..')) sys.path.insert(0, broc_path) class TestUTMaster(unittest.TestCase): """ unit test for UTMaster """ def setUp(self): """ """ pass def tearDown(self): """ """ pass def test_UTMaster(self): """ test UTMaster """ queue = Queue.Queue() queue.put("ls -al") queue.put("whoami") queue.put("gcc --version") queue.put("gcc --watch out") queue.put("echo 'broc is great'") <|code_end|> . Use current file imports: import os import sys import Queue import unittest from dependency import UTMaster from util import Log and context (classes, functions, or code) from other files: # Path: dependency/UTMaster.py # class UTMaster(object): # """ # UTMaster dispatches ut command to ut threads # """ # def __init__(self, queue, logger): # """ # Args: # queue : the ut command queue # logger : the Log.Log() object # """ # self._queue = queue # self._logger = logger # self._errors = list() # # def Run(self): # """ # thread entrence function # """ # while not self._queue.empty(): # try: # cmd = self._queue.get(True, 1) # except Queue.Empty: # break # ret, msg = Function.RunCommand(cmd, True) # if ret != 0: # self._logger.LevPrint("ERROR", "run ut cmd(%s) failed: %s" % (cmd, msg)) # self._errors.append(msg) # else: # self._logger.LevPrint("MSG", "run ut cmd(%s) OK\n%s" % (cmd, msg)) # self._queue.task_done() # # def Start(self): # """ # run all ut threads # """ # num = 4 # # if self._queue.qsize() < 4: # num = self._queue.qsize() # # workers = list() # for i in xrange(0, num): # t = threading.Thread(target=self.Run) # workers.append(t) # t.start() # # wait all ut comands done # self._queue.join() # # wait all ut threads exit # for worker in workers: # worker.join() # # def Errors(self): # """ # return all error msg # """ # return self._errors # # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) . Output only the next line.
log = Log.Log()
Given the code snippet: <|code_start|>Authors: zhousongsong(doublesongsong@gmail.com) Date: 2015/11/16 14:07:06 """ broc_path = os.path.realpath(os.path.join(os.path.realpath(__file__), '..', '..')) sys.path.insert(0, broc_path) class UTMaster(object): """ UTMaster dispatches ut command to ut threads """ def __init__(self, queue, logger): """ Args: queue : the ut command queue logger : the Log.Log() object """ self._queue = queue self._logger = logger self._errors = list() def Run(self): """ thread entrence function """ while not self._queue.empty(): try: cmd = self._queue.get(True, 1) except Queue.Empty: break <|code_end|> , generate the next line using the imports in this file: import os import sys import Queue import threading from util import Function and context (functions, classes, or occasionally code) from other files: # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): . Output only the next line.
ret, msg = Function.RunCommand(cmd, True)
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved # ################################################################################ """ Description : analyse command line option Authors : zhousongsong(doublesongsong@gmail.com) liruihao(liruihao01@gmail.com) Date : 2015-09-18 10:28:23 """ broc_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) sys.path.insert(0, broc_dir) def Help(bin_name, subcommand=None): """ Show help imformation Args: bin_name : executable file name subcommand : executable file subcommand. In broc, it's in [""] Return: 0 : success """ if subcommand is None: <|code_end|> , generate the next line using the imports in this file: import os import sys import getopt from util import Log and context (functions, classes, or occasionally code) from other files: # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) . Output only the next line.
Log.colorprint("DEFAULT", "Usage: %s <subcommand> [option] [args]" % (bin_name), False)
Predict the next line for this snippet: <|code_start|>broc_path = os.path.realpath(os.path.join(os.path.realpath(__file__), '..', '..')) sys.path.insert(0, broc_path) class TestBuilder(unittest.TestCase): """ unit test for Builder """ def setUp(self): """ """ pass def tearDown(self): """ """ pass def test_BinBuilder(self): """ test BinBuilder """ obj = 'broc_out/a/b/c/test' dep_objs = ['a/b/c/fun.o', 'a/b/c/util.o'] dep_libs = ['broc_out/a/b/d/output/lib/libfun.a', 'broc_out/a/b/d/output/lib/libutil.a'] dep_links = ['-DBROC', '-Werror', '-Wpublick=private'] compiler = '/usr/bin/g++' right_cmd = "mkdir -p broc_out/a/b/c && /usr/bin/g++ \\\n\t-DBROC \\\n\t-o \ \\\n\tbroc_out/a/b/c/test \\\n\ta/b/c/fun.o \\\n\ta/b/c/util.o \\\n\t-DBROC \\\n\t-Werror \ \\\n\t-Wpublick=private \\\n\t-Xlinker \\\n\t\"-(\" \\\n\t\tbroc_out/a/b/d/output/lib/libfun.a \ \\\n\t\tbroc_out/a/b/d/output/lib/libutil.a \\\n\t-Xlinker \\\n\t\"-)\"" <|code_end|> with the help of current file imports: import os import sys import unittest from dependency import Builder from util import Function and context from other files: # Path: dependency/Builder.py # class Builder(object): # """ # base class for splicing the compile command # """ # def __init__(self, obj, compiler, workspace): # """ # init function # Args: # obj : the cvs path of object file # compiler : the path of compiler # workspace : the workspace path # """ # self.obj = obj # self.obj_dir = os.path.dirname(obj) # self.compiler = compiler # self.workspace = workspace # self.build_cmd = None # build cmd # self.error = "OK" # # def __str__(self): # """ # """ # return self.build_cmd # # def GetBuildCmd(self): # """ # return the build cmd # """ # return self.build_cmd # # def Error(self): # """ # return the error message # """ # return self.error # # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): , which may contain function names, class names, or code. Output only the next line.
builder = Builder.BinBuilder(obj, dep_objs, dep_libs, dep_links, compiler, '.')
Based on the snippet: <|code_start|> right_header_cmd = "/usr/bin/g++ \\\n\t-MM -MG\\\n\t-I/usr/include \ \\\n\t-I/usr/local/include \\\n\tget_header_files.cpp" self.assertEqual(right_header_cmd, builder.GetHeaderCmd()) with open('hello.h', 'wb') as f: f.write("#include <stdio.h>\n\ void hello()\n\ {\n\ print(\"hello - hello\");\n\ }\n") with open('world.h', 'wb') as f: f.write("#include <stdio.h>\n\ void world()\n\ {\n\ print(\"hello - world\");\n\ }\n") with open('get_header_files.cpp', 'wb') as f: f.write("#include <stdio.h>\n\ #include <pthread.h>\n\ #include \"hello.h\"\n\ #include \"world.h\"\n\ int main()\n\ {\n\ hello();\n\ world();\n\ return 0;\n\ }\n") ret = builder.CalcHeaderFiles() self.assertEqual(True, ret['ret']) self.assertEqual(sorted(["hello.h", 'world.h']), sorted(ret['headers'])) <|code_end|> , predict the immediate next line with the help of imports: import os import sys import unittest from dependency import Builder from util import Function and context (classes, functions, sometimes code) from other files: # Path: dependency/Builder.py # class Builder(object): # """ # base class for splicing the compile command # """ # def __init__(self, obj, compiler, workspace): # """ # init function # Args: # obj : the cvs path of object file # compiler : the path of compiler # workspace : the workspace path # """ # self.obj = obj # self.obj_dir = os.path.dirname(obj) # self.compiler = compiler # self.workspace = workspace # self.build_cmd = None # build cmd # self.error = "OK" # # def __str__(self): # """ # """ # return self.build_cmd # # def GetBuildCmd(self): # """ # return the build cmd # """ # return self.build_cmd # # def Error(self): # """ # return the error message # """ # return self.error # # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): . Output only the next line.
Function.DelFiles('get_header_files.cpp')
Using the snippet: <|code_start|> if not os.path.exists(self._cache_file): self._logger.LevPrint("MSG", "no broc cache and create a empty one") return # try to load cache file self._logger.LevPrint("MSG", "loading cache(%s) ..." % self._cache_file) try: with open(self._cache_file, 'rb') as f: caches = cPickle.load(f) if caches[0] != self._version: self._logger.LevPrint("MSG", "cache version(%s) no match system(%s)" % (caches[0], self._version)) else: for cache in caches[1:]: self._cache[cache.Pathname()] = cache #self._logger.LevPrint("MSG", 'cache %s , %d hash is %s, build %s, Modified %s' % (cache.Pathname(), id(cache), cache.Hash(), cache.Build(), cache.Modified())) except BaseException as err: self._logger.LevPrint("MSG", "load broc cache(%s) faild(%s), create a empty cache" % (self._cache_file, str(err))) self._logger.LevPrint("MSG", "loading cache success") self._logger.LevPrint("MSG", "checking cache ...") self.SelfCheck() self._logger.LevPrint("MSG", "checking cache done") def _save_cache(self): """ save cache objects into file and content of file is a list and its format is [ version, cache, cache, ...]. the first item is cache version, and the 2th, 3th ... item is cache object """ dir_name = os.path.dirname(self._cache_file) <|code_end|> , determine the next line of code. You have imports: import os import sys import threading import Queue import cPickle import Target import BrocObject from util import Function and context (class names, function names, or code) available: # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): . Output only the next line.
Function.Mkdir(dir_name)
Continue the code snippet: <|code_start|> #ut bin #UT_APPLICATION('name', # Sources("src/*.cpp", Include('a/b/c')), # LinkFlags("link flags"), # Libs("$OUT_ROOT/a/b/c/output/lib/libutil.a"), # UTArgs("")) #static library file .a #STATIC_LIBRARY('name', # Sources("src/*.cpp", Include('a/b/c')), # Libs("$OUT_ROOT/a/b/c/output/lib/libutil.a")) #proto static library file .a #PROTO_LIBRARY('name', # 'proto/*.proto', # Proto_Flags(""), # Include(""), # CppFlags("debug flags", "release flags"), # CxxFlags("debug falgs","release flas"), # Libs("$OUT_ROOT/a/b/c/output/lib/libutil.a"))''' def scratch(target_dir): """ create a BCLOUD template Args: target_dir : the directory of BROC file """ broc_file = os.path.join(target_dir, 'BROC') if os.path.exists(broc_file): <|code_end|> . Use current file imports: import os import sys from util import Log and context (classes, functions, or code) from other files: # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) . Output only the next line.
Log.Log().LevPrint("ERROR", "BROC already existed in %s, couldn't create it" % target_dir)
Given the code snippet: <|code_start|> return the cvs path of result file """ return self.outfile def CalcObjectName(self): """ caculate the cvs path of result file cvs path = 'broc_out' + '/' + cvs path of infile + '/' + '%s_%s_%s.o' % (self.target.TYPE, self.target.name, file name) """ cvs_dir = os.path.dirname(self.infile) root, _ = os.path.splitext(os.path.basename(self.infile)) obj_file = os.path.join(cvs_dir, "%s_%s_%s.o" % (self.target.TYPE, self.target.Name(), root)) if not obj_file.startswith('broc_out'): self.outfile = os.path.join("broc_out", obj_file) else: self.outfile = obj_file def Action(self): """ parser compile flags including include path, preprocess flags, c compile flags and cxx compile flags """ incpaths_flag = False cppflags_flag = False cflags_flag = False cxxflags_flag = False # parse all args and take arg as local flag for args in self.args: for arg in args: <|code_end|> , generate the next line using the imports in this file: import os import sys import copy from dependency import SyntaxTag from dependency import Builder and context (functions, classes, or occasionally code) from other files: # Path: dependency/SyntaxTag.py # class TagVector(object): # class TagScalar(object): # class TagINCLUDE(TagVector): # class TagCPPFLAGS(TagVector): # class TagCFLAGS(TagVector): # class TagCXXFLAGS(TagVector): # class TagLDFLAGS(TagVector): # class TagInclude(TagVector): # class TagCppFlags(TagVector): # class TagCxxFlags(TagVector): # class TagCFlags(TagVector): # class TagLDFlags(TagVector): # class TagProtoFlags(TagVector): # class TagLibs(TagVector): # class TagSources(TagVector): # class TagUTArgs(TagVector): # def __init__(self): # def __str__(self): # def AddV(self, v): # def AddVs(self, vs): # def AddSV(self, v): # def AddSVs(self, vs): # def V(self): # def __add__(self, other): # def __sub__(self, other): # def __init__(self): # def __str__(self): # def SetV(self, v): # def V(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # # Path: dependency/Builder.py # class Builder(object): # """ # base class for splicing the compile command # """ # def __init__(self, obj, compiler, workspace): # """ # init function # Args: # obj : the cvs path of object file # compiler : the path of compiler # workspace : the workspace path # """ # self.obj = obj # self.obj_dir = os.path.dirname(obj) # self.compiler = compiler # self.workspace = workspace # self.build_cmd = None # build cmd # self.error = "OK" # # def __str__(self): # """ # """ # return self.build_cmd # # def GetBuildCmd(self): # """ # return the build cmd # """ # return self.build_cmd # # def Error(self): # """ # return the error message # """ # return self.error . Output only the next line.
if isinstance(arg, SyntaxTag.TagInclude):
Predict the next line for this snippet: <|code_start|> self.headers = res['headers'] return ret class CSource(Source): """ C Source Code """ TYPE = SourceType.C EXTS = ('.c',) def __init__(self, infile, env, args): """ """ Source.__init__(self, infile, env, args) def Compiler(self): """ return the path of compiler """ return self.env.CC() def Action(self): """ parse compile options, and join all options as a string object """ Source.Action(self) self.CalcObjectName() options = ['-DBROC'] options.extend(self.cppflags + self.cflags) <|code_end|> with the help of current file imports: import os import sys import copy from dependency import SyntaxTag from dependency import Builder and context from other files: # Path: dependency/SyntaxTag.py # class TagVector(object): # class TagScalar(object): # class TagINCLUDE(TagVector): # class TagCPPFLAGS(TagVector): # class TagCFLAGS(TagVector): # class TagCXXFLAGS(TagVector): # class TagLDFLAGS(TagVector): # class TagInclude(TagVector): # class TagCppFlags(TagVector): # class TagCxxFlags(TagVector): # class TagCFlags(TagVector): # class TagLDFlags(TagVector): # class TagProtoFlags(TagVector): # class TagLibs(TagVector): # class TagSources(TagVector): # class TagUTArgs(TagVector): # def __init__(self): # def __str__(self): # def AddV(self, v): # def AddVs(self, vs): # def AddSV(self, v): # def AddSVs(self, vs): # def V(self): # def __add__(self, other): # def __sub__(self, other): # def __init__(self): # def __str__(self): # def SetV(self, v): # def V(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # # Path: dependency/Builder.py # class Builder(object): # """ # base class for splicing the compile command # """ # def __init__(self, obj, compiler, workspace): # """ # init function # Args: # obj : the cvs path of object file # compiler : the path of compiler # workspace : the workspace path # """ # self.obj = obj # self.obj_dir = os.path.dirname(obj) # self.compiler = compiler # self.workspace = workspace # self.build_cmd = None # build cmd # self.error = "OK" # # def __str__(self): # """ # """ # return self.build_cmd # # def GetBuildCmd(self): # """ # return the build cmd # """ # return self.build_cmd # # def Error(self): # """ # return the error message # """ # return self.error , which may contain function names, class names, or code. Output only the next line.
self.builder = Builder.ObjBuilder(self.outfile, self.infile, self.includes,
Here is a snippet: <|code_start|> workspace : the abs path of workspace """ Builder.__init__(self, obj, compiler, workspace) self.workspace = workspace self._includes = "" self._opts = None self._infile = infile self._header_cmd = None if includes: self._includes += "\t".join(map(lambda x: "-I%s \\\n" % os.path.normpath(x), includes)) if opts: self._opts = " \\\n\t".join(map(lambda x: x, opts)) self.build_cmd = "mkdir -p %s && %s \\\n\t-c \\\n\t%s \\\n\t%s\t-o \\\n\t%s \\\n\t%s" % \ (self.obj_dir, self.compiler, self._opts, self._includes, self.obj, infile) self._header_cmd = "%s \\\n\t-MM -MG\\\n\t%s\t%s" % \ (self.compiler, self._includes, self._infile) def CalcHeaderFiles(self): """ calculate the header files that source file dependends Returns: { ret : True | False, headers : set(), msg : 'error message' } calculate successfully ret is True; otherwise ret is False and msg contains error message """ result = dict() result['ret'] = False result['headers'] = set() result['msg'] = '' <|code_end|> . Write the next line using the current file imports: import os import sys from util import Function from util import Log and context from other files: # Path: util/Function.py # DIGITS = [str(x) for x in xrange(0, 10)] # ALPHABETS = [] # def CheckName(v): # def DelFiles(path): # def MoveFiles(src, dst): # def Mkdir(target_dir): # def CalcHash(data, method='MD5'): # def GetFileHash(path, method='MD5'): # def RunCommand(cmd, ignore_stderr_when_ok=False): # def RunCommand_tty(cmd): # # Path: util/Log.py # class Log(object): # """ # Log class # """ # class __impl(object): # """ Implementation of singleton interface""" # def __init__(self): # """ # """ # self.levMap = {"ERROR":(0, "\033[31m%s%s\033[0m"), "WARNING":(1, "\033[33m%s%s\033[0m"), \ # "INFO":(2, "\033[34m%s%s\033[0m"), "MSG":(3, "\033[32m%s%s\033[0m"), \ # "UNKNOW":(4, "\033[31m%s%s\033[0m")} # self.config_level = 5 # # def setLogLevel(self, lev): # """ # Description : set log file level.The log message lower than this level will not be printed. # Args : lev : log level will be set.Value is [0-5],0 will not print any log message, 5 will print all log message # Return : NULL # """ # self.config_level = lev # # def LevPrint(self, level, msg, prefix=True): # """ # Description : print log message which has higher level than config level # Args: # level : ["ERROR", "WARNING", "INFO", "MSG", "UNKNOW"] # msg : string, log message # prefix : True , print time information # False , don't print time information # Return : None # """ # if level in self.levMap and self.levMap[level][0] > self.config_level: # return # # now = "" # pmsg = "" # if prefix: # now = "[" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) \ # + " " + str(threading.current_thread().ident) + "] " # if (level in self.levMap): # pmsg = self.levMap[level][1] % (now, msg) # else: # pmsg = "UNKNOW log level(%s)" % level # pmsg += self.levMap["UNKNOW"][1] % (now, msg) # # print(pmsg) # sys.stdout.flush() # # # # class Log # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if Log.__instance is None: # # Create and remember instance # Log.__instance = Log.__impl() # # # Store instance reference as the only member in the handle # self.__dict__['_Log__instance'] = Log.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) , which may include functions, classes, or code. Output only the next line.
retcode, msg = Function.RunCommand(self._header_cmd, ignore_stderr_when_ok=True)
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved # ################################################################################ """ test case for create dependent tree of modules Authors: zhousongsong(doublesongsong@gmail.com) Date: 2016/01/22 17:26:42 """ broc_path = os.path.realpath(os.path.join(os.path.realpath(__file__), '..', '..')) sys.path.insert(0, broc_path) class TestBrocConfig(unittest.TestCase): """ """ def test_singleton(self): """ """ <|code_end|> . Use current file imports: import os import sys import unittest import pprint from dependency import BrocConfig and context (classes, functions, or code) from other files: # Path: dependency/BrocConfig.py # class BrocConfig(object): # """ # this class manages the .broc.rc in $HOME # """ # class __impl(object): # """Implementation of singleton interface""" # def __init__(self): # """ # """ # self._file = os.path.join(os.environ['HOME'], '.broc.rc') # self._svn_repo_domain = 'https://svn.github.com' # self._git_repo_domain = 'https://github.com' # self._svn_postfix_branch = "BRANCH" # self._svn_postfix_tag = "PD_BL" # # def __str__(self): # """ # """ # return "svn repo domain: %s\ngit repo domain: %s\n \ # svn postfix branch: %s\nsvn postfix tag: %s"% (self._svn_repo_domain, # self._git_repo_domain, # self._svn_postfix_branch, # self._svn_postfix_tag) # # def Id(self): # """ # test method, return singleton id # """ # return id(self) # # def load(self): # """ # load broc configurations # Raise: # if load config failed, raise BrocConfigError # """ # try: # # if configuration file does not exists in $HOME, create one # if not os.path.isfile(self._file): # cfgfile = open(self._file, 'w') # conf = ConfigParser.ConfigParser() # conf.add_section('repo') # conf.set('repo', 'svn_repo_domain', self._svn_repo_domain) # conf.set('repo', 'git_repo_domain', self._git_repo_domain) # conf.set('repo', 'svn_postfix_branch', 'BRANCH') # conf.set('repo', 'svn_postfix_tag', 'PD_BL') # conf.write(cfgfile) # cfgfile.close() # else: # cfgfile = open(self._file, 'r') # conf = ConfigParser.ConfigParser() # conf.read(self._file) # self._svn_repo_domain = conf.get('repo', 'svn_repo_domain') # self._git_repo_domain = conf.get('repo', 'git_repo_domain') # self._svn_postfix_branch = conf.get('repo', 'svn_postfix_branch') # self._svn_postfix_tag = conf.get('repo', 'svn_postfix_tag') # except ConfigParser.Error as e: # raise BrocConfigError(str(e)) # # def RepoDomain(self, repo_type): # """ # return repository domain # Args: # repo_type : BrocMode_pb2.Module.EnumRepo # """ # if repo_type == BrocModule_pb2.Module.SVN: # return self._svn_repo_domain # elif repo_type == BrocModule_pb2.Module.GIT: # return self._git_repo_domain # # def SVNPostfixBranch(self): # """ # return postfix of svn branch # """ # return self._svn_postfix_branch # # def SVNPostfixTag(self): # """ # return postfix of svn tag # """ # return self._svn_postfix_tag # # def Dump(self): # """ # dump broc config # """ # print("-- svn domain : %s" % self._svn_repo_domain) # print("-- git domain : %s" % self._git_repo_domain) # print("-- svn branch posfix : %s" % self._svn_postfix_branch) # print("-- svn tag postfix : %s" % self._svn_postfix_tag) # # # class BrocConfig # __instance = None # def __init__(self): # """ Create singleton instance """ # # Check whether we already have an instance # if BrocConfig.__instance is None: # # Create and remember instance # BrocConfig.__instance = BrocConfig.__impl() # BrocConfig.__instance.load() # # # Store instance reference as the only member in the handle # self.__dict__['_BrocConfig__instance'] = BrocConfig.__instance # # def __getattr__(self, attr): # """ Delegate access to implementation """ # return getattr(self.__instance, attr) # # def __setattr__(self, attr, value): # """ Delegate access to implementation """ # return setattr(self.__instance, attr, value) . Output only the next line.
config1 = BrocConfig.BrocConfig()
Based on the snippet: <|code_start|>#!/usr/bin/env python here = osp.dirname(osp.abspath(__file__)) def test_label_accuracy_score(): img_file = osp.join(here, '../data/2007_000063.jpg') lbl_file = osp.join(here, '../data/2007_000063.png') img = skimage.io.imread(img_file) lbl_gt = np.array(PIL.Image.open(lbl_file), dtype=np.int32, copy=False) lbl_gt[lbl_gt == 255] = -1 lbl_pred = lbl_gt.copy() lbl_pred[lbl_pred == -1] = 0 lbl_pred = skimage.transform.rescale(lbl_pred, 1 / 16., order=0, preserve_range=True) lbl_pred = skimage.transform.resize(lbl_pred, lbl_gt.shape, order=0, preserve_range=True) lbl_pred = lbl_pred.astype(lbl_gt.dtype) <|code_end|> , predict the immediate next line with the help of imports: import os.path as osp import numpy as np import PIL.Image import skimage.io import skimage.transform import matplotlib.pyplot as plt import skimage.color from fcn import utils and context (classes, functions, sometimes code) from other files: # Path: fcn/utils.py # def batch_to_vars(batch, device=-1): # def bitget(byteval, idx): # def labelcolormap(*args, **kwargs): # def label_colormap(N=256): # def visualize_labelcolormap(*args, **kwargs): # def visualize_label_colormap(cmap): # def get_label_colortable(n_labels, shape): # def _fast_hist(label_true, label_pred, n_class): # def label_accuracy_score(label_trues, label_preds, n_class): # def centerize(src, dst_shape, margin_color=None): # def _tile_images(imgs, tile_shape, concatenated_image): # def get_tile_image(imgs, tile_shape=None, result_img=None, margin_color=None): # def resize(*args, **kwargs): # def get_tile_shape(img_num): # def label2rgb(lbl, img=None, label_names=None, n_labels=None, # alpha=0.5, thresh_suppress=0): # def get_text_color(color): # def visualize_segmentation(**kwargs): # Y, X = np.where(mask) . Output only the next line.
viz = utils.visualize_segmentation(
Here is a snippet: <|code_start|>def test_label_accuracy_score(): img_file = osp.join(here, '../data/2007_000063.jpg') lbl_file = osp.join(here, '../data/2007_000063.png') img = skimage.io.imread(img_file) lbl_gt = np.array(PIL.Image.open(lbl_file), dtype=np.int32, copy=False) lbl_gt[lbl_gt == 255] = -1 lbl_pred = lbl_gt.copy() lbl_pred[lbl_pred == -1] = 0 lbl_pred = skimage.transform.rescale( lbl_pred, 1 / 16., order=0, mode='constant', preserve_range=True, anti_aliasing=False, multichannel=True, ) lbl_pred = skimage.transform.resize( lbl_pred, lbl_gt.shape, order=0, mode='constant', preserve_range=True, anti_aliasing=False, ) lbl_pred = lbl_pred.astype(lbl_gt.dtype) <|code_end|> . Write the next line using the current file imports: import os.path as osp import numpy as np import PIL.Image import skimage.io import skimage.transform import matplotlib.pyplot as plt import skimage.color from fcn import utils and context from other files: # Path: fcn/utils.py # def batch_to_vars(batch, device=-1): # def bitget(byteval, idx): # def labelcolormap(*args, **kwargs): # def label_colormap(N=256): # def visualize_labelcolormap(*args, **kwargs): # def visualize_label_colormap(cmap): # def get_label_colortable(n_labels, shape): # def _fast_hist(label_true, label_pred, n_class): # def label_accuracy_score(label_trues, label_preds, n_class): # def centerize(src, dst_shape, margin_color=None): # def _tile_images(imgs, tile_shape, concatenated_image): # def get_tile_image(imgs, tile_shape=None, result_img=None, margin_color=None): # def resize(*args, **kwargs): # def get_tile_shape(img_num): # def label2rgb(lbl, img=None, label_names=None, n_labels=None, # alpha=0.5, thresh_suppress=0): # def get_text_color(color): # def visualize_segmentation(**kwargs): # Y, X = np.where(mask) , which may include functions, classes, or code. Output only the next line.
acc, acc_cls, mean_iu, fwavacc = utils.label_accuracy_score(
Here is a snippet: <|code_start|>#!/usr/bin/env python logging.basicConfig(level=logging.INFO) logging.info("RUNNING TEST: %s" % __file__) # packet to extract data from eth_data = struct.pack("BBBBBB", 0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33) eth_data += struct.pack("BBBBBB", 0xff, 0xff, 0xff, 0xff, 0xff, 0xff) eth_data += struct.pack("BB", 0x81, 0x00) eth_pkt = bytearray(eth_data) # bir structs for the the metadata fields <|code_end|> . Write the next line using the current file imports: import logging import struct from pif_ir.bir.objects.bir_struct import BIRStruct from pif_ir.bir.objects.metadata_instance import MetadataInstance from test_common import yaml_eth_struct_dict from test_common import yaml_eth_meta_dict and context from other files: # Path: pif_ir/bir/objects/bir_struct.py # class BIRStruct(object): # required_attributes = ['fields'] # # def __init__(self, name, struct_attrs): # check_attributes(name, struct_attrs, BIRStruct.required_attributes) # logging.debug("Adding bir_struct {0}".format(name)) # # self.name = name # self.length = 0 # self.fields = OrderedDict() # self.field_offsets = OrderedDict() # # for tmp_field in struct_attrs['fields']: # for name, size in tmp_field.items(): # self.fields[name] = size # # self.field_offsets[name] = self.length # self.length += size # # def __len__(self): # return self.length # # def field_offset(self, fld_name): # return self.field_offsets.get(fld_name, 0) # # def field_size(self, fld_name): # return self.fields.get(fld_name, 0) # # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val , which may include functions, classes, or code. Output only the next line.
bir_structs = {'eth_t':BIRStruct('eth_t', yaml_eth_struct_dict)}
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python logging.basicConfig(level=logging.INFO) logging.info("RUNNING TEST: %s" % __file__) # packet to extract data from eth_data = struct.pack("BBBBBB", 0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33) eth_data += struct.pack("BBBBBB", 0xff, 0xff, 0xff, 0xff, 0xff, 0xff) eth_data += struct.pack("BB", 0x81, 0x00) eth_pkt = bytearray(eth_data) # bir structs for the the metadata fields bir_structs = {'eth_t':BIRStruct('eth_t', yaml_eth_struct_dict)} <|code_end|> , predict the next line using imports from the current file: import logging import struct from pif_ir.bir.objects.bir_struct import BIRStruct from pif_ir.bir.objects.metadata_instance import MetadataInstance from test_common import yaml_eth_struct_dict from test_common import yaml_eth_meta_dict and context including class names, function names, and sometimes code from other files: # Path: pif_ir/bir/objects/bir_struct.py # class BIRStruct(object): # required_attributes = ['fields'] # # def __init__(self, name, struct_attrs): # check_attributes(name, struct_attrs, BIRStruct.required_attributes) # logging.debug("Adding bir_struct {0}".format(name)) # # self.name = name # self.length = 0 # self.fields = OrderedDict() # self.field_offsets = OrderedDict() # # for tmp_field in struct_attrs['fields']: # for name, size in tmp_field.items(): # self.fields[name] = size # # self.field_offsets[name] = self.length # self.length += size # # def __len__(self): # return self.length # # def field_offset(self, fld_name): # return self.field_offsets.get(fld_name, 0) # # def field_size(self, fld_name): # return self.fields.get(fld_name, 0) # # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val . Output only the next line.
metadata = MetadataInstance('eth', yaml_eth_meta_dict, bir_structs,
Given snippet: <|code_start|> class PacketInstance(object): id_next = 0 def __init__(self, packet_data, metadata_attrs, bir_structs): """ @brief PacketInstance constructor @param packet_data The original packet data as a byte array @param metadata_dict The metadata values associated with the packet @param bir_structs The structs used for metadata fields """ self.packet_data = packet_data self.idx = PacketInstance.id_next PacketInstance.id_next += 1 self.metadata = {} for name, md in metadata_attrs.items(): <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from pif_ir.bir.objects.metadata_instance import MetadataInstance from pif_ir.bir.utils.common import int_to_bytearray, bytearray_to_int from pif_ir.bir.utils.exceptions import * and context: # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val # # Path: pif_ir/bir/utils/common.py # def int_to_bytearray(bit_offset, value, bit_width): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # RBYTE_MASK = [0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff] # ret_vals = [] # ret_mask = [] # # # pad the value so it's byte aligned # padding = (8 - ((bit_offset + bit_width) % 8)) % 8 # value <<= padding # # remain = bit_width + padding # while remain > 0: # if remain == bit_width + padding: # ret_vals.append(value & 0xFF) # ret_mask.append(BYTE_MASK[padding]) # else: # ret_vals.append(value & 0xFF) # ret_mask.append(0x00) # value >>= 8 # remain -= 8 # # ret_vals[-1] &= BYTE_MASK[8-bit_offset] # ret_mask[-1] |= RBYTE_MASK[bit_offset] # return ret_vals[::-1], ret_mask[::-1] # # def bytearray_to_int(buf, bit_width, bit_offset=0): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # base = bit_offset / 8 # last = (bit_offset + bit_width + 7) / 8 # # offset = bit_offset % 8 # if last - base == 1: # shift = 8 - (offset + bit_width) # return (buf[base] >> shift) & BYTE_MASK[bit_width] # # value = 0 # remain = bit_width # for byte in buf[base:last]: # if remain == bit_width: # first byte # take = 8 - offset # value = byte & BYTE_MASK[take] # else: # take = min(8, remain) # value = (value << take) + (byte >> (8 - take)) # remain -= take # return value which might include code, classes, or functions. Output only the next line.
self.metadata[name] = MetadataInstance(name, md, bir_structs)
Given the following code snippet before the placeholder: <|code_start|> class PacketInstance(object): id_next = 0 def __init__(self, packet_data, metadata_attrs, bir_structs): """ @brief PacketInstance constructor @param packet_data The original packet data as a byte array @param metadata_dict The metadata values associated with the packet @param bir_structs The structs used for metadata fields """ self.packet_data = packet_data self.idx = PacketInstance.id_next PacketInstance.id_next += 1 self.metadata = {} for name, md in metadata_attrs.items(): self.metadata[name] = MetadataInstance(name, md, bir_structs) logging.debug("Created packet %d", self.idx) def get_bits(self, bit_width, bit_offset=0): return bytearray_to_int(self.packet_data, bit_width, bit_offset) def set_bits(self, value, bit_width, bit_offset=0): byte_offset = bit_offset / 8 offset = bit_offset % 8 <|code_end|> , predict the next line using imports from the current file: import logging from pif_ir.bir.objects.metadata_instance import MetadataInstance from pif_ir.bir.utils.common import int_to_bytearray, bytearray_to_int from pif_ir.bir.utils.exceptions import * and context including class names, function names, and sometimes code from other files: # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val # # Path: pif_ir/bir/utils/common.py # def int_to_bytearray(bit_offset, value, bit_width): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # RBYTE_MASK = [0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff] # ret_vals = [] # ret_mask = [] # # # pad the value so it's byte aligned # padding = (8 - ((bit_offset + bit_width) % 8)) % 8 # value <<= padding # # remain = bit_width + padding # while remain > 0: # if remain == bit_width + padding: # ret_vals.append(value & 0xFF) # ret_mask.append(BYTE_MASK[padding]) # else: # ret_vals.append(value & 0xFF) # ret_mask.append(0x00) # value >>= 8 # remain -= 8 # # ret_vals[-1] &= BYTE_MASK[8-bit_offset] # ret_mask[-1] |= RBYTE_MASK[bit_offset] # return ret_vals[::-1], ret_mask[::-1] # # def bytearray_to_int(buf, bit_width, bit_offset=0): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # base = bit_offset / 8 # last = (bit_offset + bit_width + 7) / 8 # # offset = bit_offset % 8 # if last - base == 1: # shift = 8 - (offset + bit_width) # return (buf[base] >> shift) & BYTE_MASK[bit_width] # # value = 0 # remain = bit_width # for byte in buf[base:last]: # if remain == bit_width: # first byte # take = 8 - offset # value = byte & BYTE_MASK[take] # else: # take = min(8, remain) # value = (value << take) + (byte >> (8 - take)) # remain -= take # return value . Output only the next line.
vals, masks = int_to_bytearray(offset, value, bit_width)
Using the snippet: <|code_start|> class PacketInstance(object): id_next = 0 def __init__(self, packet_data, metadata_attrs, bir_structs): """ @brief PacketInstance constructor @param packet_data The original packet data as a byte array @param metadata_dict The metadata values associated with the packet @param bir_structs The structs used for metadata fields """ self.packet_data = packet_data self.idx = PacketInstance.id_next PacketInstance.id_next += 1 self.metadata = {} for name, md in metadata_attrs.items(): self.metadata[name] = MetadataInstance(name, md, bir_structs) logging.debug("Created packet %d", self.idx) def get_bits(self, bit_width, bit_offset=0): <|code_end|> , determine the next line of code. You have imports: import logging from pif_ir.bir.objects.metadata_instance import MetadataInstance from pif_ir.bir.utils.common import int_to_bytearray, bytearray_to_int from pif_ir.bir.utils.exceptions import * and context (class names, function names, or code) available: # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val # # Path: pif_ir/bir/utils/common.py # def int_to_bytearray(bit_offset, value, bit_width): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # RBYTE_MASK = [0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff] # ret_vals = [] # ret_mask = [] # # # pad the value so it's byte aligned # padding = (8 - ((bit_offset + bit_width) % 8)) % 8 # value <<= padding # # remain = bit_width + padding # while remain > 0: # if remain == bit_width + padding: # ret_vals.append(value & 0xFF) # ret_mask.append(BYTE_MASK[padding]) # else: # ret_vals.append(value & 0xFF) # ret_mask.append(0x00) # value >>= 8 # remain -= 8 # # ret_vals[-1] &= BYTE_MASK[8-bit_offset] # ret_mask[-1] |= RBYTE_MASK[bit_offset] # return ret_vals[::-1], ret_mask[::-1] # # def bytearray_to_int(buf, bit_width, bit_offset=0): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # base = bit_offset / 8 # last = (bit_offset + bit_width + 7) / 8 # # offset = bit_offset % 8 # if last - base == 1: # shift = 8 - (offset + bit_width) # return (buf[base] >> shift) & BYTE_MASK[bit_width] # # value = 0 # remain = bit_width # for byte in buf[base:last]: # if remain == bit_width: # first byte # take = 8 - offset # value = byte & BYTE_MASK[take] # else: # take = min(8, remain) # value = (value << take) + (byte >> (8 - take)) # remain -= take # return value . Output only the next line.
return bytearray_to_int(self.packet_data, bit_width, bit_offset)
Given snippet: <|code_start|> class ControlState(object): def __init__(self, control_state_attr, header, bir_parser): # control_state format: # - [[cond, new_offset], [,], [,], ..., default_offset] # - [[cond, new_bb], [,], [,], ..., default_bb] self.offset = control_state_attr[0] self.basic_block = control_state_attr[1] self.header = header self.bir_parser = bir_parser def _get_offset(self, packet, bit_offset): for cond in self.offset: if isinstance(cond, str) or isinstance(cond, int): return self.bir_parser.eval_inst(cond, self.header, packet, bit_offset) elif self.bir_parser.eval_cond(cond[0], self.header, packet, bit_offset): return self.bir_parser.eval_inst(cond[1], self.header, packet, bit_offset) <|code_end|> , continue by predicting the next line. Consider current file imports: from pif_ir.bir.utils.exceptions import BIRError and context: # Path: pif_ir/bir/utils/exceptions.py # class BIRError(Exception): # """ a base class for all bir exceptions # """ # def __init__(self, msg="BIR Error!"): # self.value = msg which might include code, classes, or functions. Output only the next line.
raise BIRError("didn't find offset!")
Next line prediction: <|code_start|> # field_ref: BIR keywords def p_field_ref_0(self, p): """ field_ref : OFFSET | DONE """ p[0] = self.bit_offset if p[1] == "$offset$" else None # field_ref: header field value in the packet def p_field_ref_1(self, p): """ field_ref : ID """ size = self.header.field_size(p[1]) offset = self.bit_offset + self.header.field_offset(p[1]) p[0] = self.packet.get_bits(size, offset) # field_ref: metadata value def p_field_ref_2(self, p): """ field_ref : ID PERIOD ID """ p[0] = int(self.packet.metadata[p[1]].get_value(p[3])) def p_int_const(self, p): """ int_const : INT_CONST_HEX | INT_CONST_DEC """ p[0] = p[1] def p_error(self, p): if p is None: msg = "Incomplete expression: {}".format(self.exp) <|code_end|> . Use current file imports: (from ply import lex from ply.lex import TOKEN from ply import yacc from pif_ir.bir.utils.exceptions import BIRParsingError) and context including class names, function names, or small code snippets from other files: # Path: pif_ir/bir/utils/exceptions.py # class BIRParsingError(BIRError): # """ something went wrong while parsing an instruction or control state # """ # def __init__(self, msg): # super(BIRParsingError, self).__init__() # self.value = msg . Output only the next line.
raise BIRParsingError(msg)
Using the snippet: <|code_start|> bit_offset) self._assign(sig[0], result, packet, bit_offset) # O Type instructions are the build-in functionality def _handle_o_call(self, sig, packet, bit_offset): op = sig[0] args = sig[1] if op == 'tLookup': resp = packet.metadata[args[0]] req = packet.metadata[args[1]] if self.table: resp.reset_values() self.table.lookup(req, resp) elif op == 'hInsert': length = args[0] if len(args) > 0 else len(self.header) packet.insert(length, bit_offset) elif op == 'hRemove': length = args[0] if len(args) > 0 else len(self.header) packet.remove(length, bit_offset) elif op == 'tInsert': mask = args[2] if len(args) > 2 else None if self.table: self.table.add_entry(args[0], args[1], mask) elif op == 'tRemove': mask = args[2] if len(args) > 2 else None if self.table: self.table.remove_entry(args[0], args[1], mask) else: <|code_end|> , determine the next line of code. You have imports: from pif_ir.bir.utils.exceptions import BIRError and context (class names, function names, or code) available: # Path: pif_ir/bir/utils/exceptions.py # class BIRError(Exception): # """ a base class for all bir exceptions # """ # def __init__(self, msg="BIR Error!"): # self.value = msg . Output only the next line.
raise BIRError("unknown build-in function: {}".format(op))
Predict the next line after this snippet: <|code_start|> class ValueInstance(object): def __init__(self, name, bit_width, value=0): if bit_width <= 0: raise BIRFieldWidthError(name, bit_width) logging.debug("Adding value {0}".format(name)) self.name = name self.bit_width = bit_width self.value = value def __len__(self): return self.bit_width def __int__(self): return self.value def extract(self, buf, bit_offset=0): <|code_end|> using the current file's imports: import logging from pif_ir.bir.utils.common import bytearray_to_int, int_to_bytearray and any relevant context from other files: # Path: pif_ir/bir/utils/common.py # def bytearray_to_int(buf, bit_width, bit_offset=0): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # base = bit_offset / 8 # last = (bit_offset + bit_width + 7) / 8 # # offset = bit_offset % 8 # if last - base == 1: # shift = 8 - (offset + bit_width) # return (buf[base] >> shift) & BYTE_MASK[bit_width] # # value = 0 # remain = bit_width # for byte in buf[base:last]: # if remain == bit_width: # first byte # take = 8 - offset # value = byte & BYTE_MASK[take] # else: # take = min(8, remain) # value = (value << take) + (byte >> (8 - take)) # remain -= take # return value # # def int_to_bytearray(bit_offset, value, bit_width): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # RBYTE_MASK = [0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff] # ret_vals = [] # ret_mask = [] # # # pad the value so it's byte aligned # padding = (8 - ((bit_offset + bit_width) % 8)) % 8 # value <<= padding # # remain = bit_width + padding # while remain > 0: # if remain == bit_width + padding: # ret_vals.append(value & 0xFF) # ret_mask.append(BYTE_MASK[padding]) # else: # ret_vals.append(value & 0xFF) # ret_mask.append(0x00) # value >>= 8 # remain -= 8 # # ret_vals[-1] &= BYTE_MASK[8-bit_offset] # ret_mask[-1] |= RBYTE_MASK[bit_offset] # return ret_vals[::-1], ret_mask[::-1] . Output only the next line.
self.value = bytearray_to_int(buf, self.bit_width, bit_offset)
Predict the next line after this snippet: <|code_start|> class ValueInstance(object): def __init__(self, name, bit_width, value=0): if bit_width <= 0: raise BIRFieldWidthError(name, bit_width) logging.debug("Adding value {0}".format(name)) self.name = name self.bit_width = bit_width self.value = value def __len__(self): return self.bit_width def __int__(self): return self.value def extract(self, buf, bit_offset=0): self.value = bytearray_to_int(buf, self.bit_width, bit_offset) return self.value def update(self, buf, bit_offset=0): byte_offset = bit_offset / 8 offset = bit_offset % 8 <|code_end|> using the current file's imports: import logging from pif_ir.bir.utils.common import bytearray_to_int, int_to_bytearray and any relevant context from other files: # Path: pif_ir/bir/utils/common.py # def bytearray_to_int(buf, bit_width, bit_offset=0): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # base = bit_offset / 8 # last = (bit_offset + bit_width + 7) / 8 # # offset = bit_offset % 8 # if last - base == 1: # shift = 8 - (offset + bit_width) # return (buf[base] >> shift) & BYTE_MASK[bit_width] # # value = 0 # remain = bit_width # for byte in buf[base:last]: # if remain == bit_width: # first byte # take = 8 - offset # value = byte & BYTE_MASK[take] # else: # take = min(8, remain) # value = (value << take) + (byte >> (8 - take)) # remain -= take # return value # # def int_to_bytearray(bit_offset, value, bit_width): # BYTE_MASK = [0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff] # RBYTE_MASK = [0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff] # ret_vals = [] # ret_mask = [] # # # pad the value so it's byte aligned # padding = (8 - ((bit_offset + bit_width) % 8)) % 8 # value <<= padding # # remain = bit_width + padding # while remain > 0: # if remain == bit_width + padding: # ret_vals.append(value & 0xFF) # ret_mask.append(BYTE_MASK[padding]) # else: # ret_vals.append(value & 0xFF) # ret_mask.append(0x00) # value >>= 8 # remain -= 8 # # ret_vals[-1] &= BYTE_MASK[8-bit_offset] # ret_mask[-1] |= RBYTE_MASK[bit_offset] # return ret_vals[::-1], ret_mask[::-1] . Output only the next line.
vals, masks = int_to_bytearray(offset, self.value, self.bit_width)
Given the following code snippet before the placeholder: <|code_start|> class ControlFlow(Processor): """ @brief Class for a control flow object @param name The name of the control flow AIR object @param air_control_flow_attrs The attributes of the control_flow AIR object @param first_packet_offset The first packet offset @param first_basic_block The first basic block """ required_attributes = ['start_control_state'] def __init__(self, name, control_flow_attrs, basic_blocks, bir_parser): super(ControlFlow, self,).__init__(name) check_attributes(name, control_flow_attrs, ControlFlow.required_attributes) logging.debug("Adding Control Flow {0}".format(name)) self.basic_blocks = basic_blocks cf = control_flow_attrs['start_control_state'] check_control_state(self.name, cf) <|code_end|> , predict the next line using imports from the current file: import logging from pif_ir.bir.objects.control_state import ControlState from pif_ir.bir.objects.processor import Processor from pif_ir.bir.utils.validate import check_attributes from pif_ir.bir.utils.validate import check_control_state and context including class names, function names, and sometimes code from other files: # Path: pif_ir/bir/objects/control_state.py # class ControlState(object): # def __init__(self, control_state_attr, header, bir_parser): # # control_state format: # # - [[cond, new_offset], [,], [,], ..., default_offset] # # - [[cond, new_bb], [,], [,], ..., default_bb] # self.offset = control_state_attr[0] # self.basic_block = control_state_attr[1] # self.header = header # self.bir_parser = bir_parser # # def _get_offset(self, packet, bit_offset): # for cond in self.offset: # if isinstance(cond, str) or isinstance(cond, int): # return self.bir_parser.eval_inst(cond, self.header, packet, # bit_offset) # elif self.bir_parser.eval_cond(cond[0], self.header, packet, # bit_offset): # return self.bir_parser.eval_inst(cond[1], self.header, packet, # bit_offset) # raise BIRError("didn't find offset!") # # def _get_basic_block(self, packet, bit_offset): # for cond in self.basic_block: # if isinstance(cond, str): # return cond # elif self.bir_parser.eval_cond(cond[0], self.header, packet, # bit_offset): # return cond[1] # raise BIRError("didn't find basic_block!") # # def process(self, packet, bit_offset): # offset = self._get_offset(packet, bit_offset) # basic_block = self._get_basic_block(packet, bit_offset) # if basic_block == "$done$": # basic_block = None # return offset, basic_block # # Path: pif_ir/bir/objects/processor.py # class Processor(object): # def __init__(self, name, next_processor=None): # self.name = name # self.next_processor = next_processor # # def process(self, packet, bit_offset=0): # msg = "Processor {}: does not implement process()".format(self.name) # raise BIRError(msg) # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) # # Path: pif_ir/bir/utils/validate.py # def check_control_state(obj_name, control_state_attributes): # # has only 2 attributes (i.e. offset, basic_block) # if len(control_state_attributes) != 2: # raise BIRControlStateError(obj_name, "expecting 2 attributes") # # # offset conditions format must be [cond, offset] # # must have a default offset (not required to be the last!) # default_offset = False # for cond in control_state_attributes[0]: # if isinstance(cond, list) and len(cond) == 2: # pass # elif isinstance(cond, str) or isinstance(cond, int): # default_offset = True # else: # msg = "unexpected offset condition: {}".format(cond) # raise BIRControlStateError(obj_name, msg) # if not default_offset: # raise BIRControlStateError(obj_name, "missing default offset") # # # basic_block conditions format must be [cond, basic_block] # # must have a default basic_block (not required to be the last!) # default_bb = False # for cond in control_state_attributes[1]: # if isinstance(cond, list) and len(cond) == 2: # pass # elif isinstance(cond, str): # default_bb = True # else: # msg = "unexpected basic_block condition: {}".format(cond) # raise BIRControlStateError(obj_name, msg) # if not default_bb: # raise BIRControlStateError(obj_name, "missing default basic block") . Output only the next line.
self.control_state = ControlState(cf, None, bir_parser)
Based on the snippet: <|code_start|> class ControlFlow(Processor): """ @brief Class for a control flow object @param name The name of the control flow AIR object @param air_control_flow_attrs The attributes of the control_flow AIR object @param first_packet_offset The first packet offset @param first_basic_block The first basic block """ required_attributes = ['start_control_state'] def __init__(self, name, control_flow_attrs, basic_blocks, bir_parser): super(ControlFlow, self,).__init__(name) <|code_end|> , predict the immediate next line with the help of imports: import logging from pif_ir.bir.objects.control_state import ControlState from pif_ir.bir.objects.processor import Processor from pif_ir.bir.utils.validate import check_attributes from pif_ir.bir.utils.validate import check_control_state and context (classes, functions, sometimes code) from other files: # Path: pif_ir/bir/objects/control_state.py # class ControlState(object): # def __init__(self, control_state_attr, header, bir_parser): # # control_state format: # # - [[cond, new_offset], [,], [,], ..., default_offset] # # - [[cond, new_bb], [,], [,], ..., default_bb] # self.offset = control_state_attr[0] # self.basic_block = control_state_attr[1] # self.header = header # self.bir_parser = bir_parser # # def _get_offset(self, packet, bit_offset): # for cond in self.offset: # if isinstance(cond, str) or isinstance(cond, int): # return self.bir_parser.eval_inst(cond, self.header, packet, # bit_offset) # elif self.bir_parser.eval_cond(cond[0], self.header, packet, # bit_offset): # return self.bir_parser.eval_inst(cond[1], self.header, packet, # bit_offset) # raise BIRError("didn't find offset!") # # def _get_basic_block(self, packet, bit_offset): # for cond in self.basic_block: # if isinstance(cond, str): # return cond # elif self.bir_parser.eval_cond(cond[0], self.header, packet, # bit_offset): # return cond[1] # raise BIRError("didn't find basic_block!") # # def process(self, packet, bit_offset): # offset = self._get_offset(packet, bit_offset) # basic_block = self._get_basic_block(packet, bit_offset) # if basic_block == "$done$": # basic_block = None # return offset, basic_block # # Path: pif_ir/bir/objects/processor.py # class Processor(object): # def __init__(self, name, next_processor=None): # self.name = name # self.next_processor = next_processor # # def process(self, packet, bit_offset=0): # msg = "Processor {}: does not implement process()".format(self.name) # raise BIRError(msg) # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) # # Path: pif_ir/bir/utils/validate.py # def check_control_state(obj_name, control_state_attributes): # # has only 2 attributes (i.e. offset, basic_block) # if len(control_state_attributes) != 2: # raise BIRControlStateError(obj_name, "expecting 2 attributes") # # # offset conditions format must be [cond, offset] # # must have a default offset (not required to be the last!) # default_offset = False # for cond in control_state_attributes[0]: # if isinstance(cond, list) and len(cond) == 2: # pass # elif isinstance(cond, str) or isinstance(cond, int): # default_offset = True # else: # msg = "unexpected offset condition: {}".format(cond) # raise BIRControlStateError(obj_name, msg) # if not default_offset: # raise BIRControlStateError(obj_name, "missing default offset") # # # basic_block conditions format must be [cond, basic_block] # # must have a default basic_block (not required to be the last!) # default_bb = False # for cond in control_state_attributes[1]: # if isinstance(cond, list) and len(cond) == 2: # pass # elif isinstance(cond, str): # default_bb = True # else: # msg = "unexpected basic_block condition: {}".format(cond) # raise BIRControlStateError(obj_name, msg) # if not default_bb: # raise BIRControlStateError(obj_name, "missing default basic block") . Output only the next line.
check_attributes(name, control_flow_attrs,
Continue the code snippet: <|code_start|> class ControlFlow(Processor): """ @brief Class for a control flow object @param name The name of the control flow AIR object @param air_control_flow_attrs The attributes of the control_flow AIR object @param first_packet_offset The first packet offset @param first_basic_block The first basic block """ required_attributes = ['start_control_state'] def __init__(self, name, control_flow_attrs, basic_blocks, bir_parser): super(ControlFlow, self,).__init__(name) check_attributes(name, control_flow_attrs, ControlFlow.required_attributes) logging.debug("Adding Control Flow {0}".format(name)) self.basic_blocks = basic_blocks cf = control_flow_attrs['start_control_state'] <|code_end|> . Use current file imports: import logging from pif_ir.bir.objects.control_state import ControlState from pif_ir.bir.objects.processor import Processor from pif_ir.bir.utils.validate import check_attributes from pif_ir.bir.utils.validate import check_control_state and context (classes, functions, or code) from other files: # Path: pif_ir/bir/objects/control_state.py # class ControlState(object): # def __init__(self, control_state_attr, header, bir_parser): # # control_state format: # # - [[cond, new_offset], [,], [,], ..., default_offset] # # - [[cond, new_bb], [,], [,], ..., default_bb] # self.offset = control_state_attr[0] # self.basic_block = control_state_attr[1] # self.header = header # self.bir_parser = bir_parser # # def _get_offset(self, packet, bit_offset): # for cond in self.offset: # if isinstance(cond, str) or isinstance(cond, int): # return self.bir_parser.eval_inst(cond, self.header, packet, # bit_offset) # elif self.bir_parser.eval_cond(cond[0], self.header, packet, # bit_offset): # return self.bir_parser.eval_inst(cond[1], self.header, packet, # bit_offset) # raise BIRError("didn't find offset!") # # def _get_basic_block(self, packet, bit_offset): # for cond in self.basic_block: # if isinstance(cond, str): # return cond # elif self.bir_parser.eval_cond(cond[0], self.header, packet, # bit_offset): # return cond[1] # raise BIRError("didn't find basic_block!") # # def process(self, packet, bit_offset): # offset = self._get_offset(packet, bit_offset) # basic_block = self._get_basic_block(packet, bit_offset) # if basic_block == "$done$": # basic_block = None # return offset, basic_block # # Path: pif_ir/bir/objects/processor.py # class Processor(object): # def __init__(self, name, next_processor=None): # self.name = name # self.next_processor = next_processor # # def process(self, packet, bit_offset=0): # msg = "Processor {}: does not implement process()".format(self.name) # raise BIRError(msg) # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) # # Path: pif_ir/bir/utils/validate.py # def check_control_state(obj_name, control_state_attributes): # # has only 2 attributes (i.e. offset, basic_block) # if len(control_state_attributes) != 2: # raise BIRControlStateError(obj_name, "expecting 2 attributes") # # # offset conditions format must be [cond, offset] # # must have a default offset (not required to be the last!) # default_offset = False # for cond in control_state_attributes[0]: # if isinstance(cond, list) and len(cond) == 2: # pass # elif isinstance(cond, str) or isinstance(cond, int): # default_offset = True # else: # msg = "unexpected offset condition: {}".format(cond) # raise BIRControlStateError(obj_name, msg) # if not default_offset: # raise BIRControlStateError(obj_name, "missing default offset") # # # basic_block conditions format must be [cond, basic_block] # # must have a default basic_block (not required to be the last!) # default_bb = False # for cond in control_state_attributes[1]: # if isinstance(cond, list) and len(cond) == 2: # pass # elif isinstance(cond, str): # default_bb = True # else: # msg = "unexpected basic_block condition: {}".format(cond) # raise BIRControlStateError(obj_name, msg) # if not default_bb: # raise BIRControlStateError(obj_name, "missing default basic block") . Output only the next line.
check_control_state(self.name, cf)
Given the following code snippet before the placeholder: <|code_start|> class MetadataInstance(object): required_attributes = ['values', 'visibility'] def __init__(self, name, metadata_attrs, bir_structs, buf=None, bit_offset=0): check_attributes(name, metadata_attrs, MetadataInstance.required_attributes) logging.debug("Adding metadata {0}".format(name)) self.name = name self.values = OrderedDict() # FIXME: used for syntactic checking self.visibility = metadata_attrs['visibility'] struct_name = metadata_attrs['values'] for f_name, f_size in bir_structs[struct_name].fields.items(): <|code_end|> , predict the next line using imports from the current file: import logging from collections import OrderedDict from pif_ir.bir.objects.value_instance import ValueInstance from pif_ir.bir.utils.validate import check_attributes and context including class names, function names, and sometimes code from other files: # Path: pif_ir/bir/objects/value_instance.py # class ValueInstance(object): # def __init__(self, name, bit_width, value=0): # if bit_width <= 0: # raise BIRFieldWidthError(name, bit_width) # logging.debug("Adding value {0}".format(name)) # self.name = name # self.bit_width = bit_width # self.value = value # # def __len__(self): # return self.bit_width # # def __int__(self): # return self.value # # def extract(self, buf, bit_offset=0): # self.value = bytearray_to_int(buf, self.bit_width, bit_offset) # return self.value # # def update(self, buf, bit_offset=0): # byte_offset = bit_offset / 8 # offset = bit_offset % 8 # # vals, masks = int_to_bytearray(offset, self.value, self.bit_width) # for idx, (val, mask) in enumerate(zip(vals,masks)): # buf[byte_offset + idx] &= mask # buf[byte_offset + idx] += val # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) . Output only the next line.
self.values[f_name] = ValueInstance(f_name, f_size)
Given the code snippet: <|code_start|> class MetadataInstance(object): required_attributes = ['values', 'visibility'] def __init__(self, name, metadata_attrs, bir_structs, buf=None, bit_offset=0): <|code_end|> , generate the next line using the imports in this file: import logging from collections import OrderedDict from pif_ir.bir.objects.value_instance import ValueInstance from pif_ir.bir.utils.validate import check_attributes and context (functions, classes, or occasionally code) from other files: # Path: pif_ir/bir/objects/value_instance.py # class ValueInstance(object): # def __init__(self, name, bit_width, value=0): # if bit_width <= 0: # raise BIRFieldWidthError(name, bit_width) # logging.debug("Adding value {0}".format(name)) # self.name = name # self.bit_width = bit_width # self.value = value # # def __len__(self): # return self.bit_width # # def __int__(self): # return self.value # # def extract(self, buf, bit_offset=0): # self.value = bytearray_to_int(buf, self.bit_width, bit_offset) # return self.value # # def update(self, buf, bit_offset=0): # byte_offset = bit_offset / 8 # offset = bit_offset % 8 # # vals, masks = int_to_bytearray(offset, self.value, self.bit_width) # for idx, (val, mask) in enumerate(zip(vals,masks)): # buf[byte_offset + idx] &= mask # buf[byte_offset + idx] += val # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) . Output only the next line.
check_attributes(name, metadata_attrs,
Based on the snippet: <|code_start|> if entry.check_match(parsed_packet): action_ref = entry.action_ref params = entry.action_params logging.debug("Pkt %d hit" % parsed_packet.id) hit = True self.packet_count += 1 self.byte_count += parsed_packet.length() break if not hit: if self.default_entry: action_ref = self.default_entry.action_ref params = self.default_entry.action_params logging.debug("Pkt %d miss" % parsed_packet.id) if action_ref: self.action_map[action_ref].eval(parsed_packet, params) return (hit, action_ref) def add_entry(self, entry): """ @brief Add an entry to the table @param entry The entry to add to the table If entry is a TableEntryDefault object, then set the default entry """ logging.debug("Adding entry to %s" % self.name) # @FIXME: Check entry is proper type for this table # @FIXME: Support entry priorities for ternary matching <|code_end|> , predict the immediate next line with the help of imports: import sys from threading import Condition from pif_ir.meta_ir.common import * from pif_ir.air.objects.table_entry import TableEntryExact from pif_ir.air.objects.table_entry import TableEntryTernary from pif_ir.air.objects.table_entry import TableEntryDefault and context (classes, functions, sometimes code) from other files: # Path: pif_ir/air/objects/table_entry.py # class TableEntryExact(TableEntryBase): # """ # @brief Match entry for exact matching # """ # def __init__(self, match_values, action_ref, action_params): # """ # @param match_values A map from match fields to values # @param action_ref The name of the action to execute # @param action_params Map from parameter name to value # """ # TableEntryBase.__init__(self, action_ref, action_params) # self.match_values = match_values # # def check_match(self, parsed_packet): # """ # @brief Check if packet matches this entry # @return (action_name, action_param_map) if match; None otherwise # """ # for field_name, value in self.match_values.items(): # p_value = parsed_packet.get_field(field_name) # if p_value is None or p_value != value: # return None # return (self.action_ref, self.action_params) # # Path: pif_ir/air/objects/table_entry.py # class TableEntryTernary(TableEntryBase): # """ # @brief General (ternary) match table # # Note that an entry here supports exact match as well; if a mask # is not specified for a field, then the match is exact. # """ # def __init__(self, match_values, match_masks, action_ref, action_params, # priority): # """ # @param match_values A map from match fields to values # @param match_masks A map from match fields to masks for comparing # @param action_ref The name of the action to execute # @param action_params Map from parameter name to value # @param priority The priority of the entry # # Higher numbers are higher priority # """ # meta_ir_assert(match_masks is None or isinstance(match_masks, dict), # "Bad mask parameter to table_entry initializer") # TableEntryBase.__init__(self, action_ref, action_params) # self.match_masks = match_masks # self.match_values = match_values # self.priority = priority # # # def check_match(self, parsed_packet): # """ # @brief Check if packet matches this entry # @return (action_name, action_param_map) if match; None otherwise # """ # for field_name, value in self.match_values.items(): # mask = deref_or_none(self.match_masks, field_name) # p_value = parsed_packet.get_field(field_name) # if p_value is None: # return None # if mask is not None: # if p_value & mask != value & mask: # return None # else: # if p_value != value: # return None # # return (self.action_ref, self.action_params) # # Path: pif_ir/air/objects/table_entry.py # class TableEntryDefault(TableEntryBase): # """ # Entry object for a default match. Same as TableEntryBase # """ # pass . Output only the next line.
if isinstance(entry, TableEntryDefault):
Here is a snippet: <|code_start|>#!/usr/bin/env python logging.basicConfig(level=logging.INFO) logging.info("RUNNING TEST: %s" % __file__) # packet to extract data from eth_data = struct.pack("BBBBBB", 0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33) eth_data += struct.pack("BBBBBB", 0xff, 0xff, 0xff, 0xff, 0xff, 0xff) eth_data += struct.pack("BB", 0x81, 0x00) eth_pkt = bytearray(eth_data) <|code_end|> . Write the next line using the current file imports: import logging import struct from pif_ir.bir.objects.packet_instance import PacketInstance and context from other files: # Path: pif_ir/bir/objects/packet_instance.py # class PacketInstance(object): # id_next = 0 # # def __init__(self, packet_data, metadata_attrs, bir_structs): # """ # @brief PacketInstance constructor # @param packet_data The original packet data as a byte array # @param metadata_dict The metadata values associated with the packet # @param bir_structs The structs used for metadata fields # """ # self.packet_data = packet_data # self.idx = PacketInstance.id_next # PacketInstance.id_next += 1 # # self.metadata = {} # for name, md in metadata_attrs.items(): # self.metadata[name] = MetadataInstance(name, md, bir_structs) # logging.debug("Created packet %d", self.idx) # # def get_bits(self, bit_width, bit_offset=0): # return bytearray_to_int(self.packet_data, bit_width, bit_offset) # # def set_bits(self, value, bit_width, bit_offset=0): # byte_offset = bit_offset / 8 # offset = bit_offset % 8 # # vals, masks = int_to_bytearray(offset, value, bit_width) # for idx, (val, mask) in enumerate(zip(vals,masks)): # self.packet_data[byte_offset + idx] &= mask # self.packet_data[byte_offset + idx] += val # # def insert(self, length, bit_offset=0): # byte_offset = bit_offset / 8 # offset = bit_offset % 8 # # # FIXME: enforced for simplicity # if offset != 0: # raise BIRError("packet insert offset should be byte address") # if length %8 != 0: # raise BIRError("packet insert length should be a factor of 8") # # tmp = self.packet_data[:byte_offset] # tmp += bytearray(length/8) # tmp += self.packet_data[byte_offset:] # self.packet_data = tmp # # def remove(self, length, bit_offset=0): # byte_offset = bit_offset / 8 # offset = bit_offset % 8 # # # FIXME: enforced for simplicity # if offset != 0: # raise BIRError("packet remove offset should be byte address") # if length %8 != 0: # raise BIRError("packet remove length should be a factor of 8") # # tmp = self.packet_data[:byte_offset] # tmp += self.packet_data[byte_offset + (length/8):] # self.packet_data = tmp , which may include functions, classes, or code. Output only the next line.
pkt = PacketInstance(eth_pkt, {}, None)
Using the snippet: <|code_start|>#!/usr/bin/env python logging.basicConfig(level=logging.INFO) logging.info("RUNNING TEST: %s" % __file__) data = struct.pack("BBBBBBBB", 0x81, 0, 0xa1, 0x64, 0x81, 0, 0, 0xc8) pkt = bytearray(data) # test cases: (size, offset, expected result) tests = [(8, 0, 0x81), (16, 0, 0x8100), (3, 0, 4), (12, 0, 0x810), (8, 3, 0x08), (16, 3, 0x0805), (3, 3, 0), (12, 3, 0x080), (8, 7, 0x80), (16, 7, 0x8050), (3, 7, 4), (12, 7, 0x805), (3, 5, 1), (12, 4, 0x100), (13, 19, 0x164)] for case, args in enumerate(tests): <|code_end|> , determine the next line of code. You have imports: import logging import struct from pif_ir.bir.objects.value_instance import ValueInstance and context (class names, function names, or code) available: # Path: pif_ir/bir/objects/value_instance.py # class ValueInstance(object): # def __init__(self, name, bit_width, value=0): # if bit_width <= 0: # raise BIRFieldWidthError(name, bit_width) # logging.debug("Adding value {0}".format(name)) # self.name = name # self.bit_width = bit_width # self.value = value # # def __len__(self): # return self.bit_width # # def __int__(self): # return self.value # # def extract(self, buf, bit_offset=0): # self.value = bytearray_to_int(buf, self.bit_width, bit_offset) # return self.value # # def update(self, buf, bit_offset=0): # byte_offset = bit_offset / 8 # offset = bit_offset % 8 # # vals, masks = int_to_bytearray(offset, self.value, self.bit_width) # for idx, (val, mask) in enumerate(zip(vals,masks)): # buf[byte_offset + idx] &= mask # buf[byte_offset + idx] += val . Output only the next line.
val = ValueInstance('val', args[0])
Predict the next line for this snippet: <|code_start|> class BIRStruct(object): required_attributes = ['fields'] def __init__(self, name, struct_attrs): <|code_end|> with the help of current file imports: import logging from collections import OrderedDict from pif_ir.bir.utils.validate import check_attributes and context from other files: # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) , which may contain function names, class names, or code. Output only the next line.
check_attributes(name, struct_attrs, BIRStruct.required_attributes)
Given snippet: <|code_start|> class Processor(object): def __init__(self, name, next_processor=None): self.name = name self.next_processor = next_processor def process(self, packet, bit_offset=0): msg = "Processor {}: does not implement process()".format(self.name) <|code_end|> , continue by predicting the next line. Consider current file imports: from threading import Thread from pif_ir.bir.utils.exceptions import BIRError and context: # Path: pif_ir/bir/utils/exceptions.py # class BIRError(Exception): # """ a base class for all bir exceptions # """ # def __init__(self, msg="BIR Error!"): # self.value = msg which might include code, classes, or functions. Output only the next line.
raise BIRError(msg)
Given the following code snippet before the placeholder: <|code_start|> class Table(object): required_attributes = ['match_type', 'depth', 'request', 'response', 'operations'] def __init__(self, name, table_attrs): check_attributes(name, table_attrs, Table.required_attributes) logging.debug("Adding table {0}".format(name)) self.name = name self.match_type = table_attrs['match_type'] self.depth = table_attrs['depth'] # FIXME: unused, but could be used for type checking? self.req_attrs = {'type':'metadata', 'values':table_attrs['request']} self.resp_attrs = {'type':'metadata', 'values':table_attrs['response']} self.operations = table_attrs.get('operations', None ) # The list of table entries self.entries = [] def add_entry(self, *args): # accepted formats: add_entry(TableEntry) # add_entry(val_metadata, key_metadata) # add_entry(val_meta, key_meta, mask_meta) if len(args) == 1: entry = args[0] elif len(args) == 2: val = args[0].to_dict() key = args[1].to_dict() <|code_end|> , predict the next line using imports from the current file: import logging from collections import OrderedDict from pif_ir.bir.objects.metadata_instance import MetadataInstance from pif_ir.bir.objects.table_entry import TableEntry from pif_ir.bir.utils.exceptions import BIRTableEntryError from pif_ir.bir.utils.validate import check_attributes and context including class names, function names, and sometimes code from other files: # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val # # Path: pif_ir/bir/objects/table_entry.py # class TableEntry(object): # def __init__(self, type_, value, key, mask): # self.type_ = type_ # self.value = value # self.key = key # self.mask = mask # # def check(self, request): # if self.type_ == 'valid': # return self._check_valid(request) # elif self.type_ == 'exact': # return self._check_exact(request) # elif self.type_ == 'ternary': # return self._check_ternary(request) # elif self.type_ == 'lpm': # return self._check_lpm(request) # logging.warning("unknown TableEntry type") # return False # # def _check_exact(self, request): # for fld_name, value in self.key.items(): # if fld_name not in request.values: # return False # elif int(request.get_value(fld_name)) != int(value): # return False # return True # # def _apply_mask(self, fld_name, val): # if self.mask == None or fld_name not in self.mask.keys(): # return int(val) # return int(val) & int(self.mask[fld_name]) # # def _check_ternary(self, request): # for fld_name, value in self.key.items(): # if fld_name not in request.values: # return False # elif (self._apply_mask(fld_name, request.get_value(fld_name)) != # self._apply_mask(fld_name, value)): # return False # return True # # def _check_valid(self, request): # logging.warning("FIXME: implement TableEntry valid") # return False # def _check_lpm(self, request): # logging.warning("FIXME: implement TableEntry lpm") # return False # # Path: pif_ir/bir/utils/exceptions.py # class BIRTableEntryError(BIRError): # """ an entry couldn't be added to table # """ # def __init__(self, name, msg): # super(BIRTableEntryError, self).__init__() # self.value = "table({}): {}".format(name, msg) # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) . Output only the next line.
entry = TableEntry(self.match_type, val, key, None)
Based on the snippet: <|code_start|> class Table(object): required_attributes = ['match_type', 'depth', 'request', 'response', 'operations'] def __init__(self, name, table_attrs): <|code_end|> , predict the immediate next line with the help of imports: import logging from collections import OrderedDict from pif_ir.bir.objects.metadata_instance import MetadataInstance from pif_ir.bir.objects.table_entry import TableEntry from pif_ir.bir.utils.exceptions import BIRTableEntryError from pif_ir.bir.utils.validate import check_attributes and context (classes, functions, sometimes code) from other files: # Path: pif_ir/bir/objects/metadata_instance.py # class MetadataInstance(object): # required_attributes = ['values', 'visibility'] # # def __init__(self, name, metadata_attrs, bir_structs, buf=None, # bit_offset=0): # check_attributes(name, metadata_attrs, # MetadataInstance.required_attributes) # # logging.debug("Adding metadata {0}".format(name)) # self.name = name # self.values = OrderedDict() # # FIXME: used for syntactic checking # self.visibility = metadata_attrs['visibility'] # # struct_name = metadata_attrs['values'] # for f_name, f_size in bir_structs[struct_name].fields.items(): # self.values[f_name] = ValueInstance(f_name, f_size) # # if buf: # self.extract(buf, bit_offset) # # def __len__(self): # return sum([len(fld) for fld in self.values.values()]) # # def __int__(self): # value = 0; # for fld in self.values.values(): # value = (value << len(fld)) + int(fld) # return value # # def to_dict(self): # return dict([(v.name,int(v)) for v in self.values.values()]) # # def extract(self, buf, bit_offset=0): # fld_offset = 0; # for fld in self.values.values(): # fld.extract(buf, bit_offset + fld_offset); # fld_offset += len(fld) # # def serialize(self): # byte_list = bytearray(len(self)/8) # bit_offset = 0; # for fld in self.values.values(): # fld.update(byte_list, bit_offset) # bit_offset += len(fld) # return byte_list # # def get_value(self, value_name): # if value_name not in self.values: # return 0 # return self.values[value_name].value # # def set_value(self, value_name, value): # fld = self.values.get(value_name, None) # if fld: # fld.value = value # # def reset_values(self, new_val=0): # for fld in self.values.values(): # fld.value = new_val # # Path: pif_ir/bir/objects/table_entry.py # class TableEntry(object): # def __init__(self, type_, value, key, mask): # self.type_ = type_ # self.value = value # self.key = key # self.mask = mask # # def check(self, request): # if self.type_ == 'valid': # return self._check_valid(request) # elif self.type_ == 'exact': # return self._check_exact(request) # elif self.type_ == 'ternary': # return self._check_ternary(request) # elif self.type_ == 'lpm': # return self._check_lpm(request) # logging.warning("unknown TableEntry type") # return False # # def _check_exact(self, request): # for fld_name, value in self.key.items(): # if fld_name not in request.values: # return False # elif int(request.get_value(fld_name)) != int(value): # return False # return True # # def _apply_mask(self, fld_name, val): # if self.mask == None or fld_name not in self.mask.keys(): # return int(val) # return int(val) & int(self.mask[fld_name]) # # def _check_ternary(self, request): # for fld_name, value in self.key.items(): # if fld_name not in request.values: # return False # elif (self._apply_mask(fld_name, request.get_value(fld_name)) != # self._apply_mask(fld_name, value)): # return False # return True # # def _check_valid(self, request): # logging.warning("FIXME: implement TableEntry valid") # return False # def _check_lpm(self, request): # logging.warning("FIXME: implement TableEntry lpm") # return False # # Path: pif_ir/bir/utils/exceptions.py # class BIRTableEntryError(BIRError): # """ an entry couldn't be added to table # """ # def __init__(self, name, msg): # super(BIRTableEntryError, self).__init__() # self.value = "table({}): {}".format(name, msg) # # Path: pif_ir/bir/utils/validate.py # def check_attributes(obj_name, attributes, required_attributes): # for attr in required_attributes: # if attr not in attributes: # raise BIRYamlAttrError(attr, obj_name) . Output only the next line.
check_attributes(name, table_attrs, Table.required_attributes)
Based on the snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', nargs='*', type=str, required=True, help='path to the input corpus file') parser.add_argument('-o', '--output', type=str, default='./', help='path to the output dir') parser.add_argument('-ts', '--test_split', type=float, required=True, help='fraction of the dataset to be used as test data') parser.add_argument('-vs', '--vocab_size', type=int, default=2000, help='vocabulary size (default 2000)') parser.add_argument('-vt', '--vocab_threshold', type=int, default=10, help='vocabulary threshold (default 10), disabled when vocab_size is set') args = parser.parse_args() <|code_end|> , predict the immediate next line with the help of imports: import argparse from autoencoder.datasets.reuters import construct_train_test_corpus and context (classes, functions, sometimes code) from other files: # Path: autoencoder/datasets/reuters.py # def construct_train_test_corpus(path_list, test_split, output, threshold=10, topn=20000): # train_data, test_data = load_data(path_list, test_split) # train_word_freq = count_words(train_data.values()) # # train_docs, vocab_dict, train_word_freq = construct_corpus(train_data, train_word_freq, True, threshold=threshold, topn=topn) # train_corpus = {'docs': train_docs, 'vocab': vocab_dict, 'word_freq': train_word_freq} # dump_json(train_corpus, os.path.join(output, 'train.corpus')) # print 'Generated training corpus' # # test_word_freq = count_words(test_data.values()) # test_docs, _, _ = construct_corpus(test_data, test_word_freq, False, vocab_dict=vocab_dict) # test_corpus = {'docs': test_docs, 'vocab': vocab_dict} # dump_json(test_corpus, os.path.join(output, 'test.corpus')) # print 'Generated test corpus' . Output only the next line.
construct_train_test_corpus(args.input, args.test_split, args.output, threshold=args.vocab_threshold, topn=args.vocab_size)
Continue the code snippet: <|code_start|> words = tiny_tokenize(subj.lower(), stem=stem, stop_words=cached_stop_words) count = Counter(words) corpus[idx] = dict(count) # doc-word frequency labels[idx] = float(rating) corpus = corpus.items() np.random.seed(seed) np.random.shuffle(corpus) n_docs = len(corpus) train_data = dict(corpus[:-int(n_docs * test_split)]) test_data = dict(corpus[-int(n_docs * test_split):]) train_labels = dict([(idx, labels[idx]) for idx in train_data.keys()]) test_labels = dict([(idx, labels[idx]) for idx in test_data.keys()]) return train_data, train_labels, test_data, test_labels def count_words(docs): # count the number of times a word appears in a corpus word_freq = defaultdict(lambda: 0) for each in docs: for word, val in each.items(): word_freq[word] += val return word_freq def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: <|code_end|> . Use current file imports: import os import re import numpy as np import pdb;pdb.set_trace() from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, tiny_tokenize, init_stopwords from ..utils.io_utils import dump_json and context (classes, functions, or code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def tiny_tokenize(text, stem=False, stop_words=[]): # words = [] # for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), ' ', \ # text.decode(encoding='UTF-8', errors='ignore'))): # if not token.isdigit() and not token in stop_words: # if stem: # try: # w = EnglishStemmer().stem(token) # except Exception as e: # w = token # else: # w = token # words.append(w) # # return words # # # return [EnglishStemmer().stem(token) if stem else token for token in wordpunct_tokenize( # # re.sub('[%s]' % re.escape(string.punctuation), ' ', text.decode(encoding='UTF-8', errors='ignore'))) if # # not token.isdigit() and not token in stop_words] # # def init_stopwords(): # try: # stopword_path = 'patterns/english_stopwords.txt' # cached_stop_words = load_stopwords(os.path.join(os.path.split(__file__)[0], stopword_path)) # print 'Loaded %s' % stopword_path # except: # from nltk.corpus import stopwords # cached_stop_words = stopwords.words("english") # print 'Loaded nltk.corpus.stopwords' # # return cached_stop_words # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn)
Given the code snippet: <|code_start|> corpus[idx] = dict(count) # doc-word frequency labels[idx] = float(rating) corpus = corpus.items() np.random.seed(seed) np.random.shuffle(corpus) n_docs = len(corpus) train_data = dict(corpus[:-int(n_docs * test_split)]) test_data = dict(corpus[-int(n_docs * test_split):]) train_labels = dict([(idx, labels[idx]) for idx in train_data.keys()]) test_labels = dict([(idx, labels[idx]) for idx in test_data.keys()]) return train_data, train_labels, test_data, test_labels def count_words(docs): # count the number of times a word appears in a corpus word_freq = defaultdict(lambda: 0) for each in docs: for word, val in each.items(): word_freq[word] += val return word_freq def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn) <|code_end|> , generate the next line using the imports in this file: import os import re import numpy as np import pdb;pdb.set_trace() from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, tiny_tokenize, init_stopwords from ..utils.io_utils import dump_json and context (functions, classes, or occasionally code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def tiny_tokenize(text, stem=False, stop_words=[]): # words = [] # for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), ' ', \ # text.decode(encoding='UTF-8', errors='ignore'))): # if not token.isdigit() and not token in stop_words: # if stem: # try: # w = EnglishStemmer().stem(token) # except Exception as e: # w = token # else: # w = token # words.append(w) # # return words # # # return [EnglishStemmer().stem(token) if stem else token for token in wordpunct_tokenize( # # re.sub('[%s]' % re.escape(string.punctuation), ' ', text.decode(encoding='UTF-8', errors='ignore'))) if # # not token.isdigit() and not token in stop_words] # # def init_stopwords(): # try: # stopword_path = 'patterns/english_stopwords.txt' # cached_stop_words = load_stopwords(os.path.join(os.path.split(__file__)[0], stopword_path)) # print 'Loaded %s' % stopword_path # except: # from nltk.corpus import stopwords # cached_stop_words = stopwords.words("english") # print 'Loaded nltk.corpus.stopwords' # # return cached_stop_words # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
docs = generate_bow(doc_word_freq, vocab_dict)
Here is a snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import cached_stop_words = init_stopwords() class CorpusIterMRD(object): def __init__(self, corpus_path, train_docs, stem=True, with_docname=False): self.corpus_path = corpus_path self.train_docs = train_docs self.stem = stem self.with_docname = with_docname def __iter__(self): try: with open(self.corpus_path, 'r') as f: for line in f: idx, _, subj = line.split('\t') if not idx in self.train_docs: continue <|code_end|> . Write the next line using the current file imports: import os import re import numpy as np import pdb;pdb.set_trace() from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, tiny_tokenize, init_stopwords from ..utils.io_utils import dump_json and context from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def tiny_tokenize(text, stem=False, stop_words=[]): # words = [] # for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), ' ', \ # text.decode(encoding='UTF-8', errors='ignore'))): # if not token.isdigit() and not token in stop_words: # if stem: # try: # w = EnglishStemmer().stem(token) # except Exception as e: # w = token # else: # w = token # words.append(w) # # return words # # # return [EnglishStemmer().stem(token) if stem else token for token in wordpunct_tokenize( # # re.sub('[%s]' % re.escape(string.punctuation), ' ', text.decode(encoding='UTF-8', errors='ignore'))) if # # not token.isdigit() and not token in stop_words] # # def init_stopwords(): # try: # stopword_path = 'patterns/english_stopwords.txt' # cached_stop_words = load_stopwords(os.path.join(os.path.split(__file__)[0], stopword_path)) # print 'Loaded %s' % stopword_path # except: # from nltk.corpus import stopwords # cached_stop_words = stopwords.words("english") # print 'Loaded nltk.corpus.stopwords' # # return cached_stop_words # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e , which may include functions, classes, or code. Output only the next line.
words = tiny_tokenize(subj.lower(), stem=self.stem, stop_words=cached_stop_words)
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import <|code_end|> . Use current file imports: import os import re import numpy as np import pdb;pdb.set_trace() from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, tiny_tokenize, init_stopwords from ..utils.io_utils import dump_json and context (classes, functions, or code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def tiny_tokenize(text, stem=False, stop_words=[]): # words = [] # for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), ' ', \ # text.decode(encoding='UTF-8', errors='ignore'))): # if not token.isdigit() and not token in stop_words: # if stem: # try: # w = EnglishStemmer().stem(token) # except Exception as e: # w = token # else: # w = token # words.append(w) # # return words # # # return [EnglishStemmer().stem(token) if stem else token for token in wordpunct_tokenize( # # re.sub('[%s]' % re.escape(string.punctuation), ' ', text.decode(encoding='UTF-8', errors='ignore'))) if # # not token.isdigit() and not token in stop_words] # # def init_stopwords(): # try: # stopword_path = 'patterns/english_stopwords.txt' # cached_stop_words = load_stopwords(os.path.join(os.path.split(__file__)[0], stopword_path)) # print 'Loaded %s' % stopword_path # except: # from nltk.corpus import stopwords # cached_stop_words = stopwords.words("english") # print 'Loaded nltk.corpus.stopwords' # # return cached_stop_words # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
cached_stop_words = init_stopwords()
Using the snippet: <|code_start|> return train_data, train_labels, test_data, test_labels def count_words(docs): # count the number of times a word appears in a corpus word_freq = defaultdict(lambda: 0) for each in docs: for word, val in each.items(): word_freq[word] += val return word_freq def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn) docs = generate_bow(doc_word_freq, vocab_dict) new_word_freq = dict([(vocab_dict[word], freq) for word, freq in word_freq.iteritems() if word in vocab_dict]) return docs, vocab_dict, new_word_freq def construct_train_test_corpus(file, test_split, output, threshold=10, topn=20000): train_data, train_labels, test_data, test_labels = load_data(file, test_split) train_word_freq = count_words(train_data.values()) train_docs, vocab_dict, train_word_freq = construct_corpus(train_data, train_word_freq, True, threshold=threshold, topn=topn) train_corpus = {'docs': train_docs, 'vocab': vocab_dict, 'word_freq': train_word_freq} <|code_end|> , determine the next line of code. You have imports: import os import re import numpy as np import pdb;pdb.set_trace() from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, tiny_tokenize, init_stopwords from ..utils.io_utils import dump_json and context (class names, function names, or code) available: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def tiny_tokenize(text, stem=False, stop_words=[]): # words = [] # for token in wordpunct_tokenize(re.sub('[%s]' % re.escape(string.punctuation), ' ', \ # text.decode(encoding='UTF-8', errors='ignore'))): # if not token.isdigit() and not token in stop_words: # if stem: # try: # w = EnglishStemmer().stem(token) # except Exception as e: # w = token # else: # w = token # words.append(w) # # return words # # # return [EnglishStemmer().stem(token) if stem else token for token in wordpunct_tokenize( # # re.sub('[%s]' % re.escape(string.punctuation), ' ', text.decode(encoding='UTF-8', errors='ignore'))) if # # not token.isdigit() and not token in stop_words] # # def init_stopwords(): # try: # stopword_path = 'patterns/english_stopwords.txt' # cached_stop_words = load_stopwords(os.path.join(os.path.split(__file__)[0], stopword_path)) # print 'Loaded %s' % stopword_path # except: # from nltk.corpus import stopwords # cached_stop_words = stopwords.words("english") # print 'Loaded nltk.corpus.stopwords' # # return cached_stop_words # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
dump_json(train_corpus, os.path.join(output, 'train.corpus'))
Next line prediction: <|code_start|> return topics def get_topics_strength(ae, vocab, topn=10): topics = [] weights = ae.encoder.get_weights()[0] for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] <|code_end|> . Use current file imports: (import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file) and context including class names, function names, or small code snippets from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
model = AutoEncoder
Given the following code snippet before the placeholder: <|code_start|>def get_topics_strength(ae, vocab, topn=10): topics = [] weights = ae.encoder.get_weights()[0] for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] model = AutoEncoder # model = DeepAutoEncoder <|code_end|> , predict the next line using imports from the current file: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and context including class names, function names, and sometimes code from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
ae = load_model(model, args.load_arch, args.load_weights)
Next line prediction: <|code_start|> score = query_vec.dot(weights.T) vidx = score.argsort()[::-1][:topn] return [revocab[idx] for idx in vidx] def get_topics(ae, vocab, topn=10): topics = [] weights = ae.encoder.get_weights()[0] for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([vocab[x] for x in token_idx]) return topics def get_topics_strength(ae, vocab, topn=10): topics = [] weights = ae.encoder.get_weights()[0] for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): <|code_end|> . Use current file imports: (import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file) and context including class names, function names, or small code snippets from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
corpus = load_corpus(args.input)
Predict the next line after this snippet: <|code_start|> for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([vocab[x] for x in token_idx]) return topics def get_topics_strength(ae, vocab, topn=10): topics = [] weights = ae.encoder.get_weights()[0] for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: <|code_end|> using the current file's imports: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and any relevant context from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0))
Continue the code snippet: <|code_start|> for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([vocab[x] for x in token_idx]) return topics def get_topics_strength(ae, vocab, topn=10): topics = [] weights = ae.encoder.get_weights()[0] for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: <|code_end|> . Use current file imports: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and context (classes, functions, or code) from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0))
Continue the code snippet: <|code_start|> return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] model = AutoEncoder # model = DeepAutoEncoder ae = load_model(model, args.load_arch, args.load_weights) doc_codes = ae.encoder.predict(X_docs) dump_json(dict(zip(doc_keys, doc_codes.tolist())), args.output) print 'Saved doc codes file to %s' % args.output if args.save_topics: <|code_end|> . Use current file imports: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and context (classes, functions, or code) from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
topics_strength = get_topics_strength(ae, revdict(vocab), topn=10)
Here is a snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import # from autoencoder.core.deepae import DeepAutoEncoder # def get_topics(ae, vocab, topn=10): # topics = [] # topic_codes = np.identity(ae.dim) # dists = ae.decoder.predict(topic_codes) # dists /= np.sum(dists, axis=1).reshape(ae.dim, 1) # for idx in range(ae.dim): # token_idx = np.argsort(dists[idx])[::-1][:topn] # topic = zip([vocab[x] for x in token_idx], dists[idx][token_idx]) # topics.append(topic) # return topics def calc_pairwise_cosine(ae): weights = ae.encoder.get_weights()[0] <|code_end|> . Write the next line using the current file imports: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and context from other files: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e , which may include functions, classes, or code. Output only the next line.
weights = unitmatrix(weights, axis=0) # normalize
Using the snippet: <|code_start|> for idx in range(ae.dim): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] model = AutoEncoder # model = DeepAutoEncoder ae = load_model(model, args.load_arch, args.load_weights) doc_codes = ae.encoder.predict(X_docs) <|code_end|> , determine the next line of code. You have imports: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and context (class names, function names, or code) available: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
dump_json(dict(zip(doc_keys, doc_codes.tolist())), args.output)
Using the snippet: <|code_start|> n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] model = AutoEncoder # model = DeepAutoEncoder ae = load_model(model, args.load_arch, args.load_weights) doc_codes = ae.encoder.predict(X_docs) dump_json(dict(zip(doc_keys, doc_codes.tolist())), args.output) print 'Saved doc codes file to %s' % args.output if args.save_topics: topics_strength = get_topics_strength(ae, revdict(vocab), topn=10) save_topics_strength(topics_strength, args.save_topics) # topics = get_topics(ae, revdict(vocab), topn=10) # write_file(topics, args.save_topics) print 'Saved topics file to %s' % args.save_topics if args.sample_words: revocab = revdict(vocab) queries = ['weapon', 'christian', 'compani', 'israel', 'law', 'hockey', 'comput', 'space'] words = [] for each in queries: words.append(get_similar_words(ae, vocab[each], revocab, topn=11)) <|code_end|> , determine the next line of code. You have imports: import argparse import math import numpy as np from autoencoder.core.ae import AutoEncoder, load_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix #, corrupted_matrix from autoencoder.utils.io_utils import dump_json, write_file and context (class names, function names, or code) available: # Path: autoencoder/core/ae.py # class AutoEncoder(object): # def __init__(self, input_size, dim, comp_topk=None, ctype=None, save_model='best_model'): # def build(self): # def fit(self, train_X, val_X, nb_epoch=50, batch_size=100, contractive=None): # def save_ae_model(model, model_file): # def load_ae_model(model_file): # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e . Output only the next line.
write_file(words, args.sample_words)
Predict the next line for this snippet: <|code_start|> if args.multilabel_clf: encoder = MultiLabelBinarizer() encoder.fit(Y_train + Y_test) Y_train = encoder.transform(Y_train) Y_test = encoder.transform(Y_test) else: Y = Y_train + Y_test n_train = len(Y_train) n_test = len(Y_test) encoder = LabelEncoder() Y = np_utils.to_categorical(encoder.fit_transform(Y)) Y_train = Y[:n_train] Y_test = Y[-n_test:] seed = 7 np.random.seed(seed) if not args.cross_validation: val_idx = np.random.choice(range(X_train.shape[0]), args.n_val, replace=False) train_idx = list(set(range(X_train.shape[0])) - set(val_idx)) X_new_train = X_train[train_idx] Y_new_train = Y_train[train_idx] X_new_val = X_train[val_idx] Y_new_val = Y_train[val_idx] print 'train: %s, val: %s, test: %s' % (X_new_train.shape[0], X_new_val.shape[0], X_test.shape[0]) if args.multilabel_clf: results = multilabel_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \ X_test, Y_test, nb_epoch=args.n_epoch, batch_size=args.batch_size, seed=seed) print 'f1 score on test set: macro_f1: %s, micro_f1: %s' % tuple(results) else: <|code_end|> with the help of current file imports: import argparse import numpy as np import pdb;pdb.set_trace() from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import ShuffleSplit from autoencoder.testing.classifier import multiclass_classifier, multilabel_classifier from autoencoder.utils.io_utils import load_json, load_pickle and context from other files: # Path: autoencoder/testing/classifier.py # def multiclass_classifier(X_train, Y_train, X_val, Y_val, X_test, Y_test, nb_epoch=200, batch_size=10, seed=7): # clf = softmax_network(X_train.shape[1], Y_train.shape[1]) # clf.fit(X_train, Y_train, # epochs=nb_epoch, # batch_size=batch_size, # shuffle=True, # validation_data=(X_val, Y_val), # callbacks=[ # ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.01), # EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, verbose=0, mode='auto'), # ] # ) # acc = clf.test_on_batch(X_test, Y_test)[1] # # confusion matrix and precision-recall # true = np.argmax(Y_test,axis=1) # pred = np.argmax(clf.predict(X_test), axis=1) # print confusion_matrix(true, pred) # print classification_report(true, pred) # return acc # # def multilabel_classifier(X_train, Y_train, X_val, Y_val, X_test, Y_test, nb_epoch=200, batch_size=10, seed=7): # clf = sigmoid_network(X_train.shape[1], Y_train.shape[1]) # clf.fit(X_train, Y_train, # nb_epoch=nb_epoch, # batch_size=batch_size, # shuffle=True, # validation_data=(X_val, Y_val), # callbacks=[ # ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.01), # EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, verbose=0, mode='auto'), # ] # ) # pred = clf.predict(X_test) # pred = (pred > .5) * 1 # macro_f1 = f1_score(Y_test, pred, average='macro') # micro_f1 = f1_score(Y_test, pred, average='micro') # # return [macro_f1, micro_f1] # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def load_pickle(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = pickle.load(f) # except Exception as e: # raise e # # return data , which may contain function names, class names, or code. Output only the next line.
results = multiclass_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \
Based on the snippet: <|code_start|> # Y_train = load_pickle(args.train_doc_labels) # X_test = np.array(load_pickle(args.test_doc_codes)) # Y_test = load_pickle(args.test_doc_labels) # import pdb;pdb.set_trace() if args.multilabel_clf: encoder = MultiLabelBinarizer() encoder.fit(Y_train + Y_test) Y_train = encoder.transform(Y_train) Y_test = encoder.transform(Y_test) else: Y = Y_train + Y_test n_train = len(Y_train) n_test = len(Y_test) encoder = LabelEncoder() Y = np_utils.to_categorical(encoder.fit_transform(Y)) Y_train = Y[:n_train] Y_test = Y[-n_test:] seed = 7 np.random.seed(seed) if not args.cross_validation: val_idx = np.random.choice(range(X_train.shape[0]), args.n_val, replace=False) train_idx = list(set(range(X_train.shape[0])) - set(val_idx)) X_new_train = X_train[train_idx] Y_new_train = Y_train[train_idx] X_new_val = X_train[val_idx] Y_new_val = Y_train[val_idx] print 'train: %s, val: %s, test: %s' % (X_new_train.shape[0], X_new_val.shape[0], X_test.shape[0]) if args.multilabel_clf: <|code_end|> , predict the immediate next line with the help of imports: import argparse import numpy as np import pdb;pdb.set_trace() from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import ShuffleSplit from autoencoder.testing.classifier import multiclass_classifier, multilabel_classifier from autoencoder.utils.io_utils import load_json, load_pickle and context (classes, functions, sometimes code) from other files: # Path: autoencoder/testing/classifier.py # def multiclass_classifier(X_train, Y_train, X_val, Y_val, X_test, Y_test, nb_epoch=200, batch_size=10, seed=7): # clf = softmax_network(X_train.shape[1], Y_train.shape[1]) # clf.fit(X_train, Y_train, # epochs=nb_epoch, # batch_size=batch_size, # shuffle=True, # validation_data=(X_val, Y_val), # callbacks=[ # ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.01), # EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, verbose=0, mode='auto'), # ] # ) # acc = clf.test_on_batch(X_test, Y_test)[1] # # confusion matrix and precision-recall # true = np.argmax(Y_test,axis=1) # pred = np.argmax(clf.predict(X_test), axis=1) # print confusion_matrix(true, pred) # print classification_report(true, pred) # return acc # # def multilabel_classifier(X_train, Y_train, X_val, Y_val, X_test, Y_test, nb_epoch=200, batch_size=10, seed=7): # clf = sigmoid_network(X_train.shape[1], Y_train.shape[1]) # clf.fit(X_train, Y_train, # nb_epoch=nb_epoch, # batch_size=batch_size, # shuffle=True, # validation_data=(X_val, Y_val), # callbacks=[ # ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.01), # EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, verbose=0, mode='auto'), # ] # ) # pred = clf.predict(X_test) # pred = (pred > .5) * 1 # macro_f1 = f1_score(Y_test, pred, average='macro') # micro_f1 = f1_score(Y_test, pred, average='micro') # # return [macro_f1, micro_f1] # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def load_pickle(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = pickle.load(f) # except Exception as e: # raise e # # return data . Output only the next line.
results = multilabel_classifier(X_new_train, Y_new_train, X_new_val, Y_new_val, \
Predict the next line after this snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc codes file') parser.add_argument('train_doc_labels', type=str, help='path to the train doc labels file') parser.add_argument('test_doc_codes', type=str, help='path to the test doc codes file') parser.add_argument('test_doc_labels', type=str, help='path to the test doc labels file') parser.add_argument('-nv', '--n_val', type=int, default=1000, help='size of validation set (default 1000)') parser.add_argument('-ne', '--n_epoch', type=int, default=100, help='num of epoches (default 100)') parser.add_argument('-bs', '--batch_size', type=int, default=100, help='batch size (default 100)') parser.add_argument('-cv', '--cross_validation', type=int, help='k-fold cross validation') parser.add_argument('-mlc', '--multilabel_clf', action='store_true', help='multilabel classification flag') args = parser.parse_args() # autoencoder <|code_end|> using the current file's imports: import argparse import numpy as np import pdb;pdb.set_trace() from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import ShuffleSplit from autoencoder.testing.classifier import multiclass_classifier, multilabel_classifier from autoencoder.utils.io_utils import load_json, load_pickle and any relevant context from other files: # Path: autoencoder/testing/classifier.py # def multiclass_classifier(X_train, Y_train, X_val, Y_val, X_test, Y_test, nb_epoch=200, batch_size=10, seed=7): # clf = softmax_network(X_train.shape[1], Y_train.shape[1]) # clf.fit(X_train, Y_train, # epochs=nb_epoch, # batch_size=batch_size, # shuffle=True, # validation_data=(X_val, Y_val), # callbacks=[ # ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.01), # EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, verbose=0, mode='auto'), # ] # ) # acc = clf.test_on_batch(X_test, Y_test)[1] # # confusion matrix and precision-recall # true = np.argmax(Y_test,axis=1) # pred = np.argmax(clf.predict(X_test), axis=1) # print confusion_matrix(true, pred) # print classification_report(true, pred) # return acc # # def multilabel_classifier(X_train, Y_train, X_val, Y_val, X_test, Y_test, nb_epoch=200, batch_size=10, seed=7): # clf = sigmoid_network(X_train.shape[1], Y_train.shape[1]) # clf.fit(X_train, Y_train, # nb_epoch=nb_epoch, # batch_size=batch_size, # shuffle=True, # validation_data=(X_val, Y_val), # callbacks=[ # ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.01), # EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=5, verbose=0, mode='auto'), # ] # ) # pred = clf.predict(X_test) # pred = (pred > .5) * 1 # macro_f1 = f1_score(Y_test, pred, average='macro') # micro_f1 = f1_score(Y_test, pred, average='micro') # # return [macro_f1, micro_f1] # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def load_pickle(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = pickle.load(f) # except Exception as e: # raise e # # return data . Output only the next line.
train_doc_codes = load_json(args.train_doc_codes)
Here is a snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('corpus', type=str, help='path to the corpus file') parser.add_argument('labels', type=str, help='path to the labels file') parser.add_argument('-bs', '--batch_size', type=int, default=100, help='batch size (default 100)') parser.add_argument('out_dir', type=str, help='path to the output dir') args = parser.parse_args() <|code_end|> . Write the next line using the current file imports: import os import sys import argparse import numpy as np import pdb;pdb.set_trace() from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.io_utils import load_json, dump_pickle and context from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def dump_pickle(data, path_to_file): # try: # with open(path_to_file, 'w') as f: # pickle.dump(data, f) # except Exception as e: # raise e , which may include functions, classes, or code. Output only the next line.
corpus = load_corpus(args.corpus)
Given the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('corpus', type=str, help='path to the corpus file') parser.add_argument('labels', type=str, help='path to the labels file') parser.add_argument('-bs', '--batch_size', type=int, default=100, help='batch size (default 100)') parser.add_argument('out_dir', type=str, help='path to the output dir') args = parser.parse_args() corpus = load_corpus(args.corpus) doc_labels = load_json(args.labels) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_names = docs.keys() <|code_end|> , generate the next line using the imports in this file: import os import sys import argparse import numpy as np import pdb;pdb.set_trace() from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.io_utils import load_json, dump_pickle and context (functions, classes, or occasionally code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def dump_pickle(data, path_to_file): # try: # with open(path_to_file, 'w') as f: # pickle.dump(data, f) # except Exception as e: # raise e . Output only the next line.
X_docs = [doc2vec(x, n_vocab) for x in docs.values()]
Given snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('corpus', type=str, help='path to the corpus file') parser.add_argument('labels', type=str, help='path to the labels file') parser.add_argument('-bs', '--batch_size', type=int, default=100, help='batch size (default 100)') parser.add_argument('out_dir', type=str, help='path to the output dir') args = parser.parse_args() corpus = load_corpus(args.corpus) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import argparse import numpy as np import pdb;pdb.set_trace() from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.io_utils import load_json, dump_pickle and context: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def dump_pickle(data, path_to_file): # try: # with open(path_to_file, 'w') as f: # pickle.dump(data, f) # except Exception as e: # raise e which might include code, classes, or functions. Output only the next line.
doc_labels = load_json(args.labels)
Next line prediction: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('corpus', type=str, help='path to the corpus file') parser.add_argument('labels', type=str, help='path to the labels file') parser.add_argument('-bs', '--batch_size', type=int, default=100, help='batch size (default 100)') parser.add_argument('out_dir', type=str, help='path to the output dir') args = parser.parse_args() corpus = load_corpus(args.corpus) doc_labels = load_json(args.labels) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_names = docs.keys() X_docs = [doc2vec(x, n_vocab) for x in docs.values()] out_dir = args.out_dir # attributes attrs = zip(*sorted(vocab.iteritems(), key=lambda d:[1]))[0] <|code_end|> . Use current file imports: (import os import sys import argparse import numpy as np import pdb;pdb.set_trace() from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.io_utils import load_json, dump_pickle) and context including class names, function names, or small code snippets from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def dump_pickle(data, path_to_file): # try: # with open(path_to_file, 'w') as f: # pickle.dump(data, f) # except Exception as e: # raise e . Output only the next line.
dump_pickle(attrs, os.path.join(out_dir, 'attributes.p'))
Based on the snippet: <|code_start|> path_list : a list of file paths test_split : fraction of the dataset to be used as test data. seed : random seed for sample shuffling. ''' # count the number of times a word appears in a doc corpus = {} for path in path_list: with open(path, 'r') as f: texts = re.split('\n\s*\n', f.read())[:-1] for block in texts: tmp = block.split('\n') did = tmp[0].split(' ')[-1] count = Counter((' '.join(tmp[2:])).split()) corpus[did] = dict(count) # doc-word frequency corpus = corpus.items() np.random.seed(seed) np.random.shuffle(corpus) n_docs = len(corpus) train_data = dict(corpus[:-int(n_docs * test_split)]) test_data = dict(corpus[-int(n_docs * test_split):]) return train_data, test_data def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: <|code_end|> , predict the immediate next line with the help of imports: import os import re import numpy as np from random import shuffle from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, count_words from ..utils.io_utils import dump_json and context (classes, functions, sometimes code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def count_words(docs): # # count the number of times a word appears in a corpus # word_freq = defaultdict(lambda: 0) # for each in docs: # for word, val in each.iteritems(): # word_freq[word] += val # # return word_freq # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn)
Predict the next line after this snippet: <|code_start|> seed : random seed for sample shuffling. ''' # count the number of times a word appears in a doc corpus = {} for path in path_list: with open(path, 'r') as f: texts = re.split('\n\s*\n', f.read())[:-1] for block in texts: tmp = block.split('\n') did = tmp[0].split(' ')[-1] count = Counter((' '.join(tmp[2:])).split()) corpus[did] = dict(count) # doc-word frequency corpus = corpus.items() np.random.seed(seed) np.random.shuffle(corpus) n_docs = len(corpus) train_data = dict(corpus[:-int(n_docs * test_split)]) test_data = dict(corpus[-int(n_docs * test_split):]) return train_data, test_data def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn) <|code_end|> using the current file's imports: import os import re import numpy as np from random import shuffle from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, count_words from ..utils.io_utils import dump_json and any relevant context from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def count_words(docs): # # count the number of times a word appears in a corpus # word_freq = defaultdict(lambda: 0) # for each in docs: # for word, val in each.iteritems(): # word_freq[word] += val # # return word_freq # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
docs = generate_bow(doc_word_freq, vocab_dict)
Predict the next line after this snippet: <|code_start|> for block in texts: tmp = block.split('\n') did = tmp[0].split(' ')[-1] count = Counter((' '.join(tmp[2:])).split()) corpus[did] = dict(count) # doc-word frequency corpus = corpus.items() np.random.seed(seed) np.random.shuffle(corpus) n_docs = len(corpus) train_data = dict(corpus[:-int(n_docs * test_split)]) test_data = dict(corpus[-int(n_docs * test_split):]) return train_data, test_data def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn) docs = generate_bow(doc_word_freq, vocab_dict) new_word_freq = dict([(vocab_dict[word], freq) for word, freq in word_freq.iteritems() if word in vocab_dict]) return docs, vocab_dict, new_word_freq def construct_train_test_corpus(path_list, test_split, output, threshold=10, topn=20000): train_data, test_data = load_data(path_list, test_split) <|code_end|> using the current file's imports: import os import re import numpy as np from random import shuffle from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, count_words from ..utils.io_utils import dump_json and any relevant context from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def count_words(docs): # # count the number of times a word appears in a corpus # word_freq = defaultdict(lambda: 0) # for each in docs: # for word, val in each.iteritems(): # word_freq[word] += val # # return word_freq # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
train_word_freq = count_words(train_data.values())
Based on the snippet: <|code_start|> corpus[did] = dict(count) # doc-word frequency corpus = corpus.items() np.random.seed(seed) np.random.shuffle(corpus) n_docs = len(corpus) train_data = dict(corpus[:-int(n_docs * test_split)]) test_data = dict(corpus[-int(n_docs * test_split):]) return train_data, test_data def construct_corpus(doc_word_freq, word_freq, training_phase, vocab_dict=None, threshold=5, topn=None): if not (training_phase or isinstance(vocab_dict, dict)): raise ValueError('vocab_dict must be provided if training_phase is set False') if training_phase: vocab_dict = build_vocab(word_freq, threshold=threshold, topn=topn) docs = generate_bow(doc_word_freq, vocab_dict) new_word_freq = dict([(vocab_dict[word], freq) for word, freq in word_freq.iteritems() if word in vocab_dict]) return docs, vocab_dict, new_word_freq def construct_train_test_corpus(path_list, test_split, output, threshold=10, topn=20000): train_data, test_data = load_data(path_list, test_split) train_word_freq = count_words(train_data.values()) train_docs, vocab_dict, train_word_freq = construct_corpus(train_data, train_word_freq, True, threshold=threshold, topn=topn) train_corpus = {'docs': train_docs, 'vocab': vocab_dict, 'word_freq': train_word_freq} <|code_end|> , predict the immediate next line with the help of imports: import os import re import numpy as np from random import shuffle from collections import Counter, defaultdict from ..preprocessing.preprocessing import build_vocab, generate_bow, count_words from ..utils.io_utils import dump_json and context (classes, functions, sometimes code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def build_vocab(word_freq, threshold=5, topn=None, start_idx=0): # """ # threshold only take effects when topn is None. # words are indexed by overall frequency in the dataset. # """ # word_freq = sorted(word_freq.iteritems(), key=lambda d:d[1], reverse=True) # if topn: # word_freq = zip(*word_freq[:topn])[0] # vocab_dict = dict(zip(word_freq, range(start_idx, len(word_freq) + start_idx))) # else: # idx = start_idx # vocab_dict = {} # for word, freq in word_freq: # if freq < threshold: # return vocab_dict # vocab_dict[word] = idx # idx += 1 # return vocab_dict # # def generate_bow(doc_word_freq, vocab_dict): # docs = {} # for key, val in doc_word_freq.iteritems(): # word_count = {} # for word, freq in val.iteritems(): # try: # word_count[vocab_dict[word]] = freq # except: # word is not in vocab, i.e., this word should be discarded # continue # docs[key] = word_count # # return docs # # def count_words(docs): # # count the number of times a word appears in a corpus # word_freq = defaultdict(lambda: 0) # for each in docs: # for word, val in each.iteritems(): # word_freq[word] += val # # return word_freq # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e . Output only the next line.
dump_json(train_corpus, os.path.join(output, 'train.corpus'))
Given the code snippet: <|code_start|> return topics def get_topics_strength(model, vocab, topn=10): topics = [] weights = model.get_weights()[0] for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] <|code_end|> , generate the next line using the imports in this file: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and context (functions, classes, or occasionally code) from other files: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) . Output only the next line.
ae = load_ae_model(args.load_model)
Using the snippet: <|code_start|> score = query_vec.dot(weights.T) vidx = score.argsort()[::-1][:topn] return [revocab[idx] for idx in vidx] def get_topics(model, vocab, topn=10): topics = [] weights = model.get_weights()[0] for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([vocab[x] for x in token_idx]) return topics def get_topics_strength(model, vocab, topn=10): topics = [] weights = model.get_weights()[0] for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): <|code_end|> , determine the next line of code. You have imports: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and context (class names, function names, or code) available: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) . Output only the next line.
corpus = load_corpus(args.input)
Given the following code snippet before the placeholder: <|code_start|> for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([vocab[x] for x in token_idx]) return topics def get_topics_strength(model, vocab, topn=10): topics = [] weights = model.get_weights()[0] for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: <|code_end|> , predict the next line using imports from the current file: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and context including class names, function names, and sometimes code from other files: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) . Output only the next line.
X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0))
Using the snippet: <|code_start|> for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([vocab[x] for x in token_idx]) return topics def get_topics_strength(model, vocab, topn=10): topics = [] weights = model.get_weights()[0] for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: <|code_end|> , determine the next line of code. You have imports: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and context (class names, function names, or code) available: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) . Output only the next line.
X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0))
Using the snippet: <|code_start|> token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] ae = load_ae_model(args.load_model) doc_codes = ae.predict(X_docs) dump_json(dict(zip(doc_keys, doc_codes.tolist())), args.output) print 'Saved doc codes file to %s' % args.output if args.save_topics: <|code_end|> , determine the next line of code. You have imports: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and context (class names, function names, or code) available: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) . Output only the next line.
topics_strength = get_topics_strength(ae, revdict(vocab), topn=10)
Given snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def calc_pairwise_cosine(model): weights = model.get_weights()[0] <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and context: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) which might include code, classes, or functions. Output only the next line.
weights = unitmatrix(weights, axis=0) # normalize
Predict the next line after this snippet: <|code_start|>def get_topics_strength(model, vocab, topn=10): topics = [] weights = model.get_weights()[0] for idx in range(model.output_shape[1]): token_idx = np.argsort(weights[:, idx])[::-1][:topn] topics.append([(vocab[x], weights[x, idx]) for x in token_idx]) return topics def print_topics(topics): for i in range(len(topics)): str_topic = ' + '.join(['%s * %s' % (prob, token) for token, prob in topics[i]]) print 'topic %s:' % i print str_topic print def test(args): corpus = load_corpus(args.input) vocab, docs = corpus['vocab'], corpus['docs'] n_vocab = len(vocab) doc_keys = docs.keys() X_docs = [] for k in doc_keys: X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0)) del docs[k] X_docs = np.r_[X_docs] ae = load_ae_model(args.load_model) doc_codes = ae.predict(X_docs) <|code_end|> using the current file's imports: import argparse import math import numpy as np from autoencoder.core.ae import load_ae_model from autoencoder.preprocessing.preprocessing import load_corpus, doc2vec from autoencoder.utils.op_utils import vecnorm, revdict, unitmatrix from autoencoder.utils.io_utils import dump_json, write_file from autoencoder.testing.visualize import word_cloud and any relevant context from other files: # Path: autoencoder/core/ae.py # def load_ae_model(model_file): # return load_keras_model(model_file, custom_objects={"KCompetitive": KCompetitive}) # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # def doc2vec(doc, dim): # vec = np.zeros(dim) # for idx, val in doc.items(): # vec[int(idx)] = val # # return vec # # Path: autoencoder/utils/op_utils.py # def vecnorm(vec, norm, epsilon=1e-3): # """ # Scale a vector to unit length. The only exception is the zero vector, which # is returned back unchanged. # """ # if norm not in ('prob', 'max1', 'logmax1'): # raise ValueError("'%s' is not a supported norm. Currently supported norms include 'prob',\ # 'max1' and 'logmax1'." % norm) # # if isinstance(vec, np.ndarray): # vec = np.asarray(vec, dtype=float) # if norm == 'prob': # veclen = np.sum(np.abs(vec)) + epsilon * len(vec) # smoothing # elif norm == 'max1': # veclen = np.max(vec) + epsilon # elif norm == 'logmax1': # vec = np.log10(1. + vec) # veclen = np.max(vec) + epsilon # if veclen > 0.0: # return (vec + epsilon) / veclen # else: # return vec # else: # raise ValueError('vec should be ndarray, found: %s' % type(vec)) # # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) # # def unitmatrix(matrix, norm='l2', axis=1): # if norm == 'l1': # maxtrixlen = np.sum(np.abs(matrix), axis=axis) # if norm == 'l2': # maxtrixlen = np.linalg.norm(matrix, axis=axis) # # if np.any(maxtrixlen <= 0): # return matrix # else: # maxtrixlen = maxtrixlen.reshape(1, len(maxtrixlen)) if axis == 0 else maxtrixlen.reshape(len(maxtrixlen), 1) # return matrix / maxtrixlen # # Path: autoencoder/utils/io_utils.py # def dump_json(data, file): # try: # with open(file, 'w') as datafile: # json.dump(data, datafile) # except Exception as e: # raise e # # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/testing/visualize.py # def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'): # words = [(i, vocab[i]) for i in s] # model = TSNE(n_components=2, random_state=0) # #Note that the following line might use a good chunk of RAM # tsne_embedding = model.fit_transform(word_embedding_matrix) # words_vectors = tsne_embedding[np.array([item[1] for item in words])] # # plt.subplots_adjust(bottom = 0.1) # plt.scatter( # words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral')) # # for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]): # plt.annotate( # label, # xy=(x, y), xytext=(-20, 20), # textcoords='offset points', ha='right', va='bottom', # fontsize=20, # # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0') # ) # plt.show() # # plt.savefig(save_file) . Output only the next line.
dump_json(dict(zip(doc_keys, doc_codes.tolist())), args.output)
Predict the next line for this snippet: <|code_start|>@author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('doc_codes_file', type=str, help='path to the input corpus file') parser.add_argument('doc_labels_file', type=str, help='path to the output doc codes file') parser.add_argument('cmd', choices=['pca', 'tsne'], help='plot cmd') parser.add_argument('-o', '--output', type=str, default='out.png', help='path to the output file') args = parser.parse_args() cmd = args.cmd.lower() # 20news class_names = ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc'] classes_to_visual = ['comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x'] # classes_to_visual = class_names # classes_to_visual = ["rec.sport.hockey", "comp.graphics", "sci.crypt", \ # "soc.religion.christian", "talk.politics.mideast", \ # "talk.politics.guns"] classes_to_visual = dict([(class_names.index(x), x) for x in classes_to_visual if x in class_names]) if cmd == 'pca': <|code_end|> with the help of current file imports: import argparse from autoencoder.testing.visualize import DBN_visualize_pca_2d, DBN_plot_tsne from autoencoder.utils.io_utils import load_marshal and context from other files: # Path: autoencoder/testing/visualize.py # def DBN_visualize_pca_2d(doc_codes, doc_labels, classes_to_visual, save_file): # """ # Visualize the input data on a 2D PCA plot. Depending on the number of components, # the plot will contain an X amount of subplots. # @param doc_codes: # @param number_of_components: The number of principal components for the PCA plot. # """ # # # markers = ["p", "s", "h", "H", "+", "x", "D"] # markers = ["o", "v", "8", "s", "p", "*", "h", "H", "+", "x", "D"] # # C = len(classes_to_visual) # while True: # if C <= len(markers): # break # markers += markers # # class_ids = dict(zip(classes_to_visual.keys(), range(C))) # # codes, labels = doc_codes, doc_labels # # X = np.r_[list(codes)] # X = PCA(n_components=3).fit_transform(X) # plt.figure(figsize=(10, 10), facecolor='white') # # x_pc, y_pc = 1, 2 # # for c in classes_to_visual.keys(): # idx = np.array(labels) == c # # idx = get_indices(labels, c) # plt.plot(X[idx, x_pc], X[idx, y_pc], linestyle='None', alpha=0.6, marker=markers[class_ids[c]], # markersize=6, label=classes_to_visual[c]) # # plt.legend(c) # plt.title('Projected on the first 2 PCs') # plt.xlabel('PC %s' % x_pc) # plt.ylabel('PC %s' % y_pc) # # legend = plt.legend(loc='upper center', shadow=True) # plt.savefig(save_file) # plt.show() # # def DBN_plot_tsne(doc_codes, doc_labels, classes_to_visual, save_file): # markers = ["o", "v", "8", "s", "p", "*", "h", "H", "+", "x", "D"] # # C = len(classes_to_visual) # while True: # if C <= len(markers): # break # markers += markers # # class_ids = dict(zip(classes_to_visual.keys(), range(C))) # # codes, labels = doc_codes, doc_labels # # X = np.r_[list(codes)] # tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000) # np.set_printoptions(suppress=True) # X = tsne.fit_transform(X) # # plt.figure(figsize=(10, 10), facecolor='white') # # for c in classes_to_visual.keys(): # idx = np.array(labels) == c # # idx = get_indices(labels, c) # plt.plot(X[idx, 0], X[idx, 1], linestyle='None', alpha=0.6, marker=markers[class_ids[c]], # markersize=6, label=classes_to_visual[c]) # legend = plt.legend(loc='upper center', shadow=True) # plt.title("tsne") # plt.savefig(save_file) # plt.show() # # Path: autoencoder/utils/io_utils.py # def load_marshal(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = m.load(f) # except Exception as e: # raise e # # return data , which may contain function names, class names, or code. Output only the next line.
DBN_visualize_pca_2d(load_marshal(args.doc_codes_file), load_marshal(args.doc_labels_file), classes_to_visual, args.output)
Predict the next line for this snippet: <|code_start|>''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('doc_codes_file', type=str, help='path to the input corpus file') parser.add_argument('doc_labels_file', type=str, help='path to the output doc codes file') parser.add_argument('cmd', choices=['pca', 'tsne'], help='plot cmd') parser.add_argument('-o', '--output', type=str, default='out.png', help='path to the output file') args = parser.parse_args() cmd = args.cmd.lower() # 20news class_names = ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc'] classes_to_visual = ['comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x'] # classes_to_visual = class_names # classes_to_visual = ["rec.sport.hockey", "comp.graphics", "sci.crypt", \ # "soc.religion.christian", "talk.politics.mideast", \ # "talk.politics.guns"] classes_to_visual = dict([(class_names.index(x), x) for x in classes_to_visual if x in class_names]) if cmd == 'pca': DBN_visualize_pca_2d(load_marshal(args.doc_codes_file), load_marshal(args.doc_labels_file), classes_to_visual, args.output) elif cmd == 'tsne': <|code_end|> with the help of current file imports: import argparse from autoencoder.testing.visualize import DBN_visualize_pca_2d, DBN_plot_tsne from autoencoder.utils.io_utils import load_marshal and context from other files: # Path: autoencoder/testing/visualize.py # def DBN_visualize_pca_2d(doc_codes, doc_labels, classes_to_visual, save_file): # """ # Visualize the input data on a 2D PCA plot. Depending on the number of components, # the plot will contain an X amount of subplots. # @param doc_codes: # @param number_of_components: The number of principal components for the PCA plot. # """ # # # markers = ["p", "s", "h", "H", "+", "x", "D"] # markers = ["o", "v", "8", "s", "p", "*", "h", "H", "+", "x", "D"] # # C = len(classes_to_visual) # while True: # if C <= len(markers): # break # markers += markers # # class_ids = dict(zip(classes_to_visual.keys(), range(C))) # # codes, labels = doc_codes, doc_labels # # X = np.r_[list(codes)] # X = PCA(n_components=3).fit_transform(X) # plt.figure(figsize=(10, 10), facecolor='white') # # x_pc, y_pc = 1, 2 # # for c in classes_to_visual.keys(): # idx = np.array(labels) == c # # idx = get_indices(labels, c) # plt.plot(X[idx, x_pc], X[idx, y_pc], linestyle='None', alpha=0.6, marker=markers[class_ids[c]], # markersize=6, label=classes_to_visual[c]) # # plt.legend(c) # plt.title('Projected on the first 2 PCs') # plt.xlabel('PC %s' % x_pc) # plt.ylabel('PC %s' % y_pc) # # legend = plt.legend(loc='upper center', shadow=True) # plt.savefig(save_file) # plt.show() # # def DBN_plot_tsne(doc_codes, doc_labels, classes_to_visual, save_file): # markers = ["o", "v", "8", "s", "p", "*", "h", "H", "+", "x", "D"] # # C = len(classes_to_visual) # while True: # if C <= len(markers): # break # markers += markers # # class_ids = dict(zip(classes_to_visual.keys(), range(C))) # # codes, labels = doc_codes, doc_labels # # X = np.r_[list(codes)] # tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000) # np.set_printoptions(suppress=True) # X = tsne.fit_transform(X) # # plt.figure(figsize=(10, 10), facecolor='white') # # for c in classes_to_visual.keys(): # idx = np.array(labels) == c # # idx = get_indices(labels, c) # plt.plot(X[idx, 0], X[idx, 1], linestyle='None', alpha=0.6, marker=markers[class_ids[c]], # markersize=6, label=classes_to_visual[c]) # legend = plt.legend(loc='upper center', shadow=True) # plt.title("tsne") # plt.savefig(save_file) # plt.show() # # Path: autoencoder/utils/io_utils.py # def load_marshal(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = m.load(f) # except Exception as e: # raise e # # return data , which may contain function names, class names, or code. Output only the next line.
DBN_plot_tsne(load_marshal(args.doc_codes_file), load_marshal(args.doc_labels_file), classes_to_visual, args.output)
Continue the code snippet: <|code_start|>@author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('doc_codes_file', type=str, help='path to the input corpus file') parser.add_argument('doc_labels_file', type=str, help='path to the output doc codes file') parser.add_argument('cmd', choices=['pca', 'tsne'], help='plot cmd') parser.add_argument('-o', '--output', type=str, default='out.png', help='path to the output file') args = parser.parse_args() cmd = args.cmd.lower() # 20news class_names = ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc'] classes_to_visual = ['comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x'] # classes_to_visual = class_names # classes_to_visual = ["rec.sport.hockey", "comp.graphics", "sci.crypt", \ # "soc.religion.christian", "talk.politics.mideast", \ # "talk.politics.guns"] classes_to_visual = dict([(class_names.index(x), x) for x in classes_to_visual if x in class_names]) if cmd == 'pca': <|code_end|> . Use current file imports: import argparse from autoencoder.testing.visualize import DBN_visualize_pca_2d, DBN_plot_tsne from autoencoder.utils.io_utils import load_marshal and context (classes, functions, or code) from other files: # Path: autoencoder/testing/visualize.py # def DBN_visualize_pca_2d(doc_codes, doc_labels, classes_to_visual, save_file): # """ # Visualize the input data on a 2D PCA plot. Depending on the number of components, # the plot will contain an X amount of subplots. # @param doc_codes: # @param number_of_components: The number of principal components for the PCA plot. # """ # # # markers = ["p", "s", "h", "H", "+", "x", "D"] # markers = ["o", "v", "8", "s", "p", "*", "h", "H", "+", "x", "D"] # # C = len(classes_to_visual) # while True: # if C <= len(markers): # break # markers += markers # # class_ids = dict(zip(classes_to_visual.keys(), range(C))) # # codes, labels = doc_codes, doc_labels # # X = np.r_[list(codes)] # X = PCA(n_components=3).fit_transform(X) # plt.figure(figsize=(10, 10), facecolor='white') # # x_pc, y_pc = 1, 2 # # for c in classes_to_visual.keys(): # idx = np.array(labels) == c # # idx = get_indices(labels, c) # plt.plot(X[idx, x_pc], X[idx, y_pc], linestyle='None', alpha=0.6, marker=markers[class_ids[c]], # markersize=6, label=classes_to_visual[c]) # # plt.legend(c) # plt.title('Projected on the first 2 PCs') # plt.xlabel('PC %s' % x_pc) # plt.ylabel('PC %s' % y_pc) # # legend = plt.legend(loc='upper center', shadow=True) # plt.savefig(save_file) # plt.show() # # def DBN_plot_tsne(doc_codes, doc_labels, classes_to_visual, save_file): # markers = ["o", "v", "8", "s", "p", "*", "h", "H", "+", "x", "D"] # # C = len(classes_to_visual) # while True: # if C <= len(markers): # break # markers += markers # # class_ids = dict(zip(classes_to_visual.keys(), range(C))) # # codes, labels = doc_codes, doc_labels # # X = np.r_[list(codes)] # tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000) # np.set_printoptions(suppress=True) # X = tsne.fit_transform(X) # # plt.figure(figsize=(10, 10), facecolor='white') # # for c in classes_to_visual.keys(): # idx = np.array(labels) == c # # idx = get_indices(labels, c) # plt.plot(X[idx, 0], X[idx, 1], linestyle='None', alpha=0.6, marker=markers[class_ids[c]], # markersize=6, label=classes_to_visual[c]) # legend = plt.legend(loc='upper center', shadow=True) # plt.title("tsne") # plt.savefig(save_file) # plt.show() # # Path: autoencoder/utils/io_utils.py # def load_marshal(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = m.load(f) # except Exception as e: # raise e # # return data . Output only the next line.
DBN_visualize_pca_2d(load_marshal(args.doc_codes_file), load_marshal(args.doc_labels_file), classes_to_visual, args.output)
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('--corpus', required=True, type=str, help='path to the corpus file') parser.add_argument('-mf', '--mod_file', required=True, type=str, help='path to the word2vec mod file') parser.add_argument('-sw', '--sample_words', type=str, help='path to the output sample words file') parser.add_argument('-o', '--output', type=str, help='path to the output doc codes file') args = parser.parse_args() <|code_end|> . Use current file imports: import argparse import numpy as np import pdb;pdb.set_trace() from os import path from autoencoder.preprocessing.preprocessing import load_corpus from autoencoder.baseline.doc_word2vec import load_w2v, doc_word2vec, get_similar_words from autoencoder.utils.io_utils import write_file from autoencoder.utils.op_utils import revdict and context (classes, functions, or code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # Path: autoencoder/baseline/doc_word2vec.py # def load_w2v(file): # model = Word2Vec.load_word2vec_format(file, binary=True) # return model # # def doc_word2vec(model, corpus, vocab, output, avg=True): # doc_codes = {} # for key, bow in corpus.iteritems(): # vec = get_doc_codes(model, bow, vocab, avg) # doc_codes[key] = vec.tolist() # dump_json(doc_codes, output) # # return doc_codes # # def get_similar_words(model, query, topn=10): # return zip(*model.most_similar(query, topn=topn))[0] # # Path: autoencoder/utils/io_utils.py # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/utils/op_utils.py # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) . Output only the next line.
corpus = load_corpus(args.corpus)
Here is a snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('--corpus', required=True, type=str, help='path to the corpus file') parser.add_argument('-mf', '--mod_file', required=True, type=str, help='path to the word2vec mod file') parser.add_argument('-sw', '--sample_words', type=str, help='path to the output sample words file') parser.add_argument('-o', '--output', type=str, help='path to the output doc codes file') args = parser.parse_args() corpus = load_corpus(args.corpus) docs, vocab_dict = corpus['docs'], corpus['vocab'] <|code_end|> . Write the next line using the current file imports: import argparse import numpy as np import pdb;pdb.set_trace() from os import path from autoencoder.preprocessing.preprocessing import load_corpus from autoencoder.baseline.doc_word2vec import load_w2v, doc_word2vec, get_similar_words from autoencoder.utils.io_utils import write_file from autoencoder.utils.op_utils import revdict and context from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # Path: autoencoder/baseline/doc_word2vec.py # def load_w2v(file): # model = Word2Vec.load_word2vec_format(file, binary=True) # return model # # def doc_word2vec(model, corpus, vocab, output, avg=True): # doc_codes = {} # for key, bow in corpus.iteritems(): # vec = get_doc_codes(model, bow, vocab, avg) # doc_codes[key] = vec.tolist() # dump_json(doc_codes, output) # # return doc_codes # # def get_similar_words(model, query, topn=10): # return zip(*model.most_similar(query, topn=topn))[0] # # Path: autoencoder/utils/io_utils.py # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/utils/op_utils.py # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) , which may include functions, classes, or code. Output only the next line.
w2v = load_w2v(args.mod_file)
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('--corpus', required=True, type=str, help='path to the corpus file') parser.add_argument('-mf', '--mod_file', required=True, type=str, help='path to the word2vec mod file') parser.add_argument('-sw', '--sample_words', type=str, help='path to the output sample words file') parser.add_argument('-o', '--output', type=str, help='path to the output doc codes file') args = parser.parse_args() corpus = load_corpus(args.corpus) docs, vocab_dict = corpus['docs'], corpus['vocab'] w2v = load_w2v(args.mod_file) # doc_codes = doc_word2vec(w2v, docs, revdict(vocab_dict), args.output, avg=True) if args.sample_words: queries = ['weapon', 'christian', 'compani', 'israel', 'law', 'hockey', 'comput', 'space'] words = [] for each in queries: <|code_end|> . Use current file imports: import argparse import numpy as np import pdb;pdb.set_trace() from os import path from autoencoder.preprocessing.preprocessing import load_corpus from autoencoder.baseline.doc_word2vec import load_w2v, doc_word2vec, get_similar_words from autoencoder.utils.io_utils import write_file from autoencoder.utils.op_utils import revdict and context (classes, functions, or code) from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # Path: autoencoder/baseline/doc_word2vec.py # def load_w2v(file): # model = Word2Vec.load_word2vec_format(file, binary=True) # return model # # def doc_word2vec(model, corpus, vocab, output, avg=True): # doc_codes = {} # for key, bow in corpus.iteritems(): # vec = get_doc_codes(model, bow, vocab, avg) # doc_codes[key] = vec.tolist() # dump_json(doc_codes, output) # # return doc_codes # # def get_similar_words(model, query, topn=10): # return zip(*model.most_similar(query, topn=topn))[0] # # Path: autoencoder/utils/io_utils.py # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/utils/op_utils.py # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) . Output only the next line.
words.append(get_similar_words(w2v, each, topn=5))
Given the following code snippet before the placeholder: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('--corpus', required=True, type=str, help='path to the corpus file') parser.add_argument('-mf', '--mod_file', required=True, type=str, help='path to the word2vec mod file') parser.add_argument('-sw', '--sample_words', type=str, help='path to the output sample words file') parser.add_argument('-o', '--output', type=str, help='path to the output doc codes file') args = parser.parse_args() corpus = load_corpus(args.corpus) docs, vocab_dict = corpus['docs'], corpus['vocab'] w2v = load_w2v(args.mod_file) # doc_codes = doc_word2vec(w2v, docs, revdict(vocab_dict), args.output, avg=True) if args.sample_words: queries = ['weapon', 'christian', 'compani', 'israel', 'law', 'hockey', 'comput', 'space'] words = [] for each in queries: words.append(get_similar_words(w2v, each, topn=5)) <|code_end|> , predict the next line using imports from the current file: import argparse import numpy as np import pdb;pdb.set_trace() from os import path from autoencoder.preprocessing.preprocessing import load_corpus from autoencoder.baseline.doc_word2vec import load_w2v, doc_word2vec, get_similar_words from autoencoder.utils.io_utils import write_file from autoencoder.utils.op_utils import revdict and context including class names, function names, and sometimes code from other files: # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus # # Path: autoencoder/baseline/doc_word2vec.py # def load_w2v(file): # model = Word2Vec.load_word2vec_format(file, binary=True) # return model # # def doc_word2vec(model, corpus, vocab, output, avg=True): # doc_codes = {} # for key, bow in corpus.iteritems(): # vec = get_doc_codes(model, bow, vocab, avg) # doc_codes[key] = vec.tolist() # dump_json(doc_codes, output) # # return doc_codes # # def get_similar_words(model, query, topn=10): # return zip(*model.most_similar(query, topn=topn))[0] # # Path: autoencoder/utils/io_utils.py # def write_file(data, file): # try: # with open(file, 'w') as datafile: # for line in data: # datafile.write(' '.join(line) + '\n') # except Exception as e: # raise e # # Path: autoencoder/utils/op_utils.py # def revdict(d): # """ # Reverse a dictionary mapping. # When two keys map to the same value, only one of them will be kept in the # result (which one is kept is arbitrary). # """ # return dict((v, k) for (k, v) in d.iteritems()) . Output only the next line.
write_file(words, args.sample_words)
Predict the next line for this snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True, help='path to the input corpus dir') parser.add_argument('-o', '--output', type=str, default='./', help='path to the output dir') parser.add_argument('-ts', '--test_split', type=float, required=True, help='fraction of the dataset to be used as test data') parser.add_argument('-vs', '--vocab_size', type=int, default=2000, help='vocabulary (default 2000)') parser.add_argument('-vt', '--vocab_threshold', type=int, default=10, help='vocabulary threshold (default 10), disabled when vocab_size is set') args = parser.parse_args() <|code_end|> with the help of current file imports: import argparse from autoencoder.datasets.wiki10plus import construct_train_test_corpus and context from other files: # Path: autoencoder/datasets/wiki10plus.py # def construct_train_test_corpus(corpus_dir, test_split, output, threshold=10, topn=2000): # train_data, test_data = load_data(corpus_dir, test_split) # train_word_freq = count_words(train_data.values()) # # train_docs, vocab_dict, train_word_freq = construct_corpus(train_data, train_word_freq, True, threshold=threshold, topn=topn) # train_corpus = {'docs': train_docs, 'vocab': vocab_dict, 'word_freq': train_word_freq} # dump_json(train_corpus, os.path.join(output, 'train.corpus')) # print 'Generated training corpus' # # test_word_freq = count_words(test_data.values()) # test_docs, _, _ = construct_corpus(test_data, test_word_freq, False, vocab_dict=vocab_dict) # test_corpus = {'docs': test_docs, 'vocab': vocab_dict} # dump_json(test_corpus, os.path.join(output, 'test.corpus')) # print 'Generated test corpus' , which may contain function names, class names, or code. Output only the next line.
construct_train_test_corpus(args.input, args.test_split, args.output, threshold=args.vocab_threshold, topn=args.vocab_size)
Here is a snippet: <|code_start|> # X_train = [] # for each in train_doc_codes.values(): # X_train.append([float(x) for x in each]) # X_test = [] # for each in test_doc_codes.values(): # X_test.append([float(x) for x in each]) # X_train = np.r_[X_train] # Y_train = np.array([train_doc_labels[i] for i in train_doc_codes]) # X_test = np.r_[X_test] # Y_test = np.array([test_doc_labels[i] for i in test_doc_codes]) # # DBN # X_train = np.array(load_marshal(args.train_doc_codes)) # Y_train = np.array(load_marshal(args.train_doc_labels)) # X_test = np.array(load_marshal(args.test_doc_codes)) # Y_test = np.array(load_marshal(args.test_doc_labels)) seed = 7 np.random.seed(seed) val_idx = np.random.choice(range(X_train.shape[0]), args.n_val, replace=False) train_idx = list(set(range(X_train.shape[0])) - set(val_idx)) X_new_train = X_train[train_idx] Y_new_train = Y_train[train_idx] X_new_val = X_train[val_idx] Y_new_val = Y_train[val_idx] print 'train: %s, val: %s, test: %s' % (X_new_train.shape[0], X_new_val.shape[0], X_test.shape[0]) <|code_end|> . Write the next line using the current file imports: import argparse import numpy as np import pdb;pdb.set_trace() from keras.utils import np_utils from autoencoder.testing.retrieval import retrieval, retrieval_by_doclength from autoencoder.utils.io_utils import load_json, load_marshal from autoencoder.preprocessing.preprocessing import load_corpus and context from other files: # Path: autoencoder/testing/retrieval.py # def retrieval(X_train, Y_train, X_test, Y_test, fractions=[0.01, 0.5, 1.0], multilabel=False): # db_size = len(X_train) # n_queries = len(X_test) # X_train = unitmatrix(X_train) # normalize # X_test = unitmatrix(X_test) # score = X_test.dot(X_train.T) # X_train = None # X_test = None # precisions = defaultdict(float) # # for idx in range(n_queries): # retrieval_idx = score[idx].argsort()[::-1] # target = Y_test[idx] # for fr in fractions: # ntop = int(fr * db_size) # pr = float(len([i for i in retrieval_idx[:ntop] if hit(Y_train[i], target, multilabel)])) / ntop # precisions[fr] += pr # precisions = dict([(x, y / n_queries) for x, y in precisions.iteritems()]) # # return sorted(precisions.items(), key=lambda d:d[0]) # # def retrieval_by_doclength(X_train, Y_train, X_test, Y_test, len_test, fraction=0.001, len_bin=600, multilabel=False): # X_train = unitmatrix(X_train) # normalize # X_test = unitmatrix(X_test) # score = X_test.dot(X_train.T) # precisions = defaultdict(list) # n_queries = len(X_test) # ntop = int(fraction * len(X_train)) # # bins = [50, 100, 200, 300, 500, 1000, 2000, 3000, 4000, 5000] # bins = [100, 120, 150, 200, 300, 1000, 1500, 2000, 4000] # # for idx in range(n_queries): # retrieval_idx = score[idx].argsort()[::-1] # pr = float(len([i for i in retrieval_idx[:ntop] if hit(Y_train[i], Y_test[idx], multilabel)])) / ntop # for each in bins: # if len_test[idx] < each: # precisions[each].append(pr) # break # import pdb;pdb.set_trace() # precisions = dict([(x, sum(y) / len(y)) for x, y in precisions.iteritems()]) # # return sorted(precisions.items(), key=lambda d:d[0]) # # Path: autoencoder/utils/io_utils.py # def load_json(file): # try: # with open(file, 'r') as datafile: # data = json.load(datafile) # except Exception as e: # raise e # # return data # # def load_marshal(path_to_file): # try: # with open(path_to_file, 'r') as f: # data = m.load(f) # except Exception as e: # raise e # # return data # # Path: autoencoder/preprocessing/preprocessing.py # def load_corpus(corpus_path): # corpus = load_json(corpus_path) # # return corpus , which may include functions, classes, or code. Output only the next line.
results = retrieval(X_new_train, Y_new_train, X_new_val, Y_new_val,\