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... | 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 Impo... | 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 repres... | 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... | 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 += "# -... | 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
... | 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 ... | 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
d... | 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 ... | 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.1... | 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__ = ... | 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 = l... | 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 = f... | 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),
... | 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 = 'hay... | 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 ha... | 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... | 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),
... | 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 walk... | 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):
# putt... | 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_UNKN... | 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', '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 t... | 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(s... | 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
"... | 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
#
################################################################################
"""
Des... | 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 tearD... | 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\
v... | 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:
... | 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',
# ... | 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.... | 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.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 inclu... | 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
#
################################################################################
"""
... | 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.... | 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... | 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 +... | 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, 0x... | 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 assoc... | 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
@par... | 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 a... | 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... | 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):
... | 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 == 't... | 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... | 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... | 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_offs... | 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
@par... | 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
... | 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,
... | 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 coll... | 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_co... | 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 ... | 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), ... | 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_attribu... | 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|>
, conti... | 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_attribute... | 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 collectio... | 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... | 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)
... | 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 = ... | 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.t... | 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 i... | 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
ret... | 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])... | 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 ... | 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[:... | 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()[... | 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 ... | 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(ar... | 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)
# ... | 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' % (... | 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(m... | 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)
... | 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_tr... | 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_do... | 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'... | 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 ... | 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')
... | 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 fi... | 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... | 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 bl... | 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.ite... | 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)... | 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... | 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... | 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 = []
we... | 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... | 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 i... | 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
fro... | 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 ... | 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 ... | 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 d... | 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... | 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', requ... | 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=Tru... | 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', requ... | 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_argu... | 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='./'... | 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([trai... | results = retrieval(X_new_train, Y_new_train, X_new_val, Y_new_val,\ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.