Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>"""\
Solving 2-SAT boolean formulas
jill-jenn vie et christoph durr - 2015-2019
"""
# snip{
def _vertex(lit): # integer encoding of a litteral
if lit > 0:
return 2 * (lit - 1)
return 2 * (-lit - 1) + 1
def two_sat(formula):
"""Solving a 2-SAT boolean formula... | sccp = tarjan(graph) |
Based on the snippet: <|code_start|>
# snip{ lowest_common_ancestor_by_rmq
class LowestCommonAncestorRMQ:
"""Lowest common ancestor data structure using a reduction to
range minimum query
"""
def __init__(self, graph):
"""builds the structure from a given tree
:param graph: adjacency... | self.rmq = RangeMinQuery(dfs_trace, (float('inf'), None)) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Maximum flow by Dinic
jill-jênn vie et christoph dürr - 2015-2018
"""
setrecursionlimit(5010) # necessary for big graphs
# snip{
def dinic(graph, capacity, source, target):
"""Maximum flow by Dinic
... | add_reverse_arcs(graph, capacity) |
Here is a snippet: <|code_start|> """Constructs an arithmetic expression tree
:param line_tokens: list of token strings containing the expression
:returns: expression tree
:complexity: linear
"""
vals = []
ops = []
for tok in line_tokens + [';']:
if tok in PRIORITY: # tok is an... | for test in range(readint()): |
Predict the next line after this snippet: <|code_start|> :param line_tokens: list of token strings containing the expression
:returns: expression tree
:complexity: linear
"""
vals = []
ops = []
for tok in line_tokens + [';']:
if tok in PRIORITY: # tok is an operator
whil... | readstr() # consume the empty line |
Given the following code snippet before the placeholder: <|code_start|># jill-jênn vie et christoph dürr - 2020
# coding=utf8
# pylint: disable=missing-docstring
class TestIntervalCover(unittest.TestCase):
def test_solve(self):
self.assertEqual(_solve([(0, 0), (5, 0)], 3), 1)
def test_interval_cove... | self.assertEqual(len(interval_cover(instance)), res) |
Given snippet: <|code_start|> letters = sorted(list(set(''.join(S))))
not_zero = '' # letters that cannot be 0
for word in S:
not_zero += word[0]
tab = ['@'] * (10 - len(letters)) + letters # minimal lex permutation
count = 0
while True:
ass = {tab[i]: i for i i... | n = readint() |
Given the following code snippet before the placeholder: <|code_start|> not_zero = '' # letters that cannot be 0
for word in S:
not_zero += word[0]
tab = ['@'] * (10 - len(letters)) + letters # minimal lex permutation
count = 0
while True:
ass = {tab[i]: i for i in ... | S = [readstr() for _ in range(n)] |
Predict the next line for this snippet: <|code_start|>def area(p):
"""Area of a polygone
:param p: list of the points taken in any orientation,
p[0] can differ from p[-1]
:returns: area
:complexity: linear
"""
A = 0
for i, _ in enumerate(p):
A += p[i - 1][0] * p[i][1] ... | S = RangeMinQuery([0] * len(rank_to_y)) # sweep structure |
Using the snippet: <|code_start|> :param f: boolean bitonic function (increasing then decreasing,
not necessarily strictly)
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: value x in [lo,hi] maximizing f(x),
x is computed up to some precision
:complexity: ... | for test in range(readint()): |
Given the following code snippet before the placeholder: <|code_start|> :param float gap:
:returns: value x in [lo,hi] maximizing f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))`
"""
while hi - lo > gap:
step = (hi - lo) / 3.
if f(lo + step) < f... | x, y, w, h = readarray(int) |
Based on the snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestOurStd(unittest.TestCase):
def test_readint(self):
with patch('sys.stdin.readline', return_value="1"):
<|code_end|>
, predict the immediate n... | self.assertEqual(readint(), 1) |
Given snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestOurStd(unittest.TestCase):
def test_readint(self):
with patch('sys.stdin.readline', return_value="1"):
self.assertEqual(readint(), 1)
... | self.assertEqual(readstr(), "1 2") |
Continue the code snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestOurStd(unittest.TestCase):
def test_readint(self):
with patch('sys.stdin.readline', return_value="1"):
self.assertEqual(read... | self.assertEqual(readmatrix(3), [[1, 2, 3], [1, 2, 3], [1, 2, 3]]) |
Continue the code snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestOurStd(unittest.TestCase):
def test_readint(self):
with patch('sys.stdin.readline', return_value="1"):
self.assertEqual(read... | self.assertEqual(readarray(int), [1, 2, 3]) |
Predict the next line for this snippet: <|code_start|> A = [0] * n # A[v] = min residual cap. on path source->v
augm_path = [None] * n # None = node was not visited yet
Q = deque() # BFS
Q.append(source)
augm_path[source] = source
A[source] = float('inf')
while ... | add_reverse_arcs(graph, capacity) |
Based on the snippet: <|code_start|> sol = 0
last = float('-inf')
for right, left in II:
if last < left: # uncovered interval
sol += 1
last = right # put an antenna
return sol
# snip{
def interval_cover(I):
"""Minimum interval cover
:param... | n, rayon = readarray(int) # n=#islands, d=radius |
Continue the code snippet: <|code_start|>
def rv(a): return row(a) * N2 + val(a) + N4
def cv(a): return col(a) * N2 + val(a) + 2 * N4
def bv(a): return blk(a) * N2 + val(a) + 3 * N4
def sudoku(G):
"""Solving Sudoku
:param G: integer matrix with 0 at empty cells
:returns bool: True if grid could be so... | sol = dancing_links(universe, S + [A]) |
Here is a snippet: <|code_start|> heappush(heap, (dist_neighbor, neighbor))
return dist, prec
# snip}
# snip{ dijkstra_update_heap
# snip}
# snip{ dijkstra_update_heap
def dijkstra_update_heap(graph, weight, source=0, target=None):
"""single source shortest paths by Dijkstra
with ... | heap = OurHeap([(dist[node], node) for node in range(n)]) |
Continue the code snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestNextPermutation(unittest.TestCase):
def test_freivalds(self):
A = [[2, 3], [3, 4]]
B = [[1, 0], [1, 2]]
C = [[5, 6], [7,... | self.assertTrue(freivalds(A, B, C)) |
Using the snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestNextPermutation(unittest.TestCase):
def test_freivalds(self):
A = [[2, 3], [3, 4]]
B = [[1, 0], [1, 2]]
C = [[5, 6], [7, 8]]
... | self.assertEqual(readint(), 1) |
Predict the next line after this snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestNextPermutation(unittest.TestCase):
def test_freivalds(self):
A = [[2, 3], [3, 4]]
B = [[1, 0], [1, 2]]
C... | self.assertEqual(readmatrix(3), [[1, 2, 3], [1, 2, 3], [1, 2, 3]]) |
Given snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
try:
except ImportError:
class TestNextPermutation(unittest.TestCase):
def test_freivalds(self):
A = [[2, 3], [3, 4]]
B = [[1, 0], [1, 2]]
C = [[5, 6], [7, 8]]
... | self.assertEqual(readarray(int), [1, 2, 3]) |
Next line prediction: <|code_start|>
graph = [[1, 3],
[0, 2, 3],
[1, 4, 5],
[0, 1, 5, 6],
[2, 7],
[2, 3, 7, 8],
[3, 8, 9],
[4, 5, 10],
[5, 6, 10],
[6, 11],
[7, 8],
[9]]
_ = None
# 0 1 2 3 4 5 6 7 8 9 ... | dist, prec = dijkstra(graph, weights, source=0) |
Here is a snippet: <|code_start|> [2, 7],
[2, 3, 7, 8],
[3, 8, 9],
[4, 5, 10],
[5, 6, 10],
[6, 11],
[7, 8],
[9]]
_ = None
# 0 1 2 3 4 5 6 7 8 9 10 11
weights = [[_, 1, _, 4, _, _, _, _, _, _, _, _], # 0
[1, _, 1, 3, _,... | sparse_graph = listlist_and_matrix_to_listdict(weights) |
Using the snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
class TestArithm(unittest.TestCase):
def test_inv(self):
self.assertEqual(inv(8, 17), 15)
def test_pgcd(self):
<|code_end|>
, determine the next line of code. You have import... | self.assertEqual(pgcd(12, 18), 6) |
Predict the next line after this snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
class TestArithm(unittest.TestCase):
def test_inv(self):
self.assertEqual(inv(8, 17), 15)
def test_pgcd(self):
self.assertEqual(pgcd(12, 18), 6... | self.assertEqual(binom(4, 2), 6) |
Given snippet: <|code_start|># coding: utf8
# jill-jênn vie et christoph dürr - 2020
# pylint: disable=missing-docstring
class TestArithm(unittest.TestCase):
def test_inv(self):
self.assertEqual(inv(8, 17), 15)
def test_pgcd(self):
self.assertEqual(pgcd(12, 18), 6)
def test_binom(self)... | self.assertEqual(binom_modulo(5, 2, 3), 1) |
Predict the next line after this snippet: <|code_start|> y = prec(r)
ry = np.dot(r, y)
sqrtry = sqrt(ry)
stop_tol = max(abstol, reltol * sqrtry)
k = 0
exitOptimal = sqrtry <= stop_tol
exitIter = k > maxiter
exitUser = False
p = -y
onBoun... | sigma = to_boundary(s, p, radius, xx=snorm2) |
Using the snippet: <|code_start|> self.qval += alpha * np.dot(r, p) + 0.5 * alpha**2 * pHp
self.ds = alpha * p
self.dr = alpha * Hp
# Move to next iterate.
s += self.ds
r += self.dr
y = prec(r)
ry_next = np.dot(r, y)
... | except UserExitRequest: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf8 -*-
u"""Strong Wolfe linesearch.
A translation of the original Fortran implementation of the Moré and Thuente
linesearch ensuring satisfaction of the strong Wolfe conditions.
The method is described in
J. J. Moré and D. J. Thue... | class StrongWolfeLineSearch(LineSearch): |
Based on the snippet: <|code_start|> :lb: initial lower bound of the bracket
:ub: initial upper bound of the bracket
"""
name = kwargs.pop("name", "Strong Wolfe linesearch")
super(StrongWolfeLineSearch, self).__init__(*args, name=name, **kwargs)
sqeps = sqrt(np.fin... | raise LineSearchFailure(self.__task) |
Using the snippet: <|code_start|>"""Tests relative to pure Python models."""
class Test_LPModel(TestCase):
def setUp(self):
self.n = n = 5
self.m = m = 3
self.c = np.random.random(n)
self.A = np.random.random((m, n))
<|code_end|>
, determine the next line of code. You have imports... | self.lp1 = LPModel(self.c, |
Given the following code snippet before the placeholder: <|code_start|> if delta is None:
raise ValueError('`delta` value must be a positive number.')
px = np.dot(p, x)
pp = np.dot(p, p)
if xx is None:
xx = np.dot(x, x)
d2 = delta**2
# Guard against abnormal cases.
rad = px**... | return norm2(pg[where(l != u)]) |
Based on the snippet: <|code_start|> raise ValueError('No linear equality constraints were specified')
# Form projection matrix
P = spmatrix.ll_mat_sym(self.n + self.m, self.nnzA + self.n)
if self.precon is not None:
P[:self.n, :self.n] = self.precon
else:
... | scale_factor = norms.norm_infty(self.proj.x[:self.n]) |
Next line prediction: <|code_start|> """Assemble projection matrix and factorize it.
P = [ G A^T ]
[ A 0 ],
where G is the preconditioner, or the identity matrix if no
preconditioner was given.
"""
if self.A is None:
raise ValueError('... | self.t_fact = cputime() |
Continue the code snippet: <|code_start|> def grad(self, x):
n = self.nvar
g = np.empty(n)
g[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
g[-1] = 200 * (x[-1] - x[-2]**2)
g[1:-1] = 200 * (x[1:-1] - x[:-2]**2) - \
400 * x[1:-1] * (x[2:] - x[1:-1]**2) -... | class QNRosenbrock(QuasiNewtonModel, Rosenbrock): |
Continue the code snippet: <|code_start|> """
name = kwargs.pop("name", "Armijo linesearch")
super(QuadraticCubicLineSearch, self).__init__(*args, name=name,
**kwargs)
self.__ftol = max(min(kwargs.get("ftol", 1.0e-4), 1 - sqeps), sqep... | raise LineSearchFailure("backtracking limit exceeded") |
Given the code snippet: <|code_start|># Define allowed command-line options.
parser = ArgumentParser(description=desc)
parser.add_argument("-1", "--sr1", action="store_true", dest="sr1",
default=False, help="use limited-memory SR1 approximation")
parser.add_argument("-p", "--pairs", type=int,
... | logger = config_logger("nlp", "%(name)-9s %(levelname)-5s %(message)s") |
Here is a snippet: <|code_start|>#!/usr/bin/env python
"""Main driver for performance profiles."""
usage_msg = """%prog [options] file1 file2 [... fileN]
where file1 through fileN contain the statistics of a solver."""
# Define allowed command-line options.
parser = OptionParser(usage=usage_msg)
parser.add_option('... | pprof = PerformanceProfile(args, **options.__dict__) |
Given the following code snippet before the placeholder: <|code_start|> """Initialize a linesearch method.
:parameters:
:linemodel: ``C1LineModel`` or ``C2LineModel`` instance
:keywords:
:step: initial step size (default: 1.0)
:value: initial function value (... | raise LineSearchFailure("initial linesearch step too small") |
Here is a snippet: <|code_start|> default=5, dest="npairs", help="BFGS memory")
parser.add_argument("-a", "--armijo", action="store_true", dest="armijo",
default=False, help="use improved Armijo linesearch")
parser.add_argument("-i", "--iter", type=int,
default... | model = QNAmplModel(problem, |
Given the code snippet: <|code_start|> else:
it = -lbfgs.iter
fc, gc = -lbfgs.model.obj.ncalls, -lbfgs.model.grad.ncalls
gn = -1.0 if lbfgs.g_norm is None else -lbfgs.g_norm
ts = -1.0 if lbfgs.tsolve is None else -lbfgs.tsolve
return (it, fc, gc, gn, ts)
desc = """Linesearch-base... | logger = config_logger("nlp", |
Here is a snippet: <|code_start|>
def random_path():
return tempfile.mkdtemp()
class StoreTestCase(unittest.TestCase):
storeClass = None
def setUp(self):
self.path = random_path()
self.repo = self.storeClass(self.path)
def tearDown(self):
shutil.rmtree(self.path)
def ... | return RootObject(gref.identifier, gref.channel, "test_protocol") |
Predict the next line for this snippet: <|code_start|>
def random_path():
return tempfile.mkdtemp()
class StoreTestCase(unittest.TestCase):
storeClass = None
def setUp(self):
self.path = random_path()
self.repo = self.storeClass(self.path)
def tearDown(self):
shutil.rmtree... | return UpdateObject(parents, data) |
Continue the code snippet: <|code_start|>
class TestStationDeferreds(StationTestCase):
def test_ready_deferred(self):
now = time.time()
<|code_end|>
. Use current file imports:
import time
import sys
from support.station_fixture import StationTestCase
from groundstation.deferred import Defer... | deferred = Deferred(now - 10, None) |
Given snippet: <|code_start|>
class TestStationDeferreds(StationTestCase):
def test_ready_deferred(self):
now = time.time()
deferred = Deferred(now - 10, None)
self.station.register_deferred(deferred)
self.assertEqual(len(self.station.deferreds), 1)
self.assertTrue(self.st... | @defer_until(now - 30) |
Predict the next line for this snippet: <|code_start|>
log = logger.getLogger(__name__)
class UnsolicitedTransfer(Exception):
pass
def handle_transfer(self):
<|code_end|>
with the help of current file imports:
import pygit2
import groundstation.utils as utils
from groundstation.proto.git_object_pb2 import Git... | git_pb = GitObject() |
Predict the next line after this snippet: <|code_start|>
class TestGrefMarshall(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
def test_marshalls_tips(self):
<|code_end|>
using the current file's imports:
from support import crypto_fixture
from support import store_fixtu... | gref = Gref(self.repo, "testchannel", "test_write_tip") |
Using the snippet: <|code_start|>
def type_of(protobuf):
base = BaseObject()
base.ParseFromString(protobuf)
return base.type
def hydrate_object(protobuf):
# Test if it's strongly typed first
_type = type_of(protobuf)
if _type == TYPE_ROOT:
return RootObject.from_object(protobuf)
e... | elif _type == TYPE_UNSET: |
Given snippet: <|code_start|>
def type_of(protobuf):
base = BaseObject()
base.ParseFromString(protobuf)
return base.type
def hydrate_object(protobuf):
# Test if it's strongly typed first
_type = type_of(protobuf)
if _type == TYPE_ROOT:
<|code_end|>
, continue by predicting the next line. Cons... | return RootObject.from_object(protobuf) |
Predict the next line for this snippet: <|code_start|>
def type_of(protobuf):
base = BaseObject()
base.ParseFromString(protobuf)
return base.type
def hydrate_object(protobuf):
# Test if it's strongly typed first
_type = type_of(protobuf)
if _type == TYPE_ROOT:
return RootObject.from_o... | return UpdateObject.from_object(protobuf) |
Given snippet: <|code_start|>
class TestGitGref(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
def test_write_tip(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from support import store_fixture
from groundstation.gref import Gref... | gref = Gref(self.repo, "testchannel", "test_write_tip") |
Given the code snippet: <|code_start|> for parent in our_parents:
self.assertIn(parent, parents)
def test_get_signature(self):
gref = Gref(self.repo, "testchannel", "test_get_signature")
root = self.create_root_object(gref)
oid = self.repo.create_blob(root.as_object())
... | self.assertTrue(valid_path("asdf")) |
Continue the code snippet: <|code_start|>
class StationConnectionTestCase(StationIntegrationFixture):
def test_two_stations_connect(self):
addr = os.path.join(self.dir, "listener")
listener = TestListener(addr)
client = TestClient(addr)
class StationCommunication(StationIntegrationFix... | peer = listener.accept(PeerSocket) |
Predict the next line after this snippet: <|code_start|> header_bytes[0] |= char_value & 0xf
header_byte_count += 1
elif header_byte_count == 1:
header_bytes[0] |= (char_value & 0xf) << 4
header_byte_count += 1
... | Gref(self.station.store, "soundstation", "demo") |
Predict the next line after this snippet: <|code_start|> elif header_byte_count == 1:
header_bytes[0] |= (char_value & 0xf) << 4
header_byte_count += 1
elif header_byte_count == 2:
header_bytes[1] |= (char_value & 0xf)
... | self.station.update_gref(g, [Tip(oid, "")], []) # yolo |
Based on the snippet: <|code_start|>
def new_root_object(weak):
root = RootObject()
root.id = "butts"
root.channel = "butts"
root.protocol = "butts"
if not weak:
root.type = TYPE_ROOT
return root
def new_update_object(weak, parents=[]):
update = UpdateObject()
update.parents... | self.assertEqual(object_factory.type_of(root_str), TYPE_UNSET) |
Predict the next line after this snippet: <|code_start|>
def new_root_object(weak):
root = RootObject()
root.id = "butts"
root.channel = "butts"
root.protocol = "butts"
if not weak:
root.type = TYPE_ROOT
return root
def new_update_object(weak, parents=[]):
<|code_end|>
using the cu... | update = UpdateObject() |
Given the code snippet: <|code_start|>
def update_object(data, parents=[]):
return UpdateObject(parents, data)
def root_object(id, channel, protocol):
<|code_end|>
, generate the next line using the imports in this file:
from groundstation.objects.root_object import RootObject
from groundstation.objects.update_... | return RootObject(id, channel, protocol) |
Using the snippet: <|code_start|>
class StationTestCase(unittest.TestCase):
def setUp(self):
self.node = Node()
<|code_end|>
, determine the next line of code. You have imports:
import tempfile
import shutil
import unittest
from groundstation.node import Node
from groundstation.station import Station
an... | self.station = Station(tempfile.mkdtemp(), self.node) |
Given snippet: <|code_start|>
log = logger.getLogger(__name__)
def handle_listallobjects(self):
if not self.station.recently_queried(self.origin):
log.info("%s not up to date, issuing LISTALLOBJECTS" % (self.origin))
# Pass in t... | if len(payload) > settings.LISTALLOBJECTS_CHUNK_THRESHOLD: |
Next line prediction: <|code_start|>
class TestRootObject(unittest.TestCase):
def test_hydrate_root_object(self):
root = RootObject(
"test_object",
"richo@psych0tik.net:groundstation/tests",
"richo@psych0tik.net:groundstation/testcase"
)
h... | update = UpdateObject( |
Based on the snippet: <|code_start|>
valid_keyset = {
"valid": crypto_fixture.valid_pubkey
}
class CryptoRSAAdaptorTestCase(unittest.TestCase):
def test_converts_pubkey_to_pem(self):
key = convert_pubkey(crypto_fixture.valid_pubkey)
self.assertIsInstance(key, RSA._RSAobj)
... | adaptor = RSAAdaptor({ |
Using the snippet: <|code_start|>
valid_keyset = {
"valid": crypto_fixture.valid_pubkey
}
class CryptoRSAAdaptorTestCase(unittest.TestCase):
def test_converts_pubkey_to_pem(self):
key = convert_pubkey(crypto_fixture.valid_pubkey)
self.assertIsInstance(key, RSA._RSAobj)
self... | adaptor = RSAPrivateAdaptor(crypto_fixture.valid_key) |
Here is a snippet: <|code_start|>
valid_keyset = {
"valid": crypto_fixture.valid_pubkey
}
class CryptoRSAAdaptorTestCase(unittest.TestCase):
def test_converts_pubkey_to_pem(self):
key = convert_pubkey(crypto_fixture.valid_pubkey)
self.assertIsInstance(key, RSA._RSAobj)
se... | key = convert_privkey(crypto_fixture.valid_key) |
Given snippet: <|code_start|>
valid_keyset = {
"valid": crypto_fixture.valid_pubkey
}
class CryptoRSAAdaptorTestCase(unittest.TestCase):
def test_converts_pubkey_to_pem(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from Crypto.PublicK... | key = convert_pubkey(crypto_fixture.valid_pubkey) |
Here is a snippet: <|code_start|> adaptor = RSAAdaptor({
"key1": crypto_fixture.valid_pubkey,
"key2": crypto_fixture.valid_pubkey,
"key3": crypto_fixture.valid_pubkey,
"key4": crypto_fixture.valid_pubkey
})
self.assertIsInstance(adaptor, RSAAdap... | materialise_exponent(crypto_fixture.materialize_in)) |
Predict the next line for this snippet: <|code_start|> "key2": crypto_fixture.valid_pubkey,
"key3": crypto_fixture.valid_pubkey,
"key4": crypto_fixture.valid_pubkey
})
self.assertIsInstance(adaptor, RSAAdaptor)
def test_signs_data(self):
adaptor = RSAP... | materialise_numeric(crypto_fixture.materialize_in)) |
Next line prediction: <|code_start|>
class TestUnambiguousEncapsulation(unittest.TestCase):
test_bytes = [0b01010101, 0b11110000]
test_message = [31, 54, 31, 54, 31, 54, 31, 54, 54, 54, 54, 54, 31, 31, 31, 31]
test_header = [41, 0, 41, 0, 41, 0, 41, 0, 0, 0, 0, 0, 41, 41, 41, 41]
def test_successfully... | encoder = UnambiguousEncoder() |
Based on the snippet: <|code_start|>
class MockStream(list):
def enqueue(self, *args, **kwargs):
self.append(*args, **kwargs)
def MockTERMINATE():
pass
class MockRequest(object):
def __init__(self, id):
self.id = id
class MockStation(object):
def __init__(self, **kwargs):
... | self.station = Station(self.tmpdir, self.node) |
Given the code snippet: <|code_start|>
log = logger.getLogger(__name__)
def handle_newgreftip(self):
proto_channels = groundstation.proto.channel_list_pb2.ChannelList()
proto_channels.ParseFromString(self.payload)
for channel in proto_channels.channels:
for gref in channel.grefs:
<|code_end|>
, ge... | _gref = Gref(self.station.store, channel.channelname, gref.identifier) |
Predict the next line for this snippet: <|code_start|> def tip_path(self, tip):
return os.path.join(self.node_path(), tip)
def __iter__(self):
return os.listdir(self.node_path()).__iter__()
def get_signature(self, tip):
try:
with open(self.tip_path(tip), 'r') as fh:
... | elif isinstance(obj, UpdateObject): |
Next line prediction: <|code_start|> fh.truncate()
fh.close()
def tip_path(self, tip):
return os.path.join(self.node_path(), tip)
def __iter__(self):
return os.listdir(self.node_path()).__iter__()
def get_signature(self, tip):
try:
with open(self.tip_pat... | if isinstance(obj, RootObject): |
Next line prediction: <|code_start|>
log = logger.getLogger(__name__)
def handle_describechannels(self):
if not self.payload:
log.info("station %s sent empty DESCRIBECHANNELS payload - new database?" % (str(self.origin)))
return
proto_channels = groundstation.proto.channel_list_pb2.ChannelLis... | _gref = Gref(self.station.store, channel.channelname, gref.identifier) |
Given the following code snippet before the placeholder: <|code_start|>
log = logger.getLogger(__name__)
def handle_describechannels(self):
if not self.payload:
log.info("station %s sent empty DESCRIBECHANNELS payload - new database?" % (str(self.origin)))
return
proto_channels = groundstatio... | tips = [Tip(tip.tip, tip.signature) for tip in gref.tips] |
Next line prediction: <|code_start|>
log = logger.getLogger(__name__)
def handle_fetchobject(self):
log.info("Handling FETCHOBJECT")
git_obj = self.station[self.payload]
<|code_end|>
. Use current file imports:
(import groundstation.transfer.request
from groundstation.proto.git_object_pb2 import GitObject
fr... | git_pb = GitObject() |
Predict the next line after this snippet: <|code_start|> segment_length, _, payload_buffer = tmp_buffer.partition(chr(0))
segment_length = int(segment_length)
if len(payload_buffer) >= segment_length:
iterations += 1
# We have the whole buffer
... | data = self.socket.recv(settings.DEFAULT_BUFSIZE) |
Given the following code snippet before the placeholder: <|code_start|>
tmp_buffer = self.buffer
iterations = 0
while True:
if not tmp_buffer: # Catch having emptied our buffer
break
# Keep the unmolested buffer
segment_length, _, payload_buffe... | if isinstance(payload, Response): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
"""NCBI Human genome assembly."""
class Resource(BaseResource):
"""docstring for CCDS Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "ncbi_assembly"
<|code_end|>
, predict the next l... | self.ftp = NCBI() |
Here is a snippet: <|code_start|>#!/usr/bin/env python
"""GenBank - reference human genome assembly."""
class Resource(BaseResource):
"""docstring for CCDS Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "genbank"
<|code_end|>
. Write the next line using the current file impo... | self.ftp = NCBI() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
"""1000 Genomes decoy assembly sequence, version 5."""
class Resource(BaseResource):
"""docstring for CCDS Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "decoy"
<|code_end|>
with the help of curren... | self.ftp = ThousandG() |
Next line prediction: <|code_start|>#!/usr/bin/env python
"""UCSC Human genome assembly."""
from __future__ import print_function
class Resource(BaseResource):
"""docstring for Ensembl Assembly Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "ucsc_assembly"
<|code_end|>
. Use... | self.ftp = UCSC() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
"""A few example BAM/Fasta files for testing provided by GATK."""
class Resource(BaseResource):
"""docstring for exampleBAM Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "example"
<|code_end|>
with... | self.ftp = GATK() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
"""Ensembl - automatically annotated human genome reference."""
class Resource(BaseResource):
"""docstring for Ensembl Assembly Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "ensembl... | self.ftp = Ensembl() |
Using the snippet: <|code_start|>#!/usr/bin/env python
"""The Consensus CoDing Sequence (CCDS) project; "a core set of human and mouse protein-coding regions"."""
class Resource(BaseResource):
"""docstring for CCDS Resource"""
def __init__(self):
super(Resource, self).__init__()
self.id = "ccds"
<|code... | self.ftp = NCBI() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
def create_bundles(app):
assets = Environment(app)
assets.debug = True if app.debug == 'True' else False
bundles = PythonLoader('assetbundle').load_bundles()
for name, bundle in bundles.iteritems():
assets.register(name, bundle)
d... | create_views(app) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def create_bundles(app):
assets = Environment(app)
assets.debug = True if app.debug == 'True' else False
bundles = PythonLoader('assetbundle').load_bundles()
for name, bundle in bundles.iteritems():
assets.register(name, bundle)
def ... | (app.db_session, app.db_metadata, app.db_engine) = init_db(database_url) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
def create_login_views(app):
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated():... | return render_template('register.html', user=User(), errors={}) |
Predict the next line for this snippet: <|code_start|> request.form['fullname']
)
if user.validate():
user.enabled = True
current_app.db_session.add(user)
current_app.db_session.commit()
login_user(user)
flash(u'Du har nå opprette... | user = get_user_by_username(username) |
Using the snippet: <|code_start|> 'date': self.start.isoformat(),
'title': self.title
}
def serialize_with_point(self):
data = self.serialize()
start = to_shape(self.points.first().geom)
data['position'] = {'lon': start.x, 'lat': start.y}
return data
... | stats = get_stats(points) |
Given snippet: <|code_start|> def serialize_with_point(self):
data = self.serialize()
start = to_shape(self.points.first().geom)
data['position'] = {'lon': start.x, 'lat': start.y}
return data
@property
def stored_points(self):
if not self.stored_points_list:
... | avg_speed = compute_speed(stats['distance_3d'], total_time) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
def parse_gpx_11(data):
gpx = parse11(data, True)
points = []
for track in gpx.get_trk():
for segment in track.get_trkseg():
for track_point in segment.get_trkpt():
<|code_end|>
. Use current file imports:
from shapely... | points.append(MTPoint( |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def parse_gpx_11(data):
gpx = parse11(data, True)
points = []
for track in gpx.get_trk():
for segment in track.get_trkseg():
for track_point in segment.get_trkpt():
points.append(MTPoint(
geo... | gpx = parse10(data, True) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class TripStatTest(unittest.TestCase):
def setUp(self):
self.trip = Trip()
<|code_end|>
. Use current file imports:
(import unittest
import dateutil.parser
from shapely.geometry import Point
from models import Trip, Point as MTPoint)
and con... | p1 = MTPoint( |
Given the following code snippet before the placeholder: <|code_start|>
@abstractmethod
def set_name(self):
pass
@abstractmethod
def get_actions(self, *args):
pass
class SearchComponent(Component, Search):
"""
Each new product will implement specific actions
"""
def s... | class MenuComponent(Component, Menu): |
Using the snippet: <|code_start|>"""
Description:
* An interface is defined for creating an object.
* Comparing to simple factory, subclasses decide which class is instantiated.
@author: Paul Bodean
@date: 12/08/2017
"""
class Component(object):
"""
Abstract class defining how a tested component will look
... | class SearchComponent(Component, Search): |
Given the code snippet: <|code_start|>"""
Description:
- Check the object instance memory location
@author: Paul Bodean
@date: 26/12/2017
"""
class TestMetaSingleton(TestCase):
def test_singleton(self):
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from... | dr1 = Driver().connect() |
Given snippet: <|code_start|>"""
Description:
@author: Eugen
@date: 24/07/2017
"""
class A(object):
def __init__(self, name):
self.__name = name
def __str__(self):
return 'A' + str(self.__name)
class B(object):
def __init__(self, name):
self.__name = na... | a = SingletonFactory.build(A, name='class A')
|
Here is a snippet: <|code_start|>"""
Description: module providing the implementation of the search class of the object pattern pattern
class declaration.
@author: Paul Bodean
@date: 25/07/2017
"""
<|code_end|>
. Write the next line using the current file imports:
from src.page_object_pattern.base_page import Base... | class SearchPage(BasePage): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.